content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Web; using MarkdownSharp; using NuGetGallery.Diagnostics; namespace NuGetGallery { public class ContentService : IContentService { // Why not use the ASP.Net Cache? // Each entry should _always_ have a value. Values never expire, they just need to be updated. Updates use the existing data, // so we don't want data just vanishing from a cache. private ConcurrentDictionary<string, ContentItem> _contentCache = new ConcurrentDictionary<string, ContentItem>(StringComparer.OrdinalIgnoreCase); private IDiagnosticsSource Trace { get; set; } public static readonly string HtmlContentFileExtension = ".html"; public static readonly string MarkdownContentFileExtension = ".md"; public static readonly string JsonContentFileExtension = ".json"; public IFileStorageService FileStorage { get; protected set; } protected ConcurrentDictionary<string, ContentItem> ContentCache { get { return _contentCache; } } protected ContentService() { Trace = NullDiagnosticsSource.Instance; } public ContentService(IFileStorageService fileStorage, IDiagnosticsService diagnosticsService) { if (fileStorage == null) { throw new ArgumentNullException("fileStorage"); } if (diagnosticsService == null) { throw new ArgumentNullException("diagnosticsService"); } FileStorage = fileStorage; Trace = diagnosticsService.GetSource("ContentService"); } public void ClearCache() { _contentCache.Clear(); } public Task<IHtmlString> GetContentItemAsync(string name, TimeSpan expiresIn) { if (String.IsNullOrEmpty(name)) { throw new ArgumentException(String.Format(CultureInfo.CurrentCulture, Strings.ParameterCannotBeNullOrEmpty, "name"), "name"); } return GetContentItemCore(name, expiresIn); } // This NNNCore pattern allows arg checking to happen synchronously, before starting the async operation. private async Task<IHtmlString> GetContentItemCore(string name, TimeSpan expiresIn) { using (Trace.Activity("GetContentItem " + name)) { ContentItem cachedItem = null; if (ContentCache.TryGetValue(name, out cachedItem) && DateTime.UtcNow < cachedItem.ExpiryUtc) { Trace.Verbose("Cache Valid. Expires at: " + cachedItem.ExpiryUtc.ToString()); return cachedItem.Content; } Trace.Verbose("Cache Expired."); // Get the file from the content service var filenames = new[] { name + HtmlContentFileExtension, name + MarkdownContentFileExtension, name + JsonContentFileExtension }; foreach (var filename in filenames) { ContentItem item = await RefreshContentFromFile(filename, cachedItem, expiresIn); if (item != null) { // Cache and return the result Debug.Assert(item.Content != null); ContentCache.AddOrSet(name, item); return item.Content; } } return new HtmlString(String.Empty); } } private async Task<ContentItem> RefreshContentFromFile(string fileName, ContentItem cachedItem, TimeSpan expiresIn) { using (Trace.Activity("Downloading Content Item: " + fileName)) { IFileReference reference = await FileStorage.GetFileReferenceAsync( Constants.ContentFolderName, fileName, ifNoneMatch: cachedItem == null ? null : cachedItem.ContentId); if (reference == null) { Trace.Error("Requested Content File Not Found: " + fileName); return null; } // Check the content ID to see if it's different if (cachedItem != null && String.Equals(cachedItem.ContentId, reference.ContentId, StringComparison.Ordinal)) { Trace.Verbose("No change to content item. Using Cache"); // Update the expiry time cachedItem.ExpiryUtc = DateTime.UtcNow + expiresIn; Trace.Verbose(String.Format("Updating Cache: {0} expires at {1}", fileName, cachedItem.ExpiryUtc)); return cachedItem; } // Retrieve the content Trace.Verbose("Content Item changed. Trying to update..."); try { using (var stream = reference.OpenRead()) { if (stream == null) { Trace.Error("Requested Content File Not Found: " + fileName); return null; } else { using (Trace.Activity("Reading Content File: " + fileName)) { using (var reader = new StreamReader(stream)) { string text = await reader.ReadToEndAsync(); string content; if (fileName.EndsWith(".md")) { content = new Markdown().Transform(text); } else { content = text; } IHtmlString html = new HtmlString(content.Trim()); // Prep the new item for the cache var expiryTime = DateTime.UtcNow + expiresIn; return new ContentItem(html, expiryTime, reference.ContentId, DateTime.UtcNow); } } } } } catch (Exception) { Debug.Assert(false, "owchy oochy - reading content failed"); Trace.Error("Reading updated content failed. Returning cached content instead."); return cachedItem; } } } public class ContentItem { public IHtmlString Content { get; private set; } public string ContentId { get; private set; } public DateTime RetrievedUtc { get; private set; } public DateTime ExpiryUtc { get; set; } public ContentItem(IHtmlString content, DateTime expiryUtc, string contentId, DateTime retrievedUtc) { Content = content; ExpiryUtc = expiryUtc; ContentId = contentId; RetrievedUtc = retrievedUtc; } } } }
40.382653
154
0.516614
[ "Apache-2.0" ]
ashuthinks/webnuget
src/NuGetGallery/Services/ContentService.cs
7,917
C#
using System.Collections.Generic; using Ocelot.Configuration.Builder; using Ocelot.DownstreamRouteFinder; using Ocelot.DownstreamRouteFinder.UrlMatcher; using Ocelot.DownstreamUrlCreator.UrlTemplateReplacer; using Ocelot.Responses; using Ocelot.Values; using Shouldly; using TestStack.BDDfy; using Xunit; namespace Ocelot.UnitTests.DownstreamUrlCreator.UrlTemplateReplacer { public class UpstreamUrlPathTemplateVariableReplacerTests { private DownstreamRoute _downstreamRoute; private Response<DownstreamPath> _result; private readonly IDownstreamPathPlaceholderReplacer _downstreamPathReplacer; public UpstreamUrlPathTemplateVariableReplacerTests() { _downstreamPathReplacer = new DownstreamTemplatePathPlaceholderReplacer(); } [Fact] public void can_replace_no_template_variables() { this.Given(x => x.GivenThereIsAUrlMatch( new DownstreamRoute( new List<UrlPathPlaceholderNameAndValue>(), new ReRouteBuilder() .WithUpstreamHttpMethod(new List<string> { "Get" }) .Build()))) .When(x => x.WhenIReplaceTheTemplateVariables()) .Then(x => x.ThenTheDownstreamUrlPathIsReturned("")) .BDDfy(); } [Fact] public void can_replace_no_template_variables_with_slash() { this.Given(x => x.GivenThereIsAUrlMatch( new DownstreamRoute( new List<UrlPathPlaceholderNameAndValue>(), new ReRouteBuilder() .WithDownstreamPathTemplate("/") .WithUpstreamHttpMethod(new List<string> { "Get" }) .Build()))) .When(x => x.WhenIReplaceTheTemplateVariables()) .Then(x => x.ThenTheDownstreamUrlPathIsReturned("/")) .BDDfy(); } [Fact] public void can_replace_url_no_slash() { this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(new List<UrlPathPlaceholderNameAndValue>(), new ReRouteBuilder() .WithDownstreamPathTemplate("api") .WithUpstreamHttpMethod(new List<string> { "Get" }) .Build()))) .When(x => x.WhenIReplaceTheTemplateVariables()) .Then(x => x.ThenTheDownstreamUrlPathIsReturned("api")) .BDDfy(); } [Fact] public void can_replace_url_one_slash() { this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(new List<UrlPathPlaceholderNameAndValue>(), new ReRouteBuilder() .WithDownstreamPathTemplate("api/") .WithUpstreamHttpMethod(new List<string> { "Get" }) .Build()))) .When(x => x.WhenIReplaceTheTemplateVariables()) .Then(x => x.ThenTheDownstreamUrlPathIsReturned("api/")) .BDDfy(); } [Fact] public void can_replace_url_multiple_slash() { this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(new List<UrlPathPlaceholderNameAndValue>(), new ReRouteBuilder() .WithDownstreamPathTemplate("api/product/products/") .WithUpstreamHttpMethod(new List<string> { "Get" }) .Build()))) .When(x => x.WhenIReplaceTheTemplateVariables()) .Then(x => x.ThenTheDownstreamUrlPathIsReturned("api/product/products/")) .BDDfy(); } [Fact] public void can_replace_url_one_template_variable() { var templateVariables = new List<UrlPathPlaceholderNameAndValue>() { new UrlPathPlaceholderNameAndValue("{productId}", "1") }; this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(templateVariables, new ReRouteBuilder() .WithDownstreamPathTemplate("productservice/products/{productId}/") .WithUpstreamHttpMethod(new List<string> { "Get" }) .Build()))) .When(x => x.WhenIReplaceTheTemplateVariables()) .Then(x => x.ThenTheDownstreamUrlPathIsReturned("productservice/products/1/")) .BDDfy(); } [Fact] public void can_replace_url_one_template_variable_with_path_after() { var templateVariables = new List<UrlPathPlaceholderNameAndValue>() { new UrlPathPlaceholderNameAndValue("{productId}", "1") }; this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(templateVariables, new ReRouteBuilder() .WithDownstreamPathTemplate("productservice/products/{productId}/variants") .WithUpstreamHttpMethod(new List<string> { "Get" }) .Build()))) .When(x => x.WhenIReplaceTheTemplateVariables()) .Then(x => x.ThenTheDownstreamUrlPathIsReturned("productservice/products/1/variants")) .BDDfy(); } [Fact] public void can_replace_url_two_template_variable() { var templateVariables = new List<UrlPathPlaceholderNameAndValue>() { new UrlPathPlaceholderNameAndValue("{productId}", "1"), new UrlPathPlaceholderNameAndValue("{variantId}", "12") }; this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(templateVariables, new ReRouteBuilder() .WithDownstreamPathTemplate("productservice/products/{productId}/variants/{variantId}") .WithUpstreamHttpMethod(new List<string> { "Get" }) .Build()))) .When(x => x.WhenIReplaceTheTemplateVariables()) .Then(x => x.ThenTheDownstreamUrlPathIsReturned("productservice/products/1/variants/12")) .BDDfy(); } [Fact] public void can_replace_url_three_template_variable() { var templateVariables = new List<UrlPathPlaceholderNameAndValue>() { new UrlPathPlaceholderNameAndValue("{productId}", "1"), new UrlPathPlaceholderNameAndValue("{variantId}", "12"), new UrlPathPlaceholderNameAndValue("{categoryId}", "34") }; this.Given(x => x.GivenThereIsAUrlMatch(new DownstreamRoute(templateVariables, new ReRouteBuilder() .WithDownstreamPathTemplate("productservice/category/{categoryId}/products/{productId}/variants/{variantId}") .WithUpstreamHttpMethod(new List<string> { "Get" }) .Build()))) .When(x => x.WhenIReplaceTheTemplateVariables()) .Then(x => x.ThenTheDownstreamUrlPathIsReturned("productservice/category/34/products/1/variants/12")) .BDDfy(); } private void GivenThereIsAUrlMatch(DownstreamRoute downstreamRoute) { _downstreamRoute = downstreamRoute; } private void WhenIReplaceTheTemplateVariables() { _result = _downstreamPathReplacer.Replace(_downstreamRoute.ReRoute.DownstreamPathTemplate, _downstreamRoute.TemplatePlaceholderNameAndValues); } private void ThenTheDownstreamUrlPathIsReturned(string expected) { _result.Data.Value.ShouldBe(expected); } } }
41.61413
154
0.593183
[ "MIT" ]
albertosam/Ocelot
test/Ocelot.UnitTests/DownstreamUrlCreator/UrlTemplateReplacer/UpstreamUrlPathTemplateVariableReplacerTests.cs
7,657
C#
using System; namespace CRM.Flexie.Fiskalizimi.examples { public class GetEic { public string GetEicCode() { try { Fiskalizimi fiskalizmi = new Fiskalizimi("Tw8Yewd1U0d4hViNzGrbLliRlteKTMBT"); string eic = fiskalizmi .GetEInvoiceCodeAsync("cc8d08a4-e46e-4442-a2c5-6e8073c05fc9") .Result; return eic; } catch (Exception ex) { throw new Exception(ex.Message); } } } }
23.24
93
0.490534
[ "MIT" ]
flexie-crm/fiskalizimi-sdk-dotnet
examples/GetEic.cs
583
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using Microsoft.Azure.Commands.Resources.Models; using Microsoft.Azure.Commands.Resources.Models.Authorization; using Microsoft.Azure.Graph.RBAC.Version1_6.ActiveDirectory; using Microsoft.WindowsAzure.Commands.Common; using System; using System.Collections.Generic; using System.Management.Automation; namespace Microsoft.Azure.Commands.Resources { /// <summary> /// Get the available role Definitions for certain resource types. /// </summary> [Cmdlet(VerbsCommon.Get, "AzureRmRoleDefinition"), OutputType(typeof(List<PSRoleDefinition>))] public class GetAzureRoleDefinitionCommand : ResourcesBaseCmdlet { [Parameter(Position = 0, Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSet.RoleDefinitionName, HelpMessage = "Role definition name. For e.g. Reader, Contributor, Virtual Machine Contributor.")] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSet.RoleDefinitionId, HelpMessage = "Role definition id.")] [ValidateGuidNotEmpty] public Guid Id { get; set; } [ValidateNotNullOrEmpty] [Parameter(Mandatory = false, ValueFromPipeline = true, ParameterSetName = ParameterSet.RoleDefinitionName, HelpMessage = "Scope of the existing role definition.")] [Parameter(Mandatory = false, ValueFromPipeline = true, ParameterSetName = ParameterSet.RoleDefinitionId, HelpMessage = "Scope of the existing role definition.")] [Parameter(Mandatory = false, ValueFromPipeline = true, ParameterSetName = ParameterSet.RoleDefinitionCustom, HelpMessage = "Scope of the existing role definition.")] public string Scope { get; set; } [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSet.RoleDefinitionCustom, HelpMessage = "If specified, only displays the custom created roles in the directory.")] public SwitchParameter Custom { get; set; } [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSet.RoleDefinitionName, HelpMessage = "If specified, displays the the roles at and below scope.")] [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, ParameterSetName = ParameterSet.RoleDefinitionCustom, HelpMessage = "If specified, displays the the roles at and below scope.")] [Obsolete("Get-AzureRmRoleDefinition: The parameter \"AtScopeAndBelow\" is being removed in an upcoming breaking change release.")] public SwitchParameter AtScopeAndBelow { get; set; } public override void ExecuteCmdlet() { FilterRoleDefinitionOptions options = new FilterRoleDefinitionOptions { CustomOnly = Custom.IsPresent ? true : false, #pragma warning disable 0618 ScopeAndBelow = AtScopeAndBelow.IsPresent ? true : false, #pragma warning restore 0618 Scope = Scope, ResourceIdentifier = new ResourceIdentifier { Subscription = DefaultProfile.DefaultContext.Subscription.Id.ToString() }, RoleDefinitionId = Id, RoleDefinitionName = Name, }; AuthorizationClient.ValidateScope(options.Scope, true); WriteObject(PoliciesClient.FilterRoleDefinitions(options), enumerateCollection: true); } } }
57.776316
243
0.6757
[ "MIT" ]
CHEEKATLAPRADEEP/azure-powershell
src/ResourceManager/Resources/Commands.Resources/RoleDefinitions/GetAzureRoleDefinitionCommand.cs
4,318
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace r5launcher.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("r5launcher.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.5
176
0.613147
[ "MIT" ]
damiennnnn/r5launch
Properties/Resources.Designer.cs
2,786
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Api_Implement.iOS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Api_Implement.iOS")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("72bdc44f-c588-44f3-b6df-9aace7daafdd")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.027027
84
0.745558
[ "MIT" ]
Osv04/XamarinWordsApi
API/Api_Implement/Api_Implement/Api_Implement.iOS/Properties/AssemblyInfo.cs
1,410
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Sora.Entities.Base; using Sora.Entities.Info; using Sora.Entities.Segment; using Sora.Entities.Segment.DataModel; using Sora.Enumeration; namespace Sora.Entities { /// <summary> /// 消息类 /// </summary> public sealed class Message : BaseModel { #region 属性 /// <summary> /// 消息ID /// </summary> public int MessageId { get; } /// <summary> /// 纯文本信息 /// </summary> public string RawText { get; } /// <summary> /// 消息段列表 /// </summary> public MessageBody MessageBody { get; } /// <summary> /// 消息时间戳 /// </summary> public long Time { get; } /// <summary> /// 消息字体id /// </summary> public int Font { get; } /// <summary> /// <para>消息序号</para> /// <para>仅用于群聊消息</para> /// </summary> public long? MessageSequence { get; } #endregion #region 构造函数 internal Message(Guid serviceId, Guid connectionId, int msgId, string text, MessageBody messageBody, long time, int font, long? messageSequence) : base(serviceId, connectionId) { MessageId = msgId; RawText = text; MessageBody = messageBody; Time = time; Font = font; MessageSequence = messageSequence; } #endregion #region 消息管理方法 /// <summary> /// 撤回本条消息 /// </summary> public async ValueTask<ApiStatus> RecallMessage() { return await SoraApi.RecallMessage(MessageId); } /// <summary> /// 标记此消息已读 /// </summary> public async ValueTask<ApiStatus> MarkMessageRead() { return await SoraApi.MarkMessageRead(MessageId); } #endregion #region 快捷方法 /// <summary> /// 获取所有At的UID /// Notice:at全体不会被转换 /// </summary> /// <returns> /// <para>At的uid列表</para> /// <para><see cref="List{T}"/>(T=<see cref="long"/>)</para> /// </returns> public IEnumerable<long> GetAllAtList() { var uidList = MessageBody.Where(s => s.MessageType == SegmentType.At) .Select(s => long.TryParse((s.Data as AtSegment)?.Target ?? "0", out var uid) ? uid : -1) .ToList(); //去除无法转换的值,如at全体 uidList.RemoveAll(uid => uid == -1); return uidList; } /// <summary> /// 获取语音URL /// 仅在消息为语音时有效 /// </summary> /// <returns>语音文件url</returns> public string GetRecordUrl() { if (MessageBody.Count != 1 || MessageBody.First().MessageType != SegmentType.Record) return null; return (MessageBody.First().Data as RecordSegment)?.Url; } /// <summary> /// 获取所有图片信息 /// </summary> /// <returns> /// <para>图片信息结构体列表</para> /// <para><see cref="List{T}"/>(T=<see cref="ImageSegment"/>)</para> /// </returns> public IEnumerable<ImageSegment> GetAllImage() { return MessageBody.Where(s => s.MessageType == SegmentType.Image) .Select(s => s.Data as ImageSegment) .ToList(); } /// <summary> /// 是否是转发消息 /// </summary> public bool IsForwardMessage() { return MessageBody.Count == 1 && MessageBody.First().MessageType == SegmentType.Forward; } /// <summary> /// 获取合并转发的ID /// </summary> public string GetForwardMsgId() { return IsForwardMessage() ? (MessageBody.First().Data as ForwardSegment)?.MessageId : null; } /// <summary> /// 截取消息中的文字部分 /// </summary> public string GetText() { var text = new StringBuilder(); MessageBody.Where(s => s.MessageType == SegmentType.Text) .Select(s => s.Data as TextSegment) .ToList() .ForEach(t => text.Append(t?.Content ?? string.Empty)); return text.ToString(); } #endregion #region 转换方法 /// <summary> /// <para>转纯文本信息</para> /// <para>注意:消息段会被转换为onebot的string消息段格式</para> /// </summary> public override string ToString() { return RawText; } #endregion #region 运算符重载 /// <summary> /// 等于重载 /// </summary> public static bool operator ==(Message msgL, Message msgR) { if (msgL is null && msgR is null) return true; return msgL is not null && msgR is not null && msgL.MessageId == msgR.MessageId && msgL.SoraApi == msgR.SoraApi && msgL.Font == msgR.Font && msgL.Time == msgR.Time && msgL.MessageSequence == msgR.MessageSequence && msgL.RawText.Equals(msgR.RawText); } /// <summary> /// 不等于重载 /// </summary> public static bool operator !=(Message msgL, Message msgR) { return !(msgL == msgR); } #endregion #region 常用重载 /// <summary> /// 比较重载 /// </summary> public override bool Equals(object obj) { if (obj is Message msg) { return this == msg; } return false; } /// <summary> /// GetHashCode /// </summary> public override int GetHashCode() { return HashCode.Combine(MessageId, RawText, MessageBody, Time, Font, MessageSequence); } #endregion #region 索引器 /// <summary> /// 索引器 /// </summary> /// <param name="index">索引</param> /// <exception cref="ArgumentOutOfRangeException">索引超出范围</exception> /// <exception cref="NullReferenceException">读取到了空消息段</exception> public SoraSegment this[int index] { get => MessageBody[index]; internal set => MessageBody[index] = value; } #endregion } }
27.444444
109
0.461105
[ "Apache-2.0" ]
RingoStudio/Sora
Sora/Entities/Message.cs
7,358
C#
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Windows.Documents; using ICSharpCode.AvalonEdit.Document; namespace ICSharpCode.AvalonEdit.Snippets { /// <summary> /// An element that binds to a <see cref="SnippetReplaceableTextElement"/> and displays the same text. /// </summary> [Serializable] public class SnippetBoundElement : SnippetElement { SnippetReplaceableTextElement targetElement; /// <summary> /// Gets/Sets the target element. /// </summary> public SnippetReplaceableTextElement TargetElement { get { return targetElement; } set { targetElement = value; } } /// <summary> /// Converts the text before copying it. /// </summary> public virtual string ConvertText(string input) { return input; } /// <inheritdoc/> public override void Insert(InsertionContext context) { if (targetElement != null) { TextAnchor start = context.Document.CreateAnchor(context.InsertionPosition); start.MovementType = AnchorMovementType.BeforeInsertion; start.SurviveDeletion = true; string inputText = targetElement.Text; if (inputText != null) { context.InsertText(ConvertText(inputText)); } TextAnchor end = context.Document.CreateAnchor(context.InsertionPosition); end.MovementType = AnchorMovementType.BeforeInsertion; end.SurviveDeletion = true; AnchorSegment segment = new AnchorSegment(start, end); context.RegisterActiveElement(this, new BoundActiveElement(context, targetElement, this, segment)); } } /// <inheritdoc/> public override Inline ToTextRun() { if (targetElement != null) { string inputText = targetElement.Text; if (inputText != null) { return new Italic(new Run(ConvertText(inputText))); } } return base.ToTextRun(); } } sealed class BoundActiveElement : IActiveElement { InsertionContext context; SnippetReplaceableTextElement targetSnippetElement; SnippetBoundElement boundElement; internal IReplaceableActiveElement targetElement; AnchorSegment segment; public BoundActiveElement(InsertionContext context, SnippetReplaceableTextElement targetSnippetElement, SnippetBoundElement boundElement, AnchorSegment segment) { this.context = context; this.targetSnippetElement = targetSnippetElement; this.boundElement = boundElement; this.segment = segment; } public void OnInsertionCompleted() { targetElement = context.GetActiveElement(targetSnippetElement) as IReplaceableActiveElement; if (targetElement != null) { targetElement.TextChanged += targetElement_TextChanged; } } void targetElement_TextChanged(object sender, EventArgs e) { // Don't copy text if the segments overlap (we would get an endless loop). // This can happen if the user deletes the text between the replaceable element and the bound element. if (SimpleSegment.GetOverlap(segment, targetElement.Segment) == SimpleSegment.Invalid) { int offset = segment.Offset; int length = segment.Length; string text = boundElement.ConvertText(targetElement.Text); if (length != text.Length || text != context.Document.GetText(offset, length)) { // Call replace only if we're actually changing something. // Without this check, we would generate an empty undo group when the user pressed undo. context.Document.Replace(offset, length, text); if (length == 0) { // replacing an empty anchor segment with text won't enlarge it, so we have to recreate it segment = new AnchorSegment(context.Document, offset, text.Length); } } } } public void Deactivate(SnippetEventArgs e) { } public bool IsEditable { get { return false; } } public ISegment Segment { get { return segment; } } } }
34.971223
162
0.736885
[ "MIT" ]
Acorisoft/AvalonEdit
ICSharpCode.AvalonEdit/Snippets/SnippetBoundElement.cs
4,863
C#
#if HasRoutes using System; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.AspNetCore.Routing; #endif namespace Prometheus.Client.HttpRequestDurations.Tools { internal static class HttpContextExtensions { #if HasRoutes public static string GetRouteName(this HttpContext httpContext) { if (httpContext == null) throw new ArgumentNullException(nameof(httpContext)); var endpoint = httpContext.GetEndpoint(); var result = endpoint?.Metadata.GetMetadata<RouteNameMetadata>()?.RouteName; if (string.IsNullOrEmpty(result)) { var routeAttribute = endpoint?.Metadata.GetMetadata<RouteAttribute>(); var methodAttribute = endpoint?.Metadata.GetMetadata<HttpMethodAttribute>(); result = $"{routeAttribute?.Template}{methodAttribute?.Template}"; } return result; } #endif } }
28.555556
92
0.660506
[ "MIT" ]
PrometheusClientNet/Prometheus.Client.HttpRequestDurations
src/Tools/HttpContextExtensions.cs
1,028
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Reflection; using System.Text; using System.Threading; using System.Web; using log4net; using OpenSim.Framework.ServiceAuth; namespace OpenSim.Framework { /// <summary> /// Implementation of a generic REST client /// </summary> /// <remarks> /// This class is a generic implementation of a REST (Representational State Transfer) web service. This /// class is designed to execute both synchronously and asynchronously. /// /// Internally the implementation works as a two stage asynchronous web-client. /// When the request is initiated, RestClient will query asynchronously for for a web-response, /// sleeping until the initial response is returned by the server. Once the initial response is retrieved /// the second stage of asynchronous requests will be triggered, in an attempt to read of the response /// object into a memorystream as a sequence of asynchronous reads. /// /// The asynchronisity of RestClient is designed to move as much processing into the back-ground, allowing /// other threads to execute, while it waits for a response from the web-service. RestClient itself can be /// invoked by the caller in either synchronous mode or asynchronous modes. /// </remarks> public class RestClient : IDisposable { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // private string realuri; #region member variables /// <summary> /// The base Uri of the web-service e.g. http://www.google.com /// </summary> private string _url; /// <summary> /// Path elements of the query /// </summary> private List<string> _pathElements = new List<string>(); /// <summary> /// Parameter elements of the query, e.g. min=34 /// </summary> private Dictionary<string, string> _parameterElements = new Dictionary<string, string>(); /// <summary> /// Request method. E.g. GET, POST, PUT or DELETE /// </summary> private string _method; /// <summary> /// Temporary buffer used to store bytes temporarily as they come in from the server /// </summary> private byte[] _readbuf; /// <summary> /// MemoryStream representing the resulting resource /// </summary> private Stream _resource; /// <summary> /// WebRequest object, held as a member variable /// </summary> private HttpWebRequest _request; /// <summary> /// WebResponse object, held as a member variable, so we can close it /// </summary> private HttpWebResponse _response; /// <summary> /// This flag will help block the main synchroneous method, in case we run in synchroneous mode /// </summary> //public static ManualResetEvent _allDone = new ManualResetEvent(false); /// <summary> /// Default time out period /// </summary> //private const int DefaultTimeout = 10*1000; // 10 seconds timeout /// <summary> /// Default Buffer size of a block requested from the web-server /// </summary> private const int BufferSize = 4096; // Read blocks of 4 KB. /// <summary> /// if an exception occours during async processing, we need to save it, so it can be /// rethrown on the primary thread; /// </summary> private Exception _asyncException; #endregion member variables #region constructors /// <summary> /// Instantiate a new RestClient /// </summary> /// <param name="url">Web-service to query, e.g. http://osgrid.org:8003</param> public RestClient(string url) { _url = url; _readbuf = new byte[BufferSize]; _resource = new MemoryStream(); _request = null; _response = null; _lock = new object(); } private object _lock; #endregion constructors #region Dispose private bool disposed = false; public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) { _resource.Dispose(); } disposed = true; } #endregion Dispose /// <summary> /// Add a path element to the query, e.g. assets /// </summary> /// <param name="element">path entry</param> public void AddResourcePath(string element) { if (isSlashed(element)) _pathElements.Add(element.Substring(0, element.Length - 1)); else _pathElements.Add(element); } /// <summary> /// Add a query parameter to the Url /// </summary> /// <param name="name">Name of the parameter, e.g. min</param> /// <param name="value">Value of the parameter, e.g. 42</param> public void AddQueryParameter(string name, string value) { try { _parameterElements.Add(HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(value)); } catch (ArgumentException) { m_log.Error("[REST]: Query parameter " + name + " is already added."); } catch (Exception e) { m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e); } } /// <summary> /// Add a query parameter to the Url /// </summary> /// <param name="name">Name of the parameter, e.g. min</param> public void AddQueryParameter(string name) { try { _parameterElements.Add(HttpUtility.UrlEncode(name), null); } catch (ArgumentException) { m_log.Error("[REST]: Query parameter " + name + " is already added."); } catch (Exception e) { m_log.Error("[REST]: An exception was raised adding query parameter to dictionary. Exception: {0}",e); } } /// <summary> /// Web-Request method, e.g. GET, PUT, POST, DELETE /// </summary> public string RequestMethod { get { return _method; } set { _method = value; } } /// <summary> /// True if string contains a trailing slash '/' /// </summary> /// <param name="s">string to be examined</param> /// <returns>true if slash is present</returns> private static bool isSlashed(string s) { return s.Substring(s.Length - 1, 1) == "/"; } /// <summary> /// Build a Uri based on the initial Url, path elements and parameters /// </summary> /// <returns>fully constructed Uri</returns> private Uri buildUri() { StringBuilder sb = new StringBuilder(); sb.Append(_url); foreach (string e in _pathElements) { sb.Append("/"); sb.Append(e); } bool firstElement = true; foreach (KeyValuePair<string, string> kv in _parameterElements) { if (firstElement) { sb.Append("?"); firstElement = false; } else sb.Append("&"); sb.Append(kv.Key); if (!string.IsNullOrEmpty(kv.Value)) { sb.Append("="); sb.Append(kv.Value); } } // realuri = sb.ToString(); //m_log.InfoFormat("[REST CLIENT]: RestURL: {0}", realuri); return new Uri(sb.ToString()); } #region Async communications with server /// <summary> /// Async method, invoked when a block of data has been received from the service /// </summary> /// <param name="ar"></param> private void StreamIsReadyDelegate(IAsyncResult ar) { try { Stream s = (Stream) ar.AsyncState; int read = s.EndRead(ar); if (read > 0) { _resource.Write(_readbuf, 0, read); // IAsyncResult asynchronousResult = // s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s); s.BeginRead(_readbuf, 0, BufferSize, new AsyncCallback(StreamIsReadyDelegate), s); // TODO! Implement timeout, without killing the server //ThreadPool.RegisterWaitForSingleObject(asynchronousResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true); } else { s.Close(); //_allDone.Set(); } } catch (Exception e) { //_allDone.Set(); _asyncException = e; } } #endregion Async communications with server /// <summary> /// Perform a synchronous request /// </summary> public Stream Request() { return Request(null); } /// <summary> /// Perform a synchronous request /// </summary> public Stream Request(IServiceAuth auth) { lock (_lock) { _request = (HttpWebRequest) WebRequest.Create(buildUri()); _request.KeepAlive = false; _request.ContentType = "application/xml"; _request.Timeout = 200000; _request.Method = RequestMethod; _asyncException = null; if (auth != null) auth.AddAuthorization(_request.Headers); int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} REST {1} to {2}", reqnum, _request.Method, _request.RequestUri); // IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request); try { using (_response = (HttpWebResponse) _request.GetResponse()) { using (Stream src = _response.GetResponseStream()) { int length = src.Read(_readbuf, 0, BufferSize); while (length > 0) { _resource.Write(_readbuf, 0, length); length = src.Read(_readbuf, 0, BufferSize); } // TODO! Implement timeout, without killing the server // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true); // _allDone.WaitOne(); } } } catch (WebException e) { using (HttpWebResponse errorResponse = e.Response as HttpWebResponse) { if (null != errorResponse && HttpStatusCode.NotFound == errorResponse.StatusCode) { // This is often benign. E.g., requesting a missing asset will return 404. m_log.DebugFormat("[REST CLIENT] Resource not found (404): {0}", _request.Address.ToString()); } else { m_log.Error(string.Format("[REST CLIENT] Error fetching resource from server: {0} ", _request.Address.ToString()), e); } } return null; } if (_asyncException != null) throw _asyncException; if (_resource != null) { _resource.Flush(); _resource.Seek(0, SeekOrigin.Begin); } if (WebUtil.DebugLevel >= 5) WebUtil.LogResponseDetail(reqnum, _resource); return _resource; } } public Stream Request(Stream src, IServiceAuth auth) { _request = (HttpWebRequest) WebRequest.Create(buildUri()); _request.KeepAlive = false; _request.ContentType = "application/xml"; _request.Timeout = 90000; _request.Method = RequestMethod; _asyncException = null; _request.ContentLength = src.Length; if (auth != null) auth.AddAuthorization(_request.Headers); src.Seek(0, SeekOrigin.Begin); int reqnum = WebUtil.RequestNumber++; if (WebUtil.DebugLevel >= 3) m_log.DebugFormat("[LOGHTTP]: HTTP OUT {0} REST {1} to {2}", reqnum, _request.Method, _request.RequestUri); if (WebUtil.DebugLevel >= 5) WebUtil.LogOutgoingDetail(string.Format("SEND {0}: ", reqnum), src); try { using (Stream dst = _request.GetRequestStream()) { // m_log.Debug("[REST]: GetRequestStream is ok"); byte[] buf = new byte[1024]; int length = src.Read(buf, 0, 1024); // m_log.Debug("[REST]: First Read is ok"); while (length > 0) { dst.Write(buf, 0, length); length = src.Read(buf, 0, 1024); } } _response = (HttpWebResponse)_request.GetResponse(); } catch (WebException e) { m_log.WarnFormat("[REST]: Request {0} {1} failed with status {2} and message {3}", RequestMethod, _request.RequestUri, e.Status, e.Message); return null; } catch (Exception e) { m_log.WarnFormat( "[REST]: Request {0} {1} failed with exception {2} {3}", RequestMethod, _request.RequestUri, e.Message, e.StackTrace); return null; } if (WebUtil.DebugLevel >= 5) { using (Stream responseStream = _response.GetResponseStream()) { using (StreamReader reader = new StreamReader(responseStream)) { string responseStr = reader.ReadToEnd(); WebUtil.LogResponseDetail(reqnum, responseStr); } } } if (_response != null) _response.Close(); // IAsyncResult responseAsyncResult = _request.BeginGetResponse(new AsyncCallback(ResponseIsReadyDelegate), _request); // TODO! Implement timeout, without killing the server // this line implements the timeout, if there is a timeout, the callback fires and the request becomes aborted //ThreadPool.RegisterWaitForSingleObject(responseAsyncResult.AsyncWaitHandle, new WaitOrTimerCallback(TimeoutCallback), _request, DefaultTimeout, true); return null; } #region Async Invocation public IAsyncResult BeginRequest(AsyncCallback callback, object state) { /// <summary> /// In case, we are invoked asynchroneously this object will keep track of the state /// </summary> AsyncResult<Stream> ar = new AsyncResult<Stream>(callback, state); Util.FireAndForget(RequestHelper, ar, "RestClient.BeginRequest"); return ar; } public Stream EndRequest(IAsyncResult asyncResult) { AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult; // Wait for operation to complete, then return result or // throw exception return ar.EndInvoke(); } private void RequestHelper(Object asyncResult) { // We know that it's really an AsyncResult<DateTime> object AsyncResult<Stream> ar = (AsyncResult<Stream>) asyncResult; try { // Perform the operation; if sucessful set the result Stream s = Request(null); ar.SetAsCompleted(s, false); } catch (Exception e) { // If operation fails, set the exception ar.HandleException(e, false); } } #endregion Async Invocation } internal class SimpleAsyncResult : IAsyncResult { private readonly AsyncCallback m_callback; /// <summary> /// Is process completed? /// </summary> /// <remarks>Should really be boolean, but VolatileRead has no boolean method</remarks> private byte m_completed; /// <summary> /// Did process complete synchronously? /// </summary> /// <remarks>I have a hard time imagining a scenario where this is the case, again, same issue about /// booleans and VolatileRead as m_completed /// </remarks> private byte m_completedSynchronously; private readonly object m_asyncState; private ManualResetEvent m_waitHandle; private Exception m_exception; internal SimpleAsyncResult(AsyncCallback cb, object state) { m_callback = cb; m_asyncState = state; m_completed = 0; m_completedSynchronously = 1; } #region IAsyncResult Members public object AsyncState { get { return m_asyncState; } } public WaitHandle AsyncWaitHandle { get { if (m_waitHandle == null) { bool done = IsCompleted; ManualResetEvent mre = new ManualResetEvent(done); if (Interlocked.CompareExchange(ref m_waitHandle, mre, null) != null) { mre.Close(); } else { if (!done && IsCompleted) { m_waitHandle.Set(); } } } return m_waitHandle; } } public bool CompletedSynchronously { get { return Thread.VolatileRead(ref m_completedSynchronously) == 1; } } public bool IsCompleted { get { return Thread.VolatileRead(ref m_completed) == 1; } } #endregion #region class Methods internal void SetAsCompleted(bool completedSynchronously) { m_completed = 1; if (completedSynchronously) m_completedSynchronously = 1; else m_completedSynchronously = 0; SignalCompletion(); } internal void HandleException(Exception e, bool completedSynchronously) { m_completed = 1; if (completedSynchronously) m_completedSynchronously = 1; else m_completedSynchronously = 0; m_exception = e; SignalCompletion(); } private void SignalCompletion() { if (m_waitHandle != null) m_waitHandle.Set(); if (m_callback != null) m_callback(this); } public void EndInvoke() { // This method assumes that only 1 thread calls EndInvoke if (!IsCompleted) { // If the operation isn't done, wait for it AsyncWaitHandle.WaitOne(); AsyncWaitHandle.Close(); m_waitHandle.Close(); m_waitHandle = null; // Allow early GC } // Operation is done: if an exception occured, throw it if (m_exception != null) throw m_exception; } #endregion } internal class AsyncResult<T> : SimpleAsyncResult { private T m_result = default(T); public AsyncResult(AsyncCallback asyncCallback, Object state) : base(asyncCallback, state) { } public void SetAsCompleted(T result, bool completedSynchronously) { // Save the asynchronous operation's result m_result = result; // Tell the base class that the operation completed // sucessfully (no exception) base.SetAsCompleted(completedSynchronously); } public new T EndInvoke() { base.EndInvoke(); return m_result; } } }
34.569546
180
0.533734
[ "BSD-3-Clause" ]
SignpostMarv/opensim
OpenSim/Framework/RestClient.cs
23,611
C#
using System; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows; using JetBrains.Annotations; using OxyPlot; using OxyPlot.Series; using WaveShaper.Core.PiecewiseFunctions; namespace WaveShaper.Controls { /// <summary> /// Interaction logic for EffectPreview.xaml /// </summary> public partial class EffectPreview : Window, INotifyPropertyChanged { private PlotModel plotModel = new PlotModel(); private readonly Func<double, double> shapingFunction; public EffectPreview(Func<double, double> shapingFunction) { this.shapingFunction = shapingFunction; InitializeComponent(); Plot(); } public PlotModel PlotModel { get => plotModel; set { if (Equals(value, plotModel)) return; plotModel = value; OnPropertyChanged(); } } private void Plot() { try { Func<double, double> func = Math.Sin; const int @from = -1; const int to = 10; const int steps = 1000; PlotModel.Series.Clear(); PlotModel.Series.Add(new FunctionSeries(func, from, to, steps, "s(t)") {Color = OxyColor.FromRgb(0, 0, 255)}); PlotModel.Series.Add(new FunctionSeries(x => shapingFunction(func(x)), from, to, steps, "f(s(t))") { Color = OxyColor.FromRgb(255, 0, 0) }); PlotModel.InvalidatePlot(true); } catch (PiecewiseFunctionInputOutOfRange) { MessageBox.Show(this, "Function does not cover all possible values.", "Error"); } } #region PropertyChanged public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion } }
30.069444
156
0.581524
[ "MIT" ]
jenzy/WaveShaper
src/WaveShaper/Controls/EffectPreview.xaml.cs
2,167
C#
 using System; using System.Collections.Generic; using UnityEngine; namespace Weathering { [Concept] public class Quest_CongratulationsQuestAllCompleted { } [Concept] public class Quest_LandRocket { } [Concept] public class Quest_CollectFood_Initial { } // 解锁:探索功能 [Concept] public class Quest_ConstructBerryBushAndWareHouse_Initial { } // 解锁:浆果丛, 茅草仓库 [Concept] public class Quest_CollectFood_Hunting { } // 解锁:道路, 猎场, 渔场 [Concept] public class Quest_HavePopulation_Settlement { } // 解锁:草屋 [Concept] public class Quest_CollectFood_Agriculture { } // 解锁:农田 [Concept] public class Quest_HavePopulation_PopulationGrowth { } // [Concept] public class Quest_CollectWood_Woodcutting { } // 解锁:伐木场 [Concept] public class Quest_ProduceWoodProduct_WoodProcessing { } // 解锁:锯木厂 [Concept] public class Quest_CollectStone_Stonecutting { } // 解锁:采石场 [Concept] public class Quest_ProduceStoneProduct_StoneProcessing { } // 解锁:石材加工厂 [Concept] public class Quest_ConstructBridge { } // 解锁:桥 [Concept] public class Quest_ProduceToolPrimitive { } // 解锁:工具厂 [Concept] public class Quest_HavePopulation_ResidenceConstruction { } // 解锁:砖厂 [Concept] public class Quest_ProduceWheelPrimitive { } // 解锁:车轮厂 [Concept] public class Quest_GainGoldCoinThroughMarket { } // 解锁:市场 [Concept] public class Quest_CollectMetalOre_Mining { } // 解锁:采矿厂 [Concept] public class Quest_ProduceMetal_Smelting { } // 解锁:冶炼厂, 运输站, 运输站终点 [Concept] public class Quest_ProduceMetalProduct_Casting { } // 解锁:铸造场 [Concept] public class Quest_ProduceMachinePrimitive { } // 解锁:简易机器厂 [Concept] public class Quest_CollectCoal { } // 解锁:煤矿 [Concept] public class Quest_ProduceSteel { } // 解锁:钢厂 [Concept] public class Quest_ProduceConcrete { } // 解锁:水泥厂 [Concept] public class Quest_ProduceBuildingPrefabrication { } // 解锁:建筑结构厂 [Concept] public class Quest_ProduceElectricity { } // 解锁:水泵, 管道, 发电厂 [Concept] public class Quest_ProduceAluminum { } // 解锁:铝土矿, 炼铝厂 [Concept] public class Quest_ProduceLPG { } // 解锁:炼油厂, 裂解厂 [Concept] public class Quest_ProducePlastic { } // 解锁:塑料厂 [Concept] public class Quest_ProduceLightMaterial { } // 解锁:铝土矿, 炼铝厂 public class MainQuestConfig : MonoBehaviour { public static MainQuestConfig Ins { get; private set; } private void Awake() { if (Ins != null) throw new Exception(); Ins = this; int i = 0; foreach (var quest in QuestSequence) { indexDict.Add(quest, i); i++; } OnTapQuest = new Dictionary<Type, Action<List<IUIItem>>>(); OnStartQuest = new Dictionary<Type, Action>(); CanCompleteQuest = new Dictionary<Type, Func<bool>>(); CreateOnTapQuest(); } public Dictionary<Type, Action<List<IUIItem>>> OnTapQuest { get; private set; } public Dictionary<Type, Action> OnStartQuest { get; private set; } public Dictionary<Type, Func<bool>> CanCompleteQuest { get; private set; } public List<Type> QuestSequence { get; } = new List<Type> { typeof(Quest_LandRocket), typeof(Quest_CollectFood_Initial), typeof(Quest_ConstructBerryBushAndWareHouse_Initial), typeof(Quest_CollectFood_Hunting), typeof(Quest_HavePopulation_Settlement), typeof(Quest_CollectFood_Agriculture), typeof(Quest_HavePopulation_PopulationGrowth), typeof(Quest_CollectWood_Woodcutting), typeof(Quest_ProduceWoodProduct_WoodProcessing), typeof(Quest_CollectStone_Stonecutting), typeof(Quest_ProduceStoneProduct_StoneProcessing), typeof(Quest_ConstructBridge), typeof(Quest_ProduceToolPrimitive), typeof(Quest_HavePopulation_ResidenceConstruction), typeof(Quest_ProduceWheelPrimitive), typeof(Quest_GainGoldCoinThroughMarket), typeof(Quest_CollectMetalOre_Mining), typeof(Quest_ProduceMetal_Smelting), typeof(Quest_ProduceMetalProduct_Casting), typeof(Quest_ProduceMachinePrimitive), typeof(Quest_CollectCoal), typeof(Quest_ProduceSteel), typeof(Quest_ProduceConcrete), typeof(Quest_ProduceBuildingPrefabrication), typeof(Quest_ProduceElectricity), typeof(Quest_ProduceAluminum), typeof(Quest_ProduceLPG), typeof(Quest_ProducePlastic), typeof(Quest_ProduceLightMaterial), typeof(Quest_CongratulationsQuestAllCompleted), }; private readonly Dictionary<Type, int> indexDict = new Dictionary<Type, int>(); public int GetIndex(Type quest) { if (!indexDict.TryGetValue(quest, out int id)) { throw new Exception($"找不到任务{quest.Name}对应的id"); } return id; } private string FAQ(string question) { return $"<color=#ff9999>({question})</color>"; } // public readonly static Type StartingQuest = typeof(Quest_CollectMetalOre_Mining); public readonly static Type StartingQuest = GameConfig.CheatMode ? typeof(Quest_CongratulationsQuestAllCompleted) : typeof(Quest_LandRocket); private void CreateOnTapQuest() { OnTapQuest.Add(typeof(Quest_CongratulationsQuestAllCompleted), items => { items.Add(UIItem.CreateMultilineText("已经完成了全部任务! 此任务无法完成, 并且没有更多任务了")); // items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<OilDriller>()}{Localization.Ins.Get<RoadForFluid>()}")); // items.Add(UIItem.CreateMultilineText($"刚解锁的东西并没有什么用")); }); // 登陆星球 OnTapQuest.Add(typeof(Quest_LandRocket), items => { items.Add(UIItem.CreateMultilineText("飞船正在宇宙中飞行, 是时候找一个星球降落了")); items.Add(UIItem.CreateSeparator()); items.Add(UIItem.CreateMultilineText($"{FAQ("如何降落?")} 进入螺旋星系、进入恒星系、进入星球、点击平原, 点击降落")); }); // 采集浆果 const long difficulty_Quest_CollectFood_Initial = 10; CanCompleteQuest.Add(typeof(Quest_CollectFood_Initial), () => MapView.Ins.TheOnlyActiveMap.Inventory.CanRemove<Berry>() >= difficulty_Quest_CollectFood_Initial); OnTapQuest.Add(typeof(Quest_CollectFood_Initial), items => { items.Add(UIItem.CreateMultilineText($"已解锁 探索{Localization.Ins.Get<TerrainType_Forest>()}")); items.Add(UIItem.CreateMultilineText($"目标: 获得{Localization.Ins.Val<Berry>(difficulty_Quest_CollectFood_Initial)}")); items.Add(UIItem.CreateSeparator()); items.Add(UIItem.CreateMultilineText($"{FAQ($"如何获得{Localization.Ins.ValUnit<Berry>()}")} 点击{Localization.Ins.Get<TerrainType_Forest>()}, 点击探索")); items.Add(UIItem.CreateMultilineText($"{FAQ($"如何获得查看浆果数量?")} 点击地图右上角“文件夹”按钮")); items.Add(UIItem.CreateMultilineText($"{FAQ($"如何获得查看当前体力?")} 点击小人")); }); // 建造浆果丛和仓库 CanCompleteQuest.Add(typeof(Quest_ConstructBerryBushAndWareHouse_Initial), () => { IMap map = MapView.Ins.TheOnlyActiveMap; IRefs refs = map.Refs; return refs.GetOrCreate<WareHouseOfGrass>().Value >= 1 && refs.GetOrCreate<BerryBush>().Value >= 1; }); OnTapQuest.Add(typeof(Quest_ConstructBerryBushAndWareHouse_Initial), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<BerryBush>()}{Localization.Ins.Get<WareHouseOfGrass>()}")); items.Add(UIItem.CreateMultilineText($"目标: 建造{Localization.Ins.Get<BerryBush>()}和{Localization.Ins.Get<WareHouseOfGrass>()}")); items.Add(UIItem.CreateText($"当前人口数: {Localization.Ins.Val(typeof(Worker), MapView.Ins.TheOnlyActiveMap.Values.GetOrCreate<Worker>().Max)}")); items.Add(UIItem.CreateSeparator()); items.Add(UIItem.CreateMultilineText($"{FAQ($"如何建造{Localization.Ins.Get<WareHouseOfGrass>()}?")} 点击{Localization.Ins.Get<TerrainType_Plain>()}, 点击物流")); items.Add(UIItem.CreateMultilineText($"{FAQ($"如何建造{Localization.Ins.Get<BerryBush>()}?")} 点击{Localization.Ins.Get<TerrainType_Plain>()}, 点击农业")); items.Add(UIItem.CreateMultilineText($"{FAQ($"快速收集仓库资源的方法?")} 走过仓库, 自动收集。收集成功时有音效")); }); // 食物 const long difficulty_Quest_CollectFood_Hunting = 200; OnStartQuest.Add(typeof(Quest_CollectFood_Hunting), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = difficulty_Quest_CollectFood_Hunting; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(Food); }); OnTapQuest.Add(typeof(Quest_CollectFood_Hunting), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<WareHouseOfGrass>()}{Localization.Ins.Get<RoadForSolid>()}{Localization.Ins.Get<BerryBush>()}{Localization.Ins.Get<HuntingGround>()}{Localization.Ins.Get<SeaFishery>()}")); items.Add(UIItem.CreateMultilineText($"目标: 拥有{Localization.Ins.Val(typeof(Food), difficulty_Quest_CollectFood_Hunting)}")); items.Add(UIItem.CreateSeparator()); items.Add(UIItem.CreateMultilineText($"{FAQ("如何自动获取大量食材?")} 建造{Localization.Ins.Get<BerryBush>()}或{Localization.Ins.Get<HuntingGround>()}或{Localization.Ins.Get<SeaFishery>()};点击平原、建造{Localization.Ins.Get<WareHouseOfGrass>()};使用磁铁工具, 建立资源连接;走过或点击{Localization.Ins.Get<WareHouseOfGrass>()}、收取资源")); }); // 获取居民 const long difficulty_Quest_HavePopulation_Settlement = 5; CanCompleteQuest.Add(typeof(Quest_HavePopulation_Settlement), () => MapView.Ins.TheOnlyActiveMap.Values.GetOrCreate<Worker>().Max >= difficulty_Quest_HavePopulation_Settlement); // 注释掉的是拥有空闲工人人物的配置 //OnStartQuest.Add(typeof(Quest_HavePopulation_Settlement), () => { // Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = difficulty_Quest_HavePopulation_Settlement; // Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(Worker); //}); OnTapQuest.Add(typeof(Quest_HavePopulation_Settlement), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<ResidenceOfGrass>()}{Localization.Ins.Get<CellarForPersonalStorage>()}")); items.Add(UIItem.CreateMultilineText($"目标: 总人口数达到{Localization.Ins.Val(typeof(Worker), difficulty_Quest_HavePopulation_Settlement)}")); items.Add(UIItem.CreateText($"当前人口数: {Localization.Ins.Val(typeof(Worker), MapView.Ins.TheOnlyActiveMap.Values.GetOrCreate<Worker>().Max)}")); items.Add(UIItem.CreateSeparator()); items.Add(UIItem.CreateMultilineText($"{FAQ("如何生产居民?")} 建造村庄, 建造道路连接猎场与村庄, 点击村庄获得居民")); }); // 原始农业 const long difficulty_Quest_CollectFood_Agriculture = 3000; OnStartQuest.Add(typeof(Quest_CollectFood_Agriculture), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = difficulty_Quest_CollectFood_Agriculture; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(Grain); }); OnTapQuest.Add(typeof(Quest_CollectFood_Agriculture), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<Farm>()}{Localization.Ins.Get<Pasture>()}{Localization.Ins.Get<Hennery>()}")); items.Add(UIItem.CreateText($"目标: 拥有{Localization.Ins.Val(typeof(Grain), difficulty_Quest_CollectFood_Agriculture)}")); items.Add(UIItem.CreateText($"当前产量: {Localization.Ins.Val(typeof(Grain), MapView.Ins.TheOnlyActiveMap.Values.GetOrCreate<Grain>().Max)}")); items.Add(UIItem.CreateSeparator()); items.Add(UIItem.CreateMultilineText($"{FAQ("如何种田?")} 建造{Localization.Ins.Get<Farm>()}, 派遣居民。")); items.Add(UIItem.CreateMultilineText($"{FAQ($"如何获得{Localization.Ins.ValUnit<WoodPlank>()}?")} 暂时无法获得, 完成后续任务解锁")); }); // 人口增长 const long difficulty_Quest_HavePopulation_PopulationGrowth = 30; CanCompleteQuest.Add(typeof(Quest_HavePopulation_PopulationGrowth), () => MapView.Ins.TheOnlyActiveMap.Values.GetOrCreate<Worker>().Max >= difficulty_Quest_HavePopulation_PopulationGrowth); //OnStartQuest.Add(typeof(Quest_HavePopulation_PopulationGrowth), () => { // Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = difficulty_Quest_HavePopulation_PopulationGrowth; // Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(Worker); //}); OnTapQuest.Add(typeof(Quest_HavePopulation_PopulationGrowth), items => { items.Add(UIItem.CreateText($"目标: 总人口数达到{Localization.Ins.Val(typeof(Worker), difficulty_Quest_HavePopulation_PopulationGrowth)}")); items.Add(UIItem.CreateText($"当前人口数: {Localization.Ins.Val(typeof(Worker), MapView.Ins.TheOnlyActiveMap.Values.GetOrCreate<Worker>().Max)}")); items.Add(UIItem.CreateSeparator()); items.Add(UIItem.CreateMultilineText($"{FAQ("如何生产更多居民?")} 建造{Localization.Ins.Get<Farm>()}和{Localization.Ins.Get<ResidenceOfGrass>()}。可以查看建筑功能页面, 注意建筑数量搭配")); }); // 初次伐木 const long difficulty_Quest_CollectWood_Woodcutting = 100; OnStartQuest.Add(typeof(Quest_CollectWood_Woodcutting), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = difficulty_Quest_CollectWood_Woodcutting; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(Wood); }); OnTapQuest.Add(typeof(Quest_CollectWood_Woodcutting), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<ForestLoggingCamp>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(Wood), difficulty_Quest_CollectWood_Woodcutting)}")); items.Add(UIItem.CreateSeparator()); items.Add(UIItem.CreateMultilineText($"{FAQ($"如何建造{Localization.Ins.Get<ForestLoggingCamp>()}?")} 点击{Localization.Ins.Get<TerrainType_Forest>()}, 点击林业")); }); // 木材加工 const long difficulty_Quest_ProduceWoodProduct_WoodProcessing = 100; OnStartQuest.Add(typeof(Quest_ProduceWoodProduct_WoodProcessing), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = difficulty_Quest_ProduceWoodProduct_WoodProcessing; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(WoodPlank); }); OnTapQuest.Add(typeof(Quest_ProduceWoodProduct_WoodProcessing), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<WorkshopOfWoodcutting>()}{Localization.Ins.Get<ResidenceOfWood>()}{Localization.Ins.Get<WareHouseOfWood>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(WoodPlank), difficulty_Quest_ProduceWoodProduct_WoodProcessing)}")); items.Add(UIItem.CreateSeparator()); items.Add(UIItem.CreateMultilineText($"{FAQ($"如何建造{Localization.Ins.Get<WorkshopOfWoodcutting>()}?")} 点击{Localization.Ins.Get<TerrainType_Plain>()}, 点击工业")); }); // 初次采石 const long difficulty_Quest_CollectStone_Stonecutting = 100; OnStartQuest.Add(typeof(Quest_CollectStone_Stonecutting), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = difficulty_Quest_CollectStone_Stonecutting; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(Stone); }); OnTapQuest.Add(typeof(Quest_CollectStone_Stonecutting), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<MountainQuarry>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(Stone), difficulty_Quest_CollectStone_Stonecutting)}")); items.Add(UIItem.CreateSeparator()); items.Add(UIItem.CreateMultilineText($"{FAQ($"如何建造{Localization.Ins.Get<MountainQuarry>()}?")} 点击{Localization.Ins.Get<TerrainType_Mountain>()}, 点击矿业")); }); // 石材加工 const long difficulty_Quest_ProduceStoneProduct_StoneProcessing = 100; OnStartQuest.Add(typeof(Quest_ProduceStoneProduct_StoneProcessing), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = difficulty_Quest_ProduceStoneProduct_StoneProcessing; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(StoneBrick); }); OnTapQuest.Add(typeof(Quest_ProduceStoneProduct_StoneProcessing), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<WorkshopOfStonecutting>()}{Localization.Ins.Get<ResidenceOfStone>()}{Localization.Ins.Get<WareHouseOfStone>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(StoneBrick), difficulty_Quest_ProduceStoneProduct_StoneProcessing)}")); }); // 造桥 const long difficulty_Quest_ConstructBridge = 1; CanCompleteQuest.Add(typeof(Quest_ConstructBridge), () => MapView.Ins.TheOnlyActiveMap.Refs.GetOrCreate<RoadAsBridge>().Value >= difficulty_Quest_ConstructBridge); OnTapQuest.Add(typeof(Quest_ConstructBridge), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<RoadAsBridge>()}")); items.Add(UIItem.CreateText($"目标: 建造{Localization.Ins.Get<RoadAsBridge>()}")); items.Add(UIItem.CreateSeparator()); items.Add(UIItem.CreateMultilineText($"{FAQ($"如何建造{Localization.Ins.Get<RoadAsBridge>()}?")} 点击{Localization.Ins.Get<TerrainType_Sea>()}")); items.Add(UIItem.CreateMultilineText($"{FAQ($"{Localization.Ins.Get<RoadAsBridge>()}有什么用?")} 跨越岛屿。桥也能像道路一样运输资源")); }); // 制造工具 const long difficulty_Quest_ProduceToolPrimitive = 100; OnStartQuest.Add(typeof(Quest_ProduceToolPrimitive), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = difficulty_Quest_ProduceToolPrimitive; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(ToolPrimitive); }); OnTapQuest.Add(typeof(Quest_ProduceToolPrimitive), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<WorkshopOfToolPrimitive>()}{Localization.Ins.Get<MineOfClay>()}{Localization.Ins.Get<ResidenceOfBrick>()}{Localization.Ins.Get<WareHouseOfBrick>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(ToolPrimitive), difficulty_Quest_ProduceToolPrimitive)}")); }); // 住房建设 const long difficulty_Quest_HavePopulation_ResidenceConstruction = 50; CanCompleteQuest.Add(typeof(Quest_HavePopulation_ResidenceConstruction), () => MapView.Ins.TheOnlyActiveMap.Values.GetOrCreate<Worker>().Max >= difficulty_Quest_HavePopulation_ResidenceConstruction); OnTapQuest.Add(typeof(Quest_HavePopulation_ResidenceConstruction), items => { items.Add(UIItem.CreateText($"目标: 总人口数达到{Localization.Ins.Val(typeof(Worker), difficulty_Quest_HavePopulation_ResidenceConstruction)}")); items.Add(UIItem.CreateText($"当前人口数: {Localization.Ins.Val(typeof(Worker), MapView.Ins.TheOnlyActiveMap.Values.GetOrCreate<Worker>().Max)}")); items.Add(UIItem.CreateSeparator()); items.Add(UIItem.CreateMultilineText($"{FAQ("如何生产更多居民? 建筑木屋、石屋、砖屋。草屋占地面积太大, 而且越来越贵了")}")); }); // 制造车轮 const long difficulty_Quest_ProduceWheelPrimitive = 100; OnStartQuest.Add(typeof(Quest_ProduceWheelPrimitive), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = difficulty_Quest_ProduceWheelPrimitive; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(WheelPrimitive); }); OnTapQuest.Add(typeof(Quest_ProduceWheelPrimitive), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<WorkshopOfWheelPrimitive>()}{Localization.Ins.Get<TransportStationSimpliest>()}{Localization.Ins.Get<TransportStationDestSimpliest>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(WheelPrimitive), difficulty_Quest_ProduceWheelPrimitive)}")); }); // 市场 OnStartQuest.Add(typeof(Quest_GainGoldCoinThroughMarket), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = 1; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(GoldCoin); }); OnTapQuest.Add(typeof(Quest_GainGoldCoinThroughMarket), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<MarketForPlayer>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(GoldCoin), 1)}")); items.Add(UIItem.CreateSeparator()); items.Add(UIItem.CreateMultilineText($"{FAQ($"如何建造{Localization.Ins.Get<WorkshopOfWoodcutting>()}?")} 点击{Localization.Ins.Get<TerrainType_Plain>()}, 点击特殊建筑")); }); // 初次采矿 OnStartQuest.Add(typeof(Quest_CollectMetalOre_Mining), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = 100; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(MetalOre); }); OnTapQuest.Add(typeof(Quest_CollectMetalOre_Mining), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<MineOfCopper>()}{Localization.Ins.Get<MineOfIron>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(MetalOre), 100)}")); items.Add(UIItem.CreateSeparator()); items.Add(UIItem.CreateMultilineText($"{FAQ("金属矿在哪里? ")}铜矿、铁矿, 都是金属矿。收集铜矿或铁矿都能完成任务")); }); // 金属冶炼 OnStartQuest.Add(typeof(Quest_ProduceMetal_Smelting), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = 100; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(MetalIngot); }); OnTapQuest.Add(typeof(Quest_ProduceMetal_Smelting), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<WorkshopOfCopperSmelting>()} {Localization.Ins.Get<WorkshopOfIronSmelting>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(MetalIngot), 100)}")); }); // 金属铸造 OnStartQuest.Add(typeof(Quest_ProduceMetalProduct_Casting), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = 100; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(MetalProduct); }); OnTapQuest.Add(typeof(Quest_ProduceMetalProduct_Casting), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<WorkshopOfCopperCasting>()}{Localization.Ins.Get<WorkshopOfIronCasting>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(MetalProduct), 100)}")); }); // 制作机器 OnStartQuest.Add(typeof(Quest_ProduceMachinePrimitive), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = 100; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(MachinePrimitive); }); OnTapQuest.Add(typeof(Quest_ProduceMachinePrimitive), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<WorkshopOfMachinePrimitive>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(MachinePrimitive), 100)}")); }); // 煤的开采 OnStartQuest.Add(typeof(Quest_CollectCoal), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = 100; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(Coal); }); OnTapQuest.Add(typeof(Quest_CollectCoal), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<MineOfCoal>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(Coal), 100)}")); }); // 钢的冶炼 OnStartQuest.Add(typeof(Quest_ProduceSteel), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = 100; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(SteelIngot); }); OnTapQuest.Add(typeof(Quest_ProduceSteel), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<WorkshopOfSteelWorking>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(SteelIngot), 100)}")); }); // 水泥制造 OnStartQuest.Add(typeof(Quest_ProduceConcrete), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = 100; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(ConcretePowder); }); OnTapQuest.Add(typeof(Quest_ProduceConcrete), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<WorkshopOfConcrete>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(ConcretePowder), 100)}")); }); // 建筑合成 OnStartQuest.Add(typeof(Quest_ProduceBuildingPrefabrication), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = 100; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(BuildingPrefabrication); }); OnTapQuest.Add(typeof(Quest_ProduceBuildingPrefabrication), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<WorkshopOfBuildingPrefabrication>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(BuildingPrefabrication), 100)}")); }); //[Concept] //public class Quest_ProduceElectricity { } // 解锁:水泵, 管道, 发电厂 //[Concept] //public class Quest_ProduceAluminum { } // 解锁:铝土矿, 炼铝厂 //[Concept] //public class Quest_ProduceNaturalGas { } // 解锁:炼油厂, 裂解厂 //[Concept] //public class Quest_ProducePlastic { } // 解锁:塑料厂 //[Concept] //public class Quest_ProduceLightMaterial { } // 解锁:铝土矿, 炼铝厂 // 发电 const long difficulty_Quest_ProduceElectricity = 50; OnStartQuest.Add(typeof(Quest_ProduceElectricity), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = difficulty_Quest_ProduceElectricity; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(Electricity); }); OnTapQuest.Add(typeof(Quest_ProduceElectricity), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<SeaWaterPump>()} {Localization.Ins.Get<RoadForFluid>()} {Localization.Ins.Get<PowerGeneratorOfWood>()} {Localization.Ins.Get<PowerGeneratorOfCoal>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(Electricity), difficulty_Quest_ProduceElectricity)}")); items.Add(UIItem.CreateSeparator()); items.Add(UIItem.CreateMultilineText($"{FAQ("如何运输海水? ")} 海水必须通过管道运输。磁铁工具可以用于海水")); }); //typeof(Quest_ProducePlastic), //typeof(Quest_ProduceLightMaterial), // 炼铝 const long difficulty_Quest_ProduceAluminum = 100; OnStartQuest.Add(typeof(Quest_ProduceAluminum), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = difficulty_Quest_ProduceAluminum; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(AluminiumIngot); }); OnTapQuest.Add(typeof(Quest_ProduceAluminum), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<MineOfAluminum>()} {Localization.Ins.Get<FactoryOfAluminiumWorking>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(AluminiumIngot), difficulty_Quest_ProduceAluminum)}")); }); // 液化石油气 const long difficulty_Quest_ProduceLPG = 100; OnStartQuest.Add(typeof(Quest_ProduceLPG), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = difficulty_Quest_ProduceLPG; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(LiquefiedPetroleumGas); }); OnTapQuest.Add(typeof(Quest_ProduceLPG), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<OilDriller>()} {Localization.Ins.Get<FactoryOfPetroleumRefining>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(LiquefiedPetroleumGas), difficulty_Quest_ProduceLPG)}")); items.Add(UIItem.CreateSeparator()); items.Add(UIItem.CreateMultilineText($"{FAQ("如何运输原油及其产品? ")} 液体必须通过管道运输。磁铁工具可以用于液体")); }); // 塑料 const long difficulty_Quest_ProducePlastic = 100; OnStartQuest.Add(typeof(Quest_ProducePlastic), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = difficulty_Quest_ProducePlastic; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(Plastic); }); OnTapQuest.Add(typeof(Quest_ProducePlastic), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<FactoryOfPlastic>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(Plastic), difficulty_Quest_ProducePlastic)}")); }); // 轻质材料 const long difficulty_Quest_ProduceLightMaterial = 100; OnStartQuest.Add(typeof(Quest_ProduceLightMaterial), () => { Globals.Ins.Values.GetOrCreate<QuestRequirement>().Max = difficulty_Quest_ProduceLightMaterial; Globals.Ins.Refs.GetOrCreate<QuestRequirement>().Type = typeof(LightMaterial); }); OnTapQuest.Add(typeof(Quest_ProduceLightMaterial), items => { items.Add(UIItem.CreateMultilineText($"已解锁 {Localization.Ins.Get<FactoryOfLightMaterial>()}")); items.Add(UIItem.CreateText($"目标:拥有{Localization.Ins.Val(typeof(LightMaterial), difficulty_Quest_ProduceLightMaterial)}")); }); } public static void QuestConfigNotProvidedThrowException(Type type) { // 在上面配置任务 throw new Exception($"没有配置任务内容{type}"); } } }
60.018657
313
0.636494
[ "MIT" ]
weatheringstudio/weatherin
Assets/Scripts/Core/MainQuest/MainQuestConfig.cs
34,452
C#
// Copyright (c) Matt Lacey Ltd. All rights reserved. // Licensed under the MIT license. [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1600:Elements should be documented", Justification = "Documentation not required for dev tooling")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("StyleCop.CSharp.DocumentationRules", "SA1601:Partial elements should be documented", Justification = "Documentation not required for dev tooling")]
83.166667
207
0.809619
[ "MIT" ]
DhiaaAlshamy/Rapid-XAML-Toolkit
VSIX/OptionsEmulator/GlobalSuppressions.cs
501
C#
using System; namespace VeritabaniProjesi.Models { public class ErrorViewModel { public string RequestId { get; set; } public bool ShowRequestId => !string.IsNullOrEmpty(RequestId); } }
18
70
0.675926
[ "MIT" ]
mehmeterenballi/webprogramlama-grup17-final
ViewModels/ErrorViewModel.cs
216
C#
using Android.App; namespace Debugging { public static class ProfilerExtensions { public static void Show(this Profiler profiler, Activity activity) { activity.StartActivity(typeof(ProfilerActivity)); } } }
17
68
0.755656
[ "MIT" ]
aloisdeniel/Profiler
Sources/Profiler.Droid/ProfilerExtensions.cs
223
C#
using Nager.Country.Currencies; namespace Nager.Country.CountryInfos { /// <summary> /// Madagascar /// </summary> public class MadagascarCountryInfo : ICountryInfo { ///<inheritdoc/> public string CommonName => "Madagascar"; ///<inheritdoc/> public string OfficialName => "Republic of Madagascar"; ///<inheritdoc/> public Alpha2Code Alpha2Code => Alpha2Code.MG; ///<inheritdoc/> public Alpha3Code Alpha3Code => Alpha3Code.MDG; ///<inheritdoc/> public int NumericCode => 450; ///<inheritdoc/> public string[] TLD => new [] { ".mg" }; ///<inheritdoc/> public Region Region => Region.Africa; ///<inheritdoc/> public SubRegion SubRegion => SubRegion.EasternAfrica; ///<inheritdoc/> public Alpha2Code[] BorderCountries => new Alpha2Code[] { }; ///<inheritdoc/> public ICurrency[] Currencies => new [] { new MgaCurrency() }; ///<inheritdoc/> public string[] CallingCodes => new [] { "261" }; } }
28.487179
70
0.563456
[ "MIT" ]
Tri125/Nager.Country
src/Nager.Country/CountryInfos/MadagascarCountryInfo.cs
1,111
C#
namespace PTDX.TypeDescription { public class TypeCategory { public TypeCategory(string name, string description = null) { Name = name; Description = description; } public string Name { get; } public string Description { get; } } }
20.666667
67
0.564516
[ "MIT" ]
PretenderX/PTDX.TypeDescription
src/PTDX.TypeDescription/TypeCategory.cs
312
C#
using Nager.Country.Currencies; namespace Nager.Country.CountryInfos { /// <summary> /// Jordan /// </summary> public class JordanCountryInfo : ICountryInfo { ///<inheritdoc/> public string CommonName => "Jordan"; ///<inheritdoc/> public string OfficialName => "Hashemite Kingdom of Jordan"; ///<inheritdoc/> public string NativeName => "الأردن"; ///<inheritdoc/> public Alpha2Code Alpha2Code => Alpha2Code.JO; ///<inheritdoc/> public Alpha3Code Alpha3Code => Alpha3Code.JOR; ///<inheritdoc/> public int NumericCode => 400; ///<inheritdoc/> public string[] TLD => new [] { ".jo", "الاردن." }; ///<inheritdoc/> public Region Region => Region.Asia; ///<inheritdoc/> public SubRegion SubRegion => SubRegion.WesternAsia; ///<inheritdoc/> public Alpha2Code[] BorderCountries => new Alpha2Code[] { Alpha2Code.IQ, Alpha2Code.IL, Alpha2Code.SA, Alpha2Code.SY, }; ///<inheritdoc/> public ICurrency[] Currencies => new [] { new JodCurrency() }; ///<inheritdoc/> public string[] CallingCodes => new [] { "962" }; } }
28.666667
70
0.547287
[ "MIT" ]
OpenBoxLab/Nager.Country
src/Nager.Country/CountryInfos/JordanCountryInfo.cs
1,302
C#
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Linq; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Diagnostics; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; namespace Adxstudio.Xrm.Cms.Replication { /// <summary> /// Replication of a Web Page (adx_webpage) /// </summary> public class WebPageReplication : CrmEntityReplication { /// <summary> /// WebPageReplication class initialization /// </summary> /// <param name="source">Web Page</param> /// <param name="context">Organization Service Context</param> public WebPageReplication(Entity source, OrganizationServiceContext context) : base(source, context, "adx_webpage") { } /// <summary> /// Entity Created Event /// </summary> public override void Created() { var source = Context.CreateQuery("adx_webpage").FirstOrDefault(w => w.GetAttributeValue<Guid>("adx_webpageid") == Source.Id); if (source == null) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Source entity is null."); return; } // Get the parent page, so we can find any subscriber pages of that page, and generate new children. var parentPage = source.GetRelatedEntity(Context, "adx_webpage_webpage", EntityRole.Referencing); // If there's no parent page, we'll currently do nothing. (Maybe create a root page?) if (parentPage == null) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Source entity has no parent page; ending replication."); return; } // Get the pages subscribed to the parent. var subscribedPages = parentPage.GetRelatedEntities(Context, "adx_webpage_masterwebpage", EntityRole.Referenced).ToList(); if (!subscribedPages.Any()) { ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Source entity parent has no subscribed pages; ending replication."); return; } var replicatedPages = subscribedPages.Select(subscribedPage => { var replicatedPage = source.Clone(false); replicatedPage.EntityState = null; replicatedPage.Id = Guid.Empty; replicatedPage.Attributes.Remove("adx_webpageid"); replicatedPage.SetAttributeValue("adx_websiteid", subscribedPage.GetAttributeValue("adx_websiteid")); replicatedPage.SetAttributeValue("adx_masterwebpageid", new EntityReference(Source.LogicalName, Source.Id)); replicatedPage.SetAttributeValue("adx_parentpageid", new EntityReference(Source.LogicalName, subscribedPage.Id)); var pageTemplate = GetMatchingPageTemplate(Source.GetAttributeValue<EntityReference>("adx_pagetemplateid"), subscribedPage.GetAttributeValue<EntityReference>("adx_websiteid")); if (pageTemplate != null) { replicatedPage.SetAttributeValue("adx_pagetemplateid", pageTemplate); } var publishingState = GetDefaultPublishingState(subscribedPage.GetAttributeValue<EntityReference>("adx_websiteid")); if (publishingState != null) { replicatedPage.SetAttributeValue("adx_publishingstateid", publishingState); } return replicatedPage; }); foreach (var page in replicatedPages) { Context.AddObject(page); } Context.SaveChanges(); //ExecuteWorkflowOnSourceAndSubscribers("Created"); } /// <summary> /// Entity Deleted Event /// </summary> public override void Deleted() { //ExecuteWorkflowOnSourceAndSubscribers("Deleted"); } /// <summary> /// Entity Updated Event /// </summary> public override void Updated() { //ExecuteWorkflowOnSourceAndSubscribers("Updated"); } protected void ExecuteWorkflowOnSourceAndSubscribers(string eventName) { ExecuteWorkflowOnSourceAndSubscribers("Web Page", eventName, "adx_webpage_masterwebpage", EntityRole.Referencing, "adx_webpageid"); } private EntityReference GetMatchingPageTemplate(EntityReference sourcePageTemplateReference, EntityReference website) { if (sourcePageTemplateReference == null || website == null) { return null; } var sourcePageTemplate = Context.CreateQuery("adx_pagetemplate").FirstOrDefault(p => p.GetAttributeValue<Guid?>("adx_pagetemplateid") == sourcePageTemplateReference.Id); if (sourcePageTemplate == null) { return null; } var sourcePageTemplateName = sourcePageTemplate.GetAttributeValue<string>("adx_name"); var targetPageTemplate = Context.CreateQuery("adx_pagetemplate").FirstOrDefault(p => p.GetAttributeValue<string>("adx_name") == sourcePageTemplateName && p.GetAttributeValue<EntityReference>("adx_websiteid") == website); return targetPageTemplate == null ? null : targetPageTemplate.ToEntityReference(); } } }
33.496454
223
0.739784
[ "MIT" ]
Adoxio/xRM-Portals-Community-Edition
Framework/Adxstudio.Xrm/Cms/Replication/WebPageReplication.cs
4,723
C#
#region License // Copyright (c) 2009, ClearCanvas Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of ClearCanvas Inc. nor the names of its contributors // may be used to endorse or promote products derived from this software without // specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, // OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE // GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY // OF SUCH DAMAGE. #endregion using System; using ClearCanvas.Common; using ClearCanvas.Desktop.Actions; namespace ClearCanvas.Desktop.Tools { /// <summary> /// Abstract base class providing a default implementation of <see cref="ITool"/>. /// </summary> /// <remarks> /// Tool classes may inherit this class, but inheriting /// from <see cref="Tool{TContextInterface}"/> is recommended. /// </remarks> public abstract class ToolBase : ITool { private IToolContext _context; private IActionSet _actions; /// <summary> /// Constructor. /// </summary> protected ToolBase() { } /// <summary> /// Provides an untyped reference to the context in which the tool is operating. /// </summary> /// <remarks> /// Attempting to access this property before <see cref="SetContext"/> /// has been called (e.g in the constructor of this tool) will return null. /// </remarks> protected IToolContext ContextBase { get { return _context; } } #region ITool members /// <summary> /// Called by the framework to set the tool context. /// </summary> public void SetContext(IToolContext context) { _context = context; } /// <summary> /// Called by the framework to allow the tool to initialize itself. /// </summary> /// <remarks> /// This method will be called after <see cref="SetContext"/> has been called, /// which guarantees that the tool will have access to its context when this method is called. /// </remarks> public virtual void Initialize() { // nothing to do } /// <summary> /// Gets the set of actions that act on this tool. /// </summary> /// <remarks> /// <see cref="ITool.Actions"/> mentions that this property should not be considered dynamic. /// This implementation assumes that the actions are <b>not</b> dynamic by lazily initializing /// the actions and storing them. If you wish to return actions dynamically, you must override /// this property. /// </remarks> public virtual IActionSet Actions { get { if (_actions == null) { _actions = new ActionSet(ActionAttributeProcessor.Process(this)); } return _actions; } } #endregion /// <summary> /// Disposes of this object; override this method to do any necessary cleanup. /// </summary> /// <param name="disposing">True if this object is being disposed, false if it is being finalized.</param> protected virtual void Dispose(bool disposing) { if (disposing) { _context = null; } } #region IDisposable Members /// <summary> /// Implementation of the <see cref="IDisposable"/> pattern. /// </summary> public void Dispose() { try { Dispose(true); GC.SuppressFinalize(this); } catch (Exception e) { // shouldn't throw anything from inside Dispose() Platform.Log(LogLevel.Error, e); } } #endregion } }
34.256757
109
0.613215
[ "Apache-2.0" ]
econmed/ImageServer20
Desktop/Tools/ToolBase.cs
5,072
C#
using System; namespace FootballTournament { internal class Program { static void Main(string[] args) { string footballTeamsName = Console.ReadLine(); int totalPlayedGames = int.Parse(Console.ReadLine()); if (totalPlayedGames == 0) { Console.WriteLine($"{footballTeamsName} hasn't played any games during this season."); return; } int totalPoints = 0; int wins = 0; int draws = 0; int loses = 0; for (int game = 1; game <= totalPlayedGames; game++) { char result = char.Parse(Console.ReadLine()); switch (result) { case 'W': totalPoints += 3; wins++; break; case 'D': totalPoints++; draws++; break; case 'L': loses++; break; } } Console.WriteLine($"{footballTeamsName} has won {totalPoints} points during this season."); Console.WriteLine("Total stats:"); Console.WriteLine($"## W: {wins}"); Console.WriteLine($"## D: {draws}"); Console.WriteLine($"## L: {loses}"); Console.WriteLine($"Win rate: {(wins * 1.00 / totalPlayedGames * 100):F2}%"); } } }
30.509804
103
0.422879
[ "MIT" ]
Ivanazzz/SoftUni-Software-Engineering
CSharp-Programming-Basics/Exams/ExamPrep5/FootballTournament/Program.cs
1,558
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime; using System.Threading.Tasks; namespace MVCTestApplication.Models { public class TodoItem // POCO Plan old c# object { public Guid Id { get; set; } public bool IsDone { get; set; } public string Title { get; set; } public DateTimeOffset? DueAt { get; set; } public List<TodoItem> MyProperty { get; set; } } }
21.666667
54
0.650549
[ "MIT" ]
raneem87/MVC-Template
MVCTestApplication/Models/TodoItem.cs
457
C#
namespace ClassLib039 { public class Class024 { public static string Property => "ClassLib039"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib039/Class024.cs
120
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using Ascon.Pilot.Common; using Ascon.Pilot.DataClasses; using Lucene.Net.QueryParsers.Classic; using Pilot.Web.Model.Search.QueryBuilder; using Pilot.Web.Model.Search.QueryBuilder.Fields; using Pilot.Web.Model.Search.QueryBuilder.SearchTerms; using Pilot.Web.Model.Search.QueryBuilder.Tools; using Pilot.Web.Model.Search.Tokens; namespace Pilot.Web.Model.Search { class UserStateSearchItem { public INUserState State { get; } public string Tooltip { get; set; } public UserStateSearchItem(INUserState state) { State = state; } } abstract class SearchExpressionContextBase : ISearchExpressionContext { protected readonly IServerApiService _context; protected SearchExpressionContextBase(IServerApiService context) { _context = context; } public static string EscapeSearchPhrase(string value) { var allEscaped = ((value.Length - value.TrimEnd('\\').Length) % 2) == 0; return $"\"{(allEscaped ? value : value + "\\")}\""; } public static string EscapeKeyword(string value) { return QueryParserBase.Escape(value).Replace("\\*", "*").Replace("\\?", "?"); } public virtual bool IsInvariantCulture => false; public virtual IEnumerable<IPresetItem> GetPresetItems(IToken target) { var today = DateTime.Today; var weekStart = DatesRangeLimits.GetStartOfTheWeek(today); if (target is DateTextArgumentToken) return new List<IPresetItem> { new PresetItem(DateTextArgumentToken.Today, "today", today.ToString(DateRangeToken.FullDateStringFormat)), new PresetItem(DateTextArgumentToken.Yesterday, "yesterday", today.AddDays(-1).ToString(DateRangeToken.FullDateStringFormat)), new PresetItem(DateTextArgumentToken.ThisWeek, "this week", $"{weekStart.ToString(DateRangeToken.FullDateStringFormat)}{SearchTokenAliases.DateRangeTokenAlias}{weekStart.AddDays(7).ToString(DateRangeToken.FullDateStringFormat)}"), new PresetItem(DateTextArgumentToken.LastWeek, "last week", $"{weekStart.AddDays(-14).ToString(DateRangeToken.FullDateStringFormat)}{SearchTokenAliases.DateRangeTokenAlias}{weekStart.AddDays(-7).ToString(DateRangeToken.FullDateStringFormat)}"), new PresetItem(DateTextArgumentToken.ThisMonth, "this month", today.ToString(DateRangeToken.ShortDateStringFormat)), new PresetItem(DateTextArgumentToken.LastMonth, "last month", today.AddMonths(-1).ToString(DateRangeToken.ShortDateStringFormat)), new PresetItem(DateTextArgumentToken.ThisYear, "this year", today.ToString("yyyy")), new PresetItem(DateTextArgumentToken.LastYear, "last year", today.AddYears(-1).ToString("yyyy")) }; if (target is YearToken) { var targetIsEmpty = string.IsNullOrEmpty(((YearToken)target).Value); var year = DateTime.Today.Year; var years = new List<IPresetItem> { new PresetItem(year.ToString(), year.ToString(), targetIsEmpty && !((YearToken)target).GetIsTopSubgroup() ? "specify custom date or range" : "specify a year") }; if (targetIsEmpty) return years; for (var delta = 1; delta < 16; delta++) { var prevYear = (year - delta).ToString(); years.Add(new PresetItem(prevYear, prevYear)); } return years; } if (target is MonthToken) { var months = new List<IPresetItem>(); for (var month = 0; month < 12; month++) { var monthString = (month + 1).ToString("D2"); months.Add(new PresetItem(monthString, monthString)); } return months; } if (target is DayToken) { var days = new List<IPresetItem>(); for (var day = 0; day < 31; day++) { var monthString = (day + 1).ToString("D2"); days.Add(new PresetItem(monthString, monthString)); } return days; } if (target is NumberAttributeValueToken) return new List<IPresetItem> { new PresetItem(string.Empty, string.Empty, "enter numeric value or range"), }; if (target is OrgUnitAttributeValueToken) return GetOrgUnitAttributePresetItems(); return new List<IPresetItem>(); } protected IEnumerable<IPresetItem> GetOrgUnitAttributePresetItems() { return GetPersonsWithUniqueDisplayNames().Select(x => new PresetItem(x.Value.Id.ToString(), x.Key, x.Value.IsDeleted ? "Deleted person" : null, isDeleted: x.Value.IsDeleted)).Where(x => !string.IsNullOrEmpty(x.DisplayValue)); } public virtual IList<IToken> ValidateNextTokens(ISearchExpression expression, IToken token, IList<IToken> nextTokens) { return nextTokens; } class NumAttributeRange { public string AttrName { get; } public bool IsFloat { get; } public double From { get; } public double? To { get; } public ITokenContext Context { get; } public NumAttributeRange(string attrName, bool isFloat, double from, double? to, ITokenContext context) { AttrName = attrName; IsFloat = isFloat; From = from; To = to; Context = context; } } protected virtual void AddIsSetSearch(IQueryBuilder queryBuilder, string attributeName, IField field, TermOccur termOccur) { var term = field.Exists(); queryBuilder.Add(term, termOccur); } protected void AddAttributesSearch(ISearchExpression expression, IQueryBuilder attributesQueryBuilder) { if (attributesQueryBuilder == null) return; var attributeIsSetTokens = expression.Tokens.OfType<AttributeIsSetToken>().ToList(); foreach (var group in attributeIsSetTokens.GroupByAttributeAndOccur()) { var token = group.First(); var field = GetAttributeField(token, group.Key.AttributeName); AddIsSetSearch(attributesQueryBuilder, group.Key.AttributeName, field, group.Key.Occur); } var stringAttributeValueTokens = expression.Tokens.OfType<StringAttributeValueToken>().ToList(); foreach (var group in stringAttributeValueTokens.GroupByAttributeAndOccur()) { var attributeName = group.Key.AttributeName; var field = AttributeFields.String(attributeName); var values = group.Select(token => EscapeStringValue(token.Value)); attributesQueryBuilder.AddAnyOf(values.Select(x => field.Be(x)).ToArray(), group.Key.Occur); } var orgUnitValueTokens = expression.Tokens.OfType<OrgUnitAttributeValueToken>().ToList(); foreach (var group in orgUnitValueTokens.GroupByAttributeAndOccur()) { var attributeName = group.Key.AttributeName; var field = AttributeFields.OrgUnit(attributeName); var positions = group .Select(token => token is OrgUnitMeArgumentToken ? _context.GetCurrentPerson() : _context.GetPerson(Convert.ToInt32(token.Id))) .SelectMany(x => x.Positions) .Distinct() .ToArray(); attributesQueryBuilder.Add(field.BeAnyOf(positions), group.Key.Occur); } var stateAttributeValueTokens = expression.Tokens.OfType<UserStateAttributeValueToken>().ToList(); foreach (var group in stateAttributeValueTokens.GroupByAttributeAndOccur()) { var field = AttributeFields.State(group.Key.AttributeName); attributesQueryBuilder.Add(field.BeAnyOf(group.Select(x => Guid.Parse(x.Id)).Distinct().ToArray()), group.Key.Occur); } var dateAttributesNames = expression.Tokens.OfType<DateAttributeNameToken>(); foreach (var dateAttributeNameToken in dateAttributesNames) { var dateFieldName = dateAttributeNameToken.Data; var dateField = AttributeFields.DateTime(dateFieldName); AddDateSearch( token => token.Context[TokenBase.GroupParentKey].Value is DateAttributeNameToken && token.Context[nameof(AttributeNameTokenBase)].Value as string == dateFieldName, datesRange => dateField.BeInRange(datesRange.FromUtc, datesRange.ToUtc), null, expression, attributesQueryBuilder, null); } var numberAttributeTokens = expression.Tokens.OfType<NumberAttributeValueToken>().ToList(); var fromNumAttributesTokens = numberAttributeTokens.Where(x => (bool?)x.Context[RangeToken.IsRangeTopKey].Value != true).ToList(); var toNumAttributesToknes = numberAttributeTokens.Where(x => (bool?)x.Context[RangeToken.IsRangeTopKey].Value == true).ToList(); var numAttributesRanges = new List<NumAttributeRange>(); foreach (var fromRangeToken in fromNumAttributesTokens) { var attributeName = fromRangeToken.Context[nameof(AttributeNameTokenBase)].Value as string; var fromValue = double.Parse(fromRangeToken.Value, CultureInfo.InvariantCulture); var isFloat = fromRangeToken.Context[nameof(FloatNumberAttributeNameToken)].Value != null; if (fromRangeToken.Context[TokenBase.GroupParentKey].Value is NumberAttributeGreaterToken) { numAttributesRanges.Add(new NumAttributeRange(attributeName, isFloat, fromValue, double.PositiveInfinity, fromRangeToken.Context)); continue; } if (fromRangeToken.Context[TokenBase.GroupParentKey].Value is NumberAttributeLessToken) { numAttributesRanges.Add(new NumAttributeRange(attributeName, isFloat, double.NegativeInfinity, fromValue, fromRangeToken.Context)); continue; } var groupParent = fromRangeToken.Context[TokenBase.GroupParentKey].Value; var toRangeToken = toNumAttributesToknes.FirstOrDefault(x => ReferenceEquals(groupParent, x.Context[TokenBase.GroupParentKey].Value)); var toValue = toRangeToken != null ? (double?)double.Parse(toRangeToken.Value, CultureInfo.InvariantCulture) : null; numAttributesRanges.Add(new NumAttributeRange(attributeName, isFloat, fromValue, toValue, fromRangeToken.Context)); } foreach (var range in numAttributesRanges) { var doubleFiled = AttributeFields.Double(range.AttrName); var longField = AttributeFields.Integer(range.AttrName); var fromDoubleValue = range.From; var fromLongValue = double.IsNegativeInfinity(fromDoubleValue) ? long.MinValue : Convert.ToInt64(Math.Floor(fromDoubleValue)); if (range.To == null) { var searchTerm = range.IsFloat ? doubleFiled.Be(fromDoubleValue) : longField.Be(fromLongValue); attributesQueryBuilder.Add(searchTerm, range.Context.GetTermOccur()); } else { var toDoubleValue = (double)range.To; var toLongValue = double.IsPositiveInfinity(toDoubleValue) ? long.MaxValue : Convert.ToInt64(Math.Floor(toDoubleValue)); var searchTerm = range.IsFloat ? doubleFiled.BeInRange(fromDoubleValue, toDoubleValue) : longField.BeInRange(fromLongValue, toLongValue); attributesQueryBuilder.Add(searchTerm, range.Context.GetTermOccur()); } } } internal static IField GetAttributeField(AttributeIsSetToken token, string attributeName) { if (token is StringAttributeIsSetToken) return AttributeFields.String(attributeName); if (token is DateTimeAttributeIsSetToken) return AttributeFields.DateTime(attributeName); if (token is OrgUnitAttributeIsSetToken) return AttributeFields.OrgUnit(attributeName); if (token is UserStateAttributeIsSetToken) return AttributeFields.State(attributeName); if (token is IntegerNumberAttributeIsSetToken) return AttributeFields.Integer(attributeName); if (token is FloatNumberAttributeIsSetToken) return AttributeFields.Double(attributeName); throw new NotSupportedException($"{token.GetType().Name} is not supported"); } protected void AddDateSearch( Func<TokenBase, bool> tokenFilter, Func<DatesRangeLimits, ISearchTerm> toObjectSearchTerm, Func<DatesRangeLimits, ISearchTerm> toFileSearchTerm, ISearchExpression expression, IQueryBuilder attributesQueryBuilder, IQueryBuilder filesQueryBuilder) { var dateRangeTokens = expression.Tokens.OfType<TokenBase>().Where(x => tokenFilter(x)).ToList(); var dateRangeGroups = dateRangeTokens.GroupBy(x => x.Context[RangeToken.RangeGroupKey].Value).Where(g => g.Key != null); var dateRanges = new List<DatesRangeLimits>(); foreach (var group in dateRangeGroups) { var dateTextPresetToken = (DateTextArgumentToken)group.FirstOrDefault(x => x is DateTextArgumentToken); if (dateTextPresetToken != null) { var presetRange = DatesRangeLimits.GetRangeLimits(dateTextPresetToken); dateRanges.Add(presetRange); continue; } var groupTail = group.Last(); var from = groupTail.Context[RangeToken.FromValueKey].Value; var to = groupTail.Context[RangeToken.ToValueKey].Value; if (from == null || to == null) continue; var range = new DatesRangeLimits((DateTime)from, (DateTime)to); if (groupTail.Context[RangeToken.RangeKindKey].Value is DateAttributeGreaterToken) range = DatesRangeLimits.GreaterThanRange(range); if (groupTail.Context[RangeToken.RangeKindKey].Value is DateAttributeLessToken) range = DatesRangeLimits.LessThanRange(range); dateRanges.Add(range); } if (!dateRanges.Any()) return; var context = dateRangeTokens.First().Context; attributesQueryBuilder?.AddAnyOf(dateRanges.Select(toObjectSearchTerm).ToArray(), context.GetTermOccur()); filesQueryBuilder?.AddAnyOf(dateRanges.Select(toFileSearchTerm).ToArray(), context.GetTermOccur()); } protected void AddIntFieldSearch<TTokenType>(Func<int[], int[]> sourceValuesToValues, Action<IQueryBuilder, int[], TermOccur> valuesToBuilder, ISearchExpression expression, IQueryBuilder queryBuilder) where TTokenType : ArgumentToken { if (queryBuilder == null) return; var tokens = expression.Tokens.OfType<TTokenType>().ToList(); foreach (var tokenGroup in tokens.GroupBy(x => x.Context.GetTermOccur())) { var sourceValues = tokenGroup .Select(token => int.TryParse(token.Id, out var intValue) ? (int?)intValue : null) .Where(value => value != null) .OfType<int>() .ToArray(); var values = sourceValuesToValues(sourceValues); if (values.Any()) valuesToBuilder(queryBuilder, values, tokenGroup.Key); } } protected void AddEnumFieldSearch<TTokenType, TEnumType>(Func<TEnumType[], ISearchTerm> valuesToTerm, ISearchExpression expression, IQueryBuilder queryBuilder) where TTokenType : ArgumentToken where TEnumType : struct, IConvertible { if (queryBuilder == null) return; var tokenGroups = expression.Tokens .OfType<TTokenType>() .GroupBy(x => x.Context.GetTermOccur()); foreach (var tokenGroup in tokenGroups) { var values = tokenGroup .Select(token => Enum.TryParse(token.Id, out TEnumType enumValue) ? (TEnumType?)enumValue : null) .Where(value => value != null) .OfType<TEnumType>() .ToArray(); if (values.Any()) queryBuilder.Add(valuesToTerm(values), tokenGroup.Key); } } protected List<PresetItem> GetUserStatesWithUniqueDisplayNames(UserStateAttributeValueToken target) { var allUserState = _context.GetUserStates().Select(x => new UserStateSearchItem(x)).ToList(); var suggestibleUserStates = GetValidUserStatesList(target); var userStatesWithUniqueDisplayNames = GetObjectsWithUniqueNames(allUserState, x => x.State.Title, x => x.State.Name); var resultUserStates = userStatesWithUniqueDisplayNames.Where(x => !string.IsNullOrEmpty(x.Key)) .Select(x => { var suggestibleUserState = suggestibleUserStates.FirstOrDefault(ss => ss.State.Name.Equals(x.Value.State.Name, StringComparison.OrdinalIgnoreCase)); var presetItem = new PresetItem( id: x.Value.State.Id.ToString(), displayValue: x.Key, hint: x.Value.State.IsDeleted ? "Deleted state" : null, isVisible: suggestibleUserState != null, isDeleted: x.Value.State.IsDeleted) { Tooltip = suggestibleUserState?.Tooltip }; return presetItem; }) .ToList(); return resultUserStates; } private List<UserStateSearchItem> GetValidUserStatesList(UserStateAttributeValueToken target) { var specifiedTypesNames = target.Context[nameof(TypeArgumentToken)].Value as List<string> ?? new List<string>(); specifiedTypesNames = specifiedTypesNames.Where(x => !string.IsNullOrEmpty(x)).ToList(); var types = _context.GetTypes() .OrderBy(x => x.Value.IsDeleted) .ThenBy(x => x.Value.Sort) .Where(x => IsUserType(x.Value) && (!specifiedTypesNames.Any() || specifiedTypesNames.Contains(x.Value.Id.ToString()))) .ToList(); var specifiedAttributeName = target.Context[nameof(AttributeNameTokenBase)].Value as string; var attributeTypePairs = types .Select(t => new Tuple<INAttribute, INType>(t.Value.Attributes.FirstOrDefault(a => a.Name == specifiedAttributeName), t.Value)) .Where(pair => pair.Item1 != null) .ToList(); var validUserStates = BuildItemsIntersection( sourceElements: attributeTypePairs, intersect: specifiedTypesNames.Count > 1, buildItemsForElement: attributeTypePair => { var stateMachineId = attributeTypePair.Item1.ParsedConfiguration().StateMachineId; if (stateMachineId == null) return new Dictionary<string, UserStateSearchItem>(); var stateMachine = _context.GetStateMachine((Guid)stateMachineId); var presetItems = stateMachine.StateTransitions .Select(state => _context.GetUserState(state.Key)) .Where(state => state != null) .ToDictionary(state => state.Name, state => new UserStateSearchItem(state) { Tooltip = attributeTypePair.Item2.Title }); return presetItems; }, onItemDuplicated: (presetItem, attributeTypePair) => { presetItem.Tooltip += GetTooltipEntryForType(attributeTypePair.Item2); }); return validUserStates; } protected Dictionary<string, INPerson> GetPersonsWithUniqueDisplayNames() { var people = _context.GetPeople(); var alivePeople = people.Where(x => !x.Value.IsDeleted).OrderBy(x => x.Value.ActualName()); var deletedPeople = people.Where(x => x.Value.IsDeleted).OrderBy(x => x.Value.ActualName()); var personList = alivePeople.ToList(); personList.AddRange(deletedPeople); return GetObjectsWithUniqueNames(personList.Select(x => x.Value), x => x.DisplayName, x => x.Login); } protected static Dictionary<string, T> GetObjectsWithUniqueNames<T>(IEnumerable<T> objects, Func<T, string> getDisplayName, Func<T, string> getUniqueId) { var dictionaryByName = new Dictionary<string, T>(); foreach (var obj in objects) { var displayName = getDisplayName(obj); var uniqueId = getUniqueId(obj); var objectKey = !string.IsNullOrWhiteSpace(displayName) && !dictionaryByName.ContainsKey(displayName) ? displayName : string.IsNullOrWhiteSpace(displayName) ? uniqueId : $"{displayName} ({uniqueId})".Trim(); var index = 2; while (dictionaryByName.ContainsKey(objectKey)) { objectKey = index == 2 ? $"{objectKey} ({index})" : objectKey.Replace($"({index - 1})", $"({index})"); index++; } dictionaryByName.Add(objectKey, obj); } return dictionaryByName; } protected IEnumerable<INType> GetTypesFromExpression<TTokenType>( ISearchExpression expression, IReadOnlyList<INType> supportedTypes, out bool isFiltered) where TTokenType : TypeArgumentToken { isFiltered = false; var typeIds = new HashSet<int>(supportedTypes.Select(x => x.Id)); var typeTokens = expression.Tokens.OfType<TTokenType>().ToList(); if (typeTokens.Any()) { var mustTypes = GetTypesFromTokens(typeTokens.Where(x => x.Context.GetTermOccur() == TermOccur.Must)); typeIds.IntersectWith(mustTypes.Select(x => x.Id)); var mustNotTypes = GetTypesFromTokens(typeTokens.Where(x => x.Context.GetTermOccur() == TermOccur.MustNot)); typeIds.ExceptWith(mustNotTypes.Select(x => x.Id)); isFiltered = true; } var attributeTokens = expression.Tokens.OfType<AttributeNameTokenBase>().ToList(); if (attributeTokens.Any()) { var attributeNames = new HashSet<string>(attributeTokens.Select(x => x.Value).Distinct()); var attributeTypes = supportedTypes .Where(t => t.Attributes.Any(a => attributeNames.Contains(a.Title))) .Select(x => x.Id); typeIds.IntersectWith(attributeTypes); isFiltered = true; } return supportedTypes.Where(t => typeIds.Contains(t.Id)); } protected List<INType> GetTypesFromTokens(IEnumerable<TypeArgumentToken> typeArguments) { var ids = new List<INType>(); var types = GetTypesWithUniqueDisplayNames(); foreach (var typeToken in typeArguments) { if (types.TryGetValue(typeToken.Value, out var type)) ids.Add(type); else throw new ArgumentException($"type &apos;{typeToken.Value}&apos; does not exist"); } return ids; } protected Dictionary<string, INType> GetTypesWithUniqueDisplayNames() { var types = GetSearchBrowsableTypes(); var aliveTypes = types.Where(t => !t.IsDeleted).OrderBy(t => t.Title); var deletedTypes = types.Where(t => t.IsDeleted).OrderBy(t => t.Title); var typeList = aliveTypes.ToList(); typeList.AddRange(deletedTypes); return GetObjectsWithUniqueNames(typeList.Select(t => t), x => x.Title, x => x.Name); } protected List<PresetItem> GetValidAttributesList(AttributeNameTokenBase target) { var specifiedTypesNames = target.Context[nameof(TypeArgumentToken)].Value as List<string> ?? new List<string>(); specifiedTypesNames = specifiedTypesNames.Where(x => !string.IsNullOrEmpty(x)).ToList(); var types = GetSearchBrowsableTypes() .OrderBy(x => x.IsDeleted) .ThenBy(x => x.Sort) .Where(x => IsUserType(x) && (!specifiedTypesNames.Any() || specifiedTypesNames.Contains(x.Id.ToString()))) .ToList(); var complimentaryTypes = GetComplimentaryAttrTypes(target); var validAttributesList = BuildItemsIntersection( sourceElements: types, intersect: specifiedTypesNames.Count > 1, buildItemsForElement: type => { var currentTypePresetItems = new Dictionary<string, PresetItem>(); var typeAttrs = type.Attributes.Where(x => complimentaryTypes.Contains(x.Type)).OrderBy(x => x.DisplaySortOrder); foreach (var nAttribute in typeAttrs) { var key = $"{nAttribute.Name}\\{nAttribute.Title}\\{AttrTypeToString(nAttribute.Type)}"; var hint = AttrTypeToString(nAttribute.Type); var tooltip = specifiedTypesNames.Count == 1 ? null : GetTooltipEntryForType(type); var presetItem = new PresetItem(nAttribute.Title, nAttribute.Title, nAttribute.Name, hint, true, type.IsDeleted) { Tooltip = tooltip != null ? $"Belongs to following types: {tooltip}" : null, Sort = nAttribute.DisplaySortOrder + type.Sort * 100 + (type.IsDeleted ? 10000 : 0) }; currentTypePresetItems.Add(key, presetItem); } return currentTypePresetItems; }, onItemDuplicated: (presetItem, type) => { presetItem.Tooltip += GetTooltipEntryForType(type); }); return validAttributesList; } protected virtual List<INType> GetSearchBrowsableTypes() { return _context.GetTypes().Values.Where(x => IsUserType(x)).ToList(); } protected string EscapeStringValue(string value) { if (string.IsNullOrEmpty(value)) return value; value = value.Length > 1 && value[0] == '"' ? EscapeSearchPhrase(value.Replace("\"", string.Empty)) : EscapeKeyword(value); return value; } enum ListIntersectionMode { Disabled, NextIteration, ThisIteration } protected List<TOut> BuildItemsIntersection<TIn, TOut>(List<TIn> sourceElements, bool intersect, Func<TIn, Dictionary<string, TOut>> buildItemsForElement, Action<TOut, TIn> onItemDuplicated) { var resultItemsIntersection = new Dictionary<string, TOut>(); var reduceToIntersection = intersect ? ListIntersectionMode.NextIteration : ListIntersectionMode.Disabled; foreach (var element in sourceElements) { var presetItemsForCurrentElement = buildItemsForElement(element); if (reduceToIntersection == ListIntersectionMode.ThisIteration) { var intersection = resultItemsIntersection.Keys.Intersect(presetItemsForCurrentElement.Keys).ToList(); foreach (var key in resultItemsIntersection.Keys.ToList()) { if (intersection.Contains(key)) onItemDuplicated(resultItemsIntersection[key], element); else resultItemsIntersection.Remove(key); } } else { foreach (var key in presetItemsForCurrentElement.Keys) { if (resultItemsIntersection.ContainsKey(key)) onItemDuplicated(resultItemsIntersection[key], element); else resultItemsIntersection.Add(key, presetItemsForCurrentElement[key]); } } if (reduceToIntersection == ListIntersectionMode.NextIteration) reduceToIntersection = ListIntersectionMode.ThisIteration; } return resultItemsIntersection.Values.ToList(); } protected string GetTooltipEntryForType(INType type) { return Environment.NewLine + type.Title + (type.IsDeleted ? " - " + "Deleted type" : string.Empty); } private List<MAttrType> GetComplimentaryAttrTypes(AttributeNameTokenBase token) { if (token is StringAttributeNameToken) return new List<MAttrType> { MAttrType.String, MAttrType.Numerator }; if (token is DateAttributeNameToken) return new List<MAttrType> { MAttrType.DateTime }; if (token is FloatNumberAttributeNameToken) return new List<MAttrType> { MAttrType.Double, MAttrType.Decimal }; if (token is IntegerNumberAttributeNameToken) return new List<MAttrType> { MAttrType.Integer }; if (token is UserStateAttributeNameToken) return new List<MAttrType> { MAttrType.UserState }; if (token is OrgUnitAttributeNameToken) return new List<MAttrType> { MAttrType.OrgUnit }; return new List<MAttrType>(); } private string AttrTypeToString(MAttrType type) { switch (type) { case MAttrType.String: return "string"; case MAttrType.Numerator: return "number"; case MAttrType.Integer: return "number"; case MAttrType.Decimal: return "number"; case MAttrType.Double: return "number"; case MAttrType.DateTime: return "date"; case MAttrType.UserState: return "state"; case MAttrType.OrgUnit: return "orgunit"; } return string.Empty; } protected bool IsUserType(INType type) { return !type.IsService && type.Kind == TypeKind.User; } public ISearchExpression ToLocalizedExpression(string invariantExpressionString, ISearchExpressionFactory factory) { var expression = factory.Parse(invariantExpressionString, InvariantCultureContext); return expression; } protected abstract ISearchExpressionContext InvariantCultureContext { get; } public string ToInvariantExpressionString(ISearchExpression expression) { var sb = new StringBuilder(); foreach (var token in expression.Tokens) { var keywordToken = token as IKeywordToken; if (keywordToken != null) { sb.Append(keywordToken.SerializationAlias); continue; } var argumentToken = token as IArgumentToken; if (argumentToken != null) { sb.Append(argumentToken.Id ?? argumentToken.Value); continue; } throw new InvalidOperationException("unknown token class"); } return sb.ToString(); } } }
44.58988
260
0.586198
[ "MIT" ]
Magicianred/Pilot.Web
Pilot.Web/Model/Search/SearchExpressionContextBase.cs
33,489
C#
/* * Erstellt mit SharpDevelop. * Benutzer: dos * Datum: 10.08.2007 * Zeit: 21:19 * * Sie können diese Vorlage unter Extras > Optionen > Codeerstellung > Standardheader ändern. */ using System; namespace StandardTemplates { /// <summary> /// Description of Dummy. /// </summary> public class Dummy { public Dummy() { } } }
14.416667
93
0.650289
[ "BSD-3-Clause" ]
cafephin/mygeneration
src/templates/Dummy.cs
350
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Projeto.DAL.DataContext { public class Context { protected SqlConnection con; protected SqlCommand cmd; protected SqlDataReader dr; protected SqlTransaction tr; /// <summary> /// Método para abrir uma conexão com o banco de dadoss /// </summary> protected void OpenConnection() { con = new SqlConnection(ConfigurationManager.ConnectionStrings["DataBase"].ConnectionString); con.Open(); } /// <summary> /// Método para fechar a conexão com o banco de dadoss /// </summary> protected void CloseConnection() { con.Close(); } } }
24.694444
105
0.616423
[ "MIT" ]
arkanael/ASPNET-MVC-02
ProjetoMVC/Projeto.DAL/DataContext/Context.cs
895
C#
// ================================================================================================================================= // Copyright (c) RapidField LLC. Licensed under the MIT License. See LICENSE.txt in the project root for license information. // ================================================================================================================================= using RapidField.SolidInstruments.Core; using RapidField.SolidInstruments.Core.ArgumentValidation; using RapidField.SolidInstruments.Core.Extensions; using System; using System.Diagnostics; using System.Runtime.Serialization; namespace RapidField.SolidInstruments.Messaging { /// <summary> /// Represents a message that emits a result when processed. /// </summary> /// <remarks> /// <see cref="Message{TResult}" /> is the default implementation of <see cref="IMessage{TResult}" />. /// </remarks> /// <typeparam name="TResult"> /// The type of the result that is produced by handling the message. /// </typeparam> [DataContract] public abstract class Message<TResult> : Message, IMessage<TResult> { /// <summary> /// Initializes a new instance of the <see cref="Message{TResult}" /> class. /// </summary> protected Message() : base() { return; } /// <summary> /// Initializes a new instance of the <see cref="Message{TResult}" /> class. /// </summary> /// <param name="correlationIdentifier"> /// A unique identifier that is assigned to related messages. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="correlationIdentifier" /> is equal to <see cref="Guid.Empty" />. /// </exception> protected Message(Guid correlationIdentifier) : base(correlationIdentifier) { return; } /// <summary> /// Initializes a new instance of the <see cref="Message{TResult}" /> class. /// </summary> /// <param name="correlationIdentifier"> /// A unique identifier that is assigned to related messages. /// </param> /// <param name="identifier"> /// A unique identifier for the message. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="correlationIdentifier" /> is equal to <see cref="Guid.Empty" /> -or- <paramref name="identifier" /> is /// equal to <see cref="Guid.Empty" />. /// </exception> protected Message(Guid correlationIdentifier, Guid identifier) : base(correlationIdentifier, identifier) { return; } /// <summary> /// Gets the type of the result that is produced by handling the message. /// </summary> [IgnoreDataMember] public sealed override Type ResultType => ResultTypeReference; /// <summary> /// Represents the type of the result that is produced by handling the message. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static readonly Type ResultTypeReference = typeof(TResult); } /// <summary> /// Represents a message. /// </summary> /// <remarks> /// <see cref="Message" /> is the default implementation of <see cref="IMessage" />. /// </remarks> [DataContract] [KnownType(typeof(MessageProcessingInformation))] public abstract class Message : IMessage { /// <summary> /// Initializes a new instance of the <see cref="Message" /> class. /// </summary> protected Message() { CorrelationIdentifierField = null; IdentifierField = null; ProcessingInformationField = null; } /// <summary> /// Initializes a new instance of the <see cref="Message" /> class. /// </summary> /// <param name="correlationIdentifier"> /// A unique identifier that is assigned to related messages. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="correlationIdentifier" /> is equal to <see cref="Guid.Empty" />. /// </exception> protected Message(Guid correlationIdentifier) { CorrelationIdentifierField = correlationIdentifier.RejectIf().IsEqualToValue(Guid.Empty, nameof(correlationIdentifier)); IdentifierField = null; ProcessingInformationField = null; } /// <summary> /// Initializes a new instance of the <see cref="Message" /> class. /// </summary> /// <param name="correlationIdentifier"> /// A unique identifier that is assigned to related messages. /// </param> /// <param name="identifier"> /// A unique identifier for the message. /// </param> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="correlationIdentifier" /> is equal to <see cref="Guid.Empty" /> -or- <paramref name="identifier" /> is /// equal to <see cref="Guid.Empty" />. /// </exception> protected Message(Guid correlationIdentifier, Guid identifier) { CorrelationIdentifierField = correlationIdentifier.RejectIf().IsEqualToValue(Guid.Empty, nameof(correlationIdentifier)); IdentifierField = identifier.RejectIf().IsEqualToValue(Guid.Empty, nameof(identifier)); ProcessingInformationField = null; } /// <summary> /// Converts the value of the current <see cref="Message" /> to its equivalent string representation. /// </summary> /// <returns> /// A string representation of the current <see cref="Message" />. /// </returns> public override String ToString() => $"{GetType().Name} | {Identifier.ToSerializedString()}"; /// <summary> /// Gets or sets a unique identifier that is assigned to related messages. /// </summary> [DataMember] public Guid CorrelationIdentifier { get { if (CorrelationIdentifierField.HasValue == false) { CorrelationIdentifierField = Guid.NewGuid(); } return CorrelationIdentifierField.Value; } set => CorrelationIdentifierField = value; } /// <summary> /// Gets or sets a unique identifier for the message. /// </summary> [DataMember] public Guid Identifier { get { if (IdentifierField.HasValue == false) { IdentifierField = Guid.NewGuid(); } return IdentifierField.Value; } set => IdentifierField = value; } /// <summary> /// Gets or sets instructions and contextual information relating to processing for the current <see cref="Message" />. /// </summary> [DataMember] public IMessageProcessingInformation ProcessingInformation { get { if (ProcessingInformationField is null) { ProcessingInformationField = new MessageProcessingInformation(); } return ProcessingInformationField; } set => ProcessingInformationField = value; } /// <summary> /// Gets the type of the result that is produced by processing the message. /// </summary> [IgnoreDataMember] public virtual Type ResultType => Nix.Type; /// <summary> /// Represents the entity type that is used for transmitting and listening for request messages. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal static MessagingEntityType RequestEntityType = MessagingEntityType.Queue; /// <summary> /// Represents the entity type that is used for transmitting and listening for response messages. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] internal static MessagingEntityType ResponseEntityType = MessagingEntityType.Topic; /// <summary> /// Represents a unique identifier that is assigned to related messages. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] [IgnoreDataMember] private Guid? CorrelationIdentifierField; /// <summary> /// Represents a unique identifier for the message. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] [IgnoreDataMember] private Guid? IdentifierField; /// <summary> /// Represents instructions and contextual information relating to processing for the current <see cref="Message" />. /// </summary> [DebuggerBrowsable(DebuggerBrowsableState.Never)] [IgnoreDataMember] private IMessageProcessingInformation ProcessingInformationField; } }
38.610879
133
0.577807
[ "MIT" ]
RapidField/solid-instruments
src/RapidField.SolidInstruments.Messaging/Message.cs
9,230
C#
namespace uTinyRipper.Classes.PhysicsManagers { public enum SolverType { ProjectedGaussSiedel = 0, TemporalGaussSiedel = 1, } }
15.222222
46
0.751825
[ "MIT" ]
Bluscream/UtinyRipper
uTinyRipperCore/Parser/Classes/PhysicsManager/SolverType.cs
139
C#
using System; using System.Threading; using System.Threading.Tasks; namespace Consul { public interface IConsulClient : IDisposable { IACLEndpoint ACL { get; } Task<IDistributedLock> AcquireLock(LockOptions opts, CancellationToken ct = default); Task<IDistributedLock> AcquireLock(string key, CancellationToken ct = default); Task<IDistributedSemaphore> AcquireSemaphore(SemaphoreOptions opts, CancellationToken ct = default); Task<IDistributedSemaphore> AcquireSemaphore(string prefix, int limit, CancellationToken ct = default); IAgentEndpoint Agent { get; } ICatalogEndpoint Catalog { get; } IDistributedLock CreateLock(LockOptions opts); IDistributedLock CreateLock(string key); IEventEndpoint Event { get; } Task ExecuteInSemaphore(SemaphoreOptions opts, Action a, CancellationToken ct = default); Task ExecuteInSemaphore(string prefix, int limit, Action a, CancellationToken ct = default); Task ExecuteLocked(LockOptions opts, Action action, CancellationToken ct = default); [Obsolete("This method will be removed in 0.8.0. Replace calls with the method signature ExecuteLocked(LockOptions, Action, CancellationToken)")] Task ExecuteLocked(LockOptions opts, CancellationToken ct, Action action); Task ExecuteLocked(string key, Action action, CancellationToken ct = default); [Obsolete("This method will be removed in 0.8.0. Replace calls with the method signature ExecuteLocked(string, Action, CancellationToken)")] Task ExecuteLocked(string key, CancellationToken ct, Action action); IHealthEndpoint Health { get; } IKVEndpoint KV { get; } IRawEndpoint Raw { get; } IDistributedSemaphore Semaphore(SemaphoreOptions opts); IDistributedSemaphore Semaphore(string prefix, int limit); ISessionEndpoint Session { get; } IStatusEndpoint Status { get; } IOperatorEndpoint Operator { get; } IPreparedQueryEndpoint PreparedQuery { get; } ICoordinateEndpoint Coordinate { get; } ISnapshotEndpoint Snapshot { get; } } }
54.05
153
0.718316
[ "MIT" ]
PingPongBoy/Wing
src/Wing.Consul/Consul/Interfaces/IConsulClient.cs
2,164
C#
using System.Runtime.InteropServices; namespace AR.Drone.Data.Navigation.Native.Options { [StructLayout(LayoutKind.Sequential, Pack = 1, CharSet = CharSet.Ansi)] public struct navdata_pressure_raw_t { public ushort tag; public ushort size; public int up; public short ut; public int Temperature_meas; public int Pression_meas; } }
26.333333
75
0.675949
[ "Unlicense" ]
Alkarex/AR.Drone
AR.Drone.Data/Navigation/Native/Options/navdata_pressure_raw_t.cs
395
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Google.Common.Geometry { public struct S1Angle : IEquatable<S1Angle>, IComparable<S1Angle> { private readonly double _radians; private S1Angle(double radians) { _radians = radians; } /// <summary> /// Return the angle between two points, which is also equal to the distance /// between these points on the unit sphere. The points do not need to be /// normalized. /// </summary> /// <param name="x"></param> /// <param name="y"></param> public S1Angle(S2Point x, S2Point y) { _radians = x.Angle(y); } public double Radians { get { return _radians; } } public double Degrees { get { return _radians*(180/Math.PI); } } public int CompareTo(S1Angle other) { return _radians < other._radians ? -1 : _radians > other._radians ? 1 : 0; } public bool Equals(S1Angle other) { return _radians.Equals(other._radians); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; return obj is S1Angle && Equals((S1Angle)obj); } public override int GetHashCode() { return _radians.GetHashCode(); } public static bool operator ==(S1Angle left, S1Angle right) { return Equals(left, right); } public static bool operator !=(S1Angle left, S1Angle right) { return !Equals(left, right); } public long E5() { return (long)Math.Round(Degrees*1e5); } public long E6() { return (long)Math.Round(Degrees*1e6); } public long E7() { return (long)Math.Round(Degrees*1e7); } /** * The default constructor yields a zero angle. */ public static bool operator <(S1Angle x, S1Angle y) { return x.Radians < y.Radians; } public static bool operator >(S1Angle x, S1Angle y) { return x.Radians > y.Radians; } public static bool operator <=(S1Angle x, S1Angle y) { return x.Radians <= y.Radians; } public static bool operator >=(S1Angle x, S1Angle y) { return x.Radians >= y.Radians; } public static S1Angle Max(S1Angle left, S1Angle right) { return right > left ? right : left; } public static S1Angle Min(S1Angle left, S1Angle right) { return right > left ? left : right; } public static S1Angle FromRadians(double radians) { return new S1Angle(radians); } public static S1Angle FromDegrees(double degrees) { return new S1Angle(degrees*(Math.PI/180)); } public static S1Angle E5(long e5) { return FromDegrees(e5*1e-5); } public static S1Angle E6(long e6) { // Multiplying by 1e-6 isn't quite as accurate as dividing by 1e6, // but it's about 10 times faster and more than accurate enough. return FromDegrees(e6*1e-6); } public static S1Angle E7(long e7) { return FromDegrees(e7*1e-7); } /** * Writes the angle in degrees with a "d" suffix, e.g. "17.3745d". By default * 6 digits are printed; this can be changed using setprecision(). Up to 17 * digits are required to distinguish one angle from another. */ public override string ToString() { return Degrees + "d"; } } }
24.93125
88
0.528453
[ "Apache-2.0" ]
Cryofortress/s2-geometry-library-csharp
S2Geometry/S1Angle.cs
3,991
C#
using LineageServer.Server.DataTables; using LineageServer.Server.Model; using LineageServer.Server.Model.identity; using LineageServer.Server.Model.Instance; using LineageServer.Server.Model.shop; using LineageServer.Serverpackets; using LineageServer.Server.Templates; using LineageServer.william; using System; using System.Collections.Generic; using LineageServer.Server; using LineageServer.Interfaces; using System.Extensions; namespace LineageServer.Clientpackets { /// <summary> /// TODO 翻譯,好多 處理收到由客戶端傳來取得結果的封包 /// </summary> class C_Result : ClientBasePacket { private const string C_RESULT = "[C] C_Result"; public C_Result(byte[] abyte0, ClientThread clientthread) : base(abyte0) { L1PcInstance pc = clientthread.ActiveChar; if (pc == null) { return; } int npcObjectId = ReadD(); int resultType = ReadC(); int size = ReadH(); int level = pc.Level; int npcId = 0; string npcImpl = ""; bool isPrivateShop = false; bool tradable = true; GameObject findObject = Container.Instance.Resolve<IGameWorld>().findObject(npcObjectId); if (findObject != null) { int diffLocX = Math.Abs(pc.X - findObject.X); int diffLocY = Math.Abs(pc.Y - findObject.Y); // 5格以上的距離視為無效要求 if ((diffLocX > 5) || (diffLocY > 5)) { return; } if (findObject is L1NpcInstance) { L1NpcInstance targetNpc = (L1NpcInstance)findObject; npcId = targetNpc.NpcTemplate.get_npcId(); npcImpl = targetNpc.NpcTemplate.Impl; } else if (findObject is L1PcInstance) { isPrivateShop = true; } } if ((resultType == 0) && (size != 0) && npcImpl == "L1Merchant") { // 買道具 L1Shop shop = ShopTable.Instance.get(npcId); L1ShopBuyOrderList orderList = shop.newBuyOrderList(); for (int i = 0; i < size; i++) { orderList.add(ReadD(), ReadD()); } shop.sellItems(pc, orderList); } else if ((resultType == 1) && (size != 0) && npcImpl == "L1Merchant") { // 賣道具 // 全道具販賣 if (Config.ALL_ITEM_SELL) { int objectId, count; L1ItemInstance item; int totalPrice = 0; int tax_rate = L1CastleLocation.getCastleTaxRateByNpcId(npcId); for (int i = 0; i < size; i++) { objectId = ReadD(); count = ReadD(); item = pc.Inventory.getItem(objectId); if (item == null) { continue; } if (item.Equipped) { continue; } count = pc.Inventory.removeItem(item, count); // 削除 int getPrice = L1WilliamItemPrice.getItemId(item.Item.ItemId); int price = 0; if (getPrice > 0) { price = getPrice; } else { price = 0; } if (tax_rate != 0) { double tax = (100 + tax_rate) / 100.0; price = (int)(price * tax); } price = price * count / 2; totalPrice += price; } totalPrice = totalPrice.Ensure(0, 2000000000); if (0 < totalPrice) { pc.Inventory.storeItem(L1ItemId.ADENA, totalPrice); } } else { L1Shop shop = ShopTable.Instance.get(npcId); L1ShopSellOrderList orderList = shop.newSellOrderList(pc); for (int i = 0; i < size; i++) { orderList.add(ReadD(), ReadD()); } shop.buyItems(orderList); } // 全道具販賣 end } else if ((resultType == 2) && (size != 0) && npcImpl == "L1Dwarf" && (level >= 5)) { // 自己的倉庫 int objectId, count; for (int i = 0; i < size; i++) { tradable = true; objectId = ReadD(); count = ReadD(); GameObject @object = pc.Inventory.getItem(objectId); L1ItemInstance item = (L1ItemInstance)@object; if (!item.Item.Tradable) { tradable = false; pc.sendPackets(new S_ServerMessage(210, item.Item.Name)); // \f1%0は捨てたりまたは他人に讓ることができません。 } foreach (L1NpcInstance petNpc in pc.PetList.Values) { if (petNpc is L1PetInstance) { L1PetInstance pet = (L1PetInstance)petNpc; if (item.Id == pet.ItemObjId) { tradable = false; // \f1%0は捨てたりまたは他人に讓ることができません。 pc.sendPackets(new S_ServerMessage(210, item.Item.Name)); break; } } } foreach (L1DollInstance doll in pc.DollList.Values) { if (item.Id == doll.ItemObjId) { tradable = false; pc.sendPackets(new S_ServerMessage(1181)); // 該当のマジックドールは現在使用中です。 break; } } if (pc.DwarfInventory.checkAddItemToWarehouse(item, count, L1Inventory.WAREHOUSE_TYPE_PERSONAL) == L1Inventory.SIZE_OVER) { pc.sendPackets(new S_ServerMessage(75)); // \f1これ以上ものを置く場所がありません。 break; } if (tradable) { pc.Inventory.tradeItem(objectId, count, pc.DwarfInventory); pc.turnOnOffLight(); } } // 強制儲存一次身上道具, 避免角色背包內的物品未正常寫入導致物品複製的問題 pc.saveInventory(); } else if ((resultType == 3) && (size != 0) && npcImpl == "L1Dwarf" && (level >= 5)) { // 從倉庫取出東西 int objectId, count; L1ItemInstance item; for (int i = 0; i < size; i++) { objectId = ReadD(); count = ReadD(); item = pc.DwarfInventory.getItem(objectId); if (pc.Inventory.checkAddItem(item, count) == L1Inventory.OK) // 檢查重量與容量 { if (pc.Inventory.consumeItem(L1ItemId.ADENA, 30)) { pc.DwarfInventory.tradeItem(item, count, pc.Inventory); } else { pc.sendPackets(new S_ServerMessage(189)); // \f1アデナが不足しています。 break; } } else { pc.sendPackets(new S_ServerMessage(270)); // \f1持っているものが重くて取引できません。 break; } } } else if ((resultType == 4) && (size != 0) && npcImpl == "L1Dwarf" && (level >= 5)) { // 儲存道具到血盟倉庫 int objectId, count; if (pc.Clanid != 0) { // 有血盟 for (int i = 0; i < size; i++) { tradable = true; objectId = ReadD(); count = ReadD(); L1Clan clan = Container.Instance.Resolve<IGameWorld>().getClan(pc.Clanname); GameObject @object = pc.Inventory.getItem(objectId); L1ItemInstance item = (L1ItemInstance)@object; if (clan != null) { if (!item.Item.Tradable) { tradable = false; pc.sendPackets(new S_ServerMessage(210, item.Item.Name)); // \f1%0は捨てたりまたは他人に讓ることができません。 } if (item.Bless >= 128) { // 被封印的裝備 tradable = false; pc.sendPackets(new S_ServerMessage(210, item.Item.Name)); // \f1%0は捨てたりまたは他人に讓ることができません。 } foreach (L1NpcInstance petNpc in pc.PetList.Values) { if (petNpc is L1PetInstance) { L1PetInstance pet = (L1PetInstance)petNpc; if (item.Id == pet.ItemObjId) { tradable = false; // \f1%0は捨てたりまたは他人に讓ることができません。 pc.sendPackets(new S_ServerMessage(210, item.Item.Name)); break; } } } foreach (L1DollInstance doll in pc.DollList.Values) { if (item.Id == doll.ItemObjId) { tradable = false; pc.sendPackets(new S_ServerMessage(1181)); // 該当のマジックドールは現在使用中です。 break; } } if (clan.DwarfForClanInventory.checkAddItemToWarehouse(item, count, L1Inventory.WAREHOUSE_TYPE_CLAN) == L1Inventory.SIZE_OVER) { pc.sendPackets(new S_ServerMessage(75)); // \f1これ以上ものを置く場所がありません。 break; } if (tradable) { pc.Inventory.tradeItem(objectId, count, clan.DwarfForClanInventory); clan.DwarfForClanInventory.writeHistory(pc, item, count, 0); // 血盟倉庫存入紀錄 pc.turnOnOffLight(); } } } // 強制儲存一次身上道具, 避免角色背包內的物品未正常寫入導致物品複製的問題 pc.saveInventory(); } else { pc.sendPackets(new S_ServerMessage(208)); // \f1血盟倉庫を使用するには血盟に加入していなくてはなりません。 } } else if ((resultType == 5) && (size != 0) && npcImpl == "L1Dwarf" && (level >= 5)) { // 從克萊因血盟倉庫中取出道具 int objectId, count; L1ItemInstance item; L1Clan clan = Container.Instance.Resolve<IGameWorld>().getClan(pc.Clanname); if (clan != null) { for (int i = 0; i < size; i++) { objectId = ReadD(); count = ReadD(); item = clan.DwarfForClanInventory.getItem(objectId); if (pc.Inventory.checkAddItem(item, count) == L1Inventory.OK) { // 容量重量確認及びメッセージ送信 if (pc.Inventory.consumeItem(L1ItemId.ADENA, 30)) { clan.DwarfForClanInventory.tradeItem(item, count, pc.Inventory); } else { pc.sendPackets(new S_ServerMessage(189)); // \f1アデナが不足しています。 break; } } else { pc.sendPackets(new S_ServerMessage(270)); // \f1持っているものが重くて取引できません。 break; } clan.DwarfForClanInventory.writeHistory(pc, item, count, 1); // 血盟倉庫領出紀錄 } clan.WarehouseUsingChar = 0; // クラン倉庫のロックを解除 } } else if ((resultType == 5) && (size == 0) && npcImpl == "L1Dwarf") { // クラン倉庫から取り出し中にCancel、または、ESCキー L1Clan clan = Container.Instance.Resolve<IGameWorld>().getClan(pc.Clanname); if (clan != null) { clan.WarehouseUsingChar = 0; // クラン倉庫のロックを解除 } } else if ((resultType == 8) && (size != 0) && npcImpl == "L1Dwarf" && (level >= 5) && pc.Elf) { // 自分のエルフ倉庫に格納 int objectId, count; for (int i = 0; i < size; i++) { tradable = true; objectId = ReadD(); count = ReadD(); GameObject @object = pc.Inventory.getItem(objectId); L1ItemInstance item = (L1ItemInstance)@object; if (!item.Item.Tradable) { tradable = false; pc.sendPackets(new S_ServerMessage(210, item.Item.Name)); // \f1%0は捨てたりまたは他人に讓ることができません。 } foreach (L1NpcInstance petNpc in pc.PetList.Values) { if (petNpc is L1PetInstance) { L1PetInstance pet = (L1PetInstance)petNpc; if (item.Id == pet.ItemObjId) { tradable = false; // \f1%0は捨てたりまたは他人に讓ることができません。 pc.sendPackets(new S_ServerMessage(210, item.Item.Name)); break; } } } foreach (L1DollInstance doll in pc.DollList.Values) { if (item.Id == doll.ItemObjId) { tradable = false; pc.sendPackets(new S_ServerMessage(1181)); // 該当のマジックドールは現在使用中です。 break; } } if (pc.DwarfForElfInventory.checkAddItemToWarehouse(item, count, L1Inventory.WAREHOUSE_TYPE_PERSONAL) == L1Inventory.SIZE_OVER) { pc.sendPackets(new S_ServerMessage(75)); // \f1これ以上ものを置く場所がありません。 break; } if (tradable) { pc.Inventory.tradeItem(objectId, count, pc.DwarfForElfInventory); pc.turnOnOffLight(); } } // 強制儲存一次身上道具, 避免角色背包內的物品未正常寫入導致物品複製的問題 pc.saveInventory(); } else if ((resultType == 9) && (size != 0) && npcImpl == "L1Dwarf" && (level >= 5) && pc.Elf) { // 自分のエルフ倉庫から取り出し int objectId, count; L1ItemInstance item; for (int i = 0; i < size; i++) { objectId = ReadD(); count = ReadD(); item = pc.DwarfForElfInventory.getItem(objectId); if (pc.Inventory.checkAddItem(item, count) == L1Inventory.OK) { // 容量重量確認及びメッセージ送信 if (pc.Inventory.consumeItem(40494, 2)) { // ミスリル pc.DwarfForElfInventory.tradeItem(item, count, pc.Inventory); } else { pc.sendPackets(new S_ServerMessage(337, "$767")); // \f1%0が不足しています。 break; } } else { pc.sendPackets(new S_ServerMessage(270)); // \f1持っているものが重くて取引できません。 break; } } } else if ((resultType == 0) && (size != 0) && isPrivateShop) { // 個人商店からアイテム購入 if (findObject == null) { return; } if (!(findObject is L1PcInstance)) { return; } L1PcInstance targetPc = (L1PcInstance)findObject; int order; int count; int price; IList<L1PrivateShopSellList> sellList; L1PrivateShopSellList pssl; int itemObjectId; int sellPrice; int sellTotalCount; int sellCount; L1ItemInstance item; bool[] isRemoveFromList = new bool[8]; if (targetPc.TradingInPrivateShop) { return; } sellList = targetPc.SellList; lock (sellList) { // 売り切れが発生し、閲覧中のアイテム数とリスト数が異なる if (pc.PartnersPrivateShopItemCount != sellList.Count) { return; } targetPc.TradingInPrivateShop = true; for (int i = 0; i < size; i++) { // 購入予定の商品 order = ReadD(); count = ReadD(); pssl = sellList[order]; itemObjectId = pssl.ItemObjectId; sellPrice = pssl.SellPrice; sellTotalCount = pssl.SellTotalCount; // 売る予定の個数 sellCount = pssl.SellCount; // 売った累計 item = targetPc.Inventory.getItem(itemObjectId); if (item == null) { continue; } if (count > sellTotalCount - sellCount) { count = sellTotalCount - sellCount; } if (count == 0) { continue; } if (pc.Inventory.checkAddItem(item, count) == L1Inventory.OK) { // 容量重量確認及びメッセージ送信 for (int j = 0; j < count; j++) { // オーバーフローをチェック if (sellPrice * j > 2000000000) { // 総販売価格は%dアデナを超過できません。 pc.sendPackets(new S_ServerMessage(904, "2000000000")); targetPc.TradingInPrivateShop = false; return; } } price = count * sellPrice; if (pc.Inventory.checkItem(L1ItemId.ADENA, price)) { L1ItemInstance adena = pc.Inventory.findItemId(L1ItemId.ADENA); if ((targetPc != null) && (adena != null)) { if (targetPc.Inventory.tradeItem(item, count, pc.Inventory) == null) { targetPc.TradingInPrivateShop = false; return; } pc.Inventory.tradeItem(adena, price, targetPc.Inventory); string message = $"{item.Item.Name} ({count})"; targetPc.sendPackets(new S_ServerMessage(877, pc.Name, message)); pssl.SellCount = count + sellCount; sellList[order] = pssl; if (pssl.SellCount == pssl.SellTotalCount) { // 売る予定の個数を売った isRemoveFromList[order] = true; } } } else { pc.sendPackets(new S_ServerMessage(189)); // \f1アデナが不足しています。 break; } } else { pc.sendPackets(new S_ServerMessage(270)); // \f1持っているものが重くて取引できません。 break; } } // 売り切れたアイテムをリストの末尾から削除 for (int i = 7; i >= 0; i--) { if (isRemoveFromList[i]) { sellList.RemoveAt(i); } } targetPc.TradingInPrivateShop = false; } } else if ((resultType == 1) && (size != 0) && isPrivateShop) { // 個人商店にアイテム売却 int count; int order; IList<L1PrivateShopBuyList> buyList; L1PrivateShopBuyList psbl; int itemObjectId; L1ItemInstance item; int buyPrice; int buyTotalCount; int buyCount; bool[] isRemoveFromList = new bool[8]; L1PcInstance targetPc = null; if (findObject is L1PcInstance) { targetPc = (L1PcInstance)findObject; } if (targetPc.TradingInPrivateShop) { return; } targetPc.TradingInPrivateShop = true; buyList = targetPc.BuyList; for (int i = 0; i < size; i++) { itemObjectId = ReadD(); count = ReadCH(); order = ReadC(); item = pc.Inventory.getItem(itemObjectId); if (item == null) { continue; } psbl = buyList[order]; buyPrice = psbl.BuyPrice; buyTotalCount = psbl.BuyTotalCount; // 買う予定の個数 buyCount = psbl.BuyCount; // 買った累計 if (count > buyTotalCount - buyCount) { count = buyTotalCount - buyCount; } if (item.Equipped) { // pc.sendPackets(new S_ServerMessage(905)); // 無法販賣裝備中的道具。 continue; } if (item.Bless >= 128) { // 被封印的裝備 // pc.sendPackets(new S_ServerMessage(210, item.getItem().getName())); // \f1%0%d是不可轉移的… continue; } if (targetPc.Inventory.checkAddItem(item, count) == L1Inventory.OK) { // 容量重量確認及びメッセージ送信 for (int j = 0; j < count; j++) { // オーバーフローをチェック if (buyPrice * j > 2000000000) { targetPc.sendPackets(new S_ServerMessage(904, "2000000000")); return; } } if (targetPc.Inventory.checkItem(L1ItemId.ADENA, count * buyPrice)) { L1ItemInstance adena = targetPc.Inventory.findItemId(L1ItemId.ADENA); if (adena != null) { targetPc.Inventory.tradeItem(adena, count * buyPrice, pc.Inventory); pc.Inventory.tradeItem(item, count, targetPc.Inventory); psbl.BuyCount = count + buyCount; buyList[order] = psbl; if (psbl.BuyCount == psbl.BuyTotalCount) { // 買う予定の個数を買った isRemoveFromList[order] = true; } } } else { targetPc.sendPackets(new S_ServerMessage(189)); // \f1アデナが不足しています。 break; } } else { pc.sendPackets(new S_ServerMessage(271)); // \f1相手が物を持ちすぎていて取引できません。 break; } } // 買い切ったアイテムをリストの末尾から削除 for (int i = 7; i >= 0; i--) { if (isRemoveFromList[i]) { buyList.RemoveAt(i); } } targetPc.TradingInPrivateShop = false; } else if ((resultType == 12) && (size != 0) && npcImpl == "L1Merchant") { // 領取寵物 int petCost, petCount, divisor, itemObjectId, itemCount = 0; bool chackAdena = true; for (int i = 0; i < size; i++) { petCost = 0; petCount = 0; divisor = 6; itemObjectId = ReadD(); itemCount = ReadD(); if (itemCount == 0) { continue; } foreach (L1NpcInstance petNpc in pc.PetList.Values) { petCost += petNpc.Petcost; } int charisma = pc.getCha(); if (pc.Crown) { // 王族 charisma += 6; } else if (pc.Elf) { // 妖精 charisma += 12; } else if (pc.Wizard) { // 法師 charisma += 6; } else if (pc.Darkelf) { // 黑暗妖精 charisma += 6; } else if (pc.DragonKnight) { // 龍騎士 charisma += 6; } else if (pc.Illusionist) { // 幻術師 charisma += 6; } if (!pc.Inventory.consumeItem(L1ItemId.ADENA, 115)) { chackAdena = false; } L1Pet l1pet = PetTable.Instance.getTemplate(itemObjectId); if (l1pet != null && chackAdena) { npcId = l1pet.get_npcid(); charisma -= petCost; if ((npcId == 45313) || (npcId == 45710) || (npcId == 45711) || (npcId == 45712)) { // 紀州犬の子犬、紀州犬 divisor = 12; } else { divisor = 6; } petCount = charisma / divisor; if (petCount <= 0) { pc.sendPackets(new S_ServerMessage(489)); // 你無法一次控制那麼多寵物。 return; } L1Npc npcTemp = Container.Instance.Resolve<INpcController>().getTemplate(npcId); L1PetInstance pet = new L1PetInstance(npcTemp, pc, l1pet); pet.Petcost = divisor; } } if (!chackAdena) { pc.sendPackets(new S_ServerMessage(189)); // \f1金幣不足。 } } } public override string Type { get { return C_RESULT; } } } }
41.689655
154
0.364235
[ "Unlicense" ]
TaiwanSpring/L1CSharpTW
LineageServer/Clientpackets/C_Result.cs
32,355
C#
 namespace Notepads.Utilities { using System; using System.Threading.Tasks; using Windows.UI.Xaml.Controls; public static class ContentDialogMaker { public static async void CreateContentDialog(ContentDialog dialog, bool awaitPreviousDialog) { await CreateDialog(dialog, awaitPreviousDialog); } public static async Task CreateContentDialogAsync(ContentDialog dialog, bool awaitPreviousDialog) { await CreateDialog(dialog, awaitPreviousDialog); } public static ContentDialog ActiveDialog; private static TaskCompletionSource<bool> _dialogAwaiter = new TaskCompletionSource<bool>(); static async Task CreateDialog(ContentDialog dialog, bool awaitPreviousDialog) { TaskCompletionSource<bool> currentAwaiter = _dialogAwaiter; TaskCompletionSource<bool> nextAwaiter = new TaskCompletionSource<bool>(); _dialogAwaiter = nextAwaiter; if (ActiveDialog != null) { if (awaitPreviousDialog) { await currentAwaiter.Task; } else { ActiveDialog.Hide(); } } ActiveDialog = dialog; await ActiveDialog.ShowAsync(); nextAwaiter.SetResult(true); } } }
32.5
158
0.621978
[ "MIT" ]
Sergio0694/Notepads
src/Notepads/Utilities/ContentDialogMaker.cs
1,367
C#
using MarketingBox.AffiliateApi.Models.Partners; namespace MarketingBox.AffiliateApi.Models.Campaigns { public class Payout { public decimal Amount { get; set; } public Currency Currency { get; set; } public Plan Plan { get; set; } } }
21.153846
52
0.658182
[ "MIT" ]
MyJetWallet/MarketingBox.AffiliateApi
src/MarketingBox.AffiliateApi/Models/Campaigns/Payout.cs
277
C#
using Npgsql; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace watchtower.Services.Db.Patches { [Patch] public class Patch22AddOutfitReportTable : IDbPatch { public int MinVersion => 22; public string Name => "Add outfit report table"; public async Task Execute(IDbHelper helper) { using NpgsqlConnection conn = helper.Connection(); using NpgsqlCommand cmd = await helper.Command(conn, @" CREATE TABLE IF NOT EXISTS outfit_report ( id bigint NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY, generator varchar NOT NULL, timestamp timestamptz NOT NULL DEFAULT (NOW() at time zone 'utc'), period_start timestamptz NOT NULL, period_end timestamptz NOT NULL ); "); await cmd.ExecuteNonQueryAsync(); await conn.CloseAsync(); } } }
30.264706
86
0.601555
[ "MIT" ]
Simacrus/honu
Services/Db/Patches/Patch22AddOutfitReportTable.cs
1,031
C#
using Bridge; namespace Bridge.Html5 { /// <summary> /// The text-transform CSS property specifies how to capitalize an element's text. It can be used to make text appear in all-uppercase or all-lowercase, or with each word capitalized. /// </summary> [Ignore] [Enum(Emit.StringNameLowerCase)] [Name("String")] public enum TextTransform { /// <summary> /// /// </summary> Inherit, /// <summary> /// Is a keyword forcing the first letter of each word to be converted to uppercase. /// </summary> Capitalize, /// <summary> /// Is a keyword forcing all characters to be converted to uppercase. /// </summary> UpperCase, /// <summary> /// Is a keyword forcing all characters to be converted to lowercase. /// </summary> LowerCase, /// <summary> /// Is a keyword preventing the case of all characters to be changed. /// </summary> None, /// <summary> /// Is a keyword forcing the writing of a character, mainly ideograms and latin scripts inside a square, allowing them to be aligned in the usual East Asian scripts (like Chinese or Japanese). /// </summary> [Name("full-width")] FullWidth } }
29.6
200
0.584835
[ "Apache-2.0" ]
corefan/Bridge
Html5/CSS/TextTransform.cs
1,334
C#
using System; using System.Collections.Generic; using QuickGraph.Algorithms.Services; using System.Diagnostics.Contracts; using System.Linq; namespace QuickGraph.Algorithms.RandomWalks { /// <summary> /// Wilson-Propp Cycle-Popping Algorithm for Random Tree Generation. /// </summary> #if !SILVERLIGHT [Serializable] #endif public sealed class CyclePoppingRandomTreeAlgorithm<TVertex, TEdge> : RootedAlgorithmBase<TVertex,IVertexListGraph<TVertex,TEdge>> , IVertexColorizerAlgorithm<TVertex, TEdge> , ITreeBuilderAlgorithm<TVertex,TEdge> where TEdge : IEdge<TVertex> { private IDictionary<TVertex, GraphColor> vertexColors = new Dictionary<TVertex, GraphColor>(); private IMarkovEdgeChain<TVertex,TEdge> edgeChain = new NormalizedMarkovEdgeChain<TVertex,TEdge>(); private IDictionary<TVertex, TEdge> successors = new Dictionary<TVertex, TEdge>(); private Random rnd = new Random((int)DateTime.Now.Ticks); public CyclePoppingRandomTreeAlgorithm( IVertexListGraph<TVertex, TEdge> visitedGraph) : this(visitedGraph, new NormalizedMarkovEdgeChain<TVertex, TEdge>()) { } public CyclePoppingRandomTreeAlgorithm( IVertexListGraph<TVertex, TEdge> visitedGraph, IMarkovEdgeChain<TVertex, TEdge> edgeChain) : this(null, visitedGraph, edgeChain) { } public CyclePoppingRandomTreeAlgorithm( IAlgorithmComponent host, IVertexListGraph<TVertex,TEdge> visitedGraph, IMarkovEdgeChain<TVertex,TEdge> edgeChain ) :base(host, visitedGraph) { Contract.Requires(edgeChain != null); this.edgeChain = edgeChain; } public IDictionary<TVertex,GraphColor> VertexColors { get { return this.vertexColors; } } public GraphColor GetVertexColor(TVertex v) { return this.vertexColors[v]; } public IMarkovEdgeChain<TVertex,TEdge> EdgeChain { get { return this.edgeChain; } } /// <summary> /// Gets or sets the random number generator used in <c>RandomTree</c>. /// </summary> /// <value> /// <see cref="Random"/> number generator /// </value> public Random Rnd { get { return this.rnd; } set { Contract.Requires(value != null); this.rnd = value; } } public IDictionary<TVertex,TEdge> Successors { get { return this.successors; } } public event VertexAction<TVertex> InitializeVertex; private void OnInitializeVertex(TVertex v) { var eh = this.InitializeVertex; if (eh != null) eh(v); } public event VertexAction<TVertex> FinishVertex; private void OnFinishVertex(TVertex v) { var eh = this.FinishVertex; if (eh != null) eh(v); } public event EdgeAction<TVertex,TEdge> TreeEdge; private void OnTreeEdge(TEdge e) { var eh = this.TreeEdge; if (eh != null) eh(e); } public event VertexAction<TVertex> ClearTreeVertex; private void OnClearTreeVertex(TVertex v) { var eh = this.ClearTreeVertex; if (eh != null) eh(v); } protected override void Initialize() { base.Initialize(); this.successors.Clear(); this.vertexColors.Clear(); foreach (var v in this.VisitedGraph.Vertices) { this.vertexColors.Add(v,GraphColor.White); OnInitializeVertex(v); } } private bool NotInTree(TVertex u) { GraphColor color = this.vertexColors[u]; return color == GraphColor.White; } private void SetInTree(TVertex u) { this.vertexColors[u] = GraphColor.Black; OnFinishVertex(u); } private bool TryGetSuccessor(Dictionary<TEdge, int> visited, TVertex u, out TEdge successor) { var outEdges = this.VisitedGraph.OutEdges(u); var edges = Enumerable.Where(outEdges, e => !visited.ContainsKey(e)); return this.EdgeChain.TryGetSuccessor(edges, u, out successor); } private void Tree(TVertex u, TEdge next) { Contract.Requires(next != null); this.successors[u] = next; OnTreeEdge(next); } private bool TryGetNextInTree(TVertex u, out TVertex next) { TEdge nextEdge; if (this.successors.TryGetValue(u, out nextEdge)) { next = nextEdge.Target; return true; } next = default(TVertex); return false; } private bool Chance(double eps) { return this.rnd.NextDouble() <= eps; } private void ClearTree(TVertex u) { this.successors[u] = default(TEdge); OnClearTreeVertex(u); } public void RandomTreeWithRoot(TVertex root) { Contract.Requires(root != null); Contract.Requires(this.VisitedGraph.ContainsVertex(root)); this.SetRootVertex(root); this.Compute(); } protected override void InternalCompute() { TVertex rootVertex; if (!this.TryGetRootVertex(out rootVertex)) throw new InvalidOperationException("RootVertex not specified"); var cancelManager = this.Services.CancelManager; // process root ClearTree(rootVertex); SetInTree(rootVertex); foreach (var i in this.VisitedGraph.Vertices) { if (cancelManager.IsCancelling) break; // first pass exploring { var visited = new Dictionary<TEdge, int>(); TVertex u = i; TEdge successor; while (NotInTree(u) && this.TryGetSuccessor(visited, u, out successor)) { visited[successor] = 0; Tree(u, successor); if (!this.TryGetNextInTree(u, out u)) break; } } // second pass, coloring { TVertex u = i; while (NotInTree(u)) { SetInTree(u); if (!this.TryGetNextInTree(u, out u)) break; } } } } public void RandomTree() { var cancelManager = this.Services.CancelManager; double eps = 1; bool success; do { if (cancelManager.IsCancelling) break; eps /= 2; success = Attempt(eps); } while (!success); } private bool Attempt(double eps) { Initialize(); int numRoots = 0; var cancelManager = this.Services.CancelManager; foreach (var i in this.VisitedGraph.Vertices) { if (cancelManager.IsCancelling) break; // first pass exploring { var visited = new Dictionary<TEdge, int>(); TEdge successor; var u = i; while (NotInTree(u)) { if (Chance(eps)) { ClearTree(u); SetInTree(u); ++numRoots; if (numRoots > 1) return false; } else { if (!this.TryGetSuccessor(visited, u, out successor)) break; visited[successor] = 0; Tree(u, successor); if (!this.TryGetNextInTree(u, out u)) break; } } } // second pass, coloring { var u = i; while (NotInTree(u)) { SetInTree(u); if (!this.TryGetNextInTree(u, out u)) break; } } } return true; } } }
29.870968
107
0.473974
[ "MIT" ]
UWBCoevolution/ParaMODA
QuickGraph/Algorithms/RandomWalks/CyclePoppingRandomTreeAlgorithm.cs
9,262
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the synthetics-2017-10-11.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Synthetics.Model { /// <summary> /// This is the response object from the DescribeCanariesLastRun operation. /// </summary> public partial class DescribeCanariesLastRunResponse : AmazonWebServiceResponse { private List<CanaryLastRun> _canariesLastRun = new List<CanaryLastRun>(); private string _nextToken; /// <summary> /// Gets and sets the property CanariesLastRun. /// <para> /// An array that contains the information from the most recent run of each canary. /// </para> /// </summary> public List<CanaryLastRun> CanariesLastRun { get { return this._canariesLastRun; } set { this._canariesLastRun = value; } } // Check to see if CanariesLastRun property is set internal bool IsSetCanariesLastRun() { return this._canariesLastRun != null && this._canariesLastRun.Count > 0; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// A token that indicates that there is more data available. You can use this token in /// a subsequent <code>DescribeCanariesLastRun</code> operation to retrieve the next set /// of results. /// </para> /// </summary> [AWSProperty(Min=4, Max=252)] public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } } }
32.379747
108
0.640735
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Synthetics/Generated/Model/DescribeCanariesLastRunResponse.cs
2,558
C#
using UnityEngine; using UnityEngine.Events; namespace ZMD { public class EnableEvent : MonoBehaviour { [SerializeField] UnityEvent Output = default; void OnEnable() { if (!locked) Output.Invoke(); } [SerializeField] bool locked; public void SetLocked(bool value) { locked = value; } } }
22.866667
61
0.632653
[ "MIT" ]
Will9371/Playcraft
Assets/ZMD/[Core]/Unity Hooks/Monobehaviour/EnableEvent.cs
345
C#
using System.Threading.Tasks; using Abp.Application.Services; using Abp.Application.Services.Dto; using AbpMpaMvcEfInit.Roles.Dto; namespace AbpMpaMvcEfInit.Roles { public interface IRoleAppService : IAsyncCrudAppService<RoleDto, int, PagedResultRequestDto, CreateRoleDto, RoleDto> { Task<ListResultDto<PermissionDto>> GetAllPermissions(); } }
28.153846
120
0.784153
[ "MIT" ]
vban512/SampleBookManage2018
src/AbpMpaMvcEfInit.Application/Roles/IRoleAppService.cs
368
C#
using System; using System.IO; using UnityEngine; using UnityObject = UnityEngine.Object; namespace Monolith.Unity { public static class GameBootstrapper { public static void Run<T>(Func<GameEngineListener, GameBootOptions, T> make) where T : Game { GameBootOptions bootOptions = null; var bootProfileSelector = Resources.Load<GameBootProfileSelector>("BootProfileSelector"); if (bootProfileSelector != null) { if (bootProfileSelector.NeedsSanitizing) { throw new InvalidDataException("Game could not be initialized because BootProfileSelector contains invalid data."); } else if (bootProfileSelector.NeedsSynchronization) { Debug.LogWarning("Game may not behave as expected due to mismatched scripting define symbols!"); } if (bootProfileSelector.ActiveIndex >= 0) { bootOptions = (GameBootOptions)bootProfileSelector.Profiles[bootProfileSelector.ActiveIndex].BootOptions; } } Resources.UnloadAsset(bootProfileSelector); var gameObject = new GameObject("EngineListener") { hideFlags = HideFlags.HideAndDontSave }; UnityObject.DontDestroyOnLoad(gameObject); var engineListener = gameObject.AddComponent<GameEngineListener>(); make(engineListener, bootOptions); } } }
32.156863
135
0.580488
[ "MIT" ]
bmotamer/monolith-unity
Monolith.Unity/GameBootstrapper.cs
1,642
C#
using Microsoft.AspNetCore.Hosting; namespace Amazon.Lambda.AspNetCoreServer { /// <summary> /// ApplicationLoadBalancerFunction is the base class that is implemented in a ASP.NET Core Web API. The derived class implements /// the Init method similar to Main function in the ASP.NET Core and provides typed Startup. The function handler for /// the Lambda function will point to this base class FunctionHandlerAsync method. /// </summary> /// <typeparam name ="TStartup">The type containing the startup methods for the application.</typeparam> public abstract class ApplicationLoadBalancerFunction<TStartup> : ApplicationLoadBalancerFunction where TStartup : class { /// <inheritdoc/> protected override IWebHostBuilder CreateWebHostBuilder() => base.CreateWebHostBuilder().UseStartup<TStartup>(); /// <inheritdoc/> protected override void Init(IWebHostBuilder builder) { } } }
42.478261
133
0.713408
[ "Apache-2.0" ]
LukeStanislaus/aws-lambda-dotnet
Libraries/src/Amazon.Lambda.AspNetCoreServer/ApplicationLoadBalancerFunction{TStartup}.cs
979
C#
//----------------------------------------------------------------------- // <copyright file="HoconArray.cs" company="Hocon Project"> // Copyright (C) 2009-2018 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2018 .NET Foundation <https://github.com/akkadotnet/hocon> // </copyright> //----------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; namespace Hocon { /// <summary> /// This class represents an array element in a HOCON (Human-Optimized Config Object Notation) /// configuration string. /// <code> /// root { /// items = [ /// "1", /// "2"] /// } /// </code> /// </summary> public sealed class HoconArray : List<HoconValue>, IHoconElement { private HoconType _arrayType = HoconType.Empty; public IHoconElement Parent { get; } public HoconType Type => HoconType.Array; public HoconArray(IHoconElement parent) { Parent = parent; } public HoconObject GetObject() { throw new HoconException("Can not convert Hocon array into an object."); } /// <inheritdoc /> /// <exception cref="HoconException"> /// This element is an array. It is not a string. /// Therefore this method will throw an exception. /// </exception> public string GetString() { throw new HoconException("Can not convert Hocon array into a string."); } public string Raw => throw new HoconException("Can not convert Hocon array into a string."); /// <inheritdoc /> public List<HoconValue> GetArray() { return this; } public new void Add(HoconValue value) { if (value.Type != HoconType.Empty) { if(_arrayType == HoconType.Empty) _arrayType = value.Type; else if (value.Type != _arrayType) throw new HoconException( $"Array value must match the rest of the array type or empty. Array value type: {_arrayType}, inserted type: {value.Type}"); } base.Add(value); } internal void ResolveValue(HoconSubstitution sub) { var subValue = (HoconValue)sub.Parent; if (sub.Type == HoconType.Empty) { subValue.Remove(sub); if (subValue.Count == 0) Remove(subValue); return; } if (_arrayType != HoconType.Empty && sub.Type != _arrayType) { throw HoconParserException.Create(sub, sub.Path, $"Substitution value must match the rest of the field type or empty. Array value type: {_arrayType}, substitution type: {sub.Type}"); } } /// <summary> /// Returns a HOCON string representation of this element. /// </summary> /// <returns>A HOCON string representation of this element.</returns> public override string ToString() => ToString(0, 2); public string ToString(int indent, int indentSize) { return $"[{string.Join(", ", this)}]"; } public IHoconElement Clone(IHoconElement newParent) { var newArray = new HoconArray(newParent); foreach (var value in this) { newArray.Add(value); } return newArray; } private bool Equals(HoconArray other) { if (Count != other.Count) return false; for(var i = 0; i < Count; ++i) { if (!Equals(this[i], other[i])) return false; } return true; } public bool Equals(IHoconElement other) { if (other is null) return false; if (ReferenceEquals(this, other)) return true; return other is HoconArray array && Equals(array); } public override bool Equals(object obj) { if (obj is null) return false; if (ReferenceEquals(this, obj)) return true; return obj is IHoconElement element && Equals(element); } public override int GetHashCode() { const int seed = 599; const int modifier = 37; unchecked { return this.Aggregate(seed, (current, item) => (current * modifier) + item.GetHashCode()); } } public static bool operator ==(HoconArray left, HoconArray right) { return Equals(left, right); } public static bool operator !=(HoconArray left, HoconArray right) { return !Equals(left, right); } } }
30.613497
153
0.511222
[ "Apache-2.0" ]
IgorFedchenko/HOCON
src/Hocon/Impl/HoconArray.cs
4,992
C#
using System.ComponentModel.DataAnnotations; using Abp.Auditing; using Abp.Authorization.Users; using Abp.AutoMapper; using Abp.Runtime.Validation; using AbpKendoDemo.Authorization.Users; namespace AbpKendoDemo.Users.Dto { [AutoMapTo(typeof(User))] public class CreateUserDto : IShouldNormalize { [Required] [StringLength(AbpUserBase.MaxUserNameLength)] public string UserName { get; set; } [Required] [StringLength(AbpUserBase.MaxNameLength)] public string Name { get; set; } [Required] [StringLength(AbpUserBase.MaxSurnameLength)] public string Surname { get; set; } [Required] [EmailAddress] [StringLength(AbpUserBase.MaxEmailAddressLength)] public string EmailAddress { get; set; } public bool IsActive { get; set; } public string[] RoleNames { get; set; } [Required] [StringLength(AbpUserBase.MaxPlainPasswordLength)] [DisableAuditing] public string Password { get; set; } public void Normalize() { if (RoleNames == null) { RoleNames = new string[0]; } } } }
25.333333
58
0.618421
[ "MIT" ]
OzBob/aspnetboilerplate-samples
KendoUiDemo/src/AbpKendoDemo.Application/Users/Dto/CreateUserDto.cs
1,216
C#
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using Microsoft.Azure.Commands.Compute.Automation.Models; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Compute.Models; using Microsoft.WindowsAzure.Commands.Common.CustomAttributes; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Management.Automation; namespace Microsoft.Azure.Commands.Compute.Automation { [CmdletOutputBreakingChange(typeof(PSSnapshotUpdate), DeprecatedOutputProperties = new string[] { "EncryptionSettings" }, NewOutputProperties = new string[] { "EncryptionSettingsCollection" })] [Cmdlet(VerbsCommon.New, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "SnapshotUpdateConfig", SupportsShouldProcess = true)] [OutputType(typeof(PSSnapshotUpdate))] public partial class NewAzureRmSnapshotUpdateConfigCommand : Microsoft.Azure.Commands.ResourceManager.Common.AzureRMCmdlet { [Parameter( Mandatory = false, Position = 0, ValueFromPipelineByPropertyName = true)] [Alias("AccountType")] [PSArgumentCompleter("Standard_LRS", "Premium_LRS", "Standard_ZRS")] public string SkuName { get; set; } [Parameter( Mandatory = false, Position = 1, ValueFromPipelineByPropertyName = true)] public OperatingSystemTypes? OsType { get; set; } [Parameter( Mandatory = false, Position = 2, ValueFromPipelineByPropertyName = true)] public int DiskSizeGB { get; set; } [Parameter( Mandatory = false, Position = 3, ValueFromPipelineByPropertyName = true)] public Hashtable Tag { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public bool? EncryptionSettingsEnabled { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public KeyVaultAndSecretReference DiskEncryptionKey { get; set; } [Parameter( Mandatory = false, ValueFromPipelineByPropertyName = true)] public KeyVaultAndKeyReference KeyEncryptionKey { get; set; } protected override void ProcessRecord() { if (ShouldProcess("SnapshotUpdate", "New")) { Run(); } } private void Run() { // EncryptionSettingsCollection EncryptionSettingsCollection vEncryptionSettingsCollection = null; // Sku SnapshotSku vSku = null; if (this.MyInvocation.BoundParameters.ContainsKey("EncryptionSettingsEnabled")) { if (vEncryptionSettingsCollection == null) { vEncryptionSettingsCollection = new EncryptionSettingsCollection(); } vEncryptionSettingsCollection.Enabled = (bool) this.EncryptionSettingsEnabled; } if (this.MyInvocation.BoundParameters.ContainsKey("DiskEncryptionKey")) { if (vEncryptionSettingsCollection == null) { vEncryptionSettingsCollection = new EncryptionSettingsCollection(); } if (vEncryptionSettingsCollection.EncryptionSettings == null) { vEncryptionSettingsCollection.EncryptionSettings = new List<EncryptionSettingsElement>(); } if (vEncryptionSettingsCollection.EncryptionSettings.Count == 0) { vEncryptionSettingsCollection.EncryptionSettings.Add(new EncryptionSettingsElement()); } vEncryptionSettingsCollection.EncryptionSettings[0].DiskEncryptionKey = this.DiskEncryptionKey; } if (this.MyInvocation.BoundParameters.ContainsKey("KeyEncryptionKey")) { if (vEncryptionSettingsCollection == null) { vEncryptionSettingsCollection = new EncryptionSettingsCollection(); } if (vEncryptionSettingsCollection.EncryptionSettings == null) { vEncryptionSettingsCollection.EncryptionSettings = new List<EncryptionSettingsElement>(); } if (vEncryptionSettingsCollection.EncryptionSettings.Count == 0) { vEncryptionSettingsCollection.EncryptionSettings.Add(new EncryptionSettingsElement()); } vEncryptionSettingsCollection.EncryptionSettings[0].KeyEncryptionKey = this.KeyEncryptionKey; } if (this.MyInvocation.BoundParameters.ContainsKey("SkuName")) { if (vSku == null) { vSku = new SnapshotSku(); } vSku.Name = this.SkuName; } var vSnapshotUpdate = new PSSnapshotUpdate { OsType = this.MyInvocation.BoundParameters.ContainsKey("OsType") ? this.OsType : (OperatingSystemTypes?)null, DiskSizeGB = this.MyInvocation.BoundParameters.ContainsKey("DiskSizeGB") ? this.DiskSizeGB : (int?)null, Tags = this.MyInvocation.BoundParameters.ContainsKey("Tag") ? this.Tag.Cast<DictionaryEntry>().ToDictionary(ht => (string)ht.Key, ht => (string)ht.Value) : null, EncryptionSettingsCollection = vEncryptionSettingsCollection, Sku = vSku, }; WriteObject(vSnapshotUpdate); } } }
40.590361
178
0.60656
[ "MIT" ]
AzPsTest/azure-powershell
src/Compute/Compute/Generated/Snapshot/Config/NewAzureRmSnapshotUpdateConfigCommand.cs
6,573
C#
using Signals.Core.Processes.Base; using Signals.Core.Processing.Input.Http; using Signals.Core.Processing.Results; using Signals.Core.Web.Http; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Signals.Core.Web.Execution.ExecutionHandlers { /// <summary> /// Result handler /// </summary> public interface IResultHandler { /// <summary> /// Handle process result /// </summary> /// <typeparam name="TProcess"></typeparam> /// <param name="process"></param> /// <param name="type"></param> /// <param name="response"></param> /// <param name="context"></param> /// <returns></returns> MiddlewareResult HandleAfterExecution<TProcess>(TProcess process, Type type, VoidResult response, IHttpContextWrapper context) where TProcess : IBaseProcess<VoidResult>; } }
31.366667
177
0.664187
[ "MIT" ]
EmitKnowledge/Signals
src/15 Hosting/Signals.Core.Web/Execution/ExecutionHandlers/IResultHandler.cs
943
C#
#pragma checksum "..\..\App.xaml" "{8829d00f-11b8-4213-878b-770e8597ac16}" "DD5537B88A062239A1D8247A0F6D51BB0BAE1B4A7E55324200E336BA84B9D667" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using MVVM; using System; using System.Diagnostics; using System.Windows; using System.Windows.Automation; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Ink; using System.Windows.Input; using System.Windows.Markup; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; using System.Windows.Media.Imaging; using System.Windows.Media.Media3D; using System.Windows.Media.TextFormatting; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Shell; namespace MVVM { /// <summary> /// App /// </summary> public partial class App : System.Windows.Application { /// <summary> /// InitializeComponent /// </summary> [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public void InitializeComponent() { #line 5 "..\..\App.xaml" this.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative); #line default #line hidden } /// <summary> /// Application Entry Point. /// </summary> [System.STAThreadAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public static void Main() { MVVM.App app = new MVVM.App(); app.InitializeComponent(); app.Run(); } } }
31.661972
142
0.615214
[ "BSD-3-Clause" ]
marlandolaud/presentations
WPF/MVVMFromBook/MVVMFinal/obj/Debug/App.g.cs
2,250
C#
using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Host; using System; using System.Diagnostics; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using System.Text; using System.Collections.Generic; using Microsoft.Extensions.Logging; using Microsoft.Azure.EventHubs; namespace StreamingProcessor { public static class Test0 { /* * Cosmos DB output using Azure Function binding */ [FunctionName("Test0")] public static async Task RunAsync( [EventHubTrigger("%EventHubName%", Connection = "EventHubsConnectionString", ConsumerGroup = "%ConsumerGroup%")] EventData[] eventHubData, [CosmosDB(databaseName: "%CosmosDBDatabaseName%", collectionName: "%CosmosDBCollectionName%", ConnectionStringSetting = "CosmosDBConnectionString")] IAsyncCollector<JObject> cosmosMessage, ILogger log) { var tasks = new List<Task>(); Stopwatch sw = new Stopwatch(); sw.Start(); foreach (var data in eventHubData) { try { string message = Encoding.UTF8.GetString(data.Body.Array); var document = JObject.Parse(message); document["id"] = document["eid"]; document["eat"] = data.SystemProperties.EnqueuedTimeUtc; document["pat"] = DateTime.UtcNow; // document.Remove("cv"); // document.Remove("ct"); tasks.Add(cosmosMessage.AddAsync(document)); } catch (Exception ex) { log.LogError($"{ex} - {ex.Message}"); } } await Task.WhenAll(tasks); sw.Stop(); string logMessage = $"[Test0] T:{eventHubData.Length} doc - E:{sw.ElapsedMilliseconds} msec"; if (eventHubData.Length > 0) { logMessage += Environment.NewLine + $"AVG:{(sw.ElapsedMilliseconds / eventHubData.Length):N3} msec"; } log.LogInformation(logMessage); } } }
32.954545
200
0.564138
[ "MIT" ]
charlierz/streaming-at-scale
eventhubs-functions-cosmosdb/StreamingProcessor-CosmosDB-Test0/StreamingProcessor-CosmosDB/Test0.cs
2,175
C#
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text; namespace ImGuiNET { public static unsafe partial class ImGui { public static bool InputText( string label, byte[] buf, uint buf_size) { return InputText(label, buf, buf_size, 0, null, IntPtr.Zero); } public static bool InputText( string label, byte[] buf, uint buf_size, ImGuiInputTextFlags flags) { return InputText(label, buf, buf_size, flags, null, IntPtr.Zero); } public static bool InputText( string label, byte[] buf, uint buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback) { return InputText(label, buf, buf_size, flags, callback, IntPtr.Zero); } public static bool InputText( string label, byte[] buf, uint buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, IntPtr user_data) { int utf8LabelByteCount = Encoding.UTF8.GetByteCount(label); byte* utf8LabelBytes; if (utf8LabelByteCount > Util.StackAllocationSizeLimit) { utf8LabelBytes = Util.Allocate(utf8LabelByteCount + 1); } else { byte* stackPtr = stackalloc byte[utf8LabelByteCount + 1]; utf8LabelBytes = stackPtr; } Util.GetUtf8(label, utf8LabelBytes, utf8LabelByteCount); bool ret; fixed (byte* bufPtr = buf) { ret = ImGuiNative.igInputText(utf8LabelBytes, bufPtr, buf_size, flags, callback, user_data.ToPointer()) != 0; } if (utf8LabelByteCount > Util.StackAllocationSizeLimit) { Util.Free(utf8LabelBytes); } return ret; } public static bool InputText( string label, ref string input, uint maxLength) => InputText(label, ref input, maxLength, 0, null, IntPtr.Zero); public static bool InputText( string label, ref string input, uint maxLength, ImGuiInputTextFlags flags) => InputText(label, ref input, maxLength, flags, null, IntPtr.Zero); public static bool InputText( string label, ref string input, uint maxLength, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback) => InputText(label, ref input, maxLength, flags, callback, IntPtr.Zero); public static bool InputText( string label, ref string input, uint maxLength, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, IntPtr user_data) { int utf8LabelByteCount = Encoding.UTF8.GetByteCount(label); byte* utf8LabelBytes; if (utf8LabelByteCount > Util.StackAllocationSizeLimit) { utf8LabelBytes = Util.Allocate(utf8LabelByteCount + 1); } else { byte* stackPtr = stackalloc byte[utf8LabelByteCount + 1]; utf8LabelBytes = stackPtr; } Util.GetUtf8(label, utf8LabelBytes, utf8LabelByteCount); int utf8InputByteCount = Encoding.UTF8.GetByteCount(input); int inputBufSize = Math.Max((int)maxLength + 1, utf8InputByteCount + 1); byte* utf8InputBytes; byte* originalUtf8InputBytes; if (inputBufSize > Util.StackAllocationSizeLimit) { utf8InputBytes = Util.Allocate(inputBufSize); originalUtf8InputBytes = Util.Allocate(inputBufSize); } else { byte* inputStackBytes = stackalloc byte[inputBufSize]; utf8InputBytes = inputStackBytes; byte* originalInputStackBytes = stackalloc byte[inputBufSize]; originalUtf8InputBytes = originalInputStackBytes; } Util.GetUtf8(input, utf8InputBytes, inputBufSize); uint clearBytesCount = (uint)(inputBufSize - utf8InputByteCount); Unsafe.InitBlockUnaligned(utf8InputBytes + utf8InputByteCount, 0, clearBytesCount); Unsafe.CopyBlock(originalUtf8InputBytes, utf8InputBytes, (uint)inputBufSize); byte result = ImGuiNative.igInputText( utf8LabelBytes, utf8InputBytes, (uint)inputBufSize, flags, callback, user_data.ToPointer()); if (!Util.AreStringsEqual(originalUtf8InputBytes, inputBufSize, utf8InputBytes)) { input = Util.StringFromPtr(utf8InputBytes); } if (utf8LabelByteCount > Util.StackAllocationSizeLimit) { Util.Free(utf8LabelBytes); } if (inputBufSize > Util.StackAllocationSizeLimit) { Util.Free(utf8InputBytes); Util.Free(originalUtf8InputBytes); } return result != 0; } public static bool InputTextMultiline( string label, ref string input, uint maxLength, Vector2 size) => InputTextMultiline(label, ref input, maxLength, size, 0, null, IntPtr.Zero); public static bool InputTextMultiline( string label, ref string input, uint maxLength, Vector2 size, ImGuiInputTextFlags flags) => InputTextMultiline(label, ref input, maxLength, size, flags, null, IntPtr.Zero); public static bool InputTextMultiline( string label, ref string input, uint maxLength, Vector2 size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback) => InputTextMultiline(label, ref input, maxLength, size, flags, callback, IntPtr.Zero); public static bool InputTextMultiline( string label, ref string input, uint maxLength, Vector2 size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, IntPtr user_data) { int utf8LabelByteCount = Encoding.UTF8.GetByteCount(label); byte* utf8LabelBytes; if (utf8LabelByteCount > Util.StackAllocationSizeLimit) { utf8LabelBytes = Util.Allocate(utf8LabelByteCount + 1); } else { byte* stackPtr = stackalloc byte[utf8LabelByteCount + 1]; utf8LabelBytes = stackPtr; } Util.GetUtf8(label, utf8LabelBytes, utf8LabelByteCount); int utf8InputByteCount = Encoding.UTF8.GetByteCount(input); int inputBufSize = Math.Max((int)maxLength + 1, utf8InputByteCount + 1); byte* utf8InputBytes; byte* originalUtf8InputBytes; if (inputBufSize > Util.StackAllocationSizeLimit) { utf8InputBytes = Util.Allocate(inputBufSize); originalUtf8InputBytes = Util.Allocate(inputBufSize); } else { byte* inputStackBytes = stackalloc byte[inputBufSize]; utf8InputBytes = inputStackBytes; byte* originalInputStackBytes = stackalloc byte[inputBufSize]; originalUtf8InputBytes = originalInputStackBytes; } Util.GetUtf8(input, utf8InputBytes, inputBufSize); uint clearBytesCount = (uint)(inputBufSize - utf8InputByteCount); Unsafe.InitBlockUnaligned(utf8InputBytes + utf8InputByteCount, 0, clearBytesCount); Unsafe.CopyBlock(originalUtf8InputBytes, utf8InputBytes, (uint)inputBufSize); byte result = ImGuiNative.igInputTextMultiline( utf8LabelBytes, utf8InputBytes, (uint)inputBufSize, size, flags, callback, user_data.ToPointer()); if (!Util.AreStringsEqual(originalUtf8InputBytes, inputBufSize, utf8InputBytes)) { input = Util.StringFromPtr(utf8InputBytes); } if (utf8LabelByteCount > Util.StackAllocationSizeLimit) { Util.Free(utf8LabelBytes); } if (inputBufSize > Util.StackAllocationSizeLimit) { Util.Free(utf8InputBytes); Util.Free(originalUtf8InputBytes); } return result != 0; } public static bool InputTextWithHint( string label, string hint, ref string input, uint maxLength) => InputTextWithHint(label, hint, ref input, maxLength, 0, null, IntPtr.Zero); public static bool InputTextWithHint( string label, string hint, ref string input, uint maxLength, ImGuiInputTextFlags flags) => InputTextWithHint(label, hint, ref input, maxLength, flags, null, IntPtr.Zero); public static bool InputTextWithHint( string label, string hint, ref string input, uint maxLength, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback) => InputTextWithHint(label, hint, ref input, maxLength, flags, callback, IntPtr.Zero); public static bool InputTextWithHint( string label, string hint, ref string input, uint maxLength, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, IntPtr user_data) { int utf8LabelByteCount = Encoding.UTF8.GetByteCount(label); byte* utf8LabelBytes; if (utf8LabelByteCount > Util.StackAllocationSizeLimit) { utf8LabelBytes = Util.Allocate(utf8LabelByteCount + 1); } else { byte* stackPtr = stackalloc byte[utf8LabelByteCount + 1]; utf8LabelBytes = stackPtr; } Util.GetUtf8(label, utf8LabelBytes, utf8LabelByteCount); int utf8HintByteCount = Encoding.UTF8.GetByteCount(hint); byte* utf8HintBytes; if (utf8HintByteCount > Util.StackAllocationSizeLimit) { utf8HintBytes = Util.Allocate(utf8HintByteCount + 1); } else { byte* stackPtr = stackalloc byte[utf8HintByteCount + 1]; utf8HintBytes = stackPtr; } Util.GetUtf8(hint, utf8HintBytes, utf8HintByteCount); int utf8InputByteCount = Encoding.UTF8.GetByteCount(input); int inputBufSize = Math.Max((int)maxLength + 1, utf8InputByteCount + 1); byte* utf8InputBytes; byte* originalUtf8InputBytes; if (inputBufSize > Util.StackAllocationSizeLimit) { utf8InputBytes = Util.Allocate(inputBufSize); originalUtf8InputBytes = Util.Allocate(inputBufSize); } else { byte* inputStackBytes = stackalloc byte[inputBufSize]; utf8InputBytes = inputStackBytes; byte* originalInputStackBytes = stackalloc byte[inputBufSize]; originalUtf8InputBytes = originalInputStackBytes; } Util.GetUtf8(input, utf8InputBytes, inputBufSize); uint clearBytesCount = (uint)(inputBufSize - utf8InputByteCount); Unsafe.InitBlockUnaligned(utf8InputBytes + utf8InputByteCount, 0, clearBytesCount); Unsafe.CopyBlock(originalUtf8InputBytes, utf8InputBytes, (uint)inputBufSize); byte result = ImGuiNative.igInputTextWithHint( utf8LabelBytes, utf8HintBytes, utf8InputBytes, (uint)inputBufSize, flags, callback, user_data.ToPointer()); if (!Util.AreStringsEqual(originalUtf8InputBytes, inputBufSize, utf8InputBytes)) { input = Util.StringFromPtr(utf8InputBytes); } if (utf8LabelByteCount > Util.StackAllocationSizeLimit) { Util.Free(utf8LabelBytes); } if (utf8HintByteCount > Util.StackAllocationSizeLimit) { Util.Free(utf8HintBytes); } if (inputBufSize > Util.StackAllocationSizeLimit) { Util.Free(utf8InputBytes); Util.Free(originalUtf8InputBytes); } return result != 0; } public static Vector2 CalcTextSize(string text) => CalcTextSizeImpl(text); public static Vector2 CalcTextSize(string text, int start) => CalcTextSizeImpl(text, start); public static Vector2 CalcTextSize(string text, float wrapWidth) => CalcTextSizeImpl(text, wrapWidth: wrapWidth); public static Vector2 CalcTextSize(string text, bool hideTextAfterDoubleHash) => CalcTextSizeImpl(text, hideTextAfterDoubleHash: hideTextAfterDoubleHash); public static Vector2 CalcTextSize(string text, int start, int length) => CalcTextSizeImpl(text, start, length); public static Vector2 CalcTextSize(string text, int start, bool hideTextAfterDoubleHash) => CalcTextSizeImpl(text, start, hideTextAfterDoubleHash: hideTextAfterDoubleHash); public static Vector2 CalcTextSize(string text, int start, float wrapWidth) => CalcTextSizeImpl(text, start, wrapWidth: wrapWidth); public static Vector2 CalcTextSize(string text, bool hideTextAfterDoubleHash, float wrapWidth) => CalcTextSizeImpl(text, hideTextAfterDoubleHash: hideTextAfterDoubleHash, wrapWidth: wrapWidth); public static Vector2 CalcTextSize(string text, int start, int length, bool hideTextAfterDoubleHash) => CalcTextSizeImpl(text, start, length, hideTextAfterDoubleHash); public static Vector2 CalcTextSize(string text, int start, int length, float wrapWidth) => CalcTextSizeImpl(text, start, length, wrapWidth: wrapWidth); public static Vector2 CalcTextSize(string text, int start, int length, bool hideTextAfterDoubleHash, float wrapWidth) => CalcTextSizeImpl(text, start, length, hideTextAfterDoubleHash, wrapWidth); private static Vector2 CalcTextSizeImpl( string text, int start = 0, int? length = null, bool hideTextAfterDoubleHash = false, float wrapWidth = -1.0f) { Vector2 ret; byte* nativeTextStart = null; byte* nativeTextEnd = null; int textByteCount = 0; if (text != null) { int textToCopyLen = length.HasValue ? length.Value : text.Length; textByteCount = Util.CalcSizeInUtf8(text, start, textToCopyLen); if (textByteCount > Util.StackAllocationSizeLimit) { nativeTextStart = Util.Allocate(textByteCount + 1); } else { byte* nativeTextStackBytes = stackalloc byte[textByteCount + 1]; nativeTextStart = nativeTextStackBytes; } int nativeTextOffset = Util.GetUtf8(text, start, textToCopyLen, nativeTextStart, textByteCount); nativeTextStart[nativeTextOffset] = 0; nativeTextEnd = nativeTextStart + nativeTextOffset; } ImGuiNative.igCalcTextSize(&ret, nativeTextStart, nativeTextEnd, *((byte*)(&hideTextAfterDoubleHash)), wrapWidth); if (textByteCount > Util.StackAllocationSizeLimit) { Util.Free(nativeTextStart); } return ret; } public static bool InputText( string label, IntPtr buf, uint buf_size) { return InputText(label, buf, buf_size, 0, null, IntPtr.Zero); } public static bool InputText( string label, IntPtr buf, uint buf_size, ImGuiInputTextFlags flags) { return InputText(label, buf, buf_size, flags, null, IntPtr.Zero); } public static bool InputText( string label, IntPtr buf, uint buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback) { return InputText(label, buf, buf_size, flags, callback, IntPtr.Zero); } public static bool InputText( string label, IntPtr buf, uint buf_size, ImGuiInputTextFlags flags, ImGuiInputTextCallback callback, IntPtr user_data) { int utf8LabelByteCount = Encoding.UTF8.GetByteCount(label); byte* utf8LabelBytes; if (utf8LabelByteCount > Util.StackAllocationSizeLimit) { utf8LabelBytes = Util.Allocate(utf8LabelByteCount + 1); } else { byte* stackPtr = stackalloc byte[utf8LabelByteCount + 1]; utf8LabelBytes = stackPtr; } Util.GetUtf8(label, utf8LabelBytes, utf8LabelByteCount); bool ret = ImGuiNative.igInputText(utf8LabelBytes, (byte*)buf.ToPointer(), buf_size, flags, callback, user_data.ToPointer()) != 0; if (utf8LabelByteCount > Util.StackAllocationSizeLimit) { Util.Free(utf8LabelBytes); } return ret; } public static bool Begin(string name, ImGuiWindowFlags flags) { int utf8NameByteCount = Encoding.UTF8.GetByteCount(name); byte* utf8NameBytes; if (utf8NameByteCount > Util.StackAllocationSizeLimit) { utf8NameBytes = Util.Allocate(utf8NameByteCount + 1); } else { byte* stackPtr = stackalloc byte[utf8NameByteCount + 1]; utf8NameBytes = stackPtr; } Util.GetUtf8(name, utf8NameBytes, utf8NameByteCount); byte* p_open = null; byte ret = ImGuiNative.igBegin(utf8NameBytes, p_open, flags); if (utf8NameByteCount > Util.StackAllocationSizeLimit) { Util.Free(utf8NameBytes); } return ret != 0; } public static bool MenuItem(string label, bool enabled) { return MenuItem(label, string.Empty, false, enabled); } } }
37.049904
142
0.572968
[ "MIT" ]
code2X/ImGui.NET
ImGui.NETEx/ImGui/ImGui.Manual.cs
19,305
C#
namespace Lovys.Domain.Web.Response { public partial class AvailabilityResponse { public string Interviewer { get; set; } public AvailabilitySlot[] AvailabilityIntervals { get; set; } } }
27
69
0.680556
[ "Apache-2.0" ]
saintbr/lovys
src/Lovys/domain/Lovys.Domain/Web/Response/AvailabilityResponse.cs
218
C#
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using NuGet.LibraryModel; using NuGet.ProjectModel; using NuGet.Versioning; namespace Microsoft.DotNet.ProjectModel.Graph { public class LockFileLookup { // REVIEW: Case sensitivity? private readonly Dictionary<Tuple<string, NuGetVersion>, LockFileLibrary> _packages; private readonly Dictionary<string, LockFileLibrary> _projects; public LockFileLookup(LockFile lockFile) { _packages = new Dictionary<Tuple<string, NuGetVersion>, LockFileLibrary>(); _projects = new Dictionary<string, LockFileLibrary>(); foreach (var library in lockFile.Libraries) { var libraryType = LibraryType.Parse(library.Type); if (libraryType == LibraryType.Package) { _packages[Tuple.Create(library.Name, library.Version)] = library; } if (libraryType == LibraryType.Project) { _projects[library.Name] = library; } } } public LockFileLibrary GetProject(string name) { LockFileLibrary project; if (_projects.TryGetValue(name, out project)) { return project; } return null; } public LockFileLibrary GetPackage(string id, NuGetVersion version) { LockFileLibrary package; if (_packages.TryGetValue(Tuple.Create(id, version), out package)) { return package; } return null; } public void Clear() { _packages.Clear(); _projects.Clear(); } } }
29.343284
101
0.57528
[ "MIT" ]
filipw/cli
src/Microsoft.DotNet.ProjectModel/Graph/LockFileLookup.cs
1,968
C#
using System; using System.Collections.Generic; using System.Text; namespace SpeedRunners.Model.User { public class MAccessToken { public int TokenID { get; set; } public string PlatformID { get; set; } public string Browser { get; set; } public string Token { get; set; } public DateTime LoginDate { get; set; } public string ExToken { get; set; } } }
24.411765
47
0.626506
[ "MIT" ]
TinyMaD/SpeedRunnersLab
SpeedRunners.API/SpeedRunners.Model/User/MAccessToken.cs
417
C#
using System.Diagnostics.CodeAnalysis; using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace CaptainHook.Api { /// <summary> /// Swagger factory /// </summary> [ExcludeFromCodeCoverage] public class SwaggerHostFactory { /// <summary> /// Create host /// </summary> /// <returns></returns> public static IHost CreateHost() { return Host .CreateDefaultBuilder() .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(w => w.UseStartup<Startup>()) .Build(); } } }
27.074074
79
0.601915
[ "MIT" ]
eShopWorld/captain-hook
src/CaptainHook.Api/SwaggerHostFactory.cs
733
C#
namespace dnlib.DotNet { /// <summary> /// See CorHdr.h/CorElementType /// </summary> public enum ElementType : byte { /// <summary /> End = 0x00, /// <summary>System.Void</summary> Void = 0x01, /// <summary>System.Boolean</summary> Boolean = 0x02, /// <summary>System.Char</summary> Char = 0x03, /// <summary>System.SByte</summary> I1 = 0x04, /// <summary>System.Byte</summary> U1 = 0x05, /// <summary>System.Int16</summary> I2 = 0x06, /// <summary>System.UInt16</summary> U2 = 0x07, /// <summary>System.Int32</summary> I4 = 0x08, /// <summary>System.UInt32</summary> U4 = 0x09, /// <summary>System.Int64</summary> I8 = 0x0A, /// <summary>System.UInt64</summary> U8 = 0x0B, /// <summary>System.Single</summary> R4 = 0x0C, /// <summary>System.Double</summary> R8 = 0x0D, /// <summary>System.String</summary> String = 0x0E, /// <summary>Pointer type (*)</summary> Ptr = 0x0F, /// <summary>ByRef type (&amp;)</summary> ByRef = 0x10, /// <summary>Value type</summary> ValueType = 0x11, /// <summary>Reference type</summary> Class = 0x12, /// <summary>Type generic parameter</summary> Var = 0x13, /// <summary>Multidimensional array ([*], [,], [,,], ...)</summary> Array = 0x14, /// <summary>Generic instance type</summary> GenericInst = 0x15, /// <summary>Typed byref</summary> TypedByRef = 0x16, /// <summary>Value array (don't use)</summary> ValueArray = 0x17, /// <summary>System.IntPtr</summary> I = 0x18, /// <summary>System.UIntPtr</summary> U = 0x19, /// <summary>native real (don't use)</summary> R = 0x1A, /// <summary>Function pointer</summary> FnPtr = 0x1B, /// <summary>System.Object</summary> Object = 0x1C, /// <summary>Single-dimension, zero lower bound array ([])</summary> SZArray = 0x1D, /// <summary>Method generic parameter</summary> MVar = 0x1E, /// <summary>Required C modifier</summary> CModReqd = 0x1F, /// <summary>Optional C modifier</summary> CModOpt = 0x20, /// <summary>Used internally by the CLR (don't use)</summary> Internal = 0x21, /// <summary>Module (don't use)</summary> Module = 0x3F, /// <summary>Sentinel (method sigs only)</summary> Sentinel = 0x41, /// <summary>Pinned type (locals only)</summary> Pinned = 0x45 } public static partial class Extensions { /// <summary> /// Returns <c>true</c> if it's an integer or a floating point type /// </summary> /// <param name="etype">Element type</param> /// <returns></returns> public static bool IsPrimitive(this ElementType etype) { switch(etype) { case ElementType.Boolean: case ElementType.Char: case ElementType.I1: case ElementType.U1: case ElementType.I2: case ElementType.U2: case ElementType.I4: case ElementType.U4: case ElementType.I8: case ElementType.U8: case ElementType.R4: case ElementType.R8: case ElementType.I: case ElementType.U: case ElementType.R: return true; default: return false; } } /// <summary> /// Returns the size of the element type in bytes or <c>-1</c> if it's unknown /// </summary> /// <param name="etype">Element type</param> /// <returns></returns> public static int GetPrimitiveSize(this ElementType etype) { return GetPrimitiveSize(etype, -1); } /// <summary> /// Returns the size of the element type in bytes or <c>-1</c> if it's unknown /// </summary> /// <param name="etype">Element type</param> /// <param name="ptrSize">Size of a pointer</param> /// <returns></returns> public static int GetPrimitiveSize(this ElementType etype, int ptrSize) { switch(etype) { case ElementType.Boolean: case ElementType.I1: case ElementType.U1: return 1; case ElementType.Char: case ElementType.I2: case ElementType.U2: return 2; case ElementType.I4: case ElementType.U4: case ElementType.R4: return 4; case ElementType.I8: case ElementType.U8: case ElementType.R8: return 8; case ElementType.Ptr: case ElementType.FnPtr: case ElementType.I: case ElementType.U: return ptrSize; default: return -1; } } /// <summary> /// Checks whether it's a value type /// </summary> /// <param name="etype">this</param> /// <returns> /// <c>true</c> if it's a value type, <c>false</c> if it's not a value type or /// if we couldn't determine whether it's a value type. Eg., it could be a generic /// instance type. /// </returns> public static bool IsValueType(this ElementType etype) { switch(etype) { case ElementType.Void: case ElementType.Boolean: case ElementType.Char: case ElementType.I1: case ElementType.U1: case ElementType.I2: case ElementType.U2: case ElementType.I4: case ElementType.U4: case ElementType.I8: case ElementType.U8: case ElementType.R4: case ElementType.R8: case ElementType.ValueType: case ElementType.TypedByRef: case ElementType.ValueArray: case ElementType.I: case ElementType.U: case ElementType.R: return true; case ElementType.GenericInst: // We don't have enough info to determine whether this is a value type return false; case ElementType.End: case ElementType.String: case ElementType.Ptr: case ElementType.ByRef: case ElementType.Class: case ElementType.Var: case ElementType.Array: case ElementType.FnPtr: case ElementType.Object: case ElementType.SZArray: case ElementType.MVar: case ElementType.CModReqd: case ElementType.CModOpt: case ElementType.Internal: case ElementType.Module: case ElementType.Sentinel: case ElementType.Pinned: default: return false; } } } }
29.174242
94
0.487406
[ "MIT" ]
Dekryptor/KoiVM-Virtualization
dnlib/src/DotNet/ElementType.cs
7,704
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Client->Server: Tell server that we joined * Server->Client: Tell the client of its ID and first playerID */ public class EventClientJoined : EventNetwork { public ConnectMenu.PlayerDescriptor[] players; public EventClientJoined() : base((byte)ChampNetPlugin.MessageIDs.ID_CLIENT_JOINED) { } public EventClientJoined(ConnectMenu.PlayerDescriptor[] playerRequests): this() { this.players = playerRequests; } public override int GetSize() { return base.GetSize() + ( sizeof(int) + this.players.Length * (sizeof(int) + (sizeof(char) * GameState.Player.SIZE_MAX_NAME) + (sizeof(float) * 3)) ); } public override void Serialize(ref byte[] data, ref int lastIndex) { base.Serialize(ref data, ref lastIndex); // write # of players WriteTo(ref data, ref lastIndex, System.BitConverter.GetBytes(this.players.Length)); for (int localID = 0; localID < this.players.Length; localID++) { char[] chars = this.players[localID].name.ToCharArray(); WriteTo(ref data, ref lastIndex, System.BitConverter.GetBytes(chars.Length)); for (int i = 0; i < chars.Length; i++) { WriteTo(ref data, ref lastIndex, System.BitConverter.GetBytes(chars[i])); } WriteTo(ref data, ref lastIndex, System.BitConverter.GetBytes(this.players[localID].color.r)); WriteTo(ref data, ref lastIndex, System.BitConverter.GetBytes(this.players[localID].color.g)); WriteTo(ref data, ref lastIndex, System.BitConverter.GetBytes(this.players[localID].color.b)); } } }
31.839286
119
0.641615
[ "Apache-2.0" ]
temportalflux/MultiPoke
Client/Assets/Scripts/Network/events/EventClientJoined.cs
1,785
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace Ejercicio1.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to // application events from iOS. [Register("AppDelegate")] public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate { // // This method is invoked when the application has loaded and is ready to run. In this // method you should instantiate the window, load the UI into it and then make the window // visible. // // You have 17 seconds to return from this method, or iOS will terminate your application. // public override bool FinishedLaunching(UIApplication app, NSDictionary options) { global::Xamarin.Forms.Forms.Init(); LoadApplication(new App()); return base.FinishedLaunching(app, options); } } }
34.40625
98
0.677566
[ "MIT" ]
djhvscf/curso-xamarin
Sesion 2/Sesion 2.2/Ejercicio1/Ejercicio1.iOS/AppDelegate.cs
1,103
C#
// // Copyright 2020 Carbonfrost Systems, Inc. (https://carbonfrost.com) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System.Collections.Generic; using System.Linq; using Carbonfrost.Commons.Spec; using Carbonfrost.Commons.Validation; using Carbonfrost.Commons.Validation.Validators; namespace Carbonfrost.UnitTests.Validation { public class EachKeyValidatorAdapterTests { [XFact(Reason = "Pending localization rules")] public void Validate_should_apply_to_enumerable_as_an_object() { var required = new RequiredValidator(); var validator = Validator.Redirect(required, ValidatorTarget.EachKey); var obj = new Dictionary<string, string> { [""] = "hello", }; var actual = validator.Validate(obj); Assert.Single(actual); Assert.Equal("Keys are required", actual.Values.First().Message); } } }
33.790698
82
0.695802
[ "Apache-2.0" ]
Carbonfrost/f-validation
dotnet/test/Carbonfrost.UnitTests.Validation/EachKeyValidatorAdapterTests.cs
1,453
C#
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Serialization.JsonConverters { // public class DictionaryJsonConverter : // JsonConverter // { // public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) // { // throw new NotSupportedException("This converter should not be used for writing as it can create loops"); // } // // public override object ReadJson(JsonReader reader, Type objectType, object existingValue, // JsonSerializer serializer) // { // Type[] arguments = objectType.GetGenericArguments(); // // Type keyType = arguments[0]; // Type valueType = arguments[1]; // return this.FastInvoke<DictionaryJsonConverter, object>(new[] {keyType, valueType}, "GetDictionary", reader, // objectType, serializer); // } // // public override bool CanConvert(Type objectType) // { // return (objectType.IsGenericType // && (objectType.GetGenericTypeDefinition() == typeof (IDictionary<,>) // || objectType.GetGenericTypeDefinition() == typeof (Dictionary<,>))); // } // // object GetDictionary<TKey, TValue>(JsonReader reader, Type objectType, JsonSerializer serializer) // { // var dictionary = new Dictionary<TKey, TValue>(); // // if (reader.TokenType == JsonToken.Null) // return dictionary; // // serializer.Populate(reader, dictionary); // // return dictionary; // } // } }
43.433962
123
0.612511
[ "Apache-2.0" ]
Johavale19/Johanna
src/MassTransit/Serialization/JsonConverters/DictionaryJsonConverter.cs
2,302
C#
// This file is part of the DisCatSharp project. // // Copyright (c) 2021 AITSYS // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. namespace DisCatSharp { /// <summary> /// Represents the activity this invite is for. /// </summary> public enum TargetActivity : ulong { /// <summary> /// Represents no embedded application. /// </summary> None = 0, /// <summary> /// Represents the embedded application Poker Night. /// </summary> PokerNight = 755827207812677713, /// <summary> /// Represents the embedded application Betrayal.io. /// </summary> Betrayal = 773336526917861400, /// <summary> /// Represents the embedded application Fishington.io. /// </summary> Fishington = 814288819477020702, /// <summary> /// Represents the embedded application YouTube Together. /// </summary> YouTubeTogether = 755600276941176913, /// <summary> /// Represents the embedded application Chess in the park. /// </summary> ChessInThePark = 832012586023256104 } }
35.901639
81
0.671233
[ "Apache-2.0", "MIT" ]
StormDevelopmentSoftware/DSharpPlusNextGen
DisCatSharp/Enums/Invite/TargetActivity.cs
2,190
C#
namespace Passion.Rover.Command.Domain.Events { public class SampleCollected : IEvent { public string Id { get; set; } public string ObjectName { get; set; } public double ObjectAmountAsGram { get; set; } public string GetEventName() { return this.GetType().FullName; } } }
25.428571
54
0.575843
[ "MIT" ]
oktydag/passion
src/Passion.Rover.Command/Domain/Events/SampleCollected.cs
358
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20171001 { public static class GetVirtualNetworkGatewayAdvertisedRoutes { /// <summary> /// List of virtual network gateway routes /// </summary> public static Task<GetVirtualNetworkGatewayAdvertisedRoutesResult> InvokeAsync(GetVirtualNetworkGatewayAdvertisedRoutesArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetVirtualNetworkGatewayAdvertisedRoutesResult>("azure-native:network/v20171001:getVirtualNetworkGatewayAdvertisedRoutes", args ?? new GetVirtualNetworkGatewayAdvertisedRoutesArgs(), options.WithVersion()); } public sealed class GetVirtualNetworkGatewayAdvertisedRoutesArgs : Pulumi.InvokeArgs { /// <summary> /// The IP address of the peer /// </summary> [Input("peer", required: true)] public string Peer { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the virtual network gateway. /// </summary> [Input("virtualNetworkGatewayName", required: true)] public string VirtualNetworkGatewayName { get; set; } = null!; public GetVirtualNetworkGatewayAdvertisedRoutesArgs() { } } [OutputType] public sealed class GetVirtualNetworkGatewayAdvertisedRoutesResult { /// <summary> /// List of gateway routes /// </summary> public readonly ImmutableArray<Outputs.GatewayRouteResponse> Value; [OutputConstructor] private GetVirtualNetworkGatewayAdvertisedRoutesResult(ImmutableArray<Outputs.GatewayRouteResponse> value) { Value = value; } } }
34.904762
260
0.673943
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20171001/GetVirtualNetworkGatewayAdvertisedRoutes.cs
2,199
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Cofoundry.Domain.CQS; namespace Cofoundry.Domain { public class PageVersionEntityDefinition : IDependableEntityDefinition { public const string DefinitionCode = "COFPGV"; public string EntityDefinitionCode { get { return DefinitionCode; } } public string Name { get { return "Page Version"; } } public IQuery<IDictionary<int, RootEntityMicroSummary>> CreateGetEntityMicroSummariesByIdRangeQuery(IEnumerable<int> ids) { return new GetPageVersionEntityMicroSummariesByIdRangeQuery(ids); } } }
28.75
129
0.728986
[ "MIT" ]
CMSCollection/cofoundry
src/Cofoundry.Domain/Domain/Pages/Bootstrap/PageVersionEntityDefinition.cs
692
C#
/* * Copyright 2020 New Relic Corporation. All rights reserved. * SPDX-License-Identifier: Apache-2.0 */ using NewRelic.Agent.Api; using NewRelic.Agent.Configuration; using NewRelic.Agent.Core.AgentHealth; using NewRelic.Agent.Core.Api; using NewRelic.Agent.Core.BrowserMonitoring; using NewRelic.Agent.Core.CallStack; using NewRelic.Agent.Core.Database; using NewRelic.Agent.Core.DistributedTracing; using NewRelic.Agent.Core.Errors; using NewRelic.Agent.Core.Metric; using NewRelic.Agent.Core.Metrics; using NewRelic.Agent.Core.Attributes; using NewRelic.Agent.Core.Segments; using NewRelic.Agent.Core.Segments.Tests; using NewRelic.Agent.Core.Timing; using NewRelic.Agent.Core.Transactions; using NewRelic.Agent.Core.Transformers.TransactionTransformer; using NewRelic.Agent.Core.Utilities; using NewRelic.Agent.Core.Wrapper.AgentWrapperApi.Builders; using NewRelic.Agent.Core.Wrapper.AgentWrapperApi.CrossApplicationTracing; using NewRelic.Agent.Core.Wrapper.AgentWrapperApi.Data; using NewRelic.Agent.Core.Wrapper.AgentWrapperApi.Synthetics; using NewRelic.Agent.Extensions.Providers.Wrapper; using NewRelic.Core.DistributedTracing; using NewRelic.SystemExtensions.Collections.Generic; using NewRelic.SystemInterfaces; using NewRelic.Testing.Assertions; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using Telerik.JustMock; using NewRelic.Agent.Api.Experimental; using NewRelic.Agent.Core.Spans; using NewRelic.Agent.TestUtilities; namespace NewRelic.Agent.Core.Wrapper.AgentWrapperApi { [TestFixture] public class AgentWrapperApiTests { private IInternalTransaction _transaction; private ITransactionService _transactionService; private IAgent _agent; private ITransactionTransformer _transactionTransformer; private ICallStackManager _callStackManager; private ITransactionMetricNameMaker _transactionMetricNameMaker; private IPathHashMaker _pathHashMaker; private ICatHeaderHandler _catHeaderHandler; private IDistributedTracePayloadHandler _distributedTracePayloadHandler; private ISyntheticsHeaderHandler _syntheticsHeaderHandler; private ITransactionFinalizer _transactionFinalizer; private IBrowserMonitoringPrereqChecker _browserMonitoringPrereqChecker; private IBrowserMonitoringScriptMaker _browserMonitoringScriptMaker; private IConfigurationService _configurationService; private IAgentHealthReporter _agentHealthReporter; private ITraceMetadataFactory _traceMetadataFactory; private ICATSupportabilityMetricCounters _catMetrics; private IThreadPoolStatic _threadPoolStatic; private IAgentTimerService _agentTimerService; private IMetricNameService _metricNameService; private IErrorService _errorService; private IAttributeDefinitionService _attribDefSvc; private IAttributeDefinitions _attribDefs => _attribDefSvc.AttributeDefs; private const string DistributedTraceHeaderName = "newrelic"; private const string ReferrerTripId = "referrerTripId"; private const string ReferrerPathHash = "referrerPathHash"; private const string ReferrerTransactionGuid = "referrerTransactionGuid"; private const string ReferrerProcessId = "referrerProcessId"; [SetUp] public void SetUp() { _callStackManager = Mock.Create<ICallStackManager>(); _transaction = Mock.Create<IInternalTransaction>(); var transactionSegmentState = TransactionSegmentStateHelpers.GetItransactionSegmentState(); Mock.Arrange(() => _transaction.CallStackManager).Returns(_callStackManager); Mock.Arrange(() => _transaction.GetTransactionSegmentState()).Returns(transactionSegmentState); Mock.Arrange(() => _transaction.Finish()).Returns(true); // grr. mocking is stupid Mock.Arrange(() => transactionSegmentState.CallStackPush(Arg.IsAny<Segment>())) .DoInstead<Segment>((segment) => _callStackManager.Push(segment.UniqueId)); Mock.Arrange(() => transactionSegmentState.CallStackPop(Arg.IsAny<Segment>(), Arg.IsAny<bool>())) .DoInstead<Segment>((segment) => _callStackManager.TryPop(segment.UniqueId, segment.ParentUniqueId)); Mock.Arrange(() => transactionSegmentState.ParentSegmentId()).Returns(_callStackManager.TryPeek); _transactionService = Mock.Create<ITransactionService>(); Mock.Arrange(() => _transactionService.GetCurrentInternalTransaction()).Returns(_transaction); _transactionTransformer = Mock.Create<ITransactionTransformer>(); _threadPoolStatic = Mock.Create<IThreadPoolStatic>(); Mock.Arrange(() => _threadPoolStatic.QueueUserWorkItem(Arg.IsAny<WaitCallback>())) .DoInstead<WaitCallback>(callback => callback(null)); Mock.Arrange(() => _threadPoolStatic.QueueUserWorkItem(Arg.IsAny<WaitCallback>(), Arg.IsAny<object>())) .DoInstead<WaitCallback, object>((callback, state) => callback(state)); _transactionMetricNameMaker = Mock.Create<ITransactionMetricNameMaker>(); _pathHashMaker = Mock.Create<IPathHashMaker>(); _catHeaderHandler = Mock.Create<ICatHeaderHandler>(); _syntheticsHeaderHandler = Mock.Create<ISyntheticsHeaderHandler>(); _transactionFinalizer = Mock.Create<ITransactionFinalizer>(); _browserMonitoringPrereqChecker = Mock.Create<IBrowserMonitoringPrereqChecker>(); _browserMonitoringScriptMaker = Mock.Create<IBrowserMonitoringScriptMaker>(); _configurationService = Mock.Create<IConfigurationService>(); _agentHealthReporter = Mock.Create<IAgentHealthReporter>(); _agentTimerService = Mock.Create<IAgentTimerService>(); _agentTimerService = Mock.Create<IAgentTimerService>(); _metricNameService = new MetricNameService(); _catMetrics = Mock.Create<ICATSupportabilityMetricCounters>(); _distributedTracePayloadHandler = Mock.Create<IDistributedTracePayloadHandler>(); _traceMetadataFactory = Mock.Create<ITraceMetadataFactory>(); _errorService = new ErrorService(_configurationService); _attribDefSvc = new AttributeDefinitionService((f) => new AttributeDefinitions(f)); _agent = new Agent(_transactionService, _transactionTransformer, _threadPoolStatic, _transactionMetricNameMaker, _pathHashMaker, _catHeaderHandler, _distributedTracePayloadHandler, _syntheticsHeaderHandler, _transactionFinalizer, _browserMonitoringPrereqChecker, _browserMonitoringScriptMaker, _configurationService, _agentHealthReporter, _agentTimerService, _metricNameService, _traceMetadataFactory, _catMetrics); } private class CallStackManagerFactory : ICallStackManagerFactory { private readonly ICallStackManager _callStackManager; public CallStackManagerFactory(ICallStackManager callStackManager) { _callStackManager = callStackManager; } public ICallStackManager CreateCallStackManager() { return _callStackManager; } } #region EndTransaction [Test] public void EndTransaction_DoesNotCallsTransactionTransformer_IfThereIsStillWorkToDo() { Mock.Arrange(() => _transaction.NoticeUnitOfWorkEnds()).Returns(1); _agent.CurrentTransaction.End(); Mock.Assert(() => _transactionTransformer.Transform(Arg.IsAny<IInternalTransaction>()), Occurs.Never()); } [Test] public void EndTransaction_CallsTransactionTransformer_WithBuiltImmutableTransaction() { SetupTransaction(); Mock.Arrange(() => _transactionFinalizer.Finish(_transaction)).Returns(true); _agent.CurrentTransaction.End(); Mock.Assert(() => _transactionTransformer.Transform(_transaction)); } [Test] public void EndTransaction_DoesNotCallTransactionTransformer_IfTransactionWasNotFinished() { Mock.Arrange(() => _transactionFinalizer.Finish(_transaction)).Returns(false); _agent.CurrentTransaction.End(); Mock.Assert(() => _transactionTransformer.Transform(Arg.IsAny<IInternalTransaction>()), Occurs.Never()); } [Test] public void EndTransaction_CallsTransactionBuilderFinalizer() { SetupTransaction(); _agent.CurrentTransaction.End(); Mock.Assert(() => _transactionFinalizer.Finish(_transaction)); } [Test] public void EndTransaction_ShouldNotLogResponseTimeAlreadyCaptured() { Mock.Arrange(() => _transaction.TryCaptureResponseTime()).Returns(true); using (var logging = new TestUtilities.Logging()) { _agent.CurrentTransaction.End(); var foundResponseTimeAlreadyCapturedMessage = logging.HasMessageBeginingWith("Transaction has already captured the response time."); Assert.False(foundResponseTimeAlreadyCapturedMessage); } } [Test] public void EndTransaction_ShouldLogResponseTimeAlreadyCaptured() { SetupTransaction(); using (var logging = new TestUtilities.Logging()) { _agent.CurrentTransaction.End(); _agent.CurrentTransaction.End(); var foundResponseTimeAlreadyCapturedMessage = logging.HasMessageThatContains("Transaction has already captured the response time."); Assert.True(foundResponseTimeAlreadyCapturedMessage); } } #endregion EndTransaction #region Transaction metadata [Test] public void IgnoreTransaction_IgnoresTransaction() { _agent.CurrentTransaction.Ignore(); Mock.Assert(() => _transaction.Ignore()); } [Test] public void SetWebTransactionName_SetsWebTransactionName() { const TransactionNamePriority priority = TransactionNamePriority.FrameworkHigh; SetupTransaction(); _agent.CurrentTransaction.SetWebTransactionName(WebTransactionType.MVC, "foo", priority); var addedTransactionName = _transaction.CandidateTransactionName.CurrentTransactionName; Assert.AreEqual("MVC", addedTransactionName.Category); Assert.AreEqual("foo", addedTransactionName.Name); } [Test] public void SetWebTransactionNameFromPath_SetsUriTransactionName() { SetupTransaction(); _agent.CurrentTransaction.SetWebTransactionNameFromPath(WebTransactionType.MVC, "some/path"); var addedTransactionName = _transaction.CandidateTransactionName.CurrentTransactionName; Assert.AreEqual("Uri/some/path", addedTransactionName.UnprefixedName); Assert.AreEqual(true, addedTransactionName.IsWeb); } [Test] public void SetMessageBrokerTransactionName_SetsMessageBrokerTransactionName() { const TransactionNamePriority priority = TransactionNamePriority.FrameworkHigh; SetupTransaction(); _agent.CurrentTransaction.SetMessageBrokerTransactionName(MessageBrokerDestinationType.Topic, "broker", "dest", priority); var addedTransactionName = _transaction.CandidateTransactionName.CurrentTransactionName; Assert.AreEqual("Message/broker/Topic/Named/dest", addedTransactionName.UnprefixedName); Assert.AreEqual(false, addedTransactionName.IsWeb); } [Test] public void SetOtherTransactionName_SetsOtherTransactionName() { const TransactionNamePriority priority = TransactionNamePriority.FrameworkHigh; SetupTransaction(); _agent.CurrentTransaction.SetOtherTransactionName("cat", "foo", priority); var addedTransactionName = _transaction.CandidateTransactionName.CurrentTransactionName; Assert.AreEqual("cat/foo", addedTransactionName.UnprefixedName); Assert.AreEqual(false, addedTransactionName.IsWeb); } [Test] public void SetCustomTransactionName_SetsCustomTransactionName() { SetupTransaction(); _agent.CurrentTransaction.SetOtherTransactionName("bar", "foo", TransactionNamePriority.Uri); _agent.CurrentTransaction.SetCustomTransactionName("foo", TransactionNamePriority.StatusCode); var addedTransactionName = _transaction.CandidateTransactionName.CurrentTransactionName; Assert.AreEqual("Custom/foo", addedTransactionName.UnprefixedName); Assert.AreEqual(false, addedTransactionName.IsWeb); } [Test] public void SetTransactionUri_SetsTransactionUri() { SetupTransaction(); _agent.CurrentTransaction.SetUri("foo"); Assert.AreEqual("foo", _transaction.TransactionMetadata.Uri); } [Test] public void SetTransactionOriginalUri_SetsTransactionOriginalUri() { SetupTransaction(); _agent.CurrentTransaction.SetOriginalUri("foo"); Assert.AreEqual("foo", _transaction.TransactionMetadata.OriginalUri); } [Test] public void SetTransactionReferrerUri_SetsTransactionReferrerUri() { SetupTransaction(); _agent.CurrentTransaction.SetReferrerUri("foo"); Assert.AreEqual("foo", _transaction.TransactionMetadata.ReferrerUri); } [Test] public void SetTransactionQueueTime_SetsTransactionQueueTime() { SetupTransaction(); _agent.CurrentTransaction.SetQueueTime(TimeSpan.FromSeconds(4)); Assert.AreEqual(TimeSpan.FromSeconds(4), _transaction.TransactionMetadata.QueueTime); } [Test] public void SetTransactionRequestParameters_SetsTransactionRequestParameters_ForRequestBucket() { SetupTransaction(); var parameters = new Dictionary<string, string> { { "key", "value" } }; _agent.CurrentTransaction.SetRequestParameters(parameters); Assert.AreEqual(1, _transaction.TransactionMetadata.RequestParameters.Length); Assert.AreEqual("key", _transaction.TransactionMetadata.RequestParameters[0].Key); Assert.AreEqual("value", _transaction.TransactionMetadata.RequestParameters[0].Value); } [Test] public void SetTransactionRequestParameters_SetMultipleRequestParameters() { SetupTransaction(); var parameters = new Dictionary<string, string> { { "firstName", "Jane" }, { "lastName", "Doe" } }; _agent.CurrentTransaction.SetRequestParameters(parameters); var result = _transaction.TransactionMetadata.RequestParameters.ToDictionary(); Assert.AreEqual(2, _transaction.TransactionMetadata.RequestParameters.Length); Assert.Contains("firstName", result.Keys); Assert.Contains("lastName", result.Keys); Assert.Contains("Jane", result.Values); Assert.Contains("Doe", result.Values); } [Test] public void SetTransactionHttpResponseStatusCode_SetsTransactionHttpResponseStatusCode() { SetupTransaction(); _agent.CurrentTransaction.SetHttpResponseStatusCode(1, 2); var immutableTransactionMetadata = _transaction.TransactionMetadata.ConvertToImmutableMetadata(); Assert.AreEqual(1, immutableTransactionMetadata.HttpResponseStatusCode); Assert.AreEqual(2, immutableTransactionMetadata.HttpResponseSubStatusCode); } #endregion Transaction metadata #region Segments [Test] public void StartTransactionSegment_ReturnsAnOpaqueSimpleSegmentBuilder() { SetupTransaction(); var expectedParentId = 1; Mock.Arrange(() => _callStackManager.TryPeek()).Returns(expectedParentId); var invocationTarget = new object(); var method = new Method(typeof(string), "methodName", "parameterTypeNames"); var methodCall = new MethodCall(method, invocationTarget, new object[0]); var opaqueSegment = _agent.CurrentTransaction.StartTransactionSegment(methodCall, "foo"); Assert.NotNull(opaqueSegment); var segment = opaqueSegment as Segment; Assert.NotNull(segment); var immutableSegment = segment as Segment; var simpleSegmentData = immutableSegment.Data as SimpleSegmentData; NrAssert.Multiple( () => Assert.NotNull(immutableSegment.UniqueId), () => Assert.AreEqual(expectedParentId, immutableSegment.ParentUniqueId), () => Assert.AreEqual("foo", simpleSegmentData?.Name), () => Assert.AreEqual("System.String", immutableSegment.MethodCallData.TypeName), () => Assert.AreEqual("methodName", immutableSegment.MethodCallData.MethodName), () => Assert.AreEqual(RuntimeHelpers.GetHashCode(invocationTarget), immutableSegment.MethodCallData.InvocationTargetHashCode) ); } [Test] public void StartTransactionSegment_PushesNewSegmentUniqueIdToCallStack() { SetupTransaction(); var pushedUniqueId = (object)null; Mock.Arrange(() => _callStackManager.Push(Arg.IsAny<int>())) .DoInstead<object>(pushed => pushedUniqueId = pushed); var opaqueSegment = _agent.CurrentTransaction.StartTransactionSegment(new MethodCall(new Method(typeof(string), "", ""), "", new object[0]), "foo"); Assert.NotNull(opaqueSegment); var segment = opaqueSegment as Segment; Assert.NotNull(segment); var immutableSegment = segment as Segment; Assert.AreEqual(pushedUniqueId, immutableSegment.UniqueId); } [Test] public void StartExternalSegment_Throws_IfUriIsNotAbsolute() { SetupTransaction(); var uri = new Uri("/test", UriKind.Relative); NrAssert.Throws<ArgumentException>(() => _agent.CurrentTransaction.StartExternalRequestSegment(new MethodCall(new Method(typeof(string), "", ""), "", new object[0]), uri, "GET")); } #endregion Segments #region EndSegment [Test] public void EndSegment_RemovesSegmentFromCallStack() { SetupTransaction(); var opaqueSegment = _agent.CurrentTransaction.StartTransactionSegment(new MethodCall(new Method(typeof(string), "", ""), "", new object[0]), "foo"); var segment = opaqueSegment as Segment; var expectedUniqueId = segment.UniqueId; var expectedParentId = segment.ParentUniqueId; segment.End(); Mock.Assert(() => _callStackManager.TryPop(expectedUniqueId, expectedParentId), Occurs.Once()); } #endregion EndSegment #region NoticeError [Test] public void NoticeError_SendsErrorDataToTransactionBuilder() { SetupTransaction(); var now = DateTime.UtcNow; var exception = NotNewRelic.ExceptionBuilder.BuildException("My message"); _agent.CurrentTransaction.NoticeError(exception); var immutableTransactionMetadata = _transaction.TransactionMetadata.ConvertToImmutableMetadata(); var errorData = immutableTransactionMetadata.ReadOnlyTransactionErrorState.ErrorData; NrAssert.Multiple( () => Assert.AreEqual("My message", errorData.ErrorMessage), () => Assert.AreEqual("System.Exception", errorData.ErrorTypeName), () => Assert.IsTrue(errorData.StackTrace?.Contains("NotNewRelic.ExceptionBuilder.BuildException") == true), () => Assert.IsTrue(errorData.NoticedAt >= now && errorData.NoticedAt < now.AddMinutes(1)) ); } #endregion NoticeError #region inbound CAT request - outbound CAT response [Test] public void AcceptDistributedTraceHeaders_SetsReferrerCrossProcessId() { SetupTransaction(); Mock.Arrange(() => _catHeaderHandler.TryDecodeInboundRequestHeadersForCrossProcessId(Arg.IsAny<Dictionary<string, string>>(), Arg.IsAny<Func<Dictionary<string, string>, string, IEnumerable<string>>>())) .Returns(ReferrerProcessId); var headers = new Dictionary<string, string>(); _agent.CurrentTransaction.AcceptDistributedTraceHeaders(headers, HeaderFunctions.GetHeaders, TransportType.HTTP); Assert.AreEqual(ReferrerProcessId, _transaction.TransactionMetadata.CrossApplicationReferrerProcessId, $"CrossApplicationReferrerProcessId"); } [Test] public void AcceptDistributedTraceHeaders_SetsTransactionData() { SetupTransaction(); var catRequestData = new CrossApplicationRequestData(ReferrerTransactionGuid, false, ReferrerTripId, ReferrerPathHash); Mock.Arrange(() => _catHeaderHandler.TryDecodeInboundRequestHeaders(Arg.IsAny<Dictionary<string, string>>(), Arg.IsAny<Func<Dictionary<string, string>, string, IEnumerable<string>>>())) .Returns(catRequestData); var headers = new Dictionary<string, string>(); _agent.CurrentTransaction.AcceptDistributedTraceHeaders(headers, HeaderFunctions.GetHeaders, TransportType.HTTP); Assert.AreEqual(ReferrerTripId, _transaction.TransactionMetadata.CrossApplicationReferrerTripId, $"CrossApplicationReferrerTripId"); Assert.AreEqual(ReferrerPathHash, _transaction.TransactionMetadata.CrossApplicationReferrerPathHash, $"CrossApplicationReferrerPathHash"); Assert.AreEqual(ReferrerTransactionGuid, _transaction.TransactionMetadata.CrossApplicationReferrerTransactionGuid, $"CrossApplicationReferrerTransactionGuid"); } [Test] public void AcceptDistributedTraceHeaders_SetsTransactionData_WithContentLength() { SetupTransaction(); var catRequestData = new CrossApplicationRequestData("referrerTransactionGuid", false, "referrerTripId", "referrerPathHash"); Mock.Arrange(() => _catHeaderHandler.TryDecodeInboundRequestHeaders(Arg.IsAny<Dictionary<string, string>>(), Arg.IsAny<Func<Dictionary<string, string>, string, IEnumerable<string>>>())) .Returns(catRequestData); var headers = new Dictionary<string, string>() { { "Content-Length", "200" } }; var transactionExperimental = _agent.CurrentTransaction.GetExperimentalApi(); _agent.CurrentTransaction.AcceptDistributedTraceHeaders(headers, HeaderFunctions.GetHeaders, TransportType.HTTP); Assert.AreEqual(ReferrerTripId, _transaction.TransactionMetadata.CrossApplicationReferrerTripId, $"CrossApplicationReferrerTripId"); Assert.AreEqual(200, _transaction.TransactionMetadata.GetCrossApplicationReferrerContentLength(), $"CrossApplicationContentLength"); Assert.AreEqual(ReferrerPathHash, _transaction.TransactionMetadata.CrossApplicationReferrerPathHash, $"CrossApplicationReferrerPathHash"); Assert.AreEqual(ReferrerTransactionGuid, _transaction.TransactionMetadata.CrossApplicationReferrerTransactionGuid, $"CrossApplicationReferrerTransactionGuid"); } [Test] public void AcceptDistributedTraceHeaders_DoesNotSetTransactionDataIfCrossProcessIdAlreadyExists() { SetupTransaction(); var newReferrerProcessId = "newProcessId"; var newReferrerTransactionGuid = "newTxGuid"; var newReferrerTripId = "newTripId"; var newReferrerPathHash = "newPathHash"; // first request to set TransactionMetadata var catRequestData = new CrossApplicationRequestData(ReferrerTransactionGuid, false, ReferrerTripId, ReferrerPathHash); Mock.Arrange(() => _catHeaderHandler.TryDecodeInboundRequestHeaders(Arg.IsAny<Dictionary<string, string>>(), Arg.IsAny<Func<Dictionary<string, string>, string, IEnumerable<string>>>())) .Returns(catRequestData); Mock.Arrange(() => _catHeaderHandler.TryDecodeInboundRequestHeadersForCrossProcessId(Arg.IsAny<Dictionary<string, string>>(), Arg.IsAny<Func<Dictionary<string, string>, string, IEnumerable<string>>>())) .Returns(ReferrerProcessId); var headers = new Dictionary<string, string>(); _agent.CurrentTransaction.AcceptDistributedTraceHeaders(headers, HeaderFunctions.GetHeaders, TransportType.HTTP); // new request catRequestData = new CrossApplicationRequestData(newReferrerTransactionGuid, false, newReferrerTripId, newReferrerPathHash); Mock.Arrange(() => _catHeaderHandler.TryDecodeInboundRequestHeaders(Arg.IsAny<Dictionary<string, string>>(), Arg.IsAny<Func<Dictionary<string, string>, string, IEnumerable<string>>>())) .Returns(catRequestData); Mock.Arrange(() => _catHeaderHandler.TryDecodeInboundRequestHeadersForCrossProcessId(Arg.IsAny<Dictionary<string, string>>(), Arg.IsAny<Func<Dictionary<string, string>, string, IEnumerable<string>>>())) .Returns(newReferrerProcessId); _agent.CurrentTransaction.AcceptDistributedTraceHeaders(headers, HeaderFunctions.GetHeaders, TransportType.HTTP); // values are for first request Assert.AreEqual(ReferrerProcessId, _transaction.TransactionMetadata.CrossApplicationReferrerProcessId, $"CrossApplicationReferrerProcessId"); Assert.AreEqual(ReferrerTripId, _transaction.TransactionMetadata.CrossApplicationReferrerTripId, $"CrossApplicationReferrerTripId"); Assert.AreEqual(ReferrerPathHash, _transaction.TransactionMetadata.CrossApplicationReferrerPathHash, $"CrossApplicationReferrerPathHash"); Assert.AreEqual(ReferrerTransactionGuid, _transaction.TransactionMetadata.CrossApplicationReferrerTransactionGuid, $"CrossApplicationReferrerTransactionGuid"); } [Test] public void AcceptDistributedTraceHeaders_DoesNotThrow_IfContentLengthIsNull() { var headers = new Dictionary<string, string>(); Assert.DoesNotThrow(() => _agent.CurrentTransaction.AcceptDistributedTraceHeaders(headers, HeaderFunctions.GetHeaders, TransportType.HTTP)); } [Test] public void AcceptDistributedTraceHeaders__ReportsSupportabilityMetric_NullPayload() { _distributedTracePayloadHandler = new DistributedTracePayloadHandler(_configurationService, _agentHealthReporter, new AdaptiveSampler()); _agent = new Agent(_transactionService, _transactionTransformer, _threadPoolStatic, _transactionMetricNameMaker, _pathHashMaker, _catHeaderHandler, _distributedTracePayloadHandler, _syntheticsHeaderHandler, _transactionFinalizer, _browserMonitoringPrereqChecker, _browserMonitoringScriptMaker, _configurationService, _agentHealthReporter, _agentTimerService, _metricNameService, _traceMetadataFactory, _catMetrics); SetupTransaction(); Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); var headers = new Dictionary<string, string>(); headers[DistributedTraceHeaderName] = null; _agent.CurrentTransaction.AcceptDistributedTraceHeaders(headers, HeaderFunctions.GetHeaders, TransportType.HTTP); Mock.Assert(() => _agentHealthReporter.ReportSupportabilityDistributedTraceAcceptPayloadIgnoredNull(), Occurs.Once()); } [Test] public void GetResponseMetadata_ReturnsEmpty_IfNoCurrentTransaction() { Mock.Arrange(() => _transactionService.GetCurrentInternalTransaction()).Returns((IInternalTransaction)null); var headers = _agent.CurrentTransaction.GetResponseMetadata(); Assert.NotNull(headers); Assert.IsEmpty(headers); } [Test] public void GetResponseMetadata_ReturnsEmpty_IfNoReferrerCrossProcessId() { var transactionName = TransactionName.ForWebTransaction("a", "b"); Mock.Arrange(() => _transaction.CandidateTransactionName.CurrentTransactionName).Returns(transactionName); Mock.Arrange(() => _transactionMetricNameMaker.GetTransactionMetricName(transactionName)).Returns(new TransactionMetricName("c", "d")); Mock.Arrange(() => _transaction.TransactionMetadata.CrossApplicationReferrerPathHash).Returns("referrerPathHash"); Mock.Arrange(() => _transaction.TransactionMetadata.CrossApplicationReferrerProcessId).Returns(null as string); Mock.Arrange(() => _pathHashMaker.CalculatePathHash("c/d", "referrerPathHash")).Returns("pathHash"); var headers = _agent.CurrentTransaction.GetResponseMetadata(); Assert.NotNull(headers); Assert.IsEmpty(headers); } [Test] public void GetResponseMetadata_CallsSetPathHashWithResultsFromPathHashMaker() { SetupTransaction(); Mock.Arrange(() => _transactionMetricNameMaker.GetTransactionMetricName(Arg.IsAny<ITransactionName>())).Returns(new TransactionMetricName("c", "d")); Mock.Arrange(() => _pathHashMaker.CalculatePathHash("c/d", "referrerPathHash")).Returns("pathHash"); _transaction.TransactionMetadata.SetCrossApplicationReferrerPathHash("referrerPathHash"); _transaction.TransactionMetadata.SetCrossApplicationReferrerProcessId("foo"); _agent.CurrentTransaction.GetResponseMetadata(); Assert.AreEqual("pathHash", _transaction.TransactionMetadata.LatestCrossApplicationPathHash); } [Test] public void GetResponseMetadata_ReturnsCatHeadersFromCatHeaderHandler() { SetupTransaction(); var catHeaders = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } }; Mock.Arrange(() => _catHeaderHandler.TryGetOutboundResponseHeaders(Arg.IsAny<IInternalTransaction>(), Arg.IsAny<TransactionMetricName>())).Returns(catHeaders); _transaction.TransactionMetadata.SetCrossApplicationReferrerProcessId("CatReferrer"); var headers = _agent.CurrentTransaction.GetResponseMetadata().ToDictionary(); Assert.NotNull(headers); NrAssert.Multiple( () => Assert.AreEqual("value1", headers["key1"]), () => Assert.AreEqual("value2", headers["key2"]) ); } #endregion inbound CAT request - outbound CAT response #region outbound CAT request - inbound CAT response [Test] public void ProcessInboundResponse_SetsSegmentCatResponseData_IfCatHeaderHandlerReturnsData() { SetupTransaction(); var expectedCatResponseData = new CrossApplicationResponseData("cpId", "name", 1.1f, 2.2f, 3); Mock.Arrange(() => _catHeaderHandler.TryDecodeInboundResponseHeaders(Arg.IsAny<IDictionary<string, string>>())) .Returns(expectedCatResponseData); var headers = new Dictionary<string, string>(); var externalSegmentData = new ExternalSegmentData(new Uri("http://www.google.com"), "method"); var segment = new Segment(TransactionSegmentStateHelpers.GetItransactionSegmentState(), new MethodCallData("foo", "bar", 1)); segment.SetSegmentData(externalSegmentData); _agent.CurrentTransaction.ProcessInboundResponse(headers, segment); var immutableTransactionMetadata = _transaction.TransactionMetadata.ConvertToImmutableMetadata(); Assert.AreEqual(expectedCatResponseData, externalSegmentData.CrossApplicationResponseData); Assert.AreEqual(true, immutableTransactionMetadata.HasCatResponseHeaders); } [Test] public void ProcessInboundResponse_DoesNotThrow_WhenNoCurrentTransaction() { Transaction transaction = null; Mock.Arrange(() => _transactionService.GetCurrentInternalTransaction()).Returns(transaction); var headers = new Dictionary<string, string>(); var segment = new Segment(TransactionSegmentStateHelpers.GetItransactionSegmentState(), new MethodCallData("foo", "bar", 1)); segment.SetSegmentData(new ExternalSegmentData(new Uri("http://www.google.com"), "method")); _agent.CurrentTransaction.ProcessInboundResponse(headers, segment); Mock.Assert(() => _transaction.TransactionMetadata.MarkHasCatResponseHeaders(), Occurs.Never()); } [Test] public void ProcessInboundResponse_NullFromTryDecode() { CrossApplicationResponseData expectedCatResponseData = null; Mock.Arrange(() => _catHeaderHandler.TryDecodeInboundResponseHeaders(Arg.IsAny<IDictionary<string, string>>())) .Returns(expectedCatResponseData); var headers = new Dictionary<string, string>(); var externalSegmentData = new ExternalSegmentData(new Uri("http://www.google.com"), "method"); var segmentBuilder = new Segment(TransactionSegmentStateHelpers.GetItransactionSegmentState(), new MethodCallData("foo", "bar", 1)); segmentBuilder.SetSegmentData(externalSegmentData); _agent.CurrentTransaction.ProcessInboundResponse(headers, segmentBuilder); Assert.AreEqual(externalSegmentData.CrossApplicationResponseData, expectedCatResponseData); Mock.Assert(() => _transaction.TransactionMetadata.MarkHasCatResponseHeaders(), Occurs.Never()); } [Test] public void ProcessInboundResponse_SetsSegmentCatResponseData() { SetupTransaction(); var expectedCatResponseData = new CrossApplicationResponseData("cpId", "name", 1.1f, 2.2f, 3); Mock.Arrange(() => _catHeaderHandler.TryDecodeInboundResponseHeaders(Arg.IsAny<IDictionary<string, string>>())) .Returns(expectedCatResponseData); var headers = new Dictionary<string, string>(); var externalSegmentData = new ExternalSegmentData(new Uri("http://www.google.com"), "method"); var segment = new Segment(TransactionSegmentStateHelpers.GetItransactionSegmentState(), new MethodCallData("foo", "bar", 1)); segment.SetSegmentData(externalSegmentData); _agent.CurrentTransaction.ProcessInboundResponse(headers, segment); var immutableTransactionMetadata = _transaction.TransactionMetadata.ConvertToImmutableMetadata(); Assert.AreEqual(expectedCatResponseData, externalSegmentData.CrossApplicationResponseData); Assert.AreEqual(true, immutableTransactionMetadata.HasCatResponseHeaders); } [Test] public void ProcessInboundResponse_DoesNotThrow_IfSegmentIsNull() { var headers = new Dictionary<string, string>(); _agent.CurrentTransaction.ProcessInboundResponse(headers, null); Mock.Assert(() => _transaction.TransactionMetadata.MarkHasCatResponseHeaders(), Occurs.Never()); // Simply not throwing is all this test needs to check for } [Test] public void GetRequestMetadata_ReturnsEmpty_IfNoCurrentTransaction() { Mock.Arrange(() => _transactionService.GetCurrentInternalTransaction()).Returns((IInternalTransaction)null); var headers = _agent.CurrentTransaction.GetRequestMetadata(); Assert.NotNull(headers); Assert.IsEmpty(headers); } [Test] public void GetRequestMetadata_CallsSetPathHashWithResultsFromPathHashMaker() { SetupTransaction(); Mock.Arrange(() => _transactionMetricNameMaker.GetTransactionMetricName(Arg.IsAny<ITransactionName>())).Returns(new TransactionMetricName("c", "d")); Mock.Arrange(() => _pathHashMaker.CalculatePathHash("c/d", "referrerPathHash")).Returns("pathHash"); _transaction.TransactionMetadata.SetCrossApplicationReferrerPathHash("referrerPathHash"); _agent.CurrentTransaction.GetRequestMetadata(); Assert.AreEqual("pathHash", _transaction.TransactionMetadata.LatestCrossApplicationPathHash); } [Test] public void GetRequestMetadata_ReturnsCatHeadersFromCatHeaderHandler() { SetupTransaction(); var catHeaders = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } }; Mock.Arrange(() => _catHeaderHandler.TryGetOutboundRequestHeaders(Arg.IsAny<IInternalTransaction>())).Returns(catHeaders); var headers = _agent.CurrentTransaction.GetRequestMetadata().ToDictionary(); Assert.NotNull(headers); NrAssert.Multiple( () => Assert.AreEqual("value1", headers["key1"]), () => Assert.AreEqual("value2", headers["key2"]) ); } #endregion outbound CAT request - inbound CAT response #region Distributed Trace private static readonly string _accountId = "acctid"; private static readonly string _appId = "appid"; private static readonly string _guid = "guid"; private static readonly float _priority = .3f; private static readonly bool _sampled = true; private static readonly string _traceId = "traceid"; private static readonly string _trustKey = "trustedkey"; private static readonly DistributedTracingParentType _type = DistributedTracingParentType.App; private static readonly string _transactionId = "transactionId"; private readonly DistributedTracePayload _distributedTracePayload = DistributedTracePayload.TryBuildOutgoingPayload(_type.ToString(), _accountId, _appId, _guid, _traceId, _trustKey, _priority, _sampled, DateTime.UtcNow, _transactionId); [Test] public void GetRequestMetadata_DoesNotReturnsCatHeaders_IfDistributedTraceEnabled() { // Arrange Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); var catHeaders = new Dictionary<string, string> { { "key1", "value1" }, { "key2", "value2" } }; Mock.Arrange(() => _catHeaderHandler.TryGetOutboundRequestHeaders(Arg.IsAny<IInternalTransaction>())).Returns(catHeaders); // Act var headers = _agent.CurrentTransaction.GetRequestMetadata().ToDictionary(); // Assert const string NewRelicIdHttpHeader = "X-NewRelic-ID"; const string TransactionDataHttpHeader = "X-NewRelic-Transaction"; const string AppDataHttpHeader = "X-NewRelic-App-Data"; Assert.That(headers, Does.Not.ContainKey(NewRelicIdHttpHeader)); Assert.That(headers, Does.Not.ContainKey(TransactionDataHttpHeader)); Assert.That(headers, Does.Not.ContainKey(AppDataHttpHeader)); Mock.Assert(() => _catHeaderHandler.TryGetOutboundRequestHeaders(Arg.IsAny<IInternalTransaction>()), Occurs.Never()); } [Test] public void GetRequestMetadata_ReturnsDistributedTraceHeadersFromDTPayloadHandler_IfDistributedTraceIsEnabled() { // Arrange SetupTransaction(); Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); var distributedTraceHeaders = Mock.Create<IDistributedTracePayload>(); Mock.Arrange(() => distributedTraceHeaders.HttpSafe()).Returns("value1"); Mock.Arrange(() => _distributedTracePayloadHandler.TryGetOutboundDistributedTraceApiModel(Arg.IsAny<IInternalTransaction>(), Arg.IsAny<ISegment>())).Returns(distributedTraceHeaders); // Act var headers = _agent.CurrentTransaction.GetRequestMetadata().ToDictionary(); // Assert NrAssert.Multiple( () => Assert.That(headers, Has.Exactly(1).Items), () => Assert.AreEqual(distributedTraceHeaders.HttpSafe(), headers[DistributedTraceHeaderName]) ); } [Test] public void AcceptDistributedTraceHeaders_SetsDTMetadataAndNotCATMetadata_IfDistributedTraceIsEnabled() { // Arrange SetupTransaction(); Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); var headers = new Dictionary<string, string>() { { DistributedTraceHeaderName, "encodedpayload" } }; Mock.Arrange(() => _distributedTracePayloadHandler.TryDecodeInboundSerializedDistributedTracePayload(Arg.IsAny<string>())).Returns(_distributedTracePayload); var tracingState = Mock.Create<ITracingState>(); Mock.Arrange(() => tracingState.Type).Returns(_type); Mock.Arrange(() => tracingState.AppId).Returns(_appId); Mock.Arrange(() => tracingState.AccountId).Returns(_accountId); Mock.Arrange(() => tracingState.Guid).Returns(_guid); Mock.Arrange(() => tracingState.TraceId).Returns(_traceId); Mock.Arrange(() => tracingState.TransactionId).Returns(_transactionId); Mock.Arrange(() => tracingState.Sampled).Returns(_sampled); Mock.Arrange(() => tracingState.Priority).Returns(_priority); Mock.Arrange(() => _distributedTracePayloadHandler.AcceptDistributedTraceHeaders(headers, Arg.IsAny<Func<Dictionary<string, string>, string, IEnumerable<string>>>(), Arg.IsAny<TransportType>(), Arg.IsAny<DateTime>())).Returns(tracingState); // Act _transaction.AcceptDistributedTraceHeaders(headers, HeaderFunctions.GetHeaders, TransportType.HTTP); // Assert var immutableTransactionMetadata = _transaction.TransactionMetadata.ConvertToImmutableMetadata(); Assert.IsNull(_transaction.TransactionMetadata.CrossApplicationReferrerProcessId); Assert.IsNull(_transaction.TransactionMetadata.CrossApplicationReferrerTripId); Assert.AreEqual(-1, _transaction.TransactionMetadata.GetCrossApplicationReferrerContentLength()); Assert.IsNull(_transaction.TransactionMetadata.CrossApplicationReferrerPathHash); Assert.IsNull(null, immutableTransactionMetadata.CrossApplicationReferrerTransactionGuid); Assert.AreEqual(_accountId, _transaction.TracingState.AccountId); Assert.AreEqual(_appId, _transaction.TracingState.AppId); Assert.AreEqual(_guid, _transaction.TracingState.Guid); Assert.AreEqual(_type, _transaction.TracingState.Type); Assert.AreEqual(_transactionId, _transaction.TracingState.TransactionId); } [Test] public void AcceptDistributedTraceHeaders_DoesNotSetTransactionData_IfPayloadAlreadyAccepted() { // Arrange SetupTransaction(); Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); var tracingState = Mock.Create<ITracingState>(); Mock.Arrange(() => _distributedTracePayloadHandler.AcceptDistributedTraceHeaders(Arg.IsAny<Dictionary<string, string>>(), Arg.IsAny<Func<Dictionary<string, string>, string, IEnumerable<string>>>(), Arg.IsAny<TransportType>(), Arg.IsAny<DateTime>())).Returns(tracingState); var headers = new Dictionary<string, string>(); _transaction.AcceptDistributedTraceHeaders(headers, HeaderFunctions.GetHeaders, TransportType.HTTP); // Act _transaction.AcceptDistributedTraceHeaders(headers, HeaderFunctions.GetHeaders, TransportType.HTTP); // Assert Mock.Assert(() => _distributedTracePayloadHandler.AcceptDistributedTraceHeaders(Arg.IsAny<Dictionary<string, string>>(), Arg.IsAny<Func<Dictionary<string, string>, string, IEnumerable<string>>>(), Arg.IsAny<TransportType>(), Arg.IsAny<DateTime>()), Occurs.Once()); Mock.Assert(() => _agentHealthReporter.ReportSupportabilityDistributedTraceAcceptPayloadIgnoredMultiple(), Occurs.Once()); } [Test] public void AcceptDistributedTraceHeaders_DoesNotSetTransactionData_IfOutgoingPayloadCreated() { // Arrange SetupTransaction(); _transaction.TransactionMetadata.HasOutgoingTraceHeaders = true; var headers = new Dictionary<string, string>(); // Act _transaction.AcceptDistributedTraceHeaders(headers, HeaderFunctions.GetHeaders, TransportType.HTTP); // Assert Mock.Assert(() => _distributedTracePayloadHandler.AcceptDistributedTraceHeaders(Arg.IsAny<Dictionary<string, string>>(), Arg.IsAny<Func<Dictionary<string, string>, string, IEnumerable<string>>>(), Arg.IsAny<TransportType>(), Arg.IsAny<DateTime>()), Occurs.Never()); Mock.Assert(() => _transaction.TracingState.AccountId, Occurs.Never()); Mock.Assert(() => _transaction.TracingState.AppId, Occurs.Never()); Mock.Assert(() => _transaction.TracingState.Guid, Occurs.Never()); Mock.Assert(() => _transaction.TraceId, Occurs.Never()); Mock.Assert(() => _transaction.TracingState.Type, Occurs.Never()); } [Test] public void AcceptDistributedTracePayload_ReportsSupportabilityMetric_IfAcceptCalledMultipleTimes() { // Arrange SetupTransaction(); Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); var payload = string.Empty; Mock.Arrange(() => _distributedTracePayloadHandler.TryDecodeInboundSerializedDistributedTracePayload(Arg.IsAny<string>())).Returns(_distributedTracePayload); _agent.CurrentTransaction.AcceptDistributedTracePayload(payload, TransportType.HTTPS); Mock.Arrange(() => _distributedTracePayloadHandler.TryDecodeInboundSerializedDistributedTracePayload(Arg.IsAny<string>())).CallOriginal(); // Act _agent.CurrentTransaction.AcceptDistributedTracePayload(payload, TransportType.HTTPS); // Assert Mock.Assert(() => _agentHealthReporter.ReportSupportabilityDistributedTraceAcceptPayloadIgnoredMultiple(), Occurs.Once()); } [Test] public void CreateDistributedTracePayload_ShouldReturnPayload_IfConfigIsTrue() { SetupTransaction(); Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); var distributedTraceHeaders = Mock.Create<IDistributedTracePayload>(); Mock.Arrange(() => distributedTraceHeaders.HttpSafe()).Returns("value1"); Mock.Arrange(() => _distributedTracePayloadHandler.TryGetOutboundDistributedTraceApiModel(Arg.IsAny<IInternalTransaction>(), Arg.IsAny<ISegment>())).Returns(distributedTraceHeaders); var payload = _agent.CurrentTransaction.CreateDistributedTracePayload(); NrAssert.Multiple( () => Assert.AreEqual(distributedTraceHeaders, payload) ); } [Test] public void CreateDistributedTracePayload_ShouldNotReturnPayload_IfConfigIsFalse() { SetupTransaction(); Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(false); var distributedTraceHeaders = Mock.Create<IDistributedTracePayload>(); Mock.Arrange(() => distributedTraceHeaders.HttpSafe()).Returns("value1"); Mock.Arrange(() => _distributedTracePayloadHandler.TryGetOutboundDistributedTraceApiModel(Arg.IsAny<IInternalTransaction>(), Arg.IsAny<ISegment>())).Returns(distributedTraceHeaders); var payload = _agent.CurrentTransaction.CreateDistributedTracePayload(); Assert.AreEqual(DistributedTraceApiModel.EmptyModel, payload); } [Test] public void TraceMetadata_ShouldReturnEmptyModel_IfDTConfigIsFalse() { SetupTransaction(); Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(false); var traceMetadata = _agent.TraceMetadata; Assert.AreEqual(TraceMetadata.EmptyModel, traceMetadata); } [Test] public void TraceMetadata_ShouldReturnValidValues_IfDTConfigIsTrue() { const string testTraceId = "testTraceId"; const string testSpanId = "testSpanId"; const bool testIsSampled = true; SetupTransaction(); Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); var traceMetadata = Mock.Create<ITraceMetadata>(); Mock.Arrange(() => traceMetadata.TraceId).Returns(testTraceId); Mock.Arrange(() => traceMetadata.SpanId).Returns(testSpanId); Mock.Arrange(() => traceMetadata.IsSampled).Returns(testIsSampled); Assert.AreEqual(traceMetadata.TraceId, testTraceId); Assert.AreEqual(traceMetadata.SpanId, testSpanId); Assert.AreEqual(traceMetadata.IsSampled, testIsSampled); } [Test] public void AcceptDistributedTracePayload_ShouldAccept_IfConfigIsTrue() { SetupTransaction(); Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); var tracingState = Mock.Create<ITracingState>(); Mock.Arrange(() => _distributedTracePayloadHandler.AcceptDistributedTracePayload(Arg.IsAny<string>(), Arg.IsAny<TransportType>(), Arg.IsAny<DateTime>())).Returns(tracingState); var payload = string.Empty; _agent.CurrentTransaction.AcceptDistributedTracePayload(payload, TransportType.HTTPS); Assert.IsNotNull(_transaction.TracingState); } [Test] public void AcceptDistributedTracePayload_ShouldNotAccept_IfConfigIsFalse() { SetupTransaction(); Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(false); var tracingState = Mock.Create<ITracingState>(); Mock.Arrange(() => _distributedTracePayloadHandler.AcceptDistributedTracePayload(Arg.IsAny<string>(), Arg.IsAny<TransportType>(), Arg.IsAny<DateTime>())).Returns(tracingState); var payload = string.Empty; _agent.CurrentTransaction.AcceptDistributedTracePayload(payload, TransportType.HTTPS); Assert.IsNull(_transaction.TracingState); } [TestCase("Newrelic", "payload", true)] [TestCase("NewRelic", "payload", true)] [TestCase("newrelic", "payload", true)] [TestCase("Fred", null, false)] public void TryGetDistributedTracePayload_ReturnsValidPayloadOrNull(string key, string expectedPayload, bool expectedResult) { var headers = new List<KeyValuePair<string, string>>(); headers.Add(new KeyValuePair<string, string>(key, expectedPayload)); var actualResult = _agent.TryGetDistributedTracePayloadFromHeaders(headers, out var actualPayload); NrAssert.Multiple( () => Assert.AreEqual(expectedPayload, actualPayload), () => Assert.AreEqual(expectedResult, actualResult) ); } [Test] public void TryGetDistributedTracePayload_HeaderCollectionTests_NullHeader() { TryGetDistributedTracePayload_HeaderCollectionTests(null, null, false); } [Test] public void TryGetDistributedTracePayload_HeaderCollectionTests_EmptyHeader() { TryGetDistributedTracePayload_HeaderCollectionTests(new List<KeyValuePair<string, string>>(), null, false); } [Test] public void TryGetDistributedTracePayload_HeaderCollectionTests_OneItemWithoutDTHeader() { var oneItemWithoutDTHeader = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("Fred", "Wilma") }; TryGetDistributedTracePayload_HeaderCollectionTests(oneItemWithoutDTHeader, null, false); } [Test] public void TryGetDistributedTracePayload_HeaderCollectionTests_MultipleItemsWithDTHeader() { var multipleItemsWithDTHeader = new List<KeyValuePair<string, string>> { new KeyValuePair<string, string>("Fred", "Wilma"), new KeyValuePair<string, string>("Barney", "Betty"), new KeyValuePair<string, string>(DistributedTraceHeaderName, "payload") }; TryGetDistributedTracePayload_HeaderCollectionTests(multipleItemsWithDTHeader, "payload", true); } private void TryGetDistributedTracePayload_HeaderCollectionTests(List<KeyValuePair<string, string>> headers, string expectedPayload, bool expectedResult) { var actualResult = _agent.TryGetDistributedTracePayloadFromHeaders(headers, out var actualPayload); NrAssert.Multiple( () => Assert.AreEqual(expectedPayload, actualPayload), () => Assert.AreEqual(expectedResult, actualResult) ); } #endregion Distributed Trace #region TraceMetadata [Test] public void TraceMetadata_ReturnsEmptyTraceMetadata_WhenDistributedTracingDisabled() { Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(false); var actualTraceMetadata = _agent.TraceMetadata; Assert.AreEqual(TraceMetadata.EmptyModel, actualTraceMetadata); } [Test] public void TraceMetadata_ReturnsEmptyTraceMetadata_WhenTransactionNotAvailable() { Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(false); Mock.Arrange(() => _transaction.IsValid).Returns(false); var actualTraceMetadata = _agent.TraceMetadata; Assert.AreEqual(TraceMetadata.EmptyModel, actualTraceMetadata); } [Test] public void TraceMetadata_ReturnsTraceMetadata_DTAndTransactionAreAvailable() { var expectedTraceMetadata = new TraceMetadata("traceId", "spanId", true); Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); Mock.Arrange(() => _transaction.IsValid).Returns(true); Mock.Arrange(() => _traceMetadataFactory.CreateTraceMetadata(_transaction)).Returns(expectedTraceMetadata); var actualTraceMetadata = _agent.TraceMetadata; Assert.AreEqual(expectedTraceMetadata, actualTraceMetadata); } #endregion TraceMetadata #region GetLinkingMetadata [Test] public void GetLinkingMetadata_ReturnsAllData_WhenAllDataIsAvailable() { //TraceMetadata Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); Mock.Arrange(() => _transaction.IsValid).Returns(true); Mock.Arrange(() => _traceMetadataFactory.CreateTraceMetadata(_transaction)).Returns(new TraceMetadata("traceId", "spanId", true)); //HostName Mock.Arrange(() => _configurationService.Configuration.UtilizationFullHostName).Returns("FullHostName"); Mock.Arrange(() => _configurationService.Configuration.UtilizationHostName).Returns("HostName"); //ApplicationName Mock.Arrange(() => _configurationService.Configuration.ApplicationNames).Returns(new[] { "AppName1", "AppName2", "AppName3" }); //EntityGuid Mock.Arrange(() => _configurationService.Configuration.EntityGuid).Returns("EntityGuid"); var actualLinkingMetadata = _agent.GetLinkingMetadata(); var expectedLinkingMetadata = new Dictionary<string, string> { { "trace.id", "traceId" }, { "span.id", "spanId" }, { "entity.name", "AppName1" }, { "entity.type", "SERVICE" }, { "entity.guid", "EntityGuid" }, { "hostname", "FullHostName" } }; CollectionAssert.AreEquivalent(expectedLinkingMetadata, actualLinkingMetadata); } [Test] public void GetLinkingMetadata_DoesNotIncludeTraceId_WhenTraceIdIsNotAvailable() { //TraceMetadata Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); Mock.Arrange(() => _transaction.IsValid).Returns(true); Mock.Arrange(() => _traceMetadataFactory.CreateTraceMetadata(_transaction)).Returns(new TraceMetadata(string.Empty, "spanId", true)); //HostName Mock.Arrange(() => _configurationService.Configuration.UtilizationFullHostName).Returns("FullHostName"); Mock.Arrange(() => _configurationService.Configuration.UtilizationHostName).Returns("HostName"); //ApplicationName Mock.Arrange(() => _configurationService.Configuration.ApplicationNames).Returns(new[] { "AppName1", "AppName2", "AppName3" }); //EntityGuid Mock.Arrange(() => _configurationService.Configuration.EntityGuid).Returns("EntityGuid"); var actualLinkingMetadata = _agent.GetLinkingMetadata(); Assert.False(actualLinkingMetadata.ContainsKey("trace.id")); } [Test] public void GetLinkingMetadata_DoesNotIncludeSpanId_WhenSpanIdIsNotAvailable() { //TraceMetadata Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); Mock.Arrange(() => _transaction.IsValid).Returns(true); Mock.Arrange(() => _traceMetadataFactory.CreateTraceMetadata(_transaction)).Returns(new TraceMetadata("traceId", string.Empty, true)); //HostName Mock.Arrange(() => _configurationService.Configuration.UtilizationFullHostName).Returns("FullHostName"); Mock.Arrange(() => _configurationService.Configuration.UtilizationHostName).Returns("HostName"); //ApplicationName Mock.Arrange(() => _configurationService.Configuration.ApplicationNames).Returns(new[] { "AppName1", "AppName2", "AppName3" }); //EntityGuid Mock.Arrange(() => _configurationService.Configuration.EntityGuid).Returns("EntityGuid"); var actualLinkingMetadata = _agent.GetLinkingMetadata(); Assert.False(actualLinkingMetadata.ContainsKey("span.id")); } [Test] public void GetLinkingMetadata_DoesNotIncludeSpanIdOrTraceId_WhenTraceMetadataIsNotAvailable() { //TraceMetadata Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(false); //HostName Mock.Arrange(() => _configurationService.Configuration.UtilizationFullHostName).Returns("FullHostName"); Mock.Arrange(() => _configurationService.Configuration.UtilizationHostName).Returns("HostName"); //ApplicationName Mock.Arrange(() => _configurationService.Configuration.ApplicationNames).Returns(new[] { "AppName1", "AppName2", "AppName3" }); //EntityGuid Mock.Arrange(() => _configurationService.Configuration.EntityGuid).Returns("EntityGuid"); var actualLinkingMetadata = _agent.GetLinkingMetadata(); CollectionAssert.IsNotSupersetOf(actualLinkingMetadata.Keys, new[] { "trace.id", "span.id" }); } [Test] public void GetLinkingMetadata_DoesNotIncludeEntityName_WhenFirstAppNameIsNotAvailable() { //TraceMetadata Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); Mock.Arrange(() => _transaction.IsValid).Returns(true); Mock.Arrange(() => _traceMetadataFactory.CreateTraceMetadata(_transaction)).Returns(new TraceMetadata("traceId", "spanId", true)); //HostName Mock.Arrange(() => _configurationService.Configuration.UtilizationFullHostName).Returns("FullHostName"); Mock.Arrange(() => _configurationService.Configuration.UtilizationHostName).Returns("HostName"); //ApplicationName Mock.Arrange(() => _configurationService.Configuration.ApplicationNames).Returns(new[] { string.Empty, "AppName2", "AppName3" }); //EntityGuid Mock.Arrange(() => _configurationService.Configuration.EntityGuid).Returns("EntityGuid"); var actualLinkingMetadata = _agent.GetLinkingMetadata(); Assert.False(actualLinkingMetadata.ContainsKey("entity.name")); } [Test] public void GetLinkingMetadata_DoesNotIncludeEntityName_WhenAppNameIsNotAvailable() { //TraceMetadata Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); Mock.Arrange(() => _transaction.IsValid).Returns(true); Mock.Arrange(() => _traceMetadataFactory.CreateTraceMetadata(_transaction)).Returns(new TraceMetadata("traceId", "spanId", true)); //HostName Mock.Arrange(() => _configurationService.Configuration.UtilizationFullHostName).Returns("FullHostName"); Mock.Arrange(() => _configurationService.Configuration.UtilizationHostName).Returns("HostName"); //ApplicationName Mock.Arrange(() => _configurationService.Configuration.ApplicationNames).Returns(new string[0]); //EntityGuid Mock.Arrange(() => _configurationService.Configuration.EntityGuid).Returns("EntityGuid"); var actualLinkingMetadata = _agent.GetLinkingMetadata(); Assert.False(actualLinkingMetadata.ContainsKey("entity.name")); } [Test] public void GetLinkingMetadata_DoesNotIncludeEntityGuid_WhenEntityGuidIsNotAvailable() { //TraceMetadata Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); Mock.Arrange(() => _transaction.IsValid).Returns(true); Mock.Arrange(() => _traceMetadataFactory.CreateTraceMetadata(_transaction)).Returns(new TraceMetadata("traceId", "spanId", true)); //HostName Mock.Arrange(() => _configurationService.Configuration.UtilizationFullHostName).Returns("FullHostName"); Mock.Arrange(() => _configurationService.Configuration.UtilizationHostName).Returns("HostName"); //ApplicationName Mock.Arrange(() => _configurationService.Configuration.ApplicationNames).Returns(new[] { "AppName1", "AppName2", "AppName3" }); //EntityGuid Mock.Arrange(() => _configurationService.Configuration.EntityGuid).Returns(string.Empty); var actualLinkingMetadata = _agent.GetLinkingMetadata(); Assert.False(actualLinkingMetadata.ContainsKey("entity.guid")); } [Test] public void GetLinkingMetadata_IncludesHostName_WhenFullHostNameIsNotAvailable() { //TraceMetadata Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); Mock.Arrange(() => _transaction.IsValid).Returns(true); Mock.Arrange(() => _traceMetadataFactory.CreateTraceMetadata(_transaction)).Returns(new TraceMetadata("traceId", "spanId", true)); //HostName Mock.Arrange(() => _configurationService.Configuration.UtilizationFullHostName).Returns(string.Empty); Mock.Arrange(() => _configurationService.Configuration.UtilizationHostName).Returns("HostName"); //ApplicationName Mock.Arrange(() => _configurationService.Configuration.ApplicationNames).Returns(new[] { "AppName1", "AppName2", "AppName3" }); //EntityGuid Mock.Arrange(() => _configurationService.Configuration.EntityGuid).Returns("EntityGuid"); var actualLinkingMetadata = _agent.GetLinkingMetadata(); Assert.AreEqual(actualLinkingMetadata["hostname"], "HostName"); } [Test] public void GetLinkingMetadata_DoesNotIncludeHostName_WhenHostNameIsNotAvailable() { //TraceMetadata Mock.Arrange(() => _configurationService.Configuration.DistributedTracingEnabled).Returns(true); Mock.Arrange(() => _transaction.IsValid).Returns(true); Mock.Arrange(() => _traceMetadataFactory.CreateTraceMetadata(_transaction)).Returns(new TraceMetadata("traceId", "spanId", true)); //HostName Mock.Arrange(() => _configurationService.Configuration.UtilizationFullHostName).Returns(string.Empty); Mock.Arrange(() => _configurationService.Configuration.UtilizationHostName).Returns(string.Empty); //ApplicationName Mock.Arrange(() => _configurationService.Configuration.ApplicationNames).Returns(new[] { "AppName1", "AppName2", "AppName3" }); //EntityGuid Mock.Arrange(() => _configurationService.Configuration.EntityGuid).Returns("EntityGuid"); var actualLinkingMetadata = _agent.GetLinkingMetadata(); Assert.False(actualLinkingMetadata.ContainsKey("hostname")); } #endregion GetLinkingMetadata private void SetupTransaction() { var transactionName = TransactionName.ForWebTransaction("foo", "bar"); _transaction = new Transaction(_configurationService.Configuration, transactionName, Mock.Create<ITimer>(), DateTime.UtcNow, _callStackManager, Mock.Create<IDatabaseService>(), default(float), Mock.Create<IDatabaseStatementParser>(), _distributedTracePayloadHandler, _errorService, _attribDefs); Mock.Arrange(() => _transactionService.GetCurrentInternalTransaction()).Returns(_transaction); } } } // In order to generate a stack trace for testing we need a frame that is not in a NewRelic.* namespace (NewRelic frames are omitted from stack traces) namespace NotNewRelic { public static class ExceptionBuilder { public static Exception BuildException(string message) { try { throw new Exception(message); } catch (Exception ex) { return ex; } } } }
48.640749
427
0.687191
[ "Apache-2.0" ]
Faithlife/newrelic-dotnet-agent
tests/Agent/UnitTests/Core.UnitTest/Wrapper/AgentWrapperApi/AgentWrapperApiTests.cs
67,562
C#
using System.Threading.Tasks; using NHSD.BuyingCatalogue.Ordering.Api.IntegrationTests.Responses; using NHSD.BuyingCatalogue.Ordering.Api.IntegrationTests.Utils; namespace NHSD.BuyingCatalogue.Ordering.Api.IntegrationTests.Requests { internal sealed class GetOrderItemsRequest { private readonly Request request; private readonly string getOrderItemUrl; public GetOrderItemsRequest( Request request, string orderingApiBaseAddress, int orderId, string catalogueItemType) { this.request = request; OrderId = orderId; CatalogueItemType = catalogueItemType; getOrderItemUrl = $"{orderingApiBaseAddress}/api/v1/orders/C{orderId}-01/order-items"; if (!string.IsNullOrWhiteSpace(CatalogueItemType)) { getOrderItemUrl += $"?catalogueItemType={CatalogueItemType}"; } } public int OrderId { get; } public string CatalogueItemType { get; } public async Task<GetOrderItemsResponse> ExecuteAsync() { var response = await request.GetAsync(getOrderItemUrl); return new GetOrderItemsResponse(response); } } }
30.853659
98
0.64664
[ "MIT" ]
nhs-digital-gp-it-futures/BuyingCatalogueOrdering
tests/NHSD.BuyingCatalogue.Ordering.Api.IntegrationTests/Requests/GetOrderItemsRequest.cs
1,267
C#
using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using TensorShader; namespace TensorShaderTest.Links.BinaryArithmetric { [TestClass] public class SubTest { [TestMethod] public void ReferenceTest() { int length = 24; float[] x1val = (new float[length]).Select((_, idx) => (float)idx).ToArray(); float[] x2val = (new float[length]).Select((_, idx) => (float)idx + 1).Reverse().ToArray(); float[] yval = (new float[length]).Select((_, idx) => (float)idx * 2).ToArray(); Tensor x1tensor = new Tensor(Shape.Vector(length), x1val); Tensor x2tensor = new Tensor(Shape.Vector(length), x2val); Tensor ytensor = new Tensor(Shape.Vector(length), yval); ParameterField x1 = x1tensor; ParameterField x2 = x2tensor; VariableField y_actual = ytensor; Field y_expect = x1 - x2; Field err = y_expect - y_actual; (Flow flow, Parameters Parameters) = Flow.Optimize(err); flow.Execute(); float[] gx1_actual = x1.GradTensor.State; float[] gx2_actual = x2.GradTensor.State; AssertError.Tolerance(gx1_expect, gx1_actual, 1e-7f, 1e-5f, $"not equal gx1"); AssertError.Tolerance(gx2_expect, gx2_actual, 1e-7f, 1e-5f, $"not equal gx2"); } float[] gx1_expect = { -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, -2.40000000e+01f, }; float[] gx2_expect = { 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, 2.40000000e+01f, }; } }
30.589474
103
0.513076
[ "MIT" ]
tk-yoshimura/TensorShaderAVX
TensorShaderTest/Links/BinaryArithmetric/SubTest.cs
2,906
C#
namespace ChefsKiss.Web.Models.Recipes { using System.ComponentModel.DataAnnotations; using ChefsKiss.Web.Infrastructure.Attributes; using Microsoft.AspNetCore.Http; using static ChefsKiss.Common.DataConstants; public class RecipeCreateFormModel : RecipeFormModel { [Required] [ImagesOnly] [MaxFileSize(Images.MaxSizeBytes)] public override IFormFile Image { get; init; } } }
23.157895
56
0.706818
[ "MIT" ]
martin-ali/chefs-kiss-site
ChefsKiss/Web/ChefsKiss.Web/Models/Recipes/RecipeCreateFormModel.cs
440
C#
/* ------------------------------------------------------------------------- */ // // Copyright (c) 2010 CubeSoft, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /* ------------------------------------------------------------------------- */ using System; using Cube.FileSystem; using Cube.Net.Rss.Reader; using NUnit.Framework; namespace Cube.Net.Rss.Tests { /* --------------------------------------------------------------------- */ /// /// SettingTest /// /// <summary> /// Setting および SettingFolder のテスト用クラスです。 /// </summary> /// /* --------------------------------------------------------------------- */ [TestFixture] class SettingTest : ResourceFixture { #region Tests /* ----------------------------------------------------------------- */ /// /// Load /// /// <summary> /// 設定ファイルを読み込むテストを実行します。 /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void Load() { Copy(); var src = new SettingFolder(RootDirectory(), new()); src.Load(); Assert.That(src.Value.Width, Is.EqualTo(1100)); Assert.That(src.Value.Height, Is.EqualTo(650)); Assert.That(src.Value.DataDirectory, Is.EqualTo(RootDirectory())); Assert.That(src.Shared.StartUri, Is.EqualTo(new Uri("https://github.com/blog.atom"))); Assert.That(src.Shared.Capacity, Is.EqualTo(5)); Assert.That(src.Shared.EnableNewWindow, Is.True); Assert.That(src.Shared.EnableMonitorMessage, Is.True); Assert.That(src.Shared.LightMode, Is.False); Assert.That(src.Shared.CheckUpdate, Is.True); Assert.That(src.Shared.HighInterval, Is.EqualTo(TimeSpan.FromHours(1))); Assert.That(src.Shared.LowInterval, Is.EqualTo(TimeSpan.FromDays(1))); Assert.That(src.Shared.InitialDelay, Is.EqualTo(TimeSpan.FromSeconds(3))); Assert.That(src.Lock.IsReadOnly, Is.False); Assert.That(src.Lock.IsReadOnly, Is.False); Assert.That(src.Lock.UserName, Is.EqualTo(Environment.UserName)); Assert.That(src.Lock.MachineName, Is.EqualTo(Environment.MachineName)); Assert.That(src.Lock.Sid, Does.StartWith("S-1-5-21")); } /* ----------------------------------------------------------------- */ /// /// Load_Empty /// /// <summary> /// 空の設定ファイルを読み込むテストを実行します。 /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void Load_Empty() { Io.Copy(GetSource("SettingsEmpty.json"), LocalSettingPath(), true); Io.Copy(GetSource("SettingsEmpty.json"), SharedSettingPath(), true); var src = new SettingFolder(RootDirectory(), new()); src.Load(); Assert.That(src.Value.Width, Is.EqualTo(1100)); Assert.That(src.Value.Height, Is.EqualTo(650)); Assert.That(src.Value.DataDirectory, Is.EqualTo(RootDirectory())); Assert.That(src.Shared.StartUri, Is.Null); Assert.That(src.Shared.Capacity, Is.EqualTo(100)); Assert.That(src.Shared.EnableNewWindow, Is.False); Assert.That(src.Shared.EnableMonitorMessage, Is.True); Assert.That(src.Shared.LightMode, Is.False); Assert.That(src.Shared.CheckUpdate, Is.True); Assert.That(src.Shared.HighInterval, Is.EqualTo(TimeSpan.FromHours(1))); Assert.That(src.Shared.LowInterval, Is.EqualTo(TimeSpan.FromDays(1))); Assert.That(src.Shared.InitialDelay, Is.EqualTo(TimeSpan.FromSeconds(3))); Assert.That(src.Lock.IsReadOnly, Is.False); Assert.That(src.Lock.IsReadOnly, Is.False); Assert.That(src.Lock.UserName, Is.EqualTo(Environment.UserName)); Assert.That(src.Lock.MachineName, Is.EqualTo(Environment.MachineName)); Assert.That(src.Lock.Sid, Does.StartWith("S-1-5-21")); } /* ----------------------------------------------------------------- */ /// /// Load_NotFound /// /// <summary> /// 設定ファイルが存在しない場合の挙動を確認します。 /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void Load_NotFound() { var src = new SettingFolder(RootDirectory(), new()); src.Load(); Assert.That(src.DataDirectory, Is.EqualTo(RootDirectory())); Assert.That(src.Value, Is.Not.Null, nameof(src.Value)); Assert.That(src.Shared, Is.Not.Null, nameof(src.Shared)); Assert.That(src.Lock, Is.Not.Null, nameof(src.Lock)); } /* ----------------------------------------------------------------- */ /// /// Load_Invalid /// /// <summary> /// 設定ファイルが破損している場合の挙動を確認します。 /// </summary> /// /* ----------------------------------------------------------------- */ [Test] public void Load_Invalid() { Io.Copy(GetSource("Dummy.txt"), LocalSettingPath(), true); Io.Copy(GetSource("Dummy.txt"), SharedSettingPath(), true); var src = new SettingFolder(RootDirectory(), new()); src.Load(); Assert.That(src.DataDirectory, Is.EqualTo(RootDirectory())); Assert.That(src.Value, Is.Not.Null, nameof(src.Value)); Assert.That(src.Shared, Is.Not.Null, nameof(src.Shared)); Assert.That(src.Lock, Is.Not.Null, nameof(src.Lock)); } #endregion } }
43.063694
110
0.469161
[ "Apache-2.0" ]
cube-soft/Cube.Net
Tests/Rss/Sources/Models/SettingTest.cs
6,977
C#
//------------------------------------------------------------------------------ // <auto-generated> // Tento kód byl generován nástrojem. // Verze modulu runtime:4.0.30319.42000 // // Změny tohoto souboru mohou způsobit nesprávné chování a budou ztraceny, // dojde-li k novému generování kódu. // </auto-generated> //------------------------------------------------------------------------------ namespace CS025ZakladyAlgoritmu.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.7.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
40.481481
151
0.592864
[ "MIT" ]
FatildaIV/CS026ZakladyAlgoritmu2
CS026ZakladyAlgoritmu2/Properties/Settings.Designer.cs
1,108
C#
using AspNetStandard.Diagnostics.HealthChecks.Models; using System; using System.Net; using System.Net.Http; using System.Net.Http.Formatting; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace AspNetStandard.Diagnostics.HealthChecks.HttpMessageHandlers { internal class AuthenticationHandler : BaseHandler, IChainable { public AuthenticationHandler(HttpConfiguration httpConfiguration, HealthChecksBuilder healthChecksBuilder) : base(httpConfiguration, healthChecksBuilder) { } #region IChainable Implementation private IHandler _nextHandler; public IHandler SetNextHandler(IHandler nextHandlerInstance) { _nextHandler = nextHandlerInstance; return nextHandlerInstance; } #endregion IChainable Implementation #region BaseHandler Implementation public async override Task<HttpResponseMessage> HandleRequest(HttpRequestMessage request, CancellationToken cancellationToken) { if (String.IsNullOrEmpty(HealthChecksBuilder.ApiKey)) { return await _nextHandler.HandleRequest(request, cancellationToken); } if (!validateKey(request)) { var response = new HttpResponseMessage(HttpStatusCode.Forbidden) { Content = new ObjectContent<ErrorResponse>( new ErrorResponse { Error = $"ApiKey is invalid or not provided." }, new JsonMediaTypeFormatter { SerializerSettings = SerializerSettings } ) }; return response; } return await _nextHandler.HandleRequest(request, cancellationToken); } #endregion BaseHandler Implementation #region Private Help Methods private bool validateKey(HttpRequestMessage request) { //query.TryGetValue var query = request.RequestUri.ParseQueryString(); string key = query["ApiKey"]; return (key == HealthChecksBuilder.ApiKey); } #endregion Private Help Methods } }
33.5
162
0.628622
[ "MIT" ]
AndrePostiga/WebApi.HealthChecks
src/AspNetStandard.Diagnostics.HealthChecks/HttpMessageHandlers/AuthenticationHandler.cs
2,280
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the codeguru-reviewer-2019-09-19.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CodeGuruReviewer.Model { /// <summary> /// Information about a repository association. /// </summary> public partial class RepositoryAssociation { private string _associationArn; private string _associationId; private DateTime? _createdTimeStamp; private DateTime? _lastUpdatedTimeStamp; private string _name; private string _owner; private ProviderType _providerType; private RepositoryAssociationState _state; private string _stateReason; /// <summary> /// Gets and sets the property AssociationArn. /// <para> /// The Amazon Resource Name (ARN) identifying the repository association. /// </para> /// </summary> [AWSProperty(Min=1, Max=1600)] public string AssociationArn { get { return this._associationArn; } set { this._associationArn = value; } } // Check to see if AssociationArn property is set internal bool IsSetAssociationArn() { return this._associationArn != null; } /// <summary> /// Gets and sets the property AssociationId. /// <para> /// The id of the repository association. /// </para> /// </summary> [AWSProperty(Min=1, Max=64)] public string AssociationId { get { return this._associationId; } set { this._associationId = value; } } // Check to see if AssociationId property is set internal bool IsSetAssociationId() { return this._associationId != null; } /// <summary> /// Gets and sets the property CreatedTimeStamp. /// <para> /// The time, in milliseconds since the epoch, when the repository association was created. /// </para> /// </summary> public DateTime CreatedTimeStamp { get { return this._createdTimeStamp.GetValueOrDefault(); } set { this._createdTimeStamp = value; } } // Check to see if CreatedTimeStamp property is set internal bool IsSetCreatedTimeStamp() { return this._createdTimeStamp.HasValue; } /// <summary> /// Gets and sets the property LastUpdatedTimeStamp. /// <para> /// The time, in milliseconds since the epoch, when the repository association was last /// updated. /// </para> /// </summary> public DateTime LastUpdatedTimeStamp { get { return this._lastUpdatedTimeStamp.GetValueOrDefault(); } set { this._lastUpdatedTimeStamp = value; } } // Check to see if LastUpdatedTimeStamp property is set internal bool IsSetLastUpdatedTimeStamp() { return this._lastUpdatedTimeStamp.HasValue; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the repository. /// </para> /// </summary> [AWSProperty(Min=1, Max=100)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Owner. /// <para> /// The owner of the repository. /// </para> /// </summary> [AWSProperty(Min=1, Max=100)] public string Owner { get { return this._owner; } set { this._owner = value; } } // Check to see if Owner property is set internal bool IsSetOwner() { return this._owner != null; } /// <summary> /// Gets and sets the property ProviderType. /// <para> /// The provider type of the repository association. /// </para> /// </summary> public ProviderType ProviderType { get { return this._providerType; } set { this._providerType = value; } } // Check to see if ProviderType property is set internal bool IsSetProviderType() { return this._providerType != null; } /// <summary> /// Gets and sets the property State. /// <para> /// The state of the repository association. /// </para> /// </summary> public RepositoryAssociationState State { get { return this._state; } set { this._state = value; } } // Check to see if State property is set internal bool IsSetState() { return this._state != null; } /// <summary> /// Gets and sets the property StateReason. /// <para> /// A description of why the repository association is in the current state. /// </para> /// </summary> [AWSProperty(Min=0, Max=256)] public string StateReason { get { return this._stateReason; } set { this._stateReason = value; } } // Check to see if StateReason property is set internal bool IsSetStateReason() { return this._stateReason != null; } } }
29.785047
115
0.564324
[ "Apache-2.0" ]
UpendoVentures/aws-sdk-net
sdk/src/Services/CodeGuruReviewer/Generated/Model/RepositoryAssociation.cs
6,374
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using SonequaBot.Shared; namespace SonequaBot { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureServices((hostContext, services) => { var configuration = hostContext.Configuration; var options = configuration.GetSection("SonequaSettings").Get<SonequaSettings>(); services.AddSingleton(options); services.AddHostedService<Sonequa>(); }); } }
29.969697
101
0.627907
[ "MIT" ]
Defkon1/SonequaBot
SonequaBot/Program.cs
989
C#
using System.Collections.Generic; using Newtonsoft.Json; namespace ArgentPonyWarcraftClient { /// <summary> /// A PvP leaderboard. /// </summary> public class PvpLeaderboard { /// <summary> /// Gets or sets the characters. /// </summary> [JsonProperty("rows")] public IList<PvpCharacter> Characters { get; set; } } }
21.277778
59
0.592689
[ "MIT" ]
Alyzandestudent/ArgentPonyWarcraftClient
src/ArgentPonyWarcraftClient/Models/PvpLeaderboard.cs
385
C#
// Copyright (c) Daniel Crenna & Contributors. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; namespace TestKitchen.TestAdapter.Tests { public class BasicTests { public BasicTests(TestContext context) { } public bool Hello_world() { return true; } public bool Test_is_skipped(TestContext context) { return context.Skip("skippy as I wanna be"); } public bool Two_string_instances_are_equal(TestContext context) { return "aaa".Equals("AAA", StringComparison.OrdinalIgnoreCase); } public bool Handles_exceptions() { try { throw new ArgumentException(); } catch { return true; } } } }
18.414634
111
0.699338
[ "Apache-2.0" ]
danielcrenna/TestKitchen
test/TestKitchen.TestAdapter.Tests/BasicTests.cs
757
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BossPrize : CollectableItem { public BossPrize(Vector2Int pos): base(pos) { } public override void PickUp() { base.PickUp(); if (OverworldMemory.PlayerProfile != null) { OverworldMemory.PlayerProfile.ProfileStats[eStatType.NumberOfLevelsCompleted].Value += 1; } if (ProceduralDungeon.Instance.NumberOfDungeonsMade == 1) { ProceduralDungeon.Instance.GenerateMap(Room.eArea.Indoors); FlowManager.Instance.TransToOverworld(Settings.SceneOverworld); } else { FlowManager.Instance.TransToGameOver(Settings.SceneOverworld, true); } } }
21.483871
92
0.756757
[ "Apache-2.0" ]
40219124/MonsterMash
MonsterMash/Assets/Scripts/Procedural/Collectable/BossPrize.cs
666
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Linq; using System.Runtime.InteropServices; using Moq; using System.Windows.Forms.TestUtilities; using Xunit; using static Interop; using static Interop.User32; namespace System.Windows.Forms.Tests { using Point = System.Drawing.Point; using Size = System.Drawing.Size; public class ListBoxTests : IClassFixture<ThreadExceptionFixture> { [WinFormsFact] public void ListBox_Ctor_Default() { using var control = new SubListBox(); Assert.Null(control.AccessibleDefaultActionDescription); Assert.Null(control.AccessibleDescription); Assert.Null(control.AccessibleName); Assert.Equal(AccessibleRole.Default, control.AccessibleRole); Assert.False(control.AllowDrop); Assert.True(control.AllowSelection); Assert.Equal(AnchorStyles.Top | AnchorStyles.Left, control.Anchor); Assert.False(control.AutoSize); Assert.Equal(SystemColors.Window, control.BackColor); Assert.Null(control.BackgroundImage); Assert.Equal(ImageLayout.Tile, control.BackgroundImageLayout); Assert.Null(control.BindingContext); Assert.Equal(BorderStyle.Fixed3D, control.BorderStyle); Assert.Equal(96, control.Bottom); Assert.Equal(new Rectangle(0, 0, 120, 96), control.Bounds); Assert.True(control.CanEnableIme); Assert.False(control.CanFocus); Assert.True(control.CanRaiseEvents); Assert.True(control.CanSelect); Assert.False(control.Capture); Assert.True(control.CausesValidation); Assert.Equal(new Size(116, 92), control.ClientSize); Assert.Equal(new Rectangle(0, 0, 116, 92), control.ClientRectangle); Assert.Equal(0, control.ColumnWidth); Assert.Null(control.Container); Assert.False(control.ContainsFocus); Assert.Null(control.ContextMenuStrip); Assert.Empty(control.Controls); Assert.Same(control.Controls, control.Controls); Assert.False(control.Created); Assert.Same(Cursors.Default, control.Cursor); Assert.Empty(control.CustomTabOffsets); Assert.Same(control.CustomTabOffsets, control.CustomTabOffsets); Assert.Null(control.DataManager); Assert.Null(control.DataSource); Assert.Same(Cursors.Default, control.DefaultCursor); Assert.Equal(ImeMode.Inherit, control.DefaultImeMode); Assert.Equal(new Padding(3), control.DefaultMargin); Assert.Equal(Size.Empty, control.DefaultMaximumSize); Assert.Equal(Size.Empty, control.DefaultMinimumSize); Assert.Equal(Padding.Empty, control.DefaultPadding); Assert.Equal(new Size(120, 96), control.DefaultSize); Assert.False(control.DesignMode); Assert.Empty(control.DisplayMember); Assert.Equal(new Rectangle(0, 0, 116, 92), control.DisplayRectangle); Assert.Equal(DockStyle.None, control.Dock); Assert.False(control.DoubleBuffered); Assert.Equal(DrawMode.Normal, control.DrawMode); Assert.True(control.Enabled); Assert.NotNull(control.Events); Assert.Same(control.Events, control.Events); Assert.False(control.Focused); Assert.Equal(Control.DefaultFont, control.Font); Assert.Equal(control.Font.Height, control.FontHeight); Assert.Equal(SystemColors.WindowText, control.ForeColor); Assert.Null(control.FormatInfo); Assert.Empty(control.FormatString); Assert.False(control.FormattingEnabled); Assert.False(control.HasChildren); Assert.Equal(96, control.Height); Assert.Equal(0, control.HorizontalExtent); Assert.False(control.HorizontalScrollbar); Assert.Equal(ImeMode.NoControl, control.ImeMode); Assert.Equal(ImeMode.NoControl, control.ImeModeBase); Assert.True(control.IntegralHeight); Assert.False(control.IsAccessible); Assert.False(control.IsMirrored); Assert.Equal(13, control.ItemHeight); Assert.Empty(control.Items); Assert.Same(control.Items, control.Items); Assert.NotNull(control.LayoutEngine); Assert.Same(control.LayoutEngine, control.LayoutEngine); Assert.Equal(0, control.Left); Assert.Equal(Point.Empty, control.Location); Assert.Equal(new Padding(3), control.Margin); Assert.Equal(Size.Empty, control.MaximumSize); Assert.Equal(Size.Empty, control.MinimumSize); Assert.False(control.MultiColumn); Assert.Equal(Padding.Empty, control.Padding); Assert.Null(control.Parent); Assert.Equal("Microsoft\u00AE .NET", control.ProductName); Assert.Equal(13 + SystemInformation.BorderSize.Height * 4 + 3, control.PreferredHeight); Assert.Equal(new Size(120, 96), control.PreferredSize); Assert.False(control.RecreatingHandle); Assert.Null(control.Region); Assert.False(control.ResizeRedraw); Assert.Equal(120, control.Right); Assert.Equal(RightToLeft.No, control.RightToLeft); Assert.False(control.ScrollAlwaysVisible); Assert.Null(control.SelectedValue); Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Same(control.SelectedIndices, control.SelectedIndices); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedItems); Assert.Same(control.SelectedItems, control.SelectedItems); Assert.Equal(SelectionMode.One, control.SelectionMode); Assert.True(control.ShowFocusCues); Assert.True(control.ShowKeyboardCues); Assert.Null(control.Site); Assert.Equal(new Size(120, 96), control.Size); Assert.False(control.Sorted); Assert.Equal(0, control.TabIndex); Assert.True(control.TabStop); Assert.Empty(control.Text); Assert.Equal(0, control.Top); Assert.Equal(0, control.TopIndex); Assert.Null(control.TopLevelControl); Assert.False(control.UseCustomTabOffsets); Assert.True(control.UseTabStops); Assert.False(control.UseWaitCursor); Assert.Empty(control.ValueMember); Assert.True(control.Visible); Assert.Equal(120, control.Width); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void ListBox_CreateParams_GetDefault_ReturnsExpected() { using var control = new SubListBox(); CreateParams createParams = control.CreateParams; Assert.Null(createParams.Caption); Assert.Equal("ListBox", createParams.ClassName); Assert.Equal(0x8, createParams.ClassStyle); Assert.Equal(0x200, createParams.ExStyle); Assert.Equal(96, createParams.Height); Assert.Equal(IntPtr.Zero, createParams.Parent); Assert.Null(createParams.Param); Assert.Equal(0x562100C1, createParams.Style); Assert.Equal(120, createParams.Width); Assert.Equal(0, createParams.X); Assert.Equal(0, createParams.Y); Assert.Same(createParams, control.CreateParams); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(true, 0x562110C1)] [InlineData(false, 0x562100C1)] public void ListBox_CreateParams_GetScrollAlwaysVisible_ReturnsExpected(bool scrollAlwaysVisible, int expectedStyle) { using var control = new SubListBox { ScrollAlwaysVisible = scrollAlwaysVisible }; CreateParams createParams = control.CreateParams; Assert.Null(createParams.Caption); Assert.Equal("ListBox", createParams.ClassName); Assert.Equal(0x8, createParams.ClassStyle); Assert.Equal(0x200, createParams.ExStyle); Assert.Equal(96, createParams.Height); Assert.Equal(IntPtr.Zero, createParams.Parent); Assert.Null(createParams.Param); Assert.Equal(expectedStyle, createParams.Style); Assert.Equal(120, createParams.Width); Assert.Equal(0, createParams.X); Assert.Equal(0, createParams.Y); Assert.Same(createParams, control.CreateParams); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(true, 0x562100C1)] [InlineData(false, 0x562101C1)] public void ListBox_CreateParams_GetIntegralHeight_ReturnsExpected(bool integralHeight, int expectedStyle) { using var control = new SubListBox { IntegralHeight = integralHeight }; CreateParams createParams = control.CreateParams; Assert.Null(createParams.Caption); Assert.Equal("ListBox", createParams.ClassName); Assert.Equal(0x8, createParams.ClassStyle); Assert.Equal(0x200, createParams.ExStyle); Assert.Equal(96, createParams.Height); Assert.Equal(IntPtr.Zero, createParams.Parent); Assert.Null(createParams.Param); Assert.Equal(expectedStyle, createParams.Style); Assert.Equal(120, createParams.Width); Assert.Equal(0, createParams.X); Assert.Equal(0, createParams.Y); Assert.Same(createParams, control.CreateParams); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(true, 0x562100C1)] [InlineData(false, 0x56210041)] public void ListBox_CreateParams_GetUseTabStops_ReturnsExpected(bool useTabStops, int expectedStyle) { using var control = new SubListBox { UseTabStops = useTabStops }; CreateParams createParams = control.CreateParams; Assert.Null(createParams.Caption); Assert.Equal("ListBox", createParams.ClassName); Assert.Equal(0x8, createParams.ClassStyle); Assert.Equal(0x200, createParams.ExStyle); Assert.Equal(96, createParams.Height); Assert.Equal(IntPtr.Zero, createParams.Parent); Assert.Null(createParams.Param); Assert.Equal(expectedStyle, createParams.Style); Assert.Equal(120, createParams.Width); Assert.Equal(0, createParams.X); Assert.Equal(0, createParams.Y); Assert.Same(createParams, control.CreateParams); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(BorderStyle.None, 0x562100C1, 0)] [InlineData(BorderStyle.Fixed3D, 0x562100C1, 0x200)] [InlineData(BorderStyle.FixedSingle, 0x56A100C1, 0)] public void ListBox_CreateParams_GetBorderStyle_ReturnsExpected(BorderStyle borderStyle, int expectedStyle, int expectedExStyle) { using var control = new SubListBox { BorderStyle = borderStyle }; CreateParams createParams = control.CreateParams; Assert.Null(createParams.Caption); Assert.Equal("ListBox", createParams.ClassName); Assert.Equal(0x8, createParams.ClassStyle); Assert.Equal(expectedExStyle, createParams.ExStyle); Assert.Equal(96, createParams.Height); Assert.Equal(IntPtr.Zero, createParams.Parent); Assert.Null(createParams.Param); Assert.Equal(expectedStyle, createParams.Style); Assert.Equal(120, createParams.Width); Assert.Equal(0, createParams.X); Assert.Equal(0, createParams.Y); Assert.Same(createParams, control.CreateParams); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(true, true, 0x563102C1)] [InlineData(true, false, 0x563102C1)] [InlineData(false, true, 0x563100C1)] [InlineData(false, false, 0x562100C1)] public void ListBox_CreateParams_GetMultiColumn_ReturnsExpected(bool multiColumn, bool horizontalScrollBar, int expectedStyle) { using var control = new SubListBox { MultiColumn = multiColumn, HorizontalScrollbar = horizontalScrollBar }; CreateParams createParams = control.CreateParams; Assert.Null(createParams.Caption); Assert.Equal("ListBox", createParams.ClassName); Assert.Equal(0x8, createParams.ClassStyle); Assert.Equal(0x200, createParams.ExStyle); Assert.Equal(96, createParams.Height); Assert.Equal(IntPtr.Zero, createParams.Parent); Assert.Null(createParams.Param); Assert.Equal(expectedStyle, createParams.Style); Assert.Equal(120, createParams.Width); Assert.Equal(0, createParams.X); Assert.Equal(0, createParams.Y); Assert.Same(createParams, control.CreateParams); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(SelectionMode.MultiExtended, 0x562108C1)] [InlineData(SelectionMode.MultiSimple, 0x562100C9)] [InlineData(SelectionMode.None, 0x562140C1)] [InlineData(SelectionMode.One, 0x562100C1)] public void ListBox_CreateParams_GetSelectionMode_ReturnsExpected(SelectionMode selectionMode, int expectedStyle) { using var control = new SubListBox { SelectionMode = selectionMode }; CreateParams createParams = control.CreateParams; Assert.Null(createParams.Caption); Assert.Equal("ListBox", createParams.ClassName); Assert.Equal(0x8, createParams.ClassStyle); Assert.Equal(0x200, createParams.ExStyle); Assert.Equal(96, createParams.Height); Assert.Equal(IntPtr.Zero, createParams.Parent); Assert.Null(createParams.Param); Assert.Equal(expectedStyle, createParams.Style); Assert.Equal(120, createParams.Width); Assert.Equal(0, createParams.X); Assert.Equal(0, createParams.Y); Assert.Same(createParams, control.CreateParams); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(DrawMode.Normal, 0x562100C1)] [InlineData(DrawMode.OwnerDrawFixed, 0x562100D1)] [InlineData(DrawMode.OwnerDrawVariable, 0x562100E1)] public void ListBox_CreateParams_GetDrawMode_ReturnsExpected(DrawMode drawMode, int expectedStyle) { using var control = new SubListBox { DrawMode = drawMode }; CreateParams createParams = control.CreateParams; Assert.Null(createParams.Caption); Assert.Equal("ListBox", createParams.ClassName); Assert.Equal(0x8, createParams.ClassStyle); Assert.Equal(0x200, createParams.ExStyle); Assert.Equal(96, createParams.Height); Assert.Equal(IntPtr.Zero, createParams.Parent); Assert.Null(createParams.Param); Assert.Equal(expectedStyle, createParams.Style); Assert.Equal(120, createParams.Width); Assert.Equal(0, createParams.X); Assert.Equal(0, createParams.Y); Assert.Same(createParams, control.CreateParams); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> BackColor_Set_TestData() { yield return new object[] { Color.Empty, SystemColors.Window }; yield return new object[] { Color.Red, Color.Red }; } [WinFormsTheory] [MemberData(nameof(BackColor_Set_TestData))] public void ListBox_BackColor_Set_GetReturnsExpected(Color value, Color expected) { using var control = new ListBox { BackColor = value }; Assert.Equal(expected, control.BackColor); Assert.False(control.IsHandleCreated); // Set same. control.BackColor = value; Assert.Equal(expected, control.BackColor); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> BackColor_SetWithHandle_TestData() { yield return new object[] { Color.Empty, SystemColors.Window, 0 }; yield return new object[] { Color.Red, Color.Red, 1 }; } [WinFormsTheory] [MemberData(nameof(BackColor_SetWithHandle_TestData))] public void ListBox_BackColor_SetWithHandle_GetReturnsExpected(Color value, Color expected, int expectedInvalidatedCallCount) { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.BackColor = value; Assert.Equal(expected, control.BackColor); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.BackColor = value; Assert.Equal(expected, control.BackColor); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void ListBox_BackColor_SetWithHandler_CallsBackColorChanged() { using var control = new ListBox(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; control.BackColorChanged += handler; // Set different. control.BackColor = Color.Red; Assert.Equal(Color.Red, control.BackColor); Assert.Equal(1, callCount); // Set same. control.BackColor = Color.Red; Assert.Equal(Color.Red, control.BackColor); Assert.Equal(1, callCount); // Set different. control.BackColor = Color.Empty; Assert.Equal(SystemColors.Window, control.BackColor); Assert.Equal(2, callCount); // Remove handler. control.BackColorChanged -= handler; control.BackColor = Color.Red; Assert.Equal(Color.Red, control.BackColor); Assert.Equal(2, callCount); } [WinFormsFact] public void ListBox_BackColor_ResetValue_Success() { PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(ListBox))[nameof(ListBox.BackColor)]; using var control = new ListBox(); Assert.False(property.CanResetValue(control)); control.BackColor = Color.Red; Assert.Equal(Color.Red, control.BackColor); Assert.True(property.CanResetValue(control)); property.ResetValue(control); Assert.Equal(SystemColors.Window, control.BackColor); Assert.False(property.CanResetValue(control)); } [WinFormsFact] public void ListBox_BackColor_ShouldSerializeValue_Success() { PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(ListBox))[nameof(ListBox.BackColor)]; using var control = new ListBox(); Assert.False(property.ShouldSerializeValue(control)); control.BackColor = Color.Red; Assert.Equal(Color.Red, control.BackColor); Assert.True(property.ShouldSerializeValue(control)); property.ResetValue(control); Assert.Equal(SystemColors.Window, control.BackColor); Assert.False(property.ShouldSerializeValue(control)); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelperEx), nameof(CommonTestHelperEx.GetImageTheoryData))] public void ListBox_BackgroundImage_Set_GetReturnsExpected(Image value) { using var control = new ListBox { BackgroundImage = value }; Assert.Same(value, control.BackgroundImage); Assert.False(control.IsHandleCreated); // Set same. control.BackgroundImage = value; Assert.Same(value, control.BackgroundImage); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void ListBox_BackgroundImage_SetWithHandler_CallsBackgroundImageChanged() { using var control = new ListBox(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; control.BackgroundImageChanged += handler; // Set different. using var image1 = new Bitmap(10, 10); control.BackgroundImage = image1; Assert.Same(image1, control.BackgroundImage); Assert.Equal(1, callCount); // Set same. control.BackgroundImage = image1; Assert.Same(image1, control.BackgroundImage); Assert.Equal(1, callCount); // Set different. using var image2 = new Bitmap(10, 10); control.BackgroundImage = image2; Assert.Same(image2, control.BackgroundImage); Assert.Equal(2, callCount); // Set null. control.BackgroundImage = null; Assert.Null(control.BackgroundImage); Assert.Equal(3, callCount); // Remove handler. control.BackgroundImageChanged -= handler; control.BackgroundImage = image1; Assert.Same(image1, control.BackgroundImage); Assert.Equal(3, callCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(ImageLayout))] public void ListBox_BackgroundImageLayout_Set_GetReturnsExpected(ImageLayout value) { using var control = new ListBox { BackgroundImageLayout = value }; Assert.Equal(value, control.BackgroundImageLayout); Assert.False(control.IsHandleCreated); // Set same. control.BackgroundImageLayout = value; Assert.Equal(value, control.BackgroundImageLayout); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void ListBox_BackgroundImageLayout_SetWithHandler_CallsBackgroundImageLayoutChanged() { using var control = new ListBox(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; control.BackgroundImageLayoutChanged += handler; // Set different. control.BackgroundImageLayout = ImageLayout.Center; Assert.Equal(ImageLayout.Center, control.BackgroundImageLayout); Assert.Equal(1, callCount); // Set same. control.BackgroundImageLayout = ImageLayout.Center; Assert.Equal(ImageLayout.Center, control.BackgroundImageLayout); Assert.Equal(1, callCount); // Set different. control.BackgroundImageLayout = ImageLayout.Stretch; Assert.Equal(ImageLayout.Stretch, control.BackgroundImageLayout); Assert.Equal(2, callCount); // Remove handler. control.BackgroundImageLayoutChanged -= handler; control.BackgroundImageLayout = ImageLayout.Center; Assert.Equal(ImageLayout.Center, control.BackgroundImageLayout); Assert.Equal(2, callCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(ImageLayout))] public void ListBox_BackgroundImageLayout_SetInvalid_ThrowsInvalidEnumArgumentException(ImageLayout value) { using var control = new ListBox(); Assert.Throws<InvalidEnumArgumentException>("value", () => control.BackgroundImageLayout = value); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(BorderStyle))] public void ListBox_BorderStyle_Set_GetReturnsExpected(BorderStyle value) { using var control = new ListBox() { BorderStyle = value }; Assert.Equal(value, control.BorderStyle); Assert.Equal(96, control.Height); Assert.False(control.IsHandleCreated); // Set same. control.BorderStyle = value; Assert.Equal(value, control.BorderStyle); Assert.Equal(96, control.Height); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(BorderStyle.Fixed3D, 0)] [InlineData(BorderStyle.FixedSingle, 1)] [InlineData(BorderStyle.None, 1)] public void ListBox_BorderStyle_SetWithHandle_GetReturnsExpected(BorderStyle value, int expectedCreatedCallCount) { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.BorderStyle = value; Assert.Equal(value, control.BorderStyle); Assert.True(control.Height > 0); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); // Set same. control.BorderStyle = value; Assert.Equal(value, control.BorderStyle); Assert.True(control.Height > 0); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(BorderStyle))] public void ListBox_BorderStyle_SetInvalid_ThrowsInvalidEnumArgumentException(BorderStyle value) { using var control = new ListBox(); Assert.Throws<InvalidEnumArgumentException>("value", () => control.BorderStyle = value); } [WinFormsTheory] [InlineData(0)] [InlineData(1)] [InlineData(60)] [InlineData(int.MaxValue)] public void ListBox_ColumnWidth_Set_GetReturnsExpected(int value) { using var control = new ListBox { ColumnWidth = value }; Assert.Equal(value, control.ColumnWidth); Assert.False(control.IsHandleCreated); control.ColumnWidth = value; Assert.Equal(value, control.ColumnWidth); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(0)] [InlineData(1)] [InlineData(60)] [InlineData(int.MaxValue)] public void ListBox_ColumnWidth_SetWithCustomOldValue_GetReturnsExpected(int value) { using var control = new ListBox { ColumnWidth = 10 }; control.ColumnWidth = value; Assert.Equal(value, control.ColumnWidth); Assert.False(control.IsHandleCreated); control.ColumnWidth = value; Assert.Equal(value, control.ColumnWidth); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(0)] [InlineData(1)] [InlineData(60)] [InlineData(int.MaxValue)] public void ListBox_ColumnWidth_SetWithHandle_GetReturnsExpected(int value) { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.ColumnWidth = value; Assert.Equal(value, control.ColumnWidth); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); control.ColumnWidth = value; Assert.Equal(value, control.ColumnWidth); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [InlineData(0, 1)] [InlineData(1, 0)] [InlineData(60, 0)] [InlineData(int.MaxValue, 0)] public void ListBox_ColumnWidth_SetWithCustomOldValueWithHandle_GetReturnsExpected(int value, int expectedCreatedCallCount) { using var control = new ListBox { ColumnWidth = 10 }; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.ColumnWidth = value; Assert.Equal(value, control.ColumnWidth); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); control.ColumnWidth = value; Assert.Equal(value, control.ColumnWidth); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); } [WinFormsFact] public void ListBox_ColumnWidth_GetItemRect_ReturnsExpected() { using var control = new ListBox { MultiColumn = true }; control.Items.Add("Value"); Assert.NotEqual(IntPtr.Zero, control.Handle); control.ColumnWidth = 123; RECT rc = default; Assert.Equal((IntPtr)1, SendMessageW(control.Handle, (WM)LB.GETITEMRECT, (IntPtr)0, ref rc)); Assert.Equal(123, ((Rectangle)rc).Width); } [WinFormsFact] public void ListBox_ColumnWidth_SetNegative_ThrowsArgumentOutOfRangeException() { using var control = new ListBox(); Assert.Throws<ArgumentOutOfRangeException>("value", () => control.ColumnWidth = -1); } public static IEnumerable<object[]> DataSource_Set_TestData() { yield return new object[] { null }; yield return new object[] { new List<int>() }; yield return new object[] { Array.Empty<int>() }; var mockSource = new Mock<IListSource>(MockBehavior.Strict); mockSource .Setup(s => s.GetList()) .Returns(new int[] { 1 }); yield return new object[] { mockSource.Object }; } [WinFormsTheory] [MemberData(nameof(DataSource_Set_TestData))] public void ListBox_DataSource_Set_GetReturnsExpected(object value) { using var control = new SubListBox { DataSource = value }; Assert.Same(value, control.DataSource); Assert.Empty(control.DisplayMember); Assert.Null(control.DataManager); Assert.False(control.IsHandleCreated); // Set same. control.DataSource = value; Assert.Same(value, control.DataSource); Assert.Empty(control.DisplayMember); Assert.Null(control.DataManager); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void ListBox_DataSource_SetWithHandler_CallsDataSourceChanged() { using var control = new ListBox(); int dataSourceCallCount = 0; int displayMemberCallCount = 0; EventHandler dataSourceHandler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); dataSourceCallCount++; }; EventHandler displayMemberHandler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); displayMemberCallCount++; }; control.DataSourceChanged += dataSourceHandler; control.DisplayMemberChanged += displayMemberHandler; // Set different. var dataSource1 = new List<int>(); control.DataSource = dataSource1; Assert.Same(dataSource1, control.DataSource); Assert.Equal(1, dataSourceCallCount); Assert.Equal(0, displayMemberCallCount); // Set same. control.DataSource = dataSource1; Assert.Same(dataSource1, control.DataSource); Assert.Equal(1, dataSourceCallCount); Assert.Equal(0, displayMemberCallCount); // Set different. var dataSource2 = new List<int>(); control.DataSource = dataSource2; Assert.Same(dataSource2, control.DataSource); Assert.Equal(2, dataSourceCallCount); Assert.Equal(0, displayMemberCallCount); // Set null. control.DataSource = null; Assert.Null(control.DataSource); Assert.Equal(3, dataSourceCallCount); Assert.Equal(0, displayMemberCallCount); // Remove handler. control.DataSourceChanged -= dataSourceHandler; control.DisplayMemberChanged -= displayMemberHandler; control.DataSource = dataSource1; Assert.Same(dataSource1, control.DataSource); Assert.Equal(3, dataSourceCallCount); Assert.Equal(0, displayMemberCallCount); } public static IEnumerable<object[]> DrawMode_Set_TestData() { foreach (bool autoSize in new bool[] { true, false }) { yield return new object[] { autoSize, true, DrawMode.Normal }; yield return new object[] { autoSize, false, DrawMode.Normal }; yield return new object[] { autoSize, true, DrawMode.OwnerDrawFixed }; yield return new object[] { autoSize, false, DrawMode.OwnerDrawFixed }; yield return new object[] { autoSize, false, DrawMode.OwnerDrawVariable }; } } [WinFormsTheory] [MemberData(nameof(DrawMode_Set_TestData))] public void ListBox_DrawMode_Set_GetReturnsExpected(bool autoSize, bool multiColumn, DrawMode value) { using var control = new ListBox { AutoSize = autoSize, MultiColumn = multiColumn }; int layoutCallCount = 0; control.Layout += (sender, e) => layoutCallCount++; control.DrawMode = value; Assert.Equal(value, control.DrawMode); Assert.Equal(0, layoutCallCount); Assert.False(control.IsHandleCreated); // Set same. control.DrawMode = value; Assert.Equal(value, control.DrawMode); Assert.Equal(0, layoutCallCount); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> DrawMode_SetWithParent_TestData() { yield return new object[] { true, true, DrawMode.Normal, 0 }; yield return new object[] { true, false, DrawMode.Normal, 0 }; yield return new object[] { false, true, DrawMode.Normal, 0 }; yield return new object[] { false, false, DrawMode.Normal, 0 }; yield return new object[] { true, true, DrawMode.OwnerDrawFixed, 0 }; yield return new object[] { true, false, DrawMode.OwnerDrawFixed, 0 }; yield return new object[] { false, true, DrawMode.OwnerDrawFixed, 0 }; yield return new object[] { false, false, DrawMode.OwnerDrawFixed, 0 }; yield return new object[] { true, false, DrawMode.OwnerDrawVariable, 1 }; yield return new object[] { false, false, DrawMode.OwnerDrawVariable, 0 }; } [WinFormsTheory] [MemberData(nameof(DrawMode_SetWithParent_TestData))] public void ListBox_DrawMode_SetWithParent_GetReturnsExpected(bool autoSize, bool multiColumn, DrawMode value, int expectedParentLayoutCallCount) { using var parent = new Control(); using var control = new ListBox { AutoSize = autoSize, MultiColumn = multiColumn, Parent = parent }; int layoutCallCount = 0; control.Layout += (sender, e) => layoutCallCount++; int parentLayoutCallCount = 0; void parentHandler(object sender, LayoutEventArgs e) { Assert.Same(parent, sender); Assert.Same(control, e.AffectedControl); Assert.Equal("DrawMode", e.AffectedProperty); parentLayoutCallCount++; } parent.Layout += parentHandler; try { control.DrawMode = value; Assert.Equal(value, control.DrawMode); Assert.Equal(0, layoutCallCount); Assert.Equal(expectedParentLayoutCallCount, parentLayoutCallCount); Assert.False(control.IsHandleCreated); Assert.False(parent.IsHandleCreated); // Set same. control.DrawMode = value; Assert.Equal(value, control.DrawMode); Assert.Equal(0, layoutCallCount); Assert.Equal(expectedParentLayoutCallCount, parentLayoutCallCount); Assert.False(control.IsHandleCreated); Assert.False(parent.IsHandleCreated); } finally { parent.Layout -= parentHandler; } } public static IEnumerable<object[]> DrawMode_SetWithHandle_TestData() { foreach (bool autoSize in new bool[] { true, false }) { yield return new object[] { autoSize, true, DrawMode.Normal, 0 }; yield return new object[] { autoSize, false, DrawMode.Normal, 0 }; yield return new object[] { autoSize, true, DrawMode.OwnerDrawFixed, 1 }; yield return new object[] { autoSize, false, DrawMode.OwnerDrawFixed, 1 }; yield return new object[] { autoSize, false, DrawMode.OwnerDrawVariable, 1 }; } } [WinFormsTheory] [MemberData(nameof(DrawMode_SetWithHandle_TestData))] public void ListBox_DrawMode_SetWithHandle_GetReturnsExpected(bool autoSize, bool multiColumn, DrawMode value, int expectedCreatedCallCount) { using var control = new ListBox { AutoSize = autoSize, MultiColumn = multiColumn }; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; int layoutCallCount = 0; control.Layout += (sender, e) => layoutCallCount++; control.DrawMode = value; Assert.Equal(value, control.DrawMode); Assert.Equal(expectedCreatedCallCount * 2, layoutCallCount); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); // Set same. control.DrawMode = value; Assert.Equal(value, control.DrawMode); Assert.Equal(expectedCreatedCallCount * 2, layoutCallCount); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(DrawMode))] public void ListBox_DrawMode_SetInvalidValue_ThrowsInvalidEnumArgumentException(DrawMode value) { using var control = new ListBox(); Assert.Throws<InvalidEnumArgumentException>("value", () => control.DrawMode = value); } [WinFormsFact] public void ListBox_DrawMode_SetMultiColumnOwnerDrawVariable_ThrowsArgumentException() { using var control = new ListBox { MultiColumn = true }; Assert.Throws<ArgumentException>("value", () => control.DrawMode = DrawMode.OwnerDrawVariable); } public static IEnumerable<object[]> Font_Set_TestData() { foreach (bool integralHeight in new bool[] { true, false }) { yield return new object[] { integralHeight, null }; yield return new object[] { integralHeight, new Font("Arial", 8.25f) }; } } [WinFormsTheory] [MemberData(nameof(Font_Set_TestData))] public void ListBox_Font_Set_GetReturnsExpected(bool integralHeight, Font value) { using var control = new SubListBox { IntegralHeight = integralHeight, Font = value }; Assert.Equal(value ?? Control.DefaultFont, control.Font); Assert.Equal(control.Font.Height, control.FontHeight); Assert.Equal(96, control.Height); Assert.Empty(control.Items); Assert.False(control.IsHandleCreated); // Set same. control.Font = value; Assert.Equal(value ?? Control.DefaultFont, control.Font); Assert.Equal(control.Font.Height, control.FontHeight); Assert.Equal(96, control.Height); Assert.Empty(control.Items); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(Font_Set_TestData))] public void ListBox_Font_SetWithItems_GetReturnsExpected(bool integralHeight, Font value) { using var control = new SubListBox { IntegralHeight = integralHeight }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); control.Font = value; Assert.Equal(value ?? Control.DefaultFont, control.Font); Assert.Equal(control.Font.Height, control.FontHeight); Assert.Equal(96, control.Height); Assert.Equal(new string[] { "item1", "item2", "item1" }, control.Items.Cast<object>()); Assert.False(control.IsHandleCreated); // Set same. control.Font = value; Assert.Equal(value ?? Control.DefaultFont, control.Font); Assert.Equal(control.Font.Height, control.FontHeight); Assert.Equal(96, control.Height); Assert.Equal(new string[] { "item1", "item2", "item1" }, control.Items.Cast<object>()); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> Font_SetWithHandle_TestData() { yield return new object[] { true, null, 0, 0 }; yield return new object[] { false, null, 0, 1 }; yield return new object[] { true, new Font("Arial", 8.25f), 1, 1 }; yield return new object[] { false, new Font("Arial", 8.25f), 1, 2 }; } [WinFormsTheory] [MemberData(nameof(Font_SetWithHandle_TestData))] public void ListBox_Font_SetWithHandle_GetReturnsExpected(bool integralHeight, Font value, int expectedInvalidatedCallCount1, int expectedInvalidatedCallCount2) { using var control = new SubListBox { IntegralHeight = integralHeight }; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.Font = value; Assert.Equal(value ?? Control.DefaultFont, control.Font); Assert.Equal(control.Font.Height, control.FontHeight); Assert.True(control.Height > 0); Assert.Empty(control.Items); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.Font = value; Assert.Equal(value ?? Control.DefaultFont, control.Font); Assert.Equal(control.Font.Height, control.FontHeight); Assert.True(control.Height > 0); Assert.Empty(control.Items); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount2, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } public static IEnumerable<object[]> Font_SetHandleWithItems_TestData() { yield return new object[] { true, null, 0, 0 }; yield return new object[] { false, null, 1, 2 }; yield return new object[] { true, new Font("Arial", 8.25f), 1, 1 }; yield return new object[] { false, new Font("Arial", 8.25f), 2, 3 }; } [WinFormsTheory] [MemberData(nameof(Font_SetHandleWithItems_TestData))] public void ListBox_Font_SetWithItemsWithHandle_GetReturnsExpected(bool integralHeight, Font value, int expectedInvalidatedCallCount1, int expectedInvalidatedCallCount2) { using var control = new SubListBox { IntegralHeight = integralHeight }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.Font = value; Assert.Equal(value ?? Control.DefaultFont, control.Font); Assert.Equal(control.Font.Height, control.FontHeight); Assert.True(control.Height > 0); Assert.Equal(new string[] { "item1", "item2", "item1" }, control.Items.Cast<object>()); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.Font = value; Assert.Equal(value ?? Control.DefaultFont, control.Font); Assert.Equal(control.Font.Height, control.FontHeight); Assert.True(control.Height > 0); Assert.Equal(new string[] { "item1", "item2", "item1" }, control.Items.Cast<object>()); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount2, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void ListBox_Font_SetWithHandler_CallsFontChanged() { using var control = new ListBox(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; control.FontChanged += handler; // Set different. using var font1 = new Font("Arial", 8.25f); control.Font = font1; Assert.Same(font1, control.Font); Assert.Equal(1, callCount); // Set same. control.Font = font1; Assert.Same(font1, control.Font); Assert.Equal(1, callCount); // Set different. using var font2 = SystemFonts.DialogFont; control.Font = font2; Assert.Same(font2, control.Font); Assert.Equal(2, callCount); // Set null. control.Font = null; Assert.Equal(Control.DefaultFont, control.Font); Assert.Equal(3, callCount); // Remove handler. control.FontChanged -= handler; control.Font = font1; Assert.Same(font1, control.Font); Assert.Equal(3, callCount); } public static IEnumerable<object[]> ForeColor_Set_TestData() { yield return new object[] { Color.Empty, SystemColors.WindowText }; yield return new object[] { Color.FromArgb(254, 1, 2, 3), Color.FromArgb(254, 1, 2, 3) }; yield return new object[] { Color.White, Color.White }; yield return new object[] { Color.Black, Color.Black }; yield return new object[] { Color.Red, Color.Red }; } [WinFormsTheory] [MemberData(nameof(ForeColor_Set_TestData))] public void ListBox_ForeColor_Set_GetReturnsExpected(Color value, Color expected) { using var control = new ListBox { ForeColor = value }; Assert.Equal(expected, control.ForeColor); Assert.False(control.IsHandleCreated); // Set same. control.ForeColor = value; Assert.Equal(expected, control.ForeColor); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> ForeColor_SetWithHandle_TestData() { yield return new object[] { Color.Empty, SystemColors.WindowText, 0 }; yield return new object[] { Color.FromArgb(254, 1, 2, 3), Color.FromArgb(254, 1, 2, 3), 1 }; yield return new object[] { Color.White, Color.White, 1 }; yield return new object[] { Color.Black, Color.Black, 1 }; yield return new object[] { Color.Red, Color.Red, 1 }; } [WinFormsTheory] [MemberData(nameof(ForeColor_SetWithHandle_TestData))] public void ListBox_ForeColor_SetWithHandle_GetReturnsExpected(Color value, Color expected, int expectedInvalidatedCallCount) { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.ForeColor = value; Assert.Equal(expected, control.ForeColor); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.ForeColor = value; Assert.Equal(expected, control.ForeColor); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void ListBox_ForeColor_SetWithHandler_CallsForeColorChanged() { using var control = new ListBox(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; control.ForeColorChanged += handler; // Set different. control.ForeColor = Color.Red; Assert.Equal(Color.Red, control.ForeColor); Assert.Equal(1, callCount); // Set same. control.ForeColor = Color.Red; Assert.Equal(Color.Red, control.ForeColor); Assert.Equal(1, callCount); // Set different. control.ForeColor = Color.Empty; Assert.Equal(SystemColors.WindowText, control.ForeColor); Assert.Equal(2, callCount); // Remove handler. control.ForeColorChanged -= handler; control.ForeColor = Color.Red; Assert.Equal(Color.Red, control.ForeColor); Assert.Equal(2, callCount); } [WinFormsFact] public void ListBox_ForeColor_ResetValue_Success() { PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(ListBox))[nameof(ListBox.ForeColor)]; using var control = new ListBox(); Assert.False(property.CanResetValue(control)); control.ForeColor = Color.Red; Assert.Equal(Color.Red, control.ForeColor); Assert.True(property.CanResetValue(control)); property.ResetValue(control); Assert.Equal(SystemColors.WindowText, control.ForeColor); Assert.False(property.CanResetValue(control)); } [WinFormsFact] public void ListBox_ForeColor_ShouldSerializeValue_Success() { PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(ListBox))[nameof(ListBox.ForeColor)]; using var control = new ListBox(); Assert.False(property.ShouldSerializeValue(control)); control.ForeColor = Color.Red; Assert.Equal(Color.Red, control.ForeColor); Assert.True(property.ShouldSerializeValue(control)); property.ResetValue(control); Assert.Equal(SystemColors.WindowText, control.ForeColor); Assert.False(property.ShouldSerializeValue(control)); } public static IEnumerable<object[]> HorizontalExtent_Set_TestData() { foreach (bool multiColumn in new bool[] { true, false }) { foreach (bool horizontalScrollbar in new bool[] { true, false }) { yield return new object[] { multiColumn, horizontalScrollbar, -1 }; yield return new object[] { multiColumn, horizontalScrollbar, 0 }; yield return new object[] { multiColumn, horizontalScrollbar, 120 }; } } } [WinFormsTheory] [MemberData(nameof(HorizontalExtent_Set_TestData))] public void ListBox_HorizontalExtent_Set_GetReturnsExpected(bool multiColumn, bool horizontalScrollBar, int value) { using var control = new ListBox { MultiColumn = multiColumn, HorizontalScrollbar = horizontalScrollBar, HorizontalExtent = value }; Assert.Equal(value, control.HorizontalExtent); Assert.False(control.IsHandleCreated); // Set same. control.HorizontalExtent = value; Assert.Equal(value, control.HorizontalExtent); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> HorizontalExtent_SetWithHandle_TestData() { foreach (bool multiColumn in new bool[] { true, false }) { foreach (bool horizontalScrollbar in new bool[] { true, false }) { yield return new object[] { multiColumn, horizontalScrollbar, -1, 0 }; yield return new object[] { multiColumn, horizontalScrollbar, 0, 0 }; yield return new object[] { multiColumn, horizontalScrollbar, 120, !multiColumn && horizontalScrollbar ? 1 : 0 }; } } } [WinFormsTheory] [MemberData(nameof(HorizontalExtent_SetWithHandle_TestData))] public void ListBox_HorizontalExtent_SetWithHandle_GetReturnsExpected(bool multiColumn, bool horizontalScrollBar, int value, int expectedInvalidatedCallCount) { using var control = new ListBox { MultiColumn = multiColumn, HorizontalScrollbar = horizontalScrollBar }; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.HorizontalExtent = value; Assert.Equal(value, control.HorizontalExtent); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.HorizontalExtent = value; Assert.Equal(value, control.HorizontalExtent); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [InlineData(true, true, 0)] [InlineData(true, false, 0)] [InlineData(false, true, 10)] [InlineData(false, false, 0)] public void ListBox_HorizontalExtent_GetHorizontalExtent_Success(bool multiColumn, bool horizontalScrollBar, int expected) { using var control = new ListBox { MultiColumn = multiColumn, HorizontalScrollbar = horizontalScrollBar }; Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Equal(0, control.HorizontalExtent); Assert.Equal((IntPtr)0, SendMessageW(control.Handle, (WM)LB.GETHORIZONTALEXTENT)); control.HorizontalExtent = 10; Assert.Equal((IntPtr)expected, SendMessageW(control.Handle, (WM)LB.GETHORIZONTALEXTENT)); } public static IEnumerable<object[]> HorizontalScrollbar_Set_TestData() { foreach (bool multiColumn in new bool[] { true, false }) { yield return new object[] { multiColumn, true }; } } [WinFormsTheory] [MemberData(nameof(HorizontalScrollbar_Set_TestData))] public void ListBox_HorizontalScrollbar_Set_GetReturnsExpected(bool multiColumn, bool value) { using var control = new ListBox { MultiColumn = multiColumn, HorizontalScrollbar = value }; Assert.Equal(value, control.HorizontalScrollbar); Assert.Empty(control.Items); Assert.False(control.IsHandleCreated); // Set same. control.HorizontalScrollbar = value; Assert.Equal(value, control.HorizontalScrollbar); Assert.Empty(control.Items); Assert.False(control.IsHandleCreated); // Set different. control.HorizontalScrollbar = !value; Assert.Equal(!value, control.HorizontalScrollbar); Assert.Empty(control.Items); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(HorizontalScrollbar_Set_TestData))] public void ListBox_HorizontalScrollbar_SetWithItems_GetReturnsExpected(bool multiColumn, bool value) { using var control = new ListBox { MultiColumn = multiColumn }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); control.HorizontalScrollbar = value; Assert.Equal(value, control.HorizontalScrollbar); Assert.Equal(new string[] { "item1", "item2", "item1" }, control.Items.Cast<string>()); Assert.False(control.IsHandleCreated); // Set same. control.HorizontalScrollbar = value; Assert.Equal(value, control.HorizontalScrollbar); Assert.Equal(new string[] { "item1", "item2", "item1" }, control.Items.Cast<string>()); Assert.False(control.IsHandleCreated); // Set different. control.HorizontalScrollbar = !value; Assert.Equal(!value, control.HorizontalScrollbar); Assert.Equal(new string[] { "item1", "item2", "item1" }, control.Items.Cast<string>()); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> HorizontalScrollbar_SetWithHandle_TestData() { yield return new object[] { true, true, 0, 0, 1, 0 }; yield return new object[] { true, false, 0, 0, 1, 0 }; yield return new object[] { false, true, 2, 1, 3, 2 }; yield return new object[] { false, false, 0, 0, 3, 1 }; } [WinFormsTheory] [MemberData(nameof(HorizontalScrollbar_SetWithHandle_TestData))] public void ListBox_HorizontalScrollbar_SetWithHandle_GetReturnsExpected(bool multiColumn, bool value, int expectedInvalidatedCallCount1, int expectedCreatedCallCount1, int expectedInvalidatedCallCount2, int expectedCreatedCallCount2) { using var control = new ListBox { MultiColumn = multiColumn }; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.HorizontalScrollbar = value; Assert.Equal(value, control.HorizontalScrollbar); Assert.Empty(control.Items); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount1, createdCallCount); // Set same. control.HorizontalScrollbar = value; Assert.Equal(value, control.HorizontalScrollbar); Assert.Empty(control.Items); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount1, createdCallCount); // Set different. control.HorizontalScrollbar = !value; Assert.Equal(!value, control.HorizontalScrollbar); Assert.Empty(control.Items); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount2, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount2, createdCallCount); } public static IEnumerable<object[]> HorizontalScrollbar_SetWithItemsWithHandle_TestData() { yield return new object[] { true, true, 1, 0, 2, 0 }; yield return new object[] { true, false, 0, 0, 1, 0 }; yield return new object[] { false, true, 3, 1, 4, 2 }; yield return new object[] { false, false, 0, 0, 3, 1 }; } [WinFormsTheory] [MemberData(nameof(HorizontalScrollbar_SetWithItemsWithHandle_TestData))] public void ListBox_HorizontalScrollbar_SetWithItemsWithHandle_GetReturnsExpected(bool multiColumn, bool value, int expectedInvalidatedCallCount1, int expectedCreatedCallCount1, int expectedInvalidatedCallCount2, int expectedCreatedCallCount2) { using var control = new ListBox { MultiColumn = multiColumn }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.HorizontalScrollbar = value; Assert.Equal(value, control.HorizontalScrollbar); Assert.Equal(new string[] { "item1", "item2", "item1" }, control.Items.Cast<string>()); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount1, createdCallCount); // Set same. control.HorizontalScrollbar = value; Assert.Equal(value, control.HorizontalScrollbar); Assert.Equal(new string[] { "item1", "item2", "item1" }, control.Items.Cast<string>()); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount1, createdCallCount); // Set different. control.HorizontalScrollbar = !value; Assert.Equal(!value, control.HorizontalScrollbar); Assert.Equal(new string[] { "item1", "item2", "item1" }, control.Items.Cast<string>()); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount2, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount2, createdCallCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))] public void ListBox_IntegralHeight_Set_GetReturnsExpected(bool value) { using var control = new ListBox { IntegralHeight = value }; Assert.Equal(value, control.IntegralHeight); Assert.Equal(96, control.Height); Assert.False(control.IsHandleCreated); // Set same. control.IntegralHeight = value; Assert.Equal(value, control.IntegralHeight); Assert.Equal(96, control.Height); Assert.False(control.IsHandleCreated); // Set different. control.IntegralHeight = !value; Assert.Equal(!value, control.IntegralHeight); Assert.Equal(96, control.Height); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(true, 0)] [InlineData(false, 1)] public void ListBox_IntegralHeight_SetWithHandle_GetReturnsExpected(bool value, int expectedCreatedCallCount) { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.IntegralHeight = value; Assert.Equal(value, control.IntegralHeight); Assert.True(control.Height > 0); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); // Set same. control.IntegralHeight = value; Assert.Equal(value, control.IntegralHeight); Assert.True(control.Height > 0); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); // Set different. control.IntegralHeight = !value; Assert.Equal(!value, control.IntegralHeight); Assert.True(control.Height > 0); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount + 1, createdCallCount); } public static IEnumerable<object[]> ItemHeight_Set_TestData() { foreach (Enum drawMode in Enum.GetValues(typeof(DrawMode))) { foreach (bool integralHeight in new bool[] { true, false }) { yield return new object[] { drawMode, integralHeight, 1 }; yield return new object[] { drawMode, integralHeight, 13 }; yield return new object[] { drawMode, integralHeight, 255 }; } } } [WinFormsTheory] [MemberData(nameof(ItemHeight_Set_TestData))] public void ListBox_ItemHeight_Set_GetReturnsExpected(DrawMode drawMode, bool integralHeight, int value) { using var control = new ListBox { DrawMode = drawMode, IntegralHeight = integralHeight, ItemHeight = value }; Assert.Equal(value, control.ItemHeight); Assert.Equal(96, control.Height); Assert.False(control.IsHandleCreated); // Set same. control.ItemHeight = value; Assert.Equal(value, control.ItemHeight); Assert.Equal(96, control.Height); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> ItemHeight_SetWithHandle_TestData() { foreach (bool integralHeight in new bool[] { true, false }) { yield return new object[] { DrawMode.Normal, integralHeight, 1, 0 }; yield return new object[] { DrawMode.Normal, integralHeight, 13, 0 }; yield return new object[] { DrawMode.Normal, integralHeight, 255, 0 }; yield return new object[] { DrawMode.OwnerDrawFixed, integralHeight, 1, 1 }; yield return new object[] { DrawMode.OwnerDrawFixed, integralHeight, 13, 0 }; yield return new object[] { DrawMode.OwnerDrawFixed, integralHeight, 255, 1 }; yield return new object[] { DrawMode.OwnerDrawVariable, integralHeight, 1, 0 }; yield return new object[] { DrawMode.OwnerDrawVariable, integralHeight, 13, 0 }; yield return new object[] { DrawMode.OwnerDrawVariable, integralHeight, 255, 0 }; } } [WinFormsTheory] [MemberData(nameof(ItemHeight_SetWithHandle_TestData))] public void ListBox_ItemHeight_SetWithHandle_GetReturnsExpected(DrawMode drawMode, bool integralHeight, int value, int expectedInvalidatedCallCount) { using var control = new ListBox { DrawMode = drawMode, IntegralHeight = integralHeight }; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.ItemHeight = value; Assert.True(control.ItemHeight > 0); Assert.True(control.Height > 0); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.ItemHeight = value; Assert.True(control.ItemHeight > 0); Assert.True(control.Height > 0); Assert.True(control.IsHandleCreated); Assert.Equal(expectedInvalidatedCallCount, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [InlineData(DrawMode.Normal, false)] [InlineData(DrawMode.OwnerDrawFixed, true)] [InlineData(DrawMode.OwnerDrawVariable, false)] public void ListBox_ItemHeight_Set_GetItemHeight_ReturnsExpected(DrawMode drawMode, bool expected) { using var control = new ListBox { DrawMode = drawMode, ItemHeight = 25 }; Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Equal(expected, SendMessageW(control.Handle, (WM)LB.GETITEMHEIGHT) == (IntPtr)25); } [WinFormsTheory] [InlineData(0)] [InlineData(256)] public void ListBox_ItemHeight_SetInvalidValue_ThrowsArgumentOutOfRangeException(int value) { using var control = new ListBox(); Assert.Throws<ArgumentOutOfRangeException>("value", () => control.ItemHeight = value); } [WinFormsFact] public void ListBox_ItemHeight_ResetValue_Success() { PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(ListBox))[nameof(ListBox.ItemHeight)]; using var control = new ListBox(); Assert.False(property.CanResetValue(control)); control.ItemHeight = 15; Assert.Equal(15, control.ItemHeight); Assert.True(property.CanResetValue(control)); property.ResetValue(control); Assert.Equal(13, control.ItemHeight); Assert.False(property.CanResetValue(control)); } [WinFormsFact] public void ListBox_ItemHeight_ShouldSerializeValue_Success() { PropertyDescriptor property = TypeDescriptor.GetProperties(typeof(ListBox))[nameof(ListBox.ItemHeight)]; using var control = new ListBox(); Assert.False(property.ShouldSerializeValue(control)); control.ItemHeight = 15; Assert.Equal(15, control.ItemHeight); Assert.True(property.ShouldSerializeValue(control)); property.ResetValue(control); Assert.Equal(13, control.ItemHeight); Assert.False(property.ShouldSerializeValue(control)); } public static IEnumerable<object[]> Items_CustomCreateItemCollection_TestData() { yield return new object[] { null }; yield return new object[] { new ListBox.ObjectCollection(new ListBox()) }; } [WinFormsTheory] [MemberData(nameof(Items_CustomCreateItemCollection_TestData))] public void ListBox_Items_GetCustomCreateItemCollection_ReturnsExpected(ListBox.ObjectCollection result) { using var control = new CustomCreateItemCollectionListBox { CreateListBoxResult = result }; Assert.Same(result, control.Items); Assert.Same(control.Items, control.Items); Assert.False(control.IsHandleCreated); } private class CustomCreateItemCollectionListBox : ListBox { public ListBox.ObjectCollection CreateListBoxResult { get; set; } protected override ListBox.ObjectCollection CreateItemCollection() => CreateListBoxResult; } public static IEnumerable<object[]> MultiColumn_Set_TestData() { yield return new object[] { DrawMode.Normal, true }; yield return new object[] { DrawMode.Normal, false }; yield return new object[] { DrawMode.OwnerDrawFixed, true }; yield return new object[] { DrawMode.OwnerDrawFixed, false }; } [WinFormsTheory] [MemberData(nameof(MultiColumn_Set_TestData))] public void ListBox_MultiColumn_Set_GetReturnsExpected(DrawMode drawMode, bool value) { using var control = new ListBox { DrawMode = drawMode, MultiColumn = value }; Assert.Equal(value, control.MultiColumn); Assert.False(control.IsHandleCreated); // Set same. control.MultiColumn = value; Assert.Equal(value, control.MultiColumn); Assert.False(control.IsHandleCreated); // Set different. control.MultiColumn = !value; Assert.Equal(!value, control.MultiColumn); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> MultiColumn_SetWithHandle_TestData() { yield return new object[] { DrawMode.Normal, true, 1 }; yield return new object[] { DrawMode.Normal, false, 0 }; yield return new object[] { DrawMode.OwnerDrawFixed, true, 1 }; yield return new object[] { DrawMode.OwnerDrawFixed, false, 0 }; } [WinFormsTheory] [MemberData(nameof(MultiColumn_SetWithHandle_TestData))] public void ListBox_MultiColumn_SetWithHandle_GetReturnsExpected(DrawMode drawMode, bool value, int expectedCreatedCallCount) { using var control = new ListBox { DrawMode = drawMode }; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.MultiColumn = value; Assert.Equal(value, control.MultiColumn); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); // Set same. control.MultiColumn = value; Assert.Equal(value, control.MultiColumn); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); // Set different. control.MultiColumn = !value; Assert.Equal(!value, control.MultiColumn); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount + 1, createdCallCount); } [WinFormsFact] public void ListBox_MultiColumn_SetOwnerDrawVariable_ThrowsArgumentException() { using var control = new ListBox { DrawMode = DrawMode.OwnerDrawVariable }; control.MultiColumn = false; Assert.False(control.MultiColumn); Assert.Throws<ArgumentException>("value", () => control.MultiColumn = true); Assert.False(control.MultiColumn); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelperEx), nameof(CommonTestHelperEx.GetPaddingNormalizedTheoryData))] public void ListBox_Padding_Set_GetReturnsExpected(Padding value, Padding expected) { using var control = new ListBox { Padding = value }; Assert.Equal(expected, control.Padding); Assert.False(control.IsHandleCreated); // Set same. control.Padding = value; Assert.Equal(expected, control.Padding); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelperEx), nameof(CommonTestHelperEx.GetPaddingNormalizedTheoryData))] public void ListBox_Padding_SetWithHandle_GetReturnsExpected(Padding value, Padding expected) { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.Padding = value; Assert.Equal(expected, control.Padding); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.Padding = value; Assert.Equal(expected, control.Padding); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void ListBox_Padding_SetWithHandler_CallsPaddingChanged() { using var control = new ListBox(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Equal(control, sender); Assert.Equal(EventArgs.Empty, e); callCount++; }; control.PaddingChanged += handler; // Set different. var padding1 = new Padding(1); control.Padding = padding1; Assert.Equal(padding1, control.Padding); Assert.Equal(1, callCount); // Set same. control.Padding = padding1; Assert.Equal(padding1, control.Padding); Assert.Equal(1, callCount); // Set different. var padding2 = new Padding(2); control.Padding = padding2; Assert.Equal(padding2, control.Padding); Assert.Equal(2, callCount); // Remove handler. control.PaddingChanged -= handler; control.Padding = padding1; Assert.Equal(padding1, control.Padding); Assert.Equal(2, callCount); } public static IEnumerable<object[]> PreferredHeight_GetEmpty_TestData() { int extra = SystemInformation.BorderSize.Height * 4 + 3; yield return new object[] { DrawMode.Normal, BorderStyle.Fixed3D, 13 + extra }; yield return new object[] { DrawMode.Normal, BorderStyle.FixedSingle, 13 + extra }; yield return new object[] { DrawMode.Normal, BorderStyle.None, 13 }; yield return new object[] { DrawMode.OwnerDrawFixed, BorderStyle.Fixed3D, 13 + extra }; yield return new object[] { DrawMode.OwnerDrawFixed, BorderStyle.FixedSingle, 13 + extra }; yield return new object[] { DrawMode.OwnerDrawFixed, BorderStyle.None, 13 }; yield return new object[] { DrawMode.OwnerDrawVariable, BorderStyle.Fixed3D, extra }; yield return new object[] { DrawMode.OwnerDrawVariable, BorderStyle.FixedSingle, extra }; yield return new object[] { DrawMode.OwnerDrawVariable, BorderStyle.None, 0 }; } [WinFormsTheory] [MemberData(nameof(PreferredHeight_GetEmpty_TestData))] public void ListBox_PreferredHeight_GetEmpty_ReturnsExpected(DrawMode drawMode, BorderStyle borderStyle, int expected) { using var control = new ListBox { DrawMode = drawMode, BorderStyle = borderStyle }; Assert.Equal(expected, control.PreferredHeight); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> PreferredHeight_GetNotEmpty_TestData() { int extra = SystemInformation.BorderSize.Height * 4 + 3; yield return new object[] { DrawMode.Normal, BorderStyle.Fixed3D, 26 + extra }; yield return new object[] { DrawMode.Normal, BorderStyle.FixedSingle, 26 + extra }; yield return new object[] { DrawMode.Normal, BorderStyle.None, 26 }; yield return new object[] { DrawMode.OwnerDrawFixed, BorderStyle.Fixed3D, 26 + extra }; yield return new object[] { DrawMode.OwnerDrawFixed, BorderStyle.FixedSingle, 26 + extra }; yield return new object[] { DrawMode.OwnerDrawFixed, BorderStyle.None, 26 }; yield return new object[] { DrawMode.OwnerDrawVariable, BorderStyle.Fixed3D, 26 + extra }; yield return new object[] { DrawMode.OwnerDrawVariable, BorderStyle.FixedSingle, 26 + extra }; yield return new object[] { DrawMode.OwnerDrawVariable, BorderStyle.None, 26 }; } [WinFormsTheory] [MemberData(nameof(PreferredHeight_GetNotEmpty_TestData))] public void ListBox_PreferredHeight_GetNotEmpty_ReturnsExpected(DrawMode drawMode, BorderStyle borderStyle, int expected) { using var control = new ListBox { DrawMode = drawMode, BorderStyle = borderStyle }; control.Items.Add("Item1"); control.Items.Add("Item2"); Assert.Equal(expected, control.PreferredHeight); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> PreferredHeight_GetWithHandle_TestData() { yield return new object[] { DrawMode.Normal, BorderStyle.Fixed3D }; yield return new object[] { DrawMode.Normal, BorderStyle.FixedSingle }; yield return new object[] { DrawMode.Normal, BorderStyle.None }; yield return new object[] { DrawMode.OwnerDrawFixed, BorderStyle.Fixed3D }; yield return new object[] { DrawMode.OwnerDrawFixed, BorderStyle.FixedSingle }; yield return new object[] { DrawMode.OwnerDrawFixed, BorderStyle.None }; yield return new object[] { DrawMode.OwnerDrawVariable, BorderStyle.Fixed3D }; yield return new object[] { DrawMode.OwnerDrawVariable, BorderStyle.FixedSingle }; yield return new object[] { DrawMode.OwnerDrawVariable, BorderStyle.None }; } [WinFormsTheory] [MemberData(nameof(PreferredHeight_GetWithHandle_TestData))] public void ListBox_PreferredHeight_GetEmptyWithHandle_ReturnsExpected(DrawMode drawMode, BorderStyle borderStyle) { using var control = new ListBox { DrawMode = drawMode, BorderStyle = borderStyle }; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; Assert.True(control.PreferredHeight >= 0); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [MemberData(nameof(PreferredHeight_GetWithHandle_TestData))] public void ListBox_PreferredHeight_GetNotEmptyWithHandle_ReturnsExpected(DrawMode drawMode, BorderStyle borderStyle) { using var control = new ListBox { DrawMode = drawMode, BorderStyle = borderStyle }; control.Items.Add("Item1"); control.Items.Add("Item2"); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; Assert.True(control.PreferredHeight > 0); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelperEx), nameof(CommonTestHelperEx.GetRightToLeftTheoryData))] public void ListBox_RightToLeft_Set_GetReturnsExpected(RightToLeft value, RightToLeft expected) { using var control = new ListBox { RightToLeft = value }; Assert.Equal(expected, control.RightToLeft); Assert.False(control.IsHandleCreated); // Set same. control.RightToLeft = value; Assert.Equal(expected, control.RightToLeft); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void ListBox_RightToLeft_SetWithHandler_CallsRightToLeftChanged() { using var control = new ListBox(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; control.RightToLeftChanged += handler; // Set different. control.RightToLeft = RightToLeft.Yes; Assert.Equal(RightToLeft.Yes, control.RightToLeft); Assert.Equal(1, callCount); // Set same. control.RightToLeft = RightToLeft.Yes; Assert.Equal(RightToLeft.Yes, control.RightToLeft); Assert.Equal(1, callCount); // Set different. control.RightToLeft = RightToLeft.Inherit; Assert.Equal(RightToLeft.No, control.RightToLeft); Assert.Equal(2, callCount); // Remove handler. control.RightToLeftChanged -= handler; control.RightToLeft = RightToLeft.Yes; Assert.Equal(RightToLeft.Yes, control.RightToLeft); Assert.Equal(2, callCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(RightToLeft))] public void ListBox_RightToLeft_SetInvalid_ThrowsInvalidEnumArgumentException(RightToLeft value) { using var control = new ListBox(); Assert.Throws<InvalidEnumArgumentException>("value", () => control.RightToLeft = value); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))] public void ListBox_ScrollAlwaysVisible_Set_GetReturnsExpected(bool value) { using var control = new ListBox { ScrollAlwaysVisible = value }; Assert.Equal(value, control.ScrollAlwaysVisible); Assert.False(control.IsHandleCreated); // Set same. control.ScrollAlwaysVisible = value; Assert.Equal(value, control.ScrollAlwaysVisible); Assert.False(control.IsHandleCreated); // Set different. control.ScrollAlwaysVisible = !value; Assert.Equal(!value, control.ScrollAlwaysVisible); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(true, 1)] [InlineData(false, 0)] public void ListBox_ScrollAlwaysVisible_SetWithHandle_GetReturnsExpected(bool value, int expectedCreatedCallCount) { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.ScrollAlwaysVisible = value; Assert.Equal(value, control.ScrollAlwaysVisible); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); // Set same. control.ScrollAlwaysVisible = value; Assert.Equal(value, control.ScrollAlwaysVisible); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); // Set different. control.ScrollAlwaysVisible = !value; Assert.Equal(!value, control.ScrollAlwaysVisible); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount + 1, createdCallCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(SelectionMode))] public void ListBox_SelectedIndex_GetEmptyWithHandle_ReturnsMinusOne(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode }; Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Equal(-1, control.SelectedIndex); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(SelectionMode))] public void ListBox_SelectedIndex_GetNotEmptyWithHandle_ReturnsMinusOne(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode }; control.Items.Add("Item"); Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Equal(-1, control.SelectedIndex); } [WinFormsTheory] [InlineData(SelectionMode.MultiExtended)] [InlineData(SelectionMode.MultiSimple)] [InlineData(SelectionMode.One)] public void ListBox_SelectedIndex_SetEmpty_GetReturnsExpected(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode, SelectedIndex = -1 }; Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.False(control.IsHandleCreated); // Set same. control.SelectedIndex = -1; Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void ListBox_SelectedIndex_SetSelectionModeOne_GetReturnsExpected() { using var control = new ListBox { SelectionMode = SelectionMode.One }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); // Select end. control.SelectedIndex = 1; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); // Select same. control.SelectedIndex = 1; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); // Select first. control.SelectedIndex = 0; Assert.Equal(0, control.SelectedIndex); Assert.Equal(0, Assert.Single(control.SelectedIndices)); Assert.Equal("item1", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); // Clear selection. control.SelectedIndex = -1; Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(SelectionMode.MultiExtended)] [InlineData(SelectionMode.MultiSimple)] public void ListBox_SelectedIndex_SetSelectionModeMultiple_GetReturnsExpected(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); // Select end. control.SelectedIndex = 1; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); // Select same. control.SelectedIndex = 1; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); // Select first. control.SelectedIndex = 0; Assert.Equal(0, control.SelectedIndex); Assert.Equal("item1", control.SelectedItem); Assert.Equal(new int[] { 0, 1 }, control.SelectedIndices.Cast<int>()); Assert.Equal(new string[] { "item1", "item2" }, control.SelectedItems.Cast<string>()); Assert.False(control.IsHandleCreated); // Clear selection. control.SelectedIndex = -1; Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(true, 0)] [InlineData(true, 1)] [InlineData(false, 0)] [InlineData(false, 1)] public void ListBox_SelectedIndex_SetWithDataManager_SetsDataManagerPosition(bool formattingEnabled, int position) { var bindingContext = new BindingContext(); var dataSource = new List<string> { "item1", "item2", "item3" }; using var control = new SubListBox { BindingContext = bindingContext, DataSource = dataSource, FormattingEnabled = formattingEnabled }; control.DataManager.Position = position; // Select end. control.SelectedIndex = 1; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.Equal(1, control.DataManager.Position); Assert.False(control.IsHandleCreated); // Select same. control.SelectedIndex = 1; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.Equal(1, control.DataManager.Position); Assert.False(control.IsHandleCreated); // Select first. control.SelectedIndex = 0; Assert.Equal(0, control.SelectedIndex); Assert.Equal("item1", control.SelectedItem); Assert.Equal(0, Assert.Single(control.SelectedIndices)); Assert.Equal("item1", Assert.Single(control.SelectedItems)); Assert.Equal(0, control.DataManager.Position); Assert.False(control.IsHandleCreated); // Clear selection. control.SelectedIndex = -1; Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.Equal(0, control.DataManager.Position); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void ListBox_SelectedIndex_SetSelectionModeOneWithHandle_GetReturnsExpected() { using var control = new ListBox { SelectionMode = SelectionMode.One }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; // Select end. control.SelectedIndex = 1; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Select same. control.SelectedIndex = 1; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Select first. control.SelectedIndex = 0; Assert.Equal(0, control.SelectedIndex); Assert.Equal(0, Assert.Single(control.SelectedIndices)); Assert.Equal("item1", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Clear selection. control.SelectedIndex = -1; Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [InlineData(SelectionMode.MultiExtended)] [InlineData(SelectionMode.MultiSimple)] public void ListBox_SelectedIndex_SetSelectionModeMultipleWithHandle_GetReturnsExpected(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; // Select end. control.SelectedIndex = 1; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Select same. control.SelectedIndex = 1; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Select first. control.SelectedIndex = 0; Assert.Equal(0, control.SelectedIndex); Assert.Equal("item1", control.SelectedItem); Assert.Equal(new int[] { 0, 1 }, control.SelectedIndices.Cast<int>()); Assert.Equal(new string[] { "item1", "item2" }, control.SelectedItems.Cast<string>()); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Clear selection. control.SelectedIndex = -1; Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void ListBox_SelectedIndex_GetCurSelOne_Success() { using var control = new ListBox { SelectionMode = SelectionMode.One }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); // Select last. Assert.NotEqual(IntPtr.Zero, control.Handle); control.SelectedIndex = 1; Assert.Equal((IntPtr)1, SendMessageW(control.Handle, (WM)LB.GETCURSEL)); // Select first. control.SelectedIndex = 0; Assert.Equal((IntPtr)0, SendMessageW(control.Handle, (WM)LB.GETCURSEL)); // Clear selection. control.SelectedIndex = -1; Assert.Equal((IntPtr)(-1), SendMessageW(control.Handle, (WM)LB.GETCURSEL)); } [WinFormsTheory] [InlineData(SelectionMode.MultiExtended)] [InlineData(SelectionMode.MultiSimple)] public void ListBox_SelectedIndex_GetCurSelMultiple_Success(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); // Select last. Assert.NotEqual(IntPtr.Zero, control.Handle); control.SelectedIndex = 1; Assert.Equal((IntPtr)1, SendMessageW(control.Handle, (WM)LB.GETCURSEL)); Span<int> buffer = stackalloc int[5]; Assert.Equal((IntPtr)1, SendMessageW(control.Handle, (WM)LB.GETSELITEMS, (IntPtr)buffer.Length, ref buffer[0])); Assert.Equal(new int[] { 1, 0, 0, 0, 0 }, buffer.ToArray()); // Select first. control.SelectedIndex = 0; Assert.Equal((IntPtr)0, SendMessageW(control.Handle, (WM)LB.GETCURSEL)); Assert.Equal((IntPtr)2, SendMessageW(control.Handle, (WM)LB.GETSELITEMS, (IntPtr)buffer.Length, ref buffer[0])); Assert.Equal(new int[] { 0, 1, 0, 0, 0 }, buffer.ToArray()); // Clear selection. control.SelectedIndex = -1; Assert.Equal((IntPtr)0, SendMessageW(control.Handle, (WM)LB.GETCURSEL)); Assert.Equal((IntPtr)0, SendMessageW(control.Handle, (WM)LB.GETSELITEMS, (IntPtr)buffer.Length, ref buffer[0])); Assert.Equal(new int[] { 0, 1, 0, 0, 0 }, buffer.ToArray()); } [WinFormsTheory] [InlineData(SelectionMode.One)] [InlineData(SelectionMode.MultiExtended)] [InlineData(SelectionMode.MultiSimple)] public void ListBox_SelectedIndex_SetWithHandler_CallsSelectedIndexChanged(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; control.SelectedIndexChanged += handler; // Select last. control.SelectedIndex = 1; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, callCount); // Select same. control.SelectedIndex = 1; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, callCount); // Select first. control.SelectedIndex = 0; Assert.Equal(0, control.SelectedIndex); Assert.Equal(2, callCount); // Clear selection. control.SelectedIndex = -1; Assert.Equal(-1, control.SelectedIndex); Assert.Equal(3, callCount); // Remove handler. control.SelectedIndexChanged -= handler; control.SelectedIndex = 1; Assert.Equal(1, control.SelectedIndex); Assert.Equal(3, callCount); } [WinFormsTheory] [InlineData(-2)] [InlineData(0)] [InlineData(1)] public void ListBox_SelectedIndex_SetInvalidValueEmpty_ThrowsArgumentOutOfRangeException(int value) { using var control = new ListBox(); Assert.Throws<ArgumentOutOfRangeException>("value", () => control.SelectedIndex = value); } [WinFormsTheory] [InlineData(-2)] [InlineData(1)] public void ListBox_SelectedIndex_SetInvalidValueNotEmpty_ThrowsArgumentOutOfRangeException(int value) { using var control = new ListBox(); control.Items.Add("Item"); Assert.Throws<ArgumentOutOfRangeException>("value", () => control.SelectedIndex = value); } [WinFormsFact] public void ListBox_SelectedIndex_SetNoSelection_ThrowsArgumentException() { using var control = new ListBox { SelectionMode = SelectionMode.None }; Assert.Throws<ArgumentException>("value", () => control.SelectedIndex = -1); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(SelectionMode))] public void ListBox_SelectedItem_GetEmptyWithHandle_ReturnsNull(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode }; Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Null(control.SelectedItem); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(SelectionMode))] public void ListBox_SelectedItem_GetNotEmptyWithHandle_ReturnsNull(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode }; control.Items.Add("Item"); Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Null(control.SelectedItem); } [WinFormsTheory] [InlineData(SelectionMode.MultiExtended, null)] [InlineData(SelectionMode.MultiSimple, null)] [InlineData(SelectionMode.One, null)] [InlineData(SelectionMode.MultiExtended, "item")] [InlineData(SelectionMode.MultiSimple, "item")] [InlineData(SelectionMode.One, "item")] public void ListBox_SelectedItem_SetEmpty_GetReturnsExpected(SelectionMode selectionMode, string value) { using var control = new ListBox { SelectionMode = selectionMode, SelectedItem = value }; Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.False(control.IsHandleCreated); // Set same. control.SelectedItem = value; Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void ListBox_SelectedItem_SetSelectionModeOne_GetReturnsExpected() { using var control = new ListBox { SelectionMode = SelectionMode.One }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); // Select end. control.SelectedItem = "item2"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); // Select same. control.SelectedItem = "item2"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); // Select invalid. control.SelectedItem = "NoSuchItem"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); // Select first. control.SelectedItem = "item1"; Assert.Equal(0, control.SelectedIndex); Assert.Equal(0, Assert.Single(control.SelectedIndices)); Assert.Equal("item1", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); // Clear selection. control.SelectedItem = null; Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(SelectionMode.MultiExtended)] [InlineData(SelectionMode.MultiSimple)] public void ListBox_SelectedItem_SetSelectionModeMultiple_GetReturnsExpected(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); // Select end. control.SelectedItem = "item2"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); // Select same. control.SelectedItem = "item2"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); // Select invalid. control.SelectedItem = "NoSuchItem"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); // Select first. control.SelectedItem = "item1"; Assert.Equal(0, control.SelectedIndex); Assert.Equal("item1", control.SelectedItem); Assert.Equal(new int[] { 0, 1 }, control.SelectedIndices.Cast<int>()); Assert.Equal(new string[] { "item1", "item2" }, control.SelectedItems.Cast<string>()); Assert.False(control.IsHandleCreated); // Clear selection. control.SelectedItem = null; Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(true, 0)] [InlineData(true, 1)] [InlineData(false, 0)] [InlineData(false, 1)] public void ListBox_SelectedItem_SetWithDataManager_SetsDataManagerPosition(bool formattingEnabled, int position) { var bindingContext = new BindingContext(); var dataSource = new List<string> { "item1", "item2", "item3" }; using var control = new SubListBox { BindingContext = bindingContext, DataSource = dataSource, FormattingEnabled = formattingEnabled }; control.DataManager.Position = position; // Select end. control.SelectedItem = "item2"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.Equal(1, control.DataManager.Position); Assert.False(control.IsHandleCreated); // Select same. control.SelectedItem = "item2"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.Equal(1, control.DataManager.Position); Assert.False(control.IsHandleCreated); // Select invalid. control.SelectedItem = "NoSuchItem"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.Equal(1, control.DataManager.Position); Assert.False(control.IsHandleCreated); // Select first. control.SelectedItem = "item1"; Assert.Equal(0, control.SelectedIndex); Assert.Equal("item1", control.SelectedItem); Assert.Equal(0, Assert.Single(control.SelectedIndices)); Assert.Equal("item1", Assert.Single(control.SelectedItems)); Assert.Equal(0, control.DataManager.Position); Assert.False(control.IsHandleCreated); // Clear selection. control.SelectedItem = null; Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.Equal(0, control.DataManager.Position); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void ListBox_SelectedItem_SetSelectionModeOneWithHandle_GetReturnsExpected() { using var control = new ListBox { SelectionMode = SelectionMode.One }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; // Select end. control.SelectedItem = "item2"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Select same. control.SelectedItem = "item2"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Select invalid. control.SelectedItem = "NoSuchItem"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Select first. control.SelectedItem = "item1"; Assert.Equal(0, control.SelectedIndex); Assert.Equal(0, Assert.Single(control.SelectedIndices)); Assert.Equal("item1", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Clear selection. control.SelectedItem = null; Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [InlineData(SelectionMode.MultiExtended)] [InlineData(SelectionMode.MultiSimple)] public void ListBox_SelectedItem_SetSelectionModeMultipleWithHandle_GetReturnsExpected(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; // Select end. control.SelectedItem = "item2"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Select same. control.SelectedItem = "item2"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Select invalid. control.SelectedItem = "NoSuchItem"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Select first. control.SelectedItem = "item1"; Assert.Equal(0, control.SelectedIndex); Assert.Equal("item1", control.SelectedItem); Assert.Equal(new int[] { 0, 1 }, control.SelectedIndices.Cast<int>()); Assert.Equal(new string[] { "item1", "item2" }, control.SelectedItems.Cast<string>()); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Clear selection. control.SelectedItem = null; Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void ListBox_SelectedItem_GetCurSelOne_Success() { using var control = new ListBox { SelectionMode = SelectionMode.One }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); // Select last. Assert.NotEqual(IntPtr.Zero, control.Handle); control.SelectedItem = "item2"; Assert.Equal((IntPtr)1, SendMessageW(control.Handle, (WM)LB.GETCURSEL)); // Select invalid. control.SelectedItem = "NoSuchItem"; Assert.Equal((IntPtr)1, SendMessageW(control.Handle, (WM)LB.GETCURSEL)); // Select first. control.SelectedItem = "item1"; Assert.Equal((IntPtr)0, SendMessageW(control.Handle, (WM)LB.GETCURSEL)); // Clear selection. control.SelectedItem = null; Assert.Equal((IntPtr)(-1), SendMessageW(control.Handle, (WM)LB.GETCURSEL)); } [WinFormsTheory] [InlineData(SelectionMode.MultiExtended)] [InlineData(SelectionMode.MultiSimple)] public void ListBox_SelectedItem_GetCurSelMultiple_Success(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); // Select last. Assert.NotEqual(IntPtr.Zero, control.Handle); control.SelectedItem = "item2"; Assert.Equal((IntPtr)1, SendMessageW(control.Handle, (WM)LB.GETCURSEL)); Span<int> buffer = stackalloc int[5]; Assert.Equal((IntPtr)1, SendMessageW(control.Handle, (WM)LB.GETSELITEMS, (IntPtr)buffer.Length, ref buffer[0])); Assert.Equal(new int[] { 1, 0, 0, 0, 0 }, buffer.ToArray()); // Select invalid. control.SelectedItem = "NoSuchItem"; Assert.Equal((IntPtr)1, SendMessageW(control.Handle, (WM)LB.GETCURSEL)); buffer = stackalloc int[5]; Assert.Equal((IntPtr)1, SendMessageW(control.Handle, (WM)LB.GETSELITEMS, (IntPtr)buffer.Length, ref buffer[0])); Assert.Equal(new int[] { 1, 0, 0, 0, 0 }, buffer.ToArray()); // Select first. control.SelectedItem = "item1"; Assert.Equal((IntPtr)0, SendMessageW(control.Handle, (WM)LB.GETCURSEL)); Assert.Equal((IntPtr)2, SendMessageW(control.Handle, (WM)LB.GETSELITEMS, (IntPtr)buffer.Length, ref buffer[0])); Assert.Equal(new int[] { 0, 1, 0, 0, 0 }, buffer.ToArray()); // Clear selection. control.SelectedItem = null; Assert.Equal((IntPtr)0, SendMessageW(control.Handle, (WM)LB.GETCURSEL)); Assert.Equal((IntPtr)0, SendMessageW(control.Handle, (WM)LB.GETSELITEMS, (IntPtr)buffer.Length, ref buffer[0])); Assert.Equal(new int[] { 0, 1, 0, 0, 0 }, buffer.ToArray()); } [WinFormsTheory] [InlineData(SelectionMode.One)] [InlineData(SelectionMode.MultiExtended)] [InlineData(SelectionMode.MultiSimple)] public void ListBox_SelectedItem_SetWithHandler_CallsSelectedIndexChanged(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(EventArgs.Empty, e); callCount++; }; control.SelectedIndexChanged += handler; // Select last. control.SelectedItem = "item2"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, callCount); // Select same. control.SelectedItem = "item2"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, callCount); // Select invalid. control.SelectedItem = "NoSuchItem"; Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, callCount); // Select first. control.SelectedItem = "item1"; Assert.Equal(0, control.SelectedIndex); Assert.Equal(2, callCount); // Clear selection. control.SelectedItem = null; Assert.Equal(-1, control.SelectedIndex); Assert.Equal(3, callCount); // Remove handler. control.SelectedIndexChanged -= handler; control.SelectedItem = "item2"; Assert.Equal(1, control.SelectedIndex); Assert.Equal(3, callCount); } [WinFormsTheory] [InlineData(null)] [InlineData("NoSuchItem")] public void ListBox_SelectedItem_SetNoSelectionEmpty_Nop(object value) { using var control = new ListBox { SelectionMode = SelectionMode.None }; control.SelectedItem = value; Assert.Null(control.SelectedItem); } [WinFormsFact] public void ListBox_SelectedItem_SetNoSelectionNotEmpty_ThrowsArgumentException() { using var control = new ListBox { SelectionMode = SelectionMode.None }; control.Items.Add("item"); AssertExtensions.Throws<ArgumentException>("value", () => control.SelectedItem = "item"); Assert.Null(control.SelectedItem); control.SelectedItem = "NoSuchItem"; Assert.Null(control.SelectedItem); AssertExtensions.Throws<ArgumentException>("value", () => control.SelectedItem = null); Assert.Null(control.SelectedItem); } [WinFormsFact] public void ListBox_SelectedItems_GetDirtyCustom_ReturnsExpected() { using var control = new CustomListBox { SelectionMode = SelectionMode.MultiSimple }; control.Items.Add("Item0"); control.Items.Add("Item1"); control.Items.Add("Item2"); control.Items.Add("Item3"); control.Items.Add("Item4"); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; // Set MakeCustom after the Handle is created to allow for default behaviour. control.MakeCustom = true; // Verify equal lengths. control.GetSelCountResult = (IntPtr)1; control.GetSelResult = new int[] { 2 }; Dirty(); Assert.Equal(new int[] { 2 }, control.SelectedIndices.Cast<int>()); // Verify truncated control.GetSelCountResult = (IntPtr)2; control.GetSelResult = new int[] { 2 }; Dirty(); Assert.Equal(new int[] { 0, 2 }, control.SelectedIndices.Cast<int>()); void Dirty() { // Simulate a selection change notification. SendMessageW(control.Handle, WM.REFLECT | WM.COMMAND, PARAM.FromLowHigh(0, (int)LBN.SELCHANGE)); } } private class CustomListBox : ListBox { public bool MakeCustom { get; set; } public IntPtr GetSelCountResult { get; set; } public int[] GetSelResult { get; set; } protected override void WndProc(ref Message m) { if (MakeCustom && m.Msg == (int)LB.GETSELCOUNT) { m.Result = GetSelCountResult; return; } else if (MakeCustom && m.Msg == (int)LB.GETSELITEMS) { Assert.Equal(GetSelCountResult, m.WParam); Marshal.Copy(GetSelResult, 0, m.LParam, GetSelResult.Length); m.Result = (IntPtr)GetSelResult.Length; return; } base.WndProc(ref m); } } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(SelectionMode))] public void ListBox_SelectionMode_SetEmpty_GetReturnsExpected(SelectionMode value) { using var control = new ListBox { SelectionMode = value }; Assert.Equal(value, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.False(control.IsHandleCreated); // Set same. control.SelectionMode = value; Assert.Equal(value, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> SelectionMode_SetWithCustomOldValue_TestData() { foreach (SelectionMode selectionMode in Enum.GetValues(typeof(SelectionMode))) { foreach (SelectionMode value in Enum.GetValues(typeof(SelectionMode))) { yield return new object[] { selectionMode, value }; } } } [WinFormsTheory] [MemberData(nameof(SelectionMode_SetWithCustomOldValue_TestData))] public void ListBox_SelectionMode_SetEmptyWithCustomOldValue_GetReturnsExpected(SelectionMode selectionMode, SelectionMode value) { using var control = new ListBox { SelectionMode = selectionMode }; control.SelectionMode = value; Assert.Equal(value, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.False(control.IsHandleCreated); // Set same. control.SelectionMode = value; Assert.Equal(value, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(SelectionMode.MultiSimple)] [InlineData(SelectionMode.MultiExtended)] public void ListBox_SelectionMode_SetWithItemsOneSelectedToMulti_GetReturnsExpected(SelectionMode value) { using var control = new ListBox(); control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); control.SelectedIndex = 1; control.SelectionMode = value; Assert.Equal(value, control.SelectionMode); Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); // Set same. control.SelectionMode = value; Assert.Equal(value, control.SelectionMode); Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); // Set back to one. control.SelectionMode = SelectionMode.One; Assert.Equal(SelectionMode.One, control.SelectionMode); Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void ListBox_SelectionMode_SetWithItemsOneSelectedToNone_GetReturnsExpected() { using var control = new ListBox(); control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); control.SelectedIndex = 1; control.SelectionMode = SelectionMode.None; Assert.Equal(SelectionMode.None, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); // Set same. control.SelectionMode = SelectionMode.None; Assert.Equal(SelectionMode.None, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); // Set back to one. control.SelectionMode = SelectionMode.One; Assert.Equal(SelectionMode.One, control.SelectionMode); Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(SelectionMode.MultiExtended)] [InlineData(SelectionMode.MultiSimple)] public void ListBox_SelectionMode_SetWithItemsMultiSelectedToOne_GetReturnsExpected(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); control.SelectedIndex = 0; control.SelectedIndex = 1; control.SelectionMode = SelectionMode.One; Assert.Equal(SelectionMode.One, control.SelectionMode); Assert.Equal(0, control.SelectedIndex); Assert.Equal("item1", control.SelectedItem); Assert.Equal(new int[] { 0, 1 }, control.SelectedIndices.Cast<int>()); Assert.Equal(new string[] { "item1", "item2" }, control.SelectedItems.Cast<object>()); Assert.False(control.IsHandleCreated); // Set same. control.SelectionMode = SelectionMode.One; Assert.Equal(SelectionMode.One, control.SelectionMode); Assert.Equal(0, control.SelectedIndex); Assert.Equal("item1", control.SelectedItem); Assert.Equal(new int[] { 0, 1 }, control.SelectedIndices.Cast<int>()); Assert.Equal(new string[] { "item1", "item2" }, control.SelectedItems.Cast<object>()); Assert.False(control.IsHandleCreated); // Set back to multi. control.SelectionMode = selectionMode; Assert.Equal(selectionMode, control.SelectionMode); Assert.Equal(0, control.SelectedIndex); Assert.Equal("item1", control.SelectedItem); Assert.Equal(new int[] { 0, 1 }, control.SelectedIndices.Cast<int>()); Assert.Equal(new string[] { "item1", "item2" }, control.SelectedItems.Cast<object>()); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(SelectionMode.MultiExtended)] [InlineData(SelectionMode.MultiSimple)] public void ListBox_SelectionMode_SetWithItemsMultiSelectedToNone_GetReturnsExpected(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); control.SelectedIndex = 0; control.SelectedIndex = 1; control.SelectionMode = SelectionMode.None; Assert.Equal(SelectionMode.None, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Equal("item1", control.SelectedItem); Assert.Equal(new int[] { 0, 1 }, control.SelectedIndices.Cast<int>()); Assert.Equal(new string[] { "item1", "item2" }, control.SelectedItems.Cast<object>()); Assert.False(control.IsHandleCreated); // Set same. control.SelectionMode = SelectionMode.None; Assert.Equal(SelectionMode.None, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Equal("item1", control.SelectedItem); Assert.Equal(new int[] { 0, 1 }, control.SelectedIndices.Cast<int>()); Assert.Equal(new string[] { "item1", "item2" }, control.SelectedItems.Cast<object>()); Assert.False(control.IsHandleCreated); // Set back to multi. control.SelectionMode = selectionMode; Assert.Equal(selectionMode, control.SelectionMode); Assert.Equal(0, control.SelectedIndex); Assert.Equal("item1", control.SelectedItem); Assert.Equal(new int[] { 0, 1 }, control.SelectedIndices.Cast<int>()); Assert.Equal(new string[] { "item1", "item2" }, control.SelectedItems.Cast<object>()); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(SelectionMode.None, 1)] [InlineData(SelectionMode.MultiExtended, 1)] [InlineData(SelectionMode.MultiSimple, 1)] [InlineData(SelectionMode.One, 0)] public void ListBox_SelectionMode_SetEmptyWithHandle_GetReturnsExpected(SelectionMode value, int expectedCreatedCallCount) { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.SelectionMode = value; Assert.Equal(value, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); // Set same. control.SelectionMode = value; Assert.Equal(value, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); } public static IEnumerable<object[]> SelectionMode_SetWithCustomOldValueWithHandle_TestData() { yield return new object[] { SelectionMode.None, SelectionMode.None, 0 }; yield return new object[] { SelectionMode.None, SelectionMode.MultiExtended, 1 }; yield return new object[] { SelectionMode.None, SelectionMode.MultiSimple, 1 }; yield return new object[] { SelectionMode.None, SelectionMode.One, 1 }; yield return new object[] { SelectionMode.MultiExtended, SelectionMode.None, 1 }; yield return new object[] { SelectionMode.MultiExtended, SelectionMode.MultiExtended, 0 }; yield return new object[] { SelectionMode.MultiExtended, SelectionMode.MultiSimple, 1 }; yield return new object[] { SelectionMode.MultiExtended, SelectionMode.One, 1 }; yield return new object[] { SelectionMode.MultiSimple, SelectionMode.None, 1 }; yield return new object[] { SelectionMode.MultiSimple, SelectionMode.MultiExtended, 1 }; yield return new object[] { SelectionMode.MultiSimple, SelectionMode.MultiSimple, 0 }; yield return new object[] { SelectionMode.MultiSimple, SelectionMode.One, 1 }; yield return new object[] { SelectionMode.One, SelectionMode.None, 1 }; yield return new object[] { SelectionMode.One, SelectionMode.MultiExtended, 1 }; yield return new object[] { SelectionMode.One, SelectionMode.MultiSimple, 1 }; yield return new object[] { SelectionMode.One, SelectionMode.One, 0 }; } [WinFormsTheory] [MemberData(nameof(SelectionMode_SetWithCustomOldValueWithHandle_TestData))] public void ListBox_SelectionMode_SetEmptyWithCustomOldValueWithHandle_GetReturnsExpected(SelectionMode selectionMode, SelectionMode value, int expectedCreatedCallCount) { using var control = new ListBox { SelectionMode = selectionMode }; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.SelectionMode = value; Assert.Equal(value, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); // Set same. control.SelectionMode = value; Assert.Equal(value, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); } [WinFormsTheory] [InlineData(SelectionMode.MultiSimple)] [InlineData(SelectionMode.MultiExtended)] public void ListBox_SelectionMode_SetWithItemsOneSelectedToMultiWithHandle_GetReturnsExpected(SelectionMode value) { using var control = new ListBox(); control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); control.SelectedIndex = 1; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.SelectionMode = value; Assert.Equal(value, control.SelectionMode); Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(1, createdCallCount); // Set same. control.SelectionMode = value; Assert.Equal(value, control.SelectionMode); Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(1, createdCallCount); // Set back to one. control.SelectionMode = SelectionMode.One; Assert.Equal(SelectionMode.One, control.SelectionMode); Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(2, createdCallCount); } [WinFormsFact] public void ListBox_SelectionMode_SetWithItemsOneSelectedToNoneWithHandle_GetReturnsExpected() { using var control = new ListBox(); control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); control.SelectedIndex = 1; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.SelectionMode = SelectionMode.None; Assert.Equal(SelectionMode.None, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(1, createdCallCount); // Set same. control.SelectionMode = SelectionMode.None; Assert.Equal(SelectionMode.None, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(1, createdCallCount); // Set back to one. control.SelectionMode = SelectionMode.One; Assert.Equal(SelectionMode.One, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(2, createdCallCount); } [WinFormsTheory] [InlineData(SelectionMode.MultiExtended)] [InlineData(SelectionMode.MultiSimple)] public void ListBox_SelectionMode_SetWithItemsMultiSelectedToOneWithHandle_GetReturnsExpected(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); control.SelectedIndex = 0; control.SelectedIndex = 1; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.SelectionMode = SelectionMode.One; Assert.Equal(SelectionMode.One, control.SelectionMode); Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(1, createdCallCount); // Set same. control.SelectionMode = SelectionMode.One; Assert.Equal(SelectionMode.One, control.SelectionMode); Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(1, createdCallCount); // Set back to multi. control.SelectionMode = selectionMode; Assert.Equal(selectionMode, control.SelectionMode); Assert.Equal(1, control.SelectedIndex); Assert.Equal("item2", control.SelectedItem); Assert.Equal(1, Assert.Single(control.SelectedIndices)); Assert.Equal("item2", Assert.Single(control.SelectedItems)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(2, createdCallCount); } [WinFormsTheory] [InlineData(SelectionMode.MultiExtended)] [InlineData(SelectionMode.MultiSimple)] public void ListBox_SelectionMode_SetWithItemsMultiSelectedToNoneWithHandle_GetReturnsExpected(SelectionMode selectionMode) { using var control = new ListBox { SelectionMode = selectionMode }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); control.SelectedIndex = 0; control.SelectedIndex = 1; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.SelectionMode = SelectionMode.None; Assert.Equal(SelectionMode.None, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(1, createdCallCount); // Set same. control.SelectionMode = SelectionMode.None; Assert.Equal(SelectionMode.None, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(1, createdCallCount); // Set back to multi. control.SelectionMode = selectionMode; Assert.Equal(selectionMode, control.SelectionMode); Assert.Equal(-1, control.SelectedIndex); Assert.Null(control.SelectedItem); Assert.Empty(control.SelectedIndices); Assert.Empty(control.SelectedItems); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(2, createdCallCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryDataInvalid), typeof(SelectionMode))] public void ListBox_SelectionMode_SetInvalidValue_ThrowsInvalidEnumArgumentException(SelectionMode value) { using var control = new ListBox(); Assert.Throws<InvalidEnumArgumentException>("value", () => control.SelectionMode = value); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))] public void ListBox_Sorted_SetWithoutItems_GetReturnsExpected(bool value) { using var control = new ListBox { Sorted = value }; Assert.Equal(value, control.Sorted); Assert.Empty(control.Items); Assert.False(control.IsHandleCreated); // Set same. control.Sorted = value; Assert.Equal(value, control.Sorted); Assert.Empty(control.Items); Assert.False(control.IsHandleCreated); // Set different. control.Sorted = !value; Assert.Equal(!value, control.Sorted); Assert.Empty(control.Items); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))] public void ListBox_Sorted_SetWithEmptyItems_GetReturnsExpected(bool value) { using var control = new ListBox(); Assert.Empty(control.Items); control.Sorted = value; Assert.Equal(value, control.Sorted); Assert.Empty(control.Items); Assert.False(control.IsHandleCreated); // Set same. control.Sorted = value; Assert.Equal(value, control.Sorted); Assert.Empty(control.Items); Assert.False(control.IsHandleCreated); // Set different. control.Sorted = !value; Assert.Equal(!value, control.Sorted); Assert.Empty(control.Items); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> Sorted_SetWithItems_TestData() { yield return new object[] { true, new string[] { "item1", "item2" } }; yield return new object[] { false, new string[] { "item2", "item1" } }; } [WinFormsTheory] [MemberData(nameof(Sorted_SetWithItems_TestData))] public void ListBox_Sorted_SetWithItems_GetReturnsExpected(bool value, string[] expected) { using var control = new ListBox(); control.Items.Add("item2"); control.Items.Add("item1"); control.Sorted = value; Assert.Equal(value, control.Sorted); Assert.Equal(expected, control.Items.Cast<string>()); Assert.False(control.IsHandleCreated); // Set same. control.Sorted = value; Assert.Equal(value, control.Sorted); Assert.Equal(expected, control.Items.Cast<string>()); Assert.False(control.IsHandleCreated); // Set different. control.Sorted = !value; Assert.Equal(!value, control.Sorted); Assert.Equal(new string[] { "item1", "item2" }, control.Items.Cast<string>()); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))] public void ListBox_Sorted_SetWithoutItemsWithHandle_GetReturnsExpected(bool value) { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.Sorted = value; Assert.Equal(value, control.Sorted); Assert.Empty(control.Items); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.Sorted = value; Assert.Equal(value, control.Sorted); Assert.Empty(control.Items); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set different. control.Sorted = !value; Assert.Equal(!value, control.Sorted); Assert.Empty(control.Items); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))] public void ListBox_Sorted_SetWithEmptyItemsWithHandle_GetReturnsExpected(bool value) { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; Assert.Empty(control.Items); control.Sorted = value; Assert.Equal(value, control.Sorted); Assert.Empty(control.Items); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.Sorted = value; Assert.Equal(value, control.Sorted); Assert.Empty(control.Items); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set different. control.Sorted = !value; Assert.Equal(!value, control.Sorted); Assert.Empty(control.Items); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [MemberData(nameof(Sorted_SetWithItems_TestData))] public void ListBox_Sorted_SetWithItemsWithHandle_GetReturnsExpected(bool value, string[] expected) { using var control = new ListBox(); control.Items.Add("item2"); control.Items.Add("item1"); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.Sorted = value; Assert.Equal(value, control.Sorted); Assert.Equal(expected, control.Items.Cast<string>()); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.Sorted = value; Assert.Equal(value, control.Sorted); Assert.Equal(expected, control.Items.Cast<string>()); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set different. control.Sorted = !value; Assert.Equal(!value, control.Sorted); Assert.Equal(new string[] { "item1", "item2" }, control.Items.Cast<string>()); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))] public void ListBox_Text_Set_GetReturnsExpected(string value, string expected) { using var control = new ListBox { Text = value }; Assert.Equal(expected, control.Text); Assert.Equal(-1, control.SelectedIndex); Assert.False(control.IsHandleCreated); // Set same. control.Text = value; Assert.Equal(expected, control.Text); Assert.Equal(-1, control.SelectedIndex); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> Text_SetWithItems_TestData() { foreach (bool formattingEnabled in new bool[] { true, false }) { yield return new object[] { formattingEnabled, SelectionMode.None, null, string.Empty, -1 }; yield return new object[] { formattingEnabled, SelectionMode.None, string.Empty, string.Empty, -1 }; yield return new object[] { formattingEnabled, SelectionMode.None, "NoSuchItem", "NoSuchItem", -1 }; yield return new object[] { formattingEnabled, SelectionMode.None, "item1", "item1", -1 }; yield return new object[] { formattingEnabled, SelectionMode.None, "ITEM1", "ITEM1", -1 }; yield return new object[] { formattingEnabled, SelectionMode.None, "item2", "item2", -1 }; foreach (SelectionMode selectionMode in new SelectionMode[] { SelectionMode.MultiExtended, SelectionMode.MultiSimple, SelectionMode.One }) { yield return new object[] { formattingEnabled, selectionMode, null, string.Empty, -1 }; yield return new object[] { formattingEnabled, selectionMode, string.Empty, string.Empty, -1 }; yield return new object[] { formattingEnabled, selectionMode, "NoSuchItem", "NoSuchItem", -1 }; yield return new object[] { formattingEnabled, selectionMode, "item1", "item1", 0 }; yield return new object[] { formattingEnabled, selectionMode, "ITEM1", "item1", 0 }; yield return new object[] { formattingEnabled, selectionMode, "item2", "item2", 1 }; } } } [WinFormsTheory] [MemberData(nameof(Text_SetWithItems_TestData))] public void ListBox_Text_SetWithItems_GetReturnsExpected(bool formattingEnabled, SelectionMode selectionMode, string value, string expected, int expectedSelectedIndex) { using var control = new ListBox { FormattingEnabled = formattingEnabled, SelectionMode = selectionMode }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); control.Text = value; Assert.Equal(expected, control.Text); Assert.Equal(expectedSelectedIndex, control.SelectedIndex); Assert.False(control.IsHandleCreated); // Set same. control.Text = value; Assert.Equal(expected, control.Text); Assert.Equal(expectedSelectedIndex, control.SelectedIndex); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> Text_SetWithItemsWithSelection_TestData() { foreach (bool formattingEnabled in new bool[] { true, false }) { yield return new object[] { formattingEnabled, SelectionMode.None, null, string.Empty, -1 }; yield return new object[] { formattingEnabled, SelectionMode.None, string.Empty, string.Empty, -1 }; yield return new object[] { formattingEnabled, SelectionMode.None, "NoSuchItem", "NoSuchItem", -1 }; yield return new object[] { formattingEnabled, SelectionMode.None, "item1", "item1", -1 }; yield return new object[] { formattingEnabled, SelectionMode.None, "ITEM1", "ITEM1", -1 }; yield return new object[] { formattingEnabled, SelectionMode.None, "item2", "item2", -1 }; foreach (SelectionMode selectionMode in new SelectionMode[] { SelectionMode.MultiExtended, SelectionMode.MultiSimple, SelectionMode.One }) { yield return new object[] { formattingEnabled, selectionMode, null, "item1", 0 }; yield return new object[] { formattingEnabled, selectionMode, string.Empty, "item1", 0 }; yield return new object[] { formattingEnabled, selectionMode, "NoSuchItem", "item1", 0 }; yield return new object[] { formattingEnabled, selectionMode, "item1", "item1", 0 }; yield return new object[] { formattingEnabled, selectionMode, "ITEM1", "item1", 0 }; } yield return new object[] { formattingEnabled, SelectionMode.MultiExtended, "item2", "item1", 0 }; yield return new object[] { formattingEnabled, SelectionMode.MultiSimple, "item2", "item1", 0 }; yield return new object[] { formattingEnabled, SelectionMode.One, "item2", "item2", 1 }; } } [WinFormsTheory] [MemberData(nameof(Text_SetWithItemsWithSelection_TestData))] public void ListBox_Text_SetWithItemsWithSelection_GetReturnsExpected(bool formattingEnabled, SelectionMode selectionMode, string value, string expected, int expectedSelectedIndex) { using var control = new ListBox { FormattingEnabled = formattingEnabled }; control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); control.SelectedIndex = 0; control.SelectionMode = selectionMode; control.Text = value; Assert.Equal(expected, control.Text); Assert.Equal(expectedSelectedIndex, control.SelectedIndex); Assert.False(control.IsHandleCreated); // Set same. control.Text = value; Assert.Equal(expected, control.Text); Assert.Equal(expectedSelectedIndex, control.SelectedIndex); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetStringNormalizedTheoryData))] public void ListBox_Text_SetWithHandle_GetReturnsExpected(string value, string expected) { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.Text = value; Assert.Equal(expected, control.Text); Assert.Equal(-1, control.SelectedIndex); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.Text = value; Assert.Equal(expected, control.Text); Assert.Equal(-1, control.SelectedIndex); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void ListBox_Text_SetWithHandler_CallsTextChanged() { using var control = new ListBox(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Equal(EventArgs.Empty, e); callCount++; }; control.TextChanged += handler; // Set different. control.Text = "text"; Assert.Equal("text", control.Text); Assert.Equal(1, callCount); // Set same. control.Text = "text"; Assert.Equal("text", control.Text); Assert.Equal(1, callCount); // Set different. control.Text = null; Assert.Empty(control.Text); Assert.Equal(2, callCount); // Remove handler. control.TextChanged -= handler; control.Text = "text"; Assert.Equal("text", control.Text); Assert.Equal(2, callCount); } [WinFormsFact] public void ListBox_TopIndex_GetWithHandle_ReturnsExpected() { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Equal(0, control.TopIndex); } [WinFormsTheory] [InlineData(int.MinValue)] [InlineData(-1)] [InlineData(0)] [InlineData(1)] [InlineData(int.MaxValue)] public void ListBox_TopIndex_SetEmpty_GetReturnsExpected(int value) { using var control = new ListBox { TopIndex = value }; Assert.Equal(value, control.TopIndex); Assert.False(control.IsHandleCreated); // Set same. control.TopIndex = value; Assert.Equal(value, control.TopIndex); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(int.MinValue)] [InlineData(-1)] [InlineData(0)] [InlineData(1)] [InlineData(int.MaxValue)] public void ListBox_TopIndex_SetNotEmpty_GetReturnsExpected(int value) { using var control = new ListBox(); control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); control.TopIndex = value; Assert.Equal(value, control.TopIndex); Assert.False(control.IsHandleCreated); // Set same. control.TopIndex = value; Assert.Equal(value, control.TopIndex); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(int.MinValue)] [InlineData(-1)] [InlineData(0)] [InlineData(1)] [InlineData(int.MaxValue)] public void ListBox_TopIndex_SetWithHandleEmpty_GetReturnsExpected(int value) { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.TopIndex = value; Assert.Equal(0, control.TopIndex); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.TopIndex = value; Assert.Equal(0, control.TopIndex); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [InlineData(int.MinValue)] [InlineData(-1)] [InlineData(0)] [InlineData(1)] [InlineData(2)] [InlineData(3)] [InlineData(int.MaxValue)] public void ListBox_TopIndex_SetWithHandleNotEmpty_GetReturnsExpected(int value) { using var control = new ListBox(); control.Items.Add("item1"); control.Items.Add("item2"); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.TopIndex = value; Assert.Equal(0, control.TopIndex); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Set same. control.TopIndex = value; Assert.Equal(0, control.TopIndex); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void ListBox_TopIndex_GetTopIndex_ReturnsExpected() { using var control = new ListBox(); control.Items.Add("item1"); control.Items.Add("item2"); control.Items.Add("item1"); Assert.NotEqual(IntPtr.Zero, control.Handle); control.TopIndex = 1; Assert.Equal((IntPtr)0, SendMessageW(control.Handle, (WM)LB.GETTOPINDEX)); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))] public void ListBox_UseCustomTabOffsets_Set_GetReturnsExpected(bool value) { using var control = new ListBox { UseCustomTabOffsets = value }; Assert.Equal(value, control.UseCustomTabOffsets); Assert.False(control.IsHandleCreated); // Set same. control.UseCustomTabOffsets = value; Assert.Equal(value, control.UseCustomTabOffsets); Assert.False(control.IsHandleCreated); // Set different. control.UseCustomTabOffsets = !value; Assert.Equal(!value, control.UseCustomTabOffsets); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(true, 1)] [InlineData(false, 0)] public void ListBox_UseCustomTabOffsets_SetWithHandle_GetReturnsExpected(bool value, int expectedCreatedCallCount) { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.UseCustomTabOffsets = value; Assert.Equal(value, control.UseCustomTabOffsets); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); // Set same. control.UseCustomTabOffsets = value; Assert.Equal(value, control.UseCustomTabOffsets); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); // Set different. control.UseCustomTabOffsets = !value; Assert.Equal(!value, control.UseCustomTabOffsets); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount + 1, createdCallCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetBoolTheoryData))] public void ListBox_UseTabStops_Set_GetReturnsExpected(bool value) { using var control = new ListBox { UseTabStops = value }; Assert.Equal(value, control.UseTabStops); Assert.False(control.IsHandleCreated); // Set same. control.UseTabStops = value; Assert.Equal(value, control.UseTabStops); Assert.False(control.IsHandleCreated); // Set different. control.UseTabStops = !value; Assert.Equal(!value, control.UseTabStops); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(true, 0)] [InlineData(false, 1)] public void ListBox_UseTabStops_SetWithHandle_GetReturnsExpected(bool value, int expectedCreatedCallCount) { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.UseTabStops = value; Assert.Equal(value, control.UseTabStops); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); // Set same. control.UseTabStops = value; Assert.Equal(value, control.UseTabStops); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount, createdCallCount); // Set different. control.UseTabStops = !value; Assert.Equal(!value, control.UseTabStops); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(expectedCreatedCallCount + 1, createdCallCount); } [WinFormsFact] public void ListBox_AddItemsCore_Invoke_Success() { using var control = new SubListBox(); // Add multiple. control.AddItemsCore(new object[] { "item1", "item2" }); Assert.Equal(new string[] { "item1", "item2" }, control.Items.Cast<object>()); Assert.False(control.IsHandleCreated); // Add another. control.AddItemsCore(new object[] { "item3" }); Assert.Equal(new string[] { "item1", "item2", "item3" }, control.Items.Cast<object>()); Assert.False(control.IsHandleCreated); // Add empty. control.AddItemsCore(Array.Empty<object>()); Assert.Equal(new string[] { "item1", "item2", "item3" }, control.Items.Cast<object>()); Assert.False(control.IsHandleCreated); // Add null. control.AddItemsCore(null); Assert.Equal(new string[] { "item1", "item2", "item3" }, control.Items.Cast<object>()); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void ListBox_AddItemsCore_InvokeWithHandle_Success() { using var control = new SubListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; // Add multiple. control.AddItemsCore(new object[] { "item1", "item2" }); Assert.Equal(new string[] { "item1", "item2" }, control.Items.Cast<object>()); Assert.True(control.IsHandleCreated); Assert.Equal(1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Add another. control.AddItemsCore(new object[] { "item3" }); Assert.Equal(new string[] { "item1", "item2", "item3" }, control.Items.Cast<object>()); Assert.True(control.IsHandleCreated); Assert.Equal(2, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Add empty. control.AddItemsCore(Array.Empty<object>()); Assert.Equal(new string[] { "item1", "item2", "item3" }, control.Items.Cast<object>()); Assert.True(control.IsHandleCreated); Assert.Equal(2, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Add null. control.AddItemsCore(null); Assert.Equal(new string[] { "item1", "item2", "item3" }, control.Items.Cast<object>()); Assert.True(control.IsHandleCreated); Assert.Equal(2, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void ListBox_BeginUpdate_InvokeWithoutHandle_Nop() { using var control = new ListBox(); control.BeginUpdate(); Assert.False(control.IsHandleCreated); // Call again. control.BeginUpdate(); Assert.False(control.IsHandleCreated); // End once. control.EndUpdate(); Assert.False(control.IsHandleCreated); // End twice. control.EndUpdate(); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void ListBox_BeginUpdate_InvokeWithHandle_Nop() { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.BeginUpdate(); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Call again. control.BeginUpdate(); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // End once. control.EndUpdate(); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // End twice. control.EndUpdate(); Assert.True(control.IsHandleCreated); Assert.Equal(1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void ListBox_EndUpdate_InvokeWithoutHandle_Success() { using var control = new ListBox(); // End without beginning. control.EndUpdate(); Assert.False(control.IsHandleCreated); // Begin. control.BeginUpdate(); Assert.False(control.IsHandleCreated); // End. control.EndUpdate(); Assert.False(control.IsHandleCreated); // End again. control.EndUpdate(); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void ListBox_EndUpdate_InvokeWithHandle_Success() { using var control = new ListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; // End without beginning. control.EndUpdate(); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Begin. control.BeginUpdate(); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // End. control.EndUpdate(); Assert.True(control.IsHandleCreated); Assert.Equal(1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // End again. control.EndUpdate(); Assert.True(control.IsHandleCreated); Assert.Equal(1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [InlineData(true, AccessibleRole.List)] [InlineData(false, AccessibleRole.None)] public void ListBox_CreateAccessibilityInstance_Invoke_ReturnsExpected(bool createControl, AccessibleRole accessibleRole) { using var control = new SubListBox(); if (createControl) { control.CreateControl(); } Control.ControlAccessibleObject instance = Assert.IsAssignableFrom<Control.ControlAccessibleObject>(control.CreateAccessibilityInstance()); Assert.NotNull(instance); Assert.Same(control, instance.Owner); Assert.Equal(accessibleRole, instance.Role); Assert.NotSame(control.CreateAccessibilityInstance(), instance); Assert.NotSame(control.AccessibilityObject, instance); Assert.Equal(createControl, control.IsHandleCreated); } [WinFormsFact] public void ListBox_CreateControlsInstance_Invoke_ReturnsExpected() { using var control = new SubListBox(); ListBox.ObjectCollection items = Assert.IsType<ListBox.ObjectCollection>(control.CreateItemCollection()); Assert.Empty(items); Assert.False(items.IsReadOnly); Assert.NotSame(items, control.CreateItemCollection()); } [WinFormsFact] public void ListBox_GetAutoSizeMode_Invoke_ReturnsExpected() { using var control = new SubListBox(); Assert.Equal(AutoSizeMode.GrowOnly, control.GetAutoSizeMode()); } public static IEnumerable<object[]> GetPreferredSize_TestData() { foreach (BorderStyle borderStyle in Enum.GetValues(typeof(BorderStyle))) { yield return new object[] { borderStyle, Size.Empty }; yield return new object[] { borderStyle, new Size(-1, -2) }; yield return new object[] { borderStyle, new Size(10, 20) }; yield return new object[] { borderStyle, new Size(30, 40) }; yield return new object[] { borderStyle, new Size(int.MaxValue, int.MaxValue) }; } } [WinFormsTheory] [MemberData(nameof(GetPreferredSize_TestData))] public void ListBox_GetPreferredSize_Invoke_ReturnsExpected(BorderStyle borderStyle, Size proposedSize) { using var control = new ListBox { BorderStyle = borderStyle }; Assert.Equal(new Size(120, 96), control.GetPreferredSize(proposedSize)); Assert.False(control.IsHandleCreated); // Call again. Assert.Equal(new Size(120, 96), control.GetPreferredSize(proposedSize)); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(GetPreferredSize_TestData))] public void ListBox_GetPreferredSize_InvokeWithPadding_ReturnsExpected(BorderStyle borderStyle, Size proposedSize) { using var control = new ListBox { BorderStyle = borderStyle, Padding = new Padding(1, 2, 3, 4) }; Assert.Equal(new Size(120, 96), control.GetPreferredSize(proposedSize)); Assert.False(control.IsHandleCreated); // Call again. Assert.Equal(new Size(120, 96), control.GetPreferredSize(proposedSize)); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(GetPreferredSize_TestData))] public void ListBox_GetPreferredSize_InvokeWithHandle_ReturnsExpected(BorderStyle borderStyle, Size proposedSize) { using var control = new ListBox { BorderStyle = borderStyle }; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; Size result = control.GetPreferredSize(proposedSize); Assert.True(result.Width > 0 && result.Width < 120); Assert.Equal(control.PreferredHeight, result.Height); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Call again. Assert.Equal(result, control.GetPreferredSize(proposedSize)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [MemberData(nameof(GetPreferredSize_TestData))] public void ListBox_GetPreferredSize_InvokeWithHandleWithPadding_ReturnsExpected(BorderStyle borderStyle, Size proposedSize) { using var control = new ListBox { BorderStyle = borderStyle, Padding = new Padding(1, 2, 3, 4) }; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; Size result = control.GetPreferredSize(proposedSize); Assert.True(result.Width > 0 && result.Width < 120); Assert.Equal(control.PreferredHeight + 6, result.Height); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Call again. Assert.Equal(result, control.GetPreferredSize(proposedSize)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [InlineData(ControlStyles.ContainerControl, false)] [InlineData(ControlStyles.UserPaint, false)] [InlineData(ControlStyles.Opaque, false)] [InlineData(ControlStyles.ResizeRedraw, false)] [InlineData(ControlStyles.FixedWidth, false)] [InlineData(ControlStyles.FixedHeight, false)] [InlineData(ControlStyles.StandardClick, false)] [InlineData(ControlStyles.Selectable, true)] [InlineData(ControlStyles.UserMouse, false)] [InlineData(ControlStyles.SupportsTransparentBackColor, false)] [InlineData(ControlStyles.StandardDoubleClick, true)] [InlineData(ControlStyles.AllPaintingInWmPaint, true)] [InlineData(ControlStyles.CacheText, false)] [InlineData(ControlStyles.EnableNotifyMessage, false)] [InlineData(ControlStyles.DoubleBuffer, false)] [InlineData(ControlStyles.OptimizedDoubleBuffer, false)] [InlineData(ControlStyles.UseTextForAccessibility, false)] [InlineData((ControlStyles)0, true)] [InlineData((ControlStyles)int.MaxValue, false)] [InlineData((ControlStyles)(-1), false)] public void ListBox_GetStyle_Invoke_ReturnsExpected(ControlStyles flag, bool expected) { using var control = new SubListBox(); Assert.Equal(expected, control.GetStyle(flag)); // Call again to test caching. Assert.Equal(expected, control.GetStyle(flag)); } [WinFormsFact] public void ListBox_GetTopLevel_Invoke_ReturnsExpected() { using var control = new SubListBox(); Assert.False(control.GetTopLevel()); } public static IEnumerable<object[]> FindString_TestData() { foreach (int startIndex in new int[] { -2, -1, 0, 1 }) { yield return new object[] { new ListBox(), null, startIndex, -1 }; yield return new object[] { new ListBox(), string.Empty, startIndex, -1 }; yield return new object[] { new ListBox(), "s", startIndex, -1 }; using var controlWithNoItems = new ListBox(); Assert.Empty(controlWithNoItems.Items); yield return new object[] { new ListBox(), null, startIndex, -1 }; yield return new object[] { new ListBox(), string.Empty, startIndex, -1 }; yield return new object[] { new ListBox(), "s", startIndex, -1 }; } using var controlWithItems = new ListBox { DisplayMember = "Value" }; controlWithItems.Items.Add(new DataClass { Value = "abc" }); controlWithItems.Items.Add(new DataClass { Value = "abc" }); controlWithItems.Items.Add(new DataClass { Value = "ABC" }); controlWithItems.Items.Add(new DataClass { Value = "def" }); controlWithItems.Items.Add(new DataClass { Value = "" }); controlWithItems.Items.Add(new DataClass { Value = null }); yield return new object[] { controlWithItems, "abc", -1, 0 }; yield return new object[] { controlWithItems, "abc", 0, 1 }; yield return new object[] { controlWithItems, "abc", 1, 2 }; yield return new object[] { controlWithItems, "abc", 2, 0 }; yield return new object[] { controlWithItems, "abc", 5, 0 }; yield return new object[] { controlWithItems, "ABC", -1, 0 }; yield return new object[] { controlWithItems, "ABC", 0, 1 }; yield return new object[] { controlWithItems, "ABC", 1, 2 }; yield return new object[] { controlWithItems, "ABC", 2, 0 }; yield return new object[] { controlWithItems, "ABC", 5, 0 }; yield return new object[] { controlWithItems, "a", -1, 0 }; yield return new object[] { controlWithItems, "a", 0, 1 }; yield return new object[] { controlWithItems, "a", 1, 2 }; yield return new object[] { controlWithItems, "a", 2, 0 }; yield return new object[] { controlWithItems, "a", 5, 0 }; yield return new object[] { controlWithItems, "A", -1, 0 }; yield return new object[] { controlWithItems, "A", 0, 1 }; yield return new object[] { controlWithItems, "A", 1, 2 }; yield return new object[] { controlWithItems, "A", 2, 0 }; yield return new object[] { controlWithItems, "A", 5, 0 }; yield return new object[] { controlWithItems, "abcd", -1, -1 }; yield return new object[] { controlWithItems, "abcd", 0, -1 }; yield return new object[] { controlWithItems, "abcd", 1, -1 }; yield return new object[] { controlWithItems, "abcd", 2, -1 }; yield return new object[] { controlWithItems, "abcd", 5, -1 }; yield return new object[] { controlWithItems, "def", -1, 3 }; yield return new object[] { controlWithItems, "def", 0, 3 }; yield return new object[] { controlWithItems, "def", 1, 3 }; yield return new object[] { controlWithItems, "def", 2, 3 }; yield return new object[] { controlWithItems, "def", 5, 3 }; yield return new object[] { controlWithItems, null, -1, -1 }; yield return new object[] { controlWithItems, null, 0, -1 }; yield return new object[] { controlWithItems, null, 1, -1 }; yield return new object[] { controlWithItems, null, 2, -1 }; yield return new object[] { controlWithItems, null, 5, -1 }; yield return new object[] { controlWithItems, string.Empty, -1, 0 }; yield return new object[] { controlWithItems, string.Empty, 0, 1 }; yield return new object[] { controlWithItems, string.Empty, 1, 2 }; yield return new object[] { controlWithItems, string.Empty, 2, 3 }; yield return new object[] { controlWithItems, string.Empty, 5, 0 }; yield return new object[] { controlWithItems, "NoSuchItem", -1, -1 }; yield return new object[] { controlWithItems, "NoSuchItem", 0, -1 }; yield return new object[] { controlWithItems, "NoSuchItem", 1, -1 }; yield return new object[] { controlWithItems, "NoSuchItem", 2, -1 }; yield return new object[] { controlWithItems, "NoSuchItem", 5, -1 }; } [WinFormsTheory] [MemberData(nameof(FindString_TestData))] public void ListBox_FindString_Invoke_ReturnsExpected(ListBox control, string s, int startIndex, int expected) { if (startIndex == -1) { Assert.Equal(expected, control.FindString(s)); } Assert.Equal(expected, control.FindString(s, startIndex)); } [WinFormsTheory] [InlineData(-2)] [InlineData(1)] [InlineData(2)] public void ListBox_FindString_InvalidStartIndex_ThrowsArgumentOutOfRangeException(int startIndex) { using var control = new ListBox(); control.Items.Add("item"); Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => control.FindString("s", startIndex)); } public static IEnumerable<object[]> FindStringExact_TestData() { foreach (int startIndex in new int[] { -2, -1, 0, 1 }) { yield return new object[] { new ListBox(), null, startIndex, -1 }; yield return new object[] { new ListBox(), string.Empty, startIndex, -1 }; yield return new object[] { new ListBox(), "s", startIndex, -1 }; using var controlWithNoItems = new ListBox(); Assert.Empty(controlWithNoItems.Items); yield return new object[] { new ListBox(), null, startIndex, -1 }; yield return new object[] { new ListBox(), string.Empty, startIndex, -1 }; yield return new object[] { new ListBox(), "s", startIndex, -1 }; } using var controlWithItems = new ListBox { DisplayMember = "Value" }; controlWithItems.Items.Add(new DataClass { Value = "abc" }); controlWithItems.Items.Add(new DataClass { Value = "abc" }); controlWithItems.Items.Add(new DataClass { Value = "ABC" }); controlWithItems.Items.Add(new DataClass { Value = "def" }); controlWithItems.Items.Add(new DataClass { Value = "" }); controlWithItems.Items.Add(new DataClass { Value = null }); yield return new object[] { controlWithItems, "abc", -1, 0 }; yield return new object[] { controlWithItems, "abc", 0, 1 }; yield return new object[] { controlWithItems, "abc", 1, 2 }; yield return new object[] { controlWithItems, "abc", 2, 0 }; yield return new object[] { controlWithItems, "abc", 5, 0 }; yield return new object[] { controlWithItems, "ABC", -1, 0 }; yield return new object[] { controlWithItems, "ABC", 0, 1 }; yield return new object[] { controlWithItems, "ABC", 1, 2 }; yield return new object[] { controlWithItems, "ABC", 2, 0 }; yield return new object[] { controlWithItems, "ABC", 5, 0 }; yield return new object[] { controlWithItems, "a", -1, -1 }; yield return new object[] { controlWithItems, "a", 0, -1 }; yield return new object[] { controlWithItems, "a", 1, -1 }; yield return new object[] { controlWithItems, "a", 2, -1 }; yield return new object[] { controlWithItems, "a", 5, -1 }; yield return new object[] { controlWithItems, "A", -1, -1 }; yield return new object[] { controlWithItems, "A", 0, -1 }; yield return new object[] { controlWithItems, "A", 1, -1 }; yield return new object[] { controlWithItems, "A", 2, -1 }; yield return new object[] { controlWithItems, "A", 5, -1 }; yield return new object[] { controlWithItems, "abcd", -1, -1 }; yield return new object[] { controlWithItems, "abcd", 0, -1 }; yield return new object[] { controlWithItems, "abcd", 1, -1 }; yield return new object[] { controlWithItems, "abcd", 2, -1 }; yield return new object[] { controlWithItems, "abcd", 5, -1 }; yield return new object[] { controlWithItems, "def", -1, 3 }; yield return new object[] { controlWithItems, "def", 0, 3 }; yield return new object[] { controlWithItems, "def", 1, 3 }; yield return new object[] { controlWithItems, "def", 2, 3 }; yield return new object[] { controlWithItems, "def", 5, 3 }; yield return new object[] { controlWithItems, null, -1, -1 }; yield return new object[] { controlWithItems, null, 0, -1 }; yield return new object[] { controlWithItems, null, 1, -1 }; yield return new object[] { controlWithItems, null, 2, -1 }; yield return new object[] { controlWithItems, null, 5, -1 }; yield return new object[] { controlWithItems, string.Empty, -1, 4 }; yield return new object[] { controlWithItems, string.Empty, 0, 4 }; yield return new object[] { controlWithItems, string.Empty, 1, 4 }; yield return new object[] { controlWithItems, string.Empty, 2, 4 }; yield return new object[] { controlWithItems, string.Empty, 5, 4 }; yield return new object[] { controlWithItems, "NoSuchItem", -1, -1 }; yield return new object[] { controlWithItems, "NoSuchItem", 0, -1 }; yield return new object[] { controlWithItems, "NoSuchItem", 1, -1 }; yield return new object[] { controlWithItems, "NoSuchItem", 2, -1 }; yield return new object[] { controlWithItems, "NoSuchItem", 5, -1 }; } [WinFormsTheory] [MemberData(nameof(FindStringExact_TestData))] public void ListBox_FindStringExact_Invoke_ReturnsExpected(ListBox control, string s, int startIndex, int expected) { if (startIndex == -1) { Assert.Equal(expected, control.FindStringExact(s)); } Assert.Equal(expected, control.FindStringExact(s, startIndex)); } [WinFormsTheory] [InlineData(-2)] [InlineData(1)] [InlineData(2)] public void ListBox_FindStringExact_InvalidStartIndex_ThrowsArgumentOutOfRangeException(int startIndex) { using var control = new ListBox(); control.Items.Add("item"); Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => control.FindStringExact("s", startIndex)); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEnumTypeTheoryData), typeof(DrawMode))] public void ListBox_GetItemHeight_InvokeEmptyWithoutHandle_ReturnsExpected(DrawMode drawMode) { using var control = new ListBox { DrawMode = drawMode }; Assert.Equal(13, control.GetItemHeight(0)); Assert.False(control.IsHandleCreated); } public static IEnumerable<object[]> GetItemHeight_NotEmpty_TestData() { foreach (DrawMode drawMode in Enum.GetValues(typeof(DrawMode))) { yield return new object[] { drawMode, 0 }; yield return new object[] { drawMode, 1 }; } } [WinFormsTheory] [MemberData(nameof(GetItemHeight_NotEmpty_TestData))] public void ListBox_GetItemHeight_InvokeNotEmptyWithoutHandle_ReturnsExpected(DrawMode drawMode, int index) { using var control = new ListBox { DrawMode = drawMode }; control.Items.Add("Item1"); control.Items.Add("Item2"); Assert.Equal(13, control.GetItemHeight(index)); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [InlineData(DrawMode.Normal)] [InlineData(DrawMode.OwnerDrawFixed)] [InlineData(DrawMode.OwnerDrawVariable)] public void ListBox_GetItemHeight_InvokeEmptyWithHandle_ReturnsExpected(DrawMode drawMode) { using var control = new ListBox { DrawMode = drawMode }; Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; Assert.True(control.GetItemHeight(0) > 0); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsTheory] [MemberData(nameof(GetItemHeight_NotEmpty_TestData))] public void ListBox_GetItemHeight_InvokeNotEmptyWithHandle_ReturnsExpected(DrawMode drawMode, int index) { using var control = new ListBox { DrawMode = drawMode }; control.Items.Add("Item1"); control.Items.Add("Item2"); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; Assert.True(control.GetItemHeight(index) > 0); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } public static IEnumerable<object[]> GetItemHeight_CustomGetItemHeight_TestData() { yield return new object[] { DrawMode.Normal, 0, 0, 0, 0 }; yield return new object[] { DrawMode.Normal, 1, 0, -2, -2 }; yield return new object[] { DrawMode.Normal, 0, 0, 10, 10 }; yield return new object[] { DrawMode.OwnerDrawFixed, 0, 0, 0, 0 }; yield return new object[] { DrawMode.OwnerDrawFixed, 1, 0, -2, -2 }; yield return new object[] { DrawMode.OwnerDrawFixed, 0, 0, 10, 10 }; yield return new object[] { DrawMode.OwnerDrawVariable, 0, 0, 0, 0 }; yield return new object[] { DrawMode.OwnerDrawVariable, 1, 1, -2, -2 }; yield return new object[] { DrawMode.OwnerDrawVariable, 0, 0, 10, 10 }; } [WinFormsTheory] [MemberData(nameof(GetItemHeight_CustomGetItemHeight_TestData))] public void ListBox_GetItemHeight_InvokeCustomGetItemHeight_ReturnsExpected(DrawMode drawMode, int index, int expectedIndex, int getItemRectResult, int expected) { using var control = new CustomGetItemHeightListBox { DrawMode = drawMode, ExpectedIndex = expectedIndex, GetItemHeightResult = (IntPtr)getItemRectResult }; control.Items.Add("Item1"); control.Items.Add("Item2"); Assert.NotEqual(IntPtr.Zero, control.Handle); control.MakeCustom = true; Assert.Equal(expected, control.GetItemHeight(index)); } private class CustomGetItemHeightListBox : ListBox { public bool MakeCustom { get; set; } public int ExpectedIndex { get; set; } public IntPtr GetItemHeightResult { get; set; } protected unsafe override void WndProc(ref Message m) { if (MakeCustom && m.Msg == (int)LB.GETITEMHEIGHT) { Assert.Equal(ExpectedIndex, (int)m.WParam); m.Result = GetItemHeightResult; return; } base.WndProc(ref m); } } [WinFormsFact] public void ListBox_GetItemHeight_InvokeInvalidGetItemHeight_ThrowsWin32Exception() { using var control = new InvalidGetItemHeightListBox(); control.Items.Add("Item"); Assert.NotEqual(IntPtr.Zero, control.Handle); control.MakeInvalid = true; Assert.Throws<Win32Exception>(() => control.GetItemHeight(0)); } private class InvalidGetItemHeightListBox : ListBox { public bool MakeInvalid { get; set; } protected unsafe override void WndProc(ref Message m) { if (MakeInvalid && m.Msg == (int)LB.GETITEMHEIGHT) { m.Result = (IntPtr)(-1); return; } base.WndProc(ref m); } } [WinFormsTheory] [InlineData(-1)] [InlineData(1)] public void ListBox_GetItemHeight_InvalidIndexEmpty_ThrowsArgumentOutOfRangeException(int index) { using var control = new ListBox(); Assert.Throws<ArgumentOutOfRangeException>("index", () => control.GetItemHeight(index)); } [WinFormsTheory] [InlineData(-1)] [InlineData(1)] [InlineData(2)] public void ListBox_GetItemHeight_InvalidIndexNotEmpty_ThrowsArgumentOutOfRangeException(int index) { using var control = new ListBox(); control.Items.Add("Item"); Assert.Throws<ArgumentOutOfRangeException>("index", () => control.GetItemHeight(index)); } [WinFormsFact] public void ListBox_GetItemRectangle_InvokeWithoutHandle_ReturnsExpectedAndCreatedHandle() { using var control = new ListBox(); control.Items.Add("Item1"); control.Items.Add("Item1"); Rectangle rect1 = control.GetItemRectangle(0); Assert.True(rect1.X >= 0); Assert.True(rect1.Y >= 0); Assert.True(rect1.Width > 0); Assert.True(rect1.Height > 0); Assert.Equal(rect1, control.GetItemRectangle(0)); Assert.True(control.IsHandleCreated); Rectangle rect2 = control.GetItemRectangle(1); Assert.Equal(rect2.X, rect1.X); Assert.True(rect2.Y >= rect1.Y + rect1.Height); Assert.True(rect2.Width > 0); Assert.True(rect2.Height > 0); Assert.True(control.IsHandleCreated); } [WinFormsFact] public void ListBox_GetItemRectangle_InvokeWithHandle_ReturnsExpected() { using var control = new ListBox(); control.Items.Add("Item1"); control.Items.Add("Item1"); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; Rectangle rect1 = control.GetItemRectangle(0); Assert.True(rect1.X >= 0); Assert.True(rect1.Y >= 0); Assert.True(rect1.Width > 0); Assert.True(rect1.Height > 0); Assert.Equal(rect1, control.GetItemRectangle(0)); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); Rectangle rect2 = control.GetItemRectangle(1); Assert.Equal(rect2.X, rect1.X); Assert.True(rect2.Y >= rect1.Y + rect1.Height); Assert.True(rect2.Width > 0); Assert.True(rect2.Height > 0); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } public static IEnumerable<object[]> GetItemRectangle_CustomGetItemRect_TestData() { yield return new object[] { new RECT(), Rectangle.Empty }; yield return new object[] { new RECT(1, 2, 3, 4), new Rectangle(1, 2, 2, 2) }; } [WinFormsTheory] [MemberData(nameof(GetItemRectangle_CustomGetItemRect_TestData))] public void ListBox_GetItemRectangle_InvokeCustomGetItemRect_ReturnsExpected(object getItemRectResult, Rectangle expected) { using var control = new CustomGetItemRectListBox { GetItemRectResult = (RECT)getItemRectResult }; control.Items.Add("Item"); Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Equal(expected, control.GetItemRectangle(0)); } private class CustomGetItemRectListBox : ListBox { public RECT GetItemRectResult { get; set; } protected unsafe override void WndProc(ref Message m) { if (m.Msg == (int)LB.GETITEMRECT) { RECT* pRect = (RECT*)m.LParam; *pRect = GetItemRectResult; m.Result = (IntPtr)1; return; } base.WndProc(ref m); } } [WinFormsFact] public void ListBox_GetItemRectangle_InvokeInvalidGetItemRect_ReturnsExpected() { using var control = new InvalidGetItemRectListBox(); control.Items.Add("Item"); Assert.NotEqual(IntPtr.Zero, control.Handle); control.MakeInvalid = true; Assert.Equal(Rectangle.Empty, control.GetItemRectangle(0)); } private class InvalidGetItemRectListBox : ListBox { public bool MakeInvalid { get; set; } protected unsafe override void WndProc(ref Message m) { if (MakeInvalid && m.Msg == (int)LB.GETITEMRECT) { RECT* pRect = (RECT*)m.LParam; *pRect = new RECT(1, 2, 3, 4); m.Result = IntPtr.Zero; return; } base.WndProc(ref m); } } [WinFormsFact] public void ListBox_GetItemRectangle_InvalidIndexEmpty_ThrowsArgumentOutOfRangeException() { using var control = new ListBox(); Assert.Throws<ArgumentOutOfRangeException>("index", () => control.GetItemRectangle(-1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => control.GetItemRectangle(0)); Assert.Throws<ArgumentOutOfRangeException>("index", () => control.GetItemRectangle(1)); } [WinFormsFact] public void ListBox_GetItemRectangle_InvalidIndexNotEmpty_ThrowsArgumentOutOfRangeException() { using var control = new ListBox(); control.Items.Add("Item"); Assert.Throws<ArgumentOutOfRangeException>("index", () => control.GetItemRectangle(-1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => control.GetItemRectangle(1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => control.GetItemRectangle(2)); } [WinFormsFact] public void ListBox_GetItemRectangle_InvalidIndexWithHandleEmpty_ThrowsArgumentOutOfRangeException() { using var control = new ListBox(); Assert.Throws<ArgumentOutOfRangeException>("index", () => control.GetItemRectangle(-1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => control.GetItemRectangle(0)); Assert.Throws<ArgumentOutOfRangeException>("index", () => control.GetItemRectangle(1)); } [WinFormsFact] public void ListBox_GetItemRectangle_InvalidIndexWithHandleNotEmpty_ThrowsArgumentOutOfRangeException() { using var control = new ListBox(); control.Items.Add("Item"); Assert.NotEqual(IntPtr.Zero, control.Handle); Assert.Throws<ArgumentOutOfRangeException>("index", () => control.GetItemRectangle(-1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => control.GetItemRectangle(1)); Assert.Throws<ArgumentOutOfRangeException>("index", () => control.GetItemRectangle(2)); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void ListBox_OnClick_Invoke_CallsClick(EventArgs eventArgs) { using var control = new SubListBox(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.Click += handler; control.OnClick(eventArgs); Assert.Equal(1, callCount); // Remove handler. control.Click -= handler; control.OnClick(eventArgs); Assert.Equal(1, callCount); } public static IEnumerable<object[]> OnDrawItem_TestData() { using var bitmap = new Bitmap(10, 10); using Graphics graphics = Graphics.FromImage(bitmap); yield return new object[] { null }; yield return new object[] { new DrawItemEventArgs(graphics, null, new Rectangle(1, 2, 3, 4), 0, DrawItemState.Checked) }; } [WinFormsTheory] [MemberData(nameof(OnDrawItem_TestData))] public void ListBox_OnDrawItem_Invoke_CallsDrawItem(DrawItemEventArgs eventArgs) { using var control = new SubListBox(); int callCount = 0; void handler(object sender, DrawItemEventArgs e) { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; } // Call with handler. control.DrawItem += handler; control.OnDrawItem(eventArgs); Assert.Equal(1, callCount); // Remove handler. control.DrawItem -= handler; control.OnDrawItem(eventArgs); Assert.Equal(1, callCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void ListBox_OnFontChanged_Invoke_CallsFontChanged(EventArgs eventArgs) { using var control = new SubListBox(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.FontChanged += handler; control.OnFontChanged(eventArgs); Assert.Equal(1, callCount); Assert.Equal(96, control.Height); // Remove handler. control.FontChanged -= handler; control.OnFontChanged(eventArgs); Assert.Equal(1, callCount); Assert.Equal(96, control.Height); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void ListBox_OnGotFocus_Invoke_CallsGotFocus(EventArgs eventArgs) { using var control = new SubListBox(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.GotFocus += handler; control.OnGotFocus(eventArgs); Assert.Equal(1, callCount); Assert.False(control.IsHandleCreated); // Remove handler. control.GotFocus -= handler; control.OnGotFocus(eventArgs); Assert.Equal(1, callCount); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void ListBox_OnGotFocus_InvokeWithHandle_CallsGotFocus(EventArgs eventArgs) { using var control = new SubListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.GotFocus += handler; control.OnGotFocus(eventArgs); Assert.Equal(1, callCount); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Remove handler. control.GotFocus -= handler; control.OnGotFocus(eventArgs); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } public static IEnumerable<object[]> OnMeasureItem_TestData() { using var bitmap = new Bitmap(10, 10); using Graphics graphics = Graphics.FromImage(bitmap); yield return new object[] { null }; yield return new object[] { new MeasureItemEventArgs(graphics, 0, 0) }; } [WinFormsTheory] [MemberData(nameof(OnMeasureItem_TestData))] public void ListBox_OnMeasureItem_Invoke_CallsMeasureItem(MeasureItemEventArgs eventArgs) { using var control = new SubListBox(); int callCount = 0; void handler(object sender, MeasureItemEventArgs e) { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; } // Call with handler. control.MeasureItem += handler; control.OnMeasureItem(eventArgs); Assert.Equal(1, callCount); // Remove handler. control.MeasureItem -= handler; control.OnMeasureItem(eventArgs); Assert.Equal(1, callCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelperEx), nameof(CommonTestHelperEx.GetMouseEventArgsTheoryData))] public void ListBox_OnMouseClick_Invoke_CallsMouseClick(MouseEventArgs eventArgs) { using var control = new SubListBox(); int callCount = 0; MouseEventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.MouseClick += handler; control.OnMouseClick(eventArgs); Assert.Equal(1, callCount); // Remove handler. control.MouseClick -= handler; control.OnMouseClick(eventArgs); Assert.Equal(1, callCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelperEx), nameof(CommonTestHelperEx.GetPaintEventArgsTheoryData))] public void ListBox_OnPaint_Invoke_CallsPaint(PaintEventArgs eventArgs) { using var control = new SubListBox(); int callCount = 0; PaintEventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.Paint += handler; control.OnPaint(eventArgs); Assert.Equal(1, callCount); // Remove handler. control.Paint -= handler; control.OnPaint(eventArgs); Assert.Equal(1, callCount); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void ListBox_OnSelectedIndexChanged_Invoke_CallsSelectedIndexChanged(EventArgs eventArgs) { using var control = new SubListBox(); int selectedValueChangedCallCount = 0; control.SelectedValueChanged += (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); selectedValueChangedCallCount++; }; int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); Assert.True(callCount < selectedValueChangedCallCount); callCount++; }; // Call with handler. control.SelectedIndexChanged += handler; control.OnSelectedIndexChanged(eventArgs); Assert.Equal(1, callCount); Assert.Equal(1, selectedValueChangedCallCount); Assert.False(control.IsHandleCreated); // Remove handler. control.SelectedIndexChanged -= handler; control.OnSelectedIndexChanged(eventArgs); Assert.Equal(1, callCount); Assert.Equal(2, selectedValueChangedCallCount); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void ListBox_OnSelectedIndexChanged_InvokeWithHandle_CallsSelectedIndexChanged(EventArgs eventArgs) { using var control = new SubListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; int selectedValueChangedCallCount = 0; control.SelectedValueChanged += (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); selectedValueChangedCallCount++; }; int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); Assert.True(callCount < selectedValueChangedCallCount); callCount++; }; // Call with handler. control.SelectedIndexChanged += handler; control.OnSelectedIndexChanged(eventArgs); Assert.Equal(1, callCount); Assert.Equal(1, selectedValueChangedCallCount); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Remove handler. control.SelectedIndexChanged -= handler; control.OnSelectedIndexChanged(eventArgs); Assert.Equal(1, callCount); Assert.Equal(2, selectedValueChangedCallCount); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } public static IEnumerable<object[]> OnSelectedIndexChanged_WithDataManager_TestData() { foreach (bool formattingEnabled in new bool[] { true, false }) { foreach (int position in new int[] { 0, 1 }) { yield return new object[] { formattingEnabled, position, null }; yield return new object[] { formattingEnabled, position, new EventArgs() }; } } } [WinFormsTheory] [MemberData(nameof(OnSelectedIndexChanged_WithDataManager_TestData))] public void ListBox_OnSelectedIndexChanged_InvokeWithDataManager_CallsSelectedIndexChanged(bool formattingEnabled, int position, EventArgs eventArgs) { var bindingContext = new BindingContext(); var dataSource = new List<string> { "item1", "item2", "item3" }; using var control = new SubListBox { BindingContext = bindingContext, DataSource = dataSource, FormattingEnabled = formattingEnabled }; control.DataManager.Position = position; int selectedValueChangedCallCount = 0; control.SelectedValueChanged += (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); selectedValueChangedCallCount++; }; int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); Assert.True(callCount < selectedValueChangedCallCount); callCount++; }; // Call with handler. control.SelectedIndexChanged += handler; control.OnSelectedIndexChanged(eventArgs); Assert.Equal(1, callCount); Assert.Equal(1, selectedValueChangedCallCount); Assert.Equal(position, control.DataManager.Position); // Remove handler. control.SelectedIndexChanged -= handler; control.OnSelectedIndexChanged(eventArgs); Assert.Equal(1, callCount); Assert.Equal(2, selectedValueChangedCallCount); Assert.Equal(position, control.DataManager.Position); } [WinFormsTheory] [CommonMemberData(typeof(CommonTestHelper), nameof(CommonTestHelper.GetEventArgsTheoryData))] public void ListBox_OnSelectedValueChanged_Invoke_CallsSelectedValueChanged(EventArgs eventArgs) { using var control = new SubListBox(); int callCount = 0; EventHandler handler = (sender, e) => { Assert.Same(control, sender); Assert.Same(eventArgs, e); callCount++; }; // Call with handler. control.SelectedValueChanged += handler; control.OnSelectedValueChanged(eventArgs); Assert.Equal(1, callCount); // Remove handler. control.SelectedValueChanged -= handler; control.OnSelectedValueChanged(eventArgs); Assert.Equal(1, callCount); } [WinFormsFact] public void ListBox_RefreshItems_InvokeEmpty_Success() { using var control = new SubListBox(); control.RefreshItems(); Assert.Empty(control.Items); Assert.False(control.IsHandleCreated); // Call again. control.RefreshItems(); Assert.Empty(control.Items); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void ListBox_RefreshItems_InvokeNotEmpty_Success() { using var control = new SubListBox(); control.Items.Add("item1"); control.Items.Add("item2"); control.RefreshItems(); Assert.Equal(new object[] { "item1", "item2" }, control.Items.Cast<object>()); Assert.False(control.IsHandleCreated); // Call again. control.RefreshItems(); Assert.Equal(new object[] { "item1", "item2" }, control.Items.Cast<object>()); Assert.False(control.IsHandleCreated); } [WinFormsFact] public void ListBox_RefreshItems_InvokeEmptyWithHandle_Success() { using var control = new SubListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.RefreshItems(); Assert.Empty(control.Items); Assert.True(control.IsHandleCreated); Assert.Equal(0, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Call again. control.RefreshItems(); Assert.Empty(control.Items); Assert.True(control.IsHandleCreated); Assert.Equal(1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void ListBox_RefreshItems_InvokeNotEmptyWithHandle_Success() { using var control = new SubListBox(); control.Items.Add("item1"); control.Items.Add("item2"); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.RefreshItems(); Assert.Equal(new object[] { "item1", "item2" }, control.Items.Cast<object>()); Assert.True(control.IsHandleCreated); Assert.Equal(1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Call again. control.RefreshItems(); Assert.Equal(new object[] { "item1", "item2" }, control.Items.Cast<object>()); Assert.True(control.IsHandleCreated); Assert.Equal(2, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void ListBox_ResetBackColor_Invoke_Success() { using var control = new ListBox(); // Reset without value. control.ResetBackColor(); Assert.Equal(SystemColors.Window, control.BackColor); // Reset with value. control.BackColor = Color.Black; control.ResetBackColor(); Assert.Equal(SystemColors.Window, control.BackColor); // Reset again. control.ResetBackColor(); Assert.Equal(SystemColors.Window, control.BackColor); } [WinFormsFact] public void ListBox_ResetForeColor_Invoke_Success() { using var control = new ListBox(); // Reset without value. control.ResetForeColor(); Assert.Equal(SystemColors.WindowText, control.ForeColor); // Reset with value. control.ForeColor = Color.Black; control.ResetForeColor(); Assert.Equal(SystemColors.WindowText, control.ForeColor); // Reset again. control.ResetForeColor(); Assert.Equal(SystemColors.WindowText, control.ForeColor); } public static IEnumerable<object[]> SetItemsCore_TestData() { yield return new object[] { new object[] { "item1", "item2", "item3" } }; yield return new object[] { Array.Empty<object>() }; } [WinFormsTheory] [MemberData(nameof(SetItemsCore_TestData))] public void ListBox_SetItemsCore_Invoke_Success(object[] value) { using var control = new SubListBox(); control.SetItemsCore(value); Assert.Equal(value, control.Items.Cast<object>()); Assert.False(control.IsHandleCreated); // Call again. control.SetItemsCore(value); Assert.Equal(value, control.Items.Cast<object>()); Assert.False(control.IsHandleCreated); } [WinFormsTheory] [MemberData(nameof(SetItemsCore_TestData))] public void ListBox_SetItemsCore_InvokeWithHandle_Success(object[] value) { using var control = new SubListBox(); Assert.NotEqual(IntPtr.Zero, control.Handle); int invalidatedCallCount = 0; control.Invalidated += (sender, e) => invalidatedCallCount++; int styleChangedCallCount = 0; control.StyleChanged += (sender, e) => styleChangedCallCount++; int createdCallCount = 0; control.HandleCreated += (sender, e) => createdCallCount++; control.SetItemsCore(value); Assert.Equal(value, control.Items.Cast<object>()); Assert.True(control.IsHandleCreated); Assert.Equal(1, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); // Call again. control.SetItemsCore(value); Assert.Equal(value, control.Items.Cast<object>()); Assert.True(control.IsHandleCreated); Assert.Equal(2, invalidatedCallCount); Assert.Equal(0, styleChangedCallCount); Assert.Equal(0, createdCallCount); } [WinFormsFact] public void ListBox_SetItemsCore_NullValueEmpty_ThrowsArgumentNullException() { using var control = new SubListBox(); Assert.Throws<ArgumentNullException>("value", () => control.SetItemsCore(null)); Assert.Empty(control.Items); } [WinFormsFact] public void ListBox_SetItemsCore_NullValueNotEmpty_ThrowsArgumentNullException() { using var control = new SubListBox(); control.Items.Add("item1"); control.Items.Add("item2"); Assert.Throws<ArgumentNullException>("value", () => control.SetItemsCore(null)); Assert.Equal(new object[] { "item1", "item2" }, control.Items.Cast<object>()); } [WinFormsFact] public void ListBox_ToString_InvokeWithoutItems_ReturnsExpected() { using var control = new ListBox(); Assert.Equal("System.Windows.Forms.ListBox", control.ToString()); } [WinFormsFact] public void ListBox_ToString_InvokeWithEmptyItems_ReturnsExpected() { using var control = new ListBox(); Assert.Empty(control.Items); Assert.Equal("System.Windows.Forms.ListBox, Items.Count: 0", control.ToString()); } public static IEnumerable<object[]> ToString_WithItems_TestData() { yield return new object[] { string.Empty, "System.Windows.Forms.ListBox, Items.Count: 2, Items[0]: " }; yield return new object[] { "abc", "System.Windows.Forms.ListBox, Items.Count: 2, Items[0]: abc" }; yield return new object[] { new string('a', 41), "System.Windows.Forms.ListBox, Items.Count: 2, Items[0]: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" }; } [WinFormsTheory] [MemberData(nameof(ToString_WithItems_TestData))] public void ListBox_ToString_InvokeWithItems_ReturnsExpected(string item1, string expected) { using var control = new ListBox(); control.Items.Add(item1); control.Items.Add("item2"); Assert.Equal(expected, control.ToString()); } private class SubListBox : ListBox { public new bool AllowSelection => base.AllowSelection; public new bool CanEnableIme => base.CanEnableIme; public new bool CanRaiseEvents => base.CanRaiseEvents; public new CreateParams CreateParams => base.CreateParams; public new CurrencyManager DataManager => base.DataManager; public new Cursor DefaultCursor => base.DefaultCursor; public new ImeMode DefaultImeMode => base.DefaultImeMode; public new Padding DefaultMargin => base.DefaultMargin; public new Size DefaultMaximumSize => base.DefaultMaximumSize; public new Size DefaultMinimumSize => base.DefaultMinimumSize; public new Padding DefaultPadding => base.DefaultPadding; public new Size DefaultSize => base.DefaultSize; public new bool DesignMode => base.DesignMode; public new bool DoubleBuffered { get => base.DoubleBuffered; set => base.DoubleBuffered = value; } public new EventHandlerList Events => base.Events; public new int FontHeight { get => base.FontHeight; set => base.FontHeight = value; } public new ImeMode ImeModeBase { get => base.ImeModeBase; set => base.ImeModeBase = value; } public new bool ResizeRedraw { get => base.ResizeRedraw; set => base.ResizeRedraw = value; } public new bool ShowFocusCues => base.ShowFocusCues; public new bool ShowKeyboardCues => base.ShowKeyboardCues; #pragma warning disable 0618 public new void AddItemsCore(object[] value) => base.AddItemsCore(value); #pragma warning restore 0618 public new AccessibleObject CreateAccessibilityInstance() => base.CreateAccessibilityInstance(); public new ObjectCollection CreateItemCollection() => base.CreateItemCollection(); public new AutoSizeMode GetAutoSizeMode() => base.GetAutoSizeMode(); public new bool GetStyle(ControlStyles flag) => base.GetStyle(flag); public new bool GetTopLevel() => base.GetTopLevel(); public new void OnChangeUICues(UICuesEventArgs e) => base.OnChangeUICues(e); public new void OnClick(EventArgs e) => base.OnClick(e); public new void OnDataSourceChanged(EventArgs e) => base.OnDataSourceChanged(e); public new void OnDisplayMemberChanged(EventArgs e) => base.OnDisplayMemberChanged(e); public new void OnDrawItem(DrawItemEventArgs e) => base.OnDrawItem(e); public new void OnFontChanged(EventArgs e) => base.OnFontChanged(e); public new void OnGotFocus(EventArgs e) => base.OnGotFocus(e); public new void OnHandleCreated(EventArgs e) => base.OnHandleCreated(e); public new void OnHandleDestroyed(EventArgs e) => base.OnHandleDestroyed(e); public new void OnMeasureItem(MeasureItemEventArgs e) => base.OnMeasureItem(e); public new void OnMouseClick(MouseEventArgs e) => base.OnMouseClick(e); public new void OnPaint(PaintEventArgs e) => base.OnPaint(e); public new void OnParentChanged(EventArgs e) => base.OnParentChanged(e); public new void OnResize(EventArgs e) => base.OnResize(e); public new void OnSelectedIndexChanged(EventArgs e) => base.OnSelectedIndexChanged(e); public new void OnSelectedValueChanged(EventArgs e) => base.OnSelectedValueChanged(e); public new void RefreshItem(int index) => base.RefreshItem(index); public new void RefreshItems() => base.RefreshItems(); public new void RescaleConstantsForDpi(int deviceDpiOld, int deviceDpiNew) => base.RescaleConstantsForDpi(deviceDpiOld, deviceDpiNew); public new void ScaleControl(SizeF factor, BoundsSpecified specified) => base.ScaleControl(factor, specified); public new void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified) => base.SetBoundsCore(x, y, width, height, specified); public new void SetItemCore(int index, object value) => base.SetItemCore(index, value); public new void SetItemsCore(IList value) => base.SetItemsCore(value); public new void Sort() => base.Sort(); public new void WmReflectCommand(ref Message m) => base.WmReflectCommand(ref m); public new void WndProc(ref Message m) => base.WndProc(ref m); } private class DataClass { public string Value { get; set; } } } }
42.712502
251
0.599344
[ "MIT" ]
abdullah1133/winforms
src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ListBoxTests.cs
266,827
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ServicesCars.Models { using System; using System.Collections.Generic; public partial class vwAtendimentos { public int id { get; set; } public string cliente { get; set; } public string serviço { get; set; } public string modelo { get; set; } public string grupo { get; set; } public string marca { get; set; } public string matricula { get; set; } public string pagamento { get; set; } public Nullable<decimal> valor { get; set; } public System.TimeSpan hora { get; set; } public System.DateTime data { get; set; } public string estado { get; set; } public string funcionário { get; set; } } }
36.1875
85
0.537133
[ "Apache-2.0" ]
RaulMatias7/ServicesCar
ServicesCars/Models/vwAtendimentos.cs
1,160
C#
using System; namespace Dragonite.Objects { public enum DragonState { healthy, dead } public class DragonStates { // Difffernt possible states the dragon can have public static string GetDragonString(DragonState dragonState) { switch (dragonState) { case DragonState.healthy: return "healthy"; case DragonState.dead: return "dead"; default: return "healthy"; } } public static DragonState GetDragonState(string dragonString) { switch (dragonString) { case "healthy": return DragonState.healthy; case "dead": return DragonState.dead; default: return DragonState.healthy; } } } }
21.108696
69
0.467559
[ "MIT" ]
James-Havinga99/Dragonite_App
Dragonite/Objects/DragonState.cs
973
C#
/** * Wallee SDK Client * * This client allows to interact with the Wallee API. * * Wallee API: 1.0.0 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; namespace Customweb.Wallee.Model { /// <summary> /// Application User /// </summary> [DataContract] public partial class ApplicationUserUpdate : AbstractApplicationUserUpdate, IEquatable<ApplicationUserUpdate>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="ApplicationUserUpdate" /> class. /// </summary> [JsonConstructorAttribute] protected ApplicationUserUpdate() { } /// <summary> /// Initializes a new instance of the <see cref="ApplicationUserUpdate" /> class. /// </summary> /// <param name="Id">The ID is the primary key of the entity. The ID identifies the entity uniquely. (required)</param> /// <param name="Version">The version number indicates the version of the entity. The version is incremented whenever the entity is changed. (required)</param> public ApplicationUserUpdate(string Name = default(string), long? Id = default(long?), long? Version = default(long?), CreationEntityState? State = default(CreationEntityState?)) { // to ensure "Id" is required (not null) if (Id == null) { throw new ArgumentNullException("Id is a required property for ApplicationUserUpdate and cannot be null"); } else { this.Id = Id; } // to ensure "Version" is required (not null) if (Version == null) { throw new ArgumentNullException("Version is a required property for ApplicationUserUpdate and cannot be null"); } else { this.Version = Version; } this.Name = Name; this.State = State; } /// <summary> /// The ID is the primary key of the entity. The ID identifies the entity uniquely. /// </summary> /// <value>The ID is the primary key of the entity. The ID identifies the entity uniquely.</value> [DataMember(Name="id", EmitDefaultValue=false)] public long? Id { get; set; } /// <summary> /// The version number indicates the version of the entity. The version is incremented whenever the entity is changed. /// </summary> /// <value>The version number indicates the version of the entity. The version is incremented whenever the entity is changed.</value> [DataMember(Name="version", EmitDefaultValue=false)] public long? Version { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { return this.ToJson(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public new string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="obj">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object obj) { return this.Equals(obj as ApplicationUserUpdate); } /// <summary> /// Returns true if ApplicationUserUpdate instances are equal /// </summary> /// <param name="other">Instance of ApplicationUserUpdate to be compared</param> /// <returns>Boolean</returns> public bool Equals(ApplicationUserUpdate other) { if (other == null) { return false; } return ( this.Id == other.Id || this.Id != null && this.Id.Equals(other.Id) ) && ( this.Version == other.Version || this.Version != null && this.Version.Equals(other.Version) ) && ( this.Name == other.Name || this.Name != null && this.Name.Equals(other.Name) ) && ( this.State == other.State || this.State != null && this.State.Equals(other.State) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hash = 41; if (this.Id != null) { hash = hash * 59 + this.Id.GetHashCode(); } if (this.Version != null) { hash = hash * 59 + this.Version.GetHashCode(); } if (this.Name != null) { hash = hash * 59 + this.Name.GetHashCode(); } if (this.State != null) { hash = hash * 59 + this.State.GetHashCode(); } return hash; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
35.476923
186
0.551605
[ "Apache-2.0" ]
computop-services/c--sdk
src/Customweb.Wallee/Model/ApplicationUserUpdate.cs
6,918
C#
namespace FindScanCode { partial class FindScanCodeForm { private System.ComponentModel.IContainer components = null; protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form 디자이너에서 생성한 코드 /// <summary> /// 디자이너 지원에 필요한 메서드입니다. /// 이 메서드의 내용을 코드 편집기로 수정하지 마세요. /// </summary> private void InitializeComponent() { System.Windows.Forms.Label label1; this.lbScanCode = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.lbVKey = new System.Windows.Forms.Label(); label1 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // label1 // label1.AutoSize = true; label1.Location = new System.Drawing.Point(13, 13); label1.Name = "label1"; label1.Size = new System.Drawing.Size(125, 24); label1.TabIndex = 0; label1.Text = "ScanCode:"; // // lbScanCode // this.lbScanCode.AutoSize = true; this.lbScanCode.Location = new System.Drawing.Point(145, 13); this.lbScanCode.Name = "lbScanCode"; this.lbScanCode.Size = new System.Drawing.Size(114, 24); this.lbScanCode.TabIndex = 1; this.lbScanCode.Text = "00000000"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(266, 13); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(71, 24); this.label2.TabIndex = 2; this.label2.Text = "VKey:"; // // lbVKey // this.lbVKey.AutoSize = true; this.lbVKey.Location = new System.Drawing.Point(344, 13); this.lbVKey.Name = "lbVKey"; this.lbVKey.Size = new System.Drawing.Size(270, 24); this.lbVKey.TabIndex = 3; this.lbVKey.Text = "00000000000000000000"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(13F, 24F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(637, 53); this.Controls.Add(this.lbVKey); this.Controls.Add(this.label2); this.Controls.Add(this.lbScanCode); this.Controls.Add(label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.Name = "Form1"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "FindScanCode"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label lbScanCode; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label lbVKey; } }
36.255319
86
0.524941
[ "MIT" ]
bspfp/findscancode
FindScanCodeForm.Designer.cs
3,506
C#
using Core.Services.Helpers; using System; using System.Linq; using System.Linq.Expressions; namespace Core.Services.Extensions { public static class ExpressionExtensions { public static Expression<T> Compose<T>(this Expression<T> first, Expression<T> second, Func<Expression, Expression, Expression> merge) { // build parameter map (from parameters of second to parameters of first) var map = first.Parameters.Select((f, i) => new { f, s = second.Parameters[i] }).ToDictionary(p => p.s, p => p.f); // replace parameters in the second lambda expression with parameters from the first var secondBody = ParameterRebinder.ReplaceParameters(map, second.Body); // apply composition of lambda expression bodies to parameters from the first expression return Expression.Lambda<T>(merge(first.Body, secondBody), first.Parameters); } public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) { return first.Compose(second, Expression.And); } public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> first, Expression<Func<T, bool>> second) { return first.Compose(second, Expression.Or); } } }
46.482759
142
0.661721
[ "MIT" ]
zolgera/Onion.Core.Services
Extensions/ExpressionExtensions.cs
1,350
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Tests; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Text.Tests { public partial class StringBuilderTests { private static readonly string s_chunkSplitSource = new string('a', 30); private static readonly string s_noCapacityParamName = "valueCount"; private static StringBuilder StringBuilderWithMultipleChunks() => new StringBuilder(20).Append(s_chunkSplitSource); [Fact] public static void Ctor_Empty() { var builder = new StringBuilder(); Assert.Same(string.Empty, builder.ToString()); Assert.Equal(string.Empty, builder.ToString(0, 0)); Assert.Equal(0, builder.Length); Assert.Equal(int.MaxValue, builder.MaxCapacity); } [Fact] public static void Ctor_Int() { var builder = new StringBuilder(42); Assert.Same(string.Empty, builder.ToString()); Assert.Equal(0, builder.Length); Assert.True(builder.Capacity >= 42); Assert.Equal(int.MaxValue, builder.MaxCapacity); } [Fact] public static void Ctor_Int_NegativeCapacity_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new StringBuilder(-1)); // Capacity < 0 } [Fact] public static void Ctor_Int_Int() { // The second int parameter is MaxCapacity but in CLR4.0 and later, StringBuilder isn't required to honor it. var builder = new StringBuilder(42, 50); Assert.Equal("", builder.ToString()); Assert.Equal(0, builder.Length); Assert.InRange(builder.Capacity, 42, builder.MaxCapacity); Assert.Equal(50, builder.MaxCapacity); } [Fact] public static void Ctor_Int_Int_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new StringBuilder(-1, 1)); // Capacity < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("maxCapacity", () => new StringBuilder(0, 0)); // MaxCapacity < 1 AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new StringBuilder(2, 1)); // Capacity > maxCapacity } [Theory] [InlineData("Hello")] [InlineData("")] [InlineData(null)] public static void Ctor_String(string value) { var builder = new StringBuilder(value); string expected = value ?? ""; Assert.Equal(expected, builder.ToString()); Assert.Equal(expected.Length, builder.Length); } [Theory] [InlineData("Hello")] [InlineData("")] [InlineData(null)] public static void Ctor_String_Int(string value) { var builder = new StringBuilder(value, 42); string expected = value ?? ""; Assert.Equal(expected, builder.ToString()); Assert.Equal(expected.Length, builder.Length); Assert.True(builder.Capacity >= 42); } [Fact] public static void Ctor_String_Int_NegativeCapacity_ThrowsArgumentOutOfRangeException() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new StringBuilder("", -1)); // Capacity < 0 } [Theory] [InlineData("Hello", 0, 5)] [InlineData("Hello", 2, 3)] [InlineData("", 0, 0)] [InlineData(null, 0, 0)] public static void Ctor_String_Int_Int_Int(string value, int startIndex, int length) { var builder = new StringBuilder(value, startIndex, length, 42); string expected = value?.Substring(startIndex, length) ?? ""; Assert.Equal(expected, builder.ToString()); Assert.Equal(length, builder.Length); Assert.Equal(expected.Length, builder.Length); Assert.True(builder.Capacity >= 42); } [Fact] public static void Ctor_String_Int_Int_Int_Invalid() { AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => new StringBuilder("foo", -1, 0, 0)); // Start index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => new StringBuilder("foo", 0, -1, 0)); // Length < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => new StringBuilder("foo", 0, 0, -1)); // Capacity < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => new StringBuilder("foo", 4, 0, 0)); // Start index + length > builder.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => new StringBuilder("foo", 3, 1, 0)); // Start index + length > builder.Length } [Fact] public static void Item_Get_Set() { string s = "Hello"; var builder = new StringBuilder(s); for (int i = 0; i < s.Length; i++) { Assert.Equal(s[i], builder[i]); char c = (char)(i + '0'); builder[i] = c; Assert.Equal(c, builder[i]); } Assert.Equal("01234", builder.ToString()); } [Fact] public static void Item_Get_Set_InvalidIndex() { var builder = new StringBuilder("Hello"); Assert.Throws<IndexOutOfRangeException>(() => builder[-1]); // Index < 0 Assert.Throws<IndexOutOfRangeException>(() => builder[5]); // Index >= string.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder[-1] = 'a'); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder[5] = 'a'); // Index >= string.Length } [Fact] public static void Capacity_Get_Set() { var builder = new StringBuilder("Hello"); Assert.True(builder.Capacity >= builder.Length); builder.Capacity = 10; Assert.True(builder.Capacity >= 10); builder.Capacity = 5; Assert.True(builder.Capacity >= 5); // Setting the capacity to the same value does not change anything int oldCapacity = builder.Capacity; builder.Capacity = 5; Assert.Equal(oldCapacity, builder.Capacity); } [Fact] public static void Capacity_Set_Invalid_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(10, 10); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => builder.Capacity = -1); // Capacity < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => builder.Capacity = builder.MaxCapacity + 1); // Capacity > builder.MaxCapacity AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => builder.Capacity = builder.Length - 1); // Capacity < builder.Length } [Fact] public static void Length_Get_Set() { var builder = new StringBuilder("Hello"); builder.Length = 2; Assert.Equal(2, builder.Length); Assert.Equal("He", builder.ToString()); builder.Length = 10; Assert.Equal(10, builder.Length); Assert.Equal("He" + new string((char)0, 8), builder.ToString()); } [Fact] public static void Length_Set_InvalidValue_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(10, 10); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => builder.Length = -1); // Value < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => builder.Length = builder.MaxCapacity + 1); // Value > builder.MaxCapacity } [Theory] [InlineData("Hello", (ushort)0, "Hello0")] [InlineData("Hello", (ushort)123, "Hello123")] [InlineData("", (ushort)456, "456")] public static void Append_UShort(string original, ushort value, string expected) { var builder = new StringBuilder(original); builder.Append(value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Append_UShort_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.Append((ushort)1)); } [Theory] [InlineData("Hello", true, "HelloTrue")] [InlineData("Hello", false, "HelloFalse")] [InlineData("", false, "False")] public static void Append_Bool(string original, bool value, string expected) { var builder = new StringBuilder(original); builder.Append(value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Append_Bool_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.Append(true)); } public static IEnumerable<object[]> Append_Decimal_TestData() { yield return new object[] { "Hello", (double)0, "Hello0" }; yield return new object[] { "Hello", 1.23, "Hello1.23" }; yield return new object[] { "", -4.56, "-4.56" }; } [Fact] public static void Test_Append_Decimal() { using (new ThreadCultureChange(CultureInfo.InvariantCulture)) { foreach (var testdata in Append_Decimal_TestData()) { Append_Decimal((string)testdata[0], (double)testdata[1], (string)testdata[2]); } } } private static void Append_Decimal(string original, double doubleValue, string expected) { var builder = new StringBuilder(original); builder.Append(new decimal(doubleValue)); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Append_Decimal_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.Append((decimal)1)); } public static IEnumerable<object[]> Append_Double_TestData() { yield return new object[] { "Hello", (double)0, "Hello0" }; yield return new object[] { "Hello", 1.23, "Hello1.23" }; yield return new object[] { "", -4.56, "-4.56" }; } [Fact] public static void Test_Append_Double() { using (new ThreadCultureChange(CultureInfo.InvariantCulture)) { foreach (var testdata in Append_Double_TestData()) { Append_Double((string)testdata[0], (double)testdata[1], (string)testdata[2]); } } } private static void Append_Double(string original, double value, string expected) { var builder = new StringBuilder(original); builder.Append(value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Append_Double_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.Append((double)1)); } [Theory] [InlineData("Hello", (short)0, "Hello0")] [InlineData("Hello", (short)123, "Hello123")] [InlineData("", (short)-456, "-456")] public static void Append_Short(string original, short value, string expected) { var builder = new StringBuilder(original); builder.Append(value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Append_Short_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.Append((short)1)); } [Theory] [InlineData("Hello", 0, "Hello0")] [InlineData("Hello", 123, "Hello123")] [InlineData("", -456, "-456")] public static void Append_Int(string original, int value, string expected) { var builder = new StringBuilder(original); builder.Append(value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Append_Int_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.Append(1)); } [Theory] [InlineData("Hello", (long)0, "Hello0")] [InlineData("Hello", (long)123, "Hello123")] [InlineData("", (long)-456, "-456")] public static void Append_Long(string original, long value, string expected) { var builder = new StringBuilder(original); builder.Append(value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Append_Long_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.Append((long)1)); } [Theory] [InlineData("Hello", "abc", "Helloabc")] [InlineData("Hello", "def", "Hellodef")] [InlineData("", "g", "g")] [InlineData("Hello", "", "Hello")] [InlineData("Hello", null, "Hello")] public static void Append_Object(string original, object value, string expected) { var builder = new StringBuilder(original); builder.Append(value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Append_Object_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.Append(new object())); } [Theory] [InlineData("Hello", (sbyte)0, "Hello0")] [InlineData("Hello", (sbyte)123, "Hello123")] [InlineData("", (sbyte)-123, "-123")] public static void Append_SByte(string original, sbyte value, string expected) { var builder = new StringBuilder(original); builder.Append(value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Append_SByte_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.Append((sbyte)1)); } public static IEnumerable<object[]> Append_Float_TestData() { yield return new object[] { "Hello", (float)0, "Hello0" }; yield return new object[] { "Hello", (float)1.23, "Hello1.23" }; yield return new object[] { "", (float)-4.56, "-4.56" }; } [Fact] public static void Test_Append_Float() { using (new ThreadCultureChange(CultureInfo.InvariantCulture)) { foreach (var testdata in Append_Float_TestData()) { Append_Float((string)testdata[0], (float)testdata[1], (string)testdata[2]); } } } private static void Append_Float(string original, float value, string expected) { var builder = new StringBuilder(original); builder.Append(value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Append_Float_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.Append((float)1)); } [Theory] [InlineData("Hello", (byte)0, "Hello0")] [InlineData("Hello", (byte)123, "Hello123")] [InlineData("", (byte)123, "123")] public static void Append_Byte(string original, byte value, string expected) { var builder = new StringBuilder(original); builder.Append(value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Append_Byte_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.Append((byte)1)); } [Theory] [InlineData("Hello", (uint)0, "Hello0")] [InlineData("Hello", (uint)123, "Hello123")] [InlineData("", (uint)456, "456")] public static void Append_UInt(string original, uint value, string expected) { var builder = new StringBuilder(original); builder.Append(value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Append_UInt_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.Append((uint)1)); } [Theory] [InlineData("Hello", (ulong)0, "Hello0")] [InlineData("Hello", (ulong)123, "Hello123")] [InlineData("", (ulong)456, "456")] public static void Append_ULong(string original, ulong value, string expected) { var builder = new StringBuilder(original); builder.Append(value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Append_ULong_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.Append((ulong)1)); } [Theory] [InlineData("Hello", '\0', 1, "Hello\0")] [InlineData("Hello", 'a', 1, "Helloa")] [InlineData("", 'b', 1, "b")] [InlineData("Hello", 'c', 2, "Hellocc")] [InlineData("Hello", '\0', 0, "Hello")] public static void Append_Char(string original, char value, int repeatCount, string expected) { StringBuilder builder; if (repeatCount == 1) { // Use Append(char) builder = new StringBuilder(original); builder.Append(value); Assert.Equal(expected, builder.ToString()); } // Use Append(char, int) builder = new StringBuilder(original); builder.Append(value, repeatCount); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Append_Char_NegativeRepeatCount_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); AssertExtensions.Throws<ArgumentOutOfRangeException>("repeatCount", () => builder.Append('a', -1)); } [Fact] public static void Append_Char_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("repeatCount", "requiredLength", () => builder.Append('a')); AssertExtensions.Throws<ArgumentOutOfRangeException>("repeatCount", "requiredLength", () => builder.Append('a', 1)); } [Theory] [InlineData("Hello", new char[] { 'a', 'b', 'c' }, 1, "Helloa")] [InlineData("Hello", new char[] { 'a', 'b', 'c' }, 2, "Helloab")] [InlineData("Hello", new char[] { 'a', 'b', 'c' }, 3, "Helloabc")] [InlineData("", new char[] { 'a' }, 1, "a")] [InlineData("", new char[] { 'a' }, 0, "")] [InlineData("Hello", new char[0], 0, "Hello")] [InlineData("Hello", null, 0, "Hello")] public static unsafe void Append_CharPointer(string original, char[] charArray, int valueCount, string expected) { _ = charArray; // https://github.com/xunit/xunit/issues/1969 fixed (char* value = charArray) { var builder = new StringBuilder(original); builder.Append(value, valueCount); Assert.Equal(expected, builder.ToString()); } } [Fact] public static unsafe void Append_CharPointer_Null_ThrowsNullReferenceException() { var builder = new StringBuilder(); Assert.Throws<NullReferenceException>(() => builder.Append(null, 2)); } [Fact] public static unsafe void Append_CharPointer_NegativeValueCount_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("valueCount", () => { fixed (char* value = new char[0]) { builder.Append(value, -1); } }); } [Fact] public static unsafe void Append_CharPointer_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => { fixed (char* value = new char[] { 'a' }) { builder.Append(value, 1); } }); } [Theory] [InlineData("Hello", "abc", 0, 3, "Helloabc")] [InlineData("Hello", "def", 1, 2, "Helloef")] [InlineData("Hello", "def", 2, 1, "Hellof")] [InlineData("", "g", 0, 1, "g")] [InlineData("Hello", "g", 1, 0, "Hello")] [InlineData("Hello", "g", 0, 0, "Hello")] [InlineData("Hello", "", 0, 0, "Hello")] [InlineData("Hello", null, 0, 0, "Hello")] public static void Append_String(string original, string value, int startIndex, int count, string expected) { StringBuilder builder; if (startIndex == 0 && count == (value?.Length ?? 0)) { // Use Append(string) builder = new StringBuilder(original); builder.Append(value); Assert.Equal(expected, builder.ToString()); } // Use Append(string, int, int) builder = new StringBuilder(original); builder.Append(value, startIndex, count); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Append_String_NullValueNonZeroStartIndexCount_ThrowsArgumentNullException() { var builder = new StringBuilder(); AssertExtensions.Throws<ArgumentNullException>("value", () => builder.Append((string)null, 1, 1)); } [Theory] [InlineData("", -1, 0)] [InlineData("hello", 5, 1)] [InlineData("hello", 4, 2)] public static void Append_String_InvalidIndexPlusCount_ThrowsArgumentOutOfRangeException(string value, int startIndex, int count) { var builder = new StringBuilder(); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => builder.Append(value, startIndex, count)); } [Fact] public static void Append_String_NegativeCount_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.Append("", 0, -1)); } [Fact] public static void Append_String_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.Append("a")); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.Append("a", 0, 1)); } [Theory] [InlineData("Hello", new char[] { 'a' }, 0, 1, "Helloa")] [InlineData("Hello", new char[] { 'b', 'c', 'd' }, 0, 3, "Hellobcd")] [InlineData("Hello", new char[] { 'b', 'c', 'd' }, 1, 2, "Hellocd")] [InlineData("Hello", new char[] { 'b', 'c', 'd' }, 2, 1, "Hellod")] [InlineData("", new char[] { 'e', 'f', 'g' }, 0, 3, "efg")] [InlineData("Hello", new char[] { 'e' }, 1, 0, "Hello")] [InlineData("Hello", new char[] { 'e' }, 0, 0, "Hello")] [InlineData("Hello", new char[0], 0, 0, "Hello")] [InlineData("Hello", null, 0, 0, "Hello")] public static void Append_CharArray(string original, char[] value, int startIndex, int charCount, string expected) { StringBuilder builder; if (startIndex == 0 && charCount == (value?.Length ?? 0)) { // Use Append(char[]) builder = new StringBuilder(original); builder.Append(value); Assert.Equal(expected, builder.ToString()); } // Use Append(char[], int, int) builder = new StringBuilder(original); builder.Append(value, startIndex, charCount); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Append_CharArray_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentNullException>("value", () => builder.Append((char[])null, 1, 1)); // Value is null, startIndex > 0 and count > 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => builder.Append(new char[0], -1, 0)); // Start index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => builder.Append(new char[0], 0, -1)); // Count < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => builder.Append(new char[5], 6, 0)); // Start index + count > value.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => builder.Append(new char[5], 5, 1)); // Start index + count > value.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("valueCount", () => builder.Append(new char[] { 'a' })); // New length > builder.MaxCapacity AssertExtensions.Throws<ArgumentOutOfRangeException>("valueCount", () => builder.Append(new char[] { 'a' }, 0, 1)); // New length > builder.MaxCapacity } public static IEnumerable<object[]> AppendFormat_TestData() { yield return new object[] { "", null, "", new object[0], "" }; yield return new object[] { "", null, ", ", new object[0], ", " }; yield return new object[] { "Hello", null, ", Foo {0 }", new object[] { "Bar" }, "Hello, Foo Bar" }; // Ignores whitespace yield return new object[] { "Hello", null, ", Foo {0}", new object[] { "Bar" }, "Hello, Foo Bar" }; yield return new object[] { "Hello", null, ", Foo {0} Baz {1}", new object[] { "Bar", "Foo" }, "Hello, Foo Bar Baz Foo" }; yield return new object[] { "Hello", null, ", Foo {0} Baz {1} Bar {2}", new object[] { "Bar", "Foo", "Baz" }, "Hello, Foo Bar Baz Foo Bar Baz" }; yield return new object[] { "Hello", null, ", Foo {0} Baz {1} Bar {2} Foo {3}", new object[] { "Bar", "Foo", "Baz", "Bar" }, "Hello, Foo Bar Baz Foo Bar Baz Foo Bar" }; // Length is positive yield return new object[] { "Hello", null, ", Foo {0,2}", new object[] { "Bar" }, "Hello, Foo Bar" }; // MiValue's length > minimum length (so don't prepend whitespace) yield return new object[] { "Hello", null, ", Foo {0,3}", new object[] { "B" }, "Hello, Foo B" }; // Value's length < minimum length (so prepend whitespace) yield return new object[] { "Hello", null, ", Foo {0, 3}", new object[] { "B" }, "Hello, Foo B" }; // Same as above, but verify AppendFormat ignores whitespace yield return new object[] { "Hello", null, ", Foo {0,0}", new object[] { "Bar" }, "Hello, Foo Bar" }; // Minimum length is 0 // Length is negative yield return new object[] { "Hello", null, ", Foo {0,-2}", new object[] { "Bar" }, "Hello, Foo Bar" }; // Value's length > |minimum length| (so don't prepend whitespace) yield return new object[] { "Hello", null, ", Foo {0,-3}", new object[] { "B" }, "Hello, Foo B " }; // Value's length < |minimum length| (so append whitespace) yield return new object[] { "Hello", null, ", Foo {0, -3}", new object[] { "B" }, "Hello, Foo B " }; // Same as above, but verify AppendFormat ignores whitespace yield return new object[] { "Hello", null, ", Foo {0,0}", new object[] { "Bar" }, "Hello, Foo Bar" }; // Minimum length is 0 yield return new object[] { "Hello", null, ", Foo {0:D6}", new object[] { 1 }, "Hello, Foo 000001" }; // Custom format yield return new object[] { "Hello", null, ", Foo {0 :D6}", new object[] { 1 }, "Hello, Foo 000001" }; // Custom format with ignored whitespace yield return new object[] { "Hello", null, ", Foo {0:}", new object[] { 1 }, "Hello, Foo 1" }; // Missing custom format yield return new object[] { "Hello", null, ", Foo {0,9:D6}", new object[] { 1 }, "Hello, Foo 000001" }; // Positive minimum length and custom format yield return new object[] { "Hello", null, ", Foo {0,-9:D6}", new object[] { 1 }, "Hello, Foo 000001 " }; // Negative length and custom format yield return new object[] { "Hello", null, ", Foo {{{0}", new object[] { 1 }, "Hello, Foo {1" }; // Escaped open curly braces yield return new object[] { "Hello", null, ", Foo }}{0}", new object[] { 1 }, "Hello, Foo }1" }; // Escaped closed curly braces yield return new object[] { "Hello", null, ", Foo {0} {{0}}", new object[] { 1 }, "Hello, Foo 1 {0}" }; // Escaped placeholder yield return new object[] { "Hello", null, ", Foo {0}", new object[] { null }, "Hello, Foo " }; // Values has null only yield return new object[] { "Hello", null, ", Foo {0} {1} {2}", new object[] { "Bar", null, "Baz" }, "Hello, Foo Bar Baz" }; // Values has null yield return new object[] { "Hello", CultureInfo.InvariantCulture, ", Foo {0,9:D6}", new object[] { 1 }, "Hello, Foo 000001" }; // Positive minimum length, custom format and custom format provider yield return new object[] { "", new CustomFormatter(), "{0}", new object[] { 1.2 }, "abc" }; // Custom format provider yield return new object[] { "", new CustomFormatter(), "{0:0}", new object[] { 1.2 }, "abc" }; // Custom format provider } [Theory] [MemberData(nameof(AppendFormat_TestData))] public static void AppendFormat(string original, IFormatProvider provider, string format, object[] values, string expected) { StringBuilder builder; if (values != null) { if (values.Length == 1) { // Use AppendFormat(string, object) or AppendFormat(IFormatProvider, string, object) if (provider == null) { // Use AppendFormat(string, object) builder = new StringBuilder(original); builder.AppendFormat(format, values[0]); Assert.Equal(expected, builder.ToString()); } // Use AppendFormat(IFormatProvider, string, object) builder = new StringBuilder(original); builder.AppendFormat(provider, format, values[0]); Assert.Equal(expected, builder.ToString()); } else if (values.Length == 2) { // Use AppendFormat(string, object, object) or AppendFormat(IFormatProvider, string, object, object) if (provider == null) { // Use AppendFormat(string, object, object) builder = new StringBuilder(original); builder.AppendFormat(format, values[0], values[1]); Assert.Equal(expected, builder.ToString()); } // Use AppendFormat(IFormatProvider, string, object, object) builder = new StringBuilder(original); builder.AppendFormat(provider, format, values[0], values[1]); Assert.Equal(expected, builder.ToString()); } else if (values.Length == 3) { // Use AppendFormat(string, object, object, object) or AppendFormat(IFormatProvider, string, object, object, object) if (provider == null) { // Use AppendFormat(string, object, object, object) builder = new StringBuilder(original); builder.AppendFormat(format, values[0], values[1], values[2]); Assert.Equal(expected, builder.ToString()); } // Use AppendFormat(IFormatProvider, string, object, object, object) builder = new StringBuilder(original); builder.AppendFormat(provider, format, values[0], values[1], values[2]); Assert.Equal(expected, builder.ToString()); } } // Use AppendFormat(string, object[]) or AppendFormat(IFormatProvider, string, object[]) if (provider == null) { // Use AppendFormat(string, object[]) builder = new StringBuilder(original); builder.AppendFormat(format, values); Assert.Equal(expected, builder.ToString()); } // Use AppendFormat(IFormatProvider, string, object[]) builder = new StringBuilder(original); builder.AppendFormat(provider, format, values); Assert.Equal(expected, builder.ToString()); } [Fact] public static void AppendFormat_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); IFormatProvider formatter = null; var obj1 = new object(); var obj2 = new object(); var obj3 = new object(); var obj4 = new object(); AssertExtensions.Throws<ArgumentNullException>("format", () => builder.AppendFormat(null, obj1)); // Format is null AssertExtensions.Throws<ArgumentNullException>("format", () => builder.AppendFormat(null, obj1, obj2, obj3)); // Format is null AssertExtensions.Throws<ArgumentNullException>("format", () => builder.AppendFormat(null, obj1, obj2, obj3)); // Format is null AssertExtensions.Throws<ArgumentNullException>("format", () => builder.AppendFormat(null, obj1, obj2, obj3, obj4)); // Format is null AssertExtensions.Throws<ArgumentNullException>("args", () => builder.AppendFormat("", null)); // Args is null AssertExtensions.Throws<ArgumentNullException>("format", () => builder.AppendFormat(null, (object[])null)); // Both format and args are null AssertExtensions.Throws<ArgumentNullException>("format", () => builder.AppendFormat(formatter, null, obj1)); // Format is null AssertExtensions.Throws<ArgumentNullException>("format", () => builder.AppendFormat(formatter, null, obj1, obj2)); // Format is null AssertExtensions.Throws<ArgumentNullException>("format", () => builder.AppendFormat(formatter, null, obj1, obj2, obj3)); // Format is null AssertExtensions.Throws<ArgumentNullException>("format", () => builder.AppendFormat(formatter, null, obj1, obj2, obj3, obj4)); // Format is null AssertExtensions.Throws<ArgumentNullException>("args", () => builder.AppendFormat(formatter, "", null)); // Args is null AssertExtensions.Throws<ArgumentNullException>("format", () => builder.AppendFormat(formatter, null, null)); // Both format and args are null Assert.Throws<FormatException>(() => builder.AppendFormat("{-1}", obj1)); // Format has value < 0 Assert.Throws<FormatException>(() => builder.AppendFormat("{-1}", obj1, obj2)); // Format has value < 0 Assert.Throws<FormatException>(() => builder.AppendFormat("{-1}", obj1, obj2, obj3)); // Format has value < 0 Assert.Throws<FormatException>(() => builder.AppendFormat("{-1}", obj1, obj2, obj3, obj4)); // Format has value < 0 Assert.Throws<FormatException>(() => builder.AppendFormat(formatter, "{-1}", obj1)); // Format has value < 0 Assert.Throws<FormatException>(() => builder.AppendFormat(formatter, "{-1}", obj1, obj2)); // Format has value < 0 Assert.Throws<FormatException>(() => builder.AppendFormat(formatter, "{-1}", obj1, obj2, obj3)); // Format has value < 0 Assert.Throws<FormatException>(() => builder.AppendFormat(formatter, "{-1}", obj1, obj2, obj3, obj4)); // Format has value < 0 Assert.Throws<FormatException>(() => builder.AppendFormat("{1}", obj1)); // Format has value >= 1 Assert.Throws<FormatException>(() => builder.AppendFormat("{2}", obj1, obj2)); // Format has value >= 2 Assert.Throws<FormatException>(() => builder.AppendFormat("{3}", obj1, obj2, obj3)); // Format has value >= 3 Assert.Throws<FormatException>(() => builder.AppendFormat("{4}", obj1, obj2, obj3, obj4)); // Format has value >= 4 Assert.Throws<FormatException>(() => builder.AppendFormat(formatter, "{1}", obj1)); // Format has value >= 1 Assert.Throws<FormatException>(() => builder.AppendFormat(formatter, "{2}", obj1, obj2)); // Format has value >= 2 Assert.Throws<FormatException>(() => builder.AppendFormat(formatter, "{3}", obj1, obj2, obj3)); // Format has value >= 3 Assert.Throws<FormatException>(() => builder.AppendFormat(formatter, "{4}", obj1, obj2, obj3, obj4)); // Format has value >= 4 Assert.Throws<FormatException>(() => builder.AppendFormat("{", "")); // Format has unescaped { Assert.Throws<FormatException>(() => builder.AppendFormat("{a", "")); // Format has unescaped { Assert.Throws<FormatException>(() => builder.AppendFormat("}", "")); // Format has unescaped } Assert.Throws<FormatException>(() => builder.AppendFormat("}a", "")); // Format has unescaped } Assert.Throws<FormatException>(() => builder.AppendFormat("{0:}}", "")); // Format has unescaped } Assert.Throws<FormatException>(() => builder.AppendFormat("{\0", "")); // Format has invalid character after { Assert.Throws<FormatException>(() => builder.AppendFormat("{a", "")); // Format has invalid character after { Assert.Throws<FormatException>(() => builder.AppendFormat("{0 ", "")); // Format with index and spaces is not closed Assert.Throws<FormatException>(() => builder.AppendFormat("{1000000", new string[10])); // Format index is too long Assert.Throws<FormatException>(() => builder.AppendFormat("{10000000}", new string[10])); // Format index is too long Assert.Throws<FormatException>(() => builder.AppendFormat("{0,", "")); // Format with comma is not closed Assert.Throws<FormatException>(() => builder.AppendFormat("{0, ", "")); // Format with comma and spaces is not closed Assert.Throws<FormatException>(() => builder.AppendFormat("{0,-", "")); // Format with comma and minus sign is not closed Assert.Throws<FormatException>(() => builder.AppendFormat("{0,-\0", "")); // Format has invalid character after minus sign Assert.Throws<FormatException>(() => builder.AppendFormat("{0,-a", "")); // Format has invalid character after minus sign Assert.Throws<FormatException>(() => builder.AppendFormat("{0,1000000", new string[10])); // Format length is too long Assert.Throws<FormatException>(() => builder.AppendFormat("{0,10000000}", new string[10])); // Format length is too long Assert.Throws<FormatException>(() => builder.AppendFormat("{0:", new string[10])); // Format with colon is not closed Assert.Throws<FormatException>(() => builder.AppendFormat("{0: ", new string[10])); // Format with colon and spaces is not closed Assert.Throws<FormatException>(() => builder.AppendFormat("{0:{", new string[10])); // Format with custom format contains unescaped { Assert.Throws<FormatException>(() => builder.AppendFormat("{0:{}", new string[10])); // Format with custom format contains unescaped { } [Fact] public static void AppendFormat_NoEscapedBracesInCustomFormatSpecifier() { // Tests new rule which does not allow escaped braces in the custom format specifier var builder = new StringBuilder(); builder.AppendFormat("{0:}}}", 0); // Previous behavior: first two closing braces would be escaped and passed in as the custom format specifier, thus result = "}" // New behavior: first closing brace closes the argument hole and next two are escaped as part of the format, thus result = "0}" Assert.Equal("0}", builder.ToString()); // Previously this would be allowed and escaped brace would be passed into the custom format, now this is unsupported Assert.Throws<FormatException>(() => builder.AppendFormat("{0:{{}", 0)); // Format with custom format contains { } [Fact] public static void AppendFormat_NewLengthGreaterThanBuilderLength_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); IFormatProvider formatter = null; builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.AppendFormat("{0}", "a")); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.AppendFormat("{0}", "a", "")); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.AppendFormat("{0}", "a", "", "")); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.AppendFormat("{0}", "a", "", "", "")); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.AppendFormat(formatter, "{0}", "a")); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.AppendFormat(formatter, "{0}", "a", "")); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.AppendFormat(formatter, "{0}", "a", "", "")); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.AppendFormat(formatter, "{0}", "a", "", "", "")); } public static IEnumerable<object[]> AppendLine_TestData() { yield return new object[] { "Hello", "abc", "Helloabc" + Environment.NewLine }; yield return new object[] { "Hello", "", "Hello" + Environment.NewLine }; yield return new object[] { "Hello", null, "Hello" + Environment.NewLine }; } [Theory] [MemberData(nameof(AppendLine_TestData))] public static void AppendLine(string original, string value, string expected) { StringBuilder builder; if (string.IsNullOrEmpty(value)) { // Use AppendLine() builder = new StringBuilder(original); builder.AppendLine(); Assert.Equal(expected, builder.ToString()); } // Use AppendLine(string) builder = new StringBuilder(original); builder.AppendLine(value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void AppendLine_NoSpareCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.AppendLine()); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => builder.AppendLine("a")); } [Fact] public static void Clear() { var builder = new StringBuilder("Hello"); builder.Clear(); Assert.Equal(0, builder.Length); Assert.Same(string.Empty, builder.ToString()); } [Fact] public static void Clear_Empty_CapacityNotZero() { var builder = new StringBuilder(); builder.Clear(); Assert.NotEqual(0, builder.Capacity); } [Fact] public static void Clear_Empty_CapacityStaysUnchanged() { var sb = new StringBuilder(14); sb.Clear(); Assert.Equal(14, sb.Capacity); } [Fact] public static void Clear_Full_CapacityStaysUnchanged() { var sb = new StringBuilder(14); sb.Append("Hello World!!!"); sb.Clear(); Assert.Equal(14, sb.Capacity); } [Fact] public static void Clear_AtMaxCapacity_CapacityStaysUnchanged() { var builder = new StringBuilder(14, 14); builder.Append("Hello World!!!"); builder.Clear(); Assert.Equal(14, builder.Capacity); } [Theory] [InlineData("Hello", 0, new char[] { '\0', '\0', '\0', '\0', '\0' }, 0, 5, new char[] { 'H', 'e', 'l', 'l', 'o' })] [InlineData("Hello", 0, new char[] { '\0', '\0', '\0', '\0', '\0', '\0' }, 1, 5, new char[] { '\0', 'H', 'e', 'l', 'l', 'o' })] [InlineData("Hello", 0, new char[] { '\0', '\0', '\0', '\0' }, 0, 4, new char[] { 'H', 'e', 'l', 'l' })] [InlineData("Hello", 1, new char[] { '\0', '\0', '\0', '\0', '\0', '\0', '\0' }, 2, 4, new char[] { '\0', '\0', 'e', 'l', 'l', 'o', '\0' })] public static void CopyTo(string value, int sourceIndex, char[] destination, int destinationIndex, int count, char[] expected) { var builder = new StringBuilder(value); builder.CopyTo(sourceIndex, destination, destinationIndex, count); Assert.Equal(expected, destination); } [Fact] public static void CopyTo_StringBuilderWithMultipleChunks() { StringBuilder builder = StringBuilderWithMultipleChunks(); char[] destination = new char[builder.Length]; builder.CopyTo(0, destination, 0, destination.Length); Assert.Equal(s_chunkSplitSource.ToCharArray(), destination); } [Fact] public static void CopyTo_Invalid() { var builder = new StringBuilder("Hello"); AssertExtensions.Throws<ArgumentNullException>("destination", () => builder.CopyTo(0, null, 0, 0)); // Destination is null AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceIndex", () => builder.CopyTo(-1, new char[10], 0, 0)); // Source index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceIndex", () => builder.CopyTo(6, new char[10], 0, 0)); // Source index > builder.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("destinationIndex", () => builder.CopyTo(0, new char[10], -1, 0)); // Destination index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.CopyTo(0, new char[10], 0, -1)); // Count < 0 AssertExtensions.Throws<ArgumentException>(null, () => builder.CopyTo(5, new char[10], 0, 1)); // Source index + count > builder.Length AssertExtensions.Throws<ArgumentException>(null, () => builder.CopyTo(4, new char[10], 0, 2)); // Source index + count > builder.Length AssertExtensions.Throws<ArgumentException>(null, () => builder.CopyTo(0, new char[10], 10, 1)); // Destination index + count > destinationArray.Length AssertExtensions.Throws<ArgumentException>(null, () => builder.CopyTo(0, new char[10], 9, 2)); // Destination index + count > destinationArray.Length } [Fact] public static void EnsureCapacity() { var builder = new StringBuilder(40); builder.EnsureCapacity(20); Assert.True(builder.Capacity >= 20); builder.EnsureCapacity(20000); Assert.True(builder.Capacity >= 20000); // Ensuring a capacity less than the current capacity does not change anything int oldCapacity = builder.Capacity; builder.EnsureCapacity(10); Assert.Equal(oldCapacity, builder.Capacity); } [Fact] public static void EnsureCapacity_InvalidCapacity_ThrowsArgumentOutOfRangeException() { var builder = new StringBuilder("Hello", 10); AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => builder.EnsureCapacity(-1)); // Capacity < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => builder.EnsureCapacity(unchecked(builder.MaxCapacity + 1))); // Capacity > builder.MaxCapacity } public static IEnumerable<object[]> Equals_TestData() { var sb1 = new StringBuilder("Hello"); var sb2 = new StringBuilder("Hello"); var sb3 = new StringBuilder("HelloX"); var sb4 = new StringBuilder(10, 20); var sb5 = new StringBuilder(10, 20); var sb6 = new StringBuilder(10, 20).Append("Hello"); var sb7 = new StringBuilder(10, 20).Append("Hello"); var sb8 = new StringBuilder(10, 20).Append("HelloX"); yield return new object[] { sb1, sb1, true }; yield return new object[] { sb1, sb2, true }; yield return new object[] { sb1, sb3, false }; yield return new object[] { sb4, sb5, true }; yield return new object[] { sb6, sb7, true }; yield return new object[] { sb6, sb8, false }; yield return new object[] { sb1, null, false }; StringBuilder chunkSplitBuilder = StringBuilderWithMultipleChunks(); yield return new object[] { chunkSplitBuilder, StringBuilderWithMultipleChunks(), true }; yield return new object[] { sb1, chunkSplitBuilder, false }; yield return new object[] { chunkSplitBuilder, sb1, false }; yield return new object[] { chunkSplitBuilder, StringBuilderWithMultipleChunks().Append("b"), false }; yield return new object[] { new StringBuilder(), new StringBuilder(), true }; yield return new object[] { new StringBuilder(), new StringBuilder().Clear(), true }; } [Theory] [MemberData(nameof(Equals_TestData))] public static void EqualsTest(StringBuilder sb1, StringBuilder sb2, bool expected) { Assert.Equal(expected, sb1.Equals(sb2)); } [Theory] [InlineData("Hello", 0, (uint)0, "0Hello")] [InlineData("Hello", 3, (uint)123, "Hel123lo")] [InlineData("Hello", 5, (uint)456, "Hello456")] public static void Insert_UInt(string original, int index, uint value, string expected) { var builder = new StringBuilder(original); builder.Insert(index, value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_UInt_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, (uint)1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, (uint)1)); // Index > builder.Length Assert.Throws<OutOfMemoryException>(() => builder.Insert(builder.Length, (uint)1)); // New length > builder.MaxCapacity } [Theory] [InlineData("Hello", 0, true, "TrueHello")] [InlineData("Hello", 3, false, "HelFalselo")] [InlineData("Hello", 5, false, "HelloFalse")] public static void Insert_Bool(string original, int index, bool value, string expected) { var builder = new StringBuilder(original); builder.Insert(index, value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_Bool_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, true)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, true)); // Index > builder.Length Assert.Throws<OutOfMemoryException>(() => builder.Insert(builder.Length, true)); // New length > builder.MaxCapacity } [Theory] [InlineData("Hello", 0, (byte)0, "0Hello")] [InlineData("Hello", 3, (byte)123, "Hel123lo")] [InlineData("Hello", 5, (byte)123, "Hello123")] public static void Insert_Byte(string original, int index, byte value, string expected) { var builder = new StringBuilder(original); builder.Insert(index, value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_Byte_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, (byte)1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, (byte)1)); // Index > builder.Length Assert.Throws<OutOfMemoryException>(() => builder.Insert(builder.Length, (byte)1)); // New length > builder.MaxCapacity } [Theory] [InlineData("Hello", 0, (ulong)0, "0Hello")] [InlineData("Hello", 3, (ulong)123, "Hel123lo")] [InlineData("Hello", 5, (ulong)456, "Hello456")] public static void Insert_ULong(string original, int index, ulong value, string expected) { var builder = new StringBuilder(original); builder.Insert(index, value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_ULong_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, (ulong)1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, (ulong)1)); // Index > builder.Length Assert.Throws<OutOfMemoryException>(() => builder.Insert(builder.Length, (ulong)1)); // New length > builder.MaxCapacity } [Theory] [InlineData("Hello", 0, (ushort)0, "0Hello")] [InlineData("Hello", 3, (ushort)123, "Hel123lo")] [InlineData("Hello", 5, (ushort)456, "Hello456")] public static void Insert_UShort(string original, int index, ushort value, string expected) { var builder = new StringBuilder(original); builder.Insert(index, value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_UShort_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, (ushort)1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, (ushort)1)); // Index > builder.Length Assert.Throws<OutOfMemoryException>(() => builder.Insert(builder.Length, (ushort)1)); // New length > builder.MaxCapacity } [Theory] [InlineData("Hello", 0, '\0', "\0Hello")] [InlineData("Hello", 3, 'a', "Helalo")] [InlineData("Hello", 5, 'b', "Hellob")] public static void Insert_Char(string original, int index, char value, string expected) { var builder = new StringBuilder(original); builder.Insert(index, value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_Char_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, '\0')); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, '\0')); // Index > builder.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("requiredLength", () => builder.Insert(builder.Length, '\0')); // New length > builder.MaxCapacity } public static IEnumerable<object[]> Insert_Float_TestData() { yield return new object[] { "Hello", 0, (float)0, "0Hello" }; yield return new object[] { "Hello", 3, (float)1.23, "Hel1.23lo" }; yield return new object[] { "Hello", 5, (float)-4.56, "Hello-4.56" }; } [Fact] public static void Test_Insert_Float() { using (new ThreadCultureChange(CultureInfo.InvariantCulture)) { foreach (var testdata in Insert_Float_TestData()) { Insert_Float((string)testdata[0], (int)testdata[1], (float)testdata[2], (string)testdata[3]); } } } private static void Insert_Float(string original, int index, float value, string expected) { var builder = new StringBuilder(original); builder.Insert(index, value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_Float_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, (float)1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, (float)1)); // Index > builder.Length Assert.Throws<OutOfMemoryException>(() => builder.Insert(builder.Length, (float)1)); // New length > builder.MaxCapacity } [Theory] [InlineData("Hello", 0, "\0", "\0Hello")] [InlineData("Hello", 3, "abc", "Helabclo")] [InlineData("Hello", 5, "def", "Hellodef")] [InlineData("Hello", 0, "", "Hello")] [InlineData("Hello", 0, null, "Hello")] public static void Insert_Object(string original, int index, object value, string expected) { var builder = new StringBuilder(original); builder.Insert(index, value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_Object_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, new object())); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, new object())); // Index > builder.Length Assert.Throws<OutOfMemoryException>(() => builder.Insert(builder.Length, new object())); // New length > builder.MaxCapacity } [Theory] [InlineData("Hello", 0, (long)0, "0Hello")] [InlineData("Hello", 3, (long)123, "Hel123lo")] [InlineData("Hello", 5, (long)-456, "Hello-456")] public static void Insert_Long(string original, int index, long value, string expected) { var builder = new StringBuilder(original); builder.Insert(index, value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_Long_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, (long)1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, (long)1)); // Index > builder.Length Assert.Throws<OutOfMemoryException>(() => builder.Insert(builder.Length, (long)1)); // New length > builder.MaxCapacity } [Theory] [InlineData("Hello", 0, 0, "0Hello")] [InlineData("Hello", 3, 123, "Hel123lo")] [InlineData("Hello", 5, -456, "Hello-456")] public static void Insert_Int(string original, int index, int value, string expected) { var builder = new StringBuilder(original); builder.Insert(index, value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_Int_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, 1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, 1)); // Index > builder.Length Assert.Throws<OutOfMemoryException>(() => builder.Insert(builder.Length, 1)); // New length > builder.MaxCapacity } [Theory] [InlineData("Hello", 0, (short)0, "0Hello")] [InlineData("Hello", 3, (short)123, "Hel123lo")] [InlineData("Hello", 5, (short)-456, "Hello-456")] public static void Insert_Short(string original, int index, short value, string expected) { var builder = new StringBuilder(original); builder.Insert(index, value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_Short_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, (short)1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, (short)1)); // Index > builder.Length Assert.Throws<OutOfMemoryException>(() => builder.Insert(builder.Length, (short)1)); // New length > builder.MaxCapacity } public static IEnumerable<object[]> Insert_Double_TestData() { yield return new object[] { "Hello", 0, (double)0, "0Hello" }; yield return new object[] { "Hello", 3, 1.23, "Hel1.23lo" }; yield return new object[] { "Hello", 5, -4.56, "Hello-4.56" }; } [Fact] public static void Test_Insert_Double() { using (new ThreadCultureChange(CultureInfo.InvariantCulture)) { foreach (var testdata in Insert_Double_TestData()) { Insert_Double((string)testdata[0], (int)testdata[1], (double)testdata[2], (string)testdata[3]); } } } private static void Insert_Double(string original, int index, double value, string expected) { var builder = new StringBuilder(original); builder.Insert(index, value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_Double_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, (double)1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, (double)1)); // Index > builder.Length Assert.Throws<OutOfMemoryException>(() => builder.Insert(builder.Length, (double)1)); // New length > builder.MaxCapacity } public static IEnumerable<object[]> Test_Insert_Decimal_TestData() { yield return new object[] { "Hello", 0, (double)0, "0Hello" }; yield return new object[] { "Hello", 3, 1.23, "Hel1.23lo" }; yield return new object[] { "Hello", 5, -4.56, "Hello-4.56" }; } [Fact] public static void Test_Insert_Decimal() { using (new ThreadCultureChange(CultureInfo.InvariantCulture)) { foreach (var testdata in Test_Insert_Decimal_TestData()) { Insert_Decimal((string)testdata[0], (int)testdata[1], (double)testdata[2], (string)testdata[3]); } } } private static void Insert_Decimal(string original, int index, double doubleValue, string expected) { var builder = new StringBuilder(original); builder.Insert(index, new decimal(doubleValue)); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_Decimal_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, (decimal)1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, (decimal)1)); // Index > builder.Length Assert.Throws<OutOfMemoryException>(() => builder.Insert(builder.Length, (decimal)1)); // New length > builder.MaxCapacity } [Theory] [InlineData("Hello", 0, (sbyte)0, "0Hello")] [InlineData("Hello", 3, (sbyte)123, "Hel123lo")] [InlineData("Hello", 5, (sbyte)-123, "Hello-123")] public static void Insert_SByte(string original, int index, sbyte value, string expected) { var builder = new StringBuilder(original); builder.Insert(index, value); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_SByte_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, (sbyte)1)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, (sbyte)1)); // Index > builder.Length Assert.Throws<OutOfMemoryException>(() => builder.Insert(builder.Length, (sbyte)1)); // New length > builder.MaxCapacity } [Theory] [InlineData("Hello", 0, "\0", 0, "Hello")] [InlineData("Hello", 0, "\0", 1, "\0Hello")] [InlineData("Hello", 3, "abc", 1, "Helabclo")] [InlineData("Hello", 5, "def", 1, "Hellodef")] [InlineData("Hello", 0, "", 1, "Hello")] [InlineData("Hello", 0, null, 1, "Hello")] [InlineData("Hello", 3, "abc", 2, "Helabcabclo")] [InlineData("Hello", 5, "def", 2, "Hellodefdef")] public static void Insert_String_Count(string original, int index, string value, int count, string expected) { StringBuilder builder; if (count == 1) { // Use Insert(int, string) builder = new StringBuilder(original); builder.Insert(index, value); Assert.Equal(expected, builder.ToString()); } // Use Insert(int, string, int) builder = new StringBuilder(original); builder.Insert(index, value, count); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_String_Count_Invalid() { var builder = new StringBuilder(0, 6); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, "")); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, "", 0)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, "")); // Index > builder.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, "", 0)); // Index > builder.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.Insert(0, "", -1)); // Count < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("requiredLength", () => builder.Insert(builder.Length, "aa")); // New length > builder.MaxCapacity Assert.Throws<OutOfMemoryException>(() => builder.Insert(builder.Length, "aa", 1)); // New length > builder.MaxCapacity Assert.Throws<OutOfMemoryException>(() => builder.Insert(builder.Length, "a", 2)); // New length > builder.MaxCapacity } [Theory] [InlineData("Hello", 0, new char[] { '\0' }, 0, 1, "\0Hello")] [InlineData("Hello", 3, new char[] { 'a', 'b', 'c' }, 0, 1, "Helalo")] [InlineData("Hello", 3, new char[] { 'a', 'b', 'c' }, 0, 3, "Helabclo")] [InlineData("Hello", 5, new char[] { 'd', 'e', 'f' }, 0, 1, "Hellod")] [InlineData("Hello", 5, new char[] { 'd', 'e', 'f' }, 0, 3, "Hellodef")] [InlineData("Hello", 0, new char[0], 0, 0, "Hello")] [InlineData("Hello", 0, null, 0, 0, "Hello")] [InlineData("Hello", 3, new char[] { 'a', 'b', 'c' }, 1, 1, "Helblo")] [InlineData("Hello", 3, new char[] { 'a', 'b', 'c' }, 1, 2, "Helbclo")] [InlineData("Hello", 3, new char[] { 'a', 'b', 'c' }, 0, 2, "Helablo")] public static void Insert_CharArray(string original, int index, char[] value, int startIndex, int charCount, string expected) { StringBuilder builder; if (startIndex == 0 && charCount == (value?.Length ?? 0)) { // Use Insert(int, char[]) builder = new StringBuilder(original); builder.Insert(index, value); Assert.Equal(expected, builder.ToString()); } // Use Insert(int, char[], int, int) builder = new StringBuilder(original); builder.Insert(index, value, startIndex, charCount); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_CharArray_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, new char[1])); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, new char[0], 0, 0)); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, new char[1])); // Index > builder.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, new char[0], 0, 0)); // Index > builder.Length Assert.Throws<ArgumentNullException>(() => builder.Insert(0, null, 1, 1)); // Value is null (startIndex and count are not zero) AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => builder.Insert(0, new char[0], -1, 0)); // Start index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => builder.Insert(0, new char[3], 4, 0)); // Start index + char count > value.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => builder.Insert(0, new char[3], 3, 1)); // Start index + char count > value.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => builder.Insert(0, new char[3], 2, 2)); // Start index + char count > value.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("requiredLength", () => builder.Insert(builder.Length, new char[1])); // New length > builder.MaxCapacity AssertExtensions.Throws<ArgumentOutOfRangeException>("requiredLength", () => builder.Insert(builder.Length, new char[] { 'a' }, 0, 1)); // New length > builder.MaxCapacity } [Fact] public static void Insert_CharArray_InvalidCount() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => builder.Insert(0, new char[0], 0, -1)); // Char count < 0 } [Fact] public static void Insert_CharArray_InvalidCharCount() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("charCount", () => builder.Insert(0, new char[0], 0, -1)); // Char count < 0 } [Theory] [InlineData("", 0, 0, "")] [InlineData("Hello", 0, 5, "")] [InlineData("Hello", 1, 3, "Ho")] [InlineData("Hello", 1, 4, "H")] [InlineData("Hello", 1, 0, "Hello")] [InlineData("Hello", 5, 0, "Hello")] public static void Remove(string value, int startIndex, int length, string expected) { var builder = new StringBuilder(value); builder.Remove(startIndex, length); Assert.Equal(expected, builder.ToString()); } [Theory] [InlineData(1, 29, "a")] [InlineData(0, 29, "a")] [InlineData(20, 10, "aaaaaaaaaaaaaaaaaaaa")] [InlineData(0, 15, "aaaaaaaaaaaaaaa")] public static void Remove_StringBuilderWithMultipleChunks(int startIndex, int count, string expected) { StringBuilder builder = StringBuilderWithMultipleChunks(); builder.Remove(startIndex, count); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Remove_Invalid() { var builder = new StringBuilder("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => builder.Remove(-1, 0)); // Start index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => builder.Remove(0, -1)); // Length < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => builder.Remove(6, 0)); // Start index + length > 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => builder.Remove(5, 1)); // Start index + length > 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => builder.Remove(4, 2)); // Start index + length > 0 } [Theory] [InlineData("", 'a', '!', 0, 0, "")] [InlineData("aaaabbbbccccdddd", 'a', '!', 0, 16, "!!!!bbbbccccdddd")] [InlineData("aaaabbbbccccdddd", 'a', '!', 0, 4, "!!!!bbbbccccdddd")] [InlineData("aaaabbbbccccdddd", 'a', '!', 2, 3, "aa!!bbbbccccdddd")] [InlineData("aaaabbbbccccdddd", 'a', '!', 4, 1, "aaaabbbbccccdddd")] [InlineData("aaaabbbbccccdddd", 'b', '!', 0, 0, "aaaabbbbccccdddd")] [InlineData("aaaabbbbccccdddd", 'a', '!', 16, 0, "aaaabbbbccccdddd")] [InlineData("aaaabbbbccccdddd", 'e', '!', 0, 16, "aaaabbbbccccdddd")] public static void Replace_Char(string value, char oldChar, char newChar, int startIndex, int count, string expected) { StringBuilder builder; if (startIndex == 0 && count == value.Length) { // Use Replace(char, char) builder = new StringBuilder(value); builder.Replace(oldChar, newChar); Assert.Equal(expected, builder.ToString()); } // Use Replace(char, char, int, int) builder = new StringBuilder(value); builder.Replace(oldChar, newChar, startIndex, count); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Replace_Char_StringBuilderWithMultipleChunks() { StringBuilder builder = StringBuilderWithMultipleChunks(); builder.Replace('a', 'b', 0, builder.Length); Assert.Equal(new string('b', builder.Length), builder.ToString()); } [Fact] public static void Replace_Char_Invalid() { var builder = new StringBuilder("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => builder.Replace('a', 'b', -1, 0)); // Start index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.Replace('a', 'b', 0, -1)); // Count < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => builder.Replace('a', 'b', 6, 0)); // Count + start index > builder.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.Replace('a', 'b', 5, 1)); // Count + start index > builder.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.Replace('a', 'b', 4, 2)); // Count + start index > builder.Length } [Theory] [InlineData("", "a", "!", 0, 0, "")] [InlineData("aaaabbbbccccdddd", "a", "!", 0, 16, "!!!!bbbbccccdddd")] [InlineData("aaaabbbbccccdddd", "a", "!", 2, 3, "aa!!bbbbccccdddd")] [InlineData("aaaabbbbccccdddd", "a", "!", 4, 1, "aaaabbbbccccdddd")] [InlineData("aaaabbbbccccdddd", "aab", "!", 2, 2, "aaaabbbbccccdddd")] [InlineData("aaaabbbbccccdddd", "aab", "!", 2, 3, "aa!bbbccccdddd")] [InlineData("aaaabbbbccccdddd", "aa", "!", 0, 16, "!!bbbbccccdddd")] [InlineData("aaaabbbbccccdddd", "aa", "$!", 0, 16, "$!$!bbbbccccdddd")] [InlineData("aaaabbbbccccdddd", "aa", "$!$", 0, 16, "$!$$!$bbbbccccdddd")] [InlineData("aaaabbbbccccdddd", "aaaa", "!", 0, 16, "!bbbbccccdddd")] [InlineData("aaaabbbbccccdddd", "aaaa", "$!", 0, 16, "$!bbbbccccdddd")] [InlineData("aaaabbbbccccdddd", "a", "", 0, 16, "bbbbccccdddd")] [InlineData("aaaabbbbccccdddd", "b", null, 0, 16, "aaaaccccdddd")] [InlineData("aaaabbbbccccdddd", "aaaabbbbccccdddd", "", 0, 16, "")] [InlineData("aaaabbbbccccdddd", "aaaabbbbccccdddd", "", 16, 0, "aaaabbbbccccdddd")] [InlineData("aaaabbbbccccdddd", "aaaabbbbccccdddde", "", 0, 16, "aaaabbbbccccdddd")] [InlineData("aaaaaaaaaaaaaaaa", "a", "b", 0, 16, "bbbbbbbbbbbbbbbb")] public static void Replace_String(string value, string oldValue, string newValue, int startIndex, int count, string expected) { StringBuilder builder; if (startIndex == 0 && count == value.Length) { // Use Replace(string, string) builder = new StringBuilder(value); builder.Replace(oldValue, newValue); Assert.Equal(expected, builder.ToString()); } // Use Replace(string, string, int, int) builder = new StringBuilder(value); builder.Replace(oldValue, newValue, startIndex, count); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Replace_String_StringBuilderWithMultipleChunks() { StringBuilder builder = StringBuilderWithMultipleChunks(); builder.Replace("a", "b", builder.Length - 10, 10); Assert.Equal(new string('a', builder.Length - 10) + new string('b', 10), builder.ToString()); } [Fact] public static void Replace_String_StringBuilderWithMultipleChunks_WholeString() { StringBuilder builder = StringBuilderWithMultipleChunks(); builder.Replace(builder.ToString(), ""); Assert.Same(string.Empty, builder.ToString()); } [Fact] public static void Replace_String_StringBuilderWithMultipleChunks_LongString() { StringBuilder builder = StringBuilderWithMultipleChunks(); builder.Replace(builder.ToString() + "b", ""); Assert.Equal(s_chunkSplitSource, builder.ToString()); } [Fact] public static void Replace_String_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentNullException>("oldValue", () => builder.Replace(null, "")); // Old value is null AssertExtensions.Throws<ArgumentNullException>("oldValue", () => builder.Replace(null, "a", 0, 0)); // Old value is null AssertExtensions.Throws<ArgumentException>("oldValue", () => builder.Replace("", "a")); // Old value is empty AssertExtensions.Throws<ArgumentException>("oldValue", () => builder.Replace("", "a", 0, 0)); // Old value is empty AssertExtensions.Throws<ArgumentOutOfRangeException>("requiredLength", () => builder.Replace("o", "oo")); // New length > builder.MaxCapacity AssertExtensions.Throws<ArgumentOutOfRangeException>("requiredLength", () => builder.Replace("o", "oo", 0, 5)); // New length > builder.MaxCapacity AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => builder.Replace("a", "b", -1, 0)); // Start index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.Replace("a", "b", 0, -1)); // Count < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => builder.Replace("a", "b", 6, 0)); // Count + start index > builder.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.Replace("a", "b", 5, 1)); // Count + start index > builder.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.Replace("a", "b", 4, 2)); // Count + start index > builder.Length } [Theory] [InlineData("Hello", 0, 5, "Hello")] [InlineData("Hello", 2, 3, "llo")] [InlineData("Hello", 2, 2, "ll")] [InlineData("Hello", 5, 0, "")] [InlineData("Hello", 4, 0, "")] [InlineData("Hello", 0, 0, "")] [InlineData("", 0, 0, "")] public static void ToStringTest(string value, int startIndex, int length, string expected) { var builder = new StringBuilder(value); if (startIndex == 0 && length == value.Length) { Assert.Equal(expected, builder.ToString()); } Assert.Equal(expected, builder.ToString(startIndex, length)); } [Fact] public static void ToString_StringBuilderWithMultipleChunks() { StringBuilder builder = StringBuilderWithMultipleChunks(); Assert.Equal(s_chunkSplitSource, builder.ToString()); Assert.Equal(s_chunkSplitSource, builder.ToString(0, builder.Length)); Assert.Equal("a", builder.ToString(0, 1)); Assert.Equal(string.Empty, builder.ToString(builder.Length - 1, 0)); } [Fact] public static void ToString_Invalid() { var builder = new StringBuilder("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => builder.ToString(-1, 0)); // Start index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => builder.ToString(0, -1)); // Length < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("startIndex", () => builder.ToString(6, 0)); // Length + start index > builder.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => builder.ToString(5, 1)); // Length + start index > builder.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => builder.ToString(4, 2)); // Length + start index > builder.Length } public class CustomFormatter : ICustomFormatter, IFormatProvider { public string Format(string format, object arg, IFormatProvider formatProvider) => "abc"; public object GetFormat(Type formatType) => this; } [Fact] public static void AppendJoin_NullValues_ThrowsArgumentNullException() { AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin('|', (object[])null)); AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin('|', (IEnumerable<object>)null)); AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin('|', (string[])null)); AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin("|", (object[])null)); AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin("|", (IEnumerable<object>)null)); AssertExtensions.Throws<ArgumentNullException>("values", () => new StringBuilder().AppendJoin("|", (string[])null)); } [Theory] [InlineData(new object[0], "")] [InlineData(new object[] { null }, "")] [InlineData(new object[] { 10 }, "10")] [InlineData(new object[] { null, null }, "|")] [InlineData(new object[] { null, 20 }, "|20")] [InlineData(new object[] { 10, null }, "10|")] [InlineData(new object[] { 10, 20 }, "10|20")] [InlineData(new object[] { null, null, null }, "||")] [InlineData(new object[] { null, null, 30 }, "||30")] [InlineData(new object[] { null, 20, null }, "|20|")] [InlineData(new object[] { null, 20, 30 }, "|20|30")] [InlineData(new object[] { 10, null, null }, "10||")] [InlineData(new object[] { 10, null, 30 }, "10||30")] [InlineData(new object[] { 10, 20, null }, "10|20|")] [InlineData(new object[] { 10, 20, 30 }, "10|20|30")] [InlineData(new object[] { "" }, "")] [InlineData(new object[] { "", "" }, "|")] public static void AppendJoin_TestValues(object[] values, string expected) { var stringValues = Array.ConvertAll(values, _ => _?.ToString()); var enumerable = values.Select(_ => _); Assert.Equal(expected, new StringBuilder().AppendJoin('|', values).ToString()); Assert.Equal(expected, new StringBuilder().AppendJoin('|', enumerable).ToString()); Assert.Equal(expected, new StringBuilder().AppendJoin('|', stringValues).ToString()); Assert.Equal(expected, new StringBuilder().AppendJoin("|", values).ToString()); Assert.Equal(expected, new StringBuilder().AppendJoin("|", enumerable).ToString()); Assert.Equal(expected, new StringBuilder().AppendJoin("|", stringValues).ToString()); } [Fact] public static void AppendJoin_NullToStringValues() { AppendJoin_TestValues(new object[] { new NullToStringObject() }, ""); AppendJoin_TestValues(new object[] { new NullToStringObject(), new NullToStringObject() }, "|"); } private sealed class NullToStringObject { public override string ToString() => null; } [Theory] [InlineData(null, "123")] [InlineData("", "123")] [InlineData(" ", "1 2 3")] [InlineData(", ", "1, 2, 3")] public static void AppendJoin_TestStringSeparators(string separator, string expected) { Assert.Equal(expected, new StringBuilder().AppendJoin(separator, new object[] { 1, 2, 3 }).ToString()); Assert.Equal(expected, new StringBuilder().AppendJoin(separator, Enumerable.Range(1, 3)).ToString()); Assert.Equal(expected, new StringBuilder().AppendJoin(separator, new string[] { "1", "2", "3" }).ToString()); } private static StringBuilder CreateBuilderWithNoSpareCapacity() { return new StringBuilder(0, 5).Append("Hello"); } [Theory] [InlineData(null, new object[] { null, null })] [InlineData("", new object[] { "", "" })] [InlineData(" ", new object[] { })] [InlineData(", ", new object[] { "" })] public static void AppendJoin_NoValues_NoSpareCapacity_DoesNotThrow(string separator, object[] values) { var stringValues = Array.ConvertAll(values, _ => _?.ToString()); var enumerable = values.Select(_ => _); if (separator?.Length == 1) { CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], values); CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], enumerable); CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], stringValues); } CreateBuilderWithNoSpareCapacity().AppendJoin(separator, values); CreateBuilderWithNoSpareCapacity().AppendJoin(separator, enumerable); CreateBuilderWithNoSpareCapacity().AppendJoin(separator, stringValues); } [Theory] [InlineData(null, new object[] { " " })] [InlineData(" ", new object[] { " " })] [InlineData(" ", new object[] { null, null })] [InlineData(" ", new object[] { "", "" })] public static void AppendJoin_NoSpareCapacity_ThrowsArgumentOutOfRangeException(string separator, object[] values) { var builder = new StringBuilder(0, 5); builder.Append("Hello"); var stringValues = Array.ConvertAll(values, _ => _?.ToString()); var enumerable = values.Select(_ => _); if (separator?.Length == 1) { AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], values)); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], enumerable)); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator[0], stringValues)); } AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator, values)); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator, enumerable)); AssertExtensions.Throws<ArgumentOutOfRangeException>(s_noCapacityParamName, () => CreateBuilderWithNoSpareCapacity().AppendJoin(separator, stringValues)); } [Theory] [InlineData("Hello", new char[] { 'a' }, "Helloa")] [InlineData("Hello", new char[] { 'b', 'c', 'd' }, "Hellobcd")] [InlineData("Hello", new char[] { 'b', '\0', 'd' }, "Hellob\0d")] [InlineData("", new char[] { 'e', 'f', 'g' }, "efg")] [InlineData("Hello", new char[0], "Hello")] public static void Append_CharSpan(string original, char[] value, string expected) { var builder = new StringBuilder(original); builder.Append(new ReadOnlySpan<char>(value)); Assert.Equal(expected, builder.ToString()); } [Theory] [InlineData("Hello", new char[] { 'a' }, "Helloa")] [InlineData("Hello", new char[] { 'b', 'c', 'd' }, "Hellobcd")] [InlineData("Hello", new char[] { 'b', '\0', 'd' }, "Hellob\0d")] [InlineData("", new char[] { 'e', 'f', 'g' }, "efg")] [InlineData("Hello", new char[0], "Hello")] public static void Append_CharMemory(string original, char[] value, string expected) { var builder = new StringBuilder(original); builder.Append(value.AsMemory()); Assert.Equal(expected, builder.ToString()); } [Theory] [InlineData(1)] [InlineData(10000)] public static void Clear_AppendAndInsertBeforeClearManyTimes_CapacityStaysWithinRange(int times) { var builder = new StringBuilder(); var originalCapacity = builder.Capacity; var s = new string(' ', 10); int oldLength = 0; for (int i = 0; i < times; i++) { builder.Append(s); builder.Append(s); builder.Append(s); builder.Insert(0, s); builder.Insert(0, s); oldLength = builder.Length; builder.Clear(); } Assert.InRange(builder.Capacity, 1, oldLength * 1.2); } [Fact] public static void Clear_InitialCapacityMuchLargerThanLength_CapacityReducedToInitialCapacity() { var builder = new StringBuilder(100); var initialCapacity = builder.Capacity; builder.Append(new string('a', 40)); builder.Insert(0, new string('a', 10)); builder.Insert(0, new string('a', 10)); builder.Insert(0, new string('a', 10)); var oldCapacity = builder.Capacity; var oldLength = builder.Length; builder.Clear(); Assert.NotEqual(oldCapacity, builder.Capacity); Assert.Equal(initialCapacity, builder.Capacity); Assert.NotInRange(builder.Capacity, 1, oldLength * 1.2); Assert.InRange(builder.Capacity, 1, Math.Max(initialCapacity, oldLength * 1.2)); } [Fact] public static void Clear_StringBuilderHasTwoChunks_OneChunkIsEmpty_ClearReducesCapacity() { var sb = new StringBuilder(string.Empty); int initialCapacity = sb.Capacity; for (int i = 0; i < initialCapacity; i++) { sb.Append('a'); } sb.Insert(0, 'a'); while (sb.Length > 1) { sb.Remove(1, 1); } int oldCapacity = sb.Capacity; sb.Clear(); Assert.Equal(oldCapacity - 1, sb.Capacity); Assert.Equal(initialCapacity, sb.Capacity); } [Theory] [InlineData("Hello", 0, new char[] { '\0', '\0', '\0', '\0', '\0' }, 5, new char[] { 'H', 'e', 'l', 'l', 'o' })] [InlineData("Hello", 0, new char[] { '\0', '\0', '\0', '\0' }, 4, new char[] { 'H', 'e', 'l', 'l' })] [InlineData("Hello", 1, new char[] { '\0', '\0', '\0', '\0', '\0' }, 4, new char[] { 'e', 'l', 'l', 'o', '\0' })] public static void CopyTo_CharSpan(string value, int sourceIndex, char[] destination, int count, char[] expected) { var builder = new StringBuilder(value); builder.CopyTo(sourceIndex, new Span<char>(destination), count); Assert.Equal(expected, destination); } [Fact] public static void CopyTo_CharSpan_StringBuilderWithMultipleChunks() { StringBuilder builder = StringBuilderWithMultipleChunks(); char[] destination = new char[builder.Length]; builder.CopyTo(0, new Span<char>(destination), destination.Length); Assert.Equal(s_chunkSplitSource.ToCharArray(), destination); } [Fact] public static void CopyTo_CharSpan_Invalid() { var builder = new StringBuilder("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceIndex", () => builder.CopyTo(-1, new Span<char>(new char[10]), 0)); // Source index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("sourceIndex", () => builder.CopyTo(6, new Span<char>(new char[10]), 0)); // Source index > builder.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.CopyTo(0, new Span<char>(new char[10]), -1)); // Count < 0 AssertExtensions.Throws<ArgumentException>(null, () => builder.CopyTo(5, new Span<char>(new char[10]), 1)); // Source index + count > builder.Length AssertExtensions.Throws<ArgumentException>(null, () => builder.CopyTo(4, new Span<char>(new char[10]), 2)); // Source index + count > builder.Length AssertExtensions.Throws<ArgumentException>(null, () => builder.CopyTo(0, new Span<char>(new char[10]), 11)); // count > destinationArray.Length } [Theory] [InlineData("Hello", 0, new char[] { '\0' }, "\0Hello")] [InlineData("Hello", 3, new char[] { 'a', 'b', 'c' }, "Helabclo")] [InlineData("Hello", 5, new char[] { 'd', 'e', 'f' }, "Hellodef")] [InlineData("Hello", 0, new char[0], "Hello")] public static void Insert_CharSpan(string original, int index, char[] value, string expected) { var builder = new StringBuilder(original); builder.Insert(index, new ReadOnlySpan<char>(value)); Assert.Equal(expected, builder.ToString()); } [Fact] public static void Insert_CharSpan_Invalid() { var builder = new StringBuilder(0, 5); builder.Append("Hello"); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, new ReadOnlySpan<char>(new char[0]))); // Index < 0 AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Length + 1, new ReadOnlySpan<char>(new char[0]))); // Index > builder.Length AssertExtensions.Throws<ArgumentOutOfRangeException>("requiredLength", () => builder.Insert(builder.Length, new ReadOnlySpan<char>(new char[1]))); // New length > builder.MaxCapacity } public static IEnumerable<object[]> Append_StringBuilder_TestData() { string mediumString = new string('a', 30); string largeString = new string('b', 1000); var sb1 = new StringBuilder("Hello"); var sb2 = new StringBuilder("one"); var sb3 = new StringBuilder(20).Append(mediumString); yield return new object[] { new StringBuilder("Hello"), sb1, "HelloHello" }; yield return new object[] { new StringBuilder("Hello"), sb2, "Helloone" }; yield return new object[] { new StringBuilder("Hello"), new StringBuilder(), "Hello" }; yield return new object[] { new StringBuilder("one"), sb3, "one" + mediumString }; yield return new object[] { new StringBuilder(20).Append(mediumString), sb3, mediumString + mediumString }; yield return new object[] { new StringBuilder(10).Append(mediumString), sb3, mediumString + mediumString }; yield return new object[] { new StringBuilder(20).Append(largeString), sb3, largeString + mediumString }; yield return new object[] { new StringBuilder(10).Append(largeString), sb3, largeString + mediumString }; yield return new object[] { new StringBuilder(10), sb3, mediumString }; yield return new object[] { new StringBuilder(30), sb3, mediumString }; yield return new object[] { new StringBuilder(10), new StringBuilder(20), string.Empty}; yield return new object[] { sb1, null, "Hello" }; yield return new object[] { sb1, sb1, "HelloHello" }; } [Theory] [MemberData(nameof(Append_StringBuilder_TestData))] public static void Append_StringBuilder(StringBuilder s1, StringBuilder s2, string s) { Assert.Equal(s, s1.Append(s2).ToString()); } public static IEnumerable<object[]> Append_StringBuilder_Substring_TestData() { string mediumString = new string('a', 30); string largeString = new string('b', 1000); var sb1 = new StringBuilder("Hello"); var sb2 = new StringBuilder("one"); var sb3 = new StringBuilder(20).Append(mediumString); yield return new object[] { new StringBuilder("Hello"), sb1, 0, 5, "HelloHello" }; yield return new object[] { new StringBuilder("Hello"), sb1, 0, 0, "Hello" }; yield return new object[] { new StringBuilder("Hello"), sb1, 2, 3, "Hellollo" }; yield return new object[] { new StringBuilder("Hello"), sb1, 2, 2, "Helloll" }; yield return new object[] { new StringBuilder("Hello"), sb1, 2, 0, "Hello" }; yield return new object[] { new StringBuilder("Hello"), new StringBuilder(), 0, 0, "Hello" }; yield return new object[] { new StringBuilder("Hello"), null, 0, 0, "Hello" }; yield return new object[] { new StringBuilder(), new StringBuilder("Hello"), 2, 3, "llo" }; yield return new object[] { new StringBuilder("Hello"), sb2, 0, 3, "Helloone" }; yield return new object[] { new StringBuilder("one"), sb3, 5, 25, "one" + new string('a', 25) }; yield return new object[] { new StringBuilder("one"), sb3, 5, 20, "one" + new string('a', 20) }; yield return new object[] { new StringBuilder("one"), sb3, 10, 10, "one" + new string('a', 10) }; yield return new object[] { new StringBuilder(20).Append(mediumString), sb3, 20, 10, new string('a', 40) }; yield return new object[] { new StringBuilder(10).Append(mediumString), sb3, 10, 10, new string('a', 40) }; yield return new object[] { new StringBuilder(20).Append(largeString), new StringBuilder(20).Append(largeString), 100, 50, largeString + new string('b', 50) }; yield return new object[] { new StringBuilder(10).Append(mediumString), new StringBuilder(20).Append(largeString), 20, 10, mediumString + new string('b', 10) }; yield return new object[] { new StringBuilder(10).Append(mediumString), new StringBuilder(20).Append(largeString), 100, 50, mediumString + new string('b', 50) }; yield return new object[] { sb1, sb1, 2, 3, "Hellollo" }; yield return new object[] { sb2, sb2, 2, 0, "one" }; } [Theory] [MemberData(nameof(Append_StringBuilder_Substring_TestData))] public static void Append_StringBuilder_Substring(StringBuilder s1, StringBuilder s2, int startIndex, int count, string s) { Assert.Equal(s, s1.Append(s2, startIndex, count).ToString()); } [Fact] public static void Append_StringBuilder_InvalidInput() { StringBuilder sb = new StringBuilder(5, 5).Append("Hello"); Assert.Throws<ArgumentOutOfRangeException>(() => sb.Append(sb, -1, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => sb.Append(sb, 0, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => sb.Append(sb, 4, 5)); Assert.Throws<ArgumentNullException>(() => sb.Append( (StringBuilder)null, 2, 2)); Assert.Throws<ArgumentNullException>(() => sb.Append((StringBuilder)null, 2, 3)); Assert.Throws<ArgumentOutOfRangeException>(() => new StringBuilder(3, 6).Append("Hello").Append(sb)); Assert.Throws<ArgumentOutOfRangeException>(() => new StringBuilder(3, 6).Append("Hello").Append("Hello")); Assert.Throws<ArgumentOutOfRangeException>(() => sb.Append(sb)); } public static IEnumerable<object[]> Equals_String_TestData() { string mediumString = new string('a', 30); string largeString = new string('a', 1000); string extraLargeString = new string('a', 41000); // 8000 is the maximum chunk size var sb1 = new StringBuilder("Hello"); var sb2 = new StringBuilder(20).Append(mediumString); var sb3 = new StringBuilder(20).Append(largeString); var sb4 = new StringBuilder(20).Append(extraLargeString); yield return new object[] { sb1, "Hello", true }; yield return new object[] { sb1, "Hel", false }; yield return new object[] { sb1, "Hellz", false }; yield return new object[] { sb1, "Helloz", false }; yield return new object[] { sb1, "", false }; yield return new object[] { new StringBuilder(), "", true }; yield return new object[] { new StringBuilder(), "Hello", false }; yield return new object[] { sb2, mediumString, true }; yield return new object[] { sb2, "H", false }; yield return new object[] { sb3, largeString, true }; yield return new object[] { sb3, "H", false }; yield return new object[] { sb3, new string('a', 999) + 'b', false }; yield return new object[] { sb4, extraLargeString, true }; yield return new object[] { sb4, "H", false }; } [Theory] [MemberData(nameof(Equals_String_TestData))] public static void Equals_String(StringBuilder sb1, string value, bool expected) { Assert.Equal(expected, sb1.Equals(value.AsSpan())); } [Fact] public static void ForEach() { // Test on a variety of lengths, at least up to the point of 9 8K chunks = 72K because this is where // we start using a different technique for creating the ChunkEnumerator. 200 * 500 = 100K which hits this. for (int i = 0; i < 200; i++) { StringBuilder inBuilder = new StringBuilder(); for (int j = 0; j < i; j++) { // Make some unique strings that are at least 500 bytes long. inBuilder.Append(j); inBuilder.Append("_abcdefghijklmnopqrstuvwxyz01234567890__Abcdefghijklmnopqrstuvwxyz01234567890__ABcdefghijklmnopqrstuvwxyz01_"); inBuilder.Append("_abcdefghijklmnopqrstuvwxyz01234567890__Abcdefghijklmnopqrstuvwxyz01234567890__ABcdefghijklmnopqrstuvwxyz0123_"); inBuilder.Append("_abcdefghijklmnopqrstuvwxyz01234567890__Abcdefghijklmnopqrstuvwxyz01234567890__ABcdefghijklmnopqrstuvwxyz012345_"); inBuilder.Append("_abcdefghijklmnopqrstuvwxyz01234567890__Abcdefghijklmnopqrstuvwxyz01234567890__ABcdefghijklmnopqrstuvwxyz012345678_"); inBuilder.Append("_abcdefghijklmnopqrstuvwxyz01234567890__Abcdefghijklmnopqrstuvwxyz01234567890__ABcdefghijklmnopqrstuvwxyz01234567890_"); } // Copy the string out (not using StringBuilder). string outStr = ""; foreach (ReadOnlyMemory<char> chunk in inBuilder.GetChunks()) outStr += new string(chunk.Span); // The strings formed by concatenating the chunks should be the same as the value in the StringBuilder. Assert.Equal(outStr, inBuilder.ToString()); } } [Fact] public static void EqualsIgnoresCapacity() { var sb1 = new StringBuilder(5); var sb2 = new StringBuilder(10); Assert.True(sb1.Equals(sb2)); sb1.Append("12345"); sb2.Append("12345"); Assert.True(sb1.Equals(sb2)); } [Fact] public static void EqualsIgnoresMaxCapacity() { var sb1 = new StringBuilder(5, 5); var sb2 = new StringBuilder(5, 10); Assert.True(sb1.Equals(sb2)); sb1.Append("12345"); sb2.Append("12345"); Assert.True(sb1.Equals(sb2)); } [ActiveIssue("https://github.com/dotnet/runtime/issues/40625")] // Hangs expanding the SB [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public static unsafe void FailureOnLargeString() { RemoteExecutor.Invoke(() => // Uses lots of memory { AssertExtensions.ThrowsAny<ArgumentOutOfRangeException, OutOfMemoryException>(() => { StringBuilder sb = new StringBuilder(); sb.Append(new char[2_000_000_000]); sb.Length--; string s = new string('x', 500_000_000); sb.Append(s); // This should throw, not AV }); return RemoteExecutor.SuccessExitCode; // workaround https://github.com/dotnet/arcade/issues/5865 }).Dispose(); } } }
49.59583
211
0.588036
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Runtime/tests/System/Text/StringBuilderTests.cs
111,789
C#
#region copyright // <copyright file="IConsoleWriter.cs" company="Christopher McNeely"> // The MIT License (MIT) // Copyright (c) Christopher McNeely // Permission is hereby granted, free of charge, to any person obtaining a copy of this software // and associated documentation files (the "Software"), to deal in the Software without restriction, // including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT // NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. // IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE // SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // </copyright> #endregion namespace Evands.Pellucid.Terminal { /// <summary> /// Defines the requirements for an object that allows writing to a console of some sort. /// <para>Typically this will be the default <see cref="CrestronConsoleWriter"/>, but additional nodes can be /// created for writing to something like an open network port, for example.</para> /// </summary> public interface IConsoleWriter { /// <summary> /// Writes a message to the console, without a line termination. /// </summary> /// <param name="message">The message to write to the console.</param> /// <param name="args">Optional array of arguments to format the message using.</param> void Write(string message, params object[] args); /// <summary> /// Writes a message to the console, without a line termination. /// </summary> /// <param name="message">The message to write to the console.</param> void Write(string message); /// <summary> /// Writes a message to the console, with a line termination. /// </summary> /// <param name="message">The message to write to the console.</param> /// <param name="args">Optional array of arguments to format the message using.</param> void WriteLine(string message, params object[] args); /// <summary> /// Writes a message to the console, with a line termination. /// </summary> /// <param name="message">The message to write to the console.</param> void WriteLine(string message); /// <summary> /// Writes an empty line to the console. /// </summary> void WriteLine(); /// <summary> /// Writes a console command response to the console. /// <para>Most nodes will recycle their normal console writer commands for this. /// This is provided specifically to accommodate the Crestron console class.</para> /// </summary> /// <param name="message">The message response to write to the console.</param> /// <param name="args">Optional array of arguments to format the message using.</param> void WriteCommandResponse(string message, params object[] args); /// <summary> /// Writes a console command response to the console. /// <para>Most nodes will recycle their normal console writer commands for this. /// This is provided specifically to accommodate the Crestron console class.</para> /// </summary> /// <param name="message">The message response to write to the console.</param> void WriteCommandResponse(string message); } }
50.333333
129
0.674223
[ "MIT" ]
ProfessorAire/Evands.Pellucid-Crestron
src/Evands.Pellucid/Terminal/IConsoleWriter.cs
3,928
C#
using Test.Screen; using SadCanvas.Shapes; namespace Test.Pages; internal class LoadingImages : Page { public LoadingImages() : base("Image files", "Canvas instance can be created directly from various image formats.") { var canvas = new Parrot(); Add(canvas); } class Parrot : Canvas { public Parrot() : base("Res/Images/parrot.jpg") { Children.Add(new Mario()); Children.Add(new VerticalLines() { Position = (70, 430) }); Children.Add(new VerticalLines() { Position = (70, -24) }); } } class Mario : ScreenSurface { public Mario() : base(16, 9) { Canvas mario = new("Res/Images/mario.png") { UsePixelPositioning = true, Position = (16, 23) }; Children.Add(mario); Surface.DrawBox(new SadRogue.Primitives.Rectangle(0, 0, Surface.Width, Surface.Height), ShapeParameters.CreateStyledBox(ICellSurface.ConnectedLineThick, new ColoredGlyph(Color.Green, Color.Yellow)) ); Position = (4, 3); } } class VerticalLines : Canvas { int currentColumn = 0; public VerticalLines() : base(500, 20, Color.LightBlue.ToMonoColor()) { UsePixelPositioning = true; } public override void Update(TimeSpan delta) { MonoColor color = GetRandomColor(); Point start = (currentColumn, 0); Point end = (currentColumn++, Height - 1); if (currentColumn >= Width) currentColumn = 0; Draw(new Line(start, end, color)); base.Update(delta); } } }
27.307692
119
0.538592
[ "MIT" ]
RychuP/SadCanvas
Test/Pages/LoadingImages.cs
1,777
C#
using System; using Microsoft.CodeAnalysis; namespace Melville.Generators.INPC.GenerationTools.CodeWriters; public static class WriteCodeNear { public static IDisposable Symbol(SyntaxNode node, CodeWriter cw, string baseDeclaration = "") { var namespaces = cw.GeneratePartialClassContext(node); var classes = cw.GenerateEnclosingClasses(node, baseDeclaration); return new CompositeDispose(new[] { namespaces, classes }); } }
33.071429
97
0.7473
[ "MIT" ]
JohnN6TSM/Melville
src/Melville.Generators.INPC/GenerationTools/CodeWriters/WriteCodeNear.cs
465
C#
using VoteApp.Application.Requests.Identity; using VoteApp.Client.Extensions; using VoteApp.Shared.Constants.Application; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.SignalR.Client; using MudBlazor; using System.Threading.Tasks; using Blazored.FluentValidation; using VoteApp.Client.Infrastructure.Managers.Identity.Roles; namespace VoteApp.Client.Pages.Identity { public partial class RoleModal { [Inject] private IRoleManager RoleManager { get; set; } [Parameter] public RoleRequest RoleModel { get; set; } = new(); [CascadingParameter] private MudDialogInstance MudDialog { get; set; } [CascadingParameter] private HubConnection HubConnection { get; set; } private FluentValidationValidator _fluentValidationValidator; private bool Validated => _fluentValidationValidator.Validate(options => { options.IncludeAllRuleSets(); }); public void Cancel() { MudDialog.Cancel(); } protected override async Task OnInitializedAsync() { HubConnection = HubConnection.TryInitialize(_navigationManager); if (HubConnection.State == HubConnectionState.Disconnected) { await HubConnection.StartAsync(); } } private async Task SaveAsync() { var response = await RoleManager.SaveAsync(RoleModel); if (response.Succeeded) { _snackBar.Add(response.Messages[0], Severity.Success); await HubConnection.SendAsync(ApplicationConstants.SignalR.SendUpdateDashboard); MudDialog.Close(); } else { foreach (var message in response.Messages) { _snackBar.Add(message, Severity.Error); } } } } }
33.982143
116
0.632685
[ "MIT" ]
andlekbra/dat250-gruppe5-VoteApp2
src/Client/Pages/Identity/RoleModal.razor.cs
1,905
C#
// Copyright 2011-2017 The Poderosa Project. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //#define DUMP_PACKET //#define TRACE_RECEIVER using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Diagnostics; using System.IO; using Granados.SSH; using Granados.SSH1; using Granados.SSH2; using Granados.IO; using Granados.IO.SSH2; using Granados.Util; using System.Collections.Concurrent; namespace Granados.Poderosa.SCP { /// <summary> /// Channel stream for SCPClient /// </summary> internal class SCPChannelStream : IDisposable { #region Private enum /// <summary> /// Stream status /// </summary> private enum StreamStatus { /// <summary>Channel is not opened yet</summary> NotOpened, /// <summary>Channel is opened, but not ready</summary> Opened, /// <summary>Channel is closing</summary> Closing, /// <summary>Channel is closed</summary> Closed, /// <summary>Channel has error</summary> Error, } #endregion #region Private constants private const int INITIAL_CAPACITY = 1024; #endregion #region Private fields private volatile StreamStatus _status; private readonly object _statusSync = new object(); private ISSHChannel _channel = null; private SCPClientChannelEventHandler _eventHandler = null; private ByteBuffer _buffer = new ByteBuffer(INITIAL_CAPACITY, -1); private readonly object _bufferSync = new object(); #endregion #region Constructor /// <summary> /// Constructor /// </summary> public SCPChannelStream() { } #endregion #region Properties #if UNITTEST internal byte[] DataBuffer { get { return _buffer.GetBytes(); } } internal SCPClientChannelEventHandler ChannelEventHandler { get { return _eventHandler; } } internal string Status { get { return _status.ToString(); } } #endif #endregion #region Public methods /// <summary> /// Opens channel. /// </summary> /// <param name="connection">SSH connection object</param> /// <param name="command">Remote command</param> /// <param name="millisecondsTimeout">timeout in milliseconds</param> /// <exception cref="SCPClientInvalidStatusException">Channel has been already opened or already closed.</exception> /// <exception cref="SCPClientTimeoutException">Timeout has occurred while waiting for READY status.</exception> public void Open(ISSHConnection connection, string command, int millisecondsTimeout) { if (_status != StreamStatus.NotOpened) throw new SCPClientInvalidStatusException(); ISSHChannel channel = null; SCPClientChannelEventHandler eventHandler = connection.ExecCommand( (ch) => { channel = ch; return new SCPClientChannelEventHandler( new DataReceivedDelegate(OnDataReceived), new ChannelStatusChangedDelegate(OnChannelStatusChanged) ); }, command ); _eventHandler = eventHandler; _channel = channel; if (!_eventHandler.WaitStatus(SCPChannelStatus.READY, millisecondsTimeout)) { throw new SCPClientTimeoutException(); } lock(_statusSync) { if (_status == StreamStatus.NotOpened) { _status = StreamStatus.Opened; } } } #if UNITTEST internal void OpenForTest(ISSHChannel channel) { if (_status != StreamStatus.NotOpened) throw new SCPClientInvalidStatusException(); SCPClientChannelEventHandler eventHandler = new SCPClientChannelEventHandler( new DataReceivedDelegate(OnDataReceived), new ChannelStatusChangedDelegate(OnChannelStatusChanged) ); _eventHandler = eventHandler; _channel = channel; lock (_statusSync) { if (_status == StreamStatus.NotOpened) { _status = StreamStatus.Opened; } } } internal void SetBuffer(int capacity) { lock (_bufferSync) { _buffer = new ByteBuffer(capacity, -1); } } internal void SetBufferContent(byte[] bytes) { lock (_bufferSync) { _buffer.Clear(); _buffer.Append(bytes); } } #endif /// <summary> /// Close channel. /// </summary> public void Close() { lock (_statusSync) { if (_status != StreamStatus.Opened && _status != StreamStatus.Error) return; _status = StreamStatus.Closing; } _channel.SendEOF(); if (_status != StreamStatus.Closing) return; _channel.Close(); lock (_statusSync) { if (_status == StreamStatus.Closing) { _status = StreamStatus.Closed; } } } /// <summary> /// Gets preferred datagram size. /// </summary> /// <returns>size in bytes</returns> public int GetPreferredDatagramSize() { return (_channel != null) ? Math.Max(1024, _channel.MaxChannelDatagramSize) : 1024; } /// <summary> /// Writes data. /// </summary> /// <param name="buffer">Buffer</param> public void Write(byte[] buffer) { Write(buffer, buffer.Length); } /// <summary> /// Writes data. /// </summary> /// <param name="buffer">Buffer</param> /// <param name="length">Length</param> public void Write(byte[] buffer, int length) { if (_status != StreamStatus.Opened) throw new SCPClientInvalidStatusException(); Debug.Assert(_channel != null); _channel.Send(new DataFragment(buffer, 0, length)); } /// <summary> /// Reads data /// </summary> /// <param name="buffer">Byte array to store the data</param> /// <param name="millisecondsTimeout">Timeout in milliseconds</param> /// <returns>Length to be stored in the buffer</returns> /// <exception cref="SCPClientTimeoutException">Timeout has occurred</exception> public int Read(byte[] buffer, int millisecondsTimeout) { return Read(buffer, buffer.Length, millisecondsTimeout); } /// <summary> /// Reads data /// </summary> /// <param name="buffer">Byte array to store the data</param> /// <param name="maxLength">Maximum bytes to read</param> /// <param name="millisecondsTimeout">Timeout in milliseconds</param> /// <returns>Length to be stored in the buffer</returns> /// <exception cref="SCPClientTimeoutException">Timeout has occurred</exception> public int Read(byte[] buffer, int maxLength, int millisecondsTimeout) { if (_status != StreamStatus.Opened) throw new SCPClientInvalidStatusException(); lock (_bufferSync) { while (_buffer.Length == 0) { bool signaled = Monitor.Wait(_bufferSync, millisecondsTimeout); if (!signaled) throw new SCPClientTimeoutException(); if (_status != StreamStatus.Opened) throw new SCPClientInvalidStatusException(); } int retrieveSize = Math.Min(_buffer.Length, Math.Min(buffer.Length, maxLength)); Buffer.BlockCopy(_buffer.RawBuffer, _buffer.RawBufferOffset, buffer, 0, retrieveSize); _buffer.RemoveHead(retrieveSize); return retrieveSize; } } /// <summary> /// Read one byte /// </summary> /// <param name="millisecondsTimeout">Timeout in milliseconds</param> /// <returns>Byte value</returns> /// <exception cref="SCPClientTimeoutException">Timeout has occurred</exception> public byte ReadByte(int millisecondsTimeout) { if (_status != StreamStatus.Opened) throw new SCPClientInvalidStatusException(); lock (_bufferSync) { while (_buffer.Length < 1) { bool signaled = Monitor.Wait(_bufferSync, millisecondsTimeout); if (!signaled) throw new SCPClientTimeoutException(); if (_status != StreamStatus.Opened) throw new SCPClientInvalidStatusException(); } byte b = _buffer[0]; _buffer.RemoveHead(1); return b; } } /// <summary> /// Read data until specified byte value is read. /// </summary> /// <param name="terminator">Byte value to stop reading</param> /// <param name="millisecondsTimeout">Timeout in milliseconds</param> /// <returns>Byte array received.</returns> /// <exception cref="SCPClientTimeoutException">Timeout has occurred</exception> /// <exception cref="SCPClientException">Buffer overflow</exception> public byte[] ReadUntil(byte terminator, int millisecondsTimeout) { if (_status != StreamStatus.Opened) throw new SCPClientInvalidStatusException(); lock (_bufferSync) { for(int dataOffset = 0; ; dataOffset++) { while (_buffer.Length <= dataOffset) { bool signaled = Monitor.Wait(_bufferSync, millisecondsTimeout); if (!signaled) throw new SCPClientTimeoutException(); if (_status != StreamStatus.Opened) throw new SCPClientInvalidStatusException(); } byte b = _buffer[dataOffset]; if (b == terminator) { int dataLength = dataOffset + 1; byte[] data = new byte[dataLength]; Buffer.BlockCopy(_buffer.RawBuffer, _buffer.RawBufferOffset, data, 0, dataLength); _buffer.RemoveHead(dataLength); return data; } } } } #endregion #region SCPClientChannelEventReceiver Handlers private void OnDataReceived(DataFragment data) { lock (_bufferSync) { _buffer.Append(data); Monitor.PulseAll(_bufferSync); } } private void OnChannelStatusChanged(SCPChannelStatus newStatus) { if (newStatus == SCPChannelStatus.CLOSED) { lock (_statusSync) { _status = StreamStatus.Closed; } lock (_bufferSync) { Monitor.PulseAll(_bufferSync); } } else if (newStatus == SCPChannelStatus.ERROR) { lock (_statusSync) { _status = StreamStatus.Error; } lock (_bufferSync) { Monitor.PulseAll(_bufferSync); } } } #endregion #region IDisposable /// <summary> /// IDisposable implementation /// </summary> public void Dispose() { Close(); } #endregion } /// <summary> /// Channel status /// </summary> internal enum SCPChannelStatus { UNKNOWN, READY, CLOSED, ERROR, } /// <summary> /// Delegate that handles channel data. /// </summary> /// <param name="data">Data buffer</param> internal delegate void DataReceivedDelegate(DataFragment data); /// <summary> /// Delegate that handles transition of the channel status. /// </summary> /// <param name="newStatus">New status</param> internal delegate void ChannelStatusChangedDelegate(SCPChannelStatus newStatus); /// <summary> /// Channel data handler for SCPClient /// </summary> internal class SCPClientChannelEventHandler : SimpleSSHChannelEventHandler { #region Private fields private volatile SCPChannelStatus _channelStatus = SCPChannelStatus.UNKNOWN; private readonly Object _statusSync = new object(); private readonly Object _responseNotifier = new object(); private readonly DataReceivedDelegate _dataHandler = null; private readonly ChannelStatusChangedDelegate _statusChangeHandler = null; #endregion #region Properties /// <summary> /// Gets channel status /// </summary> public SCPChannelStatus ChannelStatus { get { return _channelStatus; } } #endregion #region Constructor /// <summary> /// Constructor /// </summary> /// <param name="dataHandler">Data handler</param> /// <param name="statusChangeHandler">Channel status handler</param> public SCPClientChannelEventHandler(DataReceivedDelegate dataHandler, ChannelStatusChangedDelegate statusChangeHandler) { this._dataHandler = dataHandler; this._statusChangeHandler = statusChangeHandler; } #endregion public bool WaitStatus(SCPChannelStatus status, int millisecondsTimeout) { lock (_statusSync) { while (_channelStatus != status) { bool acquired = Monitor.Wait(_statusSync, millisecondsTimeout); if (!acquired) { return false; } } return true; } } #region ISSHChannelEventHandler public override void OnData(DataFragment data) { #if DUMP_PACKET Dump("SCP: OnData", data); #endif if (_dataHandler != null) { _dataHandler(data); } } public override void OnClosed(bool byServer) { #if TRACE_RECEIVER System.Diagnostics.Debug.WriteLine("SCP: Closed"); #endif TransitStatus(SCPChannelStatus.CLOSED); } public override void OnError(Exception error) { #if TRACE_RECEIVER System.Diagnostics.Debug.WriteLine("SCP: Error: " + error.Message); #endif TransitStatus(SCPChannelStatus.ERROR); } public override void OnReady() { #if TRACE_RECEIVER System.Diagnostics.Debug.WriteLine("SCP: OnChannelReady"); #endif TransitStatus(SCPChannelStatus.READY); } #endregion #region Private methods private void TransitStatus(SCPChannelStatus newStatus) { lock (_statusSync) { _channelStatus = newStatus; Monitor.PulseAll(_statusSync); } if (_statusChangeHandler != null) { _statusChangeHandler(newStatus); } } #if DUMP_PACKET // for debug private void Dump(string caption, DataFragment data) { Dump(caption, data.Data, data.Offset, data.Length); } // for debug private void Dump(string caption, byte[] data, int offset, int length) { StringBuilder s = new StringBuilder(); s.AppendLine(caption); s.Append("0--1--2--3--4--5--6--7--8--9--A--B--C--D--E--F-"); for (int i = 0; i < length; i++) { byte b = data[offset + i]; int pos = i % 16; if (pos == 0) s.AppendLine(); else s.Append(' '); s.Append("0123456789abcdef"[b >> 4]).Append("0123456789abcdef"[b & 0xf]); } s.AppendLine().Append("0--1--2--3--4--5--6--7--8--9--A--B--C--D--E--F-"); System.Diagnostics.Debug.WriteLine(s); } #endif #endregion } }
32.235622
129
0.549928
[ "Apache-2.0" ]
dnobori/poderosa
Granados/Poderosa/SCP/SCPChannelStream.cs
17,377
C#
using RuriLib; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace OpenBullet.Pages.Main.Settings { /// <summary> /// Logica di interazione per RLSettingsPage.xaml /// </summary> public partial class RLSettingsPage : Page { RLSettingsGeneral GeneralPage = new RLSettingsGeneral(); RLSettingsProxies ProxiesPage = new RLSettingsProxies(); RLSettingsCaptchas CaptchasPage = new RLSettingsCaptchas(); RLSettingsSelenium SeleniumPage = new RLSettingsSelenium(); public RLSettingsPage() { InitializeComponent(); menuOptionGeneral_MouseDown(this, null); } #region Menu Options private void menuOptionGeneral_MouseDown(object sender, MouseButtonEventArgs e) { Main.Content = GeneralPage; menuOptionSelected(menuOptionGeneral); } private void menuOptionProxies_MouseDown(object sender, MouseButtonEventArgs e) { Main.Content = ProxiesPage; menuOptionSelected(menuOptionProxies); } private void menuOptionCaptchas_MouseDown(object sender, MouseButtonEventArgs e) { Main.Content = CaptchasPage; menuOptionSelected(menuOptionCaptchas); } private void menuOptionSelenium_MouseDown(object sender, MouseButtonEventArgs e) { Main.Content = SeleniumPage; menuOptionSelected(menuOptionSelenium); } private void menuOptionSelected(object sender) { foreach (var child in topMenu.Children) { try { var c = (Label)child; c.Foreground = Globals.GetBrush("ForegroundMain"); } catch { } } ((Label)sender).Foreground = Globals.GetBrush("ForegroundGood"); } #endregion private void saveButton_Click(object sender, RoutedEventArgs e) { IOManager.SaveSettings(Globals.rlSettingsFile, Globals.rlSettings); } } }
30.320988
88
0.638844
[ "MIT" ]
Cheetah55/openbullet-1.2
OpenBullet/Pages/Main/Settings/RLSettingsPage.xaml.cs
2,458
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System.ComponentModel; namespace osu.Game.Screens.Select.Leaderboards { public enum BeatmapLeaderboardScope { [Description("本地排行")] Local, [Description("国内/区内排行")] Country, [Description("全球排行")] Global, [Description("好友排行")] Friend, } }
21.565217
80
0.596774
[ "MIT" ]
RocketMaDev/osu
osu.Game/Screens/Select/Leaderboards/BeatmapLeaderboardScope.cs
512
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis.FlowAnalysis; using Microsoft.CodeAnalysis.Operations; namespace Microsoft.CodeAnalysis.Diagnostics { /// <summary> /// Scope for setting up analyzers for an entire session, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerAnalysisContext : AnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostSessionStartAnalysisScope _scope; public AnalyzerAnalysisContext(DiagnosticAnalyzer analyzer, HostSessionStartAnalysisScope scope) { _analyzer = analyzer; _scope = scope; } public override void RegisterCompilationStartAction(Action<CompilationStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationStartAction(_analyzer, action); } public override void RegisterCompilationAction(Action<CompilationAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCompilationAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, symbolKinds); _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, syntaxKinds); _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { DiagnosticAnalysisContextHelpers.VerifyArguments(action, operationKinds); _scope.RegisterOperationAction(_analyzer, action, operationKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void EnableConcurrentExecution() { _scope.EnableConcurrentExecution(_analyzer); } public override void ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags mode) { _scope.ConfigureGeneratedCodeAnalysis(_analyzer, mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCompilationStartAnalysisContext : CompilationStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCompilationStartAnalysisScope _scope; private readonly CompilationAnalysisValueProviderFactory _compilationAnalysisValueProviderFactory; public AnalyzerCompilationStartAnalysisContext( DiagnosticAnalyzer analyzer, HostCompilationStartAnalysisScope scope, Compilation compilation, AnalyzerOptions options, CompilationAnalysisValueProviderFactory compilationAnalysisValueProviderFactory, CancellationToken cancellationToken) : base(compilation, options, cancellationToken) { _analyzer = analyzer; _scope = scope; _compilationAnalysisValueProviderFactory = compilationAnalysisValueProviderFactory; } public override void RegisterCompilationEndAction(Action<CompilationAnalysisContext> action) { _scope.RegisterCompilationEndAction(_analyzer, action); } public override void RegisterSyntaxTreeAction(Action<SyntaxTreeAnalysisContext> action) { _scope.RegisterSyntaxTreeAction(_analyzer, action); } public override void RegisterSemanticModelAction(Action<SemanticModelAnalysisContext> action) { _scope.RegisterSemanticModelAction(_analyzer, action); } public override void RegisterSymbolAction(Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { _scope.RegisterSymbolAction(_analyzer, action, symbolKinds); } public override void RegisterCodeBlockStartAction<TLanguageKindEnum>(Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) { _scope.RegisterCodeBlockStartAction<TLanguageKindEnum>(_analyzer, action); } public override void RegisterCodeBlockAction(Action<CodeBlockAnalysisContext> action) { _scope.RegisterCodeBlockAction(_analyzer, action); } public override void RegisterSyntaxNodeAction<TLanguageKindEnum>(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } public override void RegisterOperationBlockStartAction(Action<OperationBlockStartAnalysisContext> action) { _scope.RegisterOperationBlockStartAction(_analyzer, action); } public override void RegisterOperationBlockAction(Action<OperationBlockAnalysisContext> action) { DiagnosticAnalysisContextHelpers.VerifyArguments(action); _scope.RegisterOperationBlockAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { _scope.RegisterOperationAction(_analyzer, action, operationKinds); } internal override bool TryGetValueCore<TKey, TValue>(TKey key, AnalysisValueProvider<TKey, TValue> valueProvider, out TValue value) { var compilationAnalysisValueProvider = _compilationAnalysisValueProviderFactory.GetValueProvider(valueProvider); return compilationAnalysisValueProvider.TryGetValue(key, out value); } } /// <summary> /// Scope for setting up analyzers for a code block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerCodeBlockStartAnalysisContext<TLanguageKindEnum> : CodeBlockStartAnalysisContext<TLanguageKindEnum> where TLanguageKindEnum : struct { private readonly DiagnosticAnalyzer _analyzer; private readonly HostCodeBlockStartAnalysisScope<TLanguageKindEnum> _scope; internal AnalyzerCodeBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostCodeBlockStartAnalysisScope<TLanguageKindEnum> scope, SyntaxNode codeBlock, ISymbol owningSymbol, SemanticModel semanticModel, AnalyzerOptions options, CancellationToken cancellationToken) : base(codeBlock, owningSymbol, semanticModel, options, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterCodeBlockEndAction(Action<CodeBlockAnalysisContext> action) { _scope.RegisterCodeBlockEndAction(_analyzer, action); } public override void RegisterSyntaxNodeAction(Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { _scope.RegisterSyntaxNodeAction(_analyzer, action, syntaxKinds); } } /// <summary> /// Scope for setting up analyzers for an operation block, automatically associating actions with analyzers. /// </summary> internal sealed class AnalyzerOperationBlockStartAnalysisContext : OperationBlockStartAnalysisContext { private readonly DiagnosticAnalyzer _analyzer; private readonly HostOperationBlockStartAnalysisScope _scope; internal AnalyzerOperationBlockStartAnalysisContext(DiagnosticAnalyzer analyzer, HostOperationBlockStartAnalysisScope scope, ImmutableArray<IOperation> operationBlocks, ISymbol owningSymbol, Compilation compilation, AnalyzerOptions options, Func<IOperation, ControlFlowGraph> getControlFlowGraph, CancellationToken cancellationToken) : base(operationBlocks, owningSymbol, compilation, options, getControlFlowGraph, cancellationToken) { _analyzer = analyzer; _scope = scope; } public override void RegisterOperationBlockEndAction(Action<OperationBlockAnalysisContext> action) { _scope.RegisterOperationBlockEndAction(_analyzer, action); } public override void RegisterOperationAction(Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { _scope.RegisterOperationAction(_analyzer, action, operationKinds); } } /// <summary> /// Scope for setting up analyzers for an entire session, capable of retrieving the actions. /// </summary> internal sealed class HostSessionStartAnalysisScope : HostAnalysisScope { private ImmutableArray<CompilationStartAnalyzerAction> _compilationStartActions = ImmutableArray<CompilationStartAnalyzerAction>.Empty; private ImmutableHashSet<DiagnosticAnalyzer> _concurrentAnalyzers = ImmutableHashSet<DiagnosticAnalyzer>.Empty; private ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags> _generatedCodeConfigurationMap = new ConcurrentDictionary<DiagnosticAnalyzer, GeneratedCodeAnalysisFlags>(); public ImmutableArray<CompilationStartAnalyzerAction> CompilationStartActions { get { return _compilationStartActions; } } public bool IsConcurrentAnalyzer(DiagnosticAnalyzer analyzer) { return _concurrentAnalyzers.Contains(analyzer); } public GeneratedCodeAnalysisFlags GetGeneratedCodeAnalysisFlags(DiagnosticAnalyzer analyzer) { GeneratedCodeAnalysisFlags mode; return _generatedCodeConfigurationMap.TryGetValue(analyzer, out mode) ? mode : AnalyzerDriver.DefaultGeneratedCodeAnalysisFlags; } public void RegisterCompilationStartAction(DiagnosticAnalyzer analyzer, Action<CompilationStartAnalysisContext> action) { CompilationStartAnalyzerAction analyzerAction = new CompilationStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).AddCompilationStartAction(analyzerAction); _compilationStartActions = _compilationStartActions.Add(analyzerAction); } public void EnableConcurrentExecution(DiagnosticAnalyzer analyzer) { _concurrentAnalyzers = _concurrentAnalyzers.Add(analyzer); GetOrCreateAnalyzerActions(analyzer).EnableConcurrentExecution(); } public void ConfigureGeneratedCodeAnalysis(DiagnosticAnalyzer analyzer, GeneratedCodeAnalysisFlags mode) { _generatedCodeConfigurationMap.AddOrUpdate(analyzer, addValue: mode, updateValueFactory: (a, c) => mode); } } /// <summary> /// Scope for setting up analyzers for a compilation, capable of retrieving the actions. /// </summary> internal sealed class HostCompilationStartAnalysisScope : HostAnalysisScope { private readonly HostSessionStartAnalysisScope _sessionScope; public HostCompilationStartAnalysisScope(HostSessionStartAnalysisScope sessionScope) { _sessionScope = sessionScope; } public override ImmutableArray<CompilationAnalyzerAction> CompilationEndActions { get { return base.CompilationEndActions.AddRange(_sessionScope.CompilationEndActions); } } public override ImmutableArray<SemanticModelAnalyzerAction> SemanticModelActions { get { return base.SemanticModelActions.AddRange(_sessionScope.SemanticModelActions); } } public override ImmutableArray<SyntaxTreeAnalyzerAction> SyntaxTreeActions { get { return base.SyntaxTreeActions.AddRange(_sessionScope.SyntaxTreeActions); } } public override ImmutableArray<SymbolAnalyzerAction> SymbolActions { get { return base.SymbolActions.AddRange(_sessionScope.SymbolActions); } } public override ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return base.CodeBlockEndActions.AddRange(_sessionScope.CodeBlockEndActions); } } public override ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions { get { return base.CodeBlockActions.AddRange(_sessionScope.CodeBlockActions); } } public override bool HasCodeBlockEndActions { get { return base.HasCodeBlockEndActions || _sessionScope.HasCodeBlockEndActions; } } public override bool HasCodeBlockActions { get { return base.HasCodeBlockActions || _sessionScope.HasCodeBlockActions; } } public override bool HasCodeBlockStartActions<TLanguageKindEnum>() { return base.HasCodeBlockStartActions<TLanguageKindEnum>() || _sessionScope.HasCodeBlockStartActions<TLanguageKindEnum>(); } public override ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> GetCodeBlockStartActions<TLanguageKindEnum>() { return base.GetCodeBlockStartActions<TLanguageKindEnum>().AddRange(_sessionScope.GetCodeBlockStartActions<TLanguageKindEnum>()); } public override ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>() { return base.GetSyntaxNodeActions<TLanguageKindEnum>().AddRange(_sessionScope.GetSyntaxNodeActions<TLanguageKindEnum>()); } public override ImmutableArray<OperationAnalyzerAction> OperationActions { get { return base.OperationActions.AddRange(_sessionScope.OperationActions); } } public override AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { AnalyzerActions compilationActions = base.GetAnalyzerActions(analyzer); AnalyzerActions sessionActions = _sessionScope.GetAnalyzerActions(analyzer); if (sessionActions == null) { return compilationActions; } if (compilationActions == null) { return sessionActions; } return compilationActions.Append(sessionActions); } public AnalyzerActions GetCompilationOnlyAnalyzerActions(DiagnosticAnalyzer analyzer) { return base.GetAnalyzerActions(analyzer); } } /// <summary> /// Scope for setting up analyzers for a code block, capable of retrieving the actions. /// </summary> internal sealed class HostCodeBlockStartAnalysisScope<TLanguageKindEnum> where TLanguageKindEnum : struct { private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; private ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> _syntaxNodeActions = ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>.Empty; public ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } public ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> SyntaxNodeActions { get { return _syntaxNodeActions; } } internal HostCodeBlockStartAnalysisScope() { } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { _codeBlockEndActions = _codeBlockEndActions.Add(new CodeBlockAnalyzerAction(action, analyzer)); } public void RegisterSyntaxNodeAction(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) { _syntaxNodeActions = _syntaxNodeActions.Add(new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer)); } } internal sealed class HostOperationBlockStartAnalysisScope { private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; private ImmutableArray<OperationAnalyzerAction> _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; public ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions => _operationBlockEndActions; public ImmutableArray<OperationAnalyzerAction> OperationActions => _operationActions; internal HostOperationBlockStartAnalysisScope() { } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { _operationBlockEndActions = _operationBlockEndActions.Add(new OperationBlockAnalyzerAction(action, analyzer)); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { _operationActions = _operationActions.Add(new OperationAnalyzerAction(action, operationKinds, analyzer)); } } internal abstract class HostAnalysisScope { private ImmutableArray<CompilationAnalyzerAction> _compilationActions = ImmutableArray<CompilationAnalyzerAction>.Empty; private ImmutableArray<CompilationAnalyzerAction> _compilationEndActions = ImmutableArray<CompilationAnalyzerAction>.Empty; private ImmutableArray<SemanticModelAnalyzerAction> _semanticModelActions = ImmutableArray<SemanticModelAnalyzerAction>.Empty; private ImmutableArray<SyntaxTreeAnalyzerAction> _syntaxTreeActions = ImmutableArray<SyntaxTreeAnalyzerAction>.Empty; private ImmutableArray<SymbolAnalyzerAction> _symbolActions = ImmutableArray<SymbolAnalyzerAction>.Empty; private ImmutableArray<AnalyzerAction> _codeBlockStartActions = ImmutableArray<AnalyzerAction>.Empty; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; private ImmutableArray<AnalyzerAction> _syntaxNodeActions = ImmutableArray<AnalyzerAction>.Empty; private ImmutableArray<OperationBlockStartAnalyzerAction> _operationBlockStartActions = ImmutableArray<OperationBlockStartAnalyzerAction>.Empty; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; private ImmutableArray<OperationAnalyzerAction> _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; private readonly Dictionary<DiagnosticAnalyzer, AnalyzerActions> _analyzerActions = new Dictionary<DiagnosticAnalyzer, AnalyzerActions>(); public ImmutableArray<CompilationAnalyzerAction> CompilationActions { get { return _compilationActions; } } public virtual ImmutableArray<CompilationAnalyzerAction> CompilationEndActions { get { return _compilationEndActions; } } public virtual ImmutableArray<SemanticModelAnalyzerAction> SemanticModelActions { get { return _semanticModelActions; } } public virtual ImmutableArray<SyntaxTreeAnalyzerAction> SyntaxTreeActions { get { return _syntaxTreeActions; } } public virtual ImmutableArray<SymbolAnalyzerAction> SymbolActions { get { return _symbolActions; } } public virtual ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } public virtual ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions { get { return _codeBlockActions; } } public virtual bool HasCodeBlockEndActions { get { return _codeBlockEndActions.Any(); } } public virtual bool HasCodeBlockActions { get { return _codeBlockActions.Any(); } } public virtual bool HasCodeBlockStartActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _codeBlockStartActions.OfType<CodeBlockStartAnalyzerAction<TLanguageKindEnum>>().Any(); } public virtual ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> GetCodeBlockStartActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _codeBlockStartActions.OfType<CodeBlockStartAnalyzerAction<TLanguageKindEnum>>().AsImmutable(); } public virtual ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _syntaxNodeActions.OfType<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>().AsImmutable(); } public virtual ImmutableArray<OperationAnalyzerAction> OperationActions { get { return _operationActions; } } public virtual AnalyzerActions GetAnalyzerActions(DiagnosticAnalyzer analyzer) { AnalyzerActions actions; _analyzerActions.TryGetValue(analyzer, out actions); return actions; } public void RegisterCompilationAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).AddCompilationAction(analyzerAction); _compilationActions = _compilationActions.Add(analyzerAction); } public void RegisterCompilationEndAction(DiagnosticAnalyzer analyzer, Action<CompilationAnalysisContext> action) { CompilationAnalyzerAction analyzerAction = new CompilationAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).AddCompilationEndAction(analyzerAction); _compilationEndActions = _compilationEndActions.Add(analyzerAction); } public void RegisterSemanticModelAction(DiagnosticAnalyzer analyzer, Action<SemanticModelAnalysisContext> action) { SemanticModelAnalyzerAction analyzerAction = new SemanticModelAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).AddSemanticModelAction(analyzerAction); _semanticModelActions = _semanticModelActions.Add(analyzerAction); } public void RegisterSyntaxTreeAction(DiagnosticAnalyzer analyzer, Action<SyntaxTreeAnalysisContext> action) { SyntaxTreeAnalyzerAction analyzerAction = new SyntaxTreeAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).AddSyntaxTreeAction(analyzerAction); _syntaxTreeActions = _syntaxTreeActions.Add(analyzerAction); } public void RegisterSymbolAction(DiagnosticAnalyzer analyzer, Action<SymbolAnalysisContext> action, ImmutableArray<SymbolKind> symbolKinds) { SymbolAnalyzerAction analyzerAction = new SymbolAnalyzerAction(action, symbolKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).AddSymbolAction(analyzerAction); _symbolActions = _symbolActions.Add(analyzerAction); // The SymbolAnalyzerAction does not handle SymbolKind.Parameter because the compiler // does not make CompilationEvents for them. As a workaround, handle them specially by // registering further SymbolActions (for Methods) and utilize the results to construct // the necessary SymbolAnalysisContexts. if (symbolKinds.Contains(SymbolKind.Parameter)) { RegisterSymbolAction( analyzer, context => { ImmutableArray<IParameterSymbol> parameters; switch (context.Symbol.Kind) { case SymbolKind.Method: parameters = ((IMethodSymbol)context.Symbol).Parameters; break; case SymbolKind.Property: parameters = ((IPropertySymbol)context.Symbol).Parameters; break; case SymbolKind.NamedType: var namedType = (INamedTypeSymbol)context.Symbol; var delegateInvokeMethod = namedType.DelegateInvokeMethod; parameters = delegateInvokeMethod?.Parameters ?? ImmutableArray.Create<IParameterSymbol>(); break; default: throw new ArgumentException($"{context.Symbol.Kind} is not supported.", nameof(context)); } foreach (var parameter in parameters) { if (!parameter.IsImplicitlyDeclared) { action(new SymbolAnalysisContext( parameter, context.Compilation, context.Options, context.ReportDiagnostic, context.IsSupportedDiagnostic, context.CancellationToken)); } } }, ImmutableArray.Create(SymbolKind.Method, SymbolKind.Property, SymbolKind.NamedType)); } } public void RegisterCodeBlockStartAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<CodeBlockStartAnalysisContext<TLanguageKindEnum>> action) where TLanguageKindEnum : struct { CodeBlockStartAnalyzerAction<TLanguageKindEnum> analyzerAction = new CodeBlockStartAnalyzerAction<TLanguageKindEnum>(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).AddCodeBlockStartAction(analyzerAction); _codeBlockStartActions = _codeBlockStartActions.Add(analyzerAction); } public void RegisterCodeBlockEndAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).AddCodeBlockEndAction(analyzerAction); _codeBlockEndActions = _codeBlockEndActions.Add(analyzerAction); } public void RegisterCodeBlockAction(DiagnosticAnalyzer analyzer, Action<CodeBlockAnalysisContext> action) { CodeBlockAnalyzerAction analyzerAction = new CodeBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).AddCodeBlockAction(analyzerAction); _codeBlockActions = _codeBlockActions.Add(analyzerAction); } public void RegisterSyntaxNodeAction<TLanguageKindEnum>(DiagnosticAnalyzer analyzer, Action<SyntaxNodeAnalysisContext> action, ImmutableArray<TLanguageKindEnum> syntaxKinds) where TLanguageKindEnum : struct { SyntaxNodeAnalyzerAction<TLanguageKindEnum> analyzerAction = new SyntaxNodeAnalyzerAction<TLanguageKindEnum>(action, syntaxKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).AddSyntaxNodeAction(analyzerAction); _syntaxNodeActions = _syntaxNodeActions.Add(analyzerAction); } public void RegisterOperationBlockStartAction(DiagnosticAnalyzer analyzer, Action<OperationBlockStartAnalysisContext> action) { OperationBlockStartAnalyzerAction analyzerAction = new OperationBlockStartAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).AddOperationBlockStartAction(analyzerAction); _operationBlockStartActions = _operationBlockStartActions.Add(analyzerAction); } public void RegisterOperationBlockEndAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).AddOperationBlockEndAction(analyzerAction); _operationBlockEndActions = _operationBlockEndActions.Add(analyzerAction); } public void RegisterOperationBlockAction(DiagnosticAnalyzer analyzer, Action<OperationBlockAnalysisContext> action) { OperationBlockAnalyzerAction analyzerAction = new OperationBlockAnalyzerAction(action, analyzer); this.GetOrCreateAnalyzerActions(analyzer).AddOperationBlockAction(analyzerAction); _operationBlockActions = _operationBlockActions.Add(analyzerAction); } public void RegisterOperationAction(DiagnosticAnalyzer analyzer, Action<OperationAnalysisContext> action, ImmutableArray<OperationKind> operationKinds) { OperationAnalyzerAction analyzerAction = new OperationAnalyzerAction(action, operationKinds, analyzer); this.GetOrCreateAnalyzerActions(analyzer).AddOperationAction(analyzerAction); _operationActions = _operationActions.Add(analyzerAction); } protected AnalyzerActions GetOrCreateAnalyzerActions(DiagnosticAnalyzer analyzer) { AnalyzerActions actions; if (!_analyzerActions.TryGetValue(analyzer, out actions)) { actions = new AnalyzerActions(); _analyzerActions[analyzer] = actions; } return actions; } } /// <summary> /// Actions registered by a particular analyzer. /// </summary> // ToDo: AnalyzerActions, and all of the mechanism around it, can be eliminated if the IDE diagnostic analyzer driver // moves from an analyzer-centric model to an action-centric model. For example, the driver would need to stop asking // if a particular analyzer can analyze syntax trees, and instead ask if any syntax tree actions are present. Also, // the driver needs to apply all relevant actions rather then applying the actions of individual analyzers. internal sealed class AnalyzerActions { private ImmutableArray<CompilationStartAnalyzerAction> _compilationStartActions = ImmutableArray<CompilationStartAnalyzerAction>.Empty; private ImmutableArray<CompilationAnalyzerAction> _compilationEndActions = ImmutableArray<CompilationAnalyzerAction>.Empty; private ImmutableArray<CompilationAnalyzerAction> _compilationActions = ImmutableArray<CompilationAnalyzerAction>.Empty; private ImmutableArray<SyntaxTreeAnalyzerAction> _syntaxTreeActions = ImmutableArray<SyntaxTreeAnalyzerAction>.Empty; private ImmutableArray<SemanticModelAnalyzerAction> _semanticModelActions = ImmutableArray<SemanticModelAnalyzerAction>.Empty; private ImmutableArray<SymbolAnalyzerAction> _symbolActions = ImmutableArray<SymbolAnalyzerAction>.Empty; private ImmutableArray<AnalyzerAction> _codeBlockStartActions = ImmutableArray<AnalyzerAction>.Empty; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockEndActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; private ImmutableArray<CodeBlockAnalyzerAction> _codeBlockActions = ImmutableArray<CodeBlockAnalyzerAction>.Empty; private ImmutableArray<OperationBlockStartAnalyzerAction> _operationBlockStartActions = ImmutableArray<OperationBlockStartAnalyzerAction>.Empty; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockEndActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; private ImmutableArray<OperationBlockAnalyzerAction> _operationBlockActions = ImmutableArray<OperationBlockAnalyzerAction>.Empty; private ImmutableArray<AnalyzerAction> _syntaxNodeActions = ImmutableArray<AnalyzerAction>.Empty; private ImmutableArray<OperationAnalyzerAction> _operationActions = ImmutableArray<OperationAnalyzerAction>.Empty; private bool _concurrent; internal AnalyzerActions() { } public int CompilationStartActionsCount { get { return _compilationStartActions.Length; } } public int CompilationEndActionsCount { get { return _compilationEndActions.Length; } } public int CompilationActionsCount { get { return _compilationActions.Length; } } public int SyntaxTreeActionsCount { get { return _syntaxTreeActions.Length; } } public int SemanticModelActionsCount { get { return _semanticModelActions.Length; } } public int SymbolActionsCount { get { return _symbolActions.Length; } } public int SyntaxNodeActionsCount { get { return _syntaxNodeActions.Length; } } public int OperationActionsCount { get { return _operationActions.Length; } } public int OperationBlockStartActionsCount { get { return _operationBlockStartActions.Length; } } public int OperationBlockEndActionsCount { get { return _operationBlockEndActions.Length; } } public int OperationBlockActionsCount { get { return _operationBlockActions.Length; } } public int CodeBlockStartActionsCount { get { return _codeBlockStartActions.Length; } } public int CodeBlockEndActionsCount { get { return _codeBlockEndActions.Length; } } public int CodeBlockActionsCount { get { return _codeBlockActions.Length; } } public bool Concurrent => _concurrent; internal ImmutableArray<CompilationStartAnalyzerAction> CompilationStartActions { get { return _compilationStartActions; } } internal ImmutableArray<CompilationAnalyzerAction> CompilationEndActions { get { return _compilationEndActions; } } internal ImmutableArray<CompilationAnalyzerAction> CompilationActions { get { return _compilationActions; } } internal ImmutableArray<SyntaxTreeAnalyzerAction> SyntaxTreeActions { get { return _syntaxTreeActions; } } internal ImmutableArray<SemanticModelAnalyzerAction> SemanticModelActions { get { return _semanticModelActions; } } internal ImmutableArray<SymbolAnalyzerAction> SymbolActions { get { return _symbolActions; } } internal ImmutableArray<CodeBlockAnalyzerAction> CodeBlockEndActions { get { return _codeBlockEndActions; } } internal ImmutableArray<CodeBlockAnalyzerAction> CodeBlockActions { get { return _codeBlockActions; } } internal ImmutableArray<CodeBlockStartAnalyzerAction<TLanguageKindEnum>> GetCodeBlockStartActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _codeBlockStartActions.OfType<CodeBlockStartAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal ImmutableArray<SyntaxNodeAnalyzerAction<TLanguageKindEnum>> GetSyntaxNodeActions<TLanguageKindEnum>() where TLanguageKindEnum : struct { return _syntaxNodeActions.OfType<SyntaxNodeAnalyzerAction<TLanguageKindEnum>>().ToImmutableArray(); } internal ImmutableArray<OperationBlockAnalyzerAction> OperationBlockActions { get { return _operationBlockActions; } } internal ImmutableArray<OperationBlockAnalyzerAction> OperationBlockEndActions { get { return _operationBlockEndActions; } } internal ImmutableArray<OperationBlockStartAnalyzerAction> OperationBlockStartActions { get { return _operationBlockStartActions; } } internal ImmutableArray<OperationAnalyzerAction> OperationActions { get { return _operationActions; } } internal void AddCompilationStartAction(CompilationStartAnalyzerAction action) { _compilationStartActions = _compilationStartActions.Add(action); } internal void AddCompilationEndAction(CompilationAnalyzerAction action) { _compilationEndActions = _compilationEndActions.Add(action); } internal void AddCompilationAction(CompilationAnalyzerAction action) { _compilationActions = _compilationActions.Add(action); } internal void AddSyntaxTreeAction(SyntaxTreeAnalyzerAction action) { _syntaxTreeActions = _syntaxTreeActions.Add(action); } internal void AddSemanticModelAction(SemanticModelAnalyzerAction action) { _semanticModelActions = _semanticModelActions.Add(action); } internal void AddSymbolAction(SymbolAnalyzerAction action) { _symbolActions = _symbolActions.Add(action); } internal void AddCodeBlockStartAction<TLanguageKindEnum>(CodeBlockStartAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _codeBlockStartActions = _codeBlockStartActions.Add(action); } internal void AddCodeBlockEndAction(CodeBlockAnalyzerAction action) { _codeBlockEndActions = _codeBlockEndActions.Add(action); } internal void AddCodeBlockAction(CodeBlockAnalyzerAction action) { _codeBlockActions = _codeBlockActions.Add(action); } internal void AddSyntaxNodeAction<TLanguageKindEnum>(SyntaxNodeAnalyzerAction<TLanguageKindEnum> action) where TLanguageKindEnum : struct { _syntaxNodeActions = _syntaxNodeActions.Add(action); } internal void AddOperationBlockStartAction(OperationBlockStartAnalyzerAction action) { _operationBlockStartActions = _operationBlockStartActions.Add(action); } internal void AddOperationBlockAction(OperationBlockAnalyzerAction action) { _operationBlockActions = _operationBlockActions.Add(action); } internal void AddOperationBlockEndAction(OperationBlockAnalyzerAction action) { _operationBlockEndActions = _operationBlockEndActions.Add(action); } internal void AddOperationAction(OperationAnalyzerAction action) { _operationActions = _operationActions.Add(action); } internal void EnableConcurrentExecution() { _concurrent = true; } /// <summary> /// Append analyzer actions from <paramref name="otherActions"/> to actions from this instance. /// </summary> /// <param name="otherActions">Analyzer actions to append</param>. public AnalyzerActions Append(AnalyzerActions otherActions) { if (otherActions == null) { throw new ArgumentNullException(nameof(otherActions)); } AnalyzerActions actions = new AnalyzerActions(); actions._compilationStartActions = _compilationStartActions.AddRange(otherActions._compilationStartActions); actions._compilationEndActions = _compilationEndActions.AddRange(otherActions._compilationEndActions); actions._compilationActions = _compilationActions.AddRange(otherActions._compilationActions); actions._syntaxTreeActions = _syntaxTreeActions.AddRange(otherActions._syntaxTreeActions); actions._semanticModelActions = _semanticModelActions.AddRange(otherActions._semanticModelActions); actions._symbolActions = _symbolActions.AddRange(otherActions._symbolActions); actions._codeBlockStartActions = _codeBlockStartActions.AddRange(otherActions._codeBlockStartActions); actions._codeBlockEndActions = _codeBlockEndActions.AddRange(otherActions._codeBlockEndActions); actions._codeBlockActions = _codeBlockActions.AddRange(otherActions._codeBlockActions); actions._syntaxNodeActions = _syntaxNodeActions.AddRange(otherActions._syntaxNodeActions); actions._operationActions = _operationActions.AddRange(otherActions._operationActions); actions._operationBlockStartActions = _operationBlockStartActions.AddRange(otherActions._operationBlockStartActions); actions._operationBlockEndActions = _operationBlockEndActions.AddRange(otherActions._operationBlockEndActions); actions._operationBlockActions = _operationBlockActions.AddRange(otherActions._operationBlockActions); actions._concurrent = actions._concurrent || otherActions.Concurrent; return actions; } } }
48.475877
214
0.701855
[ "Apache-2.0" ]
ObsidianMinor/roslyn
src/Compilers/Core/Portable/DiagnosticAnalyzer/DiagnosticStartAnalysisScope.cs
44,212
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Deployment.Application; using System.Drawing; using System.Linq; using System.Threading; using System.Windows.Forms; using static OSS_EXP4.Eprocess; using Timer = System.Timers.Timer; namespace OSS_EXP4 { public partial class MainForm : Form { public static double Seconds = 1000; private Boolean IsStart = false; private Timer timer; // private string spaceMargin = " "; private void SetTimer() { // double seconds = 100; timer = new Timer(Seconds); timer.Elapsed += Timer_Elapsed; timer.AutoReset = true; } private void Timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { StartSimulate(); } public MainForm() { InitializeComponent(); Control.CheckForIllegalCrossThreadCalls = false; } private void buttonAdd_Click(object sender, EventArgs e) { if(!IsStart) { Method.AddRanmodProcess(); Init(); } else { if (Method.ProcessArray.Count < 10) { Eprocess p = new Eprocess(); var seed = Guid.NewGuid().GetHashCode(); Random r = new Random(seed); int Rname = r.Next(1, 10000); // 增加相同id的重新分配 int Rprimary = r.Next(50, 100); int Rtimes = r.Next(1, 50); p.status = 1; p.name = Rname; p.primary = Rprimary; p.times = Rtimes; RR.Add(new Eprocess(p.name, p.status, p.primary, p.times)); DP.Add(new Eprocess(p.name, p.status, p.primary, p.times)); SRT.Add(new Eprocess(p.name, p.status, p.primary, p.times)); SPN.Add(new Eprocess(p.name, p.status, p.primary, p.times)); } } } private void buttonAddMax_Click(object sender, EventArgs e) { Method.CreateRandomProcess(Method.MaxProcess); Init(); } private void buttonSimulate_Click(object sender, EventArgs e) { IsStart = true; SetTimer(); timer.Start(); // Init(); // StartSimulate(); label_Working.Visible = true; label_Working.Text = "调度中"; txtb_speed.Enabled = false; btn_SetTime.Enabled = false; } private void button_Reset_Click(object sender, EventArgs e) { Method.ClearArray(); Init(); if(timer != null) { timer.Stop(); } IsStart = false; label_Working.Visible = false; AllProgressBarReset(); txtb_speed.Text = "500"; txtb_speed.Enabled = true; btn_SetTime.Enabled = true; } private static List<Eprocess> RR = new List<Eprocess>(); private static List<Eprocess> DP = new List<Eprocess>(); private static List<Eprocess> SRT = new List<Eprocess>(); private static List<Eprocess> SPN = new List<Eprocess>(); private void StartSimulate() { // 增加每一段时间进行Update的控制 ; RR = Method.RR(RR); DP = Method.DP(DP); SRT = Method.SRT(SRT); //? SPN = Method.SPN(SPN); Update(RR, DP, SRT, SPN); if (SRT.Count == 0 && DP.Count == 0 && SPN.Count == 0 && RR.Count == 0) { SRTListView.Items.Clear(); DPListView.Items.Clear(); SPNListView.Items.Clear(); RRListView.Items.Clear(); timer.Stop(); IsStart = false; label_Working.Text = "调度结束"; } } private void Update(List<Eprocess> RR, List<Eprocess> DP, List<Eprocess> SRT, List<Eprocess> SPN) { double[] RRArray = new double[10]; double[] DPArray = new double[10]; double[] SRTArray = new double[10]; double[] SPNArray = new double[10]; RRListView.Items.Clear(); for (int i = 0; i < RR.Count; ++i) { double p = (RR[i].percentage - RR[i].times) / (double)RR[i].percentage; ListViewItem item = new ListViewItem(RR[i].name.ToString()); // item.SubItems.Add((p * 100).ToString()); p *= 100; item.SubItems.Add(p.ToString("F1") + "%"); item.SubItems.Add(RR[i].primary.ToString()); item.SubItems.Add(RR[i].times.ToString()); item.SubItems.Add(RR[i].status.ToString()); RRListView.Items.Add(item); RRArray[i] = p; // https://stackoverflow.com/questions/39181805/accessing-progressbar-in-listview } DPListView.Items.Clear(); for (int i = 0; i < DP.Count; ++i) { double p = (DP[i].percentage - DP[i].times) / (double)DP[i].percentage; ListViewItem item = new ListViewItem(DP[i].name.ToString()); p *= 100; item.SubItems.Add(p.ToString("F1") + "%"); item.SubItems.Add(DP[i].primary.ToString()); item.SubItems.Add(DP[i].times.ToString()); item.SubItems.Add(DP[i].status.ToString()); DPListView.Items.Add(item); DPArray[i] = p; } /*DP = DP.OrderByDescending(x => x.primary) .ToList();*/ SRTListView.Items.Clear(); for (int i = 0; i < SRT.Count; ++i) { double p = (SRT[i].percentage - SRT[i].times) / (double)SRT[i].percentage; ListViewItem item = new ListViewItem(SRT[i].name.ToString()); p *= 100; item.SubItems.Add(p.ToString("F1") + "%"); item.SubItems.Add(SRT[i].primary.ToString()); item.SubItems.Add(SRT[i].times.ToString()); item.SubItems.Add(SRT[i].status.ToString()); SRTListView.Items.Add(item); SRTArray[i] = p; } /* SRT = SRT.OrderByDescending(x => x.times) .ToList();*/ SPNListView.Items.Clear(); for (int i = 0; i < SPN.Count; ++i) { double p = (SPN[i].percentage - SPN[i].times) / (double)SPN[i].percentage; ListViewItem item = new ListViewItem(SPN[i].name.ToString()); p *= 100; item.SubItems.Add(p.ToString("F1") + "%"); item.SubItems.Add(SPN[i].primary.ToString()); item.SubItems.Add(SPN[i].times.ToString()); item.SubItems.Add(SPN[i].status.ToString()); SPNListView.Items.Add(item); SPNArray[i] = p; } UpdateRRProgressBar(RRArray); UpdateDPProgressBar(DPArray); UpdateSRTProgressBar(SRTArray); UpdateSPNProgressBar(SPNArray); /*SPN.Sort(); // first base on time and then base on Status( 2 => processing 1 => waiting) SPN = SPN.OrderByDescending(x => x.status) .ToList();*/ } // RR DP SRT SPN private void Init() { // https://stackoverflow.com/questions/14007405/how-create-a-new-deep-copy-clone-of-a-listt RR = Method.ProcessArray; DP = Method.ProcessArray.ConvertAll(i => new Eprocess(i.name, i.status, i.primary, i.times)); SRT = Method.ProcessArray.ConvertAll(i => new Eprocess(i.name, i.status, i.primary, i.times)); SPN = Method.ProcessArray.ConvertAll(i => new Eprocess(i.name, i.status, i.primary, i.times)); RRListView.Items.Clear(); for (int i = 0; i < RR.Count; ++i) { double p = 0; // (RR[i].percentage - RR[i].times) / RR[i].percentage; ListViewItem item = new ListViewItem(RR[i].name.ToString()); item.SubItems.Add(p.ToString()); item.SubItems.Add(RR[i].primary.ToString()); item.SubItems.Add(RR[i].times.ToString()); item.SubItems.Add(RR[i].status.ToString()); RRListView.Items.Add(item); /*ProgressBar pb = new ProgressBar(); Rectangle r = item.SubItems[1].Bounds; pb.SetBounds(r.X, r.Y, r.Width, r.Height); pb.Minimum = 0; pb.Maximum = 100; pb.Value = (int)(p * 100); pb.Parent = RRListView; //item.ListView.Controls.Add(pb); pb.Name = "RR" + i;*/ // item.Controls.Add(pb); } DPListView.Items.Clear(); for(int i = 0; i < DP.Count; ++i) { double p = 0; ListViewItem item = new ListViewItem(DP[i].name.ToString()); item.SubItems.Add(p.ToString()); item.SubItems.Add(DP[i].primary.ToString()); item.SubItems.Add(DP[i].times.ToString()); item.SubItems.Add(DP[i].status.ToString()); DPListView.Items.Add(item); } // https://www.techiedelight.com/sort-list-by-multiple-fields-csharp/ DP = DP.OrderByDescending(x => x.primary) .ToList(); SRTListView.Items.Clear(); for (int i = 0; i < SRT.Count; ++i) { double p = 0; ListViewItem item = new ListViewItem(SRT[i].name.ToString()); item.SubItems.Add(p.ToString()); item.SubItems.Add(SRT[i].primary.ToString()); item.SubItems.Add(SRT[i].times.ToString()); item.SubItems.Add(SRT[i].status.ToString()); SRTListView.Items.Add(item); } SRT.Sort(); // base on time SPNListView.Items.Clear(); for (int i = 0; i < SPN.Count; ++i) { double p = 0; ListViewItem item = new ListViewItem(SPN[i].name.ToString()); item.SubItems.Add(p.ToString()); item.SubItems.Add(SPN[i].primary.ToString()); item.SubItems.Add(SPN[i].times.ToString()); item.SubItems.Add(SPN[i].status.ToString()); SPNListView.Items.Add(item); } SPN.Sort(); // first base on time and then base on Status( 2 => processing 1 => waiting) SPN = SPN.OrderByDescending(x => x.status) .ToList(); } private void MainForm_Load(object sender, EventArgs e) { // SetTimer(); } // 如果使用如DP那样的方法 可以瞬间完成进度条的显示, 但是会导致莫名其妙的bug 因为这算是个小hack。就不修了 private void UpdateRRProgressBar(double[] Array) { RRpb0.Value = (int)Array[0]; RRpb1.Value = (int)Array[1]; RRpb2.Value = (int)Array[2]; RRpb3.Value = (int)Array[3]; RRpb4.Value = (int)Array[4]; RRpb5.Value = (int)Array[5]; RRpb6.Value = (int)Array[6]; RRpb7.Value = (int)Array[7]; RRpb8.Value = (int)Array[8]; RRpb9.Value = (int)Array[9]; } private void UpdateDPProgressBar(double[] Array) { DPpb0.Value = (int)Array[0]; //DPpb0.Value = (int)Array[0] - 1; //DPpb0.Value = (int)Array[0]; DPpb1.Value = (int)Array[1]; //DPpb1.Value = (int)Array[1] - 1; //DPpb1.Value = (int)Array[1]; DPpb2.Value = (int)Array[2]; //DPpb2.Value = (int)Array[2] - 1; //DPpb2.Value = (int)Array[2]; DPpb3.Value = (int)Array[3]; //DPpb3.Value = (int)Array[3] - 1; //DPpb3.Value = (int)Array[3]; DPpb4.Value = (int)Array[4]; //DPpb4.Value = (int)Array[4] - 1; //DPpb4.Value = (int)Array[4]; DPpb5.Value = (int)Array[5]; //DPpb5.Value = (int)Array[5] - 1; //DPpb5.Value = (int)Array[5]; DPpb6.Value = (int)Array[6]; //DPpb6.Value = (int)Array[6] - 1; //DPpb6.Value = (int)Array[6]; DPpb7.Value = (int)Array[7]; //DPpb7.Value = (int)Array[7] - 1; //DPpb7.Value = (int)Array[7]; DPpb8.Value = (int)Array[8]; //DPpb8.Value = (int)Array[8] - 1; //DPpb8.Value = (int)Array[8]; DPpb9.Value = (int)Array[9]; //DPpb9.Value = (int)Array[9] - 1; //DPpb9.Value = (int)Array[9]; } private void UpdateSRTProgressBar(double[] Array) { SRTpb0.Value = (int)Array[0]; SRTpb1.Value = (int)Array[1]; SRTpb2.Value = (int)Array[2]; SRTpb3.Value = (int)Array[3]; SRTpb4.Value = (int)Array[4]; SRTpb5.Value = (int)Array[5]; SRTpb6.Value = (int)Array[6]; SRTpb7.Value = (int)Array[7]; SRTpb8.Value = (int)Array[8]; SRTpb9.Value = (int)Array[9]; } private void UpdateSPNProgressBar(double[] Array) { SPNpb0.Value = (int)Array[0]; SPNpb1.Value = (int)Array[1]; SPNpb2.Value = (int)Array[2]; SPNpb3.Value = (int)Array[3]; SPNpb4.Value = (int)Array[4]; SPNpb5.Value = (int)Array[5]; SPNpb6.Value = (int)Array[6]; SPNpb7.Value = (int)Array[7]; SPNpb8.Value = (int)Array[8]; SPNpb9.Value = (int)Array[9]; } private void label6_DoubleClick(object sender, EventArgs e) { if (MessageBox.Show("如果你觉得这个软件有帮助, 请到GitHub点个Star吧.", "嘤嘤嘤", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { System.Diagnostics.Process.Start("https://github.com/Gpeter28/OS_exp4"); } } private void AllProgressBarReset() { RRpb0.Value = 0; RRpb1.Value = 0; RRpb2.Value = 0; RRpb3.Value = 0; RRpb4.Value = 0; RRpb5.Value = 0; RRpb6.Value = 0; RRpb7.Value = 0; RRpb8.Value = 0; RRpb9.Value = 0; DPpb0.Value = 0; DPpb1.Value = 0; DPpb2.Value = 0; DPpb3.Value = 0; DPpb4.Value = 0; DPpb5.Value = 0; DPpb6.Value = 0; DPpb7.Value = 0; DPpb8.Value = 0; DPpb9.Value = 0; SRTpb0.Value = 0; SRTpb1.Value = 0; SRTpb2.Value = 0; SRTpb3.Value = 0; SRTpb4.Value = 0; SRTpb5.Value = 0; SRTpb6.Value = 0; SRTpb7.Value = 0; SRTpb8.Value = 0; SRTpb9.Value = 0; SPNpb0.Value = 0; SPNpb1.Value = 0; SPNpb2.Value = 0; SPNpb3.Value = 0; SPNpb4.Value = 0; SPNpb5.Value = 0; SPNpb6.Value = 0; SPNpb7.Value = 0; SPNpb8.Value = 0; SPNpb9.Value = 0; } private void btn_SetTime_Click(object sender, EventArgs e) { string text = txtb_speed.Text; int num = 1000; try { num = Int32.Parse(text); } catch (FormatException) { MessageBox.Show("错误输入"); } if(num < 100) { MessageBox.Show("错误输入"); } else { MainForm.Seconds = num; MessageBox.Show("成功设置"); } } } }
33.777336
123
0.460977
[ "MIT" ]
Gpeter28/OS_exp4
OSS_EXP4/MainForm.cs
17,202
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Sample.MVC { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddRazorPages(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } } }
28.877193
143
0.616646
[ "MIT" ]
FahadMullaji/Sample.MVC
src/Startup.cs
1,646
C#
using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class PauseMenuHandler : MonoBehaviour { public Object mainMenuScene; public InputHandler inputHandler; public GameObject pauseMenu; public GameObject optionsMenu; [Header("Audio Settings")] public Image audioImage; public Sprite unmuteSymbol; public Sprite muteSymbol; private void Update() { if (Input.GetKeyDown(KeyCode.Escape)) OnPauseClick(); } public void OnResetClick() { GameObject.FindGameObjectWithTag("Fader").GetComponent<ScreenFader>().Fade(this, SceneManager.GetActiveScene().buildIndex); } #region settings-buttons public void OnPauseClick() { bool openPauseMenu = inputHandler.inputEnabled; pauseMenu.SetActive(openPauseMenu); if (!openPauseMenu) optionsMenu.SetActive(openPauseMenu); inputHandler.inputEnabled = !openPauseMenu; } public void OnOptionsClick() { bool openOptionsMenu = pauseMenu.activeInHierarchy; optionsMenu.SetActive(openOptionsMenu); pauseMenu.SetActive(!openOptionsMenu); } public void OnExitClick() { GameObject.FindGameObjectWithTag("Fader").GetComponent<ScreenFader>().Fade(this, 0); } #endregion #region options-buttons public void OnAudioClick() { GameObject music = GameObject.FindGameObjectWithTag("Music"); music.GetComponent<MusicHandler>().TogglePause(); // Change sprite icon if (music.GetComponent<AudioSource>().isPlaying) { // change to playing audioImage.sprite = unmuteSymbol; } else { // change to mute audioImage.sprite = muteSymbol; } } #endregion }
24.702703
131
0.655908
[ "MIT" ]
dayluke/falmouth-ccc
Assets/Scripts/Menu/PauseMenuHandler.cs
1,830
C#
#region license // Copyright (c) HatTrick Labs, LLC. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // The latest version of this file can be found at https://github.com/HatTrickLabs/db-ex #endregion using System; namespace HatTrick.DbEx.Sql.Expression { public partial class Int32FieldExpression<TEntity> : Int32FieldExpression, IEquatable<Int32FieldExpression<TEntity>> where TEntity : class, IDbEntity { #region constructors public Int32FieldExpression(string identifier, string name, EntityExpression entity) : base(identifier, name, entity) { } #endregion #region as public override Int32Element As(string alias) => new Int32SelectExpression(this).As(alias); #endregion #region equals public bool Equals(Int32FieldExpression<TEntity> obj) => obj is Int32FieldExpression<TEntity> && base.Equals(obj); public override bool Equals(object obj) => obj is Int32FieldExpression<TEntity> exp && base.Equals(exp); public override int GetHashCode() => base.GetHashCode(); #endregion } }
32.884615
125
0.685965
[ "Apache-2.0" ]
HatTrickLabs/dbExpression
src/HatTrick.DbEx.Sql/Expression/_Field/Int32FieldExpression{T}.cs
1,710
C#
using CommandLine; using Luban.Common.Protos; using Luban.Common.Utils; using Luban.Job.Cfg.DataCreators; using Luban.Job.Cfg.Defs; using Luban.Job.Cfg.Generate; using Luban.Job.Cfg.Utils; using Luban.Job.Common.Defs; using Luban.Job.Common.Utils; using Luban.Server.Common; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using FileInfo = Luban.Common.Protos.FileInfo; namespace Luban.Job.Cfg { [Controller("cfg")] public class JobController : IJobController { private static readonly NLog.Logger s_logger = NLog.LogManager.GetCurrentClassLogger(); private static bool TryParseArg(List<string> args, out GenArgs options, out string errMsg) { var helpWriter = new StringWriter(); var parser = new Parser(ps => { ps.HelpWriter = helpWriter; }); ; var parseResult = parser.ParseArguments<GenArgs>(args); if (parseResult.Tag == ParserResultType.NotParsed) { errMsg = helpWriter.ToString(); options = null; return false; } else { options = (parseResult as Parsed<GenArgs>).Value; errMsg = null; string inputDataDir = options.InputDataDir; string outputCodeDir = options.OutputCodeDir; string outputDataDir = options.OutputDataDir; var genTypes = options.GenType.Split(',').Select(s => s.Trim()).ToList(); if (genTypes.Any(t => t.StartsWith("code_", StringComparison.Ordinal)) && string.IsNullOrWhiteSpace(outputCodeDir)) { errMsg = "--outputcodedir missing"; return false; } if (genTypes.Any(t => t.StartsWith("data_", StringComparison.Ordinal))) { if (string.IsNullOrWhiteSpace(inputDataDir)) { errMsg = "--inputdatadir missing"; return false; } if (string.IsNullOrWhiteSpace(outputDataDir)) { errMsg = "--outputdatadir missing"; return false; } if (genTypes.Contains("data_resources") && string.IsNullOrWhiteSpace(options.OutputDataResourceListFile)) { errMsg = "--output_data_resource_list_file missing"; return false; } if (genTypes.Contains("output_data_json_monolithic_file") && string.IsNullOrWhiteSpace(options.OutputDataJsonMonolithicFile)) { errMsg = "--output_data_json_monolithic_file missing"; return false; } if (string.IsNullOrWhiteSpace(options.L10nInputTextTableFiles) ^ string.IsNullOrWhiteSpace(options.L10nOutputNotTranslatedTextFile)) { errMsg = "--input_l10n_text_files must be provided with --output_l10n_not_translated_text_file"; return false; } if (genTypes.Contains("data_template") ^ !string.IsNullOrWhiteSpace(options.TemplateDataFile)) { errMsg = "gen_types data_template should use with --template:data:file"; return false; } if (genTypes.Contains("code_template") ^ !string.IsNullOrWhiteSpace(options.TemplateCodeDir)) { errMsg = "gen_types code_template should use with --template:code:dir"; return false; } } if (string.IsNullOrWhiteSpace(options.L10nPatchName) ^ string.IsNullOrWhiteSpace(options.L10nPatchInputDataDir)) { errMsg = "--patch must be provided with --patch_input_data_dir"; return false; } if (options.GenType.Contains("typescript_bin") && !options.ValidateTypescriptRequire(options.GenType, ref errMsg)) { return false; } if (!options.ValidateConvention(ref errMsg)) { return false; } return true; } } public async Task GenAsync(RemoteAgent agent, GenJob rpc) { var res = new GenJobRes() { ErrCode = Luban.Common.EErrorCode.OK, ErrMsg = "succ", FileGroups = new List<FileGroup>(), }; if (!TryParseArg(rpc.Arg.JobArguments, out GenArgs args, out string errMsg)) { res.ErrCode = Luban.Common.EErrorCode.JOB_ARGUMENT_ERROR; res.ErrMsg = errMsg; agent.Session.ReplyRpc<GenJob, GenJobArg, GenJobRes>(rpc, res); return; } var timer = new ProfileTimer(); timer.StartPhase("= gen_all ="); try { string inputDataDir = args.InputDataDir; string outputCodeDir = args.OutputCodeDir; string outputDataDir = args.OutputDataDir; var genTypes = args.GenType.Split(',').Select(s => s.Trim()).ToList(); timer.StartPhase("build defines"); var loader = new CfgDefLoader(agent); await loader.LoadAsync(args.DefineFile); await loader.LoadDefinesFromFileAsync(inputDataDir); timer.EndPhaseAndLog(); var rawDefines = loader.BuildDefines(); TimeZoneInfo timeZoneInfo = string.IsNullOrEmpty(args.L10nTimeZone) ? null : TimeZoneInfo.FindSystemTimeZoneById(args.L10nTimeZone); var excludeTags = args.OutputExcludeTags.Split(',').Select(t => t.Trim().ToLowerInvariant()).Where(t => !string.IsNullOrEmpty(t)).ToList(); var ass = new DefAssembly(args.L10nPatchName, timeZoneInfo, excludeTags, agent); ass.Load(rawDefines, agent, args); List<DefTable> exportTables = ass.GetExportTables(); List<DefTypeBase> exportTypes = ass.GetExportTypes(); bool hasLoadCfgData = false; bool needL10NTextConvert = !string.IsNullOrWhiteSpace(args.L10nInputTextTableFiles); async Task CheckLoadCfgDataAsync() { if (!hasLoadCfgData) { hasLoadCfgData = true; var timer = new ProfileTimer(); timer.StartPhase("load config data"); await DataLoaderUtil.LoadCfgDataAsync(agent, ass, args.InputDataDir, args.L10nPatchName, args.L10nPatchInputDataDir, args.InputConvertDataDir); timer.EndPhaseAndLog(); if (needL10NTextConvert) { ass.InitL10n(args.L10nTextValueFieldName); await DataLoaderUtil.LoadTextTablesAsync(agent, ass, ".", args.L10nInputTextTableFiles); } timer.StartPhase("validate"); var validateCtx = new ValidatorContext(ass, args.ValidateRootDir); await validateCtx.ValidateTables(exportTables); timer.EndPhaseAndLog(); } } var tasks = new List<Task>(); var genCodeFilesInOutputCodeDir = new ConcurrentBag<FileInfo>(); var genDataFilesInOutputDataDir = new ConcurrentBag<FileInfo>(); var genScatteredFiles = new ConcurrentBag<FileInfo>(); foreach (var genType in genTypes) { var ctx = new GenContext() { GenType = genType, Assembly = ass, GenArgs = args, ExportTypes = exportTypes, ExportTables = exportTables, GenCodeFilesInOutputCodeDir = genCodeFilesInOutputCodeDir, GenDataFilesInOutputDataDir = genDataFilesInOutputDataDir, GenScatteredFiles = genScatteredFiles, Tasks = tasks, DataLoader = CheckLoadCfgDataAsync, }; GenContext.Ctx = ctx; var render = RenderFactory.CreateRender(genType); if (render == null) { throw new Exception($"unknown gentype:{genType}"); } if (render is DataRenderBase) { await CheckLoadCfgDataAsync(); } render.Render(ctx); GenContext.Ctx = null; } await Task.WhenAll(tasks.ToArray()); if (needL10NTextConvert) { var notConvertTextList = DataExporterUtil.GenNotConvertTextList(ass.NotConvertTextSet); var md5 = FileUtil.CalcMD5(notConvertTextList); string outputNotConvertTextFile = args.L10nOutputNotTranslatedTextFile; CacheManager.Ins.AddCache(outputNotConvertTextFile, md5, notConvertTextList); genScatteredFiles.Add(new FileInfo() { FilePath = outputNotConvertTextFile, MD5 = md5 }); } if (!genCodeFilesInOutputCodeDir.IsEmpty) { res.FileGroups.Add(new FileGroup() { Dir = outputCodeDir, Files = genCodeFilesInOutputCodeDir.ToList() }); } if (!genDataFilesInOutputDataDir.IsEmpty) { res.FileGroups.Add(new FileGroup() { Dir = outputDataDir, Files = genDataFilesInOutputDataDir.ToList() }); } if (!genScatteredFiles.IsEmpty) { res.ScatteredFiles.AddRange(genScatteredFiles); } } catch (DataCreateException e) { res.ErrCode = Luban.Common.EErrorCode.DATA_PARSE_ERROR; res.ErrMsg = $@" ======================================================================= 解析失败! 文件: {e.OriginDataLocation} 错误位置: {e.DataLocationInFile} Err: {e.OriginErrorMsg} 字段: {e.VariableFullPathStr} ======================================================================= "; res.StackTrace = e.OriginStackTrace; } catch (Exception e) { res.ErrCode = Luban.Common.EErrorCode.JOB_EXCEPTION; res.ErrMsg = $@" ======================================================================= {ExceptionUtil.ExtractMessage(e)} ======================================================================= "; res.StackTrace = e.StackTrace; } DefAssemblyBase.LocalAssebmly = null; timer.EndPhaseAndLog(); agent.Session.ReplyRpc<GenJob, GenJobArg, GenJobRes>(rpc, res); } } }
41.530249
167
0.510111
[ "MIT" ]
bmjoy/luban
src/Luban.Job.Cfg/Source/JobController.cs
11,694
C#
// Commons.Refactorings // // Copyright (c) 2016 Rafael 'Monoman' Teixeira, Managed Commons Team // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Formatting; namespace Commons.CodeAnalysis { [ExportCodeRefactoringProvider(LanguageNames.CSharp, Name = nameof(CodeRefactoringProvider)), Shared] public class CodeRefactoringProvider : Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringProvider { public sealed override async Task ComputeRefactoringsAsync(CodeRefactoringContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); // Find the node at the selection. var node = root.FindNode(context.Span); if (!(node is ClassDeclarationSyntax classDecl) || IsMemberOfSomeClass(classDecl)) { if (node is MemberDeclarationSyntax memberDecl && IsMemberOfSomeClass(memberDecl)) { var action = CodeAction.Create("Split here to a partial", c => Action_BreakIntoPartialFromMemberAsync(context.Document, memberDecl, c)); context.RegisterRefactoring(action); } return; } if (classDecl.HasTooManyMembers()) { var action = CodeAction.Create("Break into partials", c => Action_BreakIntoPartialsAsync(context.Document, classDecl, c)); context.RegisterRefactoring(action); } if (classDecl.HasManyPartialsInSameSource()) { var action = CodeAction.Create("Move partial to new source file", c => Action_SeparatePartialAsync(context.Document, classDecl, c)); context.RegisterRefactoring(action); } if (classDecl.HasManyInSameSource()) { var action = CodeAction.Create("Move class to new source file", c => Action_SeparateClassAsync(context.Document, classDecl, c)); context.RegisterRefactoring(action); } } private static async Task<Solution> Action_BreakIntoPartialFromMemberAsync(Document document, MemberDeclarationSyntax memberDecl, CancellationToken cancellationToken) { var classDecl = FindParentClassDeclaration(memberDecl); var partials = classDecl.Break(memberDecl, cancellationToken); return await document.Update(cancellationToken, root => { var newRoot = root.ReplaceNode(classDecl, partials.First()); var classDeclarations = newRoot.DescendantNodesAndSelf().OfType<ClassDeclarationSyntax>().Where(n => n.Identifier.Text == classDecl.Identifier.Text); var newTypeDecl = classDeclarations.FirstOrDefault(n => n.SpanStart >= classDecl.SpanStart) ?? classDeclarations.FirstOrDefault(); var rootNode = newTypeDecl == null ? newRoot : newRoot.InsertNodesAfter(newTypeDecl, partials.Skip(1)); return Formatter.Format(rootNode, document.Project.Solution.Workspace, cancellationToken: cancellationToken); }); } private static async Task<Solution> Action_BreakIntoPartialsAsync(Document document, ClassDeclarationSyntax classDecl, CancellationToken cancellationToken) { var partials = classDecl.Break(cancellationToken); return await document.Update(cancellationToken, root => { var newRoot = root.ReplaceNode(classDecl, partials.First()); var classDeclarations = newRoot.DescendantNodesAndSelf().OfType<ClassDeclarationSyntax>(); var newTypeDecl = classDeclarations.FirstOrDefault(n => n.Identifier.Text == classDecl.Identifier.Text); var rootNode = newTypeDecl == null ? newRoot : newRoot.InsertNodesAfter(newTypeDecl, partials.Skip(1)); return Formatter.Format(rootNode, document.Project.Solution.Workspace, cancellationToken: cancellationToken); }); } private static async Task<Solution> Action_SeparateClassAsync(Document document, ClassDeclarationSyntax classDecl, CancellationToken cancellationToken) => await ActionInternal_SeparateClassAsync(document, classDecl, cancellationToken, classDecl.Identifier.Text); private static async Task<Solution> Action_SeparatePartialAsync(Document document, ClassDeclarationSyntax classDecl, CancellationToken cancellationToken) => await ActionInternal_SeparateClassAsync(document, classDecl, cancellationToken, classDecl.BuildNewPartialSourceName()); private static async Task<Solution> ActionInternal_SeparateClassAsync(Document document, ClassDeclarationSyntax classDecl, CancellationToken cancellationToken, string newSourceName) { var newCompilationUnit = await classDecl.AsNewCompilationUnitAsync(document, cancellationToken); if (newCompilationUnit == null || cancellationToken.IsCancellationRequested) return document.Project.Solution; var newSolution = await document.Update(cancellationToken, root => { var newRoot = root.RemoveNode(classDecl, SyntaxRemoveOptions.KeepNoTrivia); return Formatter.Format(newRoot, document.Project.Solution.Workspace, cancellationToken: cancellationToken); }); return cancellationToken.IsCancellationRequested ? document.Project.Solution : document.AddDerivedDocument(newSolution, newSourceName, newCompilationUnit); } private static T FindParent<T>(SyntaxNode node) where T : SyntaxNode => node switch { null => null, T _ => (T)node, _ => FindParent<T>(node.Parent), }; private static ClassDeclarationSyntax FindParentClassDeclaration(MemberDeclarationSyntax memberDecl) => FindParent<ClassDeclarationSyntax>(memberDecl.Parent); private static bool IsMemberOfSomeClass(MemberDeclarationSyntax memberDecl) => FindParentClassDeclaration(memberDecl) != null; } }
57.492537
285
0.680685
[ "MIT" ]
managed-commons/commons.refactorings
Commons.Refactorings/CodeRefactoringProvider.cs
7,704
C#
using System; using System.Xml.Linq; using Brimborium.WebDavServer.Model; namespace Brimborium.WebDavServer.Locking { /// <summary> /// The lock share mode /// </summary> public struct LockShareMode : IEquatable<LockShareMode> { /// <summary> /// Gets the default <c>shared</c> lock share mode /// </summary> public static readonly LockShareMode Shared = new LockShareMode(SharedId, new lockscope() { ItemElementName = ItemChoiceType.shared, Item = new object(), }); /// <summary> /// Gets the default <c>exclusive</c> lock share mode /// </summary> public static readonly LockShareMode Exclusive = new LockShareMode(ExclusiveId, new lockscope() { ItemElementName = ItemChoiceType.exclusive, Item = new object(), }); private const string SharedId = "shared"; private const string ExclusiveId = "exclusive"; private LockShareMode(string id, lockscope xmlValue) { if (id == null) { throw new ArgumentNullException(nameof(id)); } this.Name = WebDavXml.Dav + id; this.XmlValue = xmlValue; } /// <summary> /// Gets the XML name of the lock share mode /// </summary> public XName Name { get; } /// <summary> /// Gets the <see cref="lockscope"/> element for this lock share mode /// </summary> public lockscope XmlValue { get; } /// <summary> /// Compares two lock share modes for their equality /// </summary> /// <param name="x">The first lock share mode to compare</param> /// <param name="y">The second lock share mode to compare</param> /// <returns><see langword="true"/> when both lock share modes are of equal value</returns> public static bool operator ==(LockShareMode x, LockShareMode y) { return x.Name == y.Name; } /// <summary> /// Compares two lock share modes for their inequality /// </summary> /// <param name="x">The first lock share mode to compare</param> /// <param name="y">The second lock share mode to compare</param> /// <returns><see langword="true"/> when both lock share modes are not of equal value</returns> public static bool operator !=(LockShareMode x, LockShareMode y) { return x.Name != y.Name; } /// <summary> /// Parses the given lock share mode value and returns the corresponding <see cref="LockShareMode"/> instance. /// </summary> /// <param name="shareMode">The share mode to parse</param> /// <returns>The corresponding <see cref="LockShareMode"/></returns> public static LockShareMode Parse(string shareMode) { if (shareMode == null) { throw new ArgumentNullException(nameof(shareMode)); } switch (shareMode.ToLowerInvariant()) { case SharedId: return Shared; case ExclusiveId: return Exclusive; } throw new ArgumentOutOfRangeException(nameof(shareMode), $"The share mode {shareMode} is not supported."); } /// <inheritdoc /> public bool Equals(LockShareMode other) { return this.Name.Equals(other.Name); } /// <inheritdoc /> public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) { return false; } return obj is LockShareMode && this.Equals((LockShareMode)obj); } /// <inheritdoc /> public override int GetHashCode() { return this.Name.GetHashCode(); } } }
35.284404
118
0.567863
[ "MIT" ]
FlorianGrimm/Brimborium.Net
Brimborium.WebDavServer/Brimborium.WebDavServer/Locking/LockShareMode.cs
3,848
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Tem.V20210701.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class MountedSettingConf : AbstractModel { /// <summary> /// Configuration name /// </summary> [JsonProperty("ConfigDataName")] public string ConfigDataName{ get; set; } /// <summary> /// Mount point path /// </summary> [JsonProperty("MountedPath")] public string MountedPath{ get; set; } /// <summary> /// Configuration content /// </summary> [JsonProperty("Data")] public Pair[] Data{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "ConfigDataName", this.ConfigDataName); this.SetParamSimple(map, prefix + "MountedPath", this.MountedPath); this.SetParamArrayObj(map, prefix + "Data.", this.Data); } } }
30.724138
85
0.630191
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet-intl-en
TencentCloud/Tem/V20210701/Models/MountedSettingConf.cs
1,782
C#
using Autofac; using PVScan.Core; using PVScan.Core.Services.Interfaces; using PVScan.Mobile.Services; using PVScan.Core.Services.Interfaces; using PVScan.Mobile.Views; using System; using Xamarin.Essentials; using Xamarin.Forms; using Xamarin.Forms.PlatformConfiguration; using Xamarin.Forms.PlatformConfiguration.iOSSpecific; using Xamarin.Forms.Svg; using Xamarin.Forms.Xaml; using PVScan.Mobile.Services.Interfaces; namespace PVScan.Mobile { public partial class App : Xamarin.Forms.Application { public App() { DataAccess.Init(System.IO.Path.Combine(FileSystem.AppDataDirectory, "PVScan.db3")); InitializeTheme(); InitializeComponent(); SvgImageSource.RegisterAssembly(); var mainPage = Resolver.Resolve<MainPage>(); InitializePopupService(mainPage); var navigationPage = new Xamarin.Forms.NavigationPage(mainPage); navigationPage.On<iOS>().SetHideNavigationBarSeparator(false); navigationPage.SetOnAppTheme(Xamarin.Forms.NavigationPage.BarTextColorProperty, Color.Black, Color.White); MainPage = navigationPage; } private async void InitializeTheme() { using var scope = Resolver.Container.BeginLifetimeScope(); var kvp = scope.Resolve<IPersistentKVP>(); string themeSelected = await kvp.Get(StorageKeys.Theme, null); if (themeSelected == null) { // User hasn't changed the app theme yet, use system theme. UserAppTheme = RequestedTheme; } else { UserAppTheme = themeSelected == "Light" ? OSAppTheme.Light : OSAppTheme.Dark; } RequestedThemeChanged += (s, e) => { // Respond to user device theme change if option is set? }; } private void InitializePopupService(MainPage mainPage) { var popupService = (Resolver.Resolve<IPopupMessageService>() as PopupMessageService); popupService.Initialize(mainPage.PopupMessageBox, mainPage.PopupMessageLabel); } protected override async void OnStart() { using var scope = Resolver.Container.BeginLifetimeScope(); var identity = scope.Resolve<IIdentityService>(); var barcodeHub = scope.Resolve<IAPIBarcodeHub>(); var userInfoHub = scope.Resolve<IAPIUserInfoHub>(); await identity.Initialize(); if (identity.AccessToken != null) { await barcodeHub.Connect(); await userInfoHub.Connect(); } } protected override void OnSleep() { } protected override void OnResume() { } } }
30.221053
118
0.61442
[ "MIT" ]
meJevin/PVScan
Source/Mobile/PVScan.Mobile/App.xaml.cs
2,873
C#
using System.Windows; using System.Windows.Controls; using Appli.Navigator; using Modele; namespace Appli { /// <summary> /// Logique d'interaction pour Accueil.xaml /// </summary> public partial class Accueil : UserControl { private static Manager Man => (Application.Current as App)?.Man; public Accueil() { InitializeComponent(); Populaires.DataContext = Man.RendreListePopulaire(Man.ConnectedUser); Consultes.DataContext = Man; Add.DataContext = Man.ConnectedUser; } private void List_OnSelected(object sender, RoutedEventArgs e) => GeneralNavigator.ListSelected(sender); private void Add_OnClick(object sender, RoutedEventArgs e) { Man.CurrentOeuvre = null; GeneralNavigator.NewOeuvre(); } } }
27
112
0.635417
[ "MIT" ]
iShoFen/Cinema
Source/Cinema/Appli/Accueil.xaml.cs
866
C#
using System.Collections.Generic; using Brainiac.Serialization; namespace Brainiac { public abstract class Composite : BehaviourNode { [BTProperty("Children")] [BTHideInInspector] protected List<BehaviourNode> m_children; [BTIgnore] public int ChildCount { get { return m_children.Count; } } public Composite() { m_children = new List<BehaviourNode>(); } public override void OnBeforeSerialize(BTAsset btAsset) { base.OnBeforeSerialize(btAsset); for(int i = 0; i < m_children.Count; i++) { m_children[i].OnBeforeSerialize(btAsset); } } public override void OnAfterDeserialize(BTAsset btAsset) { base.OnAfterDeserialize(btAsset); for(int i = 0; i < m_children.Count; i++) { m_children[i].OnAfterDeserialize(btAsset); } } public override void OnStart(AIAgent agent) { for(int i = 0; i < m_children.Count; i++) { m_children[i].OnStart(agent); } } public override void OnReset() { base.OnReset(); for(int i = 0; i < m_children.Count; i++) { m_children[i].OnReset(); } } public void AddChild(BehaviourNode child) { if(child != null) { m_children.Add(child); } } public void InsertChild(int index, BehaviourNode child) { if(child != null) { m_children.Insert(index, child); } } public void RemoveChild(BehaviourNode child) { if(child != null) { m_children.Remove(child); } } public void RemoveChild(int index) { if(index >= 0 && index < m_children.Count) { m_children.RemoveAt(index); } } public void RemoveAllChildren() { m_children.Clear(); } public void MoveChildPriorityUp(int index) { if(index > 0 && index < m_children.Count) { var temp = m_children[index]; m_children[index] = m_children[index - 1]; m_children[index - 1] = temp; } } public void MoveChildPriorityDown(int index) { if(index >= 0 && index < m_children.Count - 1) { var temp = m_children[index]; m_children[index] = m_children[index + 1]; m_children[index + 1] = temp; } } public BehaviourNode GetChild(int index) { if (index >= 0 && index < m_children.Count) return m_children[index]; else return null; } } }
17.635659
58
0.632967
[ "MIT" ]
CloudDevStudios/Brainiac
Assets/Brainiac/Source/Runtime/Core/Composite.cs
2,275
C#