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
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("Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Universiteit Gent")] [assembly: AssemblyProduct("Tests")] [assembly: AssemblyCopyright("Copyright © Universiteit Gent 2015")] [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("71780abb-f98c-4672-b156-a702025c8f29")] // 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")]
39.27027
85
0.728837
[ "MIT" ]
ilyanevolin/ForumAnalyzerPro
Tests/Properties/AssemblyInfo.cs
1,456
C#
/* _BEGIN_TEMPLATE_ { "id": "TB_BaconShop_HP_041b", "name": [ "机械之王", "King of Mechs" ], "text": [ "<b>被动英雄技能</b>\n每当你购买一个<b>机械</b>,使其获得+1/+2。每回合切换类型。", "[x]<b>Passive Hero Power</b>\nWhenever you buy a\n<b>Mech</b>, give it +1/+2.\nSwaps type each turn." ], "CardClass": "NEUTRAL", "type": "HERO_POWER", "cost": 0, "rarity": null, "set": "BATTLEGROUNDS", "collectible": null, "dbfId": 59853 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_TB_BaconShop_HP_041b : SimTemplate { } }
19.357143
106
0.595941
[ "MIT" ]
chi-rei-den/Silverfish
cards/BATTLEGROUNDS/TB/Sim_TB_BaconShop_HP_041b.cs
608
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Util; using Util.Applications.Dtos; namespace GreatWall.Service.Dtos { /// <summary> /// 身份资源参数 /// </summary> public class IdentityResourceDto : DtoBase { /// <summary> /// 资源标识 /// </summary> [StringLength( 300 )] [Display( Name = "资源标识" )] [Required( ErrorMessage = "资源标识不能为空" )] public string Uri { get; set; } /// <summary> /// 显示名称 /// </summary> [StringLength( 200 )] [Display( Name = "显示名称" )] public string Name { get; set; } /// <summary> /// 描述 /// </summary> [StringLength( 500 )] [Display( Name = "描述" )] public string Remark { get; set; } /// <summary> /// 必选 /// </summary> [Display( Name = "必选" )] public bool? Required { get; set; } /// <summary> /// 强调 /// </summary> [Display( Name = "强调" )] public bool? Emphasize { get; set; } /// <summary> /// 发现文档中显示 /// </summary> [Display( Name = "发现文档中显示" )] public bool? ShowInDiscoveryDocument { get; set; } /// <summary> /// 启用 /// </summary> [Display( Name = "启用" )] public bool? Enabled { get; set; } /// <summary> /// 用户声明 /// </summary> [Display( Name = "用户声明" )] public List<string> Claims { get; set; } /// <summary> /// 用户声明 /// </summary> [Display( Name = "用户声明" )] public string ClaimsDisplay => Claims.Join(); /// <summary> /// 排序号 /// </summary> [Display( Name = "排序号" )] public int? SortId { get; set; } /// <summary> /// 创建时间 /// </summary> [Display( Name = "创建时间" )] public DateTime? CreationTime { get; set; } /// <summary> /// 创建人标识 /// </summary> [Display( Name = "创建人标识" )] public Guid? CreatorId { get; set; } /// <summary> /// 最后修改时间 /// </summary> [Display( Name = "最后修改时间" )] public DateTime? LastModificationTime { get; set; } /// <summary> /// 最后修改人标识 /// </summary> [Display( Name = "最后修改人标识" )] public Guid? LastModifierId { get; set; } /// <summary> /// 版本号 /// </summary> [Display( Name = "版本号" )] public Byte[] Version { get; set; } } }
28.054348
59
0.456412
[ "MIT" ]
UtilCore/GreatWall
src/GreatWall.Service/Dtos/IdentityResourceDto.cs
2,847
C#
using System.Collections.Generic; using System.Linq; namespace Engine.StrategyPattern.PatternVersion { public class AverageByMedian : IAveragingMethod { public double AverageFor(List<double> values) { // Median average is the middle value of the values in the list. var sortedValues = values.OrderBy(x => x).ToList(); // Use the "%" (modulus) to determine if there is an even, or odd, number of values. if(sortedValues.Count % 2 == 1) { // Number of values is odd. // Return the middle value of the sorted list. // REMEMBER: The list's index is zero-based, so we subtract 1, instead of adding 1, // to determine which element of the list to return return sortedValues[(sortedValues.Count - 1) / 2]; } // Number of values is even. // Return the mean average of the two middle values. // REMEMBER: The list's index is zero-based, so we subtract 1, instead of adding 1, // to determine which elements of the list to use return (sortedValues[(sortedValues.Count / 2) - 1] + sortedValues[sortedValues.Count / 2]) / 2; } } }
40.875
99
0.574159
[ "MIT" ]
ScottLilly/CSharpDesignPatterns
Engine/StrategyPattern/PatternVersion/AverageByMedian.cs
1,310
C#
using System.Linq; using MongoFramework.Infrastructure.Mapping; namespace MongoFramework.Infrastructure.Linq { public static class QueryHelper { public static string GetQuery<TEntity>(AggregateExecutionModel model) { var entityDefinition = EntityMapping.GetOrCreateDefinition(typeof(TEntity)); var stages = string.Join(", ", model.Stages.Select(x => x.ToString())); return $"db.{entityDefinition.CollectionName}.aggregate([{stages}])"; } } }
28.875
79
0.757576
[ "MIT" ]
bobbyangers/MongoFramework
src/MongoFramework/Infrastructure/Linq/QueryHelper.cs
464
C#
using System.Collections.Generic; using Content.Server.Cargo; using Robust.Shared.GameObjects.Systems; namespace Content.Server.GameObjects.EntitySystems { public class CargoConsoleSystem : EntitySystem { /// <summary> /// How much time to wait (in seconds) before increasing bank accounts balance. /// </summary> private const float Delay = 10f; /// <summary> /// How many points to give to every bank account every <see cref="Delay"/> seconds. /// </summary> private const int PointIncrease = 10; /// <summary> /// Keeps track of how much time has elapsed since last balance increase. /// </summary> private float _timer; /// <summary> /// Stores all bank accounts. /// </summary> private readonly Dictionary<int, CargoBankAccount> _accountsDict = new Dictionary<int, CargoBankAccount>(); /// <summary> /// Used to assign IDs to bank accounts. Incremental counter. /// </summary> private int _accountIndex = 0; /// <summary> /// Enumeration of all bank accounts. /// </summary> public IEnumerable<CargoBankAccount> BankAccounts => _accountsDict.Values; /// <summary> /// The station's bank account. /// </summary> public CargoBankAccount StationAccount => GetBankAccount(0); public override void Initialize() { CreateBankAccount("Orbital Monitor IV Station", 100000); } public override void Update(float frameTime) { _timer += frameTime; if (_timer < Delay) { return; } _timer -= Delay; foreach (var account in BankAccounts) { account.Balance += PointIncrease; } } /// <summary> /// Creates a new bank account. /// </summary> public void CreateBankAccount(string name, int balance) { var account = new CargoBankAccount(_accountIndex, name, balance); _accountsDict.Add(_accountIndex, account); _accountIndex += 1; } /// <summary> /// Returns the bank account associated with the given ID. /// </summary> public CargoBankAccount GetBankAccount(int id) { return _accountsDict[id]; } /// <summary> /// Returns whether the account exists, eventually passing the account in the out parameter. /// </summary> public bool TryGetBankAccount(int id, out CargoBankAccount account) { return _accountsDict.TryGetValue(id, out account); } /// <summary> /// Attempts to change the given account's balance. /// Returns false if there's no account associated with the given ID /// or if the balance would end up being negative. /// </summary> public bool ChangeBalance(int id, int amount) { if (!TryGetBankAccount(id, out var account)) { return false; } if (account.Balance + amount < 0) { return false; } account.Balance += amount; return true; } } }
31.485981
115
0.554764
[ "MIT" ]
ALMv1/space-station-14
Content.Server/GameObjects/EntitySystems/CargoConsoleSystem.cs
3,371
C#
using System.Threading.Tasks; using InfluxDB.Client.Core.Exceptions; using NUnit.Framework; using WireMock.RequestBuilders; using WireMock.ResponseBuilders; namespace Client.Legacy.Test { public class FluxClientVersionTest : AbstractFluxClientTest { [Test] public async Task Version() { MockServer.Given(Request.Create().WithPath("/ping").UsingGet()) .RespondWith(Response.Create().WithStatusCode(204) .WithHeader("X-Influxdb-Version", "1.7.0")); Assert.AreEqual("1.7.0", await FluxClient.VersionAsync()); } [Test] public async Task VersionUnknown() { MockServer.Given(Request.Create().WithPath("/ping").UsingGet()) .RespondWith(Response.Create().WithStatusCode(204)); Assert.AreEqual("unknown", await FluxClient.VersionAsync()); } [Test] public async Task Error() { MockServer.Stop(); try { await FluxClient.VersionAsync(); Assert.Fail(); } catch (InfluxException e) { Assert.IsNotEmpty(e.Message); } } } }
26.680851
75
0.555024
[ "MIT" ]
bonitoo-io/flux-csharp
Client.Legacy.Test/FluxClientVersionTest.cs
1,254
C#
using System; namespace DirectX12GameEngine.Graphics { public class DepthStencilView : ResourceView { public DepthStencilView(GraphicsResource resource) : base(resource, CreateDepthStencilView(resource)) { } private static IntPtr CreateDepthStencilView(GraphicsResource resource) { IntPtr cpuHandle = resource.GraphicsDevice.DepthStencilViewAllocator.Allocate(1); resource.GraphicsDevice.NativeDevice.CreateDepthStencilView(resource.NativeResource, null, cpuHandle.ToCpuDescriptorHandle()); return cpuHandle; } } }
30.75
138
0.710569
[ "MIT" ]
5l1v3r1/DirectX12GameEngine
DirectX12GameEngine.Graphics/DepthStencilView.cs
617
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Text; namespace January23rd { public class LuckyNumbers : IEnumerable<int> { public IEnumerator<int> GetEnumerator() { yield return 1; yield return 2; yield return 3; yield return 4; yield return 5; } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } public class Fibonacci : IEnumerable<int> { int previous; int current; public Fibonacci() { previous = 0; current = 1; } public IEnumerator<int> GetEnumerator() { int next; do { yield return current; next = current + previous; previous = current; current = next; } while (next > 0); } IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); } } public abstract class Polygon { public int numberOfSides { get; private set;} protected int[] sideLengths; public Polygon(int numberOfSides) { this.numberOfSides = numberOfSides; sideLengths = new int[numberOfSides]; } public virtual void setSideLength(int sideNumber, int sideLength) { if ( sideNumber < 0 || sideNumber >= sideLengths.Length) { throw new ArgumentOutOfRangeException(); } sideLengths[sideNumber] = sideLength; } public int getSideLength(int sideNumber) { if (sideNumber < 0 || sideNumber >= sideLengths.Length) { throw new ArgumentOutOfRangeException(); } return sideLengths[sideNumber]; } public int GetPerimeter() { int perimeter = 0; foreach( var sideLength in sideLengths ) { perimeter += sideLength; } return perimeter; } public abstract int getArea(); } public class Rectangle : Polygon, IEquatable<Rectangle>, IComparable<Rectangle> { public Rectangle() : base(4) { // empty } public void setWidth(int width) { base.setSideLength(1, width); base.setSideLength(3, width); } public void setLength(int length) { base.setSideLength(0, length); base.setSideLength(2, length); } public override void setSideLength(int sideNumber, int sideLength) { throw new InvalidOperationException("You can't side just 1 side of a rectangle, it breaks the law"); } public override int getArea() { return getSideLength(0) * getSideLength(1); } public bool Equals(Rectangle other) { return getSideLength(0) == other.getSideLength(0) && getSideLength(1) == other.getSideLength(1); } int IComparable<Rectangle>.CompareTo(Rectangle other) { return getArea() - other.getArea(); } } }
24.856115
112
0.520405
[ "MIT" ]
EricCharnesky/CIS297-Winter2020
January23rd/January23rd/Class1.cs
3,457
C#
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.Collections; using System.Globalization; using System.Collections.Generic; using System.IO; using System.Text; using System.Management.Automation.Language; using System.Text.RegularExpressions; #if CORECLR // Use stub for SerializableAttribute. using Microsoft.PowerShell.CoreClr.Stubs; #endif namespace System.Management.Automation { /// <summary> /// Class describing a PowerShell module... /// </summary> [Serializable] internal class ScriptAnalysis { internal static ScriptAnalysis Analyze(string path, ExecutionContext context) { ModuleIntrinsics.Tracer.WriteLine("Analyzing path: {0}", path); try { if (Utils.PathIsUnc(path) && (context.CurrentCommandProcessor.CommandRuntime != null)) { ProgressRecord analysisProgress = new ProgressRecord(0, Modules.ScriptAnalysisPreparing, String.Format(CultureInfo.InvariantCulture, Modules.ScriptAnalysisModule, path)); analysisProgress.RecordType = ProgressRecordType.Processing; // Write the progress using a static source ID so that all // analysis messages get single-threaded in the progress pane (rather than nesting). context.CurrentCommandProcessor.CommandRuntime.WriteProgress(typeof(ScriptAnalysis).FullName.GetHashCode(), analysisProgress); } } catch (InvalidOperationException) { // This may be called when we are not allowed to write progress, // So eat the invalid operation } string scriptContent = ReadScript(path); ParseError[] errors; var moduleAst = (new Parser()).Parse(path, scriptContent, null, out errors, ParseMode.ModuleAnalysis); // Don't bother analyzing if there are syntax errors (we don't do semantic analysis which would // detect other errors that we also might choose to ignore, but it's slower.) if (errors.Length > 0) return null; ExportVisitor exportVisitor = new ExportVisitor(forCompletion: false); moduleAst.Visit(exportVisitor); var result = new ScriptAnalysis { DiscoveredClasses = exportVisitor.DiscoveredClasses, DiscoveredExports = exportVisitor.DiscoveredExports, DiscoveredAliases = new Dictionary<string, string>(), DiscoveredModules = exportVisitor.DiscoveredModules, DiscoveredCommandFilters = exportVisitor.DiscoveredCommandFilters, AddsSelfToPath = exportVisitor.AddsSelfToPath }; if (result.DiscoveredCommandFilters.Count == 0) { result.DiscoveredCommandFilters.Add("*"); } else { // Post-process aliases, as they are not exported by default List<WildcardPattern> patterns = new List<WildcardPattern>(); foreach (string discoveredCommandFilter in result.DiscoveredCommandFilters) { patterns.Add(WildcardPattern.Get(discoveredCommandFilter, WildcardOptions.IgnoreCase)); } foreach (var pair in exportVisitor.DiscoveredAliases) { string discoveredAlias = pair.Key; if (SessionStateUtilities.MatchesAnyWildcardPattern(discoveredAlias, patterns, defaultValue: false)) { result.DiscoveredAliases[discoveredAlias] = pair.Value; } } } return result; } internal static string ReadScript(string path) { using (FileStream readerStream = new FileStream(path, FileMode.Open, FileAccess.Read)) { Encoding defaultEncoding = ClrFacade.GetDefaultEncoding(); Microsoft.Win32.SafeHandles.SafeFileHandle safeFileHandle = readerStream.SafeFileHandle; using (StreamReader scriptReader = new StreamReader(readerStream, defaultEncoding)) { return scriptReader.ReadToEnd(); } } } internal List<string> DiscoveredExports { get; set; } internal Dictionary<string, string> DiscoveredAliases { get; set; } internal List<RequiredModuleInfo> DiscoveredModules { get; set; } internal List<string> DiscoveredCommandFilters { get; set; } internal bool AddsSelfToPath { get; set; } internal List<TypeDefinitionAst> DiscoveredClasses { get; set; } } // Defines the visitor that analyzes a script to determine its exports // and dependencies. internal class ExportVisitor : AstVisitor2 { internal ExportVisitor(bool forCompletion) { _forCompletion = forCompletion; DiscoveredExports = new List<string>(); DiscoveredFunctions = new Dictionary<string, FunctionDefinitionAst>(StringComparer.OrdinalIgnoreCase); DiscoveredAliases = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); DiscoveredModules = new List<RequiredModuleInfo>(); DiscoveredCommandFilters = new List<string>(); DiscoveredClasses = new List<TypeDefinitionAst>(); } static ExportVisitor() { var nameParam = new ParameterInfo { name = "Name", position = 0 }; var valueParam = new ParameterInfo { name = "Value", position = 1 }; var aliasParameterInfo = new ParameterBindingInfo { parameterInfo = new[] { nameParam, valueParam } }; var functionParam = new ParameterInfo { name = "Function", position = -1 }; var cmdletParam = new ParameterInfo { name = "Cmdlet", position = -1 }; var aliasParam = new ParameterInfo { name = "Alias", position = -1 }; var ipmoParameterInfo = new ParameterBindingInfo { parameterInfo = new[] { nameParam, functionParam, cmdletParam, aliasParam } }; functionParam = new ParameterInfo { name = "Function", position = 0 }; var exportModuleMemberInfo = new ParameterBindingInfo { parameterInfo = new[] { functionParam, cmdletParam, aliasParam } }; s_parameterBindingInfoTable = new Dictionary<string, ParameterBindingInfo>(StringComparer.OrdinalIgnoreCase) { {"New-Alias", aliasParameterInfo}, {@"Microsoft.PowerShell.Utility\New-Alias", aliasParameterInfo}, {"Set-Alias", aliasParameterInfo}, {@"Microsoft.PowerShell.Utility\Set-Alias", aliasParameterInfo}, {"nal", aliasParameterInfo}, {"sal", aliasParameterInfo}, {"Import-Module", ipmoParameterInfo}, {@"Microsoft.PowerShell.Core\Import-Module", ipmoParameterInfo}, {"ipmo", ipmoParameterInfo}, {"Export-ModuleMember", exportModuleMemberInfo}, {@"Microsoft.PowerShell.Core\Export-ModuleMember", exportModuleMemberInfo} }; } private readonly bool _forCompletion; internal List<string> DiscoveredExports { get; set; } internal List<RequiredModuleInfo> DiscoveredModules { get; set; } internal Dictionary<string, FunctionDefinitionAst> DiscoveredFunctions { get; set; } internal Dictionary<string, string> DiscoveredAliases { get; set; } internal List<string> DiscoveredCommandFilters { get; set; } internal bool AddsSelfToPath { get; set; } internal List<TypeDefinitionAst> DiscoveredClasses { get; set; } public override AstVisitAction VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) { DiscoveredClasses.Add(typeDefinitionAst); return _forCompletion ? AstVisitAction.Continue : AstVisitAction.SkipChildren; } // Capture simple function definitions public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { // Nested functions are ignored for the purposes of exports, but are still // recorded for command/parameter completion. // function Foo-Bar { ... } var functionName = functionDefinitionAst.Name; DiscoveredFunctions[functionName] = functionDefinitionAst; ModuleIntrinsics.Tracer.WriteLine("Discovered function definition: {0}", functionName); // Check if they've defined any aliases // function Foo-Bar { [Alias("Alias1", "...")] param() ... } var functionBody = functionDefinitionAst.Body; if ((functionBody.ParamBlock != null) && (functionBody.ParamBlock.Attributes != null)) { foreach (AttributeAst attribute in functionBody.ParamBlock.Attributes) { if (attribute.TypeName.GetReflectionAttributeType() == typeof(AliasAttribute)) { foreach (ExpressionAst aliasAst in attribute.PositionalArguments) { var aliasExpression = aliasAst as StringConstantExpressionAst; if (aliasExpression != null) { string alias = aliasExpression.Value; DiscoveredAliases[alias] = functionName; ModuleIntrinsics.Tracer.WriteLine("Function defines alias: {0} = {1}", alias, functionName); } } } } } if (_forCompletion) { if (Ast.GetAncestorAst<ScriptBlockAst>(functionDefinitionAst).Parent == null) { DiscoveredExports.Add(functionName); } return AstVisitAction.Continue; } DiscoveredExports.Add(functionName); return AstVisitAction.SkipChildren; } // Capture modules that add themselves to the path (so they generally package their functionality // as loose PS1 files) public override AstVisitAction VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) { // $env:PATH += "";$psScriptRoot"" if (String.Equals("$env:PATH", assignmentStatementAst.Left.ToString(), StringComparison.OrdinalIgnoreCase) && Regex.IsMatch(assignmentStatementAst.Right.ToString(), "\\$psScriptRoot", RegexOptions.IgnoreCase)) { ModuleIntrinsics.Tracer.WriteLine("Module adds itself to the path."); AddsSelfToPath = true; } return AstVisitAction.SkipChildren; } // We skip a bunch of random statements because we can't really be accurate detecting functions/classes etc. that // are conditionally defined. public override AstVisitAction VisitIfStatement(IfStatementAst ifStmtAst) { return AstVisitAction.SkipChildren; } public override AstVisitAction VisitDataStatement(DataStatementAst dataStatementAst) { return AstVisitAction.SkipChildren; } public override AstVisitAction VisitForEachStatement(ForEachStatementAst forEachStatementAst) { return AstVisitAction.SkipChildren; } public override AstVisitAction VisitForStatement(ForStatementAst forStatementAst) { return AstVisitAction.SkipChildren; } public override AstVisitAction VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) { return AstVisitAction.SkipChildren; } public override AstVisitAction VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) { return AstVisitAction.SkipChildren; } public override AstVisitAction VisitWhileStatement(WhileStatementAst whileStatementAst) { return AstVisitAction.SkipChildren; } public override AstVisitAction VisitInvokeMemberExpression(InvokeMemberExpressionAst methodCallAst) { return AstVisitAction.SkipChildren; } public override AstVisitAction VisitSwitchStatement(SwitchStatementAst switchStatementAst) { return AstVisitAction.SkipChildren; } // Visit one the other variations: // - Dotting scripts // - Setting aliases // - Importing modules // - Exporting module members public override AstVisitAction VisitCommand(CommandAst commandAst) { string commandName = commandAst.GetCommandName() ?? GetSafeValueVisitor.GetSafeValue(commandAst.CommandElements[0], null, GetSafeValueVisitor.SafeValueContext.ModuleAnalysis) as string; if (commandName == null) return AstVisitAction.SkipChildren; // They are trying to dot a script if (commandAst.InvocationOperator == TokenKind.Dot) { // . Foo-Bar4.ps1 // . $psScriptRoot\Foo-Bar.ps1 -Bing Baz // . ""$psScriptRoot\Support Files\Foo-Bar2.ps1"" -Bing Baz // . '$psScriptRoot\Support Files\Foo-Bar3.ps1' -Bing Baz DiscoveredModules.Add( new RequiredModuleInfo { Name = commandName, CommandsToPostFilter = new List<string>() }); ModuleIntrinsics.Tracer.WriteLine("Module dots {0}", commandName); } // They are setting an alias. if (String.Equals(commandName, "New-Alias", StringComparison.OrdinalIgnoreCase) || String.Equals(commandName, "Microsoft.PowerShell.Utility\\New-Alias", StringComparison.OrdinalIgnoreCase) || String.Equals(commandName, "Set-Alias", StringComparison.OrdinalIgnoreCase) || String.Equals(commandName, "Microsoft.PowerShell.Utility\\Set-Alias", StringComparison.OrdinalIgnoreCase) || String.Equals(commandName, "nal", StringComparison.OrdinalIgnoreCase) || String.Equals(commandName, "sal", StringComparison.OrdinalIgnoreCase)) { // Set-Alias Foo-Bar5 Foo-Bar // Set-Alias -Name Foo-Bar6 -Value Foo-Bar // sal Foo-Bar7 Foo-Bar // sal -Value Foo-Bar -Name Foo-Bar8 var boundParameters = DoPsuedoParameterBinding(commandAst, commandName); var name = boundParameters["Name"] as string; if (!string.IsNullOrEmpty(name)) { var value = boundParameters["Value"] as string; if (!string.IsNullOrEmpty(value)) { // These aren't stored in DiscoveredExports, as they are only // exported after the user calls Export-ModuleMember. DiscoveredAliases[name] = value; ModuleIntrinsics.Tracer.WriteLine("Module defines alias: {0} = {1}", name, value); } } return AstVisitAction.SkipChildren; } // They are importing a module if (String.Equals(commandName, "Import-Module", StringComparison.OrdinalIgnoreCase) || String.Equals(commandName, "ipmo", StringComparison.OrdinalIgnoreCase)) { // Import-Module Module1 // Import-Module Module2 -Function Foo-Module2*, Foo-Module2Second* -Cmdlet Foo-Module2Cmdlet,Foo-Module2Cmdlet* // Import-Module Module3 -Function Foo-Module3Command1, Foo-Module3Command2 // Import-Module Module4, // Module5 // Import-Module -Name Module6, // Module7 -Global var boundParameters = DoPsuedoParameterBinding(commandAst, commandName); List<string> commandsToPostFilter = new List<string>(); Action<string> onEachCommand = importedCommandName => { commandsToPostFilter.Add(importedCommandName); }; // Process any exports from the module that we determine from // the -Function, -Cmdlet, or -Alias parameters ProcessCmdletArguments(boundParameters["Function"], onEachCommand); ProcessCmdletArguments(boundParameters["Cmdlet"], onEachCommand); ProcessCmdletArguments(boundParameters["Alias"], onEachCommand); // Now, go through all of the discovered modules on Import-Module // and register them for deeper investigation. Action<string> onEachModule = moduleName => { ModuleIntrinsics.Tracer.WriteLine("Discovered module import: {0}", moduleName); DiscoveredModules.Add( new RequiredModuleInfo { Name = moduleName, CommandsToPostFilter = commandsToPostFilter }); }; ProcessCmdletArguments(boundParameters["Name"], onEachModule); return AstVisitAction.SkipChildren; } // They are exporting a module member if (String.Equals(commandName, "Export-ModuleMember", StringComparison.OrdinalIgnoreCase) || String.Equals(commandName, "Microsoft.PowerShell.Core\\Export-ModuleMember", StringComparison.OrdinalIgnoreCase) || String.Equals(commandName, "$script:ExportModuleMember", StringComparison.OrdinalIgnoreCase)) { // Export-ModuleMember * // Export-ModuleMember Exported-UnNamedModuleMember // Export-ModuleMember -Function Exported-FunctionModuleMember1, Exported-FunctionModuleMember2 -Cmdlet Exported-CmdletModuleMember ` // -Alias Exported-AliasModuleMember // & $script:ExportModuleMember -Function (...) var boundParameters = DoPsuedoParameterBinding(commandAst, commandName); Action<string> onEachFunction = exportedCommandName => { DiscoveredCommandFilters.Add(exportedCommandName); ModuleIntrinsics.Tracer.WriteLine("Discovered explicit export: {0}", exportedCommandName); // If the export doesn't contain wildcards, then add it to the // discovered commands as well. It is likely that they created // the command dynamically if ((!WildcardPattern.ContainsWildcardCharacters(exportedCommandName)) && (!DiscoveredExports.Contains(exportedCommandName))) { DiscoveredExports.Add(exportedCommandName); } }; ProcessCmdletArguments(boundParameters["Function"], onEachFunction); ProcessCmdletArguments(boundParameters["Cmdlet"], onEachFunction); Action<string> onEachAlias = exportedAlias => { DiscoveredCommandFilters.Add(exportedAlias); // If the export doesn't contain wildcards, then add it to the // discovered commands as well. It is likely that they created // the command dynamically if (!WildcardPattern.ContainsWildcardCharacters(exportedAlias)) { DiscoveredAliases[exportedAlias] = null; } }; ProcessCmdletArguments(boundParameters["Alias"], onEachAlias); return AstVisitAction.SkipChildren; } // They are exporting a module member using our advanced 'public' function // that we've presented in many demos if ((String.Equals(commandName, "public", StringComparison.OrdinalIgnoreCase)) && (commandAst.CommandElements.Count > 2)) { // public function Publicly-ExportedFunction // public alias Publicly-ExportedAlias string publicCommandName = commandAst.CommandElements[2].ToString().Trim(); DiscoveredExports.Add(publicCommandName); DiscoveredCommandFilters.Add(publicCommandName); } return AstVisitAction.SkipChildren; } private void ProcessCmdletArguments(object value, Action<string> onEachArgument) { if (value == null) return; var commandName = value as string; if (commandName != null) { onEachArgument(commandName); return; } var names = value as object[]; if (names != null) { foreach (var n in names) { // This is slightly more permissive than what would really happen with parameter binding // in that it would allow arrays of arrays in ways that don't actually work ProcessCmdletArguments(n, onEachArgument); } } } // This method does parameter binding for a very limited set of scenarios, specifically // for New-Alias, Set-Alias, Import-Module, and Export-ModuleMember. It might not even // correctly handle these cmdlets if new parameters are added. // // It also only populates the bound parameters for a limited set of parameters needed // for module analysis. private Hashtable DoPsuedoParameterBinding(CommandAst commandAst, string commandName) { var result = new Hashtable(StringComparer.OrdinalIgnoreCase); var parameterBindingInfo = s_parameterBindingInfoTable[commandName].parameterInfo; int positionsBound = 0; for (int i = 1; i < commandAst.CommandElements.Count; i++) { var element = commandAst.CommandElements[i]; var specifiedParameter = element as CommandParameterAst; if (specifiedParameter != null) { bool boundParameter = false; var specifiedParamName = specifiedParameter.ParameterName; foreach (var parameterInfo in parameterBindingInfo) { if (parameterInfo.name.StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase)) { if (parameterInfo.position != -1) { positionsBound |= 1 << parameterInfo.position; } var argumentAst = specifiedParameter.Argument; if (argumentAst == null) { argumentAst = commandAst.CommandElements[i] as ExpressionAst; if (argumentAst != null) { i += 1; } } if (argumentAst != null) { boundParameter = true; result[parameterInfo.name] = GetSafeValueVisitor.GetSafeValue(argumentAst, null, GetSafeValueVisitor.SafeValueContext.ModuleAnalysis); } break; } } if (boundParameter || specifiedParameter.Argument != null) { continue; } if (!"PassThru".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) && !"Force".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) && !"Confirm".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) && !"Global".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) && !"AsCustomObject".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) && !"Verbose".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) && !"Debug".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) && !"DisableNameChecking".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase) && !"NoClobber".StartsWith(specifiedParamName, StringComparison.OrdinalIgnoreCase)) { // Named parameter, skip the argument (except for specific switch parameters i += 1; } } else { // Positional argument, find which position we want to bind int pos = 0; for (; pos < 10; pos++) { if ((positionsBound & (1 << pos)) == 0) break; } positionsBound |= 1 << pos; // Now see if we care (we probably do, but if the user did something odd, like specify too many, then we don't really) foreach (var parameterInfo in parameterBindingInfo) { if (parameterInfo.position == pos) { result[parameterInfo.name] = GetSafeValueVisitor.GetSafeValue( commandAst.CommandElements[i], null, GetSafeValueVisitor.SafeValueContext.ModuleAnalysis); } } } } return result; } private static Dictionary<string, ParameterBindingInfo> s_parameterBindingInfoTable; private class ParameterBindingInfo { internal ParameterInfo[] parameterInfo; } private struct ParameterInfo { internal string name; internal int position; } } // Class to keep track of modules we need to import, and commands that should // be filtered out of them. [Serializable] internal class RequiredModuleInfo { internal string Name { get; set; } internal List<string> CommandsToPostFilter { get; set; } } } // System.Management.Automation
48.950178
149
0.5747
[ "Apache-2.0", "MIT" ]
JM2K69/PowerShell
src/System.Management.Automation/engine/Modules/ScriptAnalysis.cs
27,510
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable namespace Azure.Management.Network.Models { /// <summary> The routes table associated with the ExpressRouteCircuit. </summary> public partial class ExpressRouteCircuitRoutesTable { /// <summary> Initializes a new instance of ExpressRouteCircuitRoutesTable. </summary> internal ExpressRouteCircuitRoutesTable() { } /// <summary> Initializes a new instance of ExpressRouteCircuitRoutesTable. </summary> /// <param name="network"> IP address of a network entity. </param> /// <param name="nextHop"> NextHop address. </param> /// <param name="locPrf"> Local preference value as set with the set local-preference route-map configuration command. </param> /// <param name="weight"> Route Weight. </param> /// <param name="path"> Autonomous system paths to the destination network. </param> internal ExpressRouteCircuitRoutesTable(string network, string nextHop, string locPrf, int? weight, string path) { Network = network; NextHop = nextHop; LocPrf = locPrf; Weight = weight; Path = path; } /// <summary> IP address of a network entity. </summary> public string Network { get; } /// <summary> NextHop address. </summary> public string NextHop { get; } /// <summary> Local preference value as set with the set local-preference route-map configuration command. </summary> public string LocPrf { get; } /// <summary> Route Weight. </summary> public int? Weight { get; } /// <summary> Autonomous system paths to the destination network. </summary> public string Path { get; } } }
41.577778
135
0.639765
[ "MIT" ]
AbelHu/azure-sdk-for-net
sdk/testcommon/Azure.Management.Network.2020_04/src/Generated/Models/ExpressRouteCircuitRoutesTable.cs
1,871
C#
// (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Public License (Ms-PL). // Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details. // All other rights reserved. using System; using System.Reflection; using System.Resources; using System.Runtime.InteropServices; using System.Windows.Markup; [assembly: AssemblyTitle("CSHTML5.Controls.Input")] [assembly: AssemblyDescription("Silverlight Input Controls for OpenSilver")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("")] [assembly: AssemblyCopyright("© Copyright 2021.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("2.0.5.0")] [assembly: AssemblyFileVersion("4.0.40413.1959")] #if __CLSCOMPLIANT__ [assembly: CLSCompliant(true)] #endif [assembly: XmlnsPrefix("http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk", "sdk")] #if MIGRATION [assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk", "System.Windows.Controls")] #else [assembly: XmlnsDefinition("http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk", "Windows.UI.Xaml.Controls")] #endif
38.757576
120
0.770915
[ "MIT" ]
KeyurJP/OpenSilver
src/Runtime/Controls.Input/.CSHTML5/Properties/AssemblyInfo.cs
1,282
C#
using System; using System.IO; namespace DotNet.zy.Utilities { /// <summary> /// This class represents the Pop3 PASS command. /// </summary> internal sealed class PassCommand : Pop3Command<Pop3Response> { private string _password; /// <summary> /// Initializes a new instance of the <see cref="PassCommand"/> class. /// </summary> /// <param name="stream">The stream.</param> /// <param name="password">The password.</param> public PassCommand(Stream stream, string password) : base(stream, false, Pop3State.Authorization) { if (string.IsNullOrEmpty(password)) { throw new ArgumentNullException("password"); } _password = password; } /// <summary> /// Creates the PASS request message. /// </summary> /// <returns> /// The byte[] containing the PASS request message. /// </returns> protected override byte[] CreateRequestMessage() { return GetRequestMessage(Pop3Commands.Pass, _password, Pop3Commands.Crlf); } } }
28
86
0.565476
[ "MIT" ]
cqkxzyi/ZhangYi.Utilities
doNet/DotNet.zy.Utilities/邮件/邮件2/PassCommand.cs
1,178
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.Collections.ObjectModel; using System.ComponentModel.DataAnnotations.Schema; namespace Microsoft.EntityFrameworkCore.TestModels.ManyToManyModel { public class ImplicitManyToManyA { [DatabaseGenerated(DatabaseGeneratedOption.None)] public virtual int Id { get; set; } public virtual string Name { get; set; } public virtual ICollection<ImplicitManyToManyB> Bs { get; } = new ObservableCollection<ImplicitManyToManyB>(); } }
32.8
118
0.75
[ "MIT" ]
CameronAavik/efcore
test/EFCore.Specification.Tests/TestModels/ManyToManyModel/ImplicitManyToManyA.cs
658
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.Linq; using System.Reflection; using Xunit; namespace System.Tests { public static partial class ArrayTests { [Fact] public static void IList_GetSetItem() { var intArray = new int[] { 7, 8, 9, 10, 11, 12, 13 }; IList<int> iList = intArray; Assert.Equal(intArray.Length, iList.Count); for (int i = 0; i < iList.Count; i++) { Assert.Equal(intArray[i], iList[i]); iList[i] = 99; Assert.Equal(99, iList[i]); Assert.Equal(99, intArray[i]); } } [Fact] public static void IList_GetSetItem_Invalid() { IList iList = new int[] { 7, 8, 9, 10, 11, 12, 13 }; Assert.Throws<IndexOutOfRangeException>(() => iList[-1]); // Index < 0 Assert.Throws<IndexOutOfRangeException>(() => iList[iList.Count]); // Index >= list.Count Assert.Throws<IndexOutOfRangeException>(() => iList[-1] = 0); // Index < 0 Assert.Throws<IndexOutOfRangeException>(() => iList[iList.Count] = 0); // Index >= list.Count iList = new int[,] { { 1 }, { 2 } }; Assert.Throws<ArgumentException>(null, () => iList[0]); // Array is multidimensional Assert.Throws<ArgumentException>(null, () => iList[0] = 0); // Array is multidimensional } [Fact] public static void IList_ModifyingArray_ThrowsNotSupportedException() { var array = new int[] { 7, 8, 9, 10, 11, 12, 13 }; IList<int> iList = array; Assert.True(iList.IsReadOnly); Assert.True(((IList)array).IsFixedSize); Assert.Throws<NotSupportedException>(() => iList.Add(2)); Assert.Throws<NotSupportedException>(() => iList.Insert(0, 0)); Assert.Throws<NotSupportedException>(() => iList.Clear()); Assert.Throws<NotSupportedException>(() => iList.Remove(2)); Assert.Throws<NotSupportedException>(() => iList.RemoveAt(2)); } [Fact] public static void CastAs_IListOfT() { var sa = new string[] { "Hello", "There" }; Assert.True(sa is IList<string>); IList<string> ils = sa; Assert.Equal(2, ils.Count); ils[0] = "50"; Assert.Equal("50", sa[0]); Assert.Equal(sa[1], ils[1]); Assert.Equal("There", sa[1]); } [Fact] public static void Construction() { // Check a number of the simple APIs on Array for dimensions up to 4. Array array = new int[] { 1, 2, 3 }; VerifyArray(array, typeof(int), new int[] { 3 }, new int[1]); array = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }; VerifyArray(array, typeof(int), new int[] { 2, 3 }, new int[2]); array = new int[2, 3, 4]; VerifyArray(array, typeof(int), new int[] { 2, 3, 4 }, new int[3]); array = new int[2, 3, 4, 5]; VerifyArray(array, typeof(int), new int[] { 2, 3, 4, 5 }, new int[4]); } [Fact] public static void Construction_MultiDimensionalArray() { // This C# initialization syntax generates some peculiar looking IL. // Initializations of this form are handled specially on Desktop and in .NET Native by UTC. var array = new int[,,,] { { { { 1, 2, 3 }, { 1, 2, 3 } }, { { 1, 2, 3 }, { 1, 2, 3 } } }, { { { 1, 2, 3 }, { 1, 2, 3 } }, { { 1, 2, 3 }, { 1, 2, 3 } } } }; Assert.NotNull(array); Assert.Equal(array.GetValue(0, 0, 0, 0), 1); Assert.Equal(array.GetValue(0, 0, 0, 1), 2); Assert.Equal(array.GetValue(0, 0, 0, 2), 3); } public static IEnumerable<object[]> BinarySearch_SZArray_TestData() { string[] stringArray = new string[] { null, "aa", "bb", "bb", "cc", "dd", "ee" }; yield return new object[] { stringArray, 0, 7, "bb", null, 3 }; yield return new object[] { stringArray, 0, 7, "ee", null, 6 }; yield return new object[] { stringArray, 3, 4, "bb", null, 3 }; yield return new object[] { stringArray, 4, 3, "bb", null, -5 }; yield return new object[] { stringArray, 4, 0, "bb", null, -5 }; yield return new object[] { stringArray, 0, 7, "bb", new StringComparer(), 3 }; yield return new object[] { stringArray, 0, 7, "ee", new StringComparer(), 6 }; yield return new object[] { stringArray, 0, 7, "no-such-object", new StringComparer(), -8 }; yield return new object[] { new string[0], 0, 0, "", null, -1 }; // SByte sbyte[] sbyteArray = new sbyte[] { sbyte.MinValue, 0, 0, sbyte.MaxValue }; yield return new object[] { sbyteArray, 0, 4, sbyte.MinValue, null, 0 }; yield return new object[] { sbyteArray, 0, 4, (sbyte)0, null, 1 }; yield return new object[] { sbyteArray, 0, 4, sbyte.MaxValue, null, 3 }; yield return new object[] { sbyteArray, 0, 4, (sbyte)1, null, -4 }; yield return new object[] { sbyteArray, 0, 1, sbyte.MinValue, null, 0 }; yield return new object[] { sbyteArray, 1, 3, sbyte.MaxValue, null, 3 }; yield return new object[] { sbyteArray, 1, 3, sbyte.MinValue, null, -2 }; yield return new object[] { sbyteArray, 1, 0, (sbyte)0, null, -2 }; yield return new object[] { new sbyte[0], 0, 0, (sbyte)0, null, -1 }; // Byte byte[] byteArray = new byte[] { byte.MinValue, 5, 5, byte.MaxValue }; yield return new object[] { byteArray, 0, 4, byte.MinValue, null, 0 }; yield return new object[] { byteArray, 0, 4, (byte)5, null, 1 }; yield return new object[] { byteArray, 0, 4, byte.MaxValue, null, 3 }; yield return new object[] { byteArray, 0, 4, (byte)1, null, -2 }; yield return new object[] { byteArray, 0, 1, byte.MinValue, null, 0 }; yield return new object[] { byteArray, 1, 3, byte.MaxValue, null, 3 }; yield return new object[] { byteArray, 1, 3, byte.MinValue, null, -2 }; yield return new object[] { byteArray, 1, 0, (byte)5, null, -2 }; yield return new object[] { new byte[0], 0, 0, (byte)0, null, -1 }; // Int16 short[] shortArray = new short[] { short.MinValue, 0, 0, short.MaxValue }; yield return new object[] { shortArray, 0, 4, short.MinValue, null, 0 }; yield return new object[] { shortArray, 0, 4, (short)0, null, 1 }; yield return new object[] { shortArray, 0, 4, short.MaxValue, null, 3 }; yield return new object[] { shortArray, 0, 4, (short)1, null, -4 }; yield return new object[] { shortArray, 0, 1, short.MinValue, null, 0 }; yield return new object[] { shortArray, 1, 3, short.MaxValue, null, 3 }; yield return new object[] { shortArray, 1, 3, short.MinValue, null, -2 }; yield return new object[] { shortArray, 1, 0, (short)0, null, -2 }; yield return new object[] { new short[0], 0, 0, (short)0, null, -1 }; // UInt16 ushort[] ushortArray = new ushort[] { ushort.MinValue, 5, 5, ushort.MaxValue }; yield return new object[] { ushortArray, 0, 4, ushort.MinValue, null, 0 }; yield return new object[] { ushortArray, 0, 4, (ushort)5, null, 1 }; yield return new object[] { ushortArray, 0, 4, ushort.MaxValue, null, 3 }; yield return new object[] { ushortArray, 0, 4, (ushort)1, null, -2 }; yield return new object[] { ushortArray, 0, 1, ushort.MinValue, null, 0 }; yield return new object[] { ushortArray, 1, 3, ushort.MaxValue, null, 3 }; yield return new object[] { ushortArray, 1, 3, ushort.MinValue, null, -2 }; yield return new object[] { ushortArray, 1, 0, (ushort)5, null, -2 }; yield return new object[] { new ushort[0], 0, 0, (ushort)0, null, -1 }; // Int32 int[] intArray = new int[] { int.MinValue, 0, 0, int.MaxValue }; yield return new object[] { intArray, 0, 4, int.MinValue, null, 0 }; yield return new object[] { intArray, 0, 4, 0, null, 1 }; yield return new object[] { intArray, 0, 4, int.MaxValue, null, 3 }; yield return new object[] { intArray, 0, 4, 1, null, -4 }; yield return new object[] { intArray, 0, 1, int.MinValue, null, 0 }; yield return new object[] { intArray, 1, 3, int.MaxValue, null, 3 }; yield return new object[] { intArray, 1, 3, int.MinValue, null, -2 }; int[] intArray2 = new int[] { 1, 3, 6, 6, 8, 10, 12, 16 }; yield return new object[] { intArray2, 0, 8, 8, new IntegerComparer(), 4 }; yield return new object[] { intArray2, 0, 8, 6, new IntegerComparer(), 3 }; yield return new object[] { intArray2, 0, 8, 0, new IntegerComparer(), -1 }; yield return new object[] { new int[0], 0, 0, 0, null, -1 }; // UInt32 uint[] uintArray = new uint[] { uint.MinValue, 5, 5, uint.MaxValue }; yield return new object[] { uintArray, 0, 4, uint.MinValue, null, 0 }; yield return new object[] { uintArray, 0, 4, (uint)5, null, 1 }; yield return new object[] { uintArray, 0, 4, uint.MaxValue, null, 3 }; yield return new object[] { uintArray, 0, 4, (uint)1, null, -2 }; yield return new object[] { uintArray, 0, 1, uint.MinValue, null, 0 }; yield return new object[] { uintArray, 1, 3, uint.MaxValue, null, 3 }; yield return new object[] { uintArray, 1, 3, uint.MinValue, null, -2 }; yield return new object[] { uintArray, 1, 0, (uint)5, null, -2 }; yield return new object[] { new uint[0], 0, 0, (uint)0, null, -1 }; // Int64 long[] longArray = new long[] { long.MinValue, 0, 0, long.MaxValue }; yield return new object[] { longArray, 0, 4, long.MinValue, null, 0 }; yield return new object[] { longArray, 0, 4, (long)0, null, 1 }; yield return new object[] { longArray, 0, 4, long.MaxValue, null, 3 }; yield return new object[] { longArray, 0, 4, (long)1, null, -4 }; yield return new object[] { longArray, 0, 1, long.MinValue, null, 0 }; yield return new object[] { longArray, 1, 3, long.MaxValue, null, 3 }; yield return new object[] { longArray, 1, 3, long.MinValue, null, -2 }; yield return new object[] { longArray, 1, 0, (long)0, null, -2 }; yield return new object[] { new long[0], 0, 0, (long)0, null, -1 }; // UInt64 ulong[] ulongArray = new ulong[] { ulong.MinValue, 5, 5, ulong.MaxValue }; yield return new object[] { ulongArray, 0, 4, ulong.MinValue, null, 0 }; yield return new object[] { ulongArray, 0, 4, (ulong)5, null, 1 }; yield return new object[] { ulongArray, 0, 4, ulong.MaxValue, null, 3 }; yield return new object[] { ulongArray, 0, 4, (ulong)1, null, -2 }; yield return new object[] { ulongArray, 0, 1, ulong.MinValue, null, 0 }; yield return new object[] { ulongArray, 1, 3, ulong.MaxValue, null, 3 }; yield return new object[] { ulongArray, 1, 3, ulong.MinValue, null, -2 }; yield return new object[] { ulongArray, 1, 0, (ulong)5, null, -2 }; yield return new object[] { new ulong[0], 0, 0, (ulong)0, null, -1 }; // Char char[] charArray = new char[] { char.MinValue, (char)5, (char)5, char.MaxValue }; yield return new object[] { charArray, 0, 4, char.MinValue, null, 0 }; yield return new object[] { charArray, 0, 4, (char)5, null, 1 }; yield return new object[] { charArray, 0, 4, char.MaxValue, null, 3 }; yield return new object[] { charArray, 0, 4, (char)1, null, -2 }; yield return new object[] { charArray, 0, 1, char.MinValue, null, 0 }; yield return new object[] { charArray, 1, 3, char.MaxValue, null, 3 }; yield return new object[] { charArray, 1, 3, char.MinValue, null, -2 }; yield return new object[] { charArray, 1, 0, (char)5, null, -2 }; yield return new object[] { new char[0], 0, 0, '\0', null, -1 }; // Bool bool[] boolArray = new bool[] { false, false, true }; yield return new object[] { boolArray, 0, 3, false, null, 1 }; yield return new object[] { boolArray, 0, 3, true, null, 2 }; yield return new object[] { new bool[] { false }, 0, 1, true, null, -2 }; yield return new object[] { boolArray, 0, 1, false, null, 0 }; yield return new object[] { boolArray, 2, 1, true, null, 2 }; yield return new object[] { boolArray, 2, 1, false, null, -3 }; yield return new object[] { boolArray, 1, 0, false, null, -2 }; yield return new object[] { new bool[0], 0, 0, false, null, -1 }; // Single float[] floatArray = new float[] { float.MinValue, 0, 0, float.MaxValue }; yield return new object[] { floatArray, 0, 4, float.MinValue, null, 0 }; yield return new object[] { floatArray, 0, 4, 0f, null, 1 }; yield return new object[] { floatArray, 0, 4, float.MaxValue, null, 3 }; yield return new object[] { floatArray, 0, 4, (float)1, null, -4 }; yield return new object[] { floatArray, 0, 1, float.MinValue, null, 0 }; yield return new object[] { floatArray, 1, 3, float.MaxValue, null, 3 }; yield return new object[] { floatArray, 1, 3, float.MinValue, null, -2 }; yield return new object[] { floatArray, 1, 0, 0f, null, -2 }; yield return new object[] { new float[0], 0, 0, 0f, null, -1 }; // Double double[] doubleArray = new double[] { double.MinValue, 0, 0, double.MaxValue }; yield return new object[] { doubleArray, 0, 4, double.MinValue, null, 0 }; yield return new object[] { doubleArray, 0, 4, 0d, null, 1 }; yield return new object[] { doubleArray, 0, 4, double.MaxValue, null, 3 }; yield return new object[] { doubleArray, 0, 4, (double)1, null, -4 }; yield return new object[] { doubleArray, 0, 1, double.MinValue, null, 0 }; yield return new object[] { doubleArray, 1, 3, double.MaxValue, null, 3 }; yield return new object[] { doubleArray, 1, 3, double.MinValue, null, -2 }; yield return new object[] { doubleArray, 1, 0, 0d, null, -2 }; yield return new object[] { new double[0], 0, 0, 0d, null, -1 }; } [Theory] // Workaround: Move these tests to BinarySearch_SZArray_TestData if/ when https://github.com/xunit/xunit/pull/965 is available [InlineData(new sbyte[] { 0 }, 0, 1, null, null, -1)] [InlineData(new byte[] { 0 }, 0, 1, null, null, -1)] [InlineData(new short[] { 0 }, 0, 1, null, null, -1)] [InlineData(new ushort[] { 0 }, 0, 1, null, null, -1)] [InlineData(new int[] { 0 }, 0, 1, null, null, -1)] [InlineData(new uint[] { 0 }, 0, 1, null, null, -1)] [InlineData(new long[] { 0 }, 0, 1, null, null, -1)] [InlineData(new ulong[] { 0 }, 0, 1, null, null, -1)] [InlineData(new bool[] { false }, 0, 1, null, null, -1)] [InlineData(new char[] { '\0' }, 0, 1, null, null, -1)] [InlineData(new float[] { 0 }, 0, 1, null, null, -1)] [InlineData(new double[] { 0 }, 0, 1, null, null, -1)] public static void BinarySearch_Array(Array array, int index, int length, object value, IComparer comparer, int expected) { bool isDefaultComparer = comparer == null || comparer == Comparer.Default; if (index == array.GetLowerBound(0) && length == array.Length) { if (isDefaultComparer) { // Use BinarySearch(Array, object) Assert.Equal(expected, Array.BinarySearch(array, value)); Assert.Equal(expected, Array.BinarySearch(array, value, Comparer.Default)); } // Use BinarySearch(Array, object, IComparer) Assert.Equal(expected, Array.BinarySearch(array, value, comparer)); } if (isDefaultComparer) { // Use BinarySearch(Array, int, int, object) Assert.Equal(expected, Array.BinarySearch(array, index, length, value)); } // Use BinarySearch(Array, int, int, object, IComparer) Assert.Equal(expected, Array.BinarySearch(array, index, length, value, comparer)); } [Theory] [MemberData(nameof(BinarySearch_SZArray_TestData))] public static void BinarySearch_SZArray<T>(T[] array, int index, int length, T value, IComparer<T> comparer, int expected) { // Forward to the non-generic overload if we can. bool isDefaultComparer = comparer == null || comparer == Comparer<T>.Default; if (isDefaultComparer || comparer is IComparer) { // Basic: forward SZArray BinarySearch_Array(array, index, length, value, (IComparer)comparer, expected); // Advanced: convert SZArray to an array with non-zero lower bound const int lowerBound = 5; Array nonZeroLowerBoundArray = NonZeroLowerBoundArray(array, lowerBound); int lowerBoundExpected = expected < 0 ? expected - lowerBound : expected + lowerBound; BinarySearch_Array(nonZeroLowerBoundArray, index + lowerBound, length, value, (IComparer)comparer, lowerBoundExpected); } if (index == 0 && length == array.Length) { if (isDefaultComparer) { // Use BinarySearch<T>(T[], T) Assert.Equal(expected, Array.BinarySearch(array, value)); Assert.Equal(expected, Array.BinarySearch(array, value, Comparer<T>.Default)); } // Use BinarySearch<T>(T[], T, IComparer) Assert.Equal(expected, Array.BinarySearch(array, value, comparer)); } if (isDefaultComparer) { // Use BinarySearch<T>(T, int, int, T) Assert.Equal(expected, Array.BinarySearch(array, index, length, value)); } // Use BinarySearch<T>(T[], int, int, T, IComparer) Assert.Equal(expected, Array.BinarySearch(array, index, length, value, comparer)); } [Fact] public static void BinarySearch_SZArray_NonInferrableEntries() { // Workaround: Move these values to BinarySearch_SZArray_TestData if/ when https://github.com/xunit/xunit/pull/965 is available BinarySearch_SZArray(new string[] { null, "a", "b", "c" }, 0, 4, null, null, 0); BinarySearch_SZArray(new string[] { null, "a", "b", "c" }, 0, 4, null, new StringComparer(), 0); } [Fact] public static void BinarySearch_NullArray_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("array", () => Array.BinarySearch((int[])null, "")); Assert.Throws<ArgumentNullException>("array", () => Array.BinarySearch(null, "")); Assert.Throws<ArgumentNullException>("array", () => Array.BinarySearch((int[])null, "", null)); Assert.Throws<ArgumentNullException>("array", () => Array.BinarySearch(null, "", null)); Assert.Throws<ArgumentNullException>("array", () => Array.BinarySearch((int[])null, 0, 0, "")); Assert.Throws<ArgumentNullException>("array", () => Array.BinarySearch(null, 0, 0, "")); Assert.Throws<ArgumentNullException>("array", () => Array.BinarySearch((int[])null, 0, 0, "", null)); Assert.Throws<ArgumentNullException>("array", () => Array.BinarySearch(null, 0, 0, "", null)); } [Fact] public static void BinarySearch_MultiDimensionalArray_ThrowsRankException() { Assert.Throws<RankException>(() => Array.BinarySearch(new string[0, 0], "")); Assert.Throws<RankException>(() => Array.BinarySearch(new string[0, 0], "", null)); Assert.Throws<RankException>(() => Array.BinarySearch(new string[0, 0], 0, 0, "")); Assert.Throws<RankException>(() => Array.BinarySearch(new string[0, 0], 0, 0, "", null)); } public static IEnumerable<object[]> BinarySearch_TypesNotComparable_TestData() { // Different types yield return new object[] { new int[] { 0 }, "", 0 }; // Type does not implement IComparable yield return new object[] { new object[] { new object() }, new object(), new object() }; // IntPtr and UIntPtr are not supported yield return new object[] { new IntPtr[] { IntPtr.Zero }, IntPtr.Zero, IntPtr.Zero }; yield return new object[] { new UIntPtr[] { UIntPtr.Zero }, UIntPtr.Zero, UIntPtr.Zero }; // Conversion between primitives is not allowed yield return new object[] { new sbyte[] { 0 }, 0, (sbyte)0 }; yield return new object[] { new char[] { '\0' }, (ushort)0, '\0' }; } [Theory] [MemberData(nameof(BinarySearch_TypesNotComparable_TestData))] public static void BinarySearch_TypesNotIComparable_ThrowsInvalidOperationException<T>(T[] array, object value, T dummy) { Assert.Throws<InvalidOperationException>(() => Array.BinarySearch(array, value)); Assert.Throws<InvalidOperationException>(() => Array.BinarySearch(array, value, null)); Assert.Throws<InvalidOperationException>(() => Array.BinarySearch(array, 0, array.Length, value)); Assert.Throws<InvalidOperationException>(() => Array.BinarySearch(array, 0, array.Length, value, null)); if (value is T) { Assert.Throws<InvalidOperationException>(() => Array.BinarySearch(array, (T)value)); Assert.Throws<InvalidOperationException>(() => Array.BinarySearch(array, 0, array.Length, (T)value)); Assert.Throws<InvalidOperationException>(() => Array.BinarySearch(array, 0, array.Length, (T)value, null)); } } [Fact] public static void BinarySearch_IndexLessThanZero_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("index", () => Array.BinarySearch(new int[3], -1, 0, "")); Assert.Throws<ArgumentOutOfRangeException>("index", () => Array.BinarySearch(new string[3], -1, 0, "")); Assert.Throws<ArgumentOutOfRangeException>("index", () => Array.BinarySearch(new int[3], -1, 0, "", null)); Assert.Throws<ArgumentOutOfRangeException>("index", () => Array.BinarySearch(new string[3], -1, 0, "", null)); } [Fact] public static void BinarySearch_LengthLessThanZero_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.BinarySearch(new int[3], 0, -1, "")); Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.BinarySearch(new string[3], 0, -1, "")); Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.BinarySearch(new int[3], 0, -1, "", null)); Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.BinarySearch(new string[3], 0, -1, "", null)); } [Theory] [InlineData(0, 0, 1)] [InlineData(0, 1, 0)] [InlineData(3, 0, 4)] [InlineData(3, 1, 3)] [InlineData(3, 3, 1)] public static void BinarySearch_IndexPlusLengthInvalid_ThrowsArgumentException(int count, int index, int length) { Assert.Throws<ArgumentException>(null, () => Array.BinarySearch(new int[count], index, length, "")); Assert.Throws<ArgumentException>(null, () => Array.BinarySearch(new string[count], index, length, "")); Assert.Throws<ArgumentException>(null, () => Array.BinarySearch(new int[count], index, length, "", null)); Assert.Throws<ArgumentException>(null, () => Array.BinarySearch(new string[count], index, length, "", null)); } [Theory] [InlineData(typeof(object), 0)] [InlineData(typeof(object), 2)] [InlineData(typeof(int), 0)] [InlineData(typeof(int), 2)] [InlineData(typeof(IntPtr), 0)] [InlineData(typeof(IntPtr), 2)] [InlineData(typeof(UIntPtr), 0)] [InlineData(typeof(UIntPtr), 2)] public static void BinarySearch_CountZero_ValueInvalidType_DoesNotThrow(Type elementType, int length) { Array array = Array.CreateInstance(elementType, length); Assert.Equal(-1, Array.BinarySearch(array, 0, 0, new object())); } [Fact] public static void GetValue_SetValue() { var intArray = new int[] { 7, 8, 9 }; Array array = intArray; Assert.Equal(7, array.GetValue(0)); array.SetValue(41, 0); Assert.Equal(41, intArray[0]); Assert.Equal(8, array.GetValue(1)); array.SetValue(42, 1); Assert.Equal(42, intArray[1]); Assert.Equal(9, array.GetValue(2)); array.SetValue(43, 2); Assert.Equal(43, intArray[2]); array = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }; Assert.Equal(1, array.GetValue(0, 0)); Assert.Equal(6, array.GetValue(1, 2)); array.SetValue(42, 1, 2); Assert.Equal(42, array.GetValue(1, 2)); array = Array.CreateInstance(typeof(int), 2, 3, 4); array.SetValue(42, 1, 2, 3); Assert.Equal(42, array.GetValue(1, 2, 3)); array = Array.CreateInstance(typeof(int), 2, 3, 4, 5); array.SetValue(42, 1, 2, 3, 4); Assert.Equal(42, array.GetValue(1, 2, 3, 4)); } [Fact] public static void GetValue_Invalid() { Assert.Throws<IndexOutOfRangeException>(() => new int[10].GetValue(-1)); // Index < 0 Assert.Throws<IndexOutOfRangeException>(() => new int[10].GetValue(10)); // Index >= array.Length Assert.Throws<ArgumentException>(null, () => new int[10, 10].GetValue(0)); // Array is multidimensional Assert.Throws<ArgumentNullException>("indices", () => new int[10].GetValue((int[])null)); // Indices is null Assert.Throws<ArgumentException>(null, () => new int[10, 10].GetValue(new int[] { 1, 2, 3 })); // Indices.Length > array.Rank Assert.Throws<IndexOutOfRangeException>(() => new int[8, 10].GetValue(new int[] { -1, 2 })); // Indices[0] < 0 Assert.Throws<IndexOutOfRangeException>(() => new int[8, 10].GetValue(new int[] { 9, 2 })); // Indices[0] > array.GetLength(0) Assert.Throws<IndexOutOfRangeException>(() => new int[10, 8].GetValue(new int[] { 1, -1 })); // Indices[1] < 0 Assert.Throws<IndexOutOfRangeException>(() => new int[10, 8].GetValue(new int[] { 1, 9 })); // Indices[1] > array.GetLength(1) } [Fact] public static unsafe void GetValue_ArrayOfPointers_ThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => new int*[2].GetValue(0)); } [Fact] public static unsafe void SetValue_ArrayOfPointers_ThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => new int*[2].SetValue(null, 0)); } [Theory] [InlineData(new int[] { 7, 8, 9 }, 0, 3, new int[] { 0, 0, 0 })] [InlineData(new int[] { 0x1234567, 0x789abcde, 0x22334455, 0x66778899, 0x11335577, 0x22446688 }, 0, 6, new int[] { 0, 0, 0, 0, 0, 0 })] [InlineData(new int[] { 0x1234567, 0x789abcde, 0x22334455, 0x66778899, 0x11335577, 0x22446688 }, 2, 3, new int[] { 0x1234567, 0x789abcde, 0, 0, 0, 0x22446688 })] [InlineData(new int[] { 0x1234567, 0x789abcde, 0x22334455, 0x66778899, 0x11335577, 0x22446688 }, 6, 0, new int[] { 0x1234567, 0x789abcde, 0x22334455, 0x66778899, 0x11335577, 0x22446688 })] [InlineData(new int[] { 0x1234567, 0x789abcde, 0x22334455, 0x66778899, 0x11335577, 0x22446688 }, 0, 0, new int[] { 0x1234567, 0x789abcde, 0x22334455, 0x66778899, 0x11335577, 0x22446688 })] [InlineData(new string[] { "7", "8", "9" }, 0, 3, new string[] { null, null, null })] [InlineData(new string[] { "0x1234567", "0x789abcde", "0x22334455", "0x66778899", "0x11335577", "0x22446688" }, 0, 6, new string[] { null, null, null, null, null, null })] [InlineData(new string[] { "0x1234567", "0x789abcde", "0x22334455", "0x66778899", "0x11335577", "0x22446688" }, 2, 3, new string[] { "0x1234567", "0x789abcde", null, null, null, "0x22446688" })] [InlineData(new string[] { "0x1234567", "0x789abcde", "0x22334455", "0x66778899", "0x11335577", "0x22446688" }, 6, 0, new string[] { "0x1234567", "0x789abcde", "0x22334455", "0x66778899", "0x11335577", "0x22446688" })] [InlineData(new string[] { "0x1234567", "0x789abcde", "0x22334455", "0x66778899", "0x11335577", "0x22446688" }, 0, 0, new string[] { "0x1234567", "0x789abcde", "0x22334455", "0x66778899", "0x11335577", "0x22446688" })] public static void Clear(Array array, int index, int length, Array expected) { if (index == 0 && length == array.Length) { // Use IList.Clear() Array arrayClone1 = (Array)array.Clone(); ((IList)arrayClone1).Clear(); Assert.Equal(expected, arrayClone1); } Array arrayClone2 = (Array)array.Clone(); Array.Clear(arrayClone2, index, length); Assert.Equal(expected, arrayClone2); } [Fact] public static void Clear_Struct_WithReferenceAndValueTypeFields_Array() { var array = new NonGenericStruct[] { new NonGenericStruct { x = 1, s = "Hello", z = 2 }, new NonGenericStruct { x = 2, s = "Hello", z = 3 }, new NonGenericStruct { x = 3, s = "Hello", z = 4 }, new NonGenericStruct { x = 4, s = "Hello", z = 5 }, new NonGenericStruct { x = 5, s = "Hello", z = 6 } }; Array.Clear(array, 0, 5); for (int i = 0; i < array.Length; i++) { Assert.Equal(0, array[i].x); Assert.Null(array[i].s); Assert.Equal(0, array[i].z); } array = new NonGenericStruct[] { new NonGenericStruct { x = 1, s = "Hello", z = 2 }, new NonGenericStruct { x = 2, s = "Hello", z = 3 }, new NonGenericStruct { x = 3, s = "Hello", z = 4 }, new NonGenericStruct { x = 4, s = "Hello", z = 5 }, new NonGenericStruct { x = 5, s = "Hello", z = 6 } }; Array.Clear(array, 2, 3); Assert.Equal(1, array[0].x); Assert.Equal("Hello", array[0].s); Assert.Equal(2, array[0].z); Assert.Equal(2, array[1].x); Assert.Equal("Hello", array[1].s); Assert.Equal(3, array[1].z); for (int i = 2; i < 2 + 3; i++) { Assert.Equal(0, array[i].x); Assert.Null(array[i].s); Assert.Equal(0, array[i].z); } } [Fact] public static void Clear_Invalid() { Assert.Throws<ArgumentNullException>("array", () => Array.Clear(null, 0, 0)); // Array is null Assert.Throws<IndexOutOfRangeException>(() => Array.Clear(new int[10], -1, 0)); // Index < 0 Assert.Throws<IndexOutOfRangeException>(() => Array.Clear(new int[10], 0, -1)); // Length < 0 // Index + length > array.Length Assert.Throws<IndexOutOfRangeException>(() => Array.Clear(new int[10], 0, 11)); Assert.Throws<IndexOutOfRangeException>(() => Array.Clear(new int[10], 10, 1)); Assert.Throws<IndexOutOfRangeException>(() => Array.Clear(new int[10], 9, 2)); Assert.Throws<IndexOutOfRangeException>(() => Array.Clear(new int[10], 6, 0x7fffffff)); } [Theory] [InlineData(new int[0])] [InlineData(new char[] { '1', '2', '3' })] public static void Clone(Array array) { Array clone = (Array)array.Clone(); Assert.Equal(clone, array); Assert.NotSame(clone, array); } public static IEnumerable<object[]> Copy_Array_Reliable_TestData() { // Array -> SZArray Array lowerBoundArray1 = Array.CreateInstance(typeof(int), new int[] { 1 }, new int[] { 1 }); lowerBoundArray1.SetValue(2, lowerBoundArray1.GetLowerBound(0)); yield return new object[] { lowerBoundArray1, lowerBoundArray1.GetLowerBound(0), new int[1], 0, 1, new int[] { 2 } }; // SZArray -> Array Array lowerBoundArray2 = Array.CreateInstance(typeof(int), new int[] { 1 }, new int[] { 1 }); yield return new object[] { new int[] { 2 }, 0, lowerBoundArray2, lowerBoundArray2.GetLowerBound(0), 1, lowerBoundArray1 }; // int[,] -> int[,] int[,] intRank2Array = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }; yield return new object[] { intRank2Array, 0, new int[2, 3], 0, 6, intRank2Array }; yield return new object[] { intRank2Array, 0, new int[3, 2], 0, 6, new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } } }; yield return new object[] { intRank2Array, 1, new int[2, 3], 2, 3, new int[,] { { 0, 0, 2 }, { 3, 4, 0 } } }; // object[,] -> object[,] object[,] objectRank2Array = new object[,] { { 1, 2, 3 }, { 4, 5, 6 } }; yield return new object[] { objectRank2Array, 0, new object[2, 3], 0, 6, objectRank2Array }; yield return new object[] { objectRank2Array, 0, new object[3, 2], 0, 6, new object[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } } }; yield return new object[] { objectRank2Array, 1, new object[2, 3], 2, 3, new object[,] { { null, null, 2 }, { 3, 4, null } } }; } public static IEnumerable<object[]> Copy_SZArray_Reliable_TestData() { // Int64[] -> Int64[] yield return new object[] { new long[] { 1, 2, 3 }, 0, new long[3], 0, 3, new long[] { 1, 2, 3 } }; yield return new object[] { new long[] { 1, 2, 3 }, 1, new long[] { 1, 2, 3, 4, 5 }, 2, 2, new long[] { 1, 2, 2, 3, 5 } }; // UInt64[] -> UInt64[] yield return new object[] { new ulong[] { 1, 2, 3 }, 0, new ulong[3], 0, 3, new ulong[] { 1, 2, 3 } }; yield return new object[] { new ulong[] { 1, 2, 3 }, 1, new ulong[] { 1, 2, 3, 4, 5 }, 2, 2, new ulong[] { 1, 2, 2, 3, 5 } }; // UInt32[] -> UInt32[] yield return new object[] { new uint[] { 1, 2, 3 }, 0, new uint[3], 0, 3, new uint[] { 1, 2, 3 } }; yield return new object[] { new uint[] { 1, 2, 3 }, 1, new uint[] { 1, 2, 3, 4, 5 }, 2, 2, new uint[] { 1, 2, 2, 3, 5 } }; // Int32[] -> Int32[] yield return new object[] { new int[] { 1, 2, 3 }, 0, new int[3], 0, 3, new int[] { 1, 2, 3 } }; yield return new object[] { new int[] { 1, 2, 3 }, 1, new int[] { 1, 2, 3, 4, 5 }, 2, 2, new int[] { 1, 2, 2, 3, 5 } }; // Int16[] -> Int16[] yield return new object[] { new short[] { 1, 2, 3 }, 0, new short[3], 0, 3, new short[] { 1, 2, 3 } }; yield return new object[] { new short[] { 1, 2, 3 }, 1, new short[] { 1, 2, 3, 4, 5 }, 2, 2, new short[] { 1, 2, 2, 3, 5 } }; // UInt16[] -> UInt16[] yield return new object[] { new ushort[] { 1, 2, 3 }, 0, new ushort[3], 0, 3, new ushort[] { 1, 2, 3 } }; yield return new object[] { new ushort[] { 1, 2, 3 }, 1, new ushort[] { 1, 2, 3, 4, 5 }, 2, 2, new ushort[] { 1, 2, 2, 3, 5 } }; // SByte[] -> SByte[] yield return new object[] { new sbyte[] { 1, 2, 3 }, 0, new sbyte[3], 0, 3, new sbyte[] { 1, 2, 3 } }; yield return new object[] { new sbyte[] { 1, 2, 3 }, 1, new sbyte[] { 1, 2, 3, 4, 5 }, 2, 2, new sbyte[] { 1, 2, 2, 3, 5 } }; // Byte[] -> Byte[] yield return new object[] { new byte[] { 1, 2, 3 }, 0, new byte[3], 0, 3, new byte[] { 1, 2, 3 } }; yield return new object[] { new byte[] { 1, 2, 3 }, 1, new byte[] { 1, 2, 3, 4, 5 }, 2, 2, new byte[] { 1, 2, 2, 3, 5 } }; // Char[] -> Char[] yield return new object[] { new char[] { '1', '2', '3' }, 0, new char[3], 0, 3, new char[] { '1', '2', '3' } }; yield return new object[] { new char[] { '1', '2', '3' }, 1, new char[] { '1', '2', '3', '4', '5' }, 2, 2, new char[] { '1', '2', '2', '3', '5' } }; // Bool[] -> Bool[] yield return new object[] { new bool[] { false, true, false }, 0, new bool[3], 0, 3, new bool[] { false, true, false } }; yield return new object[] { new bool[] { false, true, false }, 1, new bool[] { false, true, false, true, false }, 2, 2, new bool[] { false, true, true, false, false } }; // Single[] -> Single[] yield return new object[] { new float[] { 1, 2.2f, 3 }, 0, new float[3], 0, 3, new float[] { 1, 2.2f, 3 } }; yield return new object[] { new float[] { 1, 2.2f, 3 }, 1, new float[] { 1, 2, 3.3f, 4, 5 }, 2, 2, new float[] { 1, 2, 2.2f, 3, 5 } }; // Double[] -> Double[] yield return new object[] { new double[] { 1, 2.2, 3 }, 0, new double[3], 0, 3, new double[] { 1, 2.2, 3 } }; yield return new object[] { new double[] { 1, 2.2, 3 }, 1, new double[] { 1, 2, 3.3, 4, 5 }, 2, 2, new double[] { 1, 2, 2.2, 3, 5 } }; // IntPtr[] -> IntPtr[] yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3 }, 0, new IntPtr[3], 0, 3, new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3 } }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3 }, 1, new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)4, (IntPtr)5 }, 2, 2, new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)2, (IntPtr)3, (IntPtr)5 } }; // UIntPtr[] -> UIntPtr[] yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3 }, 0, new UIntPtr[3], 0, 3, new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3 } }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3 }, 1, new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)4, (UIntPtr)5 }, 2, 2, new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)2, (UIntPtr)3, (UIntPtr)5 } }; // String[] -> String[] yield return new object[] { new string[] { "1", "2", "3" }, 0, new string[3], 0, 3, new string[] { "1", "2", "3" } }; yield return new object[] { new string[] { "1", "2", "3" }, 1, new string[] { "1", "2", "3", "4", "5" }, 2, 2, new string[] { "1", "2", "2", "3", "5" } }; // IntEnum[] conversions yield return new object[] { new Int32Enum[] { (Int32Enum)1, (Int32Enum)2, (Int32Enum)3 }, 0, new Int32Enum[3], 0, 3, new Int32Enum[] { (Int32Enum)1, (Int32Enum)2, (Int32Enum)3 } }; yield return new object[] { new Int32Enum[] { (Int32Enum)1, (Int32Enum)2, (Int32Enum)3 }, 1, new Int32Enum[] { (Int32Enum)1, (Int32Enum)2, (Int32Enum)3, (Int32Enum)4, (Int32Enum)5 }, 2, 2, new Int32Enum[] { (Int32Enum)1, (Int32Enum)2, (Int32Enum)2, (Int32Enum)3, (Int32Enum)5 } }; yield return new object[] { new Int32Enum[] { (Int32Enum)1 }, 0, new int[1], 0, 1, new int[] { 1 } }; // Misc yield return new object[] { new int[] { 0x12345678, 0x22334455, 0x778899aa }, 0, new int[3], 0, 3, new int[] { 0x12345678, 0x22334455, 0x778899aa } }; int[] intArray1 = new int[] { 0x12345678, 0x22334455, 0x778899aa, 0x55443322, 0x33445566 }; yield return new object[] { intArray1, 3, intArray1, 2, 2, new int[] { 0x12345678, 0x22334455, 0x55443322, 0x33445566, 0x33445566 } }; int[] intArray2 = new int[] { 0x12345678, 0x22334455, 0x778899aa, 0x55443322, 0x33445566 }; yield return new object[] { intArray2, 2, intArray2, 3, 2, new int[] { 0x12345678, 0x22334455, 0x778899aa, 0x778899aa, 0x55443322 } }; yield return new object[] { new string[] { "Red", "Green", null, "Blue" }, 0, new string[] { "X", "X", "X", "X" }, 0, 4, new string[] { "Red", "Green", null, "Blue" } }; string[] stringArray = new string[] { "Red", "Green", null, "Blue" }; yield return new object[] { stringArray, 1, stringArray, 2, 2, new string[] { "Red", "Green", "Green", null } }; // Struct[] -> Struct[] NonGenericStruct[] structArray1 = CreateStructArray(); yield return new object[] { structArray1, 0, new NonGenericStruct[5], 0, 5, structArray1 }; // Struct[] overlaps NonGenericStruct[] structArray2 = CreateStructArray(); NonGenericStruct[] overlappingStructArrayExpected = new NonGenericStruct[] { new NonGenericStruct { x = 1, s = "Hello1", z = 2 }, new NonGenericStruct { x = 2, s = "Hello2", z = 3 }, new NonGenericStruct { x = 2, s = "Hello2", z = 3 }, new NonGenericStruct { x = 3, s = "Hello3", z = 4 }, new NonGenericStruct { x = 4, s = "Hello4", z = 5 } }; yield return new object[] { structArray2, 1, structArray2, 2, 3, overlappingStructArrayExpected }; // SubClass[] -> BaseClass[] yield return new object[] { new NonGenericSubClass1[10], 0, new NonGenericClass1[10], 0, 10, new NonGenericClass1[10] }; } public static IEnumerable<object[]> Copy_SZArray_PrimitiveWidening_TestData() { // Int64[] -> primitive[] yield return new object[] { new long[] { 1, 2, 3 }, 0, new float[3], 0, 3, new float[] { 1, 2, 3 } }; yield return new object[] { new long[] { 1, 2, 3 }, 0, new double[3], 0, 3, new double[] { 1, 2, 3 } }; // UInt64[] -> primitive[] yield return new object[] { new ulong[] { 1, 2, 3 }, 0, new float[3], 0, 3, new float[] { 1, 2, 3 } }; yield return new object[] { new ulong[] { 1, 2, 3 }, 0, new double[3], 0, 3, new double[] { 1, 2, 3 } }; // Int32[] -> primitive[] yield return new object[] { new int[] { 1, 2, 3 }, 0, new long[3], 0, 3, new long[] { 1, 2, 3 } }; yield return new object[] { new int[] { 1, 2, 3 }, 0, new float[3], 0, 3, new float[] { 1, 2, 3 } }; yield return new object[] { new int[] { 1, 2, 3 }, 0, new double[3], 0, 3, new double[] { 1, 2, 3 } }; // UInt32[] -> primitive[] yield return new object[] { new uint[] { 1, 2, 3 }, 0, new long[3], 0, 3, new long[] { 1, 2, 3 } }; yield return new object[] { new uint[] { 1, 2, 3 }, 0, new ulong[3], 0, 3, new ulong[] { 1, 2, 3 } }; yield return new object[] { new uint[] { 1, 2, 3 }, 0, new float[3], 0, 3, new float[] { 1, 2, 3 } }; yield return new object[] { new uint[] { 1, 2, 3 }, 0, new double[3], 0, 3, new double[] { 1, 2, 3 } }; // Int16[] -> primitive[] yield return new object[] { new short[] { 1, 2, 3 }, 0, new long[3], 0, 3, new long[] { 1, 2, 3 } }; yield return new object[] { new short[] { 1, 2, 3 }, 0, new int[3], 0, 3, new int[] { 1, 2, 3 } }; yield return new object[] { new short[] { 1, 2, 3 }, 0, new float[3], 0, 3, new float[] { 1, 2, 3 } }; yield return new object[] { new short[] { 1, 2, 3 }, 0, new double[3], 0, 3, new double[] { 1, 2, 3 } }; // UInt16[] -> primitive[] yield return new object[] { new ushort[] { 1, 2, 3 }, 0, new long[3], 0, 3, new long[] { 1, 2, 3 } }; yield return new object[] { new ushort[] { 1, 2, 3 }, 0, new ulong[3], 0, 3, new ulong[] { 1, 2, 3 } }; yield return new object[] { new ushort[] { 1, 2, 3 }, 0, new int[3], 0, 3, new int[] { 1, 2, 3 } }; yield return new object[] { new ushort[] { 1, 2, 3 }, 0, new uint[3], 0, 3, new uint[] { 1, 2, 3 } }; yield return new object[] { new ushort[] { 1, 2, 3 }, 0, new char[3], 0, 3, new char[] { (char)1, (char)2, (char)3 } }; yield return new object[] { new ushort[] { 1, 2, 3 }, 0, new float[3], 0, 3, new float[] { 1, 2, 3 } }; yield return new object[] { new ushort[] { 1, 2, 3 }, 0, new double[3], 0, 3, new double[] { 1, 2, 3 } }; // SByte[] -> primitive[] yield return new object[] { new sbyte[] { 1, 2, 3 }, 0, new long[3], 0, 3, new long[] { 1, 2, 3 } }; yield return new object[] { new sbyte[] { 1, 2, 3 }, 0, new int[3], 0, 3, new int[] { 1, 2, 3 } }; yield return new object[] { new sbyte[] { 1, 2, 3 }, 0, new short[3], 0, 3, new short[] { 1, 2, 3 } }; yield return new object[] { new sbyte[] { 1, 2, 3 }, 0, new float[3], 0, 3, new float[] { 1, 2, 3 } }; yield return new object[] { new sbyte[] { 1, 2, 3 }, 0, new double[3], 0, 3, new double[] { 1, 2, 3 } }; // Byte[] -> primitive[] yield return new object[] { new byte[] { 1, 2, 3 }, 0, new long[3], 0, 3, new long[] { 1, 2, 3 } }; yield return new object[] { new byte[] { 1, 2, 3 }, 0, new ulong[3], 0, 3, new ulong[] { 1, 2, 3 } }; yield return new object[] { new byte[] { 1, 2, 3 }, 0, new int[3], 0, 3, new int[] { 1, 2, 3 } }; yield return new object[] { new byte[] { 1, 2, 3 }, 0, new uint[3], 0, 3, new uint[] { 1, 2, 3 } }; yield return new object[] { new byte[] { 1, 2, 3 }, 0, new short[3], 0, 3, new short[] { 1, 2, 3 } }; yield return new object[] { new byte[] { 1, 2, 3 }, 0, new ushort[3], 0, 3, new ushort[] { 1, 2, 3 } }; yield return new object[] { new byte[] { 1, 2, 3 }, 0, new char[3], 0, 3, new char[] { (char)1, (char)2, (char)3 } }; yield return new object[] { new byte[] { 1, 2, 3 }, 0, new float[3], 0, 3, new float[] { 1, 2, 3 } }; yield return new object[] { new byte[] { 1, 2, 3 }, 0, new double[3], 0, 3, new double[] { 1, 2, 3 } }; // Char[] -> primitive[] yield return new object[] { new char[] { (char)1, (char)2, (char)3 }, 0, new long[3], 0, 3, new long[] { 1, 2, 3 } }; yield return new object[] { new char[] { (char)1, (char)2, (char)3 }, 0, new ulong[3], 0, 3, new ulong[] { 1, 2, 3 } }; yield return new object[] { new char[] { (char)1, (char)2, (char)3 }, 0, new int[3], 0, 3, new int[] { 1, 2, 3 } }; yield return new object[] { new char[] { (char)1, (char)2, (char)3 }, 0, new uint[3], 0, 3, new uint[] { 1, 2, 3 } }; yield return new object[] { new char[] { (char)1, (char)2, (char)3 }, 0, new ushort[3], 0, 3, new ushort[] { 1, 2, 3 } }; yield return new object[] { new char[] { (char)1, (char)2, (char)3 }, 0, new float[3], 0, 3, new float[] { 1, 2, 3 } }; yield return new object[] { new char[] { (char)1, (char)2, (char)3 }, 0, new double[3], 0, 3, new double[] { 1, 2, 3 } }; // Single[] -> primitive[] yield return new object[] { new float[] { 1, 2.2f, 3 }, 0, new double[3], 0, 3, new double[] { 1, 2.2f, 3 } }; } public static IEnumerable<object[]> Copy_SZArray_UnreliableConversion_CanPerform_TestData() { // Interface1[] -> InterfaceImplementingInterface1[] works when all values are null yield return new object[] { new NonGenericInterface1[1], 0, new NonGenericInterfaceWithNonGenericInterface1[1], 0, 1, new NonGenericInterfaceWithNonGenericInterface1[1] }; // Interface1[] -> Interface2[] works when values are all null yield return new object[] { new NonGenericInterface1[1], 0, new NonGenericInterface2[1], 0, 1, new NonGenericInterface2[1] }; // Interface1[] -> Interface2[] works when values all implement Interface2 ClassWithNonGenericInterface1_2 twoInterfacesClass = new ClassWithNonGenericInterface1_2(); yield return new object[] { new NonGenericInterface1[] { twoInterfacesClass }, 0, new NonGenericInterface2[1], 0, 1, new NonGenericInterface2[] { twoInterfacesClass } }; StructWithNonGenericInterface1_2 twoInterfacesStruct = new StructWithNonGenericInterface1_2(); yield return new object[] { new NonGenericInterface1[] { twoInterfacesStruct }, 0, new NonGenericInterface2[1], 0, 1, new NonGenericInterface2[] { twoInterfacesStruct } }; // Interface1[] -> Any[] works when values are all null yield return new object[] { new NonGenericInterface1[1], 0, new ClassWithNonGenericInterface1[1], 0, 1, new ClassWithNonGenericInterface1[1] }; // Interface1[] -> Any[] works when values are all Any ClassWithNonGenericInterface1 oneInterfaceClass = new ClassWithNonGenericInterface1(); yield return new object[] { new NonGenericInterface1[] { oneInterfaceClass }, 0, new ClassWithNonGenericInterface1[1], 0, 1, new ClassWithNonGenericInterface1[] { oneInterfaceClass } }; StructWithNonGenericInterface1 oneInterfaceStruct = new StructWithNonGenericInterface1(); yield return new object[] { new NonGenericInterface1[] { oneInterfaceStruct }, 0, new StructWithNonGenericInterface1[1], 0, 1, new StructWithNonGenericInterface1[] { oneInterfaceStruct } }; // ReferenceType[] -> InterfaceNotImplementedByReferenceType[] works when values are all null yield return new object[] { new ClassWithNonGenericInterface1[1], 0, new NonGenericInterface2[1], 0, 1, new NonGenericInterface2[1] }; // ValueType[] -> ReferenceType[] yield return new object[] { new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 2, new object[10], 5, 3, new object[] { null, null, null, null, null, 2, 3, 4, null, null } }; yield return new object[] { new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 2, new IEquatable<int>[10], 5, 3, new IEquatable<int>[] { null, null, null, null, null, 2, 3, 4, null, null } }; yield return new object[] { new int?[] { 0, 1, 2, default(int?), 4, 5, 6, 7, 8, 9 }, 2, new object[10], 5, 3, new object[] { null, null, null, null, null, 2, null, 4, null, null } }; // ReferenceType[] -> ValueType[] yield return new object[] { new object[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 2, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc }, 5, 3, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 2, 3, 4, 0xcc, 0xcc } }; yield return new object[] { new IEquatable<int>[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 2, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc }, 5, 3, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 2, 3, 4, 0xcc, 0xcc } }; yield return new object[] { new IEquatable<int>[] { 0, new NotInt32(), 2, 3, 4, new NotInt32(), 6, 7, 8, 9 }, 2, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc }, 5, 3, new int[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 2, 3, 4, 0xcc, 0xcc } }; yield return new object[] { new object[] { 0, 1, 2, 3, null, 5, 6, 7, 8, 9 }, 2, new int?[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc }, 5, 3, new int?[] { 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 2, 3, null, 0xcc, 0xcc } }; // Struct[] -> object[] NonGenericStruct[] structArray1 = CreateStructArray(); yield return new object[] { structArray1, 0, new object[5], 0, 5, structArray1.Select(g => (object)g).ToArray() }; // BaseClass[] -> SubClass[] yield return new object[] { new NonGenericClass1[10], 0, new NonGenericSubClass1[10], 0, 10, new NonGenericSubClass1[10] }; // Class[] -> Interface[] yield return new object[] { new NonGenericClass1[10], 0, new NonGenericInterface1[10], 0, 10, new NonGenericInterface1[10] }; // Interface[] -> Class[] yield return new object[] { new NonGenericInterface1[10], 0, new NonGenericClass1[10], 0, 10, new NonGenericClass1[10] }; } public static IEnumerable<object[]> Copy_Array_UnreliableConversion_CanPerform_TestData() { // int[,] -> long[,] int[,] intRank2Array = new int[,] { { 1, 2, 3 }, { 4, 5, 6 } }; yield return new object[] { intRank2Array, 0, new long[2, 3], 0, 6, new long[,] { { 1, 2, 3 }, { 4, 5, 6 } } }; // int[,] -> object[,] yield return new object[] { intRank2Array, 0, new object[2, 3], 0, 6, new object[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } } }; yield return new object[] { intRank2Array, 0, new object[3, 2], 0, 6, new object[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } } }; yield return new object[] { intRank2Array, 1, new object[2, 3], 2, 3, new object[,] { { null, null, 2 }, { 3, 4, null } } }; // object[,] -> int[,] object[,] objectRank2Array = new object[,] { { 1, 2, 3 }, { 4, 5, 6 } }; yield return new object[] { objectRank2Array, 0, new int[2, 3], 0, 6, intRank2Array }; yield return new object[] { objectRank2Array, 0, new int[3, 2], 0, 6, new int[,] { { 1, 2 }, { 3, 4 }, { 5, 6 } } }; yield return new object[] { objectRank2Array, 1, new int[2, 3], 2, 3, new int[,] { { 0, 0, 2 }, { 3, 4, 0 } } }; } [Theory] [MemberData(nameof(Copy_SZArray_Reliable_TestData))] [MemberData(nameof(Copy_SZArray_PrimitiveWidening_TestData))] [MemberData(nameof(Copy_SZArray_UnreliableConversion_CanPerform_TestData))] public static void Copy_SZArray(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, Array expected) { // Basic: forward SZArray Copy(sourceArray, sourceIndex, destinationArray, destinationIndex, length, expected); // Advanced: convert SZArray to an array with non-zero lower bound const int LowerBound = 5; Array nonZeroSourceArray = NonZeroLowerBoundArray(sourceArray, LowerBound); Array nonZeroDestinationArray = sourceArray == destinationArray ? nonZeroSourceArray : NonZeroLowerBoundArray(destinationArray, LowerBound); Copy(nonZeroSourceArray, sourceIndex + LowerBound, nonZeroDestinationArray, destinationIndex + LowerBound, length, NonZeroLowerBoundArray(expected, LowerBound)); if (sourceIndex == 0 && length == sourceArray.Length) { // CopyTo(Array, int) Array sourceClone = (Array)sourceArray.Clone(); Array destinationArrayClone = sourceArray == destinationArray ? sourceClone : (Array)destinationArray.Clone(); sourceClone.CopyTo(destinationArrayClone, destinationIndex); Assert.Equal(expected, destinationArrayClone); } } [Theory] [MemberData(nameof(Copy_Array_Reliable_TestData))] [MemberData(nameof(Copy_Array_UnreliableConversion_CanPerform_TestData))] public static void Copy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, Array expected) { bool overlaps = sourceArray == destinationArray; if (sourceIndex == sourceArray.GetLowerBound(0) && destinationIndex == destinationArray.GetLowerBound(0)) { // Use Copy(Array, Array, int) Array sourceArrayClone1 = (Array)sourceArray.Clone(); Array destinationArrayClone1 = overlaps ? sourceArrayClone1 : (Array)destinationArray.Clone(); Array.Copy(sourceArrayClone1, destinationArrayClone1, length); Assert.Equal(expected, destinationArrayClone1); } // Use Copy(Array, int, Array, int, int) Array sourceArrayClone2 = (Array)sourceArray.Clone(); Array destinationArrayClone2 = overlaps ? sourceArrayClone2 : (Array)destinationArray.Clone(); Array.Copy(sourceArrayClone2, sourceIndex, destinationArrayClone2, destinationIndex, length); Assert.Equal(expected, destinationArrayClone2); } [Theory] [MemberData(nameof(Copy_SZArray_Reliable_TestData))] [MemberData(nameof(Copy_Array_Reliable_TestData))] public static void ConstrainedCopy(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, Array expected) { Array sourceArrayClone = (Array)sourceArray.Clone(); Array destinationArrayClone = sourceArray == destinationArray ? sourceArrayClone : (Array)destinationArray.Clone(); Array.ConstrainedCopy(sourceArrayClone, sourceIndex, destinationArrayClone, destinationIndex, length); Assert.Equal(expected, destinationArrayClone); } [Fact] public static void Copy_NullSourceArray_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("sourceArray", () => Array.Copy(null, new string[10], 0)); Assert.Throws<ArgumentNullException>("source", () => Array.Copy(null, 0, new string[10], 0, 0)); Assert.Throws<ArgumentNullException>("source", () => Array.ConstrainedCopy(null, 0, new string[10], 0, 0)); } [Fact] public static void Copy_NullDestinationArray_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("destinationArray", () => Array.Copy(new string[10], null, 0)); Assert.Throws<ArgumentNullException>("dest", () => Array.Copy(new string[10], 0, null, 0, 0)); Assert.Throws<ArgumentNullException>("dest", () => Array.ConstrainedCopy(new string[10], 0, null, 0, 0)); Assert.Throws<ArgumentNullException>("dest", () => new string[10].CopyTo(null, 0)); } [Fact] public static void Copy_SourceAndDestinationArrayHaveDifferentRanks_ThrowsRankException() { Assert.Throws<RankException>(() => Array.Copy(new string[10, 10], new string[10], 0)); Assert.Throws<RankException>(() => Array.Copy(new string[10, 10], 0, new string[10], 0, 0)); Assert.Throws<RankException>(() => Array.ConstrainedCopy(new string[10, 10], 0, new string[10], 0, 0)); } public static IEnumerable<object[]> Copy_SourceAndDestinationNeverConvertible_TestData() { yield return new object[] { new string[1], new int[1] }; yield return new object[] { new int[1], new string[1] }; yield return new object[] { new int[1], new IEnumerable<int>[1] }; // Invalid jagged array yield return new object[] { new int[1][], new int[1][,] }; yield return new object[] { new int[1][,], new int[1][] }; yield return new object[] { new int[1][], new string[1][] }; yield return new object[] { new string[1][], new int[1][] }; // Can't primitive widen arrays yield return new object[] { new char[1][], new ushort[1][] }; yield return new object[] { new ushort[1][], new char[1][] }; // Can't primitive widen Int64 yield return new object[] { new long[1], new ulong[1] }; yield return new object[] { new long[1], new int[1] }; yield return new object[] { new long[1], new uint[1] }; yield return new object[] { new long[1], new short[1] }; yield return new object[] { new long[1], new ushort[1] }; yield return new object[] { new long[1], new sbyte[1] }; yield return new object[] { new long[1], new byte[1] }; yield return new object[] { new long[1], new char[1] }; yield return new object[] { new long[1], new bool[1] }; yield return new object[] { new long[1], new IntPtr[1] }; yield return new object[] { new long[1], new UIntPtr[1] }; // Can't primitive widen UInt64 yield return new object[] { new ulong[1], new long[1] }; yield return new object[] { new ulong[1], new int[1] }; yield return new object[] { new ulong[1], new uint[1] }; yield return new object[] { new ulong[1], new short[1] }; yield return new object[] { new ulong[1], new ushort[1] }; yield return new object[] { new ulong[1], new sbyte[1] }; yield return new object[] { new ulong[1], new byte[1] }; yield return new object[] { new ulong[1], new char[1] }; yield return new object[] { new ulong[1], new bool[1] }; yield return new object[] { new ulong[1], new IntPtr[1] }; yield return new object[] { new ulong[1], new UIntPtr[1] }; // Can't primitive widen Int32 yield return new object[] { new int[1], new ulong[1] }; yield return new object[] { new int[1], new uint[1] }; yield return new object[] { new int[1], new short[1] }; yield return new object[] { new int[1], new ushort[1] }; yield return new object[] { new int[1], new sbyte[1] }; yield return new object[] { new int[1], new byte[1] }; yield return new object[] { new int[1], new char[1] }; yield return new object[] { new int[1], new bool[1] }; yield return new object[] { new int[1], new IntPtr[1] }; yield return new object[] { new int[1], new UIntPtr[1] }; // Can't primitive widen UInt32 yield return new object[] { new uint[1], new short[1] }; yield return new object[] { new uint[1], new ushort[1] }; yield return new object[] { new uint[1], new sbyte[1] }; yield return new object[] { new uint[1], new byte[1] }; yield return new object[] { new uint[1], new char[1] }; yield return new object[] { new uint[1], new bool[1] }; yield return new object[] { new uint[1], new IntPtr[1] }; yield return new object[] { new uint[1], new UIntPtr[1] }; // Can't primitive widen Int16 yield return new object[] { new short[1], new ulong[1] }; yield return new object[] { new short[1], new ushort[1] }; yield return new object[] { new short[1], new ushort[1] }; yield return new object[] { new short[1], new sbyte[1] }; yield return new object[] { new short[1], new byte[1] }; yield return new object[] { new short[1], new char[1] }; yield return new object[] { new short[1], new bool[1] }; yield return new object[] { new short[1], new IntPtr[1] }; yield return new object[] { new short[1], new UIntPtr[1] }; // Can't primitive widen UInt16 yield return new object[] { new ushort[1], new sbyte[1] }; yield return new object[] { new ushort[1], new byte[1] }; yield return new object[] { new ushort[1], new bool[1] }; yield return new object[] { new ushort[1], new IntPtr[1] }; yield return new object[] { new ushort[1], new UIntPtr[1] }; // Can't primitive widen SByte yield return new object[] { new sbyte[1], new ulong[1] }; yield return new object[] { new sbyte[1], new uint[1] }; yield return new object[] { new sbyte[1], new ushort[1] }; yield return new object[] { new sbyte[1], new byte[1] }; yield return new object[] { new sbyte[1], new char[1] }; yield return new object[] { new sbyte[1], new bool[1] }; yield return new object[] { new sbyte[1], new IntPtr[1] }; yield return new object[] { new sbyte[1], new UIntPtr[1] }; // Can't primitive widen Byte yield return new object[] { new byte[1], new sbyte[1] }; yield return new object[] { new byte[1], new bool[1] }; yield return new object[] { new byte[1], new IntPtr[1] }; yield return new object[] { new byte[1], new UIntPtr[1] }; // Can't primitive widen Bool yield return new object[] { new bool[1], new long[1] }; yield return new object[] { new bool[1], new ulong[1] }; yield return new object[] { new bool[1], new int[1] }; yield return new object[] { new bool[1], new uint[1] }; yield return new object[] { new bool[1], new short[1] }; yield return new object[] { new bool[1], new ushort[1] }; yield return new object[] { new bool[1], new sbyte[1] }; yield return new object[] { new bool[1], new byte[1] }; yield return new object[] { new bool[1], new char[1] }; yield return new object[] { new bool[1], new float[1] }; yield return new object[] { new bool[1], new double[1] }; yield return new object[] { new bool[1], new IntPtr[1] }; yield return new object[] { new bool[1], new UIntPtr[1] }; // Can't primitive widen Single yield return new object[] { new float[1], new long[1] }; yield return new object[] { new float[1], new ulong[1] }; yield return new object[] { new float[1], new int[1] }; yield return new object[] { new float[1], new uint[1] }; yield return new object[] { new float[1], new short[1] }; yield return new object[] { new float[1], new ushort[1] }; yield return new object[] { new float[1], new sbyte[1] }; yield return new object[] { new float[1], new byte[1] }; yield return new object[] { new float[1], new char[1] }; yield return new object[] { new float[1], new bool[1] }; yield return new object[] { new float[1], new IntPtr[1] }; yield return new object[] { new float[1], new UIntPtr[1] }; // Can't primitive widen Double yield return new object[] { new double[1], new long[1] }; yield return new object[] { new double[1], new ulong[1] }; yield return new object[] { new double[1], new int[1] }; yield return new object[] { new double[1], new uint[1] }; yield return new object[] { new double[1], new short[1] }; yield return new object[] { new double[1], new ushort[1] }; yield return new object[] { new double[1], new sbyte[1] }; yield return new object[] { new double[1], new byte[1] }; yield return new object[] { new double[1], new char[1] }; yield return new object[] { new double[1], new bool[1] }; yield return new object[] { new double[1], new float[1] }; yield return new object[] { new double[1], new IntPtr[1] }; yield return new object[] { new double[1], new UIntPtr[1] }; // Can't primitive widen IntPtr yield return new object[] { new IntPtr[1], new long[1] }; yield return new object[] { new IntPtr[1], new ulong[1] }; yield return new object[] { new IntPtr[1], new int[1] }; yield return new object[] { new IntPtr[1], new uint[1] }; yield return new object[] { new IntPtr[1], new short[1] }; yield return new object[] { new IntPtr[1], new ushort[1] }; yield return new object[] { new IntPtr[1], new sbyte[1] }; yield return new object[] { new IntPtr[1], new byte[1] }; yield return new object[] { new IntPtr[1], new char[1] }; yield return new object[] { new IntPtr[1], new bool[1] }; yield return new object[] { new IntPtr[1], new float[1] }; yield return new object[] { new IntPtr[1], new double[1] }; yield return new object[] { new IntPtr[1], new UIntPtr[1] }; // Can't primitive widen UIntPtr yield return new object[] { new UIntPtr[1], new long[1] }; yield return new object[] { new UIntPtr[1], new ulong[1] }; yield return new object[] { new UIntPtr[1], new int[1] }; yield return new object[] { new UIntPtr[1], new uint[1] }; yield return new object[] { new UIntPtr[1], new short[1] }; yield return new object[] { new UIntPtr[1], new ushort[1] }; yield return new object[] { new UIntPtr[1], new sbyte[1] }; yield return new object[] { new UIntPtr[1], new byte[1] }; yield return new object[] { new UIntPtr[1], new char[1] }; yield return new object[] { new UIntPtr[1], new bool[1] }; yield return new object[] { new UIntPtr[1], new float[1] }; yield return new object[] { new UIntPtr[1], new double[1] }; yield return new object[] { new UIntPtr[1], new IntPtr[1] }; // Interface[] -> Any[] only works if Any implements Interface yield return new object[] { new NonGenericInterface2[1], new StructWithNonGenericInterface1[1] }; // ValueType[] -> InterfaceNotImplementedByValueType[] never works yield return new object[] { new StructWithNonGenericInterface1[1], new NonGenericInterface2[1] }; // Can't get Enum from its underlying type yield return new object[] { new int[1], new Int32Enum[1] }; // Can't primitive widen Enum yield return new object[] { new Int32Enum[1], new long[1] }; yield return new object[] { new Int32Enum[1], new Int64Enum[1] }; } [Theory] [MemberData(nameof(Copy_SourceAndDestinationNeverConvertible_TestData))] public static void Copy_SourceAndDestinationNeverConvertible_ThrowsArrayTypeMismatchException(Array sourceArray, Array destinationArray) { Assert.Throws<ArrayTypeMismatchException>(() => Array.Copy(sourceArray, destinationArray, 0)); Assert.Throws<ArrayTypeMismatchException>(() => Array.Copy(sourceArray, sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), 0)); Assert.Throws<ArrayTypeMismatchException>(() => sourceArray.CopyTo(destinationArray, destinationArray.GetLowerBound(0))); } [Fact] public static unsafe void Copy_PointerArrayToNonPointerArray_ThrowsArrayTypeMismatchException() { Copy_SourceAndDestinationNeverConvertible_ThrowsArrayTypeMismatchException(new int[1], new int*[1]); Copy_SourceAndDestinationNeverConvertible_ThrowsArrayTypeMismatchException(new int*[1], new int[1]); } public static IEnumerable<object[]> Copy_UnreliableCoversion_CantPerform_TestData() { yield return new object[] { new object[] { "1" }, new int[1] }; IEquatable<int>[] interfaceArray1 = new IEquatable<int>[10] { 0, 0, 0, 0, new NotInt32(), 0, 0, 0, 0, 0 }; yield return new object[] { interfaceArray1, new int[10]}; IEquatable<int>[] interfaceArray2 = new IEquatable<int>[10] { 0, 0, 0, 0, new NotInt32(), 0, 0, 0, 0, 0 }; yield return new object[] { interfaceArray2, new int[10] }; // Interface1[] -> Interface2[] when an Interface1 can't be assigned to Interface2 yield return new object[] { new NonGenericInterface1[] { new StructWithNonGenericInterface1() }, new NonGenericInterface2[1] }; yield return new object[] { new NonGenericInterface1[] { new StructWithNonGenericInterface1() }, new NonGenericInterface2[1] }; yield return new object[] { new NonGenericInterface1[] { new ClassWithNonGenericInterface1() }, new NonGenericInterfaceWithNonGenericInterface1[1] }; yield return new object[] { new NonGenericInterface1[] { new StructWithNonGenericInterface1() }, new NonGenericInterfaceWithNonGenericInterface1[1] }; // Interface1[] -> ValueType[] when an Interface1 is null yield return new object[] { new NonGenericInterface1[1], new StructWithNonGenericInterface1[1] }; // Interface1[] -> ValueType[] when an Interface1 can't be assigned to ValueType yield return new object[] { new NonGenericInterface1[] { new ClassWithNonGenericInterface1() }, new StructWithNonGenericInterface1[1] }; } [Theory] [MemberData(nameof(Copy_UnreliableCoversion_CantPerform_TestData))] public static void Copy_UnreliableConverson_CantPerform_ThrowsInvalidCastException(Array sourceArray, Array destinationArray) { int length = Math.Min(sourceArray.Length, destinationArray.Length); Assert.Throws<InvalidCastException>(() => Array.Copy(sourceArray, destinationArray, length)); Assert.Throws<InvalidCastException>(() => Array.Copy(sourceArray, sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), length)); Assert.Throws<InvalidCastException>(() => sourceArray.CopyTo(destinationArray, destinationArray.GetLowerBound(0))); // No exception is thrown if length == 0, as conversion error checking occurs during, not before copying Array.Copy(sourceArray, sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), 0); } [Theory] [MemberData(nameof(Copy_UnreliableCoversion_CantPerform_TestData))] public static void ConstrainedCopy_UnreliableConversion_CantPerform_ThrowsArrayTypeMismatchException(Array sourceArray, Array destinationArray) { int length = Math.Min(sourceArray.Length, destinationArray.Length); ConstrainedCopy_UnreliableConversion_ThrowsArrayTypeMismatchException(sourceArray, sourceArray.GetLowerBound(0), destinationArray, destinationArray.GetLowerBound(0), length, null); } [Theory] [MemberData(nameof(Copy_SZArray_PrimitiveWidening_TestData))] [MemberData(nameof(Copy_SZArray_UnreliableConversion_CanPerform_TestData))] [MemberData(nameof(Copy_Array_UnreliableConversion_CanPerform_TestData))] public static void ConstrainedCopy_UnreliableConversion_ThrowsArrayTypeMismatchException(Array sourceArray, int sourceIndex, Array destinationArray, int destinationIndex, int length, Array _) { Assert.Throws<ArrayTypeMismatchException>(() => Array.ConstrainedCopy(sourceArray, sourceIndex, destinationArray, destinationIndex, length)); } [Fact] public static void Copy_NegativeLength_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.Copy(new string[10], new string[10], -1)); Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.Copy(new string[10], 0, new string[10], 0, -1)); Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.ConstrainedCopy(new string[10], 0, new string[10], 0, -1)); } [Theory] [InlineData(8, 0, 10, 0, 9)] [InlineData(8, 8, 10, 0, 1)] [InlineData(8, 9, 10, 0, 0)] [InlineData(10, 0, 8, 0, 9)] [InlineData(10, 0, 8, 8, 1)] [InlineData(10, 0, 8, 9, 0)] public static void Copy_IndexPlusLengthGreaterThanArrayLength_ThrowsArgumentException(int sourceCount, int sourceIndex, int destinationCount, int destinationIndex, int count) { if (sourceIndex == 0 && destinationIndex == 0) { Assert.Throws<ArgumentException>("", () => Array.Copy(new string[sourceCount], new string[destinationCount], count)); } Assert.Throws<ArgumentException>("", () => Array.Copy(new string[sourceCount], sourceIndex, new string[destinationCount], destinationIndex, count)); Assert.Throws<ArgumentException>("", () => Array.ConstrainedCopy(new string[sourceCount], sourceIndex, new string[destinationCount], destinationIndex, count)); } [Fact] public static void Copy_StartIndexNegative_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("srcIndex", () => Array.Copy(new string[10], -1, new string[10], 0, 0)); Assert.Throws<ArgumentOutOfRangeException>("srcIndex", () => Array.ConstrainedCopy(new string[10], -1, new string[10], 0, 0)); } [Fact] public static void Copy_DestinationIndexNegative_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("dstIndex", () => Array.Copy(new string[10], 0, new string[10], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>("dstIndex", () => Array.ConstrainedCopy(new string[10], 0, new string[10], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>("dstIndex", () => new string[10].CopyTo(new string[10], -1)); } [Fact] public static void CopyTo_SourceMultiDimensional_ThrowsRankException() { Assert.Throws<RankException>(() => new int[3, 3].CopyTo(new int[3], 0)); } [Fact] public static void CopyTo_DestinationMultiDimensional_ThrowsArgumentException() { Assert.Throws<ArgumentException>(null, () => new int[3].CopyTo(new int[10, 10], 0)); } [Fact] public static void CopyTo_IndexInvalid_ThrowsArgumentException() { Assert.Throws<ArgumentException>("", () => new int[3].CopyTo(new int[10], 10)); // Index > destination.Length } public static unsafe IEnumerable<object[]> CreateInstance_TestData() { return new object[][] { // Primitives new object[] { typeof(string), default(string) }, new object[] { typeof(sbyte), default(sbyte) }, new object[] { typeof(byte), default(byte) }, new object[] { typeof(short), default(short) }, new object[] { typeof(ushort), default(ushort) }, new object[] { typeof(int), default(int) }, new object[] { typeof(uint), default(uint) }, new object[] { typeof(long), default(long) }, new object[] { typeof(ulong), default(ulong) }, new object[] { typeof(char), default(char) }, new object[] { typeof(bool), default(bool) }, new object[] { typeof(float), default(float) }, new object[] { typeof(double), default(double) }, new object[] { typeof(IntPtr), default(IntPtr) }, new object[] { typeof(UIntPtr), default(UIntPtr) }, // Array, pointers new object[] { typeof(int[]), default(int[]) }, new object[] { typeof(int*), null }, // Classes, structs, interfaces, enums new object[] { typeof(NonGenericClass1), default(NonGenericClass1) }, new object[] { typeof(GenericClass<int>), default(GenericClass<int>) }, new object[] { typeof(NonGenericStruct), default(NonGenericStruct) }, new object[] { typeof(GenericStruct<int>), default(GenericStruct<int>) }, new object[] { typeof(NonGenericInterface1), default(NonGenericInterface1) }, new object[] { typeof(GenericInterface<int>), default(GenericInterface<int>) }, new object[] { typeof(AbstractClass), default(AbstractClass) }, new object[] { typeof(StaticClass), default(StaticClass) }, new object[] { typeof(Int32Enum), default(Int32Enum) } }; } [Theory] [MemberData(nameof(CreateInstance_TestData))] public static void CreateInstance(Type elementType, object repeatedValue) { CreateInstance(elementType, new int[] { 10 }, new int[1], repeatedValue); CreateInstance(elementType, new int[] { 0 }, new int[1], repeatedValue); CreateInstance(elementType, new int[] { 1, 2 }, new int[] { 1, 2 }, repeatedValue); CreateInstance(elementType, new int[] { 5, 6 }, new int[] { int.MinValue, 0 }, repeatedValue); } [Theory] [InlineData(typeof(int), new int[] { 1, 2 }, new int[] { 0, 0 }, default(int))] [InlineData(typeof(int), new int[] { 1, 2, 3 }, new int[] { 0, 0, 0 }, default(int))] [InlineData(typeof(int), new int[] { 1, 2, 3, 4 }, new int[] { 0, 0, 0, 0 }, default(int))] [InlineData(typeof(int), new int[] { 7, 8, 9 }, new int[] { 1, 2, 3 }, default(int))] public static void CreateInstance(Type elementType, int[] lengths, int[] lowerBounds, object repeatedValue) { if (lowerBounds.All(lowerBound => lowerBound == 0)) { if (lengths.Length == 1) { // Use CreateInstance(Type, int) Array array1 = Array.CreateInstance(elementType, lengths[0]); VerifyArray(array1, elementType, lengths, lowerBounds, repeatedValue); } // Use CreateInstance(Type, int[]) Array array2 = Array.CreateInstance(elementType, lengths); VerifyArray(array2, elementType, lengths, lowerBounds, repeatedValue); } // Use CreateInstance(Type, int[], int[]) Array array3 = Array.CreateInstance(elementType, lengths, lowerBounds); VerifyArray(array3, elementType, lengths, lowerBounds, repeatedValue); } [Fact] public static void CreateInstance_NullElementType_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("elementType", () => Array.CreateInstance(null, 0)); Assert.Throws<ArgumentNullException>("elementType", () => Array.CreateInstance(null, new int[1])); Assert.Throws<ArgumentNullException>("elementType", () => Array.CreateInstance(null, new int[1], new int[1])); } public static IEnumerable<object[]> CreateInstance_NotSupportedType_TestData() { yield return new object[] { typeof(void) }; yield return new object[] { typeof(int).MakeByRefType() }; yield return new object[] { typeof(GenericClass<>) }; yield return new object[] { typeof(GenericClass<>).MakeGenericType(typeof(GenericClass<>)) }; yield return new object[] { typeof(GenericClass<>).GetTypeInfo().GetGenericArguments()[0] }; } [Theory] [MemberData(nameof(CreateInstance_NotSupportedType_TestData))] public static void CreateInstance_NotSupportedType_ThrowsNotSupportedException(Type elementType) { Assert.Throws<NotSupportedException>(() => Array.CreateInstance(elementType, 0)); Assert.Throws<NotSupportedException>(() => Array.CreateInstance(elementType, new int[1])); Assert.Throws<NotSupportedException>(() => Array.CreateInstance(elementType, new int[1], new int[1])); } [Fact] public static void CreateInstance_NegativeLength_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.CreateInstance(typeof(int), -1)); Assert.Throws<ArgumentOutOfRangeException>("lengths[0]", () => Array.CreateInstance(typeof(int), new int[] { -1 })); Assert.Throws<ArgumentOutOfRangeException>("lengths[0]", () => Array.CreateInstance(typeof(int), new int[] { -1 }, new int[1])); } [Fact] public static void CreateInstance_TypeNotRuntimeType_ThrowsArgumentException() { Assert.Throws<ArgumentException>("elementType", () => Array.CreateInstance(Helpers.NonRuntimeType(), 0)); Assert.Throws<ArgumentException>("elementType", () => Array.CreateInstance(Helpers.NonRuntimeType(), new int[1])); Assert.Throws<ArgumentException>("elementType", () => Array.CreateInstance(Helpers.NonRuntimeType(), new int[1], new int[1])); } [Fact] public static void CreateInstance_LengthsNull_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("lengths", () => Array.CreateInstance(typeof(int), null, new int[1])); } [Fact] public static void CreateInstance_LengthsEmpty_ThrowsArgumentException() { Assert.Throws<ArgumentException>(null, () => Array.CreateInstance(typeof(int), new int[0])); Assert.Throws<ArgumentException>(null, () => Array.CreateInstance(typeof(int), new int[0], new int[1])); } [Fact] public static void CreateInstance_LowerBoundNull_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("lowerBounds", () => Array.CreateInstance(typeof(int), new int[] { 1 }, null)); } [Theory] [InlineData(0)] [InlineData(2)] public static void CreateInstance_LengthsAndLowerBoundsHaveDifferentLengths_ThrowsArgumentException(int length) { Assert.Throws<ArgumentException>(null, () => Array.CreateInstance(typeof(int), new int[1], new int[length])); } [Fact] public static void CreateInstance_Type_LengthsPlusLowerBoundOverflows_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>(null, () => Array.CreateInstance(typeof(int), new int[] { int.MaxValue }, new int[] { 2 })); } [Fact] public static void Empty() { Assert.True(Array.Empty<int>() != null); Assert.Equal(0, Array.Empty<int>().Length); Assert.Equal(1, Array.Empty<int>().Rank); Assert.Same(Array.Empty<int>(), Array.Empty<int>()); Assert.True(Array.Empty<object>() != null); Assert.Equal(0, Array.Empty<object>().Length); Assert.Equal(1, Array.Empty<object>().Rank); Assert.Same(Array.Empty<object>(), Array.Empty<object>()); } [Fact] public static void Find() { var intArray = new int[] { 7, 8, 9 }; // Exists included here since it's a trivial wrapper around FindIndex Assert.True(Array.Exists(intArray, i => i == 8)); Assert.False(Array.Exists(intArray, i => i == -1)); int[] results = Array.FindAll(intArray, i => (i % 2) != 0); Assert.Equal(results.Length, 2); Assert.True(Array.Exists(results, i => i == 7)); Assert.True(Array.Exists(results, i => i == 9)); var stringArray = new string[] { "7", "8", "88", "888", "9" }; Assert.Equal("8", Array.Find(stringArray, s => s.StartsWith("8"))); Assert.Null(Array.Find(stringArray, s => s == "X")); intArray = new int[] { 40, 41, 42, 43, 44, 45, 46, 47, 48, 49 }; Assert.Equal(3, Array.FindIndex(intArray, i => i >= 43)); Assert.Equal(-1, Array.FindIndex(intArray, i => i == 99)); Assert.Equal(3, Array.FindIndex(intArray, 3, i => i == 43)); Assert.Equal(-1, Array.FindIndex(intArray, 4, i => i == 43)); Assert.Equal(3, Array.FindIndex(intArray, 1, 3, i => i == 43)); Assert.Equal(-1, Array.FindIndex(intArray, 1, 2, i => i == 43)); stringArray = new string[] { "7", "8", "88", "888", "9" }; Assert.Equal("888", Array.FindLast(stringArray, s => s.StartsWith("8"))); Assert.Null(Array.FindLast(stringArray, s => s == "X")); intArray = new int[] { 40, 41, 42, 43, 44, 45, 46, 47, 48, 49 }; Assert.Equal(9, Array.FindLastIndex(intArray, i => i >= 43)); Assert.Equal(-1, Array.FindLastIndex(intArray, i => i == 99)); Assert.Equal(3, Array.FindLastIndex(intArray, 3, i => i == 43)); Assert.Equal(-1, Array.FindLastIndex(intArray, 2, i => i == 43)); Assert.Equal(3, Array.FindLastIndex(intArray, 5, 3, i => i == 43)); Assert.Equal(-1, Array.FindLastIndex(intArray, 5, 2, i => i == 43)); intArray = new int[0]; Assert.Equal(-1, Array.FindLastIndex(intArray, -1, i => i == 43)); } [Fact] public static void Exists_Invalid() { Assert.Throws<ArgumentNullException>("array", () => Array.Exists((int[])null, i => i == 43)); // Array is null Assert.Throws<ArgumentNullException>("match", () => Array.Exists(new int[0], null)); // Match is null } [Fact] public static void Find_Invalid() { Assert.Throws<ArgumentNullException>("array", () => Array.Find((int[])null, i => i == 43)); // Array is null Assert.Throws<ArgumentNullException>("match", () => Array.Find(new int[0], null)); // Match is null } [Fact] public static void FindIndex_Invalid() { // Array is null Assert.Throws<ArgumentNullException>("array", () => Array.FindIndex((int[])null, i => i == 43)); Assert.Throws<ArgumentNullException>("array", () => Array.FindIndex((int[])null, 0, i => i == 43)); Assert.Throws<ArgumentNullException>("array", () => Array.FindIndex((int[])null, 0, 0, i => i == 43)); // Start index < 0 Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.FindIndex(new int[3], -1, i => i == 43)); Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.FindIndex(new int[3], -1, 0, i => i == 43)); // Start index > array.Length Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.FindIndex(new int[3], 4, i => i == 43)); Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.FindIndex(new int[3], 4, 0, i => i == 43)); // Count < 0 or count > array.Length Assert.Throws<ArgumentOutOfRangeException>("count", () => Array.FindIndex(new int[3], 0, -1, i => i == 43)); Assert.Throws<ArgumentOutOfRangeException>("count", () => Array.FindIndex(new int[3], 0, 4, i => i == 43)); // Start index + count > array.Length Assert.Throws<ArgumentOutOfRangeException>("count", () => Array.FindIndex(new int[3], 3, 1, i => i == 43)); Assert.Throws<ArgumentOutOfRangeException>("count", () => Array.FindIndex(new int[3], 2, 2, i => i == 43)); } [Fact] public static void FindAll_Invalid() { Assert.Throws<ArgumentNullException>("array", () => Array.FindAll((int[])null, i => i == 43)); // Array is null Assert.Throws<ArgumentNullException>("match", () => Array.FindAll(new int[0], null)); // Match is null } [Fact] public static void FindLast_Invalid() { Assert.Throws<ArgumentNullException>("array", () => Array.FindLast((int[])null, i => i == 43)); // Array is null Assert.Throws<ArgumentNullException>("match", () => Array.FindLast(new int[0], null)); // Match is null } [Fact] public static void FindLastIndex_Invalid() { // Array is null Assert.Throws<ArgumentNullException>("array", () => Array.FindLastIndex((int[])null, i => i == 43)); Assert.Throws<ArgumentNullException>("array", () => Array.FindLastIndex((int[])null, 0, i => i == 43)); Assert.Throws<ArgumentNullException>("array", () => Array.FindLastIndex((int[])null, 0, 0, i => i == 43)); // Match is null Assert.Throws<ArgumentNullException>("match", () => Array.FindLastIndex(new int[0], null)); Assert.Throws<ArgumentNullException>("match", () => Array.FindLastIndex(new int[0], 0, null)); Assert.Throws<ArgumentNullException>("match", () => Array.FindLastIndex(new int[0], 0, 0, null)); Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.FindLastIndex(new int[0], 0, i => i == 43)); // Start index != -1 for an empty array // Start index < 0 Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.FindLastIndex(new int[3], -1, i => i == 43)); Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.FindLastIndex(new int[3], -1, 0, i => i == 43)); // Start index > array.Length Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.FindLastIndex(new int[3], 4, i => i == 43)); Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.FindLastIndex(new int[3], 4, 0, i => i == 43)); // Count < 0 or count > array.Length Assert.Throws<ArgumentOutOfRangeException>("count", () => Array.FindLastIndex(new int[3], 0, -1, i => i == 43)); Assert.Throws<ArgumentOutOfRangeException>("count", () => Array.FindLastIndex(new int[3], 0, 4, i => i == 43)); // Start index + count > array.Length Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.FindLastIndex(new int[3], 3, 1, i => i == 43)); } public static IEnumerable<object[]> GetEnumerator_TestData() { yield return new object[] { new int[0] }; yield return new object[] { new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 } }; yield return new object[] { new int[,] { { 1, 2 }, { 2, 4 } } }; yield return new object[] { new char[] { '7', '8', '9' } }; yield return new object[] { Array.CreateInstance(typeof(int), new int[] { 3 }, new int[] { 4 }) }; yield return new object[] { Array.CreateInstance(typeof(int), new int[] { 3, 3 }, new int[] { 4, 5 }) }; } [Theory] [MemberData(nameof(GetEnumerator_TestData))] public static void GetEnumerator(Array array) { Assert.NotSame(array.GetEnumerator(), array.GetEnumerator()); Array expected = array.Cast<object>().ToArray(); // Flatten multidimensional arrays IEnumerator enumerator = array.GetEnumerator(); for (int i = 0; i < 2; i++) { int counter = 0; while (enumerator.MoveNext()) { Assert.Equal(expected.GetValue(counter), enumerator.Current); counter++; } Assert.False(enumerator.MoveNext()); Assert.Equal(array.Length, counter); enumerator.Reset(); } } [Theory] [MemberData(nameof(GetEnumerator_TestData))] public static void GetEnumerator_Invalid(Array array) { IEnumerator enumerator = array.GetEnumerator(); // Enumerator should throw when accessing Current before starting enumeration Assert.Throws<InvalidOperationException>(() => enumerator.Current); while (enumerator.MoveNext()) ; // Enumerator should throw when accessing Current after finishing enumeration Assert.False(enumerator.MoveNext()); Assert.Throws<InvalidOperationException>(() => enumerator.Current); // Enumerator should throw when accessing Current after being reset enumerator.Reset(); Assert.Throws<InvalidOperationException>(() => enumerator.Current); } [Fact] public static unsafe void GetEnumerator_ArrayOfPointers_ThrowsNotSupportedException() { Array nonEmptyArray = new int*[2]; Assert.Throws<NotSupportedException>(() => { foreach (object obj in nonEmptyArray) { } }); Array emptyArray = new int*[0]; foreach (object obj in emptyArray) { } } public static IEnumerable<object[]> IndexOf_SZArray_TestData() { // SByte yield return new object[] { new sbyte[] { 1, 2, 3, 3 }, (sbyte)1, 0, 4, 0 }; yield return new object[] { new sbyte[] { 1, 2, 3, 3 }, (sbyte)3, 0, 4, 2 }; yield return new object[] { new sbyte[] { 1, 2, 3, 3 }, (sbyte)2, 1, 2, 1 }; yield return new object[] { new sbyte[] { 1, 2, 3, 3 }, (sbyte)1, 1, 2, -1 }; yield return new object[] { new sbyte[] { 1, 2, 3, 3 }, (sbyte)1, 4, 0, -1 }; yield return new object[] { new sbyte[] { 1, 2, 3, 3 }, (sbyte)1, 0, 0, -1 }; yield return new object[] { new sbyte[0], (sbyte)1, 0, 0, -1 }; // Byte yield return new object[] { new byte[] { 1, 2, 3, 3 }, (byte)1, 0, 4, 0 }; yield return new object[] { new byte[] { 1, 2, 3, 3 }, (byte)3, 0, 4, 2 }; yield return new object[] { new byte[] { 1, 2, 3, 3 }, (byte)2, 1, 2, 1 }; yield return new object[] { new byte[] { 1, 2, 3, 3 }, (byte)1, 1, 2, -1 }; yield return new object[] { new byte[] { 1, 2, 3, 3 }, (byte)1, 4, 0, -1 }; yield return new object[] { new byte[] { 1, 2, 3, 3 }, (byte)1, 0, 0, -1 }; yield return new object[] { new byte[0], (byte)1, 0, 0, -1 }; // Int16 yield return new object[] { new short[] { 1, 2, 3, 3 }, (short)1, 0, 4, 0 }; yield return new object[] { new short[] { 1, 2, 3, 3 }, (short)3, 0, 4, 2 }; yield return new object[] { new short[] { 1, 2, 3, 3 }, (short)2, 1, 2, 1 }; yield return new object[] { new short[] { 1, 2, 3, 3 }, (short)1, 1, 2, -1 }; yield return new object[] { new short[] { 1, 2, 3, 3 }, (short)1, 4, 0, -1 }; yield return new object[] { new short[] { 1, 2, 3, 3 }, (short)1, 0, 0, -1 }; yield return new object[] { new short[0], (short)1, 0, 0, -1 }; // UInt16 yield return new object[] { new ushort[] { 1, 2, 3, 3 }, (ushort)1, 0, 4, 0 }; yield return new object[] { new ushort[] { 1, 2, 3, 3 }, (ushort)3, 0, 4, 2 }; yield return new object[] { new ushort[] { 1, 2, 3, 3 }, (ushort)2, 1, 2, 1 }; yield return new object[] { new ushort[] { 1, 2, 3, 3 }, (ushort)1, 1, 2, -1 }; yield return new object[] { new ushort[] { 1, 2, 3, 3 }, (ushort)1, 4, 0, -1 }; yield return new object[] { new ushort[] { 1, 2, 3, 3 }, (ushort)1, 0, 0, -1 }; yield return new object[] { new ushort[0], (ushort)1, 0, 0, -1 }; // Int32 var intArray = new int[] { 7, 7, 8, 8, 9, 9 }; yield return new object[] { intArray, 8, 0, 6, 2 }; yield return new object[] { intArray, 8, 3, 3, 3 }; yield return new object[] { intArray, 8, 4, 2, -1 }; yield return new object[] { intArray, 9, 2, 2, -1 }; yield return new object[] { intArray, 9, 2, 3, 4 }; yield return new object[] { intArray, 10, 0, 6, -1 }; // UInt32 yield return new object[] { new uint[] { 1, 2, 3, 3 }, (uint)1, 0, 4, 0 }; yield return new object[] { new uint[] { 1, 2, 3, 3 }, (uint)3, 0, 4, 2 }; yield return new object[] { new uint[] { 1, 2, 3, 3 }, (uint)2, 1, 2, 1 }; yield return new object[] { new uint[] { 1, 2, 3, 3 }, (uint)1, 1, 2, -1 }; yield return new object[] { new uint[] { 1, 2, 3, 3 }, (uint)1, 4, 0, -1 }; yield return new object[] { new uint[] { 1, 2, 3, 3 }, (uint)1, 0, 0, -1 }; yield return new object[] { new uint[0], (uint)1, 0, 0, -1 }; // Int64 yield return new object[] { new long[] { 1, 2, 3, 3 }, (long)1, 0, 4, 0 }; yield return new object[] { new long[] { 1, 2, 3, 3 }, (long)3, 0, 4, 2 }; yield return new object[] { new long[] { 1, 2, 3, 3 }, (long)2, 1, 2, 1 }; yield return new object[] { new long[] { 1, 2, 3, 3 }, (long)1, 1, 2, -1 }; yield return new object[] { new long[] { 1, 2, 3, 3 }, (long)1, 4, 0, -1 }; yield return new object[] { new long[] { 1, 2, 3, 3 }, (long)1, 0, 0, -1 }; yield return new object[] { new long[0], (long)1, 0, 0, -1 }; // UInt64 yield return new object[] { new ulong[] { 1, 2, 3, 3 }, (ulong)1, 0, 4, 0 }; yield return new object[] { new ulong[] { 1, 2, 3, 3 }, (ulong)3, 0, 4, 2 }; yield return new object[] { new ulong[] { 1, 2, 3, 3 }, (ulong)2, 1, 2, 1 }; yield return new object[] { new ulong[] { 1, 2, 3, 3 }, (ulong)1, 1, 2, -1 }; yield return new object[] { new ulong[] { 1, 2, 3, 3 }, (ulong)1, 4, 0, -1 }; yield return new object[] { new ulong[] { 1, 2, 3, 3 }, (ulong)1, 0, 0, -1 }; yield return new object[] { new ulong[0], (ulong)1, 0, 0, -1 }; // Char yield return new object[] { new char[] { (char)1, (char)2, (char)3, (char)3 }, (char)1, 0, 4, 0 }; yield return new object[] { new char[] { (char)1, (char)2, (char)3, (char)3 }, (char)3, 0, 4, 2 }; yield return new object[] { new char[] { (char)1, (char)2, (char)3, (char)3 }, (char)2, 1, 2, 1 }; yield return new object[] { new char[] { (char)1, (char)2, (char)3, (char)3 }, (char)1, 1, 2, -1 }; yield return new object[] { new char[] { (char)1, (char)2, (char)3, (char)3 }, (char)1, 4, 0, -1 }; yield return new object[] { new char[] { (char)1, (char)2, (char)3, (char)3 }, (char)1, 0, 0, -1 }; yield return new object[] { new char[0], (char)1, 0, 0, -1 }; // Bool yield return new object[] { new bool[] { true, false, false, true }, true, 0, 4, 0 }; yield return new object[] { new bool[] { true, false, false, true }, false, 1, 2, 1 }; yield return new object[] { new bool[] { true, false, false, true }, true, 1, 1, -1 }; yield return new object[] { new bool[] { true, false, false, true }, true, 4, 0, -1 }; yield return new object[] { new bool[] { true, false, false, true }, true, 0, 0, -1 }; yield return new object[] { new bool[0], true, 0, 0, -1 }; // Single yield return new object[] { new float[] { 1, 2, 3, 3 }, (float)1, 0, 4, 0 }; yield return new object[] { new float[] { 1, 2, 3, 3 }, (float)3, 0, 4, 2 }; yield return new object[] { new float[] { 1, 2, 3, 3 }, (float)2, 1, 2, 1 }; yield return new object[] { new float[] { 1, 2, 3, 3 }, (float)1, 1, 2, -1 }; yield return new object[] { new float[] { 1, 2, 3, 3 }, (float)1, 4, 0, -1 }; yield return new object[] { new float[] { 1, 2, 3, 3 }, (float)1, 0, 0, -1 }; yield return new object[] { new float[0], (float)1, 0, 0, -1 }; // Double yield return new object[] { new double[] { 1, 2, 3, 3 }, (double)1, 0, 4, 0 }; yield return new object[] { new double[] { 1, 2, 3, 3 }, (double)3, 0, 4, 2 }; yield return new object[] { new double[] { 1, 2, 3, 3 }, (double)2, 1, 2, 1 }; yield return new object[] { new double[] { 1, 2, 3, 3 }, (double)1, 1, 2, -1 }; yield return new object[] { new double[] { 1, 2, 3, 3 }, (double)1, 4, 0, -1 }; yield return new object[] { new double[] { 1, 2, 3, 3 }, (double)1, 0, 0, -1 }; yield return new object[] { new double[0], (double)1, 0, 0, -1 }; // IntPtr yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)3 }, (IntPtr)1, 0, 4, 0 }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)3 }, (IntPtr)3, 0, 4, 2 }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)3 }, (IntPtr)2, 1, 2, 1 }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)3 }, (IntPtr)1, 1, 2, -1 }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)3 }, (IntPtr)1, 4, 0, -1 }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)3 }, (IntPtr)1, 0, 0, -1 }; yield return new object[] { new IntPtr[0], (IntPtr)1, 0, 0, -1 }; // UIntPtr yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)3 }, (UIntPtr)1, 0, 4, 0 }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)3 }, (UIntPtr)3, 0, 4, 2 }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)3 }, (UIntPtr)2, 1, 2, 1 }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)3 }, (UIntPtr)1, 1, 2, -1 }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)3 }, (UIntPtr)1, 4, 0, -1 }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)3 }, (UIntPtr)1, 0, 0, -1 }; yield return new object[] { new UIntPtr[0], (UIntPtr)1, 0, 0, -1 }; // String var stringArray = new string[] { null, null, "Hello", "Hello", "Goodbye", "Goodbye", null, null }; yield return new object[] { stringArray, "Hello", 0, 8, 2 }; yield return new object[] { stringArray, "Goodbye", 0, 8, 4 }; yield return new object[] { stringArray, "Nowhere", 0, 8, -1 }; yield return new object[] { stringArray, "Hello", 3, 5, 3 }; yield return new object[] { stringArray, "Hello", 4, 4, -1 }; yield return new object[] { stringArray, "Goodbye", 2, 3, 4 }; yield return new object[] { stringArray, "Goodbye", 2, 2, -1 }; // SByteEnum yield return new object[] { new SByteEnum[] { SByteEnum.MinusTwo, SByteEnum.Zero }, SByteEnum.Zero, 0, 2, 1 }; yield return new object[] { new SByteEnum[] { SByteEnum.MinusTwo, SByteEnum.Zero }, SByteEnum.Zero, 1, 1, 1 }; yield return new object[] { new SByteEnum[] { SByteEnum.MinusTwo, SByteEnum.Zero }, SByteEnum.Zero, 2, 0, -1 }; yield return new object[] { new SByteEnum[] { SByteEnum.Five, SByteEnum.Five }, SByteEnum.Five, 0, 2, 0 }; yield return new object[] { new SByteEnum[] { SByteEnum.Five, SByteEnum.Five }, SByteEnum.Five, 1, 1, 1 }; yield return new object[] { new SByteEnum[] { SByteEnum.Five, SByteEnum.Five }, SByteEnum.Five, 2, 0, -1 }; // Int16Enum yield return new object[] { new Int16Enum[] { Int16Enum.Min }, Int16Enum.Min, 0, 1, 0 }; yield return new object[] { new Int16Enum[] { Int16Enum.Min + 1 }, Int16Enum.One, 0, 1, -1 }; yield return new object[] { new Int16Enum[] { Int16Enum.Max, Int16Enum.Max }, Int16Enum.Max, 0, 2, 0 }; yield return new object[] { new Int16Enum[] { Int16Enum.Max, Int16Enum.Max }, Int16Enum.Max, 1, 1, 1 }; yield return new object[] { new Int16Enum[] { Int16Enum.Max, Int16Enum.Max }, Int16Enum.Max, 2, 0, -1 }; // Int32Enum yield return new object[] { new Int32Enum[] { Int32Enum.Case1, Int32Enum.Case2, Int32Enum.Case1 }, Int32Enum.Case1, 0, 3, 0 }; yield return new object[] { new Int32Enum[] { Int32Enum.Case1, Int32Enum.Case2, Int32Enum.Case1 }, Int32Enum.Case3, 0, 3, -1 }; // Int64Enum yield return new object[] { new Int64Enum[] { (Int64Enum)1, (Int64Enum)2, (Int64Enum)1 }, (Int64Enum)1, 0, 3, 0 }; yield return new object[] { new Int64Enum[] { (Int64Enum)1, (Int64Enum)2, (Int64Enum)1 }, (Int64Enum)3, 0, 3, -1 }; // Class NonGenericClass1 classObject = new NonGenericClass1(); yield return new object[] { new NonGenericClass1[] { classObject, new NonGenericClass1() }, classObject, 0, 2, 0 }; yield return new object[] { new NonGenericClass1[] { classObject, new NonGenericClass1() }, new NonGenericClass1(), 0, 2, -1 }; yield return new object[] { new NonGenericClass1[] { classObject, new NonGenericClass1() }, classObject, 2, 0, -1 }; yield return new object[] { new NonGenericClass1[] { classObject, new NonGenericClass1() }, classObject, 0, 0, -1 }; // Struct NonGenericStruct structObject = new NonGenericStruct(); yield return new object[] { new NonGenericStruct[] { structObject, new NonGenericStruct() }, structObject, 0, 2, 0 }; yield return new object[] { new NonGenericStruct[] { structObject, new NonGenericStruct() }, new NonGenericStruct(), 0, 2, 0 }; yield return new object[] { new NonGenericStruct[] { structObject, new NonGenericStruct() }, structObject, 2, 0, -1 }; yield return new object[] { new NonGenericStruct[] { structObject, new NonGenericStruct() }, structObject, 0, 0, -1 }; // Interface ClassWithNonGenericInterface1 interfaceObject = new ClassWithNonGenericInterface1(); yield return new object[] { new NonGenericInterface1[] { interfaceObject, new ClassWithNonGenericInterface1() }, interfaceObject, 0, 2, 0 }; yield return new object[] { new NonGenericInterface1[] { interfaceObject, new ClassWithNonGenericInterface1() }, new ClassWithNonGenericInterface1(), 0, 2, -1 }; yield return new object[] { new NonGenericInterface1[] { interfaceObject, new ClassWithNonGenericInterface1() }, interfaceObject, 2, 0, -1 }; yield return new object[] { new NonGenericInterface1[] { interfaceObject, new ClassWithNonGenericInterface1() }, interfaceObject, 0, 0, -1 }; // Object yield return new object[] { new object[] { new EqualsOverrider { Value = 1 } }, null, 0, 1, -1 }; yield return new object[] { new object[] { new EqualsOverrider { Value = 1 } }, new EqualsOverrider { Value = 1 }, 0, 1, 0 }; yield return new object[] { new object[] { new EqualsOverrider { Value = 1 } }, new EqualsOverrider { Value = 2 }, 0, 1, -1 }; yield return new object[] { new object[1], null, 0, 1, 0 }; yield return new object[] { new object[2], null, 2, 0, -1 }; yield return new object[] { new object[2], null, 0, 0, -1 }; } public static IEnumerable<object[]> IndexOf_Array_TestData() { // Workaround: Move these tests to IndexOf_SZArray_TestData if/ when https://github.com/xunit/xunit/pull/965 is available // SByte yield return new object[] { new sbyte[] { 1, 2 }, (byte)1, 0, 2, -1 }; yield return new object[] { new sbyte[] { 1, 2 }, new object(), 0, 2, -1 }; yield return new object[] { new sbyte[] { 1, 2 }, null, 0, 2, -1 }; // Byte yield return new object[] { new byte[] { 1, 2 }, (sbyte)1, 0, 2, -1 }; yield return new object[] { new byte[] { 1, 2 }, new object(), 0, 2, -1 }; yield return new object[] { new byte[] { 1, 2 }, null, 0, 2, -1 }; // Int16 yield return new object[] { new short[] { 1, 2 }, (ushort)1, 0, 2, -1 }; yield return new object[] { new short[] { 1, 2 }, new object(), 0, 2, -1 }; yield return new object[] { new short[] { 1, 2 }, null, 0, 2, -1 }; // UInt16 yield return new object[] { new ushort[] { 1, 2 }, (short)1, 0, 2, -1 }; yield return new object[] { new ushort[] { 1, 2 }, new object(), 0, 2, -1 }; yield return new object[] { new ushort[] { 1, 2 }, null, 0, 2, -1 }; // Int32 yield return new object[] { new int[] { 1, 2 }, (uint)1, 0, 2, -1 }; yield return new object[] { new int[] { 1, 2 }, new object(), 0, 2, -1 }; yield return new object[] { new int[] { 1, 2 }, null, 0, 2, -1 }; // UInt32 yield return new object[] { new uint[] { 1, 2 }, 1, 0, 2, -1 }; yield return new object[] { new uint[] { 1, 2 }, new object(), 0, 2, -1 }; yield return new object[] { new uint[] { 1, 2 }, null, 0, 2, -1 }; // Int64 yield return new object[] { new long[] { 1, 2 }, (ulong)1, 0, 2, -1 }; yield return new object[] { new long[] { 1, 2 }, new object(), 0, 2, -1 }; yield return new object[] { new long[] { 1, 2 }, null, 0, 2, -1 }; // UInt64 yield return new object[] { new ulong[] { 1, 2 }, (long)1, 0, 2, -1 }; yield return new object[] { new ulong[] { 1, 2 }, new object(), 0, 2, -1 }; yield return new object[] { new ulong[] { 1, 2 }, null, 0, 2, -1 }; // Char yield return new object[] { new char[] { (char)1, (char)2 }, (ushort)1, 0, 2, -1 }; yield return new object[] { new char[] { (char)1, (char)2 }, new object(), 0, 2, -1 }; yield return new object[] { new char[] { (char)1, (char)2 }, null, 0, 2, -1 }; // Bool yield return new object[] { new bool[] { true, false }, (char)0, 0, 2, -1 }; yield return new object[] { new bool[] { true, false }, new object(), 0, 2, -1 }; yield return new object[] { new bool[] { true, false }, null, 0, 2, -1 }; // Single yield return new object[] { new float[] { 1, 2 }, (double)1, 0, 2, -1 }; yield return new object[] { new float[] { 1, 2 }, new object(), 0, 2, -1 }; yield return new object[] { new float[] { 1, 2 }, null, 0, 2, -1 }; // Double yield return new object[] { new double[] { 1, 2 }, (float)1, 0, 2, -1 }; yield return new object[] { new double[] { 1, 2 }, new object(), 0, 2, -1 }; yield return new object[] { new double[] { 1, 2 }, null, 0, 2, -1 }; // IntPtr yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2 }, (UIntPtr)1, 0, 2, -1 }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2 }, new object(), 0, 2, -1 }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2 }, null, 0, 2, -1 }; // UIntPtr yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2 }, (IntPtr)1, 0, 2, -1 }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2 }, new object(), 0, 2, -1 }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2 }, null, 0, 2, -1 }; // String yield return new object[] { new string[] { "Hello", "Hello", "Goodbyte", "Goodbye" }, new object(), 0, 4, -1 }; // Nullable var nullableArray = new int?[] { 0, null, 10 }; yield return new object[] { nullableArray, null, 0, 3, 1 }; yield return new object[] { nullableArray, 10, 0, 3, 2 }; yield return new object[] { nullableArray, 100, 0, 3, -1 }; } [Theory] [MemberData(nameof(IndexOf_SZArray_TestData))] public static void IndexOf_SZArray<T>(T[] array, T value, int startIndex, int count, int expected) { if (startIndex + count == array.Length) { if (startIndex == 0) { // Use IndexOf<T>(T[], T) Assert.Equal(expected, Array.IndexOf(array, value)); IList<T> iList = array; Assert.Equal(expected, iList.IndexOf(value)); Assert.Equal(expected >= startIndex, iList.Contains(value)); } // Use IndexOf<T>(T[], T, int) Assert.Equal(expected, Array.IndexOf(array, value, startIndex)); } // Use IndexOf<T>(T[], T, int, int) Assert.Equal(expected, Array.IndexOf(array, value, startIndex, count)); // Basic: forward SZArray IndexOf_Array(array, value, startIndex, count, expected); // Advanced: convert SZArray to an array with non-zero lower bound const int LowerBound = 5; Array nonZeroLowerBoundArray = NonZeroLowerBoundArray(array, LowerBound); IndexOf_Array(nonZeroLowerBoundArray, value, startIndex + LowerBound, count, expected + LowerBound); } [Theory] [MemberData(nameof(IndexOf_Array_TestData))] public static void IndexOf_Array(Array array, object value, int startIndex, int count, int expected) { if (startIndex + count == array.GetLowerBound(0) + array.Length) { if (startIndex == array.GetLowerBound(0)) { // Use IndexOf(Array, object) Assert.Equal(expected, Array.IndexOf(array, value)); IList iList = array; Assert.Equal(expected, iList.IndexOf(value)); Assert.Equal(expected >= startIndex, iList.Contains(value)); } // Use IndexOf(Array, object, int) Assert.Equal(expected, Array.IndexOf(array, value, startIndex)); } // Use IndexOf(Array, object, int, int) Assert.Equal(expected, Array.IndexOf(array, value, startIndex, count)); } [Fact] public static void IndexOf_SZArray_NonInferrableEntries() { // Workaround: Move these values to IndexOf_SZArray_TestData if/ when https://github.com/xunit/xunit/pull/965 is available IndexOf_SZArray(new string[] { "Hello", "Hello", "Goodbyte", "Goodbye" }, null, 0, 4, -1); } [Fact] public static void IndexOf_NullArray_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("array", () => Array.IndexOf((int[])null, "")); Assert.Throws<ArgumentNullException>("array", () => Array.IndexOf((int[])null, "", 0)); Assert.Throws<ArgumentNullException>("array", () => Array.IndexOf((int[])null, "", 0, 0)); Assert.Throws<ArgumentNullException>("array", () => Array.IndexOf(null, "")); Assert.Throws<ArgumentNullException>("array", () => Array.IndexOf(null, "", 0)); Assert.Throws<ArgumentNullException>("array", () => Array.IndexOf(null, "", 0, 0)); } [Fact] public static void IndexOf_MultimensionalArray_ThrowsRankException() { Assert.Throws<RankException>(() => Array.IndexOf(new string[0, 0], "")); Assert.Throws<RankException>(() => Array.IndexOf(new string[0, 0], "", 0)); Assert.Throws<RankException>(() => Array.IndexOf(new string[0, 0], "", 0, 0)); } [Theory] [InlineData(-1)] [InlineData(1)] public static void IndexOf_InvalidStartIndex_ThrowsArgumentOutOfRangeException(int startIndex) { Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.IndexOf(new int[0], "", startIndex)); Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.IndexOf(new int[0], "", startIndex, 0)); Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.IndexOf(new string[0], "", startIndex)); Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.IndexOf(new string[0], "", startIndex, 0)); } [Theory] [InlineData(0, 0, -1)] [InlineData(0, 0, 1)] [InlineData(2, 0, 3)] [InlineData(2, 2, 1)] public static void IndexOf_InvalidCount_ThrowsArgumentOutOfRangeException(int length, int startIndex, int count) { Assert.Throws<ArgumentOutOfRangeException>("count", () => Array.IndexOf(new int[length], "", startIndex, count)); Assert.Throws<ArgumentOutOfRangeException>("count", () => Array.IndexOf(new string[length], "", startIndex, count)); } [Fact] public static unsafe void IndexOf_ArrayOfPointers_ThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Array.IndexOf((Array)new int*[2], null)); Assert.Equal(-1, Array.IndexOf((Array)new int*[0], null)); } public static IEnumerable<object[]> LastIndexOf_SZArray_TestData() { // SByte yield return new object[] { new sbyte[] { 1, 2, 3, 3, 4 }, (sbyte)1, 4, 5, 0 }; yield return new object[] { new sbyte[] { 1, 2, 3, 3, 4 }, (sbyte)3, 4, 5, 3 }; yield return new object[] { new sbyte[] { 1, 2, 3, 3, 4 }, (sbyte)2, 2, 3, 1 }; yield return new object[] { new sbyte[] { 1, 2, 3, 3, 4 }, (sbyte)4, 2, 3, -1 }; yield return new object[] { new sbyte[] { 1, 2, 3, 3, 4 }, (sbyte)5, 4, 5, -1 }; yield return new object[] { new sbyte[] { 1, 2, 3, 3, 4 }, (sbyte)3, 0, 0, -1 }; yield return new object[] { new sbyte[] { 1, 2, 3, 3, 4 }, (sbyte)3, 3, 0, -1 }; // Byte yield return new object[] { new byte[] { 1, 2, 3, 3, 4 }, (byte)1, 4, 5, 0 }; yield return new object[] { new byte[] { 1, 2, 3, 3, 4 }, (byte)3, 4, 5, 3 }; yield return new object[] { new byte[] { 1, 2, 3, 3, 4 }, (byte)2, 2, 3, 1 }; yield return new object[] { new byte[] { 1, 2, 3, 3, 4 }, (byte)4, 2, 3, -1 }; yield return new object[] { new byte[] { 1, 2, 3, 3, 4 }, (byte)5, 4, 5, -1 }; yield return new object[] { new byte[] { 1, 2, 3, 3, 4 }, (byte)3, 0, 0, -1 }; yield return new object[] { new byte[] { 1, 2, 3, 3, 4 }, (byte)3, 3, 0, -1 }; // Int16 yield return new object[] { new short[] { 1, 2, 3, 3, 4 }, (short)1, 4, 5, 0 }; yield return new object[] { new short[] { 1, 2, 3, 3, 4 }, (short)3, 4, 5, 3 }; yield return new object[] { new short[] { 1, 2, 3, 3, 4 }, (short)2, 2, 3, 1 }; yield return new object[] { new short[] { 1, 2, 3, 3, 4 }, (short)4, 2, 3, -1 }; yield return new object[] { new short[] { 1, 2, 3, 3, 4 }, (short)5, 4, 5, -1 }; yield return new object[] { new short[] { 1, 2, 3, 3, 4 }, (short)3, 0, 0, -1 }; yield return new object[] { new short[] { 1, 2, 3, 3, 4 }, (short)3, 3, 0, -1 }; // UInt16 yield return new object[] { new ushort[] { 1, 2, 3, 3, 4 }, (ushort)1, 4, 5, 0 }; yield return new object[] { new ushort[] { 1, 2, 3, 3, 4 }, (ushort)3, 4, 5, 3 }; yield return new object[] { new ushort[] { 1, 2, 3, 3, 4 }, (ushort)2, 2, 3, 1 }; yield return new object[] { new ushort[] { 1, 2, 3, 3, 4 }, (ushort)4, 2, 3, -1 }; yield return new object[] { new ushort[] { 1, 2, 3, 3, 4 }, (ushort)5, 4, 5, -1 }; yield return new object[] { new ushort[] { 1, 2, 3, 3, 4 }, (ushort)3, 0, 0, -1 }; yield return new object[] { new ushort[] { 1, 2, 3, 3, 4 }, (ushort)3, 3, 0, -1 }; // Int32 var intArray = new int[] { 7, 7, 8, 8, 9, 9 }; yield return new object[] { intArray, 8, 5, 6, 3 }; yield return new object[] { intArray, 8, 1, 1, -1 }; yield return new object[] { intArray, 8, 3, 3, 3 }; yield return new object[] { intArray, 7, 3, 2, -1 }; yield return new object[] { intArray, 7, 3, 3, 1 }; yield return new object[] { new int[0], 0, 0, 0, -1 }; yield return new object[] { new int[0], 0, -1, 0, -1 }; // UInt32 yield return new object[] { new uint[] { 1, 2, 3, 3, 4 }, (uint)1, 4, 5, 0 }; yield return new object[] { new uint[] { 1, 2, 3, 3, 4 }, (uint)3, 4, 5, 3 }; yield return new object[] { new uint[] { 1, 2, 3, 3, 4 }, (uint)2, 2, 3, 1 }; yield return new object[] { new uint[] { 1, 2, 3, 3, 4 }, (uint)4, 2, 3, -1 }; yield return new object[] { new uint[] { 1, 2, 3, 3, 4 }, (uint)5, 4, 5, -1 }; yield return new object[] { new uint[] { 1, 2, 3, 3, 4 }, (uint)3, 0, 0, -1 }; yield return new object[] { new uint[] { 1, 2, 3, 3, 4 }, (uint)3, 3, 0, -1 }; // UInt64 yield return new object[] { new long[] { 1, 2, 3, 3, 4 }, (long)1, 4, 5, 0 }; yield return new object[] { new long[] { 1, 2, 3, 3, 4 }, (long)3, 4, 5, 3 }; yield return new object[] { new long[] { 1, 2, 3, 3, 4 }, (long)2, 2, 3, 1 }; yield return new object[] { new long[] { 1, 2, 3, 3, 4 }, (long)4, 2, 3, -1 }; yield return new object[] { new long[] { 1, 2, 3, 3, 4 }, (long)5, 4, 5, -1 }; yield return new object[] { new long[] { 1, 2, 3, 3, 4 }, (long)3, 0, 0, -1 }; yield return new object[] { new long[] { 1, 2, 3, 3, 4 }, (long)3, 3, 0, -1 }; // UInt64 yield return new object[] { new ulong[] { 1, 2, 3, 3, 4 }, (ulong)1, 4, 5, 0 }; yield return new object[] { new ulong[] { 1, 2, 3, 3, 4 }, (ulong)3, 4, 5, 3 }; yield return new object[] { new ulong[] { 1, 2, 3, 3, 4 }, (ulong)2, 2, 3, 1 }; yield return new object[] { new ulong[] { 1, 2, 3, 3, 4 }, (ulong)4, 2, 3, -1 }; yield return new object[] { new ulong[] { 1, 2, 3, 3, 4 }, (ulong)5, 4, 5, -1 }; yield return new object[] { new ulong[] { 1, 2, 3, 3, 4 }, (ulong)3, 0, 0, -1 }; yield return new object[] { new ulong[] { 1, 2, 3, 3, 4 }, (ulong)3, 3, 0, -1 }; // Char yield return new object[] { new char[] { (char)1, (char)2, (char)3, (char)3, (char)4 }, (char)1, 4, 5, 0 }; yield return new object[] { new char[] { (char)1, (char)2, (char)3, (char)3, (char)4 }, (char)3, 4, 5, 3 }; yield return new object[] { new char[] { (char)1, (char)2, (char)3, (char)3, (char)4 }, (char)2, 2, 3, 1 }; yield return new object[] { new char[] { (char)1, (char)2, (char)3, (char)3, (char)4 }, (char)4, 2, 3, -1 }; yield return new object[] { new char[] { (char)1, (char)2, (char)3, (char)3, (char)4 }, (char)5, 4, 5, -1 }; yield return new object[] { new char[] { (char)1, (char)2, (char)3, (char)3, (char)4 }, (char)3, 0, 0, -1 }; yield return new object[] { new char[] { (char)1, (char)2, (char)3, (char)3, (char)4 }, (char)3, 4, 0, -1 }; // Bool yield return new object[] { new bool[] { false, true, true }, false, 2, 3, 0 }; yield return new object[] { new bool[] { false, true, true }, true, 2, 3, 2 }; yield return new object[] { new bool[] { false, true, true }, false, 1, 2, 0 }; yield return new object[] { new bool[] { false, true, true }, false, 1, 1, -1 }; yield return new object[] { new bool[] { false }, true, 0, 1, -1 }; yield return new object[] { new bool[] { false, true, true }, false, 0, 0, -1 }; yield return new object[] { new bool[] { false, true, true }, false, 2, 0, -1 }; // Single yield return new object[] { new float[] { 1, 2, 3, 3, 4 }, (float)1, 4, 5, 0 }; yield return new object[] { new float[] { 1, 2, 3, 3, 4 }, (float)3, 4, 5, 3 }; yield return new object[] { new float[] { 1, 2, 3, 3, 4 }, (float)2, 2, 3, 1 }; yield return new object[] { new float[] { 1, 2, 3, 3, 4 }, (float)4, 2, 3, -1 }; yield return new object[] { new float[] { 1, 2, 3, 3, 4 }, (float)5, 4, 5, -1 }; yield return new object[] { new float[] { 1, 2, 3, 3, 4 }, (float)3, 0, 0, -1 }; yield return new object[] { new float[] { 1, 2, 3, 3, 4 }, (float)3, 3, 0, -1 }; // Double yield return new object[] { new double[] { 1, 2, 3, 3, 4 }, (double)1, 4, 5, 0 }; yield return new object[] { new double[] { 1, 2, 3, 3, 4 }, (double)3, 4, 5, 3 }; yield return new object[] { new double[] { 1, 2, 3, 3, 4 }, (double)2, 2, 3, 1 }; yield return new object[] { new double[] { 1, 2, 3, 3, 4 }, (double)4, 2, 3, -1 }; yield return new object[] { new double[] { 1, 2, 3, 3, 4 }, (double)5, 4, 5, -1 }; yield return new object[] { new double[] { 1, 2, 3, 3, 4 }, (double)3, 0, 0, -1 }; yield return new object[] { new double[] { 1, 2, 3, 3, 4 }, (double)3, 3, 0, -1 }; // IntPtr yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)3, (IntPtr)4 }, (IntPtr)1, 4, 5, 0 }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)3, (IntPtr)4 }, (IntPtr)3, 4, 5, 3 }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)3, (IntPtr)4 }, (IntPtr)2, 2, 3, 1 }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)3, (IntPtr)4 }, (IntPtr)4, 2, 3, -1 }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)3, (IntPtr)4 }, (IntPtr)5, 4, 5, -1 }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)3, (IntPtr)4 }, (IntPtr)3, 0, 0, -1 }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)3, (IntPtr)4 }, (IntPtr)3, 3, 0, -1 }; // UIntPtr yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)3, (UIntPtr)4 }, (UIntPtr)1, 4, 5, 0 }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)3, (UIntPtr)4 }, (UIntPtr)3, 4, 5, 3 }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)3, (UIntPtr)4 }, (UIntPtr)2, 2, 3, 1 }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)3, (UIntPtr)4 }, (UIntPtr)4, 2, 3, -1 }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)3, (UIntPtr)4 }, (UIntPtr)5, 4, 5, -1 }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)3, (UIntPtr)4 }, (UIntPtr)3, 0, 0, -1 }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)3, (UIntPtr)4 }, (UIntPtr)3, 3, 0, -1 }; // String var stringArray = new string[] { null, null, "Hello", "Hello", "Goodbye", "Goodbye", null, null }; yield return new object[] { stringArray, "Hello", 7, 8, 3 }; yield return new object[] { stringArray, "Goodbye", 7, 8, 5 }; yield return new object[] { stringArray, "Nowhere", 7, 8, -1 }; yield return new object[] { stringArray, "Hello", 2, 2, 2 }; yield return new object[] { stringArray, "Hello", 3, 3, 3 }; yield return new object[] { stringArray, "Goodbye", 7, 2, -1 }; yield return new object[] { stringArray, "Goodbye", 7, 3, 5 }; // Int32Enum yield return new object[] { new Int32Enum[] { Int32Enum.Case1, Int32Enum.Case2, Int32Enum.Case1 }, Int32Enum.Case1, 2, 3, 2 }; yield return new object[] { new Int32Enum[] { Int32Enum.Case1, Int32Enum.Case2, Int32Enum.Case1 }, Int32Enum.Case3, 2, 3, -1 }; // Int64Enum yield return new object[] { new Int64Enum[] { (Int64Enum)1, (Int64Enum)2, (Int64Enum)1 }, (Int64Enum)1, 2, 3, 2 }; yield return new object[] { new Int64Enum[] { (Int64Enum)1, (Int64Enum)2, (Int64Enum)1 }, (Int64Enum)3, 2, 3, -1 }; // Class NonGenericClass1 classObject = new NonGenericClass1(); yield return new object[] { new NonGenericClass1[] { classObject, new NonGenericClass1() }, classObject, 1, 2, 0 }; yield return new object[] { new NonGenericClass1[] { classObject, new NonGenericClass1() }, new NonGenericClass1(), 1, 2, -1 }; yield return new object[] { new NonGenericClass1[] { classObject, new NonGenericClass1() }, classObject, 1, 0, -1 }; yield return new object[] { new NonGenericClass1[] { classObject, new NonGenericClass1() }, classObject, 0, 0, -1 }; // Struct NonGenericStruct structObject = new NonGenericStruct(); yield return new object[] { new NonGenericStruct[] { structObject, new NonGenericStruct() }, structObject, 1, 2, 1 }; yield return new object[] { new NonGenericStruct[] { structObject, new NonGenericStruct() }, new NonGenericStruct(), 1, 2, 1 }; yield return new object[] { new NonGenericStruct[] { structObject, new NonGenericStruct() }, structObject, 1, 0, -1 }; yield return new object[] { new NonGenericStruct[] { structObject, new NonGenericStruct() }, structObject, 0, 0, -1 }; // Interface ClassWithNonGenericInterface1 interfaceObject = new ClassWithNonGenericInterface1(); yield return new object[] { new NonGenericInterface1[] { interfaceObject, new ClassWithNonGenericInterface1() }, interfaceObject, 1, 2, 0 }; yield return new object[] { new NonGenericInterface1[] { interfaceObject, new ClassWithNonGenericInterface1() }, new ClassWithNonGenericInterface1(), 1, 2, -1 }; yield return new object[] { new NonGenericInterface1[] { interfaceObject, new ClassWithNonGenericInterface1() }, interfaceObject, 1, 0, -1 }; yield return new object[] { new NonGenericInterface1[] { interfaceObject, new ClassWithNonGenericInterface1() }, interfaceObject, 0, 0, -1 }; // Object yield return new object[] { new object[] { new EqualsOverrider { Value = 1 } }, null, 0, 1, -1 }; yield return new object[] { new object[] { new EqualsOverrider { Value = 1 } }, new EqualsOverrider { Value = 1 }, 0, 1, 0 }; yield return new object[] { new object[] { new EqualsOverrider { Value = 1 } }, new EqualsOverrider { Value = 2 }, 0, 1, -1 }; yield return new object[] { new object[1], null, 0, 1, 0 }; yield return new object[] { new object[2], null, 1, 0, -1 }; yield return new object[] { new object[2], null, 0, 0, -1 }; } public static IEnumerable<object[]> LastIndexOf_Array_TestData() { // Workaround: Move these values to LastIndexOf_SZArray_TestData if/ when https://github.com/xunit/xunit/pull/965 is available // SByte yield return new object[] { new sbyte[] { 1, 2 }, (byte)1, 1, 2, -1 }; yield return new object[] { new sbyte[] { 1, 2 }, new object(), 1, 2, -1 }; yield return new object[] { new sbyte[] { 1, 2 }, null, 1, 2, -1 }; // Byte yield return new object[] { new byte[] { 1, 2 }, (sbyte)1, 1, 2, -1 }; yield return new object[] { new byte[] { 1, 2 }, new object(), 1, 2, -1 }; yield return new object[] { new byte[] { 1, 2 }, null, 1, 2, -1 }; // Int16 yield return new object[] { new short[] { 1, 2 }, (ushort)1, 1, 2, -1 }; yield return new object[] { new short[] { 1, 2 }, new object(), 1, 2, -1 }; yield return new object[] { new short[] { 1, 2 }, null, 1, 2, -1 }; // UInt16 yield return new object[] { new ushort[] { 1, 2 }, (short)1, 1, 2, -1 }; yield return new object[] { new ushort[] { 1, 2 }, new object(), 1, 2, -1 }; yield return new object[] { new ushort[] { 1, 2 }, null, 1, 2, -1 }; // Int32 yield return new object[] { new int[] { 1, 2 }, (uint)1, 1, 2, -1 }; yield return new object[] { new int[] { 1, 2 }, new object(), 1, 2, -1 }; yield return new object[] { new int[] { 1, 2 }, null, 1, 2, -1 }; // UInt32 yield return new object[] { new uint[] { 1, 2 }, 1, 1, 2, -1 }; yield return new object[] { new uint[] { 1, 2 }, new object(), 1, 2, -1 }; yield return new object[] { new uint[] { 1, 2 }, null, 1, 2, -1 }; // Int64 yield return new object[] { new long[] { 1, 2 }, (ulong)1, 1, 2, -1 }; yield return new object[] { new long[] { 1, 2 }, new object(), 1, 2, -1 }; yield return new object[] { new long[] { 1, 2 }, null, 1, 2, -1 }; // UInt64 yield return new object[] { new ulong[] { 1, 2 }, (long)1, 1, 2, -1 }; yield return new object[] { new ulong[] { 1, 2 }, new object(), 1, 2, -1 }; yield return new object[] { new ulong[] { 1, 2 }, null, 1, 2, -1 }; // Char yield return new object[] { new char[] { (char)1, (char)2 }, (ushort)1, 1, 2, -1 }; yield return new object[] { new char[] { (char)1, (char)2 }, new object(), 1, 2, -1 }; yield return new object[] { new char[] { (char)1, (char)2 }, null, 1, 2, -1 }; // Bool yield return new object[] { new bool[] { true, false }, (char)0, 1, 2, -1 }; yield return new object[] { new bool[] { true, false }, new object(), 1, 2, -1 }; yield return new object[] { new bool[] { true, false }, null, 1, 2, -1 }; // Single yield return new object[] { new float[] { 1, 2 }, (double)1, 1, 2, -1 }; yield return new object[] { new float[] { 1, 2 }, new object(), 1, 2, -1 }; yield return new object[] { new float[] { 1, 2 }, null, 1, 2, -1 }; // Double yield return new object[] { new double[] { 1, 2 }, (float)1, 1, 2, -1 }; yield return new object[] { new double[] { 1, 2 }, new object(), 1, 2, -1 }; yield return new object[] { new double[] { 1, 2 }, null, 1, 2, -1 }; // IntPtr yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2 }, (UIntPtr)1, 1, 2, -1 }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2 }, new object(), 1, 2, -1 }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2 }, null, 1, 2, -1 }; // UIntPtr yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2 }, (IntPtr)1, 1, 2, -1 }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2 }, new object(), 1, 2, -1 }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2 }, null, 1, 2, -1 }; // String yield return new object[] { new string[] { "Hello", "Hello", "Goodbyte", "Goodbye" }, new object(), 3, 4, -1 }; // Nullable var nullableArray = new int?[] { 0, null, 10, 10, 0 }; yield return new object[] { nullableArray, null, 4, 5, 1 }; yield return new object[] { nullableArray, 10, 4, 5, 3 }; yield return new object[] { nullableArray, 100, 4, 5, -1 }; } [Theory] [MemberData(nameof(LastIndexOf_SZArray_TestData))] public static void LastIndexOf_SZArray<T>(T[] array, T value, int startIndex, int count, int expected) { if (count - startIndex - 1 == 0 || array.Length == 0) { if (count == array.Length) { // Use LastIndexOf<T>(T[], T) Assert.Equal(expected, Array.LastIndexOf(array, value)); } // Use LastIndexOf<T>(T[], T, int) Assert.Equal(expected, Array.LastIndexOf(array, value, startIndex)); } // Use LastIndexOf<T>(T[], int, T, int) Assert.Equal(expected, Array.LastIndexOf(array, value, startIndex, count)); // Basic: forward SZArray LastIndexOf_Array(array, value, startIndex, count, expected); // Advanced: convert SZArray to an array with non-zero lower bound const int LowerBound = 5; Array nonZeroLowerBoundArray = NonZeroLowerBoundArray(array, LowerBound); LastIndexOf_Array(nonZeroLowerBoundArray, value, startIndex + LowerBound, count, expected + LowerBound); } [Theory] [MemberData(nameof(LastIndexOf_Array_TestData))] public static void LastIndexOf_Array(Array array, object value, int startIndex, int count, int expected) { if (count - startIndex - 1 == 0 || array.Length == 0) { if (count == array.Length) { // Use LastIndexOf(Array, object) Assert.Equal(expected, Array.LastIndexOf(array, value)); } // Use LastIndexOf(Array, object, int) Assert.Equal(expected, Array.LastIndexOf(array, value, startIndex)); } // Use LastIndexOf(Array, object, int, int) Assert.Equal(expected, Array.LastIndexOf(array, value, startIndex, count)); } [Fact] public static void LastIndexOf_NonInferrableEntries() { // Workaround: Move these values to LastIndexOf_SZArray_TestData if/ when https://github.com/xunit/xunit/pull/965 is available LastIndexOf_SZArray(new string[] { null, null, "Hello", "Hello", "Goodbye", "Goodbye", null, null }, null, 7, 8, 7); LastIndexOf_SZArray(new string[] { "Hello", "Hello", "Goodbye", "Goodbye" }, null, 3, 4, -1); } [Fact] public static void LastIndexOf_NullArray_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("array", () => Array.LastIndexOf((int[])null, "")); Assert.Throws<ArgumentNullException>("array", () => Array.LastIndexOf((int[])null, "", 0)); Assert.Throws<ArgumentNullException>("array", () => Array.LastIndexOf((int[])null, "", 0, 0)); Assert.Throws<ArgumentNullException>("array", () => Array.LastIndexOf(null, "")); Assert.Throws<ArgumentNullException>("array", () => Array.LastIndexOf(null, "", 0)); Assert.Throws<ArgumentNullException>("array", () => Array.LastIndexOf(null, "", 0, 0)); } [Fact] public static void LastIndexOf_MultidimensionalArray_ThrowsRankException() { Assert.Throws<RankException>(() => Array.LastIndexOf(new int[1, 1], "")); Assert.Throws<RankException>(() => Array.LastIndexOf(new int[1, 1], "", 0)); Assert.Throws<RankException>(() => Array.LastIndexOf(new int[1, 1], "", 0, 0)); Assert.Throws<RankException>(() => Array.LastIndexOf(new string[1, 1], "")); Assert.Throws<RankException>(() => Array.LastIndexOf(new string[1, 1], "", 0)); Assert.Throws<RankException>(() => Array.LastIndexOf(new string[1, 1], "", 0, 0)); } [Fact] public static void LastIndexOf_EmptyArrayInvalidStartIndexCount_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.LastIndexOf(new int[0], 0, 1, 0)); // Start index != 0 or -1 Assert.Throws<ArgumentOutOfRangeException>("count", () => Array.LastIndexOf(new int[0], 0, 0, 1)); // Count != 0 } [Fact] public static void LastIndexOf_NegativeStartIndex_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.LastIndexOf(new int[1], "", -1)); Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.LastIndexOf(new int[1], "", -1, 0)); Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.LastIndexOf(new string[1], "", -1)); Assert.Throws<ArgumentOutOfRangeException>("startIndex", () => Array.LastIndexOf(new string[1], "", -1, 0)); } [Fact] public static void LastIndexOf_NegativeCount_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("count", () => Array.LastIndexOf(new int[1], "", 0, -1)); Assert.Throws<ArgumentOutOfRangeException>("count", () => Array.LastIndexOf(new string[1], "", 0, -1)); } [Theory] [InlineData(3, 2, 4)] [InlineData(3, 0, 3)] [InlineData(3, 1, 3)] public static void LastIndexOf_InvalidStartIndexCount_ThrowsArgumentOutOfRangeExeption(int length, int startIndex, int count) { Assert.Throws<ArgumentOutOfRangeException>("endIndex", () => Array.LastIndexOf(new int[length], "", startIndex, count)); Assert.Throws<ArgumentOutOfRangeException>("count", () => Array.LastIndexOf(new int[length], 0, startIndex, count)); } [Fact] public static unsafe void LastIndexOf_ArrayOfPointers_ThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Array.LastIndexOf((Array)new int*[2], null)); Assert.Equal(-1, Array.LastIndexOf((Array)new int*[0], null)); } public static IEnumerable<object[]> IStructuralComparable_TestData() { var intArray = new int[] { 2, 3, 4, 5 }; yield return new object[] { intArray, intArray, new IntegerComparer(), 0 }; yield return new object[] { intArray, new int[] { 2, 3, 4, 5 }, new IntegerComparer(), 0 }; yield return new object[] { intArray, new int[] { 1, 3, 4, 5 }, new IntegerComparer(), 1 }; yield return new object[] { intArray, new int[] { 2, 2, 4, 5 }, new IntegerComparer(), 1 }; yield return new object[] { intArray, new int[] { 2, 3, 3, 5 }, new IntegerComparer(), 1 }; yield return new object[] { intArray, new int[] { 2, 3, 4, 4 }, new IntegerComparer(), 1 }; yield return new object[] { intArray, new int[] { 3, 3, 4, 5 }, new IntegerComparer(), -1 }; yield return new object[] { intArray, new int[] { 2, 4, 4, 5 }, new IntegerComparer(), -1 }; yield return new object[] { intArray, new int[] { 2, 3, 5, 5 }, new IntegerComparer(), -1 }; yield return new object[] { intArray, new int[] { 2, 3, 4, 6 }, new IntegerComparer(), -1 }; yield return new object[] { intArray, null, new IntegerComparer(), 1 }; } [Theory] [MemberData(nameof(IStructuralComparable_TestData))] public static void IStructuralComparable(Array array, object other, IComparer comparer, int expected) { IStructuralComparable comparable = array; Assert.Equal(expected, Math.Sign(comparable.CompareTo(other, comparer))); } [Fact] public static void IStructuralComparable_Invalid() { IStructuralComparable comparable = new int[] { 1, 2, 3 }; Assert.Throws<ArgumentException>("other", () => comparable.CompareTo(new int[] { 1, 2 }, new IntegerComparer())); // Arrays have different lengths Assert.Throws<ArgumentException>("other", () => comparable.CompareTo(new int[] { 1, 2, 3, 4 }, new IntegerComparer())); // Arrays have different lengths Assert.Throws<ArgumentException>("other", () => comparable.CompareTo(123, new IntegerComparer())); // Other is not an array } [Fact] public static void IStructuralComparable_NullComparer_ThrowsNullReferenceException() { // This was not fixed in order to be compatible with the full .NET framework and Xamarin. See #13410 IStructuralComparable comparable = new int[] { 1, 2, 3 }; Assert.Throws<NullReferenceException>(() => comparable.CompareTo(new int[] { 1, 2, 3 }, null)); } public static IEnumerable<object[]> IStructuralEquatable_TestData() { var intArray = new int[] { 2, 3, 4, 5 }; yield return new object[] { intArray, intArray, new IntegerComparer(), true, true }; yield return new object[] { intArray, new int[] { 2, 3, 4, 5 }, new IntegerComparer(), true, true }; yield return new object[] { intArray, new int[] { 1, 3, 4, 5 }, new IntegerComparer(), false, true }; yield return new object[] { intArray, new int[] { 2, 2, 4, 5 }, new IntegerComparer(), false, true }; yield return new object[] { intArray, new int[] { 2, 3, 3, 5 }, new IntegerComparer(), false, false }; yield return new object[] { intArray, new int[] { 2, 3, 4, 4 }, new IntegerComparer(), false, true }; var longIntArray = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 }; yield return new object[] { longIntArray, longIntArray, new IntegerComparer(), true, true }; yield return new object[] { longIntArray, intArray, new IntegerComparer(), false, false }; yield return new object[] { intArray, new int[] { 2 }, new IntegerComparer(), false, false }; yield return new object[] { intArray, new int[] { 2, 3, 4, 5, 6 }, new IntegerComparer(), false, false }; yield return new object[] { intArray, 123, new IntegerComparer(), false, false }; yield return new object[] { intArray, null, new IntegerComparer(), false, false }; } [Theory] [MemberData(nameof(IStructuralEquatable_TestData))] public static void IStructuralEquatable(Array array, object other, IEqualityComparer comparer, bool expected, bool expectHashEquality) { IStructuralEquatable equatable = array; Assert.Equal(expected, equatable.Equals(other, comparer)); if (other is IStructuralEquatable) { IStructuralEquatable equatable2 = (IStructuralEquatable)other; Assert.Equal(expectHashEquality, equatable.GetHashCode(comparer).Equals(equatable2.GetHashCode(comparer))); } } [Fact] public static void IStructuralEquatable_Equals_NullComparer_ThrowsNullReferenceException() { // This was not fixed in order to be compatible with the full .NET framework and Xamarin. See #13410 IStructuralEquatable equatable = new int[] { 1, 2, 3 }; Assert.Throws<NullReferenceException>(() => equatable.Equals(new int[] { 1, 2, 3 }, null)); } [Fact] public static void IStructuralEquatable_GetHashCode_NullComparer_ThrowsArgumentNullException() { IStructuralEquatable equatable = new int[] { 1, 2, 3 }; Assert.Throws<ArgumentNullException>("comparer", () => equatable.GetHashCode(null)); } [Theory] [InlineData(new int[] { 1, 2, 3, 4, 5 }, 7, new int[] { 1, 2, 3, 4, 5, default(int), default(int) })] [InlineData(new int[] { 1, 2, 3, 4, 5 }, 3, new int[] { 1, 2, 3 })] [InlineData(null, 3, new int[] { default(int), default(int), default(int) })] public static void Resize(int[] array, int newSize, int[] expected) { int[] testArray = array; Array.Resize(ref testArray, newSize); Assert.Equal(newSize, testArray.Length); Assert.Equal(expected, testArray); } [Fact] public static void Resize_NegativeNewSize_ThrowsArgumentOutOfRangeException() { var array = new int[0]; Assert.Throws<ArgumentOutOfRangeException>("newSize", () => Array.Resize(ref array, -1)); // New size < 0 Assert.Equal(new int[0], array); } public static IEnumerable<object[]> Reverse_TestData() { // SByte yield return new object[] { new sbyte[] { 1, 2, 3, 4, 5 }, 0, 5, new sbyte[] { 5, 4, 3, 2, 1 } }; yield return new object[] { new sbyte[] { 1, 2, 3, 4, 5 }, 2, 3, new sbyte[] { 1, 2, 5, 4, 3 } }; yield return new object[] { new sbyte[] { 1, 2, 3, 4, 5 }, 0, 0, new sbyte[] { 1, 2, 3, 4, 5 } }; yield return new object[] { new sbyte[] { 1, 2, 3, 4, 5 }, 5, 0, new sbyte[] { 1, 2, 3, 4, 5 } }; // Byte yield return new object[] { new byte[] { 1, 2, 3, 4, 5 }, 0, 5, new byte[] { 5, 4, 3, 2, 1 } }; yield return new object[] { new byte[] { 1, 2, 3, 4, 5 }, 2, 3, new byte[] { 1, 2, 5, 4, 3 } }; yield return new object[] { new byte[] { 1, 2, 3, 4, 5 }, 0, 0, new byte[] { 1, 2, 3, 4, 5 } }; yield return new object[] { new byte[] { 1, 2, 3, 4, 5 }, 5, 0, new byte[] { 1, 2, 3, 4, 5 } }; // Int16 yield return new object[] { new short[] { 1, 2, 3, 4, 5 }, 0, 5, new short[] { 5, 4, 3, 2, 1 } }; yield return new object[] { new short[] { 1, 2, 3, 4, 5 }, 2, 3, new short[] { 1, 2, 5, 4, 3 } }; yield return new object[] { new short[] { 1, 2, 3, 4, 5 }, 0, 0, new short[] { 1, 2, 3, 4, 5 } }; yield return new object[] { new short[] { 1, 2, 3, 4, 5 }, 5, 0, new short[] { 1, 2, 3, 4, 5 } }; // UInt16 yield return new object[] { new ushort[] { 1, 2, 3, 4, 5 }, 0, 5, new ushort[] { 5, 4, 3, 2, 1 } }; yield return new object[] { new ushort[] { 1, 2, 3, 4, 5 }, 2, 3, new ushort[] { 1, 2, 5, 4, 3 } }; yield return new object[] { new ushort[] { 1, 2, 3, 4, 5 }, 0, 0, new ushort[] { 1, 2, 3, 4, 5 } }; yield return new object[] { new ushort[] { 1, 2, 3, 4, 5 }, 5, 0, new ushort[] { 1, 2, 3, 4, 5 } }; // Int32 yield return new object[] { new int[] { 1, 2, 3, 4, 5 }, 0, 5, new int[] { 5, 4, 3, 2, 1 } }; yield return new object[] { new int[] { 1, 2, 3, 4, 5 }, 2, 3, new int[] { 1, 2, 5, 4, 3 } }; yield return new object[] { new int[] { 1, 2, 3, 4, 5 }, 0, 0, new int[] { 1, 2, 3, 4, 5 } }; yield return new object[] { new int[] { 1, 2, 3, 4, 5 }, 5, 0, new int[] { 1, 2, 3, 4, 5 } }; // UInt32 yield return new object[] { new uint[] { 1, 2, 3, 4, 5 }, 0, 5, new uint[] { 5, 4, 3, 2, 1 } }; yield return new object[] { new uint[] { 1, 2, 3, 4, 5 }, 2, 3, new uint[] { 1, 2, 5, 4, 3 } }; yield return new object[] { new uint[] { 1, 2, 3, 4, 5 }, 0, 0, new uint[] { 1, 2, 3, 4, 5 } }; yield return new object[] { new uint[] { 1, 2, 3, 4, 5 }, 5, 0, new uint[] { 1, 2, 3, 4, 5 } }; // Int64 yield return new object[] { new long[] { 1, 2, 3, 4, 5 }, 0, 5, new long[] { 5, 4, 3, 2, 1 } }; yield return new object[] { new long[] { 1, 2, 3, 4, 5 }, 2, 3, new long[] { 1, 2, 5, 4, 3 } }; yield return new object[] { new long[] { 1, 2, 3, 4, 5 }, 0, 0, new long[] { 1, 2, 3, 4, 5 } }; yield return new object[] { new long[] { 1, 2, 3, 4, 5 }, 5, 0, new long[] { 1, 2, 3, 4, 5 } }; // UInt64 yield return new object[] { new ulong[] { 1, 2, 3, 4, 5 }, 0, 5, new ulong[] { 5, 4, 3, 2, 1 } }; yield return new object[] { new ulong[] { 1, 2, 3, 4, 5 }, 2, 3, new ulong[] { 1, 2, 5, 4, 3 } }; yield return new object[] { new ulong[] { 1, 2, 3, 4, 5 }, 0, 0, new ulong[] { 1, 2, 3, 4, 5 } }; yield return new object[] { new ulong[] { 1, 2, 3, 4, 5 }, 5, 0, new ulong[] { 1, 2, 3, 4, 5 } }; // Char yield return new object[] { new char[] { '1', '2', '3', '4', '5' }, 0, 5, new char[] { '5', '4', '3', '2', '1' } }; yield return new object[] { new char[] { '1', '2', '3', '4', '5' }, 2, 3, new char[] { '1', '2', '5', '4', '3' } }; yield return new object[] { new char[] { '1', '2', '3', '4', '5' }, 0, 0, new char[] { '1', '2', '3', '4', '5' } }; yield return new object[] { new char[] { '1', '2', '3', '4', '5' }, 5, 0, new char[] { '1', '2', '3', '4', '5' } }; // Bool yield return new object[] { new bool[] { false, false, true, true, false }, 0, 5, new bool[] { false, true, true, false, false } }; yield return new object[] { new bool[] { false, false, true, true, false }, 2, 3, new bool[] { false, false, false, true, true } }; yield return new object[] { new bool[] { false, false, true, true, false }, 0, 0, new bool[] { false, false, true, true, false } }; yield return new object[] { new bool[] { false, false, true, true, false }, 5, 0, new bool[] { false, false, true, true, false } }; // Single yield return new object[] { new float[] { 1, 2, 3, 4, 5 }, 0, 5, new float[] { 5, 4, 3, 2, 1 } }; yield return new object[] { new float[] { 1, 2, 3, 4, 5 }, 2, 3, new float[] { 1, 2, 5, 4, 3 } }; yield return new object[] { new float[] { 1, 2, 3, 4, 5 }, 0, 0, new float[] { 1, 2, 3, 4, 5 } }; yield return new object[] { new float[] { 1, 2, 3, 4, 5 }, 5, 0, new float[] { 1, 2, 3, 4, 5 } }; // Double yield return new object[] { new double[] { 1, 2, 3, 4, 5 }, 0, 5, new double[] { 5, 4, 3, 2, 1 } }; yield return new object[] { new double[] { 1, 2, 3, 4, 5 }, 2, 3, new double[] { 1, 2, 5, 4, 3 } }; yield return new object[] { new double[] { 1, 2, 3, 4, 5 }, 0, 0, new double[] { 1, 2, 3, 4, 5 } }; yield return new object[] { new double[] { 1, 2, 3, 4, 5 }, 5, 0, new double[] { 1, 2, 3, 4, 5 } }; // IntPtr yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)4, (IntPtr)5 }, 0, 5, new IntPtr[] { (IntPtr)5, (IntPtr)4, (IntPtr)3, (IntPtr)2, (IntPtr)1 } }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)4, (IntPtr)5 }, 2, 3, new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)5, (IntPtr)4, (IntPtr)3 } }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)4, (IntPtr)5 }, 0, 0, new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)4, (IntPtr)5 } }; yield return new object[] { new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)4, (IntPtr)5 }, 5, 0, new IntPtr[] { (IntPtr)1, (IntPtr)2, (IntPtr)3, (IntPtr)4, (IntPtr)5 } }; // UIntPtr yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)4, (UIntPtr)5 }, 0, 5, new UIntPtr[] { (UIntPtr)5, (UIntPtr)4, (UIntPtr)3, (UIntPtr)2, (UIntPtr)1 } }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)4, (UIntPtr)5 }, 2, 3, new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)5, (UIntPtr)4, (UIntPtr)3 } }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)4, (UIntPtr)5 }, 0, 0, new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)4, (UIntPtr)5 } }; yield return new object[] { new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)4, (UIntPtr)5 }, 5, 0, new UIntPtr[] { (UIntPtr)1, (UIntPtr)2, (UIntPtr)3, (UIntPtr)4, (UIntPtr)5 } }; // string[] can be cast to object[] yield return new object[] { new string[] { "1", "2", "3", "4", "5" }, 0, 5, new string[] { "5", "4", "3", "2", "1" } }; yield return new object[] { new string[] { "1", "2", "3", "4", "5" }, 2, 3, new string[] { "1", "2", "5", "4", "3" } }; yield return new object[] { new string[] { "1", "2", "3", "4", "5" }, 0, 0, new string[] { "1", "2", "3", "4", "5" } }; yield return new object[] { new string[] { "1", "2", "3", "4", "5" }, 5, 0, new string[] { "1", "2", "3", "4", "5" } }; // TestEnum[] can be cast to int[] var enumArray = new Int32Enum[] { Int32Enum.Case1, Int32Enum.Case2, Int32Enum.Case3, Int32Enum.Case1 }; yield return new object[] { enumArray, 0, 4, new Int32Enum[] { Int32Enum.Case1, Int32Enum.Case3, Int32Enum.Case2, Int32Enum.Case1 } }; yield return new object[] { enumArray, 2, 2, new Int32Enum[] { Int32Enum.Case1, Int32Enum.Case2, Int32Enum.Case1, Int32Enum.Case3 } }; yield return new object[] { enumArray, 0, 0, enumArray}; yield return new object[] { enumArray, 4, 0, enumArray}; // ValueType array ComparableValueType[] valueTypeArray = new ComparableValueType[] { new ComparableValueType(0), new ComparableValueType(1) }; yield return new object[] { valueTypeArray, 0, 2, new ComparableValueType[] { new ComparableValueType(1), new ComparableValueType(0) } }; yield return new object[] { valueTypeArray, 0, 0, valueTypeArray }; yield return new object[] { valueTypeArray, 2, 0, valueTypeArray }; } [Theory] [MemberData(nameof(Reverse_TestData))] public static void Reverse_SZArray(Array array, int index, int length, Array expected) { // Basic: forward SZArray Reverse(array, index, length, expected); // Advanced: convert SZArray to an array with non-zero lower bound const int LowerBound = 5; Reverse(NonZeroLowerBoundArray(array, LowerBound), index + LowerBound, length, NonZeroLowerBoundArray(expected, LowerBound)); } public static void Reverse(Array array, int index, int length, Array expected) { if (index == array.GetLowerBound(0) && length == array.Length) { // Use Reverse(Array) Array arrayClone1 = (Array)array.Clone(); Array.Reverse(arrayClone1); Assert.Equal(expected, arrayClone1); } // Use Reverse(Array, int, int) Array arrayClone2 = (Array)array.Clone(); Array.Reverse(arrayClone2, index, length); Assert.Equal(expected, expected); } [Fact] public static void Reverse_NullArray_ThrowsArgumentNullException() { Assert.Throws<ArgumentNullException>("array", () => Array.Reverse(null)); Assert.Throws<ArgumentNullException>("array", () => Array.Reverse(null, 0, 0)); } [Fact] public static void Reverse_MultidimensionalArray_ThrowsRankException() { Assert.Throws<RankException>(() => Array.Reverse((Array)new int[10, 10])); Assert.Throws<RankException>(() => Array.Reverse((Array)new int[10, 10], 0, 0)); } [Theory] [InlineData(0)] [InlineData(-1)] [InlineData(1)] public static void Reverse_IndexLessThanLowerBound_ThrowsArgumentOutOfRangeException(int lowerBound) { Assert.Throws<ArgumentOutOfRangeException>("index", () => Array.Reverse(NonZeroLowerBoundArray(new int[0], lowerBound), lowerBound - 1, 0)); } [Fact] public static void Reverse_NegativeLength_ThrowsArgumentOutOfRangeException() { Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.Reverse((Array)new int[10], 0, -1)); } [Theory] [InlineData(11, 0)] [InlineData(10, 1)] [InlineData(9, 2)] [InlineData(0, 11)] public static void Reverse_InvalidIndexPlusLength_ThrowsArgumentException(int index, int length) { Assert.Throws<ArgumentException>(null, () => Array.Reverse((Array)new int[10], index, length)); } [Fact] public static unsafe void Reverse_ArrayOfPointers_ThrowsNotSupportedException() { Assert.Throws<NotSupportedException>(() => Array.Reverse((Array)new int*[2])); Array.Reverse((Array)new int*[0]); Array.Reverse((Array)new int*[1]); } public static IEnumerable<object[]> Sort_Array_NonGeneric_TestData() { yield return new object[] { new int[0], 0, 0, new IntegerComparer(), new int[0] }; yield return new object[] { new int[] { 5 }, 0, 1, new IntegerComparer(), new int[] { 5 } }; yield return new object[] { new int[] { 5, 2 }, 0, 2, new IntegerComparer(), new int[] { 2, 5 } }; yield return new object[] { new int[] { 5, 2, 9, 8, 4, 3, 2, 4, 6 }, 0, 9, new IntegerComparer(), new int[] { 2, 2, 3, 4, 4, 5, 6, 8, 9 } }; yield return new object[] { new int[] { 5, 2, 9, 8, 4, 3, 2, 4, 6 }, 3, 4, new IntegerComparer(), new int[] { 5, 2, 9, 2, 3, 4, 8, 4, 6 } }; yield return new object[] { new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 0, 9, new IntegerComparer(), new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 } }; yield return new object[] { new int[] { 5, 2, 9, 8, 4, 3, 2, 4, 6 }, 0, 9, null, new int[] { 2, 2, 3, 4, 4, 5, 6, 8, 9 } }; yield return new object[] { new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }, 0, 9, null, new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 } }; yield return new object[] { new int[] { 5, 2, 9, 8, 4, 3, 2, 4, 6 }, 0, 0, null, new int[] { 5, 2, 9, 8, 4, 3, 2, 4, 6 } }; yield return new object[] { new int[] { 5, 2, 9, 8, 4, 3, 2, 4, 6 }, 9, 0, null, new int[] { 5, 2, 9, 8, 4, 3, 2, 4, 6 } }; } public static IEnumerable<object[]> Sort_Array_Generic_TestData() { yield return new object[] { new string[0], 0, 0, new StringComparer(), new string[0] }; yield return new object[] { new string[] { "5" }, 0, 1, new StringComparer(), new string[] { "5" } }; yield return new object[] { new string[] { "5", "2" }, 0, 2, new StringComparer(), new string[] { "2", "5" } }; yield return new object[] { new string[] { "5", "2", "9", "8", "4", "3", "2", "4", "6" }, 0, 9, new StringComparer(), new string[] { "2", "2", "3", "4", "4", "5", "6", "8", "9" } }; yield return new object[] { new string[] { "5", null, "2", "9", "8", "4", "3", "2", "4", "6" }, 0, 10, new StringComparer(), new string[] { null, "2", "2", "3", "4", "4", "5", "6", "8", "9" } }; yield return new object[] { new string[] { "5", null, "2", "9", "8", "4", "3", "2", "4", "6" }, 3, 4, new StringComparer(), new string[] { "5", null, "2", "3", "4", "8", "9", "2", "4", "6" } }; } [Theory] [MemberData(nameof(Sort_Array_NonGeneric_TestData))] [MemberData(nameof(Sort_Array_Generic_TestData))] public static void Sort_Array_NonGeneric(Array array, int index, int length, IComparer comparer, Array expected) { Array sortedArray; if (index == 0 && length == array.Length) { // Use Sort(Array) or Sort(Array, IComparer) if (comparer == null) { // Use Sort(Array) sortedArray = (Array)array.Clone(); Array.Sort(sortedArray); Assert.Equal(expected, sortedArray); } // Use Sort(Array, IComparer) sortedArray = (Array)array.Clone(); Array.Sort(sortedArray, comparer); Assert.Equal(expected, sortedArray); } if (comparer == null) { // Use Sort(Array, int, int) sortedArray = (Array)array.Clone(); Array.Sort(sortedArray, index, length); Assert.Equal(expected, sortedArray); } // Use Sort(Array, int, int, IComparer) sortedArray = (Array)array.Clone(); Array.Sort(sortedArray, index, length, comparer); Assert.Equal(expected, sortedArray); } [Theory] [MemberData(nameof(Sort_Array_Generic_TestData))] public static void Sort_Array_Generic(string[] array, int index, int length, IComparer comparer, string[] expected) { string[] sortedArray; if (index == 0 && length == array.Length) { // Use Sort<T>(T[]) or Sort<T>(T[], IComparer) if (comparer == null) { // Use Sort(Array) sortedArray = (string[])array.Clone(); Array.Sort(sortedArray); Assert.Equal(expected, sortedArray); } // Use Sort<T>(T[], IComparer) sortedArray = (string[])array.Clone(); Array.Sort(sortedArray, comparer); Assert.Equal(expected, sortedArray); } if (comparer == null) { // Use Sort<T>(T[], int, int) sortedArray = (string[])array.Clone(); Array.Sort(sortedArray, index, length); Assert.Equal(expected, sortedArray); } // Use Sort<T>(T[], int, int, IComparer) sortedArray = (string[])array.Clone(); Array.Sort(sortedArray, index, length, comparer); Assert.Equal(expected, sortedArray); } [Fact] public static void Sort_Array_Invalid() { Assert.Throws<ArgumentNullException>("array", () => Array.Sort(null)); // Array is null Assert.Throws<ArgumentNullException>("array", () => Array.Sort((int[])null)); // Array is null Assert.Throws<RankException>(() => Array.Sort(new int[10, 10])); // Array is multidimensional Assert.Throws<InvalidOperationException>(() => Array.Sort((Array)new object[] { "1", 2, new object() })); // One or more objects in array do not implement IComparable Assert.Throws<InvalidOperationException>(() => Array.Sort(new object[] { "1", 2, new object() })); // One or more objects in array do not implement IComparable } [Fact] public static void Sort_Array_IComparer_Invalid() { // Array is null Assert.Throws<ArgumentNullException>("array", () => Array.Sort(null, (IComparer)null)); Assert.Throws<ArgumentNullException>("array", () => Array.Sort(null, (IComparer<int>)null)); Assert.Throws<RankException>(() => Array.Sort(new int[10, 10], (IComparer)null)); // Array is multidimensional // One or more objects in array do not implement IComparable Assert.Throws<InvalidOperationException>(() => Array.Sort(new object[] { "1", 2, new object() }, (IComparer)null)); Assert.Throws<InvalidOperationException>(() => Array.Sort(new object[] { "1", 2, new object() }, (IComparer<object>)null)); } [Fact] public static void Sort_Array_Comparison_Invalid() { Assert.Throws<ArgumentNullException>("array", () => Array.Sort(null, (Comparison<int>)null)); // Array is null Assert.Throws<ArgumentNullException>("comparison", () => Array.Sort(new int[10], (Comparison<int>)null)); // Comparison is null } [Fact] public static void Sort_Array_Int_Int_Invalid() { // Array is null Assert.Throws<ArgumentNullException>("keys", () => Array.Sort(null, 0, 0)); Assert.Throws<ArgumentNullException>("array", () => Array.Sort((int[])null, 0, 0)); Assert.Throws<RankException>(() => Array.Sort(new int[10, 10], 0, 0, null)); // Array is multidimensional // One or more objects in keys do not implement IComparable Assert.Throws<InvalidOperationException>(() => Array.Sort((Array)new object[] { "1", 2, new object() }, 0, 3)); Assert.Throws<InvalidOperationException>(() => Array.Sort(new object[] { "1", 2, new object() }, 0, 3)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => Array.Sort((Array)new int[10], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>("index", () => Array.Sort(new int[10], -1, 0)); // Length < 0 Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.Sort((Array)new int[10], 0, -1)); Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.Sort(new int[10], 0, -1)); // Index + length > list.Count Assert.Throws<ArgumentException>(() => Array.Sort((Array)new int[10], 11, 0)); Assert.Throws<ArgumentException>(() => Array.Sort(new int[10], 11, 0)); Assert.Throws<ArgumentException>(() => Array.Sort((Array)new int[10], 10, 1)); Assert.Throws<ArgumentException>(() => Array.Sort(new int[10], 10, 1)); Assert.Throws<ArgumentException>(() => Array.Sort((Array)new int[10], 9, 2)); Assert.Throws<ArgumentException>(() => Array.Sort(new int[10], 9, 2)); } [Fact] public static void Sort_Array_Int_Int_IComparer_Invalid() { // Array is null Assert.Throws<ArgumentNullException>("keys", () => Array.Sort(null, 0, 0, null)); Assert.Throws<ArgumentNullException>("array", () => Array.Sort((int[])null, 0, 0, null)); Assert.Throws<RankException>(() => Array.Sort(new int[10, 10], 0, 0, null)); // Array is multidimensional // One or more objects in keys do not implement IComparable Assert.Throws<InvalidOperationException>(() => Array.Sort((Array)new object[] { "1", 2, new object() }, 0, 3, null)); Assert.Throws<InvalidOperationException>(() => Array.Sort(new object[] { "1", 2, new object() }, 0, 3, null)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => Array.Sort((Array)new int[10], -1, 0, null)); Assert.Throws<ArgumentOutOfRangeException>("index", () => Array.Sort(new int[10], -1, 0, null)); // Length < 0 Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.Sort((Array)new int[10], 0, -1, null)); Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.Sort(new int[10], 0, -1, null)); // Index + length > list.Count Assert.Throws<ArgumentException>(null, () => Array.Sort((Array)new int[10], 11, 0, null)); Assert.Throws<ArgumentException>(null, () => Array.Sort(new int[10], 11, 0, null)); Assert.Throws<ArgumentException>(null, () => Array.Sort((Array)new int[10], 10, 1, null)); Assert.Throws<ArgumentException>(null, () => Array.Sort(new int[10], 10, 1, null)); Assert.Throws<ArgumentException>(null, () => Array.Sort((Array)new int[10], 9, 2, null)); Assert.Throws<ArgumentException>(null, () => Array.Sort(new int[10], 9, 2, null)); } public static IEnumerable<object[]> Sort_Array_Array_NonGeneric_TestData() { yield return new object[] { new int[] { 3, 1, 2 }, new int[] { 4, 5, 6 }, 0, 3, new IntegerComparer(), new int[] { 1, 2, 3 }, new int[] { 5, 6, 4 } }; yield return new object[] { new int[] { 3, 1, 2 }, new string[] { "a", "b", "c" }, 0, 3, new IntegerComparer(), new int[] { 1, 2, 3 }, new string[] { "b", "c", "a" } }; yield return new object[] { new string[] { "bcd", "bc", "c", "ab" }, new int[] { 1, 2, 3, 4 }, 0, 4, new StringComparer(), new string[] { "ab", "bc", "bcd", "c" }, new int[] { 4, 2, 1, 3 } }; yield return new object[] { new string[] { "bcd", "bc", "c", "ab" }, new int[] { 1, 2, 3, 4 }, 1, 2, new StringComparer(), new string[] { "bcd", "bc", "c", "ab" }, new int[] { 1, 2, 3, 4 } }; yield return new object[] { new int[] { 3, 1, 2 }, new string[] { "a", "b", "c" }, 0, 2, new IntegerComparer(), new int[] { 1, 3, 2 }, new string[] { "b", "a", "c" } }; yield return new object[] { new int[] { 3, 1, 2, 1 }, new string[] { "a", "b", "c", "d" }, 1, 3, new IntegerComparer(), new int[] { 3, 1, 1, 2 }, new string[] { "a", "b", "d", "c" } }; yield return new object[] { new int[] { 3, 1, 2 }, new string[] { "a", "b", "c" }, 0, 3, null, new int[] { 1, 2, 3 }, new string[] { "b", "c", "a" } }; yield return new object[] { new int[] { 3, 2, 1, 4 }, new string[] { "a", "b", "c", "d" }, 1, 2, null, new int[] { 3, 1, 2, 4 }, new string[] { "a", "c", "b", "d" } }; yield return new object[] { new int[] { 3, 2, 1, 4 }, new string[] { "a", "b", "c", "d" }, 0, 4, new ReverseIntegerComparer(), new int[] { 4, 3, 2, 1 }, new string[] { "d", "a", "b", "c" } }; yield return new object[] { new int[] { 3, 2, 1, 4 }, new string[] { "a", "b", "c", "d", "e", "f" }, 0, 4, new IntegerComparer(), new int[] { 1, 2, 3, 4 }, new string[] { "c", "b", "a", "d", "e", "f" } }; // Items.Length > keys.Length yield return new object[] { new int[] { 3, 2, 1, 4 }, null, 0, 4, null, new int[] { 1, 2, 3, 4 }, null }; yield return new object[] { new int[] { 3, 2, 1, 4 }, null, 1, 2, null, new int[] { 3, 1, 2, 4 }, null }; var refArray = new ComparableRefType[] { new ComparableRefType(-5), new ComparableRefType(-4), new ComparableRefType(2), new ComparableRefType(-10), new ComparableRefType(5), new ComparableRefType(0) }; var sortedRefArray = new ComparableRefType[] { new ComparableRefType(-10), new ComparableRefType(-5), new ComparableRefType(-4), new ComparableRefType(0), new ComparableRefType(2), new ComparableRefType(5) }; var reversedRefArray = new ComparableRefType[] { new ComparableRefType(5), new ComparableRefType(2), new ComparableRefType(0), new ComparableRefType(-4), new ComparableRefType(-5), new ComparableRefType(-10) }; var valueArray = new ComparableValueType[] { new ComparableValueType(-5), new ComparableValueType(-4), new ComparableValueType(2), new ComparableValueType(-10), new ComparableValueType(5), new ComparableValueType(0) }; var sortedValueArray = new ComparableValueType[] { new ComparableValueType(-10), new ComparableValueType(-5), new ComparableValueType(-4), new ComparableValueType(0), new ComparableValueType(2), new ComparableValueType(5) }; yield return new object[] { refArray, refArray, 0, 6, null, sortedRefArray, sortedRefArray }; // Reference type, reference type yield return new object[] { valueArray, valueArray, 0, 6, null, sortedValueArray, sortedValueArray }; // Value type, value type yield return new object[] { refArray, valueArray, 0, 6, null, sortedRefArray, sortedValueArray }; // Reference type, value type yield return new object[] { valueArray, refArray, 0, 6, null, sortedValueArray, sortedRefArray }; // Value type, reference type yield return new object[] { refArray, refArray, 0, 6, new ReferenceTypeNormalComparer(), sortedRefArray, sortedRefArray }; // Reference type, reference type yield return new object[] { refArray, refArray, 0, 6, new ReferenceTypeReverseComparer(), reversedRefArray, reversedRefArray }; // Reference type, reference type yield return new object[] { new int[0], new int[0], 0, 0, null, new int[0], new int[0] }; yield return new object[] { refArray, null, 0, 6, null, sortedRefArray, null }; // Null items } public static IEnumerable<object[]> Sort_Array_Array_Generic_TestData() { yield return new object[] { new string[] { "bcd", "bc", "c", "ab" }, new string[] { "a", "b", "c", "d" }, 0, 4, new StringComparer(), new string[] { "ab", "bc", "bcd", "c" }, new string[] { "d", "b", "a", "c" } }; yield return new object[] { new string[] { "bcd", "bc", "c", "ab" }, new string[] { "a", "b", "c", "d" }, 0, 4, null, new string[] { "ab", "bc", "bcd", "c" }, new string[] { "d", "b", "a", "c" } }; } [Theory] [MemberData(nameof(Sort_Array_Array_NonGeneric_TestData))] [MemberData(nameof(Sort_Array_Array_Generic_TestData))] public static void Sort_Array_Array_NonGeneric(Array keys, Array items, int index, int length, IComparer comparer, Array expectedKeys, Array expectedItems) { Array sortedKeysArray = null; Array sortedItemsArray = null; if (index == 0 && length == keys.Length) { // Use Sort(Array, Array) or Sort(Array, Array, IComparer) if (comparer == null) { // Use Sort(Array, Array) sortedKeysArray = (Array)keys.Clone(); if (items != null) { sortedItemsArray = (Array)items.Clone(); } Array.Sort(sortedKeysArray, sortedItemsArray); Assert.Equal(expectedKeys, sortedKeysArray); Assert.Equal(expectedItems, sortedItemsArray); } // Use Sort(Array, Array, IComparer) sortedKeysArray = (Array)keys.Clone(); if (items != null) { sortedItemsArray = (Array)items.Clone(); } Array.Sort(sortedKeysArray, sortedItemsArray, comparer); Assert.Equal(expectedKeys, sortedKeysArray); Assert.Equal(expectedItems, sortedItemsArray); } if (comparer == null) { // Use Sort(Array, Array, int, int) sortedKeysArray = (Array)keys.Clone(); if (items != null) { sortedItemsArray = (Array)items.Clone(); } Array.Sort(sortedKeysArray, sortedItemsArray, index, length); Assert.Equal(expectedKeys, sortedKeysArray); Assert.Equal(expectedItems, sortedItemsArray); } // Use Sort(Array, Array, int, int, IComparer) sortedKeysArray = (Array)keys.Clone(); if (items != null) { sortedItemsArray = (Array)items.Clone(); } Array.Sort(sortedKeysArray, sortedItemsArray, index, length, comparer); Assert.Equal(expectedKeys, sortedKeysArray); Assert.Equal(expectedItems, sortedItemsArray); } [Theory] [MemberData(nameof(Sort_Array_Array_Generic_TestData))] public static void Sort_Array_Array_Generic(string[] keys, string[] items, int index, int length, IComparer comparer, string[] expectedKeys, string[] expectedItems) { string[] sortedKeysArray = null; string[] sortedItemsArray = null; if (index == 0 && length == keys.Length) { // Use Sort<T>(T[], T[]) or Sort<T>(T[], T[], IComparer) if (comparer == null) { // Use Sort<T>(T[], T[]) sortedKeysArray = (string[])keys.Clone(); if (items != null) { sortedItemsArray = (string[])items.Clone(); } Array.Sort(sortedKeysArray, sortedItemsArray); Assert.Equal(expectedKeys, sortedKeysArray); Assert.Equal(expectedItems, sortedItemsArray); } // Use Sort<T>(T[], T[], IComparer) sortedKeysArray = (string[])keys.Clone(); if (items != null) { sortedItemsArray = (string[])items.Clone(); } Array.Sort(sortedKeysArray, sortedItemsArray, comparer); Assert.Equal(expectedKeys, sortedKeysArray); Assert.Equal(expectedItems, sortedItemsArray); } if (comparer == null) { // Use Sort<T>(T[], T[], int, int) sortedKeysArray = (string[])keys.Clone(); if (items != null) { sortedItemsArray = (string[])items.Clone(); } Array.Sort(sortedKeysArray, sortedItemsArray, index, length); Assert.Equal(expectedKeys, sortedKeysArray); Assert.Equal(expectedItems, sortedItemsArray); } // Use Sort(Array, Array, int, int, IComparer) sortedKeysArray = (string[])keys.Clone(); if (items != null) { sortedItemsArray = (string[])items.Clone(); } Array.Sort(sortedKeysArray, sortedItemsArray, index, length, comparer); Assert.Equal(expectedKeys, sortedKeysArray); Assert.Equal(expectedItems, sortedItemsArray); } [Fact] public static void Sort_Array_Array_Invalid() { // Keys is null Assert.Throws<ArgumentNullException>("keys", () => Array.Sort(null, new int[10])); Assert.Throws<ArgumentNullException>("keys", () => Array.Sort((int[])null, new int[10])); // Keys.Length > items.Length Assert.Throws<ArgumentException>(null, () => Array.Sort((Array)new int[10], new int[9])); Assert.Throws<ArgumentException>(null, () => Array.Sort(new int[10], new int[9])); Assert.Throws<RankException>(() => Array.Sort(new int[10, 10], new int[10])); // Keys is multidimensional Assert.Throws<RankException>(() => Array.Sort(new int[10], new int[10, 10])); // Items is multidimensional Array keys = Array.CreateInstance(typeof(object), new int[] { 1 }, new int[] { 1 }); Array items = Array.CreateInstance(typeof(object), new int[] { 1 }, new int[] { 2 }); Assert.Throws<ArgumentException>(null, () => Array.Sort(keys, items)); // Keys and items have different lower bounds // One or more objects in keys do not implement IComparable Assert.Throws<InvalidOperationException>(() => Array.Sort((Array)new object[] { "1", 2, new object() }, new object[3])); Assert.Throws<InvalidOperationException>(() => Array.Sort(new object[] { "1", 2, new object() }, new object[3])); } [Fact] public static void Sort_Array_Array_IComparer_Invalid() { // Keys is null Assert.Throws<ArgumentNullException>("keys", () => Array.Sort(null, new int[10], null)); Assert.Throws<ArgumentNullException>("keys", () => Array.Sort((int[])null, new int[10], null)); // Keys.Length > items.Length Assert.Throws<ArgumentException>(null, () => Array.Sort((Array)new int[10], new int[9], null)); Assert.Throws<ArgumentException>(null, () => Array.Sort(new int[10], new int[9], null)); Assert.Throws<RankException>(() => Array.Sort(new int[10, 10], new int[10], null)); // Keys is multidimensional Assert.Throws<RankException>(() => Array.Sort(new int[10], new int[10, 10], null)); // Items is multidimensional Array keys = Array.CreateInstance(typeof(object), new int[] { 1 }, new int[] { 1 }); Array items = Array.CreateInstance(typeof(object), new int[] { 1 }, new int[] { 2 }); Assert.Throws<ArgumentException>(null, () => Array.Sort(keys, items, null)); // Keys and items have different lower bounds // One or more objects in keys do not implement IComparable Assert.Throws<InvalidOperationException>(() => Array.Sort((Array)new object[] { "1", 2, new object() }, new object[3], null)); Assert.Throws<InvalidOperationException>(() => Array.Sort(new object[] { "1", 2, new object() }, new object[3], null)); } [Fact] public static void Sort_Array_Array_Int_Int_Invalid() { // Keys is null Assert.Throws<ArgumentNullException>("keys", () => Array.Sort(null, new int[10], 0, 0)); Assert.Throws<ArgumentNullException>("keys", () => Array.Sort((int[])null, new int[10], 0, 0)); // Keys.Length > items.Length Assert.Throws<ArgumentException>(null, () => Array.Sort((Array)new int[10], new int[9], 0, 10)); Assert.Throws<ArgumentException>(null, () => Array.Sort(new int[10], new int[9], 0, 10)); Assert.Throws<RankException>(() => Array.Sort(new int[10, 10], new int[10], 0, 0)); // Keys is multidimensional Assert.Throws<RankException>(() => Array.Sort(new int[10], new int[10, 10], 0, 0)); // Items is multidimensional Array keys = Array.CreateInstance(typeof(object), new int[] { 1 }, new int[] { 1 }); Array items = Array.CreateInstance(typeof(object), new int[] { 1 }, new int[] { 2 }); Assert.Throws<ArgumentException>(null, () => Array.Sort(keys, items, 0, 1)); // Keys and items have different lower bounds // One or more objects in keys do not implement IComparable Assert.Throws<InvalidOperationException>(() => Array.Sort((Array)new object[] { "1", 2, new object() }, new object[3], 0, 3)); Assert.Throws<InvalidOperationException>(() => Array.Sort(new object[] { "1", 2, new object() }, new object[3], 0, 3)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => Array.Sort((Array)new int[10], new int[10], -1, 0)); Assert.Throws<ArgumentOutOfRangeException>("index", () => Array.Sort(new int[10], new int[10], -1, 0)); // Length < 0 Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.Sort((Array)new int[10], new int[10], 0, -1)); Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.Sort(new int[10], new int[10], 0, -1)); // Index + length > list.Count Assert.Throws<ArgumentException>(null, () => Array.Sort((Array)new int[10], new int[10], 11, 0)); Assert.Throws<ArgumentException>(null, () => Array.Sort(new int[10], new int[10], 11, 0)); Assert.Throws<ArgumentException>(null, () => Array.Sort((Array)new int[10], new int[10], 10, 1)); Assert.Throws<ArgumentException>(null, () => Array.Sort(new int[10], new int[10], 10, 1)); Assert.Throws<ArgumentException>(null, () => Array.Sort((Array)new int[10], new int[10], 9, 2)); Assert.Throws<ArgumentException>(null, () => Array.Sort(new int[10], new int[10], 9, 2)); } [Fact] public static void Sort_Array_Array_Int_Int_IComparer_Invalid() { // Keys is null Assert.Throws<ArgumentNullException>("keys", () => Array.Sort(null, new int[10], 0, 0, null)); Assert.Throws<ArgumentNullException>("keys", () => Array.Sort((int[])null, new int[10], 0, 0, null)); // Keys.Length > items.Length Assert.Throws<ArgumentException>(null, () => Array.Sort((Array)new int[10], new int[9], 0, 10, null)); Assert.Throws<ArgumentException>(null, () => Array.Sort(new int[10], new int[9], 0, 10, null)); Assert.Throws<RankException>(() => Array.Sort(new int[10, 10], new int[10], 0, 0, null)); // Keys is multidimensional Assert.Throws<RankException>(() => Array.Sort(new int[10], new int[10, 10], 0, 0, null)); // Items is multidimensional Array keys = Array.CreateInstance(typeof(object), new int[] { 1 }, new int[] { 1 }); Array items = Array.CreateInstance(typeof(object), new int[] { 1 }, new int[] { 2 }); Assert.Throws<ArgumentException>(null, () => Array.Sort(keys, items, 0, 1, null)); // Keys and items have different lower bounds // One or more objects in keys do not implement IComparable Assert.Throws<InvalidOperationException>(() => Array.Sort((Array)new object[] { "1", 2, new object() }, new object[3], 0, 3, null)); Assert.Throws<InvalidOperationException>(() => Array.Sort(new object[] { "1", 2, new object() }, new object[3], 0, 3, null)); // Index < 0 Assert.Throws<ArgumentOutOfRangeException>("index", () => Array.Sort((Array)new int[10], new int[10], -1, 0, null)); Assert.Throws<ArgumentOutOfRangeException>("index", () => Array.Sort(new int[10], new int[10], -1, 0, null)); // Length < 0 Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.Sort((Array)new int[10], new int[10], 0, -1, null)); Assert.Throws<ArgumentOutOfRangeException>("length", () => Array.Sort(new int[10], new int[10], 0, -1, null)); // Index + length > list.Count Assert.Throws<ArgumentException>(null, () => Array.Sort((Array)new int[10], new int[10], 11, 0, null)); Assert.Throws<ArgumentException>(null, () => Array.Sort(new int[10], new int[10], 11, 0, null)); Assert.Throws<ArgumentException>(null, () => Array.Sort((Array)new int[10], new int[10], 10, 1, null)); Assert.Throws<ArgumentException>(null, () => Array.Sort(new int[10], new int[10], 10, 1, null)); Assert.Throws<ArgumentException>(null, () => Array.Sort((Array)new int[10], new int[10], 9, 2, null)); Assert.Throws<ArgumentException>(null, () => Array.Sort(new int[10], new int[10], 9, 2, null)); } [Fact] public static void SetValue_Casting() { // Null -> default(null) var arr1 = new NonGenericStruct[3]; arr1[1].x = 0x22222222; arr1.SetValue(null, new int[] { 1 }); Assert.Equal(0, arr1[1].x); // T -> Nullable<T> var arr2 = new int?[3]; arr2.SetValue(42, new int[] { 1 }); int? nullable1 = arr2[1]; Assert.True(nullable1.HasValue); Assert.Equal(42, nullable1.Value); // Null -> Nullable<T> var arr3 = new int?[3]; arr3[1] = 42; arr3.SetValue(null, new int[] { 1 }); int? nullable2 = arr3[1]; Assert.False(nullable2.HasValue); // Primitive widening var arr4 = new int[3]; arr4.SetValue((short)42, new int[] { 1 }); Assert.Equal(42, arr4[1]); // Widening from enum to primitive var arr5 = new int[3]; arr5.SetValue(SByteEnum.MinusTwo, new int[] { 1 }); Assert.Equal(-2, arr5[1]); } [Fact] public static void SetValue_Casting_Invalid() { // Unlike most of the other reflection apis, converting or widening a primitive to an enum is NOT allowed. var arr1 = new SByteEnum[3]; Assert.Throws<InvalidCastException>(() => arr1.SetValue((sbyte)1, new int[] { 1 })); // Primitive widening must be value-preserving var arr2 = new int[3]; Assert.Throws<ArgumentException>(null, () => arr2.SetValue((uint)42, new int[] { 1 })); // T -> Nullable<T> T must be exact var arr3 = new int?[3]; Assert.Throws<InvalidCastException>(() => arr3.SetValue((short)42, new int[] { 1 })); } [Fact] public static void SetValue_Invalid() { Assert.Throws<InvalidCastException>(() => new int[10].SetValue("1", 1)); // Value has an incompatible type Assert.Throws<InvalidCastException>(() => new int[10, 10].SetValue("1", new int[] { 1, 1 })); // Value has an incompatible type Assert.Throws<IndexOutOfRangeException>(() => new int[10].SetValue(1, -1)); // Index < 0 Assert.Throws<IndexOutOfRangeException>(() => new int[10].SetValue(1, 10)); // Index >= array.Length Assert.Throws<ArgumentException>(null, () => new int[10, 10].SetValue(1, 0)); // Array is multidimensional Assert.Throws<ArgumentNullException>("indices", () => new int[10].SetValue(1, (int[])null)); // Indices is null Assert.Throws<ArgumentException>(null, () => new int[10, 10].SetValue(1, new int[] { 1, 2, 3 })); // Indices.Length > array.Length Assert.Throws<IndexOutOfRangeException>(() => new int[8, 10].SetValue(1, new int[] { -1, 2 })); // Indices[0] < 0 Assert.Throws<IndexOutOfRangeException>(() => new int[8, 10].SetValue(1, new int[] { 9, 2 })); // Indices[0] > array.GetLength(0) Assert.Throws<IndexOutOfRangeException>(() => new int[10, 8].SetValue(1, new int[] { 1, -1 })); // Indices[1] < 0 Assert.Throws<IndexOutOfRangeException>(() => new int[10, 8].SetValue(1, new int[] { 1, 9 })); // Indices[1] > array.GetLength(1) } public static IEnumerable<object[]> TrueForAll_TestData() { yield return new object[] { new int[] { 1, 2, 3, 4, 5 }, (Predicate<int>)(i => i > 0), true }; yield return new object[] { new int[] { 1, 2, 3, 4, 5 }, (Predicate<int>)(i => i == 3), false }; yield return new object[] { new int[0], (Predicate<int>)(i => false), true }; } [Theory] [MemberData(nameof(TrueForAll_TestData))] public static void TrueForAll(int[] array, Predicate<int> match, bool expected) { Assert.Equal(expected, Array.TrueForAll(array, match)); } [Fact] public static void TrueForAll_Null_ThrowsArgumentNullException() { // Array is null Assert.Throws<ArgumentNullException>("array", () => Array.TrueForAll((int[])null, i => i > 0)); Assert.Throws<ArgumentNullException>("match", () => Array.TrueForAll(new int[0], null)); } [Fact] public static void ICollection_IsSynchronized_ReturnsFalse() { ICollection array = new int[] { 1, 2, 3 }; Assert.False(array.IsSynchronized); Assert.Same(array, array.SyncRoot); } [Theory] [InlineData(new int[] { 0, 1, 2, 3, 4 }, new int[] { 9, 9, 9, 9, 9 }, 0, new int[] { 0, 1, 2, 3, 4 })] [InlineData(new int[] { 0, 1, 2, 3, 4 }, new int[] { 9, 9, 9, 9, 9, 9, 9, 9 }, 2, new int[] { 9, 9, 0, 1, 2, 3, 4, 9 })] public static void IList_CopyTo(Array array, Array destinationArray, int index, Array expected) { IList iList = array; iList.CopyTo(destinationArray, index); Assert.Equal(expected, destinationArray); } [Fact] public static void IList_CopyTo_Invalid() { IList iList = new int[] { 7, 8, 9, 10, 11, 12, 13 }; Assert.Throws<ArgumentNullException>("dest", () => iList.CopyTo(null, 0)); // Destination array is null Assert.Throws<ArgumentOutOfRangeException>("dstIndex", () => iList.CopyTo(new int[7], -1)); // Index < 0 Assert.Throws<ArgumentException>("", () => iList.CopyTo(new int[7], 8)); // Index > destinationArray.Length } private static void VerifyArray(Array array, Type elementType, int[] lengths, int[] lowerBounds, object repeatedValue) { VerifyArray(array, elementType, lengths, lowerBounds); // Pointer arrays don't support enumeration if (!elementType.IsPointer) { foreach (object obj in array) { Assert.Equal(repeatedValue, obj); } } } private static void VerifyArray(Array array, Type elementType, int[] lengths, int[] lowerBounds) { Assert.Equal(elementType, array.GetType().GetElementType()); Assert.Equal(array.Rank, array.GetType().GetArrayRank()); Assert.Equal(lengths.Length, array.Rank); Assert.Equal(GetLength(lengths), array.Length); for (int dimension = 0; dimension < array.Rank; dimension++) { Assert.Equal(lengths[dimension], array.GetLength(dimension)); Assert.Equal(lowerBounds[dimension], array.GetLowerBound(dimension)); Assert.Equal(lowerBounds[dimension] + lengths[dimension] - 1, array.GetUpperBound(dimension)); } Assert.Throws<IndexOutOfRangeException>(() => array.GetLength(-1)); // Dimension < 0 Assert.Throws<IndexOutOfRangeException>(() => array.GetLength(array.Rank)); // Dimension >= array.Rank Assert.Throws<IndexOutOfRangeException>(() => array.GetLowerBound(-1)); // Dimension < 0 Assert.Throws<IndexOutOfRangeException>(() => array.GetLowerBound(array.Rank)); // Dimension >= array.Rank Assert.Throws<IndexOutOfRangeException>(() => array.GetUpperBound(-1)); // Dimension < 0 Assert.Throws<IndexOutOfRangeException>(() => array.GetUpperBound(array.Rank)); // Dimension >= array.Rank if (!elementType.IsPointer) { VerifyArrayAsIList(array); } } private static void VerifyArrayAsIList(Array array) { IList iList = array; Assert.Equal(array.Length, iList.Count); Assert.Equal(array, iList.SyncRoot); Assert.False(iList.IsSynchronized); Assert.True(iList.IsFixedSize); Assert.False(iList.IsReadOnly); Assert.Throws<NotSupportedException>(() => iList.Add(2)); Assert.Throws<NotSupportedException>(() => iList.Insert(0, 2)); Assert.Throws<NotSupportedException>(() => iList.Remove(0)); Assert.Throws<NotSupportedException>(() => iList.RemoveAt(0)); if (array.Rank == 1) { int lowerBound = array.GetLowerBound(0); for (int i = lowerBound; i < lowerBound + array.Length; i++) { object obj = iList[i]; Assert.Equal(array.GetValue(i), obj); Assert.Equal(Array.IndexOf(array, obj) >= lowerBound, iList.Contains(obj)); Assert.Equal(Array.IndexOf(array, obj), iList.IndexOf(obj)); } Assert.Equal(Array.IndexOf(array, null) >= lowerBound, iList.Contains(null)); Assert.Equal(Array.IndexOf(array, 999) >= lowerBound, iList.Contains(999)); Assert.Equal(Array.IndexOf(array, null), iList.IndexOf(null)); Assert.Equal(Array.IndexOf(array, 999), iList.IndexOf(999)); if (array.Length > 1) { object oldValue = iList[lowerBound]; object newValue = iList[lowerBound + 1]; iList[lowerBound] = newValue; Assert.Equal(newValue, iList[lowerBound]); iList[lowerBound] = oldValue; } } else { Assert.Throws<RankException>(() => iList.Contains(null)); Assert.Throws<RankException>(() => iList.IndexOf(null)); Assert.Throws<ArgumentException>(null, () => iList[0]); Assert.Throws<ArgumentException>(null, () => iList[0] = 1); } } private static Array NonZeroLowerBoundArray(Array szArrayContents, int lowerBound) { Assert.Equal(0, szArrayContents.GetLowerBound(0)); Array array = Array.CreateInstance(szArrayContents.GetType().GetElementType(), new int[] { szArrayContents.Length }, new int[] { lowerBound }); for (int i = 0; i < szArrayContents.Length; i++) { array.SetValue(szArrayContents.GetValue(i), i + lowerBound); } return array; } private static int GetLength(int[] lengths) { int length = 1; for (int i = 0; i < lengths.Length; i++) { length *= lengths[i]; } return length; } private static NonGenericStruct[] CreateStructArray() { return new NonGenericStruct[] { new NonGenericStruct { x = 1, s = "Hello1", z = 2 }, new NonGenericStruct { x = 2, s = "Hello2", z = 3 }, new NonGenericStruct { x = 3, s = "Hello3", z = 4 }, new NonGenericStruct { x = 4, s = "Hello4", z = 5 }, new NonGenericStruct { x = 5, s = "Hello5", z = 6 } }; } private struct NonGenericStruct { public int x; public string s; public int z; } private class IntegerComparer : IComparer, IComparer<int>, IEqualityComparer { public int Compare(object x, object y) => Compare((int)x, (int)y); public int Compare(int x, int y) => x - y; bool IEqualityComparer.Equals(object x, object y) => ((int)x) == ((int)y); public int GetHashCode(object obj) => ((int)obj) >> 2; } public class ReverseIntegerComparer : IComparer { public int Compare(object x, object y) => -((int)x).CompareTo((int)y); } private class StringComparer : IComparer, IComparer<string> { public int Compare(object x, object y) => Compare((string)x, (string)y); public int Compare(string x, string y) => string.Compare(x, y); } private class ComparableRefType : IComparable, IEquatable<ComparableRefType> { public int Id; public ComparableRefType(int id) { Id = id; } public int CompareTo(object other) { ComparableRefType o = (ComparableRefType)other; return Id.CompareTo(o.Id); } public override string ToString() => "C:" + Id; public override bool Equals(object obj) { return obj is ComparableRefType && ((ComparableRefType)obj).Id == Id; } public bool Equals(ComparableRefType other) => other.Id == Id; public override int GetHashCode() => Id.GetHashCode(); } private struct ComparableValueType : IComparable, IEquatable<ComparableValueType> { public int Id; public ComparableValueType(int id) { Id = id; } public int CompareTo(object other) { ComparableValueType o = (ComparableValueType)other; return Id.CompareTo(o.Id); } public override string ToString() => "S:" + Id; public override bool Equals(object obj) { return obj is ComparableValueType && ((ComparableValueType)obj).Equals(this); } public bool Equals(ComparableValueType other) => other.Id == Id; public override int GetHashCode() => Id.GetHashCode(); } private class ReferenceTypeNormalComparer : IComparer { public int Compare(ComparableRefType x, ComparableRefType y) => x.CompareTo(y); public int Compare(object x, object y) => Compare((ComparableRefType)x, (ComparableRefType)y); } private class ReferenceTypeReverseComparer : IComparer { public int Compare(ComparableRefType x, ComparableRefType y) => -x.CompareTo(y); public int Compare(object x, object y) => Compare((ComparableRefType)x, (ComparableRefType)y); } private class NotInt32 : IEquatable<int> { public bool Equals(int other) { throw new NotImplementedException(); } } public class EqualsOverrider { public int Value { get; set; } public override bool Equals(object other) => other is EqualsOverrider && ((EqualsOverrider)other).Value == Value; public override int GetHashCode() => Value; } public class NonGenericClass1 { } public class NonGenericClass2 { } public class NonGenericSubClass2 : NonGenericClass2 { } public class NonGenericSubClass1 : NonGenericClass1 { } public class GenericClass<T> { } public struct GenericStruct<T> { } public interface NonGenericInterface1 { } public interface NonGenericInterface2 { } public interface GenericInterface<T> { } public struct StructWithNonGenericInterface1 : NonGenericInterface1 { } public struct StructWithNonGenericInterface1_2 : NonGenericInterface1, NonGenericInterface2 { } public class ClassWithNonGenericInterface1 : NonGenericInterface1 { } public class ClassWithNonGenericInterface1_2 : NonGenericInterface1, NonGenericInterface2 { } public interface NonGenericInterfaceWithNonGenericInterface1 : NonGenericInterface1 { } public class ClassWithNonGenericInterfaceWithNonGenericInterface1 : NonGenericInterfaceWithNonGenericInterface1 { } public abstract class AbstractClass { } public static class StaticClass { } public enum SByteEnum : sbyte { MinusTwo = -2, Zero = 0, Five = 5 } public enum Int16Enum : short { Min = short.MinValue, One = 1, Two = 2, Max = short.MaxValue } public enum Int32Enum { Case1, Case2, Case3 } public enum Int64Enum : long { } } }
58.544343
292
0.551918
[ "MIT" ]
FrancisFYK/corefx
src/System.Runtime/tests/System/ArrayTests.cs
210,584
C#
using System; using System.Collections.Generic; using System.Linq; namespace EasyElasticSearch { public class EsConfig { public string Urls { get; set; } public string UserName { get; set; } public string Password { get; set; } public List<Uri> Uris => Urls.Split('|').Select(x => new Uri(x)).ToList(); } }
19.777778
82
0.617978
[ "MIT" ]
wmchuang/EasyElasticSearch
EasyElasticSearch/EasyElasticSearch/Config/EsConfig.cs
358
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("TaskRunner.Core.Test")] [assembly: AssemblyDescription("JohnsonFan@yahoo.com")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Johnson Fan")] [assembly: AssemblyProduct("TaskRunner.Core.Test")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("Johnson Fan")] [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("f4495395-01b0-4a06-b302-4b50b6f579df")] // 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.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.305556
84
0.753357
[ "MIT" ]
CodeCowboyOrg/TaskRunner
source/TaskRunner.Core.Test/Properties/AssemblyInfo.cs
1,418
C#
// Generated on 12/11/2014 19:02:09 using System; using System.Collections.Generic; using System.Linq; using BlueSheep.Common.IO; namespace BlueSheep.Common.Protocol.Types { public class ProtectedEntityWaitingForHelpInfo { public new const short ID = 186; public virtual short TypeId { get { return ID; } } public int timeLeftBeforeFight; public int waitTimeForPlacement; public sbyte nbPositionForDefensors; public ProtectedEntityWaitingForHelpInfo() { } public ProtectedEntityWaitingForHelpInfo(int timeLeftBeforeFight, int waitTimeForPlacement, sbyte nbPositionForDefensors) { this.timeLeftBeforeFight = timeLeftBeforeFight; this.waitTimeForPlacement = waitTimeForPlacement; this.nbPositionForDefensors = nbPositionForDefensors; } public virtual void Serialize(BigEndianWriter writer) { writer.WriteInt(timeLeftBeforeFight); writer.WriteInt(waitTimeForPlacement); writer.WriteSByte(nbPositionForDefensors); } public virtual void Deserialize(BigEndianReader reader) { timeLeftBeforeFight = reader.ReadInt(); waitTimeForPlacement = reader.ReadInt(); nbPositionForDefensors = reader.ReadSByte(); if (nbPositionForDefensors < 0) throw new Exception("Forbidden value on nbPositionForDefensors = " + nbPositionForDefensors + ", it doesn't respect the following condition : nbPositionForDefensors < 0"); } } }
18.695122
187
0.704501
[ "MIT" ]
Sadikk/BlueSheep
BlueSheep/Common/Protocol/types/game/fight/ProtectedEntityWaitingForHelpInfo.cs
1,533
C#
//********************************************************************* //xCAD //Copyright(C) 2020 Xarial Pty Limited //Product URL: https://www.xcad.net //License: https://xcad.xarial.com/license/ //********************************************************************* using System; using System.Collections.Generic; using System.Text; namespace Xarial.XCad.Base.Enums { public enum MessageBoxIcon_e { Info, Question, Error, Warning } }
22.045455
72
0.461856
[ "MIT" ]
jonnypjohnston/Xarial-xcad
src/Base/Base/Enums/MessageBoxIcon_e.cs
487
C#
using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hubs; using Slack.Dtos; namespace Slack.Hubs { [HubName("messageHub")] public class MessageHub : Hub { public void Send(MessageDto dto) { Clients.Others.broadcastMessage(dto); } } }
19.866667
49
0.637584
[ "MIT" ]
QuinntyneBrown/slack
Server/Hubs/MessageHub.cs
300
C#
namespace EducationHub.Services.Data.Lessons { using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using EducationHub.Data.Common.Repositories; using EducationHub.Data.Models; using Mapping; using Microsoft.EntityFrameworkCore; public class LessonsService : ILessonsService { private readonly IDeletableEntityRepository<Lesson> lessonsRepository; public LessonsService(IDeletableEntityRepository<Lesson> lessonsRepository) { this.lessonsRepository = lessonsRepository; } public async Task<T> ByIdAsync<T>(string id) => await this.lessonsRepository .AllAsNoTracking() .Where(l => l.Id == id) .To<T>() .FirstOrDefaultAsync(); public async Task CreateAsync(string title, string description, string videoUrl, string userId, int categoryId, string courseId = null) { var lesson = new Lesson { Title = title, Description = description, VideoUrl = videoUrl, UserId = userId, CategoryId = categoryId, CourseId = courseId, }; await this.lessonsRepository.AddAsync(lesson); await this.lessonsRepository.SaveChangesAsync(); } public async Task EditAsync(string id, string title, string description, string videoUrl, int categoryId, string courseId = null) { var lesson = await this.lessonsRepository.GetByIdWithDeletedAsync(id); lesson.Title = title; lesson.Description = description; lesson.VideoUrl = videoUrl; lesson.CategoryId = categoryId; if (courseId != null) { lesson.CourseId = courseId; } this.lessonsRepository.Update(lesson); await this.lessonsRepository.SaveChangesAsync(); } public async Task<IEnumerable<T>> GetByCategoryIdAsync<T>(int categoryId, int page, int itemsPerPage = 4) => await this.lessonsRepository .AllAsNoTracking() .Where(l => l.CategoryId == categoryId && l.CourseId == null) .OrderByDescending(l => l.CreatedOn) .Skip((page - 1) * itemsPerPage) .Take(itemsPerPage) .To<T>() .ToListAsync(); public async Task<IEnumerable<T>> GetByUserIdAsync<T>(string userId) => await this.lessonsRepository .AllAsNoTracking() .Where(l => l.UserId == userId && l.CourseId == null) .OrderByDescending(l => l.CreatedOn) .To<T>() .ToListAsync(); public async Task DeleteAsync(string id) { var category = await this.lessonsRepository.GetByIdWithDeletedAsync(id); this.lessonsRepository.Delete(category); await this.lessonsRepository.SaveChangesAsync(); } public int GetCountByCategory(int id) => this.lessonsRepository .All() .Where(l => l.Course == null && l.CategoryId == id) .Count(); } }
34.863158
143
0.571558
[ "MIT" ]
mitovV/-EducationHub
Services/EducationHub.Services.Data/Lessons/LessonsService.cs
3,314
C#
// 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.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using Microsoft.AspNetCore.Mvc.ModelBinding.Validation; namespace FormatterWebSite { // A System.Security.Principal.SecurityIdentifier like type that works on xplat public class RecursiveIdentifier : IValidatableObject { public RecursiveIdentifier(string identifier) { Value = identifier; } [Required] public string Value { get; } public RecursiveIdentifier AccountIdentifier => new RecursiveIdentifier(Value); public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { return Enumerable.Empty<ValidationResult>(); } } }
30.966667
111
0.715823
[ "Apache-2.0" ]
1175169074/aspnetcore
src/Mvc/test/WebSites/FormatterWebSite/Models/RecursiveIdentifier.cs
929
C#
using System; using CarouselView.FormsPlugin.Abstractions; namespace CarouselView.FormsPlugin.Droid { internal interface IViewPager { void SetPagingEnabled(bool enabled); void SetElement(CarouselViewControl element); } }
20.916667
53
0.741036
[ "MIT" ]
Nobody84/CarouselView
CarouselView/CarouselView.FormsPlugin.Android/Implementation/IViewPager.cs
253
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Utilities; using Microsoft.MixedReality.Toolkit.Utilities.Editor; using Microsoft.MixedReality.Toolkit.Input.UnityInput; using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; using Microsoft.MixedReality.Toolkit.Editor; namespace Microsoft.MixedReality.Toolkit.Input.Editor { [CustomEditor(typeof(MixedRealityControllerMappingProfile))] public class MixedRealityControllerMappingProfileInspector : BaseMixedRealityToolkitConfigurationProfileInspector { private struct ControllerRenderProfile { public SupportedControllerType SupportedControllerType; public Handedness Handedness; public MixedRealityInteractionMapping[] Interactions; public ControllerRenderProfile(SupportedControllerType supportedControllerType, Handedness handedness, MixedRealityInteractionMapping[] interactions) { SupportedControllerType = supportedControllerType; Handedness = handedness; Interactions = interactions; } } private static readonly GUIContent ControllerAddButtonContent = new GUIContent("+ Add a New Controller Definition"); private static readonly GUIContent ControllerMinusButtonContent = new GUIContent("-", "Remove Controller Definition"); private static readonly GUIContent GenericTypeContent = new GUIContent("Generic Type"); private static readonly GUIContent HandednessTypeContent = new GUIContent("Handedness"); private static MixedRealityControllerMappingProfile thisProfile; private SerializedProperty mixedRealityControllerMappings; private static bool showControllerDefinitions = false; private const string ProfileTitle = "Controller Input Mapping Settings"; private const string ProfileDescription = "Use this profile to define all the controllers and their inputs your users will be able to use in your application.\n\n" + "You'll want to define all your Input Actions first. They can then be wired up to hardware sensors, controllers, gestures, and other input devices."; private readonly List<ControllerRenderProfile> controllerRenderList = new List<ControllerRenderProfile>(); protected override void OnEnable() { base.OnEnable(); mixedRealityControllerMappings = serializedObject.FindProperty("mixedRealityControllerMappings"); thisProfile = target as MixedRealityControllerMappingProfile; } public override void OnInspectorGUI() { if (!RenderProfileHeader(ProfileTitle, ProfileDescription, target, true, BackProfileType.Input)) { return; } using (new GUIEnabledWrapper(!IsProfileLock((BaseMixedRealityProfile)target), false)) { serializedObject.Update(); RenderControllerList(mixedRealityControllerMappings); serializedObject.ApplyModifiedProperties(); } } protected override bool IsProfileInActiveInstance() { var profile = target as BaseMixedRealityProfile; return MixedRealityToolkit.IsInitialized && profile != null && MixedRealityToolkit.Instance.HasActiveProfile && MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile != null && profile == MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.ControllerMappingProfile; } private void RenderControllerList(SerializedProperty controllerList) { if (thisProfile.MixedRealityControllerMappings.Length != controllerList.arraySize) { return; } if (InspectorUIUtility.RenderIndentedButton(ControllerAddButtonContent, EditorStyles.miniButton)) { AddController(controllerList, typeof(GenericJoystickController)); return; } controllerRenderList.Clear(); showControllerDefinitions = EditorGUILayout.Foldout(showControllerDefinitions, "Controller Definitions"); if (showControllerDefinitions) { using (var outerVerticalScope = new GUILayout.VerticalScope()) { GUILayout.HorizontalScope horizontalScope = null; for (int i = 0; i < thisProfile.MixedRealityControllerMappings.Length; i++) { MixedRealityControllerMapping controllerMapping = thisProfile.MixedRealityControllerMappings[i]; Type controllerType = controllerMapping.ControllerType; if (controllerType == null) { continue; } Handedness handedness = controllerMapping.Handedness; bool useCustomInteractionMappings = controllerMapping.HasCustomInteractionMappings; SupportedControllerType supportedControllerType = controllerMapping.SupportedControllerType; var controllerMappingProperty = controllerList.GetArrayElementAtIndex(i); var handednessProperty = controllerMappingProperty.FindPropertyRelative("handedness"); #region Profile Migration // Between MRTK v2 RC2 and GA, the HoloLens clicker and HoloLens voice select input were migrated from // SupportedControllerType.WindowsMixedReality && Handedness.None to SupportedControllerType.GGVHand && Handedness.None if (supportedControllerType == SupportedControllerType.WindowsMixedReality && handedness == Handedness.None) { for (int j = 0; j < thisProfile.MixedRealityControllerMappings.Length; j++) { if (thisProfile.MixedRealityControllerMappings[j].SupportedControllerType == SupportedControllerType.GGVHand && thisProfile.MixedRealityControllerMappings[j].Handedness == Handedness.None) { if (horizontalScope != null) { horizontalScope.Dispose(); horizontalScope = null; } serializedObject.ApplyModifiedProperties(); for (int k = 0; k < controllerMapping.Interactions.Length; k++) { MixedRealityInteractionMapping currentMapping = controllerMapping.Interactions[k]; if (currentMapping.InputType == DeviceInputType.Select) { thisProfile.MixedRealityControllerMappings[j].Interactions[0].MixedRealityInputAction = currentMapping.MixedRealityInputAction; } else if (currentMapping.InputType == DeviceInputType.SpatialGrip) { thisProfile.MixedRealityControllerMappings[j].Interactions[1].MixedRealityInputAction = currentMapping.MixedRealityInputAction; } } serializedObject.Update(); controllerList.DeleteArrayElementAtIndex(i); EditorUtility.DisplayDialog("Mappings updated", "The \"HoloLens Voice and Clicker\" mappings have been migrated to a new serialization. Please save this asset.", "Okay, thanks!"); return; } } } #endregion Profile Migration if (!useCustomInteractionMappings) { bool skip = false; // Merge controllers with the same supported controller type. for (int j = 0; j < controllerRenderList.Count; j++) { if (controllerRenderList[j].SupportedControllerType == supportedControllerType && controllerRenderList[j].Handedness == handedness) { try { thisProfile.MixedRealityControllerMappings[i].SynchronizeInputActions(controllerRenderList[j].Interactions); } catch (ArgumentException e) { Debug.LogError($"Controller mappings between {thisProfile.MixedRealityControllerMappings[i].Description} and {controllerMapping.Description} do not match. Error message: {e.Message}"); } serializedObject.ApplyModifiedProperties(); skip = true; } } if (skip) { continue; } } controllerRenderList.Add(new ControllerRenderProfile(supportedControllerType, handedness, thisProfile.MixedRealityControllerMappings[i].Interactions)); string controllerTitle = thisProfile.MixedRealityControllerMappings[i].Description; var interactionsProperty = controllerMappingProperty.FindPropertyRelative("interactions"); if (useCustomInteractionMappings) { if (horizontalScope != null) { horizontalScope.Dispose(); horizontalScope = null; } GUILayout.Space(24f); using (var verticalScope = new GUILayout.VerticalScope()) { using (horizontalScope = new GUILayout.HorizontalScope()) { EditorGUILayout.LabelField(controllerTitle, EditorStyles.boldLabel); if (GUILayout.Button(ControllerMinusButtonContent, EditorStyles.miniButtonRight, GUILayout.Width(24f))) { controllerList.DeleteArrayElementAtIndex(i); return; } } EditorGUI.BeginChangeCheck(); // Generic Type dropdown Type[] genericTypes = MixedRealityControllerMappingProfile.CustomControllerMappingTypes; var genericTypeListContent = new GUIContent[genericTypes.Length]; var genericTypeListIds = new int[genericTypes.Length]; int currentGenericType = -1; for (int genericTypeIdx = 0; genericTypeIdx < genericTypes.Length; genericTypeIdx++) { var attribute = MixedRealityControllerAttribute.Find(genericTypes[genericTypeIdx]); if (attribute != null) { genericTypeListContent[genericTypeIdx] = new GUIContent(attribute.SupportedControllerType.ToString().Replace("Generic", "").ToProperCase() + " Controller"); } else { genericTypeListContent[genericTypeIdx] = new GUIContent("Unknown Controller"); } genericTypeListIds[genericTypeIdx] = genericTypeIdx; if (controllerType == genericTypes[genericTypeIdx]) { currentGenericType = genericTypeIdx; } } Debug.Assert(currentGenericType != -1); currentGenericType = EditorGUILayout.IntPopup(GenericTypeContent, currentGenericType, genericTypeListContent, genericTypeListIds); controllerType = genericTypes[currentGenericType]; { // Handedness dropdown var attribute = MixedRealityControllerAttribute.Find(controllerType); if (attribute != null && attribute.SupportedHandedness.Length >= 1) { // Make sure handedness is valid for the selected controller type. if (Array.IndexOf(attribute.SupportedHandedness, (Handedness)handednessProperty.intValue) < 0) { handednessProperty.intValue = (int)attribute.SupportedHandedness[0]; } if (attribute.SupportedHandedness.Length >= 2) { var handednessListContent = new GUIContent[attribute.SupportedHandedness.Length]; var handednessListIds = new int[attribute.SupportedHandedness.Length]; for (int handednessIdx = 0; handednessIdx < attribute.SupportedHandedness.Length; handednessIdx++) { handednessListContent[handednessIdx] = new GUIContent(attribute.SupportedHandedness[handednessIdx].ToString()); handednessListIds[handednessIdx] = (int)attribute.SupportedHandedness[handednessIdx]; } handednessProperty.intValue = EditorGUILayout.IntPopup(HandednessTypeContent, handednessProperty.intValue, handednessListContent, handednessListIds); } } else { handednessProperty.intValue = (int)Handedness.None; } } if (EditorGUI.EndChangeCheck()) { interactionsProperty.ClearArray(); serializedObject.ApplyModifiedProperties(); thisProfile.MixedRealityControllerMappings[i].ControllerType.Type = genericTypes[currentGenericType]; thisProfile.MixedRealityControllerMappings[i].SetDefaultInteractionMapping(true); serializedObject.ApplyModifiedProperties(); return; } if (InspectorUIUtility.RenderIndentedButton("Edit Input Action Map")) { ControllerPopupWindow.Show(controllerMapping, interactionsProperty, handedness); } if (InspectorUIUtility.RenderIndentedButton("Reset Input Actions")) { interactionsProperty.ClearArray(); serializedObject.ApplyModifiedProperties(); thisProfile.MixedRealityControllerMappings[i].SetDefaultInteractionMapping(true); serializedObject.ApplyModifiedProperties(); } } } else { if (supportedControllerType == SupportedControllerType.GGVHand && handedness == Handedness.None) { controllerTitle = "HoloLens Voice and Clicker"; } if (handedness != Handedness.Right) { if (horizontalScope != null) { horizontalScope.Dispose(); horizontalScope = null; } horizontalScope = new GUILayout.HorizontalScope(); } var buttonContent = new GUIContent(controllerTitle, ControllerMappingLibrary.GetControllerTextureScaled(controllerType, handedness)); if (GUILayout.Button(buttonContent, MixedRealityStylesUtility.ControllerButtonStyle, GUILayout.Height(128f), GUILayout.MinWidth(32f), GUILayout.ExpandWidth(true))) { ControllerPopupWindow.Show(controllerMapping, interactionsProperty, handedness); } } } if (horizontalScope != null) { horizontalScope.Dispose(); horizontalScope = null; } } } } private void AddController(SerializedProperty controllerList, Type controllerType) { controllerList.InsertArrayElementAtIndex(controllerList.arraySize); var index = controllerList.arraySize - 1; var mixedRealityControllerMapping = controllerList.GetArrayElementAtIndex(index); var handednessProperty = mixedRealityControllerMapping.FindPropertyRelative("handedness"); handednessProperty.intValue = (int)Handedness.None; var interactionsProperty = mixedRealityControllerMapping.FindPropertyRelative("interactions"); interactionsProperty.ClearArray(); serializedObject.ApplyModifiedProperties(); thisProfile.MixedRealityControllerMappings[index].ControllerType.Type = controllerType; thisProfile.MixedRealityControllerMappings[index].SetDefaultInteractionMapping(true); } } }
58.694864
225
0.523574
[ "MIT" ]
ForrestTrepte/azure-remote-rendering
Unity/AzureRemoteRenderingShowcase/arr-showcase-app/Assets/MixedRealityToolkit/Inspectors/Profiles/MixedRealityControllerMappingProfileInspector.cs
19,432
C#
using System.Collections.Generic; using Abp.Configuration; namespace ABPCommerce.Configuration { public class AppSettingProvider : SettingProvider { public override IEnumerable<SettingDefinition> GetSettingDefinitions(SettingDefinitionProviderContext context) { return new[] { new SettingDefinition(AppSettingNames.UiTheme, "red", scopes: SettingScopes.Application | SettingScopes.Tenant | SettingScopes.User, clientVisibilityProvider: new VisibleSettingClientVisibilityProvider()) }; } } }
34.176471
220
0.712565
[ "MIT" ]
eminentasi/abpcommerce
aspnet-core/src/ABPCommerce.Core/Configuration/AppSettingProvider.cs
583
C#
#pragma checksum "C:\Users\gabri\OneDrive\Documentos\GitHub\BlakeChat\BlakeChat\Views\Shared\_ValidationScriptsPartial.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "4b5e5ef4ebf7354cc35c7dacddd6bc3068f19a47" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Shared__ValidationScriptsPartial), @"mvc.1.0.view", @"/Views/Shared/_ValidationScriptsPartial.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "C:\Users\gabri\OneDrive\Documentos\GitHub\BlakeChat\BlakeChat\Views\_ViewImports.cshtml" using BlakeChat; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\gabri\OneDrive\Documentos\GitHub\BlakeChat\BlakeChat\Views\_ViewImports.cshtml" using BlakeChat.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"4b5e5ef4ebf7354cc35c7dacddd6bc3068f19a47", @"/Views/Shared/_ValidationScriptsPartial.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"d498fef41bcffb9a26e2b3d5f298d8371b8efd74", @"/Views/_ViewImports.cshtml")] public class Views_Shared__ValidationScriptsPartial : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/jquery-validation/dist/jquery.validate.min.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4b5e5ef4ebf7354cc35c7dacddd6bc3068f19a473981", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4b5e5ef4ebf7354cc35c7dacddd6bc3068f19a475020", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591
67.656863
406
0.761339
[ "MIT" ]
Glightman/BlakeChat
BlakeChat/obj/Debug/net5.0/Razor/Views/Shared/_ValidationScriptsPartial.cshtml.g.cs
6,901
C#
#pragma warning disable RECS0018 using System; using UnityEngine; using System.Collections.Generic; using System.IO; using System.Reflection; using Newtonsoft.Json; using System.Collections; using AttachPoint = tk2dSpriteDefinition.AttachPoint; using YamlDotNet; using YamlDotNet.Serialization; public static partial class ETGMod { /// <summary> /// ETGMod asset management. /// </summary> public static partial class Assets { private readonly static Protocol[] _Protocols = { new ItemProtocol() }; public readonly static Type t_Object = typeof(UnityEngine.Object); public readonly static Type t_AssetDirectory = typeof(AssetDirectory); public readonly static Type t_Texture = typeof(Texture); public readonly static Type t_Texture2D = typeof(Texture2D); public readonly static Type t_tk2dSpriteCollectionData = typeof(tk2dSpriteCollectionData); public readonly static Type t_tk2dSpriteDefinition = typeof(tk2dSpriteDefinition); private readonly static FieldInfo f_tk2dSpriteCollectionData_spriteNameLookupDict = typeof(tk2dSpriteCollectionData).GetField("spriteNameLookupDict", BindingFlags.Instance | BindingFlags.NonPublic); /// <summary> /// Asset map. All string - AssetMetadata entries here will cause an asset to be remapped. Use ETGMod.Assets.AddMapping to add an entry. /// </summary> public readonly static Dictionary<string, AssetMetadata> Map = new Dictionary<string, AssetMetadata>(); /// <summary> /// Directories that would not fit into Map due to conflicts. /// </summary> public readonly static Dictionary<string, AssetMetadata> MapDirs = new Dictionary<string, AssetMetadata>(); /// <summary> /// Texture remappings. This dictionary starts empty and will be filled as sprites get replaced. Feel free to add your own remapping here. /// </summary> public readonly static Dictionary<string, Texture2D> TextureMap = new Dictionary<string, Texture2D>(); public static bool DumpResources = false; public static bool DumpSprites = false; public static bool DumpSpritesMetadata = false; private readonly static Vector2[] _DefaultUVs = { new Vector2(0f, 0f), new Vector2(1f, 0f), new Vector2(0f, 1f), new Vector2(1f, 1f) }; public static Shader DefaultSpriteShader; public static RuntimeAtlasPacker Packer = new RuntimeAtlasPacker(); public static Deserializer Deserializer = new DeserializerBuilder().Build(); public static Serializer Serializer = new SerializerBuilder().Build(); public static Vector2[] GenerateUVs(Texture2D texture, int x, int y, int width, int height) { return new Vector2[] { new Vector2((x ) / (float) texture.width, (y ) / (float) texture.height), new Vector2((x + width) / (float) texture.width, (y ) / (float) texture.height), new Vector2((x ) / (float) texture.width, (y + height) / (float) texture.height), new Vector2((x + width) / (float) texture.width, (y + height) / (float) texture.height), }; } public static bool TryGetMapped(string path, out AssetMetadata metadata, bool includeDirs = false) { if (includeDirs) { if (MapDirs.TryGetValue(path, out metadata)) { return true; } if (MapDirs.TryGetValue(path.ToLowerInvariant(), out metadata)) { return true; } } if (Map.TryGetValue(path, out metadata)) { return true; } if (Map.TryGetValue(path.ToLowerInvariant(), out metadata)) { return true; } return false; } public static AssetMetadata GetMapped(string path) { AssetMetadata metadata; TryGetMapped(path, out metadata); return metadata; } public static AssetMetadata AddMapping(string path, AssetMetadata metadata) { path = path.Replace('\\', '/'); if (metadata.AssetType == null) { path = RemoveExtension(path, out metadata.AssetType); } if (metadata.AssetType == t_AssetDirectory) { return MapDirs[path] = metadata; } return Map[path] = metadata; } public static string RemoveExtension(string file, out Type type) { type = t_Object; if (file.EndsWithInvariant(".png")) { type = t_Texture2D; file = file.Substring(0, file.Length - 4); } return file; } public static void Crawl(string dir, string root = null) { if (Path.GetDirectoryName(dir).StartsWithInvariant("DUMP")) return; if (root == null) root = dir; string[] files = Directory.GetFiles(dir); for (int i = 0; i < files.Length; i++) { string file = files[i]; if (file.EndsWithInvariant("animation.yml")) { var texture = Resources.Load<Texture2D>("sprites/test"); Console.WriteLine("TEXTURE " + texture.ToString()); var tk2d_collection = new tk2dSpriteCollectionData { assetName = "test", spriteCollectionName = "test", spriteCollectionGUID = "12834012341324" }; var material = new Material(DefaultSpriteShader); var tk2d_spritedef = new tk2dSpriteDefinition { normals = new Vector3[] { new Vector3(0.0f, 0.0f, -1.0f), new Vector3(0.0f, 0.0f, -1.0f), new Vector3(0.0f, 0.0f, -1.0f), new Vector3(0.0f, 0.0f, -1.0f), }, tangents = new Vector4[] { new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), new Vector4(1.0f, 0.0f, 0.0f, 1.0f), }, indices = new int[] { 0, 3, 1, 2, 3, 0 }, texelSize = new Vector2(0.1f, 0.1f), extractRegion = false, regionX = 0, regionY = 0, regionW = 0, regionH = 0, flipped = tk2dSpriteDefinition.FlipMode.None, complexGeometry = false, physicsEngine = tk2dSpriteDefinition.PhysicsEngine.Physics3D, colliderType = tk2dSpriteDefinition.ColliderType.Box, collisionLayer = CollisionLayer.PlayerHitBox, position0 = new Vector3(0.1f, 0.0f), position1 = new Vector3(0.8f, 0.0f), position2 = new Vector3(0.1f, 0.5f), position3 = new Vector3(0.8f, 0.5f), material = material, materialInst = material, materialId = 0, }; tk2d_spritedef.uvs = GenerateUVs(texture, 0, 0, 32, 32); tk2d_collection.textures = new Texture[] { texture }; tk2d_collection.textureInsts = new Texture2D[] { texture }; material.mainTexture = texture; tk2d_collection.spriteDefinitions = new tk2dSpriteDefinition[] { tk2d_spritedef }; tk2d_collection.material = material; tk2d_collection.materials = new Material[] {material}; tk2d_collection.materialInsts = tk2d_collection.materials; Console.WriteLine("MY COLLECTION"); Console.WriteLine(ObjectDumper.Dump(tk2d_collection)); } //if (file.RemovePrefix(dir + Path.DirectorySeparatorChar) == "animation.yml") { // var reader = new StreamReader(file); // Console.WriteLine("DESERIALIZING " + file); // var anim = Deserializer.Deserialize<YAML.Animation>(reader); // Console.WriteLine("CREATE ANIMATION"); // var animation = new tk2dSpriteAnimation(); // var tk2d_data = new tk2dSpriteCollectionData { // name = anim.Name, // spriteCollectionName = anim.Name, // assetName = anim.Name, // }; // var tk2d_collection = new tk2dSpriteCollection { // name = anim.Name, // assetName = anim.Name, // spriteCollection = tk2d_data // }; // Console.WriteLine("CREATE CLIPS"); // var tk2d_clips = new List<tk2dSpriteAnimationClip>(); // foreach (var clip in anim.Clips) { // var tk2d_clip = new tk2dSpriteAnimationClip { // name = clip.Key, // fps = clip.Value.FPS, // wrapMode = clip.Value.WrapMode, // loopStart = 0, // }; // var tk2d_frames = new List<tk2dSpriteAnimationFrame>(); // foreach (var frame in clip.Value.Frames) { // tk2d_data.textureInsts // var tk2d_frame = new tk2dSpriteAnimationFrame { // spriteCollection = tk2d_data, // } // } // tk2d_clips.Add(tk2d_clip); // } // Console.WriteLine("CREATE ANIMATOR"); // var animator = new tk2dSpriteAnimator { // name = anim.Name, // ClipFps = anim.FPS, // DefaultClipId = 0, // }; // foreach (var clip in anim.Clips) { // Console.WriteLine("CLIP " + clip.Key + ":"); // foreach (var frame in clip.Value) { // Console.WriteLine("FRAME " + frame); // } // } // Console.WriteLine("SERIALIZING " + anim); // Console.WriteLine(Serializer.Serialize(anim)); //} AddMapping(file.RemovePrefix(root).Substring(1), new AssetMetadata(file)); } files = Directory.GetDirectories(dir); for (int i = 0; i < files.Length; i++) { string file = files[i]; AddMapping(file.RemovePrefix(root).Substring(1), new AssetMetadata(file) { AssetType = t_AssetDirectory }); Crawl(file, root); } } public static void Crawl(Assembly asm) { string[] resourceNames = asm.GetManifestResourceNames(); for (int i = 0; i < resourceNames.Length; i++) { string name = resourceNames[i]; int indexOfContent = name.IndexOfInvariant("Content"); if (indexOfContent < 0) { continue; } name = name.Substring(indexOfContent + 8); AddMapping(name, new AssetMetadata(asm, resourceNames[i])); } } public static void HookUnity() { if (!Directory.Exists(ResourcesDirectory)) { Debug.Log("Resources directory not existing, creating..."); Directory.CreateDirectory(ResourcesDirectory); } string spritesDir = Path.Combine(ResourcesDirectory, "sprites"); if (!Directory.Exists(spritesDir)) { Debug.Log("Sprites directory not existing, creating..."); Directory.CreateDirectory(spritesDir); } ETGModUnityEngineHooks.Load = Load; // ETGModUnityEngineHooks.LoadAsync = LoadAsync; // ETGModUnityEngineHooks.LoadAll = LoadAll; // ETGModUnityEngineHooks.UnloadAsset = UnloadAsset; DefaultSpriteShader = Shader.Find("tk2d/BlendVertexColor"); } public static UnityEngine.Object Load(string path, Type type) { if (path == "PlayerCoopCultist" && Player.CoopReplacement != null) { path = Player.CoopReplacement; } else if (path.StartsWithInvariant("Player") && Player.PlayerReplacement != null) { path = Player.PlayerReplacement; } UnityEngine.Object customobj = null; for (int i = 0; i < _Protocols.Length; i++) { var protocol = _Protocols[i]; customobj = protocol.Get(path); if (customobj != null) return customobj; } #if DEBUG if (DumpResources) { Dump.DumpResource(path); } #endif AssetMetadata metadata; bool isJson = false; bool isPatch = false; if (TryGetMapped(path, out metadata, true)) { } else if (TryGetMapped(path + ".json", out metadata)) { isJson = true; } else if (TryGetMapped(path + ".patch.json", out metadata)) { isPatch = true; isJson = true; } if (metadata != null) { if (isJson) { if (isPatch) { UnityEngine.Object obj = Resources.Load(path + ETGModUnityEngineHooks.SkipSuffix); using (JsonHelperReader json = JSONHelper.OpenReadJSON(metadata.Stream)) { json.Read(); // Go to start; return (UnityEngine.Object) json.FillObject(obj); } } return (UnityEngine.Object) JSONHelper.ReadJSON(metadata.Stream); } if (t_tk2dSpriteCollectionData == type) { AssetMetadata json = GetMapped(path + ".json"); if (metadata.AssetType == t_Texture2D && json != null) { // Atlas string[] names; Rect[] regions; Vector2[] anchors; AttachPoint[][] attachPoints; AssetSpriteData.ToTK2D(JSONHelper.ReadJSON<List<AssetSpriteData>>(json.Stream), out names, out regions, out anchors, out attachPoints); tk2dSpriteCollectionData sprites = tk2dSpriteCollectionData.CreateFromTexture( Resources.Load<Texture2D>(path), tk2dSpriteCollectionSize.Default(), names, regions, anchors ); for (int i = 0; i < attachPoints.Length; i++) { sprites.SetAttachPoints(i, attachPoints[i]); } return sprites; } if (metadata.AssetType == t_AssetDirectory) { // Separate textures // TODO create collection from "children" assets tk2dSpriteCollectionData data = new GameObject(path.StartsWithInvariant("sprites/") ? path.Substring(8) : path).AddComponent<tk2dSpriteCollectionData>(); tk2dSpriteCollectionSize size = tk2dSpriteCollectionSize.Default(); data.spriteCollectionName = data.name; data.Transient = true; data.version = 3; data.invOrthoSize = 1f / size.OrthoSize; data.halfTargetHeight = size.TargetHeight * 0.5f; data.premultipliedAlpha = false; data.material = new Material(DefaultSpriteShader); data.materials = new Material[] { data.material }; data.buildKey = UnityEngine.Random.Range(0, int.MaxValue); data.Handle(); data.textures = new Texture2D[data.spriteDefinitions.Length]; for (int i = 0; i < data.spriteDefinitions.Length; i++) { data.textures[i] = data.spriteDefinitions[i].materialInst.mainTexture; } return data; } } if (t_Texture.IsAssignableFrom(type) || type == t_Texture2D || (type == t_Object && metadata.AssetType == t_Texture2D)) { Texture2D tex = new Texture2D(2, 2); tex.name = path; tex.LoadImage(metadata.Data); tex.filterMode = FilterMode.Point; return tex; } } UnityEngine.Object orig = Resources.Load(path + ETGModUnityEngineHooks.SkipSuffix, type); if (orig is GameObject) { Objects.HandleGameObject((GameObject) orig); } return orig; } public static void HandleSprites(tk2dSpriteCollectionData sprites) { if (sprites == null) { return; } string path = "sprites/" + sprites.spriteCollectionName; Texture2D replacement; AssetMetadata metadata; Texture mainTexture = sprites.materials?.Length != 0 ? sprites.materials[0]?.mainTexture : null; string atlasName = mainTexture?.name; if (mainTexture != null && (atlasName == null || atlasName.Length == 0 || atlasName[0] != '~')) { if (TextureMap.TryGetValue(path, out replacement)) { } else if (TryGetMapped (path, out metadata)) { TextureMap[path] = replacement = Resources.Load<Texture2D>(path); } else { foreach (KeyValuePair<string, AssetMetadata> mapping in Map) { if (!mapping.Value.HasData) continue; string resourcePath = mapping.Key; if (!resourcePath.StartsWithInvariant("sprites/@")) continue; string spriteName = resourcePath.Substring(9); if (sprites.spriteCollectionName.Contains(spriteName)) { string copyPath = Path.Combine(ResourcesDirectory, ("DUMP" + path).Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar) + ".png"); if (mapping.Value.Container == AssetMetadata.ContainerType.Filesystem && !File.Exists(copyPath)) { Directory.GetParent(copyPath).Create(); File.Copy(mapping.Value.File, copyPath); } TextureMap[path] = replacement = Resources.Load<Texture2D>(resourcePath); break; } } } if (replacement != null) { // Full atlas texture replacement. replacement.name = '~' + atlasName; for (int i = 0; i < sprites.materials.Length; i++) { if (sprites.materials[i]?.mainTexture == null) continue; sprites.materials[i].mainTexture = replacement; } } } if (DumpSprites) { Dump.DumpSpriteCollection(sprites); } if (DumpSpritesMetadata) { Dump.DumpSpriteCollectionMetadata(sprites); } List<tk2dSpriteDefinition> list = null; foreach (KeyValuePair<string, AssetMetadata> mapping in Map) { string assetPath = mapping.Key; if (assetPath.Length <= path.Length + 1) { continue; } if (!assetPath.StartsWithInvariant(path) || mapping.Value.AssetType != t_Texture2D) { continue; } string name = assetPath.Substring(path.Length + 1); tk2dSpriteDefinition frame = sprites.GetSpriteDefinition(name); if (frame != null && frame.materialInst != null) { Texture2D origTex = (Texture2D) frame.materialInst.mainTexture; if (Packer.IsPageTexture(origTex)) { continue; } } if (!TextureMap.TryGetValue(assetPath, out replacement)) replacement = TextureMap[assetPath] = Resources.Load<Texture2D>(assetPath); if (replacement == null) { continue; } if (frame == null && name[0] == '@') { name = name.Substring(1); for (int i = 0; i < sprites.spriteDefinitions.Length; i++) { tk2dSpriteDefinition frame_ = sprites.spriteDefinitions[i]; if (frame_.Valid && frame_.name.Contains(name)) { frame = frame_; name = frame_.name; break; } } if (frame == null) { continue; } } if (frame != null) { // Replace old sprite. frame.ReplaceTexture(replacement); } else { // Add new sprite. if (list == null) { list = new List<tk2dSpriteDefinition>(sprites.spriteDefinitions?.Length ?? 32); if (sprites.spriteDefinitions != null) { list.AddRange(sprites.spriteDefinitions); } } frame = new tk2dSpriteDefinition(); frame.name = name; frame.material = sprites.materials[0]; frame.ReplaceTexture(replacement); AssetSpriteData frameData = new AssetSpriteData(); AssetMetadata jsonMetadata = GetMapped(assetPath + ".json"); if (jsonMetadata != null) { frameData = JSONHelper.ReadJSON<AssetSpriteData>(jsonMetadata.Stream); } frame.normals = new Vector3[0]; frame.tangents = new Vector4[0]; frame.indices = new int[] { 0, 3, 1, 2, 3, 0 }; // TODO figure out this black magic const float pixelScale = 0.0625f; float w = replacement.width * pixelScale; float h = replacement.height * pixelScale; frame.position0 = new Vector3(0f, 0f, 0f); frame.position1 = new Vector3(w, 0f, 0f); frame.position2 = new Vector3(0f, h, 0f); frame.position3 = new Vector3(w, h, 0f); frame.boundsDataCenter = frame.untrimmedBoundsDataCenter = new Vector3(w / 2f, h / 2f, 0f); frame.boundsDataExtents = frame.untrimmedBoundsDataExtents = new Vector3(w, h, 0f); sprites.SetAttachPoints(list.Count, frameData.attachPoints); list.Add(frame); } } if (list != null) { sprites.spriteDefinitions = list.ToArray(); ReflectionHelper.SetValue(f_tk2dSpriteCollectionData_spriteNameLookupDict, sprites, null); } if (sprites.hasPlatformData) { sprites.inst.Handle(); } } public static void HandleDfAtlas(dfAtlas atlas) { if (atlas == null) { return; } string path = "sprites/DFGUI/" + atlas.name; Texture2D replacement; AssetMetadata metadata; Texture mainTexture = atlas.Material.mainTexture; string atlasName = mainTexture?.name; if (mainTexture != null && (atlasName == null || atlasName.Length == 0 || atlasName[0] != '~')) { if (TextureMap.TryGetValue(path, out replacement)) { } else if (TryGetMapped(path, out metadata)) { TextureMap[path] = replacement = Resources.Load<Texture2D>(path); } else { foreach (KeyValuePair<string, AssetMetadata> mapping in Map) { if (!mapping.Value.HasData) continue; string resourcePath = mapping.Key; if (!resourcePath.StartsWithInvariant("sprites/DFGUI/@")) continue; string spriteName = resourcePath.Substring(9); if (atlas.name.Contains(spriteName)) { string copyPath = Path.Combine(ResourcesDirectory, ("DUMP" + path).Replace('/', Path.DirectorySeparatorChar).Replace('\\', Path.DirectorySeparatorChar) + ".png"); if (mapping.Value.Container == AssetMetadata.ContainerType.Filesystem && !File.Exists(copyPath)) { Directory.GetParent(copyPath).Create(); File.Copy(mapping.Value.File, copyPath); } TextureMap[path] = replacement = Resources.Load<Texture2D>(resourcePath); break; } } } if (replacement != null) { // Full atlas texture replacement. replacement.name = '~' + atlasName; atlas.Material.mainTexture = replacement; } } /* if (DumpSprites) { Dump.DumpSpriteCollection(sprites); } if (DumpSpritesMetadata) { Dump.DumpSpriteCollectionMetadata(sprites); } */ // TODO items in dfAtlas! if (atlas.Replacement != null) HandleDfAtlas(atlas.Replacement); } public static void ReplaceTexture(tk2dSpriteDefinition frame, Texture2D replacement, bool pack = true) { frame.flipped = tk2dSpriteDefinition.FlipMode.None; frame.materialInst = new Material(frame.material); frame.texelSize = replacement.texelSize; frame.extractRegion = pack; if (pack) { RuntimeAtlasSegment segment = Packer.Pack(replacement); frame.materialInst.mainTexture = segment.texture; frame.uvs = segment.uvs; } else { frame.materialInst.mainTexture = replacement; frame.uvs = _DefaultUVs; } } } public static void Handle(this tk2dBaseSprite sprite) { Assets.HandleSprites(sprite.Collection); } public static void HandleAuto(this tk2dBaseSprite sprite) { _HandleAuto(sprite.Handle); } public static void Handle(this tk2dSpriteCollectionData sprites) { Assets.HandleSprites(sprites); } public static void Handle(this dfAtlas atlas) { Assets.HandleDfAtlas(atlas); } public static void HandleAuto(this dfAtlas atlas) { _HandleAuto(atlas.Handle); } public static void MapAssets(this Assembly asm) { Assets.Crawl(asm); } public static void ReplaceTexture(this tk2dSpriteDefinition frame, Texture2D replacement, bool pack = true) { Assets.ReplaceTexture(frame, replacement, pack); } }
44.826709
190
0.512413
[ "MIT" ]
Gl0rfindel/ETGMod
Assembly-CSharp.Base.mm/src/Core/Assets/Assets.cs
28,198
C#
 using System; namespace ConsoleUtils.ConsoleActions { public class AutoCompleteRestOfLineAction : IConsoleAction { public void Execute(IConsole console, ConsoleKeyInfo consoleKeyInfo) { if (!console.PreviousLineBuffer.HasLines) return; var previous = console.PreviousLineBuffer.LineAtIndex; if (previous.Length <= console.CursorPosition) return; var partToUse = previous.Remove(0, console.CursorPosition); var newLine = console.CurrentLine.Remove(console.CursorPosition, Math.Min(console.CurrentLine.Length - console.CursorPosition, partToUse.Length)); console.CurrentLine = newLine.Insert(console.CursorPosition, partToUse); console.CursorPosition = console.CursorPosition + partToUse.Length; } } }
38.826087
98
0.647256
[ "MIT" ]
jncronin/tysila
tysila4/ConsoleUtils/ConsoleActions/AutoCompleteRestOfLineAction.cs
895
C#
using Alex.Worlds; using ConcreteMC.MolangSharp.Attributes; namespace Alex.Entities.Hostile { public class EnderDragon : HostileMob { [MoProperty("wing_flap_position")] public double WingFlapPosition { get; set; } = 0d; public EnderDragon(World level) : base(level) { Height = 8; Width = 16; } /// <inheritdoc /> public override void EntityDied() { base.EntityDied(); Alex.Instance.AudioEngine.PlaySound("mob.enderdragon.death", RenderLocation, 1f, 1f); } /// <inheritdoc /> public override void EntityHurt() { base.EntityHurt(); Alex.Instance.AudioEngine.PlaySound("mob.enderdragon.hit", RenderLocation, 1f, 1f); } } }
22.266667
88
0.696108
[ "MPL-2.0" ]
ConcreteMC/Alex
src/Alex/Entities/Hostile/EnderDragon.cs
668
C#
using System; namespace Patterns.EventSourcing.Interface { [Serializable] public class TimestampedValue<TValue> { public TimestampedValue(TValue value, DateTime timestamp) { Timestamp = timestamp; Value = value; } public DateTime Timestamp { get; set; } public TValue Value { get; set; } public override string ToString() => $"[At {Timestamp.ToString("O")}] : {Value}"; } }
24.473684
89
0.597849
[ "MIT" ]
amccool/orleans-architecture-patterns-code
Patterns.EventSourcing/Interface/TimestampedValue.cs
467
C#
using System; using System.Runtime.InteropServices; using ExileCore; using ExileCore.PoEMemory.Components; using ExileCore.PoEMemory.MemoryObjects; using ExileCore.Shared.Cache; using SharpDX; using SharpDX.Direct3D11; using SharpDX.DXGI; using Map=ExileCore.PoEMemory.Elements.Map; namespace Terrain { internal class TerrainCore : BaseSettingsPlugin<TerrainSettings> { private CachedValue<float> _diag; private IngameUIElements _ingameStateIngameUi; private float _k; private bool _largeMap; private CachedValue<RectangleF> _mapRect; private int _numRows, _numCols; private float _scale; private Vector2 _screenCenterCache; private int[] _bitmap; private GCHandle _bitmapHandle; private bool _enabled = true; public TerrainCore() { Name = "Terrain"; } private RectangleF MapRect => _mapRect?.Value ?? (_mapRect = new TimeCache<RectangleF>(() => MapWindow.GetClientRect(), 100)) .Value; private Map MapWindow => GameController.Game.IngameState.IngameUi.Map; private Camera Camera => GameController.Game.IngameState.Camera; private float Diag => _diag?.Value ?? (_diag = new TimeCache<float>(() => { if (_ingameStateIngameUi.Map.SmallMiniMap.IsVisibleLocal) { var mapRect = _ingameStateIngameUi.Map.SmallMiniMap.GetClientRect(); return (float) (Math.Sqrt(mapRect.Width * mapRect.Width + mapRect.Height * mapRect.Height) / 2f); } return (float) Math.Sqrt(Camera.Width * Camera.Width + Camera.Height * Camera.Height); }, 100)).Value; private Vector2 ScreenCenter => new Vector2(MapRect.Width / 2, MapRect.Height / 2 - 20) + new Vector2(MapRect.X, MapRect.Y) + new Vector2(MapWindow.LargeMapShiftX, MapWindow.LargeMapShiftY); public override void AreaChange(AreaInstance area) { if (!Settings.Enable) return; var terrain = GameController.IngameState.Data.Terrain; var terrainBytes = GameController.Memory.ReadBytes(terrain.LayerMelee.First, terrain.LayerMelee.Size); _numCols = (int) terrain.NumCols * 23; _numRows = (int) terrain.NumRows * 23; if ((_numCols & 1) > 0) _numCols++; _bitmap = new int[_numCols * _numRows]; int k = 0; int dataIndex = 0; var color = Settings.TerrainColor.Value.ToRgba(); for (int i = 0; i < _numRows; i++) { for (int j = 0; j < _numCols; j += 2) { var b = terrainBytes[dataIndex + (j >> 1)]; _bitmap[k++] = (b >> 4) > 0 ? color : 0; _bitmap[k++] = (b & 0xf) > 0 ? color : 0; } dataIndex += terrain.BytesPerRow; } if (_bitmapHandle.IsAllocated) _bitmapHandle.Free(); _bitmapHandle = GCHandle.Alloc(_bitmap, GCHandleType.Pinned); var texture = new Texture2D(Graphics.LowLevel.D11Device, new Texture2DDescription { ArraySize = 1, Height = _numRows, Width = _numCols, Format = Format.R8G8B8A8_UNorm, BindFlags = BindFlags.ShaderResource, Usage = ResourceUsage.Default, MipLevels = 1, CpuAccessFlags = CpuAccessFlags.Write, SampleDescription = new SampleDescription(1, 0) }, new[] {new DataBox(_bitmapHandle.AddrOfPinnedObject(), sizeof(int)*_numCols, 0)}); var srv = new ShaderResourceView(Graphics.LowLevel.D11Device, texture); Graphics.LowLevel.AddOrUpdateTexture("terrain", srv); } public override bool Initialise() { Input.RegisterKey(Settings.HotKey.Value); Settings.HotKey.OnValueChanged += () => { Input.RegisterKey(Settings.HotKey.Value); }; return base.Initialise(); } public override Job Tick() { TickLogic(); return null; } private void TickLogic() { try { _ingameStateIngameUi = GameController.Game.IngameState.IngameUi; if (_ingameStateIngameUi.Map.SmallMiniMap.IsVisibleLocal) { var mapRect = _ingameStateIngameUi.Map.SmallMiniMap.GetClientRectCache; _screenCenterCache = new Vector2(mapRect.X + mapRect.Width / 2, mapRect.Y + mapRect.Height / 2); _largeMap = false; } else if (_ingameStateIngameUi.Map.LargeMap.IsVisibleLocal) { _screenCenterCache = ScreenCenter; _largeMap = true; } _k = Camera.Width < 1024f ? 1120f : 1024f; _scale = _k / Camera.Height * Camera.Width * 3f / 4f / MapWindow.LargeMapZoom; } catch (Exception e) { DebugWindow.LogError($"Terrain.TickLogic: {e.Message}"); } } public override void Render() { if (Settings.HotKey.PressedOnce()) { _enabled = !_enabled; } if (!_enabled || !Settings.Enable || !_largeMap || _ingameStateIngameUi.AtlasPanel.IsVisibleLocal || _ingameStateIngameUi.DelveWindow.IsVisibleLocal || _ingameStateIngameUi.TreePanel.IsVisibleLocal) return; var playerPos = GameController.Player.GetComponent<Positioned>().GridPos; var posZ = GameController.Player.GetComponent<Render>().Pos.Z; var mapWindowLargeMapZoom = MapWindow.LargeMapZoom; Vector2 Transform(Vector2 p) => _screenCenterCache + DeltaInWorldToMinimapDelta(p - playerPos, Diag, _scale, -posZ / (9f / mapWindowLargeMapZoom)); Graphics.DrawTexture(Graphics.LowLevel.GetTexture("terrain").NativePointer, Transform(new Vector2(0, 0)), Transform(new Vector2(_numCols, 0)), Transform(new Vector2(_numCols, _numRows)), Transform(new Vector2(0, _numRows)) ); } public Vector2 DeltaInWorldToMinimapDelta(Vector2 delta, double diag, float scale, float deltaZ = 0) { var CAMERA_ANGLE = 38 * MathUtil.Pi / 180; // Values according to 40 degree rotation of cartesian coordiantes, still doesn't seem right but closer var cos = (float) (diag * Math.Cos(CAMERA_ANGLE) / scale); var sin = (float) (diag * Math.Sin(CAMERA_ANGLE) / scale); // possible to use cos so angle = nearly 45 degrees // 2D rotation formulas not correct, but it's what appears to work? return new Vector2((delta.X - delta.Y) * cos, deltaZ - (delta.X + delta.Y) * sin); } } }
32.415301
150
0.691504
[ "Apache-2.0" ]
Rebrandsoft/Guard-Terrain
src/TerrainCore.cs
5,934
C#
using System; using System.Reflection; using System.Windows; using System.Windows.Media; using System.Windows.Media.Effects; namespace CairoDesktop.Common { /// <summary> /// Provides a custom message dialog for the Cairo Desktop. /// </summary> public partial class CairoMessage : Window { public delegate void DialogResultDelegate(bool? result); private static DependencyProperty buttonsProperty = DependencyProperty.Register("Buttons", typeof(MessageBoxButton), typeof(CairoMessage)); private static DependencyProperty imageProperty = DependencyProperty.Register("Image", typeof(CairoMessageImage), typeof(CairoMessage)); private static DependencyProperty messageProperty = DependencyProperty.Register("Message", typeof(string), typeof(CairoMessage)); /// <summary> /// Initializes a new instance of the CairoMessage class. /// </summary> public CairoMessage() { InitializeComponent(); } #region Public Properties /// <summary> /// Gets or sets the content of the message. /// </summary> /// <value>The contents of the message.</value> public string Message { get { return (string)GetValue(messageProperty); } set { SetValue(messageProperty, value); } } /// <summary> /// Gets or sets the type of image to display in the dialog. /// </summary> /// <value>The type of image to display.</value> public CairoMessageImage Image { get { return (CairoMessageImage)GetValue(imageProperty); } set { SetValue(imageProperty, value); } } /// <summary> /// Gets or sets the type of buttons to display. /// </summary> /// <value>The button combination to use.</value> public MessageBoxButton Buttons { get { return (MessageBoxButton)GetValue(buttonsProperty); } set { SetValue(buttonsProperty, value); } } public DialogResultDelegate ResultCallback; #endregion #region Static Methods /// <summary> /// Displays the Cairo Message as an alert with implicit settings. /// </summary> /// <param name="message">The message to display.</param> /// <param name="title">The title of the dialog.</param> /// <param name="image">The image to display.</param> /// <returns>void</returns> [STAThread] public static void Show(string message, string title, CairoMessageImage image) { Show(message, title, MessageBoxButton.OK, image, null); } /// <summary> /// Displays the Cairo Message Dialog with implicit settings. /// </summary> /// <param name="message">The message to display.</param> /// <param name="title">The title of the dialog.</param> /// <param name="buttons">The buttons configuration to use.</param> /// <param name="image">The image to display.</param> /// <returns>void</returns> public static void Show(string message, string title, MessageBoxButton buttons, CairoMessageImage image) { Show(message, title, buttons, image, null); } /// <summary> /// Displays the Cairo Message Dialog with implicit settings. /// </summary> /// <param name="message">The message to display.</param> /// <param name="title">The title of the dialog.</param> /// <param name="buttons">The buttons configuration to use.</param> /// <param name="image">The image to display.</param> /// <param name="resultCallback">The delegate to execute upon user action.</param> /// <returns>void</returns> public static void Show(string message, string title, MessageBoxButton buttons, CairoMessageImage image, DialogResultDelegate resultCallback) { CairoMessage msgDialog = new CairoMessage { Message = message, Title = title, Image = image, Buttons = buttons, ResultCallback = resultCallback }; msgDialog.Show(); } /// <summary> /// Displays the Cairo Message as an alert with implicit settings. /// </summary> /// <param name="message">The message to display.</param> /// <param name="title">The title of the dialog.</param> /// <param name="imageSource">The image source to display.</param> /// <param name="useShadow">Enable a drop shadow if the image may blend with the background.</param> /// <returns>void</returns> [STAThread] public static void Show(string message, string title, ImageSource imageSource, bool useShadow) { CairoMessage msgDialog = new CairoMessage { Message = message, Title = title, Buttons = MessageBoxButton.OK }; msgDialog.MessageIconImage.Source = imageSource; if (useShadow) { msgDialog.MessageIconImage.Effect = new DropShadowEffect { Color = Colors.Black, Direction = 270, ShadowDepth = 2, BlurRadius = 10, Opacity = 0.5 }; } msgDialog.Show(); } /// <summary> /// Displays the Cairo Message Dialog with OK/Cancel buttons, implicit settings, custom image and button text. /// </summary> /// <param name="message">The message to display.</param> /// <param name="title">The title of the dialog.</param> /// <param name="image">The path to the image for the dialog.</param> /// <param name="OkButtonText">The text for the OK button.</param> /// <param name="CancelButtonText">The text for the cancel button.</param> /// <param name="resultCallback">The delegate to execute upon user action.</param> /// <returns>void</returns> public static void ShowOkCancel(string message, string title, CairoMessageImage image, string OkButtonText, string CancelButtonText, DialogResultDelegate resultCallback) { if (string.IsNullOrEmpty(CancelButtonText)) { CancelButtonText = Localization.DisplayString.sInterface_Cancel; } if(string.IsNullOrEmpty(OkButtonText)) { OkButtonText = Localization.DisplayString.sInterface_OK; } CairoMessage msgDialog = new CairoMessage(); msgDialog.Message = message; msgDialog.Title = title; msgDialog.Buttons = MessageBoxButton.OKCancel; msgDialog.Image = image; msgDialog.ResultCallback = resultCallback; msgDialog.OkButton.Content = OkButtonText; msgDialog.CancelButton.Content = CancelButtonText; msgDialog.Show(); } #endregion private bool IsModal() { return (bool)typeof(Window).GetField("_showingAsDialog", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(this); } private void OkButton_Click(object sender, RoutedEventArgs e) { if (IsModal()) DialogResult = true; else Close(); ResultCallback?.Invoke(true); } private void NoButton_Click(object sender, RoutedEventArgs e) { if (IsModal()) DialogResult = false; else Close(); ResultCallback?.Invoke(false); } private void messageWindow_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { DragMove(); } } }
35.354701
177
0.566179
[ "Apache-2.0" ]
curoviyxru/cairoshell
Cairo Desktop/CairoDesktop.Common/CairoMessage.xaml.cs
8,275
C#
using System; using System.Linq; namespace Microsoft.Azure.Devices.Applications.RemoteMonitoring.Common.Extensions { static public class StringExtension { /// <summary> /// Try to remove prefix from input string /// </summary> /// <param name="s">The raw string</param> /// <param name="prefix">The target prefix string</param> /// <param name="result">The prefix-removed string (or the raw string if target prefix was not found)</param> /// <returns>True if the target prefix was found</returns> static public bool TryTrimPrefix(this string s, string prefix, out string result) { if (s.StartsWith(prefix, StringComparison.Ordinal)) { result = s.Substring(prefix.Length); return true; } else { result = s; return false; } } /// <summary> /// Try to remove prefix from input string /// </summary> /// <param name="s">The raw string</param> /// <param name="prefix">The target prefix string</param> /// <returns>prefix-removed string (or the raw string if target prefix was not found)</returns> static public string TryTrimPrefix(this string s, string prefix) { string result; s.TryTrimPrefix(prefix, out result); return result; } /// <summary> /// The following charactors are not allowed for PartitionKey /// and RowKey property of Storage Table: /// The forward slash (/) character /// The backslash (\) character /// The number sign (#) character /// The question mark (?) character /// Control characters U+0000 ~ U+001F, U+007F ~ U+009F /// The key length must be less than 1024 /// We also add a constraint to not using pure white space /// string since it is useless here. /// </summary> /// <param name="key"></param> /// <returns>true if it is a correct key</returns> static public bool IsAllowedTableKey(this string key) { char[] speicialChars = @"#?/\".ToCharArray(); if (string.IsNullOrWhiteSpace(key) || key.Length > 1024 || key.IndexOfAny(speicialChars) > -1 || key.ToCharArray().Any(c => c < 0X1F || c > 0X7F && c < 0X9F)) { return false; } return true; } static public string NormalizedTableKey(this string key) { char[] speicialChars = @"#?/\".ToCharArray(); string[] str = key.Split(speicialChars, StringSplitOptions.RemoveEmptyEntries); return String.Join("_", str); } /// <summary> /// The twin's tag and property flat name start with "__" and end with "__" is reserved /// for internal usage purpose. /// e.g. /// tags.HubEnabledState /// tags.__icon__, tags.cpu.__version__ /// desired.__location__, desired.__location.latitude /// reported.__location__, reported.__location__.__latitude__ /// </summary> /// <param name="flatName"></param> /// <returns></returns> static public bool IsReservedTwinName(this string flatName) { if (string.IsNullOrEmpty(flatName)) return false; // this line should be removed once we change it to tags.__HubEnabledState__ in the future. if ("tags.HubEnabledState".Equals(flatName, StringComparison.Ordinal)) return true; string[] parts = flatName.Split('.'); return parts.Any(p => p.StartsWith("__", StringComparison.Ordinal) && p.EndsWith("__", StringComparison.Ordinal)); } } }
40.030928
126
0.564512
[ "MIT" ]
incarnyx/Smart-Parking-Solution
Remote Monitoring Solution/Common/Extensions/StringExtension.cs
3,885
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace FindPair { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
22.043478
65
0.609467
[ "MIT" ]
kravtsun/au-dotnet
FindPair/FindPair/Program.cs
509
C#
namespace Pims.Api.Models.Parcel { public class AddressModel : BaseAppModel { #region Properties public long Id { get; set; } public string Line1 { get; set; } public string Line2 { get; set; } public string AdministrativeArea { get; set; } public string ProvinceId { get; set; } public string Province { get; set; } public string Postal { get; set; } #endregion } }
20.772727
54
0.582057
[ "Apache-2.0" ]
stairaku/PSP
backend/api/Models/Parcel/AddressModel.cs
457
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using VVVV.PluginInterfaces.V1; using VVVV.PluginInterfaces.V2; namespace VVVV.DX11 { public interface IDX11RenderDependencyFactory { void CreateDependency(IPin inputPin, IPin outputPin); void DeleteDependency(IPin inputPin); } }
22.117647
61
0.760638
[ "BSD-3-Clause" ]
azeno/dx11-vvvv
Core/VVVV.DX11.Core/NodeInterfaces/IDX11RenderDependencyFactory.cs
378
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 AddmlPack.Utils { 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 Files { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Files() { } /// <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("AddmlPack.Utils.Files", typeof(Files).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; } } /// <summary> /// Looks up a localized string similar to &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot; standalone=&quot;no&quot;?&gt; ///&lt;addml xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://www.arkivverket.no/standarder/addml addml.xsd&quot; xmlns=&quot;http://www.arkivverket.no/standarder/addml&quot; name=&quot;Arkivnavn&quot;&gt; /// &lt;dataset name=&quot;Filarkiv&quot;&gt; /// &lt;description&gt;Arkivmateriale.&lt;/description&gt; /// &lt;reference /&gt; /// &lt;flatFiles&gt; /// &lt;flatFile definitionReference=&quot;FilarkivDef&quot; name=&quot;Filarkiv-analyse&quot;&gt; /// &lt;properties&gt; /// &lt;property name=&quot;fileName&quot;&gt; /// [rest of string was truncated]&quot;;. /// </summary> internal static string Addml_for_FF { get { return ResourceManager.GetString("Addml_for_FF", resourceCulture); } } /// <summary> /// Looks up a localized string similar to &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; ///&lt;addml xmlns=&quot;http://www.arkivverket.no/standarder/addml&quot; /// xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; /// name=&quot;Mal for arkivuttrekk som følger Noark 3&quot; /// xsi:schemaLocation=&quot;http://www.arkivverket.no/standarder/addml addml.xsd&quot;&gt; /// &lt;dataset name=&quot;Noark_3&quot;&gt; /// &lt;reference&gt; /// &lt;context&gt; /// &lt;additionalElements&gt; /// &lt;additionalElement name=&quot;systemType&quot;&gt; /// &lt;value&gt;Journalsystem (Noark-3)&lt;/value&gt; /// [rest of string was truncated]&quot;;. /// </summary> internal static string Addml_for_N3 { get { return ResourceManager.GetString("Addml_for_N3", resourceCulture); } } /// <summary> /// Looks up a localized string similar to &lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; ///&lt;addml xmlns=&quot;http://www.arkivverket.no/standarder/addml&quot; xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation=&quot;http://www.arkivverket.no/standarder/addml addml.xsd&quot; name=&quot;Noark 5-arkivuttrekk&quot;&gt; /// &lt;dataset&gt; /// &lt;description&gt;Noark 5-arkivuttrekk&lt;/description&gt; /// &lt;reference&gt; /// &lt;context&gt; /// &lt;additionalElements&gt; /// &lt;additionalElement name=&quot;recordCreators&quot;&gt; /// &lt;additionalElements&gt; /// &lt;additionalElement name=&quot; [rest of string was truncated]&quot;;. /// </summary> internal static string Addml_for_N5 { get { return ResourceManager.GetString("Addml_for_N5", resourceCulture); } } } }
49.816667
271
0.590164
[ "MIT" ]
joergen-vs/addmlpack
AddmlPack.Utils/Files.Designer.cs
5,981
C#
#if UITEST using System; using System.Diagnostics; using System.IO; using System.Linq; using NUnit.Framework; using NUnit.Framework.Interfaces; using Xamarin.Forms.Core.UITests; using Xamarin.UITest; using Xamarin.UITest.Queries; #if __IOS__ using Xamarin.UITest.iOS; #endif namespace Xamarin.Forms.Controls { /// <summary> /// Decorator for IApp which only takes screenshots if the SCREENSHOTS symbol is specified /// </summary> internal class ScreenshotConditionalApp : IApp { readonly IApp _app; public ScreenshotConditionalApp(IApp app) { _app = app; } public AppResult[] Query(Func<AppQuery, AppQuery> query = null) { return _app.Query(query); } public AppResult[] Query(string marked) { return _app.Query(marked); } public AppWebResult[] Query(Func<AppQuery, AppWebQuery> query) { return _app.Query(query); } public T[] Query<T>(Func<AppQuery, AppTypedSelector<T>> query) { return _app.Query(query); } public string[] Query(Func<AppQuery, InvokeJSAppQuery> query) { return _app.Query(query); } public AppResult[] Flash(Func<AppQuery, AppQuery> query = null) { return _app.Flash(query); } public AppResult[] Flash(string marked) { return _app.Flash(marked); } public void EnterText(string text) { _app.EnterText(text); } public void EnterText(Func<AppQuery, AppQuery> query, string text) { _app.EnterText(query, text); } public void EnterText(string marked, string text) { _app.EnterText(marked, text); } public void EnterText(Func<AppQuery, AppWebQuery> query, string text) { _app.EnterText(query, text); } public void ClearText(Func<AppQuery, AppWebQuery> query) { _app.ClearText(query); } public void ClearText(Func<AppQuery, AppQuery> query) { _app.ClearText(query); } public void ClearText(string marked) { _app.ClearText(marked); } public void ClearText() { _app.ClearText(); } public void PressEnter() { _app.PressEnter(); } public void DismissKeyboard() { _app.DismissKeyboard(); } public void Tap(Func<AppQuery, AppQuery> query) { _app.Tap(query); } public void Tap(string marked) { _app.Tap(marked); } public void Tap(Func<AppQuery, AppWebQuery> query) { _app.Tap(query); } public void TapCoordinates(float x, float y) { _app.TapCoordinates(x, y); } public void TouchAndHold(Func<AppQuery, AppQuery> query) { _app.TouchAndHold(query); } public void TouchAndHold(string marked) { _app.TouchAndHold(marked); } public void TouchAndHoldCoordinates(float x, float y) { _app.TouchAndHoldCoordinates(x, y); } public void DoubleTap(Func<AppQuery, AppQuery> query) { _app.DoubleTap(query); } public void DoubleTap(string marked) { _app.DoubleTap(marked); } public void DoubleTapCoordinates(float x, float y) { _app.DoubleTapCoordinates(x, y); } public void PinchToZoomIn(Func<AppQuery, AppQuery> query, TimeSpan? duration = null) { _app.PinchToZoomIn(query, duration); } public void PinchToZoomIn(string marked, TimeSpan? duration = null) { _app.PinchToZoomIn(marked, duration); } public void PinchToZoomInCoordinates(float x, float y, TimeSpan? duration) { _app.PinchToZoomInCoordinates(x, y, duration); } public void PinchToZoomOut(Func<AppQuery, AppQuery> query, TimeSpan? duration = null) { _app.PinchToZoomOut(query, duration); } public void PinchToZoomOut(string marked, TimeSpan? duration = null) { _app.PinchToZoomOut(marked, duration); } public void PinchToZoomOutCoordinates(float x, float y, TimeSpan? duration) { _app.PinchToZoomOutCoordinates(x, y, duration); } public void WaitFor(Func<bool> predicate, string timeoutMessage = "Timed out waiting...", TimeSpan? timeout = null, TimeSpan? retryFrequency = null, TimeSpan? postTimeout = null) { _app.WaitFor(predicate, timeoutMessage, timeout, retryFrequency, postTimeout); } public AppResult[] WaitForElement(Func<AppQuery, AppQuery> query, string timeoutMessage = "Timed out waiting for element...", TimeSpan? timeout = null, TimeSpan? retryFrequency = null, TimeSpan? postTimeout = null) { return _app.WaitForElement(query, timeoutMessage, timeout, retryFrequency, postTimeout); } public AppResult[] WaitForElement(string marked, string timeoutMessage = "Timed out waiting for element...", TimeSpan? timeout = null, TimeSpan? retryFrequency = null, TimeSpan? postTimeout = null) { return _app.WaitForElement(marked, timeoutMessage, timeout, retryFrequency, postTimeout); } public AppWebResult[] WaitForElement(Func<AppQuery, AppWebQuery> query, string timeoutMessage = "Timed out waiting for element...", TimeSpan? timeout = null, TimeSpan? retryFrequency = null, TimeSpan? postTimeout = null) { return _app.WaitForElement(query, timeoutMessage, timeout, retryFrequency, postTimeout); } public AppResult WaitForFirstElement(string marked, string timeoutMessage = "Timed out waiting for element...", TimeSpan? timeout = null, TimeSpan? retryFrequency = null) { #if __WINDOWS__ return (_app as WinDriverApp).WaitForFirstElement(marked, timeoutMessage, timeout, retryFrequency); #else return _app.WaitForElement(marked, timeoutMessage, timeout, retryFrequency).FirstOrDefault(); #endif } public void WaitForNoElement(Func<AppQuery, AppQuery> query, string timeoutMessage = "Timed out waiting for no element...", TimeSpan? timeout = null, TimeSpan? retryFrequency = null, TimeSpan? postTimeout = null) { _app.WaitForNoElement(query, timeoutMessage, timeout, retryFrequency, postTimeout); } public void WaitForNoElement(string marked, string timeoutMessage = "Timed out waiting for no element...", TimeSpan? timeout = null, TimeSpan? retryFrequency = null, TimeSpan? postTimeout = null) { _app.WaitForNoElement(marked, timeoutMessage, timeout, retryFrequency, postTimeout); } public void WaitForNoElement(Func<AppQuery, AppWebQuery> query, string timeoutMessage = "Timed out waiting for no element...", TimeSpan? timeout = null, TimeSpan? retryFrequency = null, TimeSpan? postTimeout = null) { _app.WaitForNoElement(query, timeoutMessage, timeout, retryFrequency, postTimeout); } public FileInfo Screenshot(string title) { #if SCREENSHOTS return _app.Screenshot(title); #else return null; #endif } public void SwipeRight() { SwipeLeftToRight(); } public void SwipeLeftToRight(double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true) { _app.SwipeLeftToRight(swipePercentage, swipeSpeed, withInertia); } public void SwipeLeftToRight(string marked, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true) { _app.SwipeLeftToRight(marked, swipePercentage, swipeSpeed, withInertia); } public void SwipeLeft() { SwipeRightToLeft(); } public void SwipeRightToLeft(double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true) { _app.SwipeRightToLeft(swipePercentage, swipeSpeed, withInertia); } public void SwipeRightToLeft(string marked, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true) { _app.SwipeRightToLeft(marked, swipePercentage, swipeSpeed, withInertia); } public void SwipeLeftToRight(Func<AppQuery, AppQuery> query, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true) { _app.SwipeLeftToRight(query, swipePercentage, swipeSpeed, withInertia); } public void SwipeLeftToRight(Func<AppQuery, AppWebQuery> query, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true) { _app.SwipeLeftToRight(query, swipePercentage, swipeSpeed, withInertia); } public void SwipeRightToLeft(Func<AppQuery, AppQuery> query, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true) { _app.SwipeRightToLeft(query, swipePercentage, swipeSpeed, withInertia); } public void SwipeRightToLeft(Func<AppQuery, AppWebQuery> query, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true) { _app.SwipeRightToLeft(query, swipePercentage, swipeSpeed, withInertia); } public void ScrollUp(Func<AppQuery, AppQuery> query = null, ScrollStrategy strategy = ScrollStrategy.Auto, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true) { _app.ScrollUp(query, strategy, swipePercentage, swipeSpeed, withInertia); } public void ScrollUp(string withinMarked, ScrollStrategy strategy = ScrollStrategy.Auto, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true) { _app.ScrollUp(withinMarked, strategy, swipePercentage, swipeSpeed, withInertia); } public void ScrollDown(Func<AppQuery, AppQuery> withinQuery = null, ScrollStrategy strategy = ScrollStrategy.Auto, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true) { _app.ScrollDown(withinQuery, strategy, swipePercentage, swipeSpeed, withInertia); } public void ScrollDown(string withinMarked, ScrollStrategy strategy = ScrollStrategy.Auto, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true) { _app.ScrollDown(withinMarked, strategy, swipePercentage, swipeSpeed, withInertia); } public void ScrollTo(string toMarked, string withinMarked = null, ScrollStrategy strategy = ScrollStrategy.Auto, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true, TimeSpan? timeout = null) { _app.ScrollTo(toMarked, withinMarked, strategy, swipePercentage, swipeSpeed, withInertia, timeout); } public void ScrollUpTo(string toMarked, string withinMarked = null, ScrollStrategy strategy = ScrollStrategy.Auto, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true, TimeSpan? timeout = null) { _app.ScrollUpTo(toMarked, withinMarked, strategy, swipePercentage, swipeSpeed, withInertia, timeout); } public void ScrollUpTo(Func<AppQuery, AppWebQuery> toQuery, string withinMarked, ScrollStrategy strategy = ScrollStrategy.Auto, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true, TimeSpan? timeout = null) { _app.ScrollUpTo(toQuery, withinMarked, strategy, swipePercentage, swipeSpeed, withInertia, timeout); } public void ScrollDownTo(string toMarked, string withinMarked = null, ScrollStrategy strategy = ScrollStrategy.Auto, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true, TimeSpan? timeout = null) { _app.ScrollDownTo(toMarked, withinMarked, strategy, swipePercentage, swipeSpeed, withInertia, timeout); } public void ScrollDownTo(Func<AppQuery, AppWebQuery> toQuery, string withinMarked, ScrollStrategy strategy = ScrollStrategy.Auto, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true, TimeSpan? timeout = null) { _app.ScrollDownTo(toQuery, withinMarked, strategy, swipePercentage, swipeSpeed, withInertia, timeout); } public void ScrollUpTo(Func<AppQuery, AppQuery> toQuery, Func<AppQuery, AppQuery> withinQuery = null, ScrollStrategy strategy = ScrollStrategy.Auto, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true, TimeSpan? timeout = null) { _app.ScrollUpTo(toQuery, withinQuery, strategy, swipePercentage, swipeSpeed, withInertia, timeout); } public void ScrollUpTo(Func<AppQuery, AppWebQuery> toQuery, Func<AppQuery, AppQuery> withinQuery = null, ScrollStrategy strategy = ScrollStrategy.Auto, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true, TimeSpan? timeout = null) { _app.ScrollUpTo(toQuery, withinQuery, strategy, swipePercentage, swipeSpeed, withInertia, timeout); } public void ScrollDownTo(Func<AppQuery, AppQuery> toQuery, Func<AppQuery, AppQuery> withinQuery = null, ScrollStrategy strategy = ScrollStrategy.Auto, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true, TimeSpan? timeout = null) { _app.ScrollDownTo(toQuery, withinQuery, strategy, swipePercentage, swipeSpeed, withInertia, timeout); } public void ScrollDownTo(Func<AppQuery, AppWebQuery> toQuery, Func<AppQuery, AppQuery> withinQuery = null, ScrollStrategy strategy = ScrollStrategy.Auto, double swipePercentage = 0.67, int swipeSpeed = 500, bool withInertia = true, TimeSpan? timeout = null) { _app.ScrollDownTo(toQuery, withinQuery, strategy, swipePercentage, swipeSpeed, withInertia, timeout); } public void SetOrientationPortrait() { _app.SetOrientationPortrait(); } public void SetOrientationLandscape() { _app.SetOrientationLandscape(); } public void Repl() { _app.Repl(); } public void Back() { _app.Back(); } public void PressVolumeUp() { _app.PressVolumeUp(); } public void PressVolumeDown() { _app.PressVolumeDown(); } public object Invoke(string methodName, object argument = null) { return _app.Invoke(methodName, argument); } public object Invoke(string methodName, object[] arguments) { return _app.Invoke(methodName, arguments); } public void DragCoordinates(float fromX, float fromY, float toX, float toY) { _app.DragCoordinates(fromX, fromY, toX, toY); } public void DragAndDrop(Func<AppQuery, AppQuery> @from, Func<AppQuery, AppQuery> to) { _app.DragAndDrop(@from, to); } public void DragAndDrop(string @from, string to) { _app.DragAndDrop(@from, to); } public void SetSliderValue(string marked, double value) { _app.SetSliderValue(marked, value); } public void SetSliderValue(Func<AppQuery, AppQuery> query, double value) { _app.SetSliderValue(query, value); } public AppPrintHelper Print { get { return _app.Print; } } public IDevice Device { get { return _app.Device; } } public ITestServer TestServer { get { return _app.TestServer; } } public void TestSetup(Type testType, bool isolate) { #if __WINDOWS__ (_app as WinDriverApp).RestartIfAppIsClosed(); #endif if (isolate) { AppSetup.BeginIsolate(); } else { AppSetup.EnsureMemory(); AppSetup.EnsureConnection(); } AppSetup.NavigateToIssue(testType, this); } public void TestTearDown(bool isolate) { if (isolate) { AppSetup.EndIsolate(); } AttachScreenshotIfOutcomeFailed(); } public void AttachScreenshotToTestContext(string title = null) { title = title ?? TestContext.CurrentContext.Test.FullName .Replace(".", "_") .Replace(" ", "_"); FileInfo file = _app.Screenshot(title); if (file != null) { try { TestContext.AddTestAttachment(file.FullName, TestContext.CurrentContext.Test.FullName); } catch(Exception exc) { Debug.WriteLine($"Failed to write {file?.FullName} {exc}"); } } } public void AttachScreenshotIfOutcomeFailed() { if (TestContext.CurrentContext.Result.Outcome.Status == TestStatus.Failed) AttachScreenshotToTestContext(); } #if __IOS__ public bool IsTablet { get { if (_app is iOSApp app) { return app.Device.IsTablet; } throw new Exception($"Invaliid app type: {_app}"); } } public bool IsPhone { get { if (_app is iOSApp app) { return app.Device.IsPhone; } throw new Exception($"Invaliid app type: {_app}"); } } public void SendAppToBackground(TimeSpan timeSpan) { if (_app is iOSApp app) { app.SendAppToBackground(timeSpan); } } #endif } } #endif
27.969534
186
0.723265
[ "MIT" ]
Seuleuzeuh/Xamarin.Forms
Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/TestPages/ScreenshotConditionalApp.cs
15,607
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Inheritance_Product { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
23.478261
66
0.592593
[ "MIT" ]
kadir-code/OOP_Applications
Inheritance/Inheritance_Product_Info/Program.cs
542
C#
using System; using Aspect.Policies.CompilerServices.CompilationUnits; namespace Aspect.Policies.CompilerServices.SyntaxTokens { internal sealed class QuotedIdentifierSyntaxToken : SyntaxToken { public string Value { get; } public string ParsedValue => Value.Replace("\\\"", "\"", StringComparison.Ordinal); public QuotedIdentifierSyntaxToken(string value, int lineNumber, int position, CompilationUnit source) : base (lineNumber, position, source) { Value = value; Length = Value.Length + 2; } } }
31.052632
110
0.666102
[ "MIT" ]
Im5tu/aspect
src/Aspect.Policies/CompilerServices/SyntaxTokens/QuotedIdentifierSyntaxToken.cs
592
C#
using System.Collections.Generic; using System.Reflection; using Fody; using Xunit; public class WithIncludesTests { static Assembly assembly; static TestResult testResult; static WithIncludesTests() { var weavingTask = new ModuleWeaver { IncludeNamespaces = new List<string> { "MyNameSpace" }, }; testResult = weavingTask.ExecuteTestRun("AssemblyToProcess.dll", assemblyName: nameof(WithIncludesTests)); assembly = testResult.Assembly; } [Fact] public void ClassInheritWithNonEmptyConstructor() { var type = assembly.GetType("ClassInheritWithNonEmptyConstructor", true); Assert.Single(type.GetConstructors()); } [Fact] public void ClassInheritWithNonEmptyConstructorInNamespace() { testResult.GetInstance("MyNameSpace.ClassWithNoEmptyConstructorInNamespace"); } }
26.621622
86
0.634518
[ "MIT" ]
BrunoJuchli/EmptyConstructor
Tests/WithIncludesTests.cs
951
C#
using System.Threading.Tasks; using Craftplacer.IRC.Helpers; namespace Craftplacer.IRC.Entities { public class IrcUser : IrcEntity { public IrcUser(IrcClient client, string hostmask) : base(client) { (Nickname, Username, Host) = Utilities.ExtractHostmask(hostmask); } public string Host { get; } public string Nickname { get; } public string Username { get; } public async Task SendMessageAsync(string message) { await Client.SendMessageAsync(Username, message); } public override string ToString() { return $"{Nickname}!{Username}@{Host}"; } } }
23.266667
77
0.598854
[ "MIT" ]
Craftplacer/IRC
Craftplacer.IRC/Entities/IrcUser.cs
700
C#
using LightBDD.Framework.Scenarios; using LightBDD.XUnit2; using Nancy; namespace RestFS.Console_Test.RestApi { public partial class ReadFileInfo { [Scenario] public void Read_an_existent_file_information() { Runner.RunScenario( _ => Given_a_file("existing/file.ext"), _ => Given_a_storage(true), _ => Given_a_fake_browser(), _ => When_Head_on_file_is_invoked(), _ => Then_status_code_is_returned(HttpStatusCode.NoContent), _ => Then_expected_file_attributes_are_returned() ); } [Scenario] public void Read_a_nonexistent_file_information() { Runner.RunScenario( _ => Given_a_file("not/existing/file.ext"), _ => Given_a_storage(false), _ => Given_a_fake_browser(), _ => When_Head_on_file_is_invoked(), _ => Then_status_code_is_returned(HttpStatusCode.NotFound) ); } [Scenario] public void Wrong_query_parameter_set() { Runner.RunScenario( _ => Given_a_file(null), _ => Given_a_storage(false), _ => Given_a_fake_browser(), _ => When_Head_on_file_is_invoked(), _ => Then_status_code_is_returned(HttpStatusCode.BadRequest) ); } } }
31.891304
76
0.551466
[ "Apache-2.0" ]
secana/RestFS
test/RestFS.Console_Test/RestApi/ReadFileInfo.cs
1,469
C#
//*************************************************** //* This file was generated by JSharp //*************************************************** namespace java.net { internal partial class SocksSocketImpl : PlainSocketImpl, SocksConsts { public SocksSocketImpl(){} protected virtual void acceptFrom(SocketImpl prm1, InetSocketAddress prm2){} protected override void close(){} protected override void connect(SocketAddress prm1, int prm2){} protected virtual void socksBind(InetSocketAddress prm1){} public InetAddress InetAddress { get; private set;} public int LocalPort { get; private set;} public int Port { get; private set;} } }
39.666667
84
0.584034
[ "MIT" ]
SharpKit/Cs2Java
Runtime/rt/java/net/SocksSocketImpl.cs
714
C#
namespace DragonSpark.Application.Security.Identity.Claims.Policy; public class ClaimsPolicy : AddPolicyConfiguration { protected ClaimsPolicy(string name, params string[] claims) : base(name, new RequireClaims(claims)) {} }
37.833333
103
0.806167
[ "MIT" ]
DragonSpark/Framework
DragonSpark.Application/Security/Identity/Claims/Policy/ClaimsPolicy.cs
229
C#
// <auto-generated /> using System; using LogisticsSystem.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace LogisticsSystem.Migrations { [DbContext(typeof(LogisticsDbContext))] partial class LogisticsDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.9") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("LogisticsSystem.Data.Models.Comment", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Content") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<bool>("IsPublic") .HasColumnType("bit"); b.Property<DateTime>("PublishedOn") .HasColumnType("datetime2"); b.Property<int>("ReviewId") .HasColumnType("int"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("ReviewId"); b.HasIndex("UserId"); b.ToTable("Comments"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Customer", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(25) .HasColumnType("nvarchar(25)"); b.Property<string>("PhoneNumber") .IsRequired() .HasMaxLength(30) .HasColumnType("nvarchar(30)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId") .IsUnique(); b.ToTable("Customers"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Favourite", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("LoadId") .IsRequired() .HasColumnType("nvarchar(450)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("LoadId"); b.HasIndex("UserId"); b.ToTable("Favourites"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Kind", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasMaxLength(25) .HasColumnType("nvarchar(25)"); b.HasKey("Id"); b.ToTable("Kinds"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Load", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<DateTime?>("ArrivedOn") .HasColumnType("datetime2"); b.Property<string>("CustomerId") .HasColumnType("nvarchar(450)"); b.Property<DateTime?>("DeletedOn") .HasColumnType("datetime2"); b.Property<string>("Description") .IsRequired() .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<string>("ImageUrl") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsPublic") .HasColumnType("bit"); b.Property<int>("KindId") .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasMaxLength(30) .HasColumnType("nvarchar(30)"); b.Property<DateTime>("ShippedOn") .HasColumnType("datetime2"); b.HasKey("Id"); b.HasIndex("CustomerId"); b.HasIndex("KindId"); b.ToTable("Loads"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.LoadImage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ImageUrl") .HasColumnType("nvarchar(max)"); b.Property<string>("LoadId") .IsRequired() .HasColumnType("nvarchar(450)"); b.Property<string>("LoadId1") .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("LoadId") .IsUnique(); b.HasIndex("LoadId1") .IsUnique() .HasFilter("[LoadId1] IS NOT NULL"); b.ToTable("LoadsImages"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Question", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Content") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<bool>("IsPublic") .HasColumnType("bit"); b.Property<string>("LoadId") .IsRequired() .HasColumnType("nvarchar(450)"); b.Property<DateTime>("PublishedOn") .HasColumnType("datetime2"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("LoadId"); b.HasIndex("UserId"); b.ToTable("Questions"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Response", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Content") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<bool>("IsPublic") .HasColumnType("bit"); b.Property<DateTime>("PublishedOn") .HasColumnType("datetime2"); b.Property<int>("QuestionId") .HasColumnType("int"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("QuestionId"); b.HasIndex("UserId"); b.ToTable("Responses"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Review", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Content") .IsRequired() .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<bool>("IsPublic") .HasColumnType("bit"); b.Property<string>("LoadId") .IsRequired() .HasColumnType("nvarchar(450)"); b.Property<DateTime>("PublishedOn") .HasColumnType("datetime2"); b.Property<int>("Rating") .HasColumnType("int"); b.Property<string>("Title") .IsRequired() .HasMaxLength(20) .HasColumnType("nvarchar(20)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("LoadId"); b.HasIndex("UserId"); b.ToTable("Reviews"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.User", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<string>("FullName") .HasMaxLength(40) .HasColumnType("nvarchar(40)"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("NormalizedEmail") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedUserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasDatabaseName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasDatabaseName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasDatabaseName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("Name") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Comment", b => { b.HasOne("LogisticsSystem.Data.Models.Review", "Review") .WithMany("Comments") .HasForeignKey("ReviewId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("LogisticsSystem.Data.Models.User", "User") .WithMany("Comments") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Review"); b.Navigation("User"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Customer", b => { b.HasOne("LogisticsSystem.Data.Models.User", null) .WithOne() .HasForeignKey("LogisticsSystem.Data.Models.Customer", "UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Favourite", b => { b.HasOne("LogisticsSystem.Data.Models.Load", "Load") .WithMany("Favourites") .HasForeignKey("LoadId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("LogisticsSystem.Data.Models.User", "User") .WithMany("Favourites") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Load"); b.Navigation("User"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Load", b => { b.HasOne("LogisticsSystem.Data.Models.Customer", "Customer") .WithMany("Loads") .HasForeignKey("CustomerId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("LogisticsSystem.Data.Models.Kind", "Kind") .WithMany("Loads") .HasForeignKey("KindId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Customer"); b.Navigation("Kind"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.LoadImage", b => { b.HasOne("LogisticsSystem.Data.Models.Load", "Load") .WithOne() .HasForeignKey("LogisticsSystem.Data.Models.LoadImage", "LoadId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("LogisticsSystem.Data.Models.Load", null) .WithOne("Image") .HasForeignKey("LogisticsSystem.Data.Models.LoadImage", "LoadId1"); b.Navigation("Load"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Question", b => { b.HasOne("LogisticsSystem.Data.Models.Load", "Load") .WithMany("Questions") .HasForeignKey("LoadId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("LogisticsSystem.Data.Models.User", "User") .WithMany("Questions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Load"); b.Navigation("User"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Response", b => { b.HasOne("LogisticsSystem.Data.Models.Question", "Question") .WithMany("Responses") .HasForeignKey("QuestionId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("LogisticsSystem.Data.Models.User", "User") .WithMany("Responses") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Question"); b.Navigation("User"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Review", b => { b.HasOne("LogisticsSystem.Data.Models.Load", "Load") .WithMany("Reviews") .HasForeignKey("LoadId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("LogisticsSystem.Data.Models.User", "User") .WithMany("Reviews") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Load"); b.Navigation("User"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("LogisticsSystem.Data.Models.User", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("LogisticsSystem.Data.Models.User", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("LogisticsSystem.Data.Models.User", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("LogisticsSystem.Data.Models.User", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Customer", b => { b.Navigation("Loads"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Kind", b => { b.Navigation("Loads"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Load", b => { b.Navigation("Favourites"); b.Navigation("Image"); b.Navigation("Questions"); b.Navigation("Reviews"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Question", b => { b.Navigation("Responses"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.Review", b => { b.Navigation("Comments"); }); modelBuilder.Entity("LogisticsSystem.Data.Models.User", b => { b.Navigation("Comments"); b.Navigation("Favourites"); b.Navigation("Questions"); b.Navigation("Responses"); b.Navigation("Reviews"); }); #pragma warning restore 612, 618 } } }
36.430851
125
0.43886
[ "MIT" ]
pepsitopepsito9681/ASP.NET-Core-Project-Logistics-System
LogisticsSystem/Migrations/LogisticsDbContextModelSnapshot.cs
27,398
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 Xunit; namespace System.Threading.Tests { public static partial class SpinWaitTests { [Fact] public static void SpinOnce_Sleep1Threshold() { SpinWait spinner = new SpinWait(); AssertExtensions.Throws<ArgumentOutOfRangeException>("sleep1Threshold", () => spinner.SpinOnce(-2)); AssertExtensions.Throws<ArgumentOutOfRangeException>("sleep1Threshold", () => spinner.SpinOnce(int.MinValue)); Assert.Equal(0, spinner.Count); spinner.SpinOnce(sleep1Threshold: -1); Assert.Equal(1, spinner.Count); spinner.SpinOnce(sleep1Threshold: 0); Assert.Equal(2, spinner.Count); spinner.SpinOnce(sleep1Threshold: 1); Assert.Equal(3, spinner.Count); spinner.SpinOnce(sleep1Threshold: int.MaxValue); Assert.Equal(4, spinner.Count); int i = 5; for (; i < 10; ++i) { spinner.SpinOnce(sleep1Threshold: -1); Assert.Equal(i, spinner.Count); } for (; i < 20; ++i) { spinner.SpinOnce(sleep1Threshold: 15); Assert.Equal(i, spinner.Count); } } } }
34.97619
122
0.582709
[ "MIT" ]
2E0PGS/corefx
src/System.Threading/tests/SpinWaitTests.netcoreapp.cs
1,471
C#
using System; namespace Interface_Desacopla { class RegistrarNoConsole : IRegistro { public void RegistraInfo(string mensagem) { Console.WriteLine($"info : {mensagem}"); } } }
17.384615
52
0.597345
[ "MIT" ]
LucasCancio/poo-com-solid
Modulo02/37_Interface_Desacopla/Interface_Desacopla/RegistrarNoConsole.cs
228
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using KSP.UI.Screens; using NearFutureElectrical; using KSP.Localization; namespace NearFutureElectrical.UI { public class ReactorUIEntry { // Color of the temperature bar private Color nominalColor = Color.green; private Color criticalColor = new Color(1.0f, 102f / 255f, 0f); private Color meltdownColor = Color.red; private bool advancedMode = false; private ReactorUI host; private FissionReactor reactor; private FissionGenerator generator; // Constructor public ReactorUIEntry(FissionReactor toDraw, ReactorUI uihost) { host = uihost; reactor = toDraw; generator = reactor.GetComponent<FissionGenerator>(); } // Draw the main control area private void DrawMainControls() { Rect controlRect = GUILayoutUtility.GetRect(184f, 64f); Rect iconRect = new Rect(0f, 0f, 64f, 64f); Rect titleRect = new Rect(64f, 0f, 116f, 32f); Rect toggleRect = new Rect(64f, 32f, 32f, 32f); Rect settingsButtonRect = new Rect(133f, 36f, 20f, 20f); GUI.BeginGroup(controlRect); // STATIC: Icon GUI.DrawTextureWithTexCoords(iconRect, host.GUIResources.GetReactorIcon(reactor.UIIcon).iconAtlas, host.GUIResources.GetReactorIcon(reactor.UIIcon).iconRect); // STATIC: UI Name GUI.Label(titleRect, reactor.UIName, host.GUIResources.GetStyle("header_basic")); // BUTTON: Toggle bool current = reactor.ModuleIsActive(); bool toggled = GUI.Toggle(toggleRect, reactor.ModuleIsActive(),"ON",host.GUIResources.GetStyle("button_toggle")); if (current != toggled) { reactor.ToggleResourceConverterAction( new KSPActionParam(0,KSPActionType.Activate) ); } // BUTTON: Settings if (GUI.Button(settingsButtonRect, "", host.GUIResources.GetStyle("button_overlaid"))) { ReactorUI.ShowFocusedReactorSettings(reactor); } GUI.DrawTextureWithTexCoords(settingsButtonRect, host.GUIResources.GetIcon("gear").iconAtlas, host.GUIResources.GetIcon("gear").iconRect); GUI.EndGroup(); } // Draw the noninteractable components private void DrawReadout() { Rect controlRect = GUILayoutUtility.GetRect(270f, 64f); Rect heatIconRect = new Rect(0f, 0f, 20f, 20f); Rect heatTextRect = new Rect(20f, 1f, 60f, 20f); Rect powerIconRect = new Rect(80f, 0f, 20f, 20f); Rect powerTextRect = new Rect(100f, 1f, 60f, 20f); Rect lifetimeIconRect = new Rect(160f, 0f, 20f, 20f); Rect lifetimeTextRect = new Rect(182f, 1f, 110f, 20f); Rect temperatureIconRect = new Rect(0f, 30f, 20f, 20f); Rect temperaturePanelRect = new Rect(20f, 30f, 210f, 30f); GUI.BeginGroup(controlRect); // READOUT: Heat production GUI.DrawTextureWithTexCoords(heatIconRect, host.GUIResources.GetIcon("fire").iconAtlas, host.GUIResources.GetIcon("fire").iconRect); GUI.Label(heatTextRect, String.Format("{0:F1} {1}", reactor.AvailablePower, Localizer.Format("#LOC_NFElectrical_Units_kW")), host.GUIResources.GetStyle("text_basic")); // READOUT: Energy production GUI.DrawTextureWithTexCoords(powerIconRect, host.GUIResources.GetIcon("lightning").iconAtlas, host.GUIResources.GetIcon("lightning").iconRect); if (generator != null) { GUI.Label(powerTextRect, String.Format("{0:F1} {1}", generator.CurrentGeneration, Localizer.Format("#LOC_NFElectrical_Units_EcS")), host.GUIResources.GetStyle("text_basic")); } else { GUI.Label(powerTextRect, String.Format("N/A"), host.GUIResources.GetStyle("text_basic")); } // READOUT: Lifetime remaining GUI.DrawTextureWithTexCoords(lifetimeIconRect, host.GUIResources.GetIcon("timer").iconAtlas, host.GUIResources.GetIcon("timer").iconRect); GUI.Label(lifetimeTextRect, String.Format("{0}", reactor.FuelStatus), host.GUIResources.GetStyle("text_basic")); // PROGRESS BAR: Temperature bar GUI.DrawTextureWithTexCoords(temperatureIconRect, host.GUIResources.GetIcon("thermometer").iconAtlas, host.GUIResources.GetIcon("thermometer").iconRect); float coreTemp = (float)reactor.GetCoreTemperature(); float meltdownTemp = reactor.MaximumTemperature; float nominalTemp = reactor.NominalTemperature; float criticalTemp = reactor.CriticalTemperature; Vector2 barBackgroundSize = new Vector2(165f, 10f); Vector2 barForegroundSize = new Vector2(Mathf.Max(barBackgroundSize.x * (coreTemp / meltdownTemp),8f), 7f); Rect barBackgroundRect = new Rect(0f, 5f, barBackgroundSize.x, barBackgroundSize.y); Rect barForeroundRect = new Rect(0f, 6f, barForegroundSize.x, barForegroundSize.y); float nominalXLoc = nominalTemp / meltdownTemp * barBackgroundRect.width + barBackgroundRect.xMin; float criticalXLoc = criticalTemp / meltdownTemp * barBackgroundRect.width + barBackgroundRect.xMin; Color barColor = new Color(); if (coreTemp <= nominalTemp) barColor = nominalColor; else if (coreTemp <= criticalTemp) barColor = Color.Lerp(nominalColor, criticalColor, (coreTemp - nominalTemp) / (criticalTemp - nominalTemp)); else barColor = Color.Lerp(criticalColor, meltdownColor, (coreTemp - criticalTemp) / (meltdownTemp - criticalTemp)); GUI.BeginGroup(temperaturePanelRect); GUI.Box(barBackgroundRect, "", host.GUIResources.GetStyle("bar_background")); GUI.color = barColor; GUI.Box(barForeroundRect, "", host.GUIResources.GetStyle("bar_foreground")); GUI.color = Color.white; GUI.Label(new Rect(barBackgroundRect.xMax+7f , 1f, 50f, 20f), String.Format("{0:F0} K", coreTemp), host.GUIResources.GetStyle("text_basic")); GUI.DrawTextureWithTexCoords(new Rect(nominalXLoc - 7f, 5f, 15f, 20f), host.GUIResources.GetIcon("notch").iconAtlas, host.GUIResources.GetIcon("notch").iconRect); GUI.DrawTextureWithTexCoords(new Rect(criticalXLoc - 7f, 5f, 15f, 20f), host.GUIResources.GetIcon("notch").iconAtlas, host.GUIResources.GetIcon("notch").iconRect); GUI.EndGroup(); GUI.EndGroup(); } // Draw the basic control set private void DrawBasicControls() { GUILayout.Button(" BASIC CONTROLS", host.GUIResources.GetStyle("header_basic")); Rect controlRect; if (reactor.FollowThrottle) controlRect = GUILayoutUtility.GetRect(180f, 64f); else controlRect = GUILayoutUtility.GetRect(180f, 24f); Rect throttleIconRect = new Rect(0f, 0f, 20f, 20f); Rect throttleSliderRect = new Rect(28f, 5f, 100f, 20f); Rect throttleTextRect = new Rect(135f, 2f, 40f, 20f); Rect realThrottleIconRect = new Rect(0f, 30f, 20f, 20f); Rect realThrotlePanelRect = new Rect(28f, 33f, 100f, 20f); Rect realThrotleTextRect = new Rect(135f, 30f, 40f, 20f); GUI.BeginGroup(controlRect); // SLIDER: Throttle GUI.DrawTextureWithTexCoords(throttleIconRect, host.GUIResources.GetIcon("throttle").iconAtlas, host.GUIResources.GetIcon("throttle").iconRect); reactor.CurrentPowerPercent = GUI.HorizontalSlider(throttleSliderRect, reactor.CurrentPowerPercent, 0f, 100f); GUI.Label(throttleTextRect, String.Format("{0:F0}%", reactor.CurrentPowerPercent), host.GUIResources.GetStyle("text_basic")); // PROGRESS BAR: Adjusted Throttle if (reactor.FollowThrottle) { GUI.DrawTextureWithTexCoords(realThrottleIconRect, host.GUIResources.GetIcon("throttle_auto").iconAtlas, host.GUIResources.GetIcon("throttle_auto").iconRect); float powerFraction = reactor.ActualPowerPercent/100f; Vector2 barBackgroundSize = new Vector2(100f, 10f); Vector2 barForegroundSize = new Vector2(Mathf.Max(barBackgroundSize.x * powerFraction, 8f), 7f); Rect barBackgroundRect = new Rect(0f, 0f, barBackgroundSize.x, barBackgroundSize.y); Rect barForeroundRect = new Rect(0f, 0f, barForegroundSize.x, barForegroundSize.y); Color barColor = Color.green; GUI.BeginGroup(realThrotlePanelRect); GUI.Box(barBackgroundRect, "", host.GUIResources.GetStyle("bar_background")); GUI.color = barColor; GUI.Box(barForeroundRect, "", host.GUIResources.GetStyle("bar_foreground")); GUI.color = Color.white; GUI.EndGroup(); GUI.Label(realThrotleTextRect, String.Format("{0:F0}%", reactor.ActualPowerPercent), host.GUIResources.GetStyle("text_basic")); } GUI.EndGroup(); } // Draw the advanced control set private void DrawAdvancedControls() { Rect controlRect = GUILayoutUtility.GetRect(180f, 64f); Rect autoTempOffToggleRect = new Rect(30f, 0f, 20f, 20f); Rect autoTempOffIconRect = new Rect(0f, 0f, 28f, 28f); Rect autoTempOffSliderRect = new Rect(60f, 10f, 70f, 20f); Rect autoTempOffTextRect = new Rect(140f, 8f, 60f, 20f); Rect autoWarpOffToggleRect = new Rect(30f, 30f, 20f, 20f); Rect autoWarpOffIconRect = new Rect(0f, 30f, 28f, 28f); Rect autoWarpOffSliderRect = new Rect(60f, 40f, 70f, 20f); Rect autoWarpOffTextRect = new Rect(140f, 38f, 60f, 20f); GUI.BeginGroup(controlRect); // SLIDER: Shutdown Temperature GUI.DrawTextureWithTexCoords(autoTempOffIconRect, host.GUIResources.GetIcon("heat_limit").iconAtlas, host.GUIResources.GetIcon("heat_limit").iconRect); reactor.AutoShutdown = GUI.Toggle(autoTempOffToggleRect, reactor.AutoShutdown, "", host.GUIResources.GetStyle("button_toggle")); reactor.CurrentSafetyOverride = GUI.HorizontalSlider(autoTempOffSliderRect, reactor.CurrentSafetyOverride, 700f, reactor.MaximumTemperature); GUI.Label(autoTempOffTextRect, String.Format("{0:F0} K", reactor.CurrentSafetyOverride), host.GUIResources.GetStyle("text_basic")); // SLIDER: Time Warp Shutdown GUI.DrawTextureWithTexCoords(autoWarpOffIconRect, host.GUIResources.GetIcon("warp_limit").iconAtlas, host.GUIResources.GetIcon("warp_limit").iconRect); reactor.TimewarpShutdown = GUI.Toggle(autoWarpOffToggleRect, reactor.TimewarpShutdown, "", host.GUIResources.GetStyle("button_toggle")); reactor.TimewarpShutdownFactor = (int)GUI.HorizontalSlider(autoWarpOffSliderRect, reactor.TimewarpShutdownFactor, 0, TimeWarp.fetch.warpRates.Length-1); GUI.Label(autoWarpOffTextRect, String.Format("{0:F0}x", TimeWarp.fetch.warpRates[reactor.TimewarpShutdownFactor]), host.GUIResources.GetStyle("text_basic")); GUI.EndGroup(); } // Draws the button that unhides the advanced controls private void DrawAdvancedControlButton(bool maximized) { GUILayout.BeginHorizontal(); if (maximized) { if (GUILayout.Button("[-] " + Localizer.Format("#LOC_NFElectrical_ReactorUI_AdvancedControls"), host.GUIResources.GetStyle("header_basic"))) { advancedMode = false; } } else { if (GUILayout.Button("[+] " + Localizer.Format("#LOC_NFElectrical_ReactorUI_AdvancedControls"), host.GUIResources.GetStyle("header_basic"))) { advancedMode = true; } } GUILayout.EndHorizontal(); } public float GetReadoutSize() { if (advancedMode) if (reactor.FollowThrottle) return 198f; else return 160f; else if (reactor.FollowThrottle) return 128f; else return 96f; } // Draw the UI component public void Draw() { GUILayout.BeginHorizontal(host.GUIResources.GetStyle("block_background"), GUILayout.Width(670f)); GUILayout.BeginHorizontal(host.GUIResources.GetStyle("item_box")); DrawMainControls(); DrawReadout(); GUILayout.EndHorizontal(); GUILayout.BeginVertical(host.GUIResources.GetStyle("item_box")); DrawBasicControls(); DrawAdvancedControlButton(advancedMode); if (advancedMode) { DrawAdvancedControls(); } GUILayout.EndVertical(); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); } } }
43.169492
186
0.669415
[ "Unlicense", "MIT" ]
LouisB3/NearFutureElectrical
Source/NearFutureElectrical/UI/ReactorUIEntry.cs
12,735
C#
using System; using System.Collections.Generic; using System.Data; using CMS.Base.Web.UI; using CMS.DataEngine; using CMS.Helpers; using CMS.SiteProvider; using CMS.Synchronization; using CMS.Synchronization.Web.UI; using CMS.UIControls; [UIElement("CMS.Staging", "All")] public partial class CMSModules_Staging_Tools_AllTasks_Tasks : CMSStagingTasksPage { #region "Properties" /// <summary> /// Event code suffix for task event names /// </summary> protected override string EventCodeSuffix { get { return "TASK"; } } /// <summary> /// Grid with the task listing /// </summary> protected override UniGrid GridTasks { get { return gridTasks; } } /// <summary> /// Async control /// </summary> protected override AsyncControl AsyncControl { get { return ctlAsyncLog; } } #endregion #region "Page events" protected override void OnLoad(EventArgs e) { base.OnLoad(e); // Check 'Manage object tasks' permission if (!CurrentUser.IsAuthorizedPerResource("cms.staging", "ManageAllTasks")) { RedirectToAccessDenied("cms.staging", "ManageAllTasks"); } CurrentMaster.DisplaySiteSelectorPanel = true; // Check enabled servers var isCallback = RequestHelper.IsCallback(); if (!isCallback && !ServerInfoProvider.IsEnabledServer(SiteContext.CurrentSiteID)) { ShowInformation(GetString("ObjectStaging.NoEnabledServer")); CurrentMaster.PanelHeader.Visible = false; plcContent.Visible = false; pnlFooter.Visible = false; return; } // Setup server dropdown selectorElem.DropDownList.AutoPostBack = true; selectorElem.UniSelector.OnSelectionChanged += UniSelector_OnSelectionChanged; // Set server ID SelectedServerID = ValidationHelper.GetInteger(selectorElem.Value, 0); // All servers if (SelectedServerID == UniSelector.US_ALL_RECORDS) { SelectedServerID = 0; } // Register script for pendingCallbacks repair ScriptHelper.FixPendingCallbacks(Page); if (!isCallback) { // Check 'Manage object tasks' permission if (!CurrentUser.IsAuthorizedPerResource("cms.staging", "ManageAllTasks")) { RedirectToAccessDenied("cms.staging", "ManageAllTasks"); } ucDisabledModule.TestAnyKey = true; ucDisabledModule.TestSettingKeys = "CMSStagingLogObjectChanges;CMSStagingLogDataChanges;CMSStagingLogChanges"; ucDisabledModule.ParentPanel = pnlNotLogged; ucDisabledModule.InfoText = GetString("staging.disabledModule.allTasks"); if (!ucDisabledModule.Check()) { CurrentMaster.PanelHeader.Visible = false; plcContent.Visible = false; pnlFooter.Visible = false; return; } // Register the dialog script ScriptHelper.RegisterDialogScript(this); // Setup title if (!ControlsHelper.CausedPostBack(btnSyncSelected, btnSyncAll)) { plcContent.Visible = true; // Initialize buttons btnDeleteAll.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("Tasks.ConfirmDeleteAll")) + ");"; btnDeleteSelected.OnClientClick = "return confirm(" + ScriptHelper.GetString(GetString("general.confirmdelete")) + ");"; btnSyncSelected.OnClientClick = "return !" + gridTasks.GetCheckSelectionScript(); // Initialize grid gridTasks.ZeroRowsText = GetString("Tasks.NoTasks"); gridTasks.OnDataReload += gridTasks_OnDataReload; gridTasks.ShowActionsMenu = true; gridTasks.Columns = "TaskID, TaskSiteID, TaskDocumentID, TaskNodeAliasPath, TaskTitle, TaskTime, TaskType, TaskObjectType, TaskObjectID, TaskRunning, (SELECT COUNT(*) FROM Staging_Synchronization WHERE SynchronizationTaskID = TaskID AND SynchronizationErrorMessage IS NOT NULL AND (SynchronizationServerID = @ServerID OR (@ServerID = 0 AND (@TaskSiteID = 0 OR SynchronizationServerID IN (SELECT ServerID FROM Staging_Server WHERE ServerSiteID = @TaskSiteID AND ServerEnabled=1))))) AS FailedCount"; StagingTaskInfo ti = new StagingTaskInfo(); gridTasks.AllColumns = SqlHelper.MergeColumns(ti.ColumnNames); pnlLog.Visible = false; } } } /// <summary> /// Executes given action asynchronously /// </summary> /// <param name="action">Action to run</param> protected override void RunAsync(AsyncAction action) { base.RunAsync(action); pnlLog.Visible = true; plcContent.Visible = false; } #endregion #region "Grid events & methods" protected DataSet gridTasks_OnDataReload(string completeWhere, string currentOrder, int currentTopN, string columns, int currentOffset, int currentPageSize, ref int totalRecords) { // Get the tasks DataSet ds = StagingTaskInfoProvider.SelectTaskList(CurrentSiteID, SelectedServerID, completeWhere, currentOrder, currentTopN, columns, currentOffset, currentPageSize, ref totalRecords); pnlFooter.Visible = (totalRecords > 0); return ds; } protected void UniSelector_OnSelectionChanged(object sender, EventArgs e) { pnlUpdate.Update(); } #endregion #region "Async methods" /// <summary> /// All items synchronization. /// </summary> protected void SynchronizeAll(object parameter) { RunAction("Synchronization", "SYNCALLTASKS", SynchronizeAllInternal); } private string SynchronizeAllInternal() { AddLog(GetString("Synchronization.RunningTasks")); // Get the tasks DataSet ds = StagingTaskInfoProvider.SelectTaskList(CurrentSiteID, SelectedServerID, GridTasks.CustomFilter.WhereCondition, "TaskID", -1, "TaskID"); // Run the synchronization return StagingTaskRunner.RunSynchronization(ds); } /// <summary> /// Synchronization of selected items. /// </summary> /// <param name="list">List of selected items</param> public void SynchronizeSelected(List<String> list) { if (list == null) { return; } RunAction("Synchronization", "SYNCSELECTEDTASKS", () => SynchronizeSelectedInternal(list)); } private string SynchronizeSelectedInternal(IEnumerable<string> list) { AddLog(GetString("Synchronization.RunningTasks")); // Run the synchronization return StagingTaskRunner.RunSynchronization(list); } /// <summary> /// Deletes selected tasks. /// </summary> protected void DeleteSelected(List<String> list) { if (list == null) { return; } RunAction("Deletion", "DELETESELECTEDTASKS", () => DeleteTasks(list)); } /// <summary> /// Deletes all tasks. /// </summary> protected void DeleteAll(object parameter) { RunAction("Deletion", "DELETEALLTASKS", DeleteAllInternal); } private string DeleteAllInternal() { AddLog(GetString("Synchronization.DeletingTasks")); // Get the tasks DataSet ds = StagingTaskInfoProvider.SelectTaskList(CurrentSiteID, SelectedServerID, gridTasks.CustomFilter.WhereCondition, "TaskID", -1, "TaskID, TaskTitle"); DeleteTasks(ds); return null; } #endregion #region "Button handling" protected void btnSyncSelected_Click(object sender, EventArgs e) { if (gridTasks.SelectedItems.Count > 0) { ctlAsyncLog.TitleText = GetString("Synchronization.Title"); // Run asynchronous action RunAsync(p => SynchronizeSelected(gridTasks.SelectedItems)); } } protected void btnSyncAll_Click(object sender, EventArgs e) { ctlAsyncLog.TitleText = GetString("Synchronization.Title"); CurrentInfo = GetString("Tasks.SynchronizationCanceled"); // Run asynchronous action RunAsync(SynchronizeAll); } protected void btnDeleteAll_Click(object sender, EventArgs e) { ctlAsyncLog.TitleText = GetString("Synchronization.DeletingTasksTitle"); // Run asynchronous action RunAsync(DeleteAll); } protected void btnDeleteSelected_Click(object sender, EventArgs e) { if (gridTasks.SelectedItems.Count > 0) { ctlAsyncLog.TitleText = GetString("Synchronization.DeletingTasksTitle"); // Run asynchronous action RunAsync(p => DeleteSelected(gridTasks.SelectedItems)); } } #endregion }
29.153846
514
0.632586
[ "MIT" ]
BryanSoltis/KenticoMVCWidgetShowcase
CMS/CMSModules/Staging/Tools/AllTasks/Tasks.aspx.cs
9,098
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110 { using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions; /// <summary>Recovery plan group details.</summary> public partial class RecoveryPlanGroup { /// <summary> /// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json); /// <summary> /// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject" /// /> before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container); /// <summary> /// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of /// the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> /// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return /// instantly.</param> partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json, ref bool returnNow); /// <summary> /// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the /// object before it is serialized. /// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IRecoveryPlanGroup. /// </summary> /// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns> /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IRecoveryPlanGroup. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IRecoveryPlanGroup FromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode node) { return node is Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json ? new RecoveryPlanGroup(json) : null; } /// <summary> /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject into a new instance of <see cref="RecoveryPlanGroup" />. /// </summary> /// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject instance to deserialize from.</param> internal RecoveryPlanGroup(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } {_groupType = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString>("groupType"), out var __jsonGroupType) ? (string)__jsonGroupType : (string)GroupType;} {_replicationProtectedItem = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonArray>("replicationProtectedItems"), out var __jsonReplicationProtectedItems) ? If( __jsonReplicationProtectedItems as Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonArray, out var __v) ? new global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IRecoveryPlanProtectedItem[]>(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__v, (__u)=>(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IRecoveryPlanProtectedItem) (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.RecoveryPlanProtectedItem.FromJson(__u) )) ))() : null : ReplicationProtectedItem;} {_startGroupAction = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonArray>("startGroupActions"), out var __jsonStartGroupActions) ? If( __jsonStartGroupActions as Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonArray, out var __q) ? new global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IRecoveryPlanAction[]>(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__q, (__p)=>(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IRecoveryPlanAction) (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.RecoveryPlanAction.FromJson(__p) )) ))() : null : StartGroupAction;} {_endGroupAction = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonArray>("endGroupActions"), out var __jsonEndGroupActions) ? If( __jsonEndGroupActions as Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonArray, out var __l) ? new global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IRecoveryPlanAction[]>(()=> global::System.Linq.Enumerable.ToArray(global::System.Linq.Enumerable.Select(__l, (__k)=>(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.IRecoveryPlanAction) (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20180110.RecoveryPlanAction.FromJson(__k) )) ))() : null : EndGroupAction;} AfterFromJson(json); } /// <summary> /// Serializes this instance of <see cref="RecoveryPlanGroup" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />. /// </summary> /// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="RecoveryPlanGroup" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />. /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode serializationMode) { container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } AddIf( null != (((object)this._groupType)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonString(this._groupType.ToString()) : null, "groupType" ,container.Add ); if (null != this._replicationProtectedItem) { var __w = new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.XNodeArray(); foreach( var __x in this._replicationProtectedItem ) { AddIf(__x?.ToJson(null, serializationMode) ,__w.Add); } container.Add("replicationProtectedItems",__w); } if (null != this._startGroupAction) { var __r = new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.XNodeArray(); foreach( var __s in this._startGroupAction ) { AddIf(__s?.ToJson(null, serializationMode) ,__r.Add); } container.Add("startGroupActions",__r); } if (null != this._endGroupAction) { var __m = new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.XNodeArray(); foreach( var __n in this._endGroupAction ) { AddIf(__n?.ToJson(null, serializationMode) ,__m.Add); } container.Add("endGroupActions",__m); } AfterToJson(ref container); return container; } } }
77.022901
770
0.685828
[ "MIT" ]
3quanfeng/azure-powershell
src/Migrate/generated/api/Models/Api20180110/RecoveryPlanGroup.json.cs
9,960
C#
// Copyright (c) CBC/Radio-Canada. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for more information. namespace LinkIt.Core.Includes.Interfaces { internal interface IIncludeWithGetReference<TIReference, TLink> { TIReference GetReference(TLink link, DataStore dataStore); } }
34.3
93
0.755102
[ "MIT" ]
fynnen/LinkIt
src/LinkIt/Core/Includes/Interfaces/IIncludeWithGetReference.cs
343
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using WioLibrary.Logging; using WioLibrary.WebSocket; namespace WioLibrary { public class SocketManager { private List<SocketClientWrapper> sockets; private static readonly SocketManager instance = new SocketManager(); private ILogWrapper logger; static SocketManager() { } private SocketManager() { this.sockets = new List<SocketClientWrapper>(); } public static SocketManager Instance => instance; public void Initialize(ILogWrapper logger) { if (logger == null) throw new ArgumentNullException("Logger must not be NULL!"); this.logger = logger; } public async Task AddAsync(string id, string uri, Func<Task> onConnect, Func<Task> onDisconnect, Func<string, Task> onMessage, bool connect) { if (HasItem(id)) return; if (string.IsNullOrEmpty(id)) throw new ArgumentNullException("Id must not be NULL!"); if (string.IsNullOrEmpty(uri)) throw new ArgumentNullException("Uri must not be NULL!"); if (onConnect == null || onDisconnect == null || onMessage == null) throw new ArgumentNullException("Func must not be NULL!"); if (this.logger == null) throw new InvalidOperationException("Not initialized yet! Run Initialize() first!"); var socket = new SocketClientWrapper(id, uri, onConnect, onDisconnect, onMessage, this.logger); if (connect) await socket.Socket.ConnectAsync(); } public async Task ConnectAsync(string id) { if(!HasItem(id)) return; await sockets.First(s => s.Id.Equals(id)).Socket.ConnectAsync(); } public async Task DisconnectAsync(string id) { if (!HasItem(id)) return; await sockets.First(s => s.Id.Equals(id)).Socket.DisconnectAsync(false); } public async Task Remove(string id) { if (!HasItem(id)) return; await sockets.First(s => s.Id.Equals(id)).Socket.DisconnectAsync(false); } public async Task Send(string id, string message) { if (!HasItem(id)) return; await sockets.First(s => s.Id.Equals(id)).Socket.SendMessageAsync(message); } private bool HasItem(string id) { return sockets.Any(s => s.Id.Equals(id.Trim())); } } }
32.461538
148
0.613349
[ "MIT" ]
mplogas/WioTimer
WioLibrary/SocketManager.cs
2,534
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("IISTA.ServerCustom")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IISTA.ServerCustom")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("1076a0c7-2ff7-4603-a3de-abda64fb38c6")] // 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.081081
84
0.745919
[ "MIT" ]
primas23/IISTestApp
IISTA.Server/Properties/AssemblyInfo.cs
1,412
C#
using System; using System.Diagnostics; namespace EasyArchitecture.Core.Aspects.Log { internal class LogInterceptor:Interceptor { internal override object Invoke(ProxyMethodCall methodCall) { object ret; var sw = new Stopwatch(); sw.Start(); MethodCallLogger.LogInvokation(methodCall.Method, methodCall.Parameters); try { ret = Next(methodCall); } catch (Exception exception) { MethodCallLogger.LogException(methodCall.Method, exception, sw.ElapsedMilliseconds); throw; } MethodCallLogger.LogReturn(methodCall.Method, ret, sw.ElapsedMilliseconds); return ret; } } }
25
100
0.57125
[ "MIT" ]
TicketArchitecture/EasyArchitecture
src/EasyArchitecture/Core/Aspects/Log/LogInterceptor.cs
802
C#
// ********************************************************************************* // <copyright file=ImageLabelButtonStyle.cs company="Marcus Technical Services, Inc."> // Copyright @2019 Marcus Technical Services, Inc. // </copyright> // // MIT License // // 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 NON-INFRINGEMENT. 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 Com.MarcusTS.SharedForms.Views.Controls { using System; using Xamarin.Forms; /// <summary> /// Interface IImageLabelButtonStyle /// </summary> public interface IImageLabelButtonStyle { /// <summary> /// Gets or sets the button style. /// </summary> /// <value>The button style.</value> Style ButtonStyle { get; set; } /// <summary> /// Gets or sets the button text. /// </summary> /// <value>The button text.</value> string ButtonText { get; set; } /// <summary> /// Gets or sets a value indicating whether [get image from resource]. /// </summary> /// <value><c>true</c> if [get image from resource]; otherwise, <c>false</c>.</value> bool GetImageFromResource { get; set; } /// <summary> /// Gets or sets the image file path. /// </summary> /// <value>The image file path.</value> string ImageFilePath { get; set; } /// <summary> /// Gets or sets the type of the image resource class. /// </summary> /// <value>The type of the image resource class.</value> Type ImageResourceClassType { get; set; } /// <summary> /// Gets or sets the state of the internal button. /// </summary> /// <value>The state of the internal button.</value> string InternalButtonState { get; set; } /// <summary> /// Gets or sets the label style. /// </summary> /// <value>The label style.</value> Style LabelStyle { get; set; } } /// <summary> /// Class ImageLabelButtonStyle. /// Implements the <see cref="Com.MarcusTS.SharedForms.Views.Controls.IImageLabelButtonStyle" /> /// </summary> /// <seealso cref="Com.MarcusTS.SharedForms.Views.Controls.IImageLabelButtonStyle" /> public class ImageLabelButtonStyle : IImageLabelButtonStyle { /// <summary> /// Gets or sets the button style. /// </summary> /// <value>The button style.</value> public Style ButtonStyle { get; set; } /// <summary> /// Gets or sets the button text. /// </summary> /// <value>The button text.</value> public string ButtonText { get; set; } /// <summary> /// Gets or sets a value indicating whether [get image from resource]. /// </summary> /// <value><c>true</c> if [get image from resource]; otherwise, <c>false</c>.</value> public bool GetImageFromResource { get; set; } /// <summary> /// Gets or sets the image file path. /// </summary> /// <value>The image file path.</value> public string ImageFilePath { get; set; } /// <summary> /// Gets or sets the type of the image resource class. /// </summary> /// <value>The type of the image resource class.</value> public Type ImageResourceClassType { get; set; } /// <summary> /// Gets or sets the state of the internal button. /// </summary> /// <value>The state of the internal button.</value> public string InternalButtonState { get; set; } /// <summary> /// Gets or sets the label style. /// </summary> /// <value>The label style.</value> public Style LabelStyle { get; set; } } }
36.875969
102
0.600378
[ "MIT" ]
marcusts/Com.MarcusTS.SharedForms
Views/Controls/ImageLabelButtonStyle.cs
4,759
C#
using System; using Cake.Common; using Cake.Frosting; public sealed class FormatCode : FrostingTask<Context> { public override void Run(Context context) { int result = context.StartProcess(context.DotNetFormatToolPath); if (result != 0) { throw new Exception($"Failed to execute {context.DotNetFormatToolPath} ({result})"); } } public override bool ShouldRun(Context context) { return context.FormatCode; } }
23.285714
96
0.648262
[ "MIT" ]
maxim-lobanov/octokit.net
build/Tasks/FormatCode.cs
491
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.Immutable; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Navigation { internal interface INavigableItem { Glyph Glyph { get; } /// <summary> /// The tagged parts to display for this item. If default, the line of text from <see cref="Document"/> is used. /// </summary> ImmutableArray<TaggedText> DisplayTaggedParts { get; } /// <summary> /// Return true to display the file path of <see cref="Document"/> and the span of <see cref="SourceSpan"/> when displaying this item. /// </summary> bool DisplayFileLocation { get; } /// <summary> /// his is intended for symbols that are ordinary symbols in the language sense, and may be /// used by code, but that are simply declared implicitly rather than with explicit language /// syntax. For example, a default synthesized constructor in C# when the class contains no /// explicit constructors. /// </summary> bool IsImplicitlyDeclared { get; } Document Document { get; } TextSpan SourceSpan { get; } ImmutableArray<INavigableItem> ChildItems { get; } } }
37.473684
142
0.658006
[ "MIT" ]
06needhamt/roslyn
src/Features/Core/Portable/Navigation/INavigableItem.cs
1,426
C#
using ESRI.ArcLogistics.Utility.CoreEx; using Xceed.Wpf.DataGrid; namespace ESRI.ArcLogistics.App.GridHelpers { /// <summary> /// Helper extension methods for Xceed DataGrid cells. /// </summary> internal static class CellExtensions { /// <summary> /// Marks the specified cell as dirty. /// </summary> /// <param name="cell">The cell object to be marked dirty.</param> /// <exception cref="System.ArgumentNullException"><paramref name="cell"/> is a null /// reference.</exception> public static void MarkDirty(this Cell cell) { CodeContract.RequiresNotNull("cell", cell); var content = cell.Content; cell.Content = new object(); cell.Content = content; } } }
29.888889
92
0.599752
[ "Apache-2.0" ]
Esri/route-planner-csharp
RoutePlanner_DeveloperTools/Source/ArcLogisticsApp/GridHelpers/CellExtensions.cs
809
C#
using MicroOrm.Dapper.Repositories.Tests.DatabaseFixture; using Xunit; using Xunit.Abstractions; namespace MicroOrm.Dapper.Repositories.Tests.RepositoriesTests { public class MsSql2019RepositoriesTests : RepositoriesTests, IClassFixture<MsSql2019DatabaseFixture> { public MsSql2019RepositoriesTests(MsSql2019DatabaseFixture msSqlDatabaseFixture, ITestOutputHelper testOutputHelper) : base(msSqlDatabaseFixture.Db, testOutputHelper) { } // only Databse specific tests } }
31.176471
124
0.766038
[ "MIT" ]
WalterNagelGmbH/dapper-repositories
test/MicroOrm.Dapper.Repositories.Tests/RepositoriesTests/MsSql2019RepositoriesTests.cs
532
C#
 namespace SeeSharper.Northwind.Forms { using Serenity; using Serenity.ComponentModel; using Serenity.Data; using System; using System.Collections.Generic; using System.IO; [ColumnsScript("Northwind.OrderDetail")] [BasedOnRow(typeof(Entities.OrderDetailRow))] public class OrderDetailColumns { [EditLink, Width(200)] public String ProductName { get; set; } [Width(100)] public Decimal UnitPrice { get; set; } [Width(100)] public Int16 Quantity { get; set; } [Width(100)] public Double Discount { get; set; } [Width(100)] public Decimal LineTotal { get; set; } } }
26.5
49
0.619739
[ "MIT" ]
kingajay007/SeeSharper-Master
SeeSharper.Web/Modules/Northwind/OrderDetail/OrderDetailColumns.cs
691
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/codecapi.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using System.Runtime.InteropServices; namespace TerraFX.Interop.Windows; /// <include file='CODECAPI_AVEncVideoIntraLayerPrediction.xml' path='doc/member[@name="CODECAPI_AVEncVideoIntraLayerPrediction"]/*' /> [Guid("D3AF46B8-BF47-44BB-A283-69F0B0228FF9")] public partial struct CODECAPI_AVEncVideoIntraLayerPrediction { }
40.733333
145
0.797054
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
sources/Interop/Windows/Windows/um/codecapi/CODECAPI_AVEncVideoIntraLayerPrediction.cs
613
C#
/* * Copyright 2018 JDCLOUD.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 * * 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. * * Category * 分类管理相关接口 * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; using JDCloudSDK.Core.Service; namespace JDCloudSDK.Vod.Apis { /// <summary> /// 修改分类 /// </summary> public class UpdateCategoryResult : JdcloudResult { ///<summary> /// 分类ID ///</summary> public long? Id{ get; set; } ///<summary> /// 分类名称 ///</summary> public string Name{ get; set; } ///<summary> /// 分类级别。取值范围为 [0, 3],取值为 0 时为虚拟根节点 /// ///</summary> public int? Level{ get; set; } ///<summary> /// 父分类ID,取值为 0 或 null 时,表示该分类为一级分类 /// ///</summary> public long? ParentId{ get; set; } ///<summary> /// 分类描述信息 ///</summary> public string Description{ get; set; } ///<summary> /// 创建时间 ///</summary> public DateTime? CreateTime{ get; set; } ///<summary> /// 修改时间 ///</summary> public DateTime? UpdateTime{ get; set; } } }
25.605634
76
0.578108
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Vod/Apis/UpdateCategoryResult.cs
1,964
C#
using System; using System.Linq; class O { static void Main() { var n = int.Parse(Console.ReadLine()); var a = Enumerable.Range(0, n) .SelectMany(i => Console.ReadLine().Split().Select(int.Parse).Select(x => new { i, x })) .OrderBy(_ => _.x) .Select(_ => _.i) .ToList(); a.Insert(0, 0); var dp = new double[6 * n + 1]; dp[dp.Length - 1] = 1; var e = new double[n]; var M = 0.0; for (int i = dp.Length - 1; i > 0; i--) { e[a[i]] += dp[i] / 6; M = Math.Max(M, e[a[i]]); dp[i - 1] = M + 1; } Console.WriteLine(dp[0]); } }
19.933333
92
0.496656
[ "MIT" ]
sakapon/AtCoder-Contests
CSharp/PAST/PAST201912/O.cs
600
C#
using System.Diagnostics; using Application.Client.Infrastructure.ErrorHandling.DataBinding.Exceptions; namespace Application.Client.Infrastructure.ErrorHandling.DataBinding.TraceListeners { public class BindingErrorTraceListener : TraceListener { public override void Write(string? message) { } public override void WriteLine(string? message) { throw new DataBindingErrorException(message); } } }
27.352941
84
0.72043
[ "MIT" ]
Sullivan008/CSharp-WFA-WindowsNotepadReplication
Application.Client/Infrastructure/ErrorHandling/DataBinding/TraceListeners/BindingErrorTraceListener.cs
467
C#
using System; using System.IO; using System.Net; using System.Net.Sockets; using NUnit.Framework; namespace MongoDB.Driver { [TestFixture()] public class TestB { [Test()] public void TestCase(){ TcpClient client = new TcpClient(); client.Connect("localhost", 27017); BufferedStream buff = new BufferedStream(client.GetStream()); BinaryWriter writer = new BinaryWriter(buff); System.Text.UTF8Encoding encoding=new System.Text.UTF8Encoding(); Byte[] msg = encoding.GetBytes("Hello MongoDB!"); writer.Write(16 + msg.Length + 1); writer.Write(1); writer.Write(1); writer.Write(1000); writer.Write(msg); writer.Write((byte)0); writer.Flush(); writer.Close(); client.Close(); } } }
23.116279
88
0.508048
[ "Apache-2.0" ]
sunnanking/mongodb-csharp
MongoDB.Net-Tests/TestB.cs
994
C#
using System; using WinFormMVP.Model; using WinFormMVP.Model.Repo; using WinFormMVP.View; namespace WinFormMVP.Presenter { public class Form1Presenter : IForm1Presenter { private IFormView _view; private ITextRepository _dataRepo; public Form1Presenter(IFormView view, ITextRepository dataRepo) { _view = view; _dataRepo = dataRepo; } public void NewTextFile(string path, string content) { TryFlow(() => { var textFile = new TxtFile(path, content); var createOK = _dataRepo.Create(textFile); if(createOK) Invoke(() => _view.ShowMessageBox("Create Success")); }); } public void ReadTextFile(string path) { var textFile = new TxtFile(path, string.Empty); var readStr = _dataRepo.Read(textFile); Invoke(() => _view.ShowDataContent(readStr)); } public void SaveTxtFile(string path, string content) { var textFile = new TxtFile(path, content); var updateOK = _dataRepo.Upadate(textFile); if (updateOK) Invoke(() => _view.ShowMessageBox("Update Success")); } protected virtual void TryFlow(Action action) { try { action?.Invoke(); } catch (Exception ex) { Invoke(() => _view.ShowMessageBox(ex.ToString())); } finally { } } /// <summary> /// Update UI /// </summary> protected void Invoke(Action action) { _view.Invoke(action); } } }
25.690141
73
0.501096
[ "MIT" ]
codesensegroup/WindowsFormPattern
WinFormPatternDemo/WinFormMVP/Presenter/Form1Presenter.cs
1,826
C#
using System.Net; using System.Net.Mail; using System.Text; using ExceptionReporting.Mail; using ExceptionReporting.Network.Events; namespace ExceptionReporting.Network.Senders { internal class SmtpMailSender : MailSender, IReportSender { public SmtpMailSender(ExceptionReportInfo reportInfo, IReportSendEvent sendEvent) : base(reportInfo, sendEvent) { } public override string Description { get { return "SMTP"; } } /// <summary> /// Send SMTP email, uses native .NET SmtpClient library /// Requires following ExceptionReportInfo properties to be set: /// SmtpPort, SmtpUseSsl, SmtpUsername, SmtpPassword, SmtpFromAddress, EmailReportAddress /// </summary> public void Send(string report) { var smtp = new SmtpClient(_config.SmtpServer) { DeliveryMethod = SmtpDeliveryMethod.Network, EnableSsl = _config.SmtpUseSsl, UseDefaultCredentials = _config.SmtpUseDefaultCredentials, }; if (_config.SmtpPort != 0) // the default port is used if not set in config smtp.Port = _config.SmtpPort; if (!_config.SmtpUseDefaultCredentials) smtp.Credentials = new NetworkCredential(_config.SmtpUsername, _config.SmtpPassword); var message = new MailMessage(_config.SmtpFromAddress, _config.EmailReportAddress) { BodyEncoding = Encoding.UTF8, SubjectEncoding = Encoding.UTF8, Priority = _config.SmtpMailPriority, Body = report, Subject = EmailSubject }; _attacher.AttachFiles(new AttachAdapter(message)); smtp.SendCompleted += (sender, e) => { try { if (e.Error == null) { _sendEvent.Completed(success: true); } else { _sendEvent.Completed(success: false); _sendEvent.ShowError(string.Format("{0}: ", Description) + (e.Error.InnerException != null ? e.Error.InnerException.Message : e.Error.Message), e.Error); } } finally { message.Dispose(); smtp.Dispose(); } }; smtp.SendAsync(message, "Exception Report"); } } }
26.853333
101
0.695631
[ "MIT" ]
JavierCanon/ExceptionReporter.NET
src/Others/SharkErrorReporter/ExceptionReporter/Network/Senders/SmtpMailSender.cs
2,014
C#
namespace Caliburn.Micro.Contrib.Dialogs { public interface IDialogViewModel<TResponse> { bool? IsClosed { get; set; } Dialog<TResponse> Dialog { get; set; } IObservableCollection<BindableResponse<TResponse>> Responses { get; } void Respond(BindableResponse<TResponse> bindableResponse); } }
33.6
77
0.6875
[ "MIT" ]
kmees/CMContrib
src/CMContrib.SL/Dialogs/IDialogViewModel.cs
338
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace Lykke.Service.PayInternal.Core.Exceptions { public class ExchangeOperationPartiallyFailedException : ExchangeOperationFailedException { public ExchangeOperationPartiallyFailedException() { } public ExchangeOperationPartiallyFailedException(IEnumerable<string> transferErrors) : base(transferErrors) { } public ExchangeOperationPartiallyFailedException(string message, Exception innerException) : base(message, innerException) { } protected ExchangeOperationPartiallyFailedException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
29.576923
131
0.729519
[ "MIT" ]
LykkeCity/Lykke.Service.PayInternal
src/Lykke.Service.PayInternal.Core/Exceptions/ExchangeOperationPartiallyFailedException.cs
771
C#
using System.Reflection; 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("AWSSDK.ComputeOptimizer")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Compute Optimizer. Initial release of AWS Compute Optimizer. AWS Compute Optimizer recommends optimal AWS Compute resources to reduce costs and improve performance for your workloads.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.7.3.5")]
48
267
0.75651
[ "Apache-2.0" ]
ebattalio/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/ComputeOptimizer/Properties/AssemblyInfo.cs
1,536
C#
using System; using System.Collections.Generic; using System.Linq; using Crash.Core.Drawing; using Crash.Core.UI.Controls.ScrollBars.Markers; namespace Crash.Core.UI.Controls.ScrollBars { /// <summary> /// スクロールバー。 /// </summary> public sealed class ScrollBar : UIElement { /// <summary></summary> public event ScrollEventHandler? ValueChanged; /// <summary></summary> public static readonly int Thickness = 17; /// <summary></summary> private int _value; /// <summary></summary> public int Minimum { get; private set; } /// <summary></summary> public int Maximum { get; private set; } /// <summary>スクロール対象領域の全体の長さ。</summary> public int ContentLength => Maximum - Minimum + 1; /// <summary>スクロールボタンを押下した際のスクロール値。</summary> public int ArrowStep { get; private set; } /// <summary>スクロールエリアを押下した際のスクロール値(つまり現在表示中の領域の長さ)。</summary> public int ViewportLength { get; private set; } /// <summary>ユーザー操作によるスクロールの最大値。</summary> public int MaximumByScroll => ContentLength - ViewportLength; /// <summary>スクロールの現在値。</summary> public int Value { get => _value; set => SetValue(value, false); } /// <summary>スクロールバーの操作が可能かどうか。</summary> public bool IsScrollEnabled => ContentLength >= 2 && ArrowStep > 0 && ViewportLength > 0 && ContentLength > ViewportLength; /// <summary>つまみによる操作が可能かどうか。</summary> public bool IsThumbEnabled => IsScrollEnabled && Body.ClientSize.Height >= 15; /// <summary>マーカー表示が可能かどうか。</summary> public bool IsMarkerEnabled => Body.ClientSize.Height >= 15; public IEnumerable<IMarker> Marks { get; private set; } = Enumerable.Empty<IMarker>(); /// <summary></summary> public ScrollBody Body { get; } /// <summary></summary> public ScrollButton PrevButton { get; } /// <summary></summary> public ScrollButton NextButton { get; } /// <summary></summary> public ScrollDirection Direction { get; } /// <summary> /// /// </summary> public ScrollBar(ScrollDirection direction) { Direction = direction; Tnc.AddNode(Body = new ScrollBody(Direction)); Tnc.AddNode(PrevButton = new ScrollButton(Direction, true)); Tnc.AddNode(NextButton = new ScrollButton(Direction, false)); } /// <summary> /// /// </summary> public void SettingScrollByContentLength(int contentLength, int arrowStep, int viewportLength) { SettingScroll(0, contentLength - 1, arrowStep, viewportLength); } /// <summary> /// /// </summary> public void SettingScroll(int minimum, int maximum, int arrowStep, int viewportLength) { Verifier.Verify<ArgumentException>(maximum > minimum); Verifier.Verify<ArgumentException>(arrowStep > 0); Verifier.Verify<ArgumentException>(viewportLength > 0); Verifier.Verify<ArgumentException>(viewportLength >= arrowStep); if ((Minimum, Maximum, ArrowStep, ViewportLength) != (minimum, maximum, arrowStep, viewportLength)) { (Minimum, Maximum, ArrowStep, ViewportLength) = (minimum, maximum, arrowStep, viewportLength); SetValue(_value, true); } } /// <summary> /// /// </summary> private void SetValue(int newValue, bool isForceUpdateLayout) { var oldValue = _value; _value = ToNormalizedValue(newValue); if (_value != oldValue) { ValueChanged?.Invoke(_value); } if (_value != oldValue || isForceUpdateLayout) { UpdateLayout(); } } /// <summary> /// /// </summary> private int ToNormalizedValue(int value) { return IsScrollEnabled ? MathUtil.Clamp(value, Minimum, MaximumByScroll) : Minimum; } /// <summary> /// /// </summary> public bool IsInRangeValue(int value) { return MathUtil.IsInRange(value, Minimum, Maximum); } /// <summary> /// /// </summary> public bool IsInRangeValueByScroll(int value) { return MathUtil.IsInRange(value, Minimum, MaximumByScroll); } public void SetMarks(IEnumerable<IMarker> marks) { Marks = marks; } /// <summary> /// /// </summary> protected override Rect2D ArrangeElement() { switch (Direction) { case ScrollDirection.Vertical: var left = Tnc.GetParent().ClientSize.Width - ScrollBar.Thickness; var height = Tnc.GetParent().ClientSize.Height - ScrollBar.Thickness; return new Rect2D(left, 0, ScrollBar.Thickness, height); case ScrollDirection.Horizontal: var top = Tnc.GetParent().ClientSize.Height - ScrollBar.Thickness; var width = Tnc.GetParent().ClientSize.Width - ScrollBar.Thickness; return new Rect2D(0, top, width, ScrollBar.Thickness); default: throw new InvalidOperationException(); } } } /// <summary> /// /// </summary> public delegate void ScrollEventHandler(int value); /// <summary> /// /// </summary> public enum ScrollDirection { Vertical, Horizontal, } }
30.705263
131
0.557079
[ "MIT" ]
yoshiheight/Crash.Editor
Crash.Core.UI/Controls/ScrollBars/ScrollBar.cs
6,158
C#
/* * Class: DownloadEventArgs * Author: Pradeep Singh * Date: 3 July 2016 * Change Log: * 3 July 2016: Created the class. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using BringDownClient.Logic.Core; namespace BringDownClient.Logic { public class DownloadEventArgs : EventArgs { public int TotalItems { get; private set; } public int ItemsCompleted { get; private set; } public int ItemsFailed { get; private set; } public DownloadEventArgs(int totalItem, int itemsCompleted = 0, int itemsFailed = 0) { TotalItems = totalItem; ItemsCompleted = itemsCompleted; ItemsFailed = itemsFailed; } } }
24.16129
92
0.65287
[ "MIT" ]
pradeep-pioneer/BringDown
BringDownClient/BringDownClient.Logic/DownloadEventArgs.cs
751
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.DataFactory.V20180601.Outputs { /// <summary> /// Azure ML Update Resource management activity. /// </summary> [OutputType] public sealed class AzureMLUpdateResourceActivityResponse { /// <summary> /// Activity depends on condition. /// </summary> public readonly ImmutableArray<Outputs.ActivityDependencyResponse> DependsOn; /// <summary> /// Activity description. /// </summary> public readonly string? Description; /// <summary> /// Linked service reference. /// </summary> public readonly Outputs.LinkedServiceReferenceResponse? LinkedServiceName; /// <summary> /// Activity name. /// </summary> public readonly string Name; /// <summary> /// Activity policy. /// </summary> public readonly Outputs.ActivityPolicyResponse? Policy; /// <summary> /// The relative file path in trainedModelLinkedService to represent the .ilearner file that will be uploaded by the update operation. Type: string (or Expression with resultType string). /// </summary> public readonly object TrainedModelFilePath; /// <summary> /// Name of Azure Storage linked service holding the .ilearner file that will be uploaded by the update operation. /// </summary> public readonly Outputs.LinkedServiceReferenceResponse TrainedModelLinkedServiceName; /// <summary> /// Name of the Trained Model module in the Web Service experiment to be updated. Type: string (or Expression with resultType string). /// </summary> public readonly object TrainedModelName; /// <summary> /// Type of activity. /// Expected value is 'AzureMLUpdateResource'. /// </summary> public readonly string Type; /// <summary> /// Activity user properties. /// </summary> public readonly ImmutableArray<Outputs.UserPropertyResponse> UserProperties; [OutputConstructor] private AzureMLUpdateResourceActivityResponse( ImmutableArray<Outputs.ActivityDependencyResponse> dependsOn, string? description, Outputs.LinkedServiceReferenceResponse? linkedServiceName, string name, Outputs.ActivityPolicyResponse? policy, object trainedModelFilePath, Outputs.LinkedServiceReferenceResponse trainedModelLinkedServiceName, object trainedModelName, string type, ImmutableArray<Outputs.UserPropertyResponse> userProperties) { DependsOn = dependsOn; Description = description; LinkedServiceName = linkedServiceName; Name = name; Policy = policy; TrainedModelFilePath = trainedModelFilePath; TrainedModelLinkedServiceName = trainedModelLinkedServiceName; TrainedModelName = trainedModelName; Type = type; UserProperties = userProperties; } } }
35.84375
196
0.642546
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/DataFactory/V20180601/Outputs/AzureMLUpdateResourceActivityResponse.cs
3,441
C#
namespace EventSourcing.UserInterface { partial class AttendanceOverviewControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.splitContainer = new System.Windows.Forms.SplitContainer(); this.dataGridViewOverview = new System.Windows.Forms.DataGridView(); this.panelLowerHalf = new System.Windows.Forms.Panel(); this.comboBox = new System.Windows.Forms.ComboBox(); this.buttonManuallyCommit = new System.Windows.Forms.Button(); this.buttonCommitAttendanceChange = new System.Windows.Forms.Button(); this.userBindingSource = new System.Windows.Forms.BindingSource(this.components); this.attendanceBindingSource = new System.Windows.Forms.BindingSource(this.components); ((System.ComponentModel.ISupportInitialize)(this.splitContainer)).BeginInit(); this.splitContainer.Panel1.SuspendLayout(); this.splitContainer.Panel2.SuspendLayout(); this.splitContainer.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewOverview)).BeginInit(); this.panelLowerHalf.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.userBindingSource)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.attendanceBindingSource)).BeginInit(); this.SuspendLayout(); // // splitContainer // this.splitContainer.Dock = System.Windows.Forms.DockStyle.Fill; this.splitContainer.Location = new System.Drawing.Point(0, 0); this.splitContainer.Name = "splitContainer"; this.splitContainer.Orientation = System.Windows.Forms.Orientation.Horizontal; // // splitContainer.Panel1 // this.splitContainer.Panel1.Controls.Add(this.dataGridViewOverview); // // splitContainer.Panel2 // this.splitContainer.Panel2.Controls.Add(this.panelLowerHalf); this.splitContainer.Size = new System.Drawing.Size(566, 279); this.splitContainer.SplitterDistance = 244; this.splitContainer.TabIndex = 0; // // dataGridViewOverview // this.dataGridViewOverview.AllowUserToAddRows = false; this.dataGridViewOverview.AllowUserToDeleteRows = false; this.dataGridViewOverview.AutoGenerateColumns = false; this.dataGridViewOverview.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridViewOverview.DataSource = this.attendanceBindingSource; this.dataGridViewOverview.Dock = System.Windows.Forms.DockStyle.Fill; this.dataGridViewOverview.Location = new System.Drawing.Point(0, 0); this.dataGridViewOverview.Name = "dataGridViewOverview"; this.dataGridViewOverview.Size = new System.Drawing.Size(566, 244); this.dataGridViewOverview.TabIndex = 1; // // panelLowerHalf // this.panelLowerHalf.Controls.Add(this.comboBox); this.panelLowerHalf.Controls.Add(this.buttonManuallyCommit); this.panelLowerHalf.Controls.Add(this.buttonCommitAttendanceChange); this.panelLowerHalf.Dock = System.Windows.Forms.DockStyle.Fill; this.panelLowerHalf.Location = new System.Drawing.Point(0, 0); this.panelLowerHalf.Name = "panelLowerHalf"; this.panelLowerHalf.Size = new System.Drawing.Size(566, 31); this.panelLowerHalf.TabIndex = 0; // // comboBox // this.comboBox.DataSource = this.userBindingSource; this.comboBox.DisplayMember = "Nick"; this.comboBox.FormattingEnabled = true; this.comboBox.Location = new System.Drawing.Point(4, 4); this.comboBox.Name = "comboBox"; this.comboBox.Size = new System.Drawing.Size(152, 21); this.comboBox.TabIndex = 5; this.comboBox.SelectedValueChanged += new System.EventHandler(this.comboBox_SelectedValueChanged); // // buttonManuallyCommit // this.buttonManuallyCommit.Location = new System.Drawing.Point(473, 3); this.buttonManuallyCommit.Name = "buttonManuallyCommit"; this.buttonManuallyCommit.Size = new System.Drawing.Size(90, 23); this.buttonManuallyCommit.TabIndex = 4; this.buttonManuallyCommit.Text = "More"; this.buttonManuallyCommit.UseVisualStyleBackColor = true; this.buttonManuallyCommit.Click += new System.EventHandler(this.buttonManuallyCommit_Click); // // buttonCommitAttendanceChange // this.buttonCommitAttendanceChange.Location = new System.Drawing.Point(392, 3); this.buttonCommitAttendanceChange.Name = "buttonCommitAttendanceChange"; this.buttonCommitAttendanceChange.Size = new System.Drawing.Size(75, 23); this.buttonCommitAttendanceChange.TabIndex = 0; this.buttonCommitAttendanceChange.Text = "Commit"; this.buttonCommitAttendanceChange.UseVisualStyleBackColor = true; // // userBindingSource // this.userBindingSource.DataSource = typeof(DomainModel.Users.User); // // attendanceBindingSource // this.attendanceBindingSource.DataSource = typeof(DomainModel.Attendance.Attendance); // // AttendanceOverviewControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.splitContainer); this.Name = "AttendanceOverviewControl"; this.Size = new System.Drawing.Size(566, 279); this.Load += new System.EventHandler(this.AttendanceOverviewControl_Load); this.splitContainer.Panel1.ResumeLayout(false); this.splitContainer.Panel2.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.splitContainer)).EndInit(); this.splitContainer.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.dataGridViewOverview)).EndInit(); this.panelLowerHalf.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.userBindingSource)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.attendanceBindingSource)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.SplitContainer splitContainer; private System.Windows.Forms.DataGridView dataGridViewOverview; private System.Windows.Forms.Panel panelLowerHalf; private System.Windows.Forms.Button buttonCommitAttendanceChange; private System.Windows.Forms.Button buttonManuallyCommit; private System.Windows.Forms.ComboBox comboBox; private System.Windows.Forms.BindingSource userBindingSource; private System.Windows.Forms.BindingSource attendanceBindingSource; } }
50.95679
138
0.644337
[ "MIT" ]
xfleckx/EventSourcing
EventSourcing/UserInterface/AttendanceOverviewControl.Designer.cs
8,257
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // ------------------------------------------------------------ namespace Microsoft.Azure.Cosmos { using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Cosmos.ChangeFeed; /// <summary> /// Base class for where to start a ChangeFeed operation in <see cref="ChangeFeedRequestOptions"/>. /// </summary> /// <remarks>Use one of the static constructors to generate a StartFrom option.</remarks> #if PREVIEW public #else internal #endif abstract class ChangeFeedStartFrom { /// <summary> /// Initializes an instance of the <see cref="ChangeFeedStartFrom"/> class. /// </summary> internal ChangeFeedStartFrom() { // Internal so people can't derive from this type. } internal abstract void Accept(ChangeFeedStartFromVisitor visitor); internal abstract TResult Accept<TResult>(ChangeFeedStartFromVisitor<TResult> visitor); internal abstract Task<TResult> AcceptAsync<TInput, TResult>(ChangeFeedStartFromAsyncVisitor<TInput, TResult> visitor, TInput input, CancellationToken cancellationToken); /// <summary> /// Creates a <see cref="ChangeFeedStartFrom"/> that tells the ChangeFeed operation to start reading changes from this moment onward. /// </summary> /// <returns>A <see cref="ChangeFeedStartFrom"/> that tells the ChangeFeed operation to start reading changes from this moment onward.</returns> public static ChangeFeedStartFrom Now() { return Now(FeedRangeEpk.FullRange); } /// <summary> /// Creates a <see cref="ChangeFeedStartFrom"/> that tells the ChangeFeed operation to start reading changes from this moment onward. /// </summary> /// <param name="feedRange">The range to start from.</param> /// <returns>A <see cref="ChangeFeedStartFrom"/> that tells the ChangeFeed operation to start reading changes from this moment onward.</returns> public static ChangeFeedStartFrom Now(FeedRange feedRange) { if (!(feedRange is FeedRangeInternal feedRangeInternal)) { throw new ArgumentException($"{nameof(feedRange)} needs to be a {nameof(FeedRangeInternal)}."); } return new ChangeFeedStartFromNow(feedRangeInternal); } /// <summary> /// Creates a <see cref="ChangeFeedStartFrom"/> that tells the ChangeFeed operation to start reading changes from some point in time onward. /// </summary> /// <param name="dateTimeUtc">The time (in UTC) to start reading from.</param> /// <returns>A <see cref="ChangeFeedStartFrom"/> that tells the ChangeFeed operation to start reading changes from some point in time onward.</returns> public static ChangeFeedStartFrom Time(DateTime dateTimeUtc) { return Time(dateTimeUtc, FeedRangeEpk.FullRange); } /// <summary> /// Creates a <see cref="ChangeFeedStartFrom"/> that tells the ChangeFeed operation to start reading changes from some point in time onward. /// </summary> /// <param name="dateTimeUtc">The time to start reading from.</param> /// <param name="feedRange">The range to start from.</param> /// <returns>A <see cref="ChangeFeedStartFrom"/> that tells the ChangeFeed operation to start reading changes from some point in time onward.</returns> public static ChangeFeedStartFrom Time(DateTime dateTimeUtc, FeedRange feedRange) { if (!(feedRange is FeedRangeInternal feedRangeInternal)) { throw new ArgumentException($"{nameof(feedRange)} needs to be a {nameof(FeedRangeInternal)}."); } return new ChangeFeedStartFromTime(dateTimeUtc, feedRangeInternal); } /// <summary> /// Creates a <see cref="ChangeFeedStartFrom"/> that tells the ChangeFeed operation to start reading changes from a save point. /// </summary> /// <param name="continuationToken">The continuation to resume from.</param> /// <returns>A <see cref="ChangeFeedStartFrom"/> that tells the ChangeFeed operation to start reading changes from a save point.</returns> public static ChangeFeedStartFrom ContinuationToken(string continuationToken) { return new ChangeFeedStartFromContinuation(continuationToken); } /// <summary> /// Creates a <see cref="ChangeFeedStartFrom"/> that tells the ChangeFeed operation to start from the beginning of time. /// </summary> /// <returns>A <see cref="ChangeFeedStartFrom"/> that tells the ChangeFeed operation to start reading changes from the beginning of time.</returns> public static ChangeFeedStartFrom Beginning() { return Beginning(FeedRangeEpk.FullRange); } /// <summary> /// Creates a <see cref="ChangeFeedStartFrom"/> that tells the ChangeFeed operation to start from the beginning of time. /// </summary> /// <param name="feedRange">The range to start from.</param> /// <returns>A <see cref="ChangeFeedStartFrom"/> that tells the ChangeFeed operation to start reading changes from the beginning of time.</returns> public static ChangeFeedStartFrom Beginning(FeedRange feedRange) { if (!(feedRange is FeedRangeInternal feedRangeInternal)) { throw new ArgumentException($"{nameof(feedRange)} needs to be a {nameof(FeedRangeInternal)}."); } return new ChangeFeedStartFromBeginning(feedRangeInternal); } } }
47.967213
178
0.646787
[ "MIT" ]
FabianMeiswinkel/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/src/ChangeFeed/ChangeFeedStartFrom.cs
5,854
C#
using System; using System.IO; using System.Linq; using System.Numerics; using System.Security.Cryptography; namespace DCL_Core.Cryptography { /* Ported and refactored from Java to C# by Hans Wolff, 10/10/2013 * Released to the public domain * / /* Java code written by k3d3 * Source: https://github.com/k3d3/ed25519-java/blob/master/ed25519.java * Released to the public domain */ public class Ed25519 { private static byte[] ComputeHash(byte[] m) { using (var sha512 = SHA512Managed.Create()) { return sha512.ComputeHash(m); } } private static BigInteger ExpMod(BigInteger number, BigInteger exponent, BigInteger modulo) { if (exponent.Equals(BigInteger.Zero)) { return BigInteger.One; } BigInteger t = BigInteger.Pow(ExpMod(number, exponent / Two, modulo), 2).Mod(modulo); if (!exponent.IsEven) { t *= number; t = t.Mod(modulo); } return t; } private static BigInteger Inv(BigInteger x) { return ExpMod(x, Qm2, Q); } private static BigInteger RecoverX(BigInteger y) { BigInteger y2 = y * y; BigInteger xx = (y2 - 1) * Inv(D * y2 + 1); BigInteger x = ExpMod(xx, Qp3 / Eight, Q); if (!(x * x - xx).Mod(Q).Equals(BigInteger.Zero)) { x = (x * I).Mod(Q); } if (!x.IsEven) { x = Q - x; } return x; } private static Tuple<BigInteger, BigInteger> Edwards(BigInteger px, BigInteger py, BigInteger qx, BigInteger qy) { BigInteger xx12 = px * qx; BigInteger yy12 = py * qy; BigInteger dtemp = D * xx12 * yy12; BigInteger x3 = (px * qy + qx * py) * (Inv(1 + dtemp)); BigInteger y3 = (py * qy + xx12) * (Inv(1 - dtemp)); return new Tuple<BigInteger, BigInteger>(x3.Mod(Q), y3.Mod(Q)); } private static Tuple<BigInteger, BigInteger> EdwardsSquare(BigInteger x, BigInteger y) { BigInteger xx = x * x; BigInteger yy = y * y; BigInteger dtemp = D * xx * yy; BigInteger x3 = (2 * x * y) * (Inv(1 + dtemp)); BigInteger y3 = (yy + xx) * (Inv(1 - dtemp)); return new Tuple<BigInteger, BigInteger>(x3.Mod(Q), y3.Mod(Q)); } private static Tuple<BigInteger, BigInteger> ScalarMul(Tuple<BigInteger, BigInteger> p, BigInteger e) { if (e.Equals(BigInteger.Zero)) { return new Tuple<BigInteger, BigInteger>(BigInteger.Zero, BigInteger.One); } var q = ScalarMul(p, e / Two); q = EdwardsSquare(q.Item1, q.Item2); if (!e.IsEven) q = Edwards(q.Item1, q.Item2, p.Item1, p.Item2); return q; } public static byte[] EncodeInt(BigInteger y) { byte[] nin = y.ToByteArray(); var nout = new byte[Math.Max(nin.Length, 32)]; Array.Copy(nin, nout, nin.Length); return nout; } public static byte[] EncodePoint(BigInteger x, BigInteger y) { byte[] nout = EncodeInt(y); nout[nout.Length - 1] |= (x.IsEven ? (byte)0 : (byte)0x80); return nout; } private static int GetBit(byte[] h, int i) { return h[i / 8] >> (i % 8) & 1; } public static byte[] PublicKey(byte[] signingKey) { byte[] h = ComputeHash(signingKey); BigInteger a = TwoPowBitLengthMinusTwo; for (int i = 3; i < (BitLength - 2); i++) { var bit = GetBit(h, i); if (bit != 0) { a += TwoPowCache[i]; } } var bigA = ScalarMul(B, a); return EncodePoint(bigA.Item1, bigA.Item2); } private static BigInteger HashInt(byte[] m) { byte[] h = ComputeHash(m); BigInteger hsum = BigInteger.Zero; for (int i = 0; i < 2 * BitLength; i++) { var bit = GetBit(h, i); if (bit != 0) { hsum += TwoPowCache[i]; } } return hsum; } public static byte[] Signature(byte[] message, byte[] signingKey, byte[] publicKey) { byte[] h = ComputeHash(signingKey); BigInteger a = TwoPowBitLengthMinusTwo; for (int i = 3; i < (BitLength - 2); i++) { var bit = GetBit(h, i); if (bit != 0) { a += TwoPowCache[i]; } } BigInteger r; using (var rsub = new MemoryStream((BitLength / 8) + message.Length)) { rsub.Write(h, BitLength / 8, BitLength / 4 - BitLength / 8); rsub.Write(message, 0, message.Length); r = HashInt(rsub.ToArray()); } var bigR = ScalarMul(B, r); BigInteger s; var encodedBigR = EncodePoint(bigR.Item1, bigR.Item2); using (var stemp = new MemoryStream(32 + publicKey.Length + message.Length)) { stemp.Write(encodedBigR, 0, encodedBigR.Length); stemp.Write(publicKey, 0, publicKey.Length); stemp.Write(message, 0, message.Length); s = (r + HashInt(stemp.ToArray()) * a).Mod(L); } using (var nout = new MemoryStream(64)) { nout.Write(encodedBigR, 0, encodedBigR.Length); var encodeInt = EncodeInt(s); nout.Write(encodeInt, 0, encodeInt.Length); return nout.ToArray(); } } private static bool IsOnCurve(BigInteger x, BigInteger y) { BigInteger xx = x * x; BigInteger yy = y * y; BigInteger dxxyy = D * yy * xx; return (yy - xx - dxxyy - 1).Mod(Q).Equals(BigInteger.Zero); } private static BigInteger DecodeInt(byte[] s) { return new BigInteger(s) & Un; } private static Tuple<BigInteger, BigInteger> DecodePoint(byte[] pointBytes) { BigInteger y = new BigInteger(pointBytes) & Un; BigInteger x = RecoverX(y); if ((x.IsEven ? 0 : 1) != GetBit(pointBytes, BitLength - 1)) { x = Q - x; } var point = new Tuple<BigInteger, BigInteger>(x, y); if (!IsOnCurve(x, y)) throw new ArgumentException("Decoding point that is not on curve"); return point; } public static bool CheckValid(byte[] signature, byte[] message, byte[] publicKey) { if (signature.Length != BitLength / 4) throw new ArgumentException("Signature length is wrong"); if (publicKey.Length != BitLength / 8) throw new ArgumentException("Public key length is wrong"); byte[] rByte = Arrays.CopyOfRange(signature, 0, BitLength / 8); var r = DecodePoint(rByte); var a = DecodePoint(publicKey); byte[] sByte = Arrays.CopyOfRange(signature, BitLength / 8, BitLength / 4); BigInteger s = DecodeInt(sByte); BigInteger h; using (var stemp = new MemoryStream(32 + publicKey.Length + message.Length)) { var encodePoint = EncodePoint(r.Item1, r.Item2); stemp.Write(encodePoint, 0, encodePoint.Length); stemp.Write(publicKey, 0, publicKey.Length); stemp.Write(message, 0, message.Length); h = HashInt(stemp.ToArray()); } var ra = ScalarMul(B, s); var ah = ScalarMul(a, h); var rb = Edwards(r.Item1, r.Item2, ah.Item1, ah.Item2); if (!ra.Item1.Equals(rb.Item1) || !ra.Item2.Equals(rb.Item2)) return false; return true; } private const int BitLength = 256; private static readonly BigInteger TwoPowBitLengthMinusTwo = BigInteger.Pow(2, BitLength - 2); private static readonly BigInteger[] TwoPowCache = Enumerable.Range(0, 2 * BitLength).Select(i => BigInteger.Pow(2, i)).ToArray(); private static readonly BigInteger Q = BigInteger.Parse("57896044618658097711785492504343953926634992332820282019728792003956564819949"); private static readonly BigInteger Qm2 = BigInteger.Parse("57896044618658097711785492504343953926634992332820282019728792003956564819947"); private static readonly BigInteger Qp3 = BigInteger.Parse("57896044618658097711785492504343953926634992332820282019728792003956564819952"); private static readonly BigInteger L = BigInteger.Parse("7237005577332262213973186563042994240857116359379907606001950938285454250989"); private static readonly BigInteger D = BigInteger.Parse("-4513249062541557337682894930092624173785641285191125241628941591882900924598840740"); private static readonly BigInteger I = BigInteger.Parse("19681161376707505956807079304988542015446066515923890162744021073123829784752"); private static readonly BigInteger By = BigInteger.Parse("46316835694926478169428394003475163141307993866256225615783033603165251855960"); private static readonly BigInteger Bx = BigInteger.Parse("15112221349535400772501151409588531511454012693041857206046113283949847762202"); private static readonly Tuple<BigInteger, BigInteger> B = new Tuple<BigInteger, BigInteger>(Bx.Mod(Q), By.Mod(Q)); private static readonly BigInteger Un = BigInteger.Parse("57896044618658097711785492504343953926634992332820282019728792003956564819967"); private static readonly BigInteger Two = new BigInteger(2); private static readonly BigInteger Eight = new BigInteger(8); } internal static class Arrays { public static byte[] CopyOfRange(byte[] original, int from, int to) { int length = to - from; var result = new byte[length]; Array.Copy(original, from, result, 0, length); return result; } } internal static class BigIntegerHelpers { public static BigInteger Mod(this BigInteger num, BigInteger modulo) { var result = num % modulo; return result < 0 ? result + modulo : result; } } }
36.855219
138
0.545313
[ "MIT" ]
JohnJohnssonnl/DCL
DCL_Core/Cryptography/ED25519.cs
10,948
C#
using Flunt.Notifications; using MediatR; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace DemoJwt.Application.Core { public class RequestsValidationMiddleware<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse> where TRequest : Request<Response> where TResponse : Response { public Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next) { return request.Invalid ? Errors(request.Notifications) : next(); } private static Task<TResponse> Errors(IEnumerable<Notification> notifications) { var response = new Response(); response.AddNotifications(notifications); return Task.FromResult(response as TResponse); } } }
30.896552
132
0.675223
[ "MIT" ]
CASSIOSOUZA/DemoJwt
src/DemoJwt.Application/Core/RequestsValidationMiddleware.cs
898
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using EchonestApi.Core.Artist; using GalaSoft.MvvmLight.Command; using Meridian.Controls; using Meridian.Model; using Meridian.Services; using Meridian.View.Flyouts; using Neptune.Messages; namespace Meridian.ViewModel.Main { public class RadioViewModel : ViewModelBase { private ObservableCollection<RadioStation> _stations; #region Commands public RelayCommand CreateStationCommand { get; private set; } public RelayCommand<RadioStation> PlayStationCommand { get; private set; } public RelayCommand<RadioStation> EditStationCommand { get; private set; } public RelayCommand<RadioStation> RemoveStationCommand { get; private set; } #endregion public ObservableCollection<RadioStation> Stations { get { return _stations; } set { Set(ref _stations, value); } } public RadioViewModel() { _stations = new ObservableCollection<RadioStation>(); InitializeCommands(); Activate(); } public async void Activate() { IsWorking = true; var stations = await RadioService.LoadStations(); if (stations != null) Stations = new ObservableCollection<RadioStation>(stations); IsWorking = false; } private void InitializeCommands() { CreateStationCommand = new RelayCommand(async () => { var flyout = new FlyoutControl(); flyout.FlyoutContent = new CreateRadioStationView(); var artists = await flyout.ShowAsync() as IList<EchoArtist>; if (artists != null) { AddStation(artists); } }); PlayStationCommand = new RelayCommand<RadioStation>(station => { RadioService.PlayRadio(station); MessengerInstance.Send(new NavigateToPageMessage() { Page = "/Main.NowPlayingView" }); }); RemoveStationCommand = new RelayCommand<RadioStation>(station => { Stations.Remove(station); RadioService.SaveStations(Stations); }); EditStationCommand = new RelayCommand<RadioStation>(async station => { var createRadioStationView = new CreateRadioStationView(); createRadioStationView.Artists = new ObservableCollection<EchoArtist>(station.Artists); var flyout = new FlyoutControl(); flyout.FlyoutContent = createRadioStationView; var artists = await flyout.ShowAsync() as IList<EchoArtist>; if (artists != null) { var titleArtist = station.Artists.First(); station.Artists = artists.ToList(); //update image and title station.Title = string.Join(", ", station.Artists.Select(s => s.Name)); if (station.Artists.First().Name != titleArtist.Name) { station.ImageUrl = null; try { var artistImage = await DataService.GetArtistImage(station.Artists.First().Name, false); if (artistImage != null) station.ImageUrl = artistImage.OriginalString; } catch (Exception ex) { LoggingService.Log(ex); } } RadioService.SaveStations(Stations); } }); } private async void AddStation(IEnumerable<EchoArtist> artists) { var titleArtist = artists.First(); var newStation = new RadioStation() { Artists = artists.ToList(), Title = string.Join(", ", artists.Select(s => s.Name)), }; Stations.Add(newStation); try { var artistImage = await DataService.GetArtistImage(titleArtist.Name, false); if (artistImage != null) newStation.ImageUrl = artistImage.OriginalString; } catch (Exception ex) { LoggingService.Log(ex); } RadioService.SaveStations(Stations); } } }
31.456376
116
0.53211
[ "Apache-2.0" ]
TheELLCRO/Meridian
Meridian/ViewModel/Main/RadioViewModel.cs
4,689
C#
//#define Trace // WinZipAes.cs // ------------------------------------------------------------------ // // Copyright (c) 2009 Dino Chiesa. // All rights reserved. // // This code module is part of DotNetZip, a zipfile class library. // // ------------------------------------------------------------------ // // This code is licensed under the Microsoft Public License. // See the file License.txt for the license details. // More info on: http://dotnetzip.codeplex.com // // ------------------------------------------------------------------ // // last saved (in emacs): // Time-stamp: <2009-November-04 02:01:08> // // ------------------------------------------------------------------ // // This module defines the classes for dealing with WinZip's AES encryption, // according to the specifications for the format available on WinZip's website. // // Created: January 2009 // // ------------------------------------------------------------------ using System; using System.IO; using System.Collections.Generic; using System.Security.Cryptography; #if AESCRYPTO namespace Ionic.Zip { /// <summary> /// This is a helper class supporting WinZip AES encryption. /// This class is intended for use only by the DotNetZip library. /// </summary> /// <remarks> /// Most uses of the DotNetZip library will not involve direct calls into the /// WinZipAesCrypto class. Instead, the WinZipAesCrypto class is instantiated and /// used by the ZipEntry() class when WinZip AES encryption or decryption on an /// entry is employed. /// </remarks> internal class WinZipAesCrypto { internal byte[] _Salt; internal byte[] _providedPv; internal byte[] _generatedPv; internal int _KeyStrengthInBits; private byte[] _MacInitializationVector; private byte[] _StoredMac; private byte[] _keyBytes; private Int16 PasswordVerificationStored; private Int16 PasswordVerificationGenerated; private int Rfc2898KeygenIterations = 1000; private string _Password; private bool _cryptoGenerated ; private WinZipAesCrypto(string password, int KeyStrengthInBits) { _Password = password; _KeyStrengthInBits = KeyStrengthInBits; } //private WinZipAesCrypto() //{ //} public static WinZipAesCrypto Generate(string password, int KeyStrengthInBits) { WinZipAesCrypto c = new WinZipAesCrypto(password, KeyStrengthInBits); int saltSizeInBytes = c._KeyStrengthInBytes / 2; c._Salt = new byte[saltSizeInBytes]; Random rnd = new Random(); rnd.NextBytes(c._Salt); return c; } public static WinZipAesCrypto ReadFromStream(string password, int KeyStrengthInBits, Stream s) { // from http://www.winzip.com/aes_info.htm // // Size(bytes) Content // ----------------------------------- // Variable Salt value // 2 Password verification value // Variable Encrypted file data // 10 Authentication code // // ZipEntry.CompressedSize represents the size of all of those elements. // salt size varies with key length: // 128 bit key => 8 bytes salt // 192 bits => 12 bytes salt // 256 bits => 16 bytes salt WinZipAesCrypto c = new WinZipAesCrypto(password, KeyStrengthInBits); int saltSizeInBytes = c._KeyStrengthInBytes / 2; c._Salt = new byte[saltSizeInBytes]; c._providedPv = new byte[2]; s.Read(c._Salt, 0, c._Salt.Length); s.Read(c._providedPv, 0, c._providedPv.Length); c.PasswordVerificationStored = (Int16)(c._providedPv[0] + c._providedPv[1] * 256); if (password != null) { c.PasswordVerificationGenerated = (Int16)(c.GeneratedPV[0] + c.GeneratedPV[1] * 256); if (c.PasswordVerificationGenerated != c.PasswordVerificationStored) throw new BadPasswordException("bad password"); } return c; } public byte[] GeneratedPV { get { if (!_cryptoGenerated) _GenerateCryptoBytes(); return _generatedPv; } } public byte[] Salt { get { return _Salt; } } private int _KeyStrengthInBytes { get { return _KeyStrengthInBits / 8; } } public int SizeOfEncryptionMetadata { get { // 10 bytes after, (n-10) before the compressed data return _KeyStrengthInBytes / 2 + 10 + 2; } } public string Password { set { _Password = value; if (_Password != null) { PasswordVerificationGenerated = (Int16)(GeneratedPV[0] + GeneratedPV[1] * 256); if (PasswordVerificationGenerated != PasswordVerificationStored) throw new Ionic.Zip.BadPasswordException(); } } } private void _GenerateCryptoBytes() { //Console.WriteLine(" provided password: '{0}'", _Password); System.Security.Cryptography.Rfc2898DeriveBytes rfc2898 = new System.Security.Cryptography.Rfc2898DeriveBytes(_Password, Salt, Rfc2898KeygenIterations); _keyBytes = rfc2898.GetBytes(_KeyStrengthInBytes); // 16 or 24 or 32 ??? _MacInitializationVector = rfc2898.GetBytes(_KeyStrengthInBytes); _generatedPv = rfc2898.GetBytes(2); _cryptoGenerated = true; } public byte[] KeyBytes { get { if (!_cryptoGenerated) _GenerateCryptoBytes(); return _keyBytes; } } public byte[] MacIv { get { if (!_cryptoGenerated) _GenerateCryptoBytes(); return _MacInitializationVector; } } public byte[] CalculatedMac; public void ReadAndVerifyMac(System.IO.Stream s) { bool invalid = false; // read integrityCheckVector. // caller must ensure that the file pointer is in the right spot! _StoredMac = new byte[10]; // aka "authentication code" s.Read(_StoredMac, 0, _StoredMac.Length); if (_StoredMac.Length != CalculatedMac.Length) invalid = true; if (!invalid) { for (int i = 0; i < _StoredMac.Length; i++) { if (_StoredMac[i] != CalculatedMac[i]) invalid = true; } } if (invalid) throw new Ionic.Zip.BadStateException("The MAC does not match."); } } #region DONT_COMPILE_BUT_KEEP_FOR_POTENTIAL_FUTURE_USE #if NO internal class Util { private static void _Format(System.Text.StringBuilder sb1, byte[] b, int offset, int length) { System.Text.StringBuilder sb2 = new System.Text.StringBuilder(); sb1.Append("0000 "); int i; for (i = 0; i < length; i++) { int x = offset+i; if (i != 0 && i % 16 == 0) { sb1.Append(" ") .Append(sb2) .Append("\n") .Append(String.Format("{0:X4} ", i)); sb2.Remove(0,sb2.Length); } sb1.Append(System.String.Format("{0:X2} ", b[x])); if (b[x] >=32 && b[x] <= 126) sb2.Append((char)b[x]); else sb2.Append("."); } if (sb2.Length > 0) { sb1.Append(new String(' ', ((16 - i%16) * 3) + 4)) .Append(sb2); } } internal static string FormatByteArray(byte[] b, int limit) { System.Text.StringBuilder sb1 = new System.Text.StringBuilder(); if ((limit * 2 > b.Length) || limit == 0) { _Format(sb1, b, 0, b.Length); } else { // first N bytes of the buffer _Format(sb1, b, 0, limit); if (b.Length > limit * 2) sb1.Append(String.Format("\n ...({0} other bytes here)....\n", b.Length - limit * 2)); // last N bytes of the buffer _Format(sb1, b, b.Length - limit, limit); } return sb1.ToString(); } internal static string FormatByteArray(byte[] b) { return FormatByteArray(b, 0); } } #endif #endregion /// <summary> /// A stream that encrypts as it writes, or decrypts as it reads. The Crypto is AES in /// CTR (counter) mode, which is /// compatible with the AES encryption employed by WinZip 12.0. /// </summary> internal class WinZipAesCipherStream : Stream { private WinZipAesCrypto _params; private System.IO.Stream _s; private CryptoMode _mode; private int _nonce; private bool _finalBlock; private bool _NextXformWillBeFinal; internal HMACSHA1 _mac; // Use RijndaelManaged from .NET 2.0. // AesManaged came in .NET 3.5, but we want to limit // dependency to .NET 2.0. AES is just a restricted form // of Rijndael (fixed block size of 128, some crypto modes not supported). internal RijndaelManaged _aesCipher; internal ICryptoTransform _xform; private const int BLOCK_SIZE_IN_BYTES = 16; private byte[] counter = new byte[BLOCK_SIZE_IN_BYTES]; private byte[] counterOut = new byte[BLOCK_SIZE_IN_BYTES]; // I've had a problem when wrapping a WinZipAesCipherStream inside // a DeflateStream. Calling Read() on the DeflateStream results in // a Read() on the WinZipAesCipherStream, but the buffer is larger // than the total size of the encrypted data, and larger than the // initial Read() on the DeflateStream! When the encrypted // bytestream is embedded within a larger stream (As in a zip // archive), the Read() doesn't fail with EOF. This causes bad // data to be returned, and it messes up the MAC. // This field is used to provide a hard-stop to the size of // data that can be read from the stream. In Read(), if the buffer or // read request goes beyond the stop, we truncate it. private long _length; private long _totalBytesXferred; private byte[] _PendingWriteBuffer; private int _pendingCount; /// <summary> /// The constructor. /// </summary> /// <param name="s">The underlying stream</param> /// <param name="mode">To either encrypt or decrypt.</param> /// <param name="cryptoParams">The pre-initialized WinZipAesCrypto object.</param> /// <param name="length">The maximum number of bytes to read from the stream.</param> internal WinZipAesCipherStream(System.IO.Stream s, WinZipAesCrypto cryptoParams, long length, CryptoMode mode) : this(s, cryptoParams, mode) { // don't read beyond this limit! _length = length; //Console.WriteLine("max length of AES stream: {0}", _length); } #if WANT_TRACE Stream untransformed; String traceFileUntransformed; Stream transformed; String traceFileTransformed; #endif internal WinZipAesCipherStream(System.IO.Stream s, WinZipAesCrypto cryptoParams, CryptoMode mode) : base() { TraceOutput("-------------------------------------------------------"); TraceOutput("Create {0:X8}", this.GetHashCode()); _params = cryptoParams; _s = s; _mode = mode; _nonce = 1; if (_params == null) throw new BadPasswordException("Supply a password to use AES encryption."); int keySizeInBits = _params.KeyBytes.Length * 8; if (keySizeInBits != 256 && keySizeInBits != 128 && keySizeInBits != 192) throw new ArgumentException("keysize"); _mac = new HMACSHA1(_params.MacIv); _aesCipher = new System.Security.Cryptography.RijndaelManaged(); _aesCipher.BlockSize = 128; _aesCipher.KeySize = keySizeInBits; // 128, 192, 256 _aesCipher.Mode = CipherMode.ECB; _aesCipher.Padding = PaddingMode.None; byte[] iv = new byte[BLOCK_SIZE_IN_BYTES]; // all zeroes // Create an ENCRYPTOR, regardless whether doing decryption or encryption. // It is reflexive. _xform = _aesCipher.CreateEncryptor(_params.KeyBytes, iv); if (_mode == CryptoMode.Encrypt) _PendingWriteBuffer = new byte[BLOCK_SIZE_IN_BYTES]; #if WANT_TRACE traceFileUntransformed = "unpack\\WinZipAesCipherStream.trace.untransformed.out"; traceFileTransformed = "unpack\\WinZipAesCipherStream.trace.transformed.out"; untransformed = System.IO.File.Create(traceFileUntransformed); transformed = System.IO.File.Create(traceFileTransformed); #endif } private int ProcessOneBlockWriting(byte[] buffer, int offset, int last) { if (_finalBlock) throw new InvalidOperationException("The final block has already been transformed."); int bytesRemaining = last - offset; int bytesToRead = (bytesRemaining > BLOCK_SIZE_IN_BYTES) ? BLOCK_SIZE_IN_BYTES : bytesRemaining; // update the counter System.Array.Copy(BitConverter.GetBytes(_nonce++), 0, counter, 0, 4); // We're doing the last bytes in this batch. // // For the AES encryption stream to work properly, We must transform // blocks of 16 bytes, via TransformBlock, until the very last one, for // which we call TransformFinalBlock. But, we don't know how to // recognize the "last" bytes. The approach taken here: maintain a // buffer, so that one full or partial block of bytes is always // available. This is the _PendingWriteBuffer. Then at time of // Close(), we set the _NextXformWillBeFinal flag and flush that buffer. // // This works whether the caller writes in odd-sized batches, for example // 5000 bytes, or in batches that are neat multiples of the blocksize (16). // bytesToRead is always 16 or less. If it is exactly what remains, then we need to // either, if this is the final block, do the final transform, else buffer the data. if (bytesToRead == (last - offset)) { if (_NextXformWillBeFinal) { //Console.WriteLine("WinZipAesCipherStream::ProcessOneBlockWriting: _NextXformWillBeFinal = true"); counterOut = _xform.TransformFinalBlock(counter, 0, BLOCK_SIZE_IN_BYTES); _finalBlock = true; } else if (buffer==_PendingWriteBuffer && bytesToRead==BLOCK_SIZE_IN_BYTES) { // this happens with a Flush(), I think. } else { // NOT the final block, therefore buffer it. Array.Copy(buffer, offset, _PendingWriteBuffer, _pendingCount, bytesToRead); _pendingCount += bytesToRead; // remember to decrement the nonce. _nonce--; return bytesToRead; } } if (!_finalBlock) { // Next, do the AES transform. According to the AES/CTR method used // by WinZip, apply the transform to the counter, and then XOR // the result with the ciphertext to get the plaintext. _xform.TransformBlock(counter, 0, // offset BLOCK_SIZE_IN_BYTES, counterOut, 0); // offset } // XOR (in place) for (int i = 0; i < bytesToRead; i++) { buffer[offset + i] = (byte)(counterOut[i] ^ buffer[offset + i]); } // when encrypting, do the MAC last if (_finalBlock) _mac.TransformFinalBlock(buffer, offset, bytesToRead); else _mac.TransformBlock(buffer, offset, bytesToRead, null, 0); return bytesToRead; } private int ProcessOneBlockReading(byte[] buffer, int offset, int count) { if (_finalBlock) throw new NotSupportedException(); int bytesRemaining = count - offset; int bytesToRead = (bytesRemaining > BLOCK_SIZE_IN_BYTES) ? BLOCK_SIZE_IN_BYTES : bytesRemaining; // When READING, // Can we determine if this is the final block based on _length?? // and totalBytesRead ? YES. if (_length > 0) { if ((_totalBytesXferred + count == _length) && (bytesToRead == bytesRemaining)) { _NextXformWillBeFinal = true; } } // update the counter System.Array.Copy(BitConverter.GetBytes(_nonce++), 0, counter, 0, 4); if (_NextXformWillBeFinal && (bytesToRead == (count - offset))) { _mac.TransformFinalBlock(buffer, offset, bytesToRead); counterOut = _xform.TransformFinalBlock(counter, 0, BLOCK_SIZE_IN_BYTES); _finalBlock = true; } else { // first, do the MAC on the ciphertext _mac.TransformBlock(buffer, offset, bytesToRead, null, 0); // Next, do the decryption. According to the AES/CTR method used // by WinZip, apply the transform to the counter, and then XOR // the result with the ciphertext to get the plaintext. _xform.TransformBlock(counter, 0, // offset BLOCK_SIZE_IN_BYTES, counterOut, 0); // offset } // XOR (in place) for (int i = 0; i < bytesToRead; i++) { buffer[offset + i] = (byte)(counterOut[i] ^ buffer[offset + i]); } return bytesToRead; } private delegate int ProcessOneBlock(byte[] b, int p, int l); private void TransformInPlace(byte[] buffer, int offset, int count) { int posn = offset; int last = count + offset; ProcessOneBlock d = (_mode == CryptoMode.Encrypt) ? new ProcessOneBlock(ProcessOneBlockWriting) : new ProcessOneBlock(ProcessOneBlockReading); while (posn < buffer.Length && posn < last ) { int n = d (buffer, posn, last); posn += n; } } public override int Read(byte[] buffer, int offset, int count) { if (_mode == CryptoMode.Encrypt) throw new NotSupportedException(); if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0 || count < 0) throw new ArgumentException("Invalid parameters"); if (buffer.Length < offset + count) throw new ArgumentException("The buffer is too small"); // When I wrap a WinZipAesStream in a DeflateStream, the // DeflateStream asks its captive to read 4k blocks, even if the // encrypted bytestream is smaller than that. This is a way to // limit the number of bytes read. int bytesToRead = count; if (_totalBytesXferred >= _length) { return 0; // EOF } long bytesRemaining = _length - _totalBytesXferred; if (bytesRemaining < count) bytesToRead = (int)bytesRemaining; int n = _s.Read(buffer, offset, bytesToRead); #if WANT_TRACE untransformed.Write(buffer, offset, bytesToRead); #endif TransformInPlace(buffer, offset, bytesToRead); #if WANT_TRACE transformed.Write(buffer, offset, bytesToRead); #endif _totalBytesXferred += n; return n; // ? //return bytesToRead; //return count; } /// <summary> /// Returns the final HMAC-SHA1-80 for the data that was encrypted. /// </summary> public byte[] FinalAuthentication { get { if (!_finalBlock) { // special-case zero-byte files if ( _totalBytesXferred != 0) throw new BadStateException("The final hash has not been computed."); // Must call ComputeHash on an empty byte array when no data // has run through the MAC. byte[] b = { }; _mac.ComputeHash(b); // fall through } byte[] macBytes10 = new byte[10]; System.Array.Copy(_mac.Hash, 0, macBytes10, 0, 10); return macBytes10; } } public override void Write(byte[] buffer, int offset, int count) { // This class cannot decrypt as it writes. // If you want to decrypt, then READ through the stream. if (_mode == CryptoMode.Decrypt) throw new NotSupportedException(); if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0 || count < 0) throw new ArgumentException("Invalid parameters"); if (buffer.Length < offset + count) throw new ArgumentException("The offset and count are too large"); if (count == 0) return; TraceOutput("Write off({0}) count({1})", offset, count); #if WANT_TRACE untransformed.Write(buffer, offset, count); #endif if (_pendingCount != 0) { // Actually write only when more than 16 bytes are available. // If 16 or fewer, then just buffer the bytes if (count + _pendingCount <= BLOCK_SIZE_IN_BYTES) { Array.Copy(buffer, offset, _PendingWriteBuffer, _pendingCount, count); _pendingCount += count; // At this point, _PendingWriteBuffer contains up to // BLOCK_SIZE_IN_BYTES bytes, and _pendingCount ranges from 0 to // BLOCK_SIZE_IN_BYTES. We don't want to xform+write them yet, // because this may have been the last block. The last block gets // written at Close(). return; } // We have more than one block of data to write, therefore it is safe // to xform+write. int extra = BLOCK_SIZE_IN_BYTES - _pendingCount; // NB: extra is possibly zero here. That happens when the pending buffer // held 16 bytes (a complete block) before this call to Write. Array.Copy(buffer, offset, _PendingWriteBuffer, _pendingCount, extra); // adjust counts: _pendingCount = 0; offset += extra; count -= extra; // xform and write: ProcessOneBlockWriting(_PendingWriteBuffer, 0, BLOCK_SIZE_IN_BYTES); _s.Write(_PendingWriteBuffer, 0, BLOCK_SIZE_IN_BYTES); _totalBytesXferred += BLOCK_SIZE_IN_BYTES; } TransformInPlace(buffer, offset, count); #if WANT_TRACE transformed.Write(buffer, offset, count); #endif _s.Write(buffer, offset, count - _pendingCount); _totalBytesXferred += count - _pendingCount; } /// <summary> /// Close the stream. /// </summary> public override void Close() { TraceOutput("Close {0:X8}", this.GetHashCode()); if (_pendingCount != 0) { // xform and write whatever is left over _NextXformWillBeFinal = true; ProcessOneBlockWriting(_PendingWriteBuffer, 0, _pendingCount); _s.Write(_PendingWriteBuffer, 0, _pendingCount); _totalBytesXferred += _pendingCount; } _s.Close(); #if WANT_TRACE untransformed.Close(); transformed.Close(); Console.WriteLine("\nuntransformed bytestream is in {0}", traceFileUntransformed); Console.WriteLine("\ntransformed bytestream is in {0}", traceFileTransformed); #endif TraceOutput("-------------------------------------------------------"); } /// <summary> /// Returns true if the stream can be read. /// </summary> public override bool CanRead { get { if (_mode != CryptoMode.Decrypt) return false; return true; } } /// <summary> /// Always returns false. /// </summary> public override bool CanSeek { get { return false; } } /// <summary> /// Returns true if the CryptoMode is Encrypt. /// </summary> public override bool CanWrite { get { return (_mode == CryptoMode.Encrypt); } } /// <summary> /// Flush the content in the stream. /// </summary> public override void Flush() { _s.Flush(); } /// <summary> /// Getting this property throws a NotImplementedException. /// </summary> public override long Length { get { throw new NotImplementedException(); } } /// <summary> /// Getting or Setting this property throws a NotImplementedException. /// </summary> public override long Position { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } /// <summary> /// This method throws a NotImplementedException. /// </summary> public override long Seek(long offset, System.IO.SeekOrigin origin) { throw new NotImplementedException(); } /// <summary> /// This method throws a NotImplementedException. /// </summary> public override void SetLength(long value) { throw new NotImplementedException(); } [System.Diagnostics.ConditionalAttribute("Trace")] private void TraceOutput(string format, params object[] varParams) { lock(_outputLock) { int tid = System.Threading.Thread.CurrentThread.GetHashCode(); Console.ForegroundColor = (ConsoleColor) (tid % 8 + 8); Console.Write("{0:000} WZACS ", tid); Console.WriteLine(format, varParams); Console.ResetColor(); } } private object _outputLock = new Object(); } } #endif
34.114865
122
0.499307
[ "MIT" ]
TagsRocks/mudclient
ThirdPartyLibraries/Sources/DotNetZip/Zip Partial DLL/WinZipAes.cs
30,294
C#
namespace Microsoft.eShopWeb.ApplicationCore.Entities.OrderAggregate { public class Address // ValueObject { public string Street { get; set; } public string City { get; set; } public string State { get; set; } public string Country { get; set; } public string ZipCode { get; set; } private Address() { } public Address(string street, string city, string state, string country, string zipcode) { Street = street; City = city; State = state; Country = country; ZipCode = zipcode; } } }
23.555556
96
0.558176
[ "MIT" ]
SreekanthJos/eshopweb_with_azure
src/ApplicationCore/Entities/OrderAggregate/Address.cs
638
C#
using System; using System.Collections.Generic; using System.Text; namespace TelegramBotBase.Form { public class DynamicButton : ButtonBase { public override string Text { get { return GetText?.Invoke() ?? m_text; } set { m_text = value; } } private String m_text = ""; private Func<String> GetText; public DynamicButton(String Text, String Value, String Url = null) { this.Text = Text; this.Value = Value; this.Url = Url; } public DynamicButton(Func<String> GetText, String Value, String Url = null) { this.GetText = GetText; this.Value = Value; this.Url = Url; } } }
20.309524
83
0.488863
[ "MIT" ]
MajMcCloud/TelegramBotFramework
TelegramBotBase/Form/DynamicButton.cs
855
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.Generic; using System.Threading; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery; namespace Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery { internal sealed class CSharpSyntaxContext : SyntaxContext { public readonly TypeDeclarationSyntax ContainingTypeDeclaration; public readonly BaseTypeDeclarationSyntax ContainingTypeOrEnumDeclaration; public readonly bool IsInNonUserCode; public readonly bool IsPreProcessorKeywordContext; public readonly bool IsPreProcessorExpressionContext; public readonly bool IsGlobalStatementContext; public readonly bool IsNonAttributeExpressionContext; public readonly bool IsConstantExpressionContext; public readonly bool IsLabelContext; public readonly bool IsTypeArgumentOfConstraintContext; public readonly bool IsIsOrAsOrSwitchExpressionContext; public readonly bool IsObjectCreationTypeContext; public readonly bool IsDefiniteCastTypeContext; public readonly bool IsGenericTypeArgumentContext; public readonly bool IsEnumBaseListContext; public readonly bool IsIsOrAsTypeContext; public readonly bool IsLocalVariableDeclarationContext; public readonly bool IsDeclarationExpressionContext; public readonly bool IsFixedVariableDeclarationContext; public readonly bool IsParameterTypeContext; public readonly bool IsPossibleLambdaOrAnonymousMethodParameterTypeContext; public readonly bool IsImplicitOrExplicitOperatorTypeContext; public readonly bool IsPrimaryFunctionExpressionContext; public readonly bool IsDelegateReturnTypeContext; public readonly bool IsTypeOfExpressionContext; public readonly ISet<SyntaxKind> PrecedingModifiers; public readonly bool IsInstanceContext; public readonly bool IsCrefContext; public readonly bool IsCatchFilterContext; public readonly bool IsDestructorTypeContext; public readonly bool IsLeftSideOfImportAliasDirective; private CSharpSyntaxContext( Workspace workspace, SemanticModel semanticModel, int position, SyntaxToken leftToken, SyntaxToken targetToken, TypeDeclarationSyntax containingTypeDeclaration, BaseTypeDeclarationSyntax containingTypeOrEnumDeclaration, bool isInNonUserCode, bool isPreProcessorDirectiveContext, bool isPreProcessorKeywordContext, bool isPreProcessorExpressionContext, bool isTypeContext, bool isNamespaceContext, bool isNamespaceDeclarationNameContext, bool isStatementContext, bool isGlobalStatementContext, bool isAnyExpressionContext, bool isNonAttributeExpressionContext, bool isConstantExpressionContext, bool isAttributeNameContext, bool isEnumTypeMemberAccessContext, bool isNameOfContext, bool isInQuery, bool isInImportsDirective, bool isLeftSideOfImportAliasDirective, bool isLabelContext, bool isTypeArgumentOfConstraintContext, bool isRightOfDotOrArrowOrColonColon, bool isIsOrAsOrSwitchExpressionContext, bool isObjectCreationTypeContext, bool isDefiniteCastTypeContext, bool isGenericTypeArgumentContext, bool isEnumBaseListContext, bool isIsOrAsTypeContext, bool isLocalVariableDeclarationContext, bool isDeclarationExpressionContext, bool isFixedVariableDeclarationContext, bool isParameterTypeContext, bool isPossibleLambdaOrAnonymousMethodParameterTypeContext, bool isImplicitOrExplicitOperatorTypeContext, bool isPrimaryFunctionExpressionContext, bool isDelegateReturnTypeContext, bool isTypeOfExpressionContext, ISet<SyntaxKind> precedingModifiers, bool isInstanceContext, bool isCrefContext, bool isCatchFilterContext, bool isDestructorTypeContext, bool isPossibleTupleContext, bool isPatternContext, bool isRightSideOfNumericType, bool isInArgumentList, CancellationToken cancellationToken) : base(workspace, semanticModel, position, leftToken, targetToken, isTypeContext, isNamespaceContext, isNamespaceDeclarationNameContext, isPreProcessorDirectiveContext, isRightOfDotOrArrowOrColonColon, isStatementContext, isAnyExpressionContext, isAttributeNameContext, isEnumTypeMemberAccessContext, isNameOfContext, isInQuery, isInImportsDirective, IsWithinAsyncMethod(), isPossibleTupleContext, isPatternContext, isRightSideOfNumericType, isInArgumentList, cancellationToken) { this.ContainingTypeDeclaration = containingTypeDeclaration; this.ContainingTypeOrEnumDeclaration = containingTypeOrEnumDeclaration; this.IsInNonUserCode = isInNonUserCode; this.IsPreProcessorKeywordContext = isPreProcessorKeywordContext; this.IsPreProcessorExpressionContext = isPreProcessorExpressionContext; this.IsGlobalStatementContext = isGlobalStatementContext; this.IsNonAttributeExpressionContext = isNonAttributeExpressionContext; this.IsConstantExpressionContext = isConstantExpressionContext; this.IsLabelContext = isLabelContext; this.IsTypeArgumentOfConstraintContext = isTypeArgumentOfConstraintContext; this.IsIsOrAsOrSwitchExpressionContext = isIsOrAsOrSwitchExpressionContext; this.IsObjectCreationTypeContext = isObjectCreationTypeContext; this.IsDefiniteCastTypeContext = isDefiniteCastTypeContext; this.IsGenericTypeArgumentContext = isGenericTypeArgumentContext; this.IsEnumBaseListContext = isEnumBaseListContext; this.IsIsOrAsTypeContext = isIsOrAsTypeContext; this.IsLocalVariableDeclarationContext = isLocalVariableDeclarationContext; this.IsDeclarationExpressionContext = isDeclarationExpressionContext; this.IsFixedVariableDeclarationContext = isFixedVariableDeclarationContext; this.IsParameterTypeContext = isParameterTypeContext; this.IsPossibleLambdaOrAnonymousMethodParameterTypeContext = isPossibleLambdaOrAnonymousMethodParameterTypeContext; this.IsImplicitOrExplicitOperatorTypeContext = isImplicitOrExplicitOperatorTypeContext; this.IsPrimaryFunctionExpressionContext = isPrimaryFunctionExpressionContext; this.IsDelegateReturnTypeContext = isDelegateReturnTypeContext; this.IsTypeOfExpressionContext = isTypeOfExpressionContext; this.PrecedingModifiers = precedingModifiers; this.IsInstanceContext = isInstanceContext; this.IsCrefContext = isCrefContext; this.IsCatchFilterContext = isCatchFilterContext; this.IsDestructorTypeContext = isDestructorTypeContext; this.IsLeftSideOfImportAliasDirective = isLeftSideOfImportAliasDirective; } public static CSharpSyntaxContext CreateContext(Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken) { return CreateContextWorker(workspace, semanticModel, position, cancellationToken); } private static CSharpSyntaxContext CreateContextWorker(Workspace workspace, SemanticModel semanticModel, int position, CancellationToken cancellationToken) { var syntaxTree = semanticModel.SyntaxTree; var isInNonUserCode = syntaxTree.IsInNonUserCode(position, cancellationToken); var preProcessorTokenOnLeftOfPosition = syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken, includeDirectives: true); var isPreProcessorDirectiveContext = syntaxTree.IsPreProcessorDirectiveContext(position, preProcessorTokenOnLeftOfPosition, cancellationToken); var leftToken = isPreProcessorDirectiveContext ? preProcessorTokenOnLeftOfPosition : syntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); var targetToken = leftToken.GetPreviousTokenIfTouchingWord(position); var isPreProcessorKeywordContext = isPreProcessorDirectiveContext ? syntaxTree.IsPreProcessorKeywordContext(position, leftToken) : false; var isPreProcessorExpressionContext = isPreProcessorDirectiveContext ? targetToken.IsPreProcessorExpressionContext() : false; var isStatementContext = !isPreProcessorDirectiveContext ? targetToken.IsBeginningOfStatementContext() : false; var isGlobalStatementContext = !isPreProcessorDirectiveContext ? syntaxTree.IsGlobalStatementContext(position, cancellationToken) : false; var isAnyExpressionContext = !isPreProcessorDirectiveContext ? syntaxTree.IsExpressionContext(position, leftToken, attributes: true, cancellationToken: cancellationToken, semanticModelOpt: semanticModel) : false; var isNonAttributeExpressionContext = !isPreProcessorDirectiveContext ? syntaxTree.IsExpressionContext(position, leftToken, attributes: false, cancellationToken: cancellationToken, semanticModelOpt: semanticModel) : false; var isConstantExpressionContext = !isPreProcessorDirectiveContext ? syntaxTree.IsConstantExpressionContext(position, leftToken) : false; var containingTypeDeclaration = syntaxTree.GetContainingTypeDeclaration(position, cancellationToken); var containingTypeOrEnumDeclaration = syntaxTree.GetContainingTypeOrEnumDeclaration(position, cancellationToken); var isDestructorTypeContext = targetToken.IsKind(SyntaxKind.TildeToken) && targetToken.Parent.IsKind(SyntaxKind.DestructorDeclaration) && targetToken.Parent.Parent.IsKind(SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration); // Typing a dot after a numeric expression (numericExpression.) // - maybe a start of MemberAccessExpression like numericExpression.Member. // - or it maybe a start of a range expression like numericExpression..anotherNumericExpression (starting C# 8.0) // Therefore, in the scenario, we want the completion to be __soft selected__ until user types the next character after the dot. // If the second dot was typed, we just insert two dots. var isRightSideOfNumericType = leftToken.IsNumericTypeContext(semanticModel, cancellationToken); var isArgumentListToken = targetToken.Parent.IsKind(SyntaxKind.ArgumentList, SyntaxKind.AttributeArgumentList, SyntaxKind.ArrayRankSpecifier); return new CSharpSyntaxContext( workspace: workspace, semanticModel: semanticModel, position: position, leftToken: leftToken, targetToken: targetToken, containingTypeDeclaration: containingTypeDeclaration, containingTypeOrEnumDeclaration: containingTypeOrEnumDeclaration, isInNonUserCode: isInNonUserCode, isPreProcessorDirectiveContext: isPreProcessorDirectiveContext, isPreProcessorKeywordContext: isPreProcessorKeywordContext, isPreProcessorExpressionContext: isPreProcessorExpressionContext, isTypeContext: syntaxTree.IsTypeContext(position, cancellationToken, semanticModelOpt: semanticModel), isNamespaceContext: syntaxTree.IsNamespaceContext(position, cancellationToken, semanticModelOpt: semanticModel), isNamespaceDeclarationNameContext: syntaxTree.IsNamespaceDeclarationNameContext(position, cancellationToken), isStatementContext: isStatementContext, isGlobalStatementContext: isGlobalStatementContext, isAnyExpressionContext: isAnyExpressionContext, isNonAttributeExpressionContext: isNonAttributeExpressionContext, isConstantExpressionContext: isConstantExpressionContext, isAttributeNameContext: syntaxTree.IsAttributeNameContext(position, cancellationToken), isEnumTypeMemberAccessContext: syntaxTree.IsEnumTypeMemberAccessContext(semanticModel, position, cancellationToken), isNameOfContext: syntaxTree.IsNameOfContext(position, semanticModel, cancellationToken), isInQuery: leftToken.GetAncestor<QueryExpressionSyntax>() != null, isInImportsDirective: leftToken.GetAncestor<UsingDirectiveSyntax>() != null, isLeftSideOfImportAliasDirective: IsLeftSideOfUsingAliasDirective(leftToken), isLabelContext: syntaxTree.IsLabelContext(position, cancellationToken), isTypeArgumentOfConstraintContext: syntaxTree.IsTypeArgumentOfConstraintClause(position, cancellationToken), isRightOfDotOrArrowOrColonColon: syntaxTree.IsRightOfDotOrArrowOrColonColon(position, targetToken, cancellationToken), isIsOrAsOrSwitchExpressionContext: syntaxTree.IsIsOrAsOrSwitchExpressionContext(semanticModel, position, leftToken, cancellationToken), isObjectCreationTypeContext: syntaxTree.IsObjectCreationTypeContext(position, leftToken, cancellationToken), isDefiniteCastTypeContext: syntaxTree.IsDefiniteCastTypeContext(position, leftToken), isGenericTypeArgumentContext: syntaxTree.IsGenericTypeArgumentContext(position, leftToken, cancellationToken), isEnumBaseListContext: syntaxTree.IsEnumBaseListContext(position, leftToken), isIsOrAsTypeContext: syntaxTree.IsIsOrAsTypeContext(position, leftToken), isLocalVariableDeclarationContext: syntaxTree.IsLocalVariableDeclarationContext(position, leftToken, cancellationToken), isDeclarationExpressionContext: syntaxTree.IsDeclarationExpressionContext(position, leftToken), isFixedVariableDeclarationContext: syntaxTree.IsFixedVariableDeclarationContext(position, leftToken), isParameterTypeContext: syntaxTree.IsParameterTypeContext(position, leftToken), isPossibleLambdaOrAnonymousMethodParameterTypeContext: syntaxTree.IsPossibleLambdaOrAnonymousMethodParameterTypeContext(position, leftToken, cancellationToken), isImplicitOrExplicitOperatorTypeContext: syntaxTree.IsImplicitOrExplicitOperatorTypeContext(position, leftToken), isPrimaryFunctionExpressionContext: syntaxTree.IsPrimaryFunctionExpressionContext(position, leftToken), isDelegateReturnTypeContext: syntaxTree.IsDelegateReturnTypeContext(position, leftToken), isTypeOfExpressionContext: syntaxTree.IsTypeOfExpressionContext(position, leftToken), precedingModifiers: syntaxTree.GetPrecedingModifiers(position, leftToken), isInstanceContext: syntaxTree.IsInstanceContext(targetToken, semanticModel, cancellationToken), isCrefContext: syntaxTree.IsCrefContext(position, cancellationToken) && !leftToken.IsKind(SyntaxKind.DotToken), isCatchFilterContext: syntaxTree.IsCatchFilterContext(position, leftToken), isDestructorTypeContext: isDestructorTypeContext, isPossibleTupleContext: syntaxTree.IsPossibleTupleContext(leftToken, position), isPatternContext: syntaxTree.IsPatternContext(leftToken, position), isRightSideOfNumericType: isRightSideOfNumericType, isInArgumentList: isArgumentListToken, cancellationToken: cancellationToken); } public static CSharpSyntaxContext CreateContext_Test(SemanticModel semanticModel, int position, CancellationToken cancellationToken) { var inferenceService = new CSharpTypeInferenceService(); var types = inferenceService.InferTypes(semanticModel, position, cancellationToken); return CreateContextWorker(workspace: null, semanticModel: semanticModel, position: position, cancellationToken: cancellationToken); } private new static bool IsWithinAsyncMethod() { // TODO: Implement this if any C# completion code needs to know if it is in an async // method or not. return false; } public bool IsTypeAttributeContext(CancellationToken cancellationToken) { // cases: // [ | // class C { [ | var token = this.TargetToken; // Note that we pass the token.SpanStart to IsTypeDeclarationContext below. This is a bit subtle, // but we want to be sure that the attribute itself (i.e. the open square bracket, '[') is in a // type declaration context. if (token.Kind() == SyntaxKind.OpenBracketToken && token.Parent.Kind() == SyntaxKind.AttributeList && this.SyntaxTree.IsTypeDeclarationContext( token.SpanStart, contextOpt: null, validModifiers: null, validTypeDeclarations: SyntaxKindSet.ClassInterfaceStructTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) { return true; } return false; } public bool IsTypeDeclarationContext( ISet<SyntaxKind> validModifiers = null, ISet<SyntaxKind> validTypeDeclarations = null, bool canBePartial = false, CancellationToken cancellationToken = default) { return this.SyntaxTree.IsTypeDeclarationContext(this.Position, this, validModifiers, validTypeDeclarations, canBePartial, cancellationToken); } public bool IsMemberAttributeContext(ISet<SyntaxKind> validTypeDeclarations, CancellationToken cancellationToken) { // cases: // class C { [ | var token = this.TargetToken; if (token.Kind() == SyntaxKind.OpenBracketToken && token.Parent.Kind() == SyntaxKind.AttributeList && this.SyntaxTree.IsMemberDeclarationContext( token.SpanStart, contextOpt: null, validModifiers: null, validTypeDeclarations: validTypeDeclarations, canBePartial: false, cancellationToken: cancellationToken)) { return true; } return false; } public bool IsStatementAttributeContext() { var token = TargetToken; if (token.Kind() == SyntaxKind.OpenBracketToken && token.Parent.Kind() == SyntaxKind.AttributeList && token.Parent.Parent is StatementSyntax) { return true; } return false; } public bool IsMemberDeclarationContext( ISet<SyntaxKind> validModifiers = null, ISet<SyntaxKind> validTypeDeclarations = null, bool canBePartial = false, CancellationToken cancellationToken = default) { return this.SyntaxTree.IsMemberDeclarationContext(this.Position, this, validModifiers, validTypeDeclarations, canBePartial, cancellationToken); } private static bool IsLeftSideOfUsingAliasDirective(SyntaxToken leftToken) { var usingDirective = leftToken.GetAncestor<UsingDirectiveSyntax>(); if (usingDirective != null) { // No = token: if (usingDirective.Alias == null || usingDirective.Alias.EqualsToken.IsMissing) { return true; } return leftToken.SpanStart < usingDirective.Alias.EqualsToken.SpanStart; } return false; } internal override ITypeInferenceService GetTypeInferenceServiceWithoutWorkspace() { return new CSharpTypeInferenceService(); } /// <summary> /// Is this a possible position for an await statement (`await using` or `await foreach`)? /// </summary> internal bool IsAwaitStatementContext(int position, CancellationToken cancellationToken) { var leftToken = this.SyntaxTree.FindTokenOnLeftOfPosition(position, cancellationToken); var targetToken = leftToken.GetPreviousTokenIfTouchingWord(position); return targetToken.Kind() == SyntaxKind.AwaitKeyword && targetToken.GetPreviousToken().IsBeginningOfStatementContext(); } } }
55.781491
211
0.704134
[ "MIT" ]
missymessa/roslyn
src/Workspaces/SharedUtilitiesAndExtensions/Workspace/CSharp/Extensions/ContextQuery/CSharpSyntaxContext.cs
21,701
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from shared/hidpi.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { public unsafe partial struct HIDP_VALUE_CAPS { [NativeTypeName("USAGE")] public ushort UsagePage; [NativeTypeName("UCHAR")] public byte ReportID; [NativeTypeName("BOOLEAN")] public byte IsAlias; [NativeTypeName("USHORT")] public ushort BitField; [NativeTypeName("USHORT")] public ushort LinkCollection; [NativeTypeName("USAGE")] public ushort LinkUsage; [NativeTypeName("USAGE")] public ushort LinkUsagePage; [NativeTypeName("BOOLEAN")] public byte IsRange; [NativeTypeName("BOOLEAN")] public byte IsStringRange; [NativeTypeName("BOOLEAN")] public byte IsDesignatorRange; [NativeTypeName("BOOLEAN")] public byte IsAbsolute; [NativeTypeName("BOOLEAN")] public byte HasNull; [NativeTypeName("UCHAR")] public byte Reserved; [NativeTypeName("USHORT")] public ushort BitSize; [NativeTypeName("USHORT")] public ushort ReportCount; [NativeTypeName("USHORT [5]")] public fixed ushort Reserved2[5]; [NativeTypeName("ULONG")] public uint UnitsExp; [NativeTypeName("ULONG")] public uint Units; [NativeTypeName("LONG")] public int LogicalMin; [NativeTypeName("LONG")] public int LogicalMax; [NativeTypeName("LONG")] public int PhysicalMin; [NativeTypeName("LONG")] public int PhysicalMax; [NativeTypeName("_HIDP_VALUE_CAPS::(anonymous union at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/shared/hidpi.h:134:5)")] public _Anonymous_e__Union Anonymous; public ref _Anonymous_e__Union._Range_e__Struct Range { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref MemoryMarshal.GetReference(MemoryMarshal.CreateSpan(ref Anonymous.Range, 1)); } } public ref _Anonymous_e__Union._NotRange_e__Struct NotRange { [MethodImpl(MethodImplOptions.AggressiveInlining)] get { return ref MemoryMarshal.GetReference(MemoryMarshal.CreateSpan(ref Anonymous.NotRange, 1)); } } [StructLayout(LayoutKind.Explicit)] public partial struct _Anonymous_e__Union { [FieldOffset(0)] [NativeTypeName("struct (anonymous struct at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/shared/hidpi.h:135:9)")] public _Range_e__Struct Range; [FieldOffset(0)] [NativeTypeName("struct (anonymous struct at C:/Program Files (x86)/Windows Kits/10/Include/10.0.19041.0/shared/hidpi.h:142:9)")] public _NotRange_e__Struct NotRange; public partial struct _Range_e__Struct { [NativeTypeName("USAGE")] public ushort UsageMin; [NativeTypeName("USAGE")] public ushort UsageMax; [NativeTypeName("USHORT")] public ushort StringMin; [NativeTypeName("USHORT")] public ushort StringMax; [NativeTypeName("USHORT")] public ushort DesignatorMin; [NativeTypeName("USHORT")] public ushort DesignatorMax; [NativeTypeName("USHORT")] public ushort DataIndexMin; [NativeTypeName("USHORT")] public ushort DataIndexMax; } public partial struct _NotRange_e__Struct { [NativeTypeName("USAGE")] public ushort Usage; [NativeTypeName("USAGE")] public ushort Reserved1; [NativeTypeName("USHORT")] public ushort StringIndex; [NativeTypeName("USHORT")] public ushort Reserved2; [NativeTypeName("USHORT")] public ushort DesignatorIndex; [NativeTypeName("USHORT")] public ushort Reserved3; [NativeTypeName("USHORT")] public ushort DataIndex; [NativeTypeName("USHORT")] public ushort Reserved4; } } } }
28.964072
147
0.582386
[ "MIT" ]
Ethereal77/terrafx.interop.windows
sources/Interop/Windows/shared/hidpi/HIDP_VALUE_CAPS.cs
4,839
C#
using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Schema; namespace Digipost.Api.Client.Shared.Xml { public abstract class XmlValidator { private readonly XmlSchemaSet _schemaSet = new XmlSchemaSet(); public bool Validate(string document) { return new XmlValidationRunner(_schemaSet).Validate(document); } public bool Validate(string document, out string validationMessage) { var validationRunner = new XmlValidationRunner(_schemaSet); var status = validationRunner.Validate(document); validationMessage = validationRunner.ValidationMessages.ToString(); return status; } public bool Validate(string document, out List<string> validationMessages) { var validationRunner = new XmlValidationRunner(_schemaSet); var result = validationRunner.Validate(document); validationMessages = validationRunner.ValidationMessages; return result; } protected void AddXsd(string @namespace, string fileName) { _schemaSet.Add(@namespace, XmlReader(fileName)); } protected void AddXsd(string @namespace, XmlReader reader) { _schemaSet.Add(@namespace, reader); } private static XmlReader XmlReader(string fil) { Stream s = new MemoryStream(File.ReadAllBytes(fil)); return System.Xml.XmlReader.Create(s); } } }
31.693878
82
0.641339
[ "Apache-2.0" ]
digipost/api-client-shared-dotnet
Digipost.Api.Client.Shared/Xml/XmlValidator.cs
1,555
C#
using System.Linq; using EShopOnAbp.OrderingService.Orders; using Microsoft.EntityFrameworkCore; public static class EfCoreOrderQueryableExtensions { public static IQueryable<Order> IncludeDetails(this IQueryable<Order> queryable, bool include = true) { return !include ? queryable : queryable .Include(q => q.OrderStatus) .Include(q => q.Address) .Include(q => q.Buyer) .Include(q => q.OrderItems); } }
30.176471
105
0.614035
[ "MIT" ]
271943794/eShopOnAbp
services/ordering/src/EShopOnAbp.OrderingService.EntityFrameworkCore/Orders/EfCoreOrderQueryableExtensions.cs
515
C#
/* * Generated code file by Il2CppInspector - http://www.djkaty.com - https://github.com/djkaty */ using System; using System.Diagnostics; using System.Runtime.CompilerServices; using SpecialAnim; using UnityEngine; // Image 46: Assembly-CSharp.dll - Assembly: Assembly-CSharp, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null - Types 4339-9572 public class ReportModeWindow : UIWindowBase // TypeDefIndex: 6357 { // Fields private UIState uiState_; // 0x30 private UIPelipper manager_; // 0x38 private Mail mail_; // 0x40 // Nested types private enum UIState // TypeDefIndex: 6358 { In_Mail = 0, Message = 1, Done = 2 } private class Mail // TypeDefIndex: 6359 { // Fields private string[] actionName_; // 0x10 private Anim<ViewState> anim; // 0x18 // Nested types public enum ViewState // TypeDefIndex: 6360 { NONE = 0, MAILOPEN = 1, MAILCLOSE = 2, MAILIN = 3 } // Constructors public Mail() {} // Dummy constructor public Mail(GameObject obj) {} // 0x00A04350-0x00A04590 // Methods public void PlayAnim(ViewState state, Action cb = null) {} // 0x00A04680-0x00A04780 } // Constructors public ReportModeWindow() {} // 0x00A04780-0x00A04790 // Methods private static void PlaySe_Letter_Success() {} // 0x00A03D50-0x00A03DD0 public virtual void Init(GameObject objRoot, UIPelipper manager) {} // 0x00A03DD0-0x00A04350 public new void Update() {} // 0x00A04590-0x00A04680 }
24.166667
133
0.709655
[ "Unlicense" ]
tech-ticks/RTDXTools
Assets/Scripts/Stubs/Generated/Assembly-CSharp/ReportModeWindow.cs
1,452
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.ResourceManager.Cmdlets.SdkModels; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.WindowsAzure.Commands.Utilities.Common; using System.Collections.Generic; using System.Management.Automation; namespace Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation { /// <summary> /// Validate a template to see whether it's using the right syntax, resource providers, resource types, etc. /// </summary> [Cmdlet("Test", ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "ResourceGroupDeployment", DefaultParameterSetName = ParameterlessTemplateFileParameterSetName), OutputType(typeof(PSResourceManagerError))] public class TestAzureResourceGroupDeploymentCmdlet : ResourceWithParameterCmdletBase, IDynamicParameters { [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")] [ResourceGroupCompleter] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter(Mandatory = false, ValueFromPipelineByPropertyName = true, HelpMessage = "The deployment mode.")] public DeploymentMode Mode { get; set; } public TestAzureResourceGroupDeploymentCmdlet() { this.Mode = DeploymentMode.Incremental; } public override void ExecuteCmdlet() { PSDeploymentCmdletParameters parameters = new PSDeploymentCmdletParameters() { ResourceGroupName = ResourceGroupName, TemplateFile = TemplateUri ?? this.TryResolvePath(TemplateFile), TemplateParameterObject = GetTemplateParameterObject(TemplateParameterObject), ParameterUri = TemplateParameterUri }; WriteObject(ResourceManagerSdkClient.ValidateDeployment(parameters, Mode)); } } }
49.052632
217
0.677396
[ "MIT" ]
FonsecaSergio/azure-powershell
src/ResourceManager/Resources/Commands.ResourceManager/Cmdlets/Implementation/ResourceGroupDeployments/TestAzureResourceGroupDeploymentCmdlet.cs
2,742
C#
// /* // * Copyright (c) 2014 Behrooz Amoozad // * 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 the bd2 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 Behrooz Amoozad 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; using System.Collections.Generic; namespace BD2.Frontend.Table { public class LayeredDictionary <TKey, TValue>:IDictionary<TKey,TValue> { IDictionary<TKey, TValue> baseDictionary; IDictionary<TKey, TValue> overlay; int count; public LayeredDictionary (IDictionary<TKey, TValue> baseDictionary, bool keepStatistics) { this.baseDictionary = baseDictionary; this.overlay = new SortedDictionary<TKey, TValue> (); if (keepStatistics) count = 0; else count = -1; } #region IDictionary implementation public void Add (TKey key, TValue value) { if (count == -1) { overlay.Add (key, value); } else { if (!baseDictionary.ContainsKey (key)) count++; overlay.Add (key, value); } } public bool ContainsKey (TKey key) { return overlay.ContainsKey (key) || baseDictionary.ContainsKey (key); } public bool Remove (TKey key) { if (overlay.Remove (key)) { if (count != -1) { if (baseDictionary.ContainsKey (key)) { count--; } } return true; } return false; } public bool TryGetValue (TKey key, out TValue value) { if (!overlay.TryGetValue (key, out value)) { return baseDictionary.TryGetValue (key, out value); } return true; } public TValue this [TKey index] { get { TValue value; if (TryGetValue (index, out value)) return value; throw new KeyNotFoundException (); } set { throw new NotImplementedException (); } } public ICollection<TKey> Keys { get { throw new NotImplementedException (); } } public ICollection<TValue> Values { get { throw new NotImplementedException (); } } #endregion #region ICollection implementation public void Add (KeyValuePair<TKey, TValue> item) { overlay.Add (item.Key, item.Value); } public void Clear () { if (count != -1) count = 0; overlay.Clear (); } public bool Contains (KeyValuePair<TKey, TValue> item) { return overlay.Contains (item) || baseDictionary.Contains (item); } public void CopyTo (KeyValuePair<TKey, TValue>[] array, int arrayIndex) { throw new NotImplementedException (); } public bool Remove (KeyValuePair<TKey, TValue> item) { if (overlay.Remove (item)) { if (count != -1) { if (baseDictionary.Contains (item)) { count--; } } return true; } return false; } public int Count { get { return count; } } public bool IsReadOnly { get { return false; } } #endregion #region IEnumerable implementation public IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator () { throw new NotImplementedException (); } #endregion #region IEnumerable implementation IEnumerator IEnumerable.GetEnumerator () { throw new NotImplementedException (); } #endregion } }
24.567568
90
0.670627
[ "BSD-3-Clause" ]
jamesaxl/BD2
BD2.Frontend.Table/LayeredDictionary.cs
4,547
C#
using System; using System.Text; using System.Xml; using CMS.Base.Web.UI; using CMS.DataEngine; using CMS.FormEngine.Web.UI; using CMS.Helpers; using CMS.IO; using CMS.SiteProvider; public partial class CMSFormControls_System_SelectColumns : FormEngineUserControl { #region "Properties" /// <summary> /// Gets or sets the enabled state of the control. /// </summary> public override bool Enabled { get { return base.Enabled; } set { base.Enabled = value; txtColumns.Enabled = value; btnDesign.Enabled = value; } } ///<summary>Gets or sets field value.</summary> public override object Value { get { return hdnSelectedColumns.Value; } set { hdnSelectedColumns.Value = (string)value; } } public override bool IsValid() { var value = hdnSelectedColumns.Value; if (String.IsNullOrEmpty(value)) { return true; } try { // Check whether XML is not malformed LoadXmlDocument(new XmlDocument(), value); return true; } catch { return false; } } #endregion #region "Methods" protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (Form != null) { bool IsQuery = true; bool IsClassNames = true; bool IsCustomTable = true; ScriptHelper.RegisterDialogScript(Page); btnDesign.OnClientClick = "OpenModalDialog('" + hdnSelectedColumns.ClientID + "','" + txtColumns.ClientID + "'); return false;"; string script = @" function SetValue(input, txtInput,hdnSelColId,hdnColId){ document.getElementById(hdnSelColId).value = input; document.getElementById(hdnColId).value = txtInput; return false; } function GetClassNames(hdnColId) { return document.getElementById(hdnColId).value; } function GetSelectedColumns(hdnSelColId) { return document.getElementById(hdnSelColId).value; }"; // Try to find QueryName or ClassNames field object value; bool succ = Form.Data.TryGetValue("QueryName", out value); if (succ) { hdnProperties.Value = value.ToString(); IsClassNames = false; IsCustomTable = false; } else { IsQuery = false; } // If it still can be custom table, try it if (IsCustomTable) { // Fake it as query succ = Form.Data.TryGetValue("CustomTable", out value); if (succ) { hdnProperties.Value = value.ToString(); IsClassNames = false; IsQuery = true; } else { IsCustomTable = false; } } // If it still can be class names, try it if (IsClassNames) { value = String.Empty; succ = Form.Data.TryGetValue("ClassNames", out value); if (succ) { hdnProperties.Value = value.ToString(); } else { IsClassNames = false; } } // if QueryName field was found if (IsQuery) { // if query name isnt empty if (!String.IsNullOrEmpty(hdnProperties.Value)) { // Custom tables uses selectall query by default if (IsCustomTable) { hdnProperties.Value += ".selectall"; } string properties = ScriptHelper.GetString(hdnProperties.Value, false); script += "function OpenModalDialog(hdnSelColId, hdnColId) { modalDialog('" + ResolveUrl("~/CMSFormControls/Selectors/GridColumnDesigner.aspx") + "?queryname=" + properties + "&SelColId=' + hdnSelColId + '&ColId=' + hdnColId + '&hash=" + ValidationHelper.GetHashString("?queryname=" + properties + "&SelColId=" + hdnSelectedColumns.ClientID + "&ColId=" + txtColumns.ClientID, new HashSettings("")) + "' ,'GridColumnDesigner', 700, 560); return false;}\n"; } else { string message; // Different message for query and custom table if (IsCustomTable) { var classes = DataClassInfoProvider.GetClasses().Where("ClassIsCustomTable = 1 AND ClassID IN (SELECT ClassID FROM CMS_ClassSite WHERE SiteID = " + SiteContext.CurrentSiteID + ")"); message = classes.HasResults() ? GetString("SelectColumns.ApplyFirst") : GetString("SelectColumns.nocustomtablesavaible"); } else { message = GetString("SelectColumns.EmptyQueryName"); } script += "function OpenModalDialog(hdnSelColId, hdnColId) { alert('" + message + "'); return false;}\n"; } } else if (IsClassNames) { script += "function OpenModalDialog(hdnSelColId, hdnColId) { modalDialog('" + ResolveUrl("~/CMSFormControls/Selectors/GridColumnDesigner.aspx") + "?classnames=" + ScriptHelper.GetString(hdnProperties.Value, false) + "&SelColId=' + hdnSelColId + '&ColId=' + hdnColId ,'GridColumnDesigner', 700, 560); return false;}\n"; } else // Cant find QueryName or ClassNames or Custom table fiels { script += "function OpenModalDialog(hdnSelColId, hdnColId) { alert(" + ScriptHelper.GetLocalizedString("SelectColumns.EmptyClassNamesAndQueryName") + ");}\n"; } //Register JavaScript ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "SelectColumsGlobal", ScriptHelper.GetScript(script)); btnDesign.Text = GetString("general.select"); // Set to Textbox selected columns txtColumns.Text = ConvertXML(hdnSelectedColumns.Value); } } /// <summary> /// Convert XML to TextBox. /// </summary> /// <param name="mXML">XML document</param> public string ConvertXML(string mXML) { if (DataHelper.GetNotEmpty(mXML, "") == "") { return ""; } StringBuilder mToReturn = new StringBuilder(); XmlDocument mXMLDocument = new XmlDocument(); try { LoadXmlDocument(mXMLDocument, mXML); } catch { return ""; } if (mXMLDocument.DocumentElement == null) { return ""; } XmlNodeList NodeList = mXMLDocument.DocumentElement.GetElementsByTagName("column"); int i = 0; foreach (XmlNode node in NodeList) { if (i > 0) { mToReturn.Append(";"); } mToReturn.Append(XmlHelper.GetXmlAttributeValue(node.Attributes["name"], "")); i++; } return mToReturn.ToString(); } private static void LoadXmlDocument(XmlDocument document, string xml) { using (var stringReader = new StringReader(xml)) using (var xmlReader = XmlReader.Create(stringReader, new XmlReaderSettings())) { document.Load(xmlReader); } } #endregion }
29.961832
475
0.527516
[ "MIT" ]
BryanSoltis/KenticoMVCWidgetShowcase
CMS/CMSFormControls/System/SelectColumns.ascx.cs
7,852
C#
//Copyright 2020 Warren Harding, released under the MIT. using System; using System.Collections.Generic; using System.Text; using Sym; using Sym.Nodes; using System.Linq; namespace Sym.Goals { public class Goal { //public double Score; public virtual double CalculateGoalFitness(Node potentialSolution) { return double.NaN; } public static double CalculateGoalFitness(Node potential, List<Goal> goals) { double goalFitness = 0; foreach (Goal goal in goals) { goalFitness += goal.CalculateGoalFitness(potential); } return goalFitness; } } }
21.272727
83
0.605413
[ "MIT" ]
Wowo51/Sym
Sym/Goals/Goal.cs
704
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.vod.Transform; using Aliyun.Acs.vod.Transform.V20170321; namespace Aliyun.Acs.vod.Model.V20170321 { public class DescribeVodDomainDetailRequest : RpcAcsRequest<DescribeVodDomainDetailResponse> { public DescribeVodDomainDetailRequest() : base("vod", "2017-03-21", "DescribeVodDomainDetail", "vod", "openAPI") { } private string securityToken; private string domainName; private long? ownerId; public string SecurityToken { get { return securityToken; } set { securityToken = value; DictionaryUtil.Add(QueryParameters, "SecurityToken", value); } } public string DomainName { get { return domainName; } set { domainName = value; DictionaryUtil.Add(QueryParameters, "DomainName", value); } } public long? OwnerId { get { return ownerId; } set { ownerId = value; DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString()); } } public override DescribeVodDomainDetailResponse GetResponse(UnmarshallerContext unmarshallerContext) { return DescribeVodDomainDetailResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
26.045455
109
0.67801
[ "Apache-2.0" ]
fossabot/aliyun-openapi-net-sdk
aliyun-net-sdk-vod/Vod/Model/V20170321/DescribeVodDomainDetailRequest.cs
2,292
C#
using System; using System.Collections; class BitArrayClass { public static void logMethod() { // 创建两个大小为 8 的点阵列 BitArray ba1 = new BitArray(8); BitArray ba2 = new BitArray(8); byte[] a = { 60 }; byte[] b = { 13 }; // 把值 60 和 13 存储到点阵列中 ba1 = new BitArray(a); ba2 = new BitArray(b); // ba1 的内容 Console.WriteLine("Bit array ba1: 60"); for (int i = 0; i < ba1.Count; i++) { Console.Write("{0, -6} ", ba1[i]); } Console.WriteLine(); // ba2 的内容 Console.WriteLine("Bit array ba2: 13"); for (int i = 0; i < ba2.Count; i++) { Console.Write("{0, -6} ", ba2[i]); } Console.WriteLine(); BitArray ba3 = new BitArray(8); ba3 = ba1.And(ba2); // ba3 的内容 Console.WriteLine("Bit array ba3 after AND operation: 12"); for (int i = 0; i < ba3.Count; i++) { Console.Write("{0, -6} ", ba3[i]); } Console.WriteLine(); ba3 = ba1.Or(ba2); // ba3 的内容 Console.WriteLine("Bit array ba3 after OR operation: 61"); for (int i = 0; i < ba3.Count; i++) { Console.Write("{0, -6} ", ba3[i]); } Console.WriteLine(); Console.ReadKey(); } }
25.980392
67
0.477736
[ "MIT" ]
CainLuo/CSExamples
30.Collection/BitArrayClass.cs
1,393
C#
using System; using System.Reflection; using ToolGood.ReadyGo3.Attributes; using ToolGood.ReadyGo3.Internals; namespace ToolGood.ReadyGo3.Gadget.TableManager { public class ColumnInfo { private ColumnInfo() { } public string ColumnName; public string Comment; public string DefaultValue; public bool Required; public Type PropertyType; public string FieldLength; public bool IsText; internal static ColumnInfo FromProperty(PropertyInfo pi) { if (pi.CanRead == false || pi.CanWrite == false) return null; if (Types.IsAllowType(pi.PropertyType) == false) return null; var a = pi.GetCustomAttributes(typeof(IgnoreAttribute), true); if (a.Length > 0) return null; a = pi.GetCustomAttributes(typeof(ResultColumnAttribute), true); if (a.Length > 0) return null; ColumnInfo ci = new ColumnInfo { PropertyType = pi.PropertyType }; a = pi.GetCustomAttributes(typeof(ColumnAttribute), true); ci.ColumnName = a.Length == 0 ? pi.Name : (a[0] as ColumnAttribute).Name; if (string.IsNullOrEmpty(ci.ColumnName)) ci.ColumnName = pi.Name; ci.Comment = a.Length == 0 ? null : (a[0] as ColumnAttribute).Comment; a = pi.GetCustomAttributes(typeof(DefaultValueAttribute), true); ci.DefaultValue = a.Length == 0 ? null : (a[0] as DefaultValueAttribute).DefaultValue; a = pi.GetCustomAttributes(typeof(FieldLengthAttribute), true); if (a.Length > 0) { ci.IsText = (a[0] as FieldLengthAttribute).IsText; ci.FieldLength = (a[0] as FieldLengthAttribute).FieldLength; } var atts = pi.GetCustomAttributes(typeof(RequiredAttribute), true); if (atts.Length > 0) { ci.Required = (atts[0] as RequiredAttribute).Required; } else { if (pi.PropertyType == typeof(string) || pi.PropertyType == typeof(AnsiString)) { ci.Required = false; } else { ci.Required = Types.IsNullType(ci.PropertyType) == false; } } ci.PropertyType = Types.GetBaseType(ci.PropertyType); return ci; } } }
36.58209
99
0.569155
[ "Apache-2.0" ]
toolgood/ToolGood.ReadyGo
ToolGood.ReadyGo3/Gadget/TableManager/ColumnInfo.cs
2,453
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.AzureNextGen.Cdn.V20200415.Inputs { /// <summary> /// Defines the RequestMethod condition for the delivery rule. /// </summary> public sealed class DeliveryRuleRequestMethodConditionArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the condition for the delivery rule. /// Expected value is 'RequestMethod'. /// </summary> [Input("name", required: true)] public Input<string> Name { get; set; } = null!; /// <summary> /// Defines the parameters for the condition. /// </summary> [Input("parameters", required: true)] public Input<Inputs.RequestMethodMatchConditionParametersArgs> Parameters { get; set; } = null!; public DeliveryRuleRequestMethodConditionArgs() { } } }
31.5
104
0.650794
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Cdn/V20200415/Inputs/DeliveryRuleRequestMethodConditionArgs.cs
1,134
C#
using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using SFA.DAS.ApplyService.Configuration; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace SFA.DAS.ApplyService.InternalApi.Services.Files { public class FileStorageService : IFileStorageService { private readonly ILogger<FileStorageService> _logger; private readonly FileStorageConfig _fileStorageConfig; public FileStorageService(ILogger<FileStorageService> logger, IConfigurationService configurationService) { _logger = logger; var config = configurationService.GetConfig().GetAwaiter().GetResult(); _fileStorageConfig = config.FileStorage; } public async Task<IEnumerable<DownloadFileInfo>> GetApplicationFileList(Guid applicationId, ContainerType containerType, CancellationToken cancellationToken) { var fileList = new List<DownloadFileInfo>(); var container = await BlobContainerHelpers.GetContainer(_fileStorageConfig, containerType); if (container != null) { var applicationDirectory = container.GetDirectory(applicationId); var directoryFileList = applicationDirectory.GetFileList(); fileList.AddRange(directoryFileList); } return fileList; } public async Task<IEnumerable<DownloadFileInfo>> GetFileList(Guid applicationId, int? sequenceNumber, int? sectionNumber, string pageId, ContainerType containerType, CancellationToken cancellationToken) { var fileList = new List<DownloadFileInfo>(); if (!string.IsNullOrWhiteSpace(pageId)) { var container = await BlobContainerHelpers.GetContainer(_fileStorageConfig, containerType); if (container != null) { var pageDirectory = container.GetDirectory(applicationId, sequenceNumber, sectionNumber, pageId); var directoryFileList = pageDirectory.GetFileList(); fileList.AddRange(directoryFileList); } } return fileList; } public async Task<bool> UploadApplicationFiles(Guid applicationId, IFormFileCollection files, ContainerType containerType, CancellationToken cancellationToken) { var success = false; if (files != null) { var container = await BlobContainerHelpers.GetContainer(_fileStorageConfig, containerType); if (container != null) { var applicationDirectory = container.GetDirectory(applicationId); success = await applicationDirectory.UploadFiles(files, _logger, cancellationToken); } } return success; } public async Task<bool> UploadFiles(Guid applicationId, int? sequenceNumber, int? sectionNumber, string pageId, IFormFileCollection files, ContainerType containerType, CancellationToken cancellationToken) { var success = false; if (!string.IsNullOrWhiteSpace(pageId) && files != null) { var container = await BlobContainerHelpers.GetContainer(_fileStorageConfig, containerType); if (container != null) { var pageDirectory = container.GetDirectory(applicationId, sequenceNumber, sectionNumber, pageId); success = await pageDirectory.UploadFiles(files, _logger, cancellationToken); } } return success; } public async Task<bool> DeleteApplicationFile(Guid applicationId, string fileName, ContainerType containerType, CancellationToken cancellationToken) { var success = false; if (!string.IsNullOrWhiteSpace(fileName)) { var container = await BlobContainerHelpers.GetContainer(_fileStorageConfig, containerType); if (container != null) { var applicationDirectory = container.GetDirectory(applicationId); success = await applicationDirectory.DeleteFile(fileName, cancellationToken); } } return success; } public async Task<bool> DeleteFile(Guid applicationId, int? sequenceNumber, int? sectionNumber, string pageId, string fileName, ContainerType containerType, CancellationToken cancellationToken) { var success = false; if (!string.IsNullOrWhiteSpace(pageId) && !string.IsNullOrWhiteSpace(fileName)) { var container = await BlobContainerHelpers.GetContainer(_fileStorageConfig, containerType); if (container != null) { var pageDirectory = container.GetDirectory(applicationId, sequenceNumber, sectionNumber, pageId); success = await pageDirectory.DeleteFile(fileName, cancellationToken); } } return success; } public async Task<DownloadFile> DownloadApplicationFile(Guid applicationId, string fileName, ContainerType containerType, CancellationToken cancellationToken) { var file = default(DownloadFile); if (!string.IsNullOrWhiteSpace(fileName)) { var container = await BlobContainerHelpers.GetContainer(_fileStorageConfig, containerType); if (container != null) { var applicationDirectory = container.GetDirectory(applicationId); file = await applicationDirectory.DownloadFile(fileName, cancellationToken); } } return file; } public async Task<DownloadFile> DownloadFile(Guid applicationId, int? sequenceNumber, int? sectionNumber, string pageId, string fileName, ContainerType containerType, CancellationToken cancellationToken) { var file = default(DownloadFile); if (!string.IsNullOrWhiteSpace(pageId) && !string.IsNullOrWhiteSpace(fileName)) { var container = await BlobContainerHelpers.GetContainer(_fileStorageConfig, containerType); if (container != null) { var pageDirectory = container.GetDirectory(applicationId, sequenceNumber, sectionNumber, pageId); file = await pageDirectory.DownloadFile(fileName, cancellationToken); } } return file; } public async Task<DownloadFile> DownloadApplicationFiles(Guid applicationId, ContainerType containerType, CancellationToken cancellationToken) { var zipFile = default(DownloadFile); var container = await BlobContainerHelpers.GetContainer(_fileStorageConfig, containerType); if (container != null) { var applicationDirectory = container.GetDirectory(applicationId); var files = await applicationDirectory.DownloadDirectoryFiles(cancellationToken); if (files.Any()) { zipFile = ZipDownloadFiles(files, $"uploads.zip"); } } return zipFile; } public async Task<DownloadFile> DownloadFiles(Guid applicationId, int? sequenceNumber, int? sectionNumber, string pageId, ContainerType containerType, CancellationToken cancellationToken) { var zipFile = default(DownloadFile); if (!string.IsNullOrWhiteSpace(pageId)) { var container = await BlobContainerHelpers.GetContainer(_fileStorageConfig, containerType); if (container != null) { var pageDirectory = container.GetDirectory(applicationId, sequenceNumber, sectionNumber, pageId); var files = await pageDirectory.DownloadDirectoryFiles(cancellationToken); if (files.Any()) { zipFile = ZipDownloadFiles(files, $"{pageId}_uploads.zip"); } } } return zipFile; } private DownloadFile ZipDownloadFiles(IEnumerable<DownloadFile> files, string zipFileName) { using (var zipStream = new MemoryStream()) { using (var zipArchive = new ZipArchive(zipStream, ZipArchiveMode.Create, true)) { foreach (var file in files) { var zipEntry = zipArchive.CreateEntry(file.FileName); using (var entryStream = zipEntry.Open()) { file.Stream.CopyTo(entryStream); } } } zipStream.Position = 0; var newStream = new MemoryStream(); zipStream.CopyTo(newStream); newStream.Position = 0; return new DownloadFile { FileName = zipFileName, ContentType = "application/zip", Stream = newStream }; } } public async Task<bool> DeleteApplicationDirectory(Guid applicationId, ContainerType containerType, CancellationToken cancellationToken) { var success = false; var container = await BlobContainerHelpers.GetContainer(_fileStorageConfig, containerType); if (container != null) { var applicationDirectory = container.GetDirectory(applicationId); success = await applicationDirectory.DeleteDirectory(cancellationToken); } return success; } public async Task<bool> DeleteDirectory(Guid applicationId, int? sequenceNumber, int? sectionNumber, string pageId, ContainerType containerType, CancellationToken cancellationToken) { var success = false; if (!string.IsNullOrWhiteSpace(pageId)) { var container = await BlobContainerHelpers.GetContainer(_fileStorageConfig, containerType); if (container != null) { var applicationDirectory = container.GetDirectory(applicationId, sequenceNumber, sectionNumber, pageId); success = await applicationDirectory.DeleteDirectory(cancellationToken); } } return success; } } }
39.896679
212
0.608398
[ "MIT" ]
SkillsFundingAgency/das-apply-service
src/SFA.DAS.ApplyService.InternalApi/Services/Files/FileStorageService.cs
10,814
C#
using Rhino.Geometry; using static System.Math; namespace Robots; static class Util { // Constants public const double DistanceTol = 0.001; public const double AngleTol = 0.001; public const double TimeTol = 0.00001; public const double UnitTol = 0.000001; public const double SingularityTol = 0.0001; public const double HalfPI = PI * 0.5; public const double PI2 = PI * 2.0; // Exceptions public static T NotNull<T>(this T? value, string? text = null) { return value ?? throw new ArgumentNullException(nameof(value), text); } // String public static bool EqualsIgnoreCase(this string a, string b) { return string.Equals(a, b, StringComparison.OrdinalIgnoreCase); } // Collection public static IList<T> TryCastIList<T>(this IEnumerable<T> list) { return list as IList<T> ?? list.ToList(); } public static T[] TryCastArray<T>(this IEnumerable<T> list) { return list as T[] ?? list.ToArray(); } public static List<K> MapToList<T, K>(this IList<T> array, Func<T, K> projection) { var result = new List<K>(array.Count); for (int i = 0; i < array.Count; i++) result.Add(projection(array[i])); return result; } public static K[] Map<T, K>(this IList<T> array, Func<T, K> projection) { var result = new K[array.Count]; for (int i = 0; i < array.Count; i++) result[i] = projection(array[i]); return result; } public static K[] Map<T, K>(this IList<T> array, Func<T, int, K> projection) { var result = new K[array.Count]; for (int i = 0; i < array.Count; i++) result[i] = projection(array[i], i); return result; } public static T[] Subset<T>(this T[] array, int[] indices) { T[] subset = new T[indices.Length]; for (int i = 0; i < indices.Length; i++) subset[i] = array[indices[i]]; return subset; } public static T[] RangeSubset<T>(this T[] array, int startIndex, int length) { T[] subset = new T[length]; Array.Copy(array, startIndex, subset, 0, length); return subset; } public static T MaxBy<T, K>(this IEnumerable<T> list, Func<T, K> comparable) where K : IComparable<K> { if (!list.Any()) throw new ArgumentOutOfRangeException(nameof(list), "List cannot be empty."); T maxItem = list.First(); K maxValue = comparable(maxItem); foreach (var item in list.Skip(1)) { var val = comparable(item); if (val.CompareTo(maxValue) > 0) { maxItem = item; maxValue = val; } } return maxItem; } public static IEnumerable<List<T>> Transpose<T>(this IEnumerable<IEnumerable<T>> source) { var enumerators = source.Select(e => e.GetEnumerator()).ToArray(); try { while (enumerators.All(e => e.MoveNext())) { yield return enumerators.Select(e => e.Current).ToList(); } } finally { foreach (var enumerator in enumerators) enumerator.Dispose(); } } public static byte[] Combine(params byte[][] arrays) { var result = new byte[arrays.Sum(x => x.Length)]; int offset = 0; foreach (byte[] data in arrays) { Buffer.BlockCopy(data, 0, result, offset, data.Length); offset += data.Length; } return result; } // Geometry public static double ToRadians(this double value) { return value * (PI / 180.0); } public static double ToDegrees(this double value) { return value * (180.0 / PI); } // Transform public static void Set(this ref Transform t, double m00, double m01, double m02, double m03, double m10, double m11, double m12, double m13, double m20, double m21, double m22, double m23) { t.M00 = m00; t.M01 = m01; t.M02 = m02; t.M03 = m03; t.M10 = m10; t.M11 = m11; t.M12 = m12; t.M13 = m13; t.M20 = m20; t.M21 = m21; t.M22 = m22; t.M23 = m23; t.M33 = 1; } public static Plane ToPlane(this ref Transform t) { var p = new Point3d(t.M03, t.M13, t.M23); var vx = new Vector3d(t.M00, t.M10, t.M20); var vy = new Vector3d(t.M01, t.M11, t.M21); var vz = Vector3d.CrossProduct(vx, vy); vy = Vector3d.CrossProduct(vz, vx); vx.Normalize(); vy.Normalize(); vz.Normalize(); Plane result = default; result.Origin = p; result.XAxis = vx; result.YAxis = vy; result.ZAxis = vz; return result; } // Vector3d public static void Normalize(this ref Vector3d v) { double x = v.X; double y = v.Y; double z = v.Z; double lengthSq = x * x + y * y + z * z; double length = Sqrt(lengthSq); v.X = x / length; v.Y = y / length; v.Z = z / length; } // Plane public static void InverseOrient(this ref Plane a, ref Plane b) { a.Transform(b.ToInverseTransform()); } public static void Orient(this ref Plane a, ref Plane b) { a.Transform(b.ToTransform()); } public static Transform ToTransform(this ref Plane plane) { Transform t = default; var vx = plane.XAxis; var vy = plane.YAxis; var vz = plane.ZAxis; t.M00 = vx.X; t.M01 = vy.X; t.M02 = vz.X; t.M03 = plane.OriginX; t.M10 = vx.Y; t.M11 = vy.Y; t.M12 = vz.Y; t.M13 = plane.OriginY; t.M20 = vx.Z; t.M21 = vy.Z; t.M22 = vz.Z; t.M23 = plane.OriginZ; t.M33 = 1; return t; } public static Transform ToInverseTransform(this ref Plane plane) { Transform t = default; var vx = plane.XAxis; var vy = plane.YAxis; var vz = plane.ZAxis; var p = -(Vector3d)plane.Origin; t.M00 = vx.X; t.M01 = vx.Y; t.M02 = vx.Z; t.M03 = p * vx; t.M10 = vy.X; t.M11 = vy.Y; t.M12 = vy.Z; t.M13 = p * vy; t.M20 = vz.X; t.M21 = vz.Y; t.M22 = vz.Z; t.M23 = p * vz; t.M33 = 1; return t; } // adapted from System.Numerics.Vectors public static Quaternion ToQuaternion(this ref Plane plane) { var matrix = plane.ToTransform(); double trace = matrix.M00 + matrix.M11 + matrix.M22; Quaternion q = default; if (trace > 0.0) { double s = Sqrt(trace + 1.0); q.A = s * 0.5; s = 0.5 / s; q.B = (matrix.M21 - matrix.M12) * s; q.C = (matrix.M02 - matrix.M20) * s; q.D = (matrix.M10 - matrix.M01) * s; } else { if (matrix.M00 >= matrix.M11 && matrix.M00 >= matrix.M22) { double s = Sqrt(1.0 + matrix.M00 - matrix.M11 - matrix.M22); double invS = 0.5 / s; q.B = 0.5 * s; q.C = (matrix.M10 + matrix.M01) * invS; q.D = (matrix.M20 + matrix.M02) * invS; q.A = (matrix.M21 - matrix.M12) * invS; } else if (matrix.M11 > matrix.M22) { double s = Sqrt(1.0 + matrix.M11 - matrix.M00 - matrix.M22); double invS = 0.5 / s; q.B = (matrix.M01 + matrix.M10) * invS; q.C = 0.5 * s; q.D = (matrix.M12 + matrix.M21) * invS; q.A = (matrix.M02 - matrix.M20) * invS; } else { double s = Sqrt(1.0 + matrix.M22 - matrix.M00 - matrix.M11); double invS = 0.5 / s; q.B = (matrix.M02 + matrix.M20) * invS; q.C = (matrix.M12 + matrix.M21) * invS; q.D = 0.5 * s; q.A = (matrix.M10 - matrix.M01) * invS; } } return q; } // Quaternion // adapted from System.Numerics.Vectors public static Quaternion Slerp(ref Quaternion q1, ref Quaternion q2, double t) { const double epsilon = 1e-6; double cosOmega = q1.B * q2.B + q1.C * q2.C + q1.D * q2.D + q1.A * q2.A; bool flip = false; if (cosOmega < 0.0) { flip = true; cosOmega = -cosOmega; } double s1, s2; if (cosOmega > (1.0 - epsilon)) { // Too close, do straight linear interpolation. s1 = 1.0 - t; s2 = (flip) ? -t : t; } else { double omega = Acos(cosOmega); double invSinOmega = 1.0 / Sin(omega); s1 = Sin((1.0 - t) * omega) * invSinOmega; s2 = (flip) ? -Sin(t * omega) * invSinOmega : Sin(t * omega) * invSinOmega; } Quaternion ans = default; ans.B = s1 * q1.B + s2 * q2.B; ans.C = s1 * q1.C + s2 * q2.C; ans.D = s1 * q1.D + s2 * q2.D; ans.A = s1 * q1.A + s2 * q2.A; return ans; } public static Plane ToPlane(this ref Quaternion quaternion, Point3d point) { quaternion.GetRotation(out Plane plane); plane.Origin = point; return plane; } // adapted from System.Numerics.Vectors public static Transform ToTransform(this ref Quaternion q) { Transform result = default; double xx = q.B * q.B; double yy = q.C * q.C; double zz = q.D * q.D; double xy = q.B * q.C; double wz = q.D * q.A; double xz = q.D * q.B; double wy = q.C * q.A; double yz = q.C * q.D; double wx = q.B * q.A; result.M00 = 1.0 - 2.0 * (yy + zz); result.M01 = 2.0 * (xy - wz); result.M02 = 2.0 * (xz + wy); //result.M03 = 0.0; result.M10 = 2.0 * (xy + wz); result.M11 = 1.0 - 2.0 * (zz + xx); result.M12 = 2.0 * (yz - wx); //result.M13 = 0.0; result.M20 = 2.0 * (xz - wy); result.M21 = 2.0 * (yz + wx); result.M22 = 1.0 - 2.0 * (yy + xx); //result.M23 = 0.0; //result.M30 = 0.0; //result.M31 = 0.0; //result.M32 = 0.0; result.M33 = 1.0; return result; } }
26.720403
192
0.495192
[ "MIT" ]
lin-ycv/Robots
src/Robots/Util.cs
10,610
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lego_Blocks { class Program { static void Main(string[] args) { int R = int.Parse(Console.ReadLine()); int[][] firstJagged = new int[R][]; int[][] secondJagged = new int[R][]; int elementsFirst = 0; int elementsSecond = 0; for (int rows = 0; rows < R; rows++) { int[] input = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); firstJagged[rows] = new int[input.Length]; for (int cols = 0; cols < input.Length; cols++) { firstJagged[rows][cols] = input[cols]; elementsFirst++; } } for (int rows = 0; rows < R; rows++) { int[] input = Console.ReadLine().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray(); secondJagged[rows] = new int[input.Length]; for (int cols = 0; cols < input.Length; cols++) { secondJagged[rows][cols] = input[cols]; elementsSecond++; } } int colsCommon = 0; for (int i = 0; i < R; i++) { int firstCols = firstJagged[i].Length; int secondCols = secondJagged[i].Length; if(i==0) { colsCommon = firstCols + secondCols; } if(firstCols+secondCols!=colsCommon) { Console.WriteLine($"The total number of cells is: {elementsFirst+elementsSecond}"); Environment.Exit(0); } } int[][] rectMatrix = new int[R][]; for (int rows = 0; rows < R; rows++) { rectMatrix[rows] = new int[colsCommon]; for (int cols = 0; cols < firstJagged[rows].Length; cols++) { rectMatrix[rows][cols] = firstJagged[rows][cols]; } } for (int rows = 0; rows < R; rows++) { for (int cols = 0; cols < secondJagged[rows].Length; cols++) { int column = rectMatrix[rows].Length - 1 - cols; rectMatrix[rows][column] = secondJagged[rows][cols]; } } foreach (var row in rectMatrix) { Console.WriteLine("[" + string.Join(", ", row) + "]"); } } } }
36.454545
142
0.448165
[ "MIT" ]
SimeonShterev/2018.01.22-2018.04.22-CSharpFundamentals
2018.01.22-C#Advanced/2018.01.26-Multidimentional Arrays H2/Lego Blocks/Program.cs
2,809
C#
using Flutterwave.Net.Utilities; namespace Flutterwave.Net { public class Transactions : ITransactions { private FlutterwaveApi _flutterwaveApi { get; } public Transactions(FlutterwaveApi flutterwaveApi) { _flutterwaveApi = flutterwaveApi; } /// <summary> /// Get all transactions /// </summary> /// <returns>A list of transactions</returns> public GetTransactionsResponse GetTransactions() { return _flutterwaveApi.Get<GetTransactionsResponse>(Endpoints.TRANSACTIONS); } /// <summary> /// Verify a transaction /// </summary> /// <param name="id"> /// This is the transaction unique identifier. It is returned in the Get transactions /// call as data.id /// </param> /// <returns>The transaction with the specified id</returns> public VerifyTransactionResponse VerifyTransaction(int id) { return _flutterwaveApi.Get<VerifyTransactionResponse>($"{Endpoints.TRANSACTIONS}/{id}/verify"); } } }
30.297297
107
0.609277
[ "MIT" ]
VictorSega/flutterwave-dotnet
src/flutterwave-dotnet/APIs/Implementations/Transactions.cs
1,123
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DependencyObjectExtensions.cs" company="WildGums"> // Copyright (c) 2008 - 2015 WildGums. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Orchestra { using System.IO; using System.Windows; using System.Windows.Markup; using System.Xml; using Catel; using Catel.Windows; public static class DependencyObjectExtensions { public static T Clone<T>(this T source) where T : DependencyObject { Argument.IsNotNull(() => source); var objXaml = XamlWriter.Save(source); var stringReader = new StringReader(objXaml); var xmlReader = XmlReader.Create(stringReader); var target = (T)XamlReader.Load(xmlReader); return target; } /// <summary> /// Get the parent window for this visual object or null when not exists. /// </summary> /// <param name="visualObject">Reference to visual object.</param> /// <returns>Reference to partent window or null when not exists.</returns> public static System.Windows.Window GetParentWindow(this DependencyObject visualObject) { if (visualObject == null) { return null; } return visualObject.FindLogicalOrVisualAncestorByType<System.Windows.Window>(); } } }
33.791667
120
0.519729
[ "MIT" ]
vatsan-madhavan/Orchestra
src/Orchestra.Core/Extensions/DependencyObjectExtensions.cs
1,624
C#