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
namespace AspNetCoreApi { using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.DependencyInjection; using IdentityServer4.AccessTokenValidation; using System; public class Startup { public void ConfigureServices(IServiceCollection services) { services .AddMvcCore() .AddJsonFormatters() .AddAuthorization(); services.AddCors(); services.AddDistributedMemoryCache(); services .AddAuthentication( IdentityServerAuthenticationDefaults.AuthenticationScheme) .AddIdentityServerAuthentication(options => { options.Authority = "http://localhost:5000"; options.RequireHttpsMetadata = false; options.EnableCaching = true; options.CacheDuration = TimeSpan.FromSeconds(5); // used for retrospection calls options.ApiName = "api1"; options.ApiSecret = "secret"; }); } public void Configure(IApplicationBuilder app) { app.UseCors(policy => { policy.WithOrigins( "http://localhost:28895", // AspNetCoreWeb "http://localhost:7017", "http://localhost:3000"); // phonegap app policy.AllowAnyHeader(); policy.AllowAnyMethod(); policy.WithExposedHeaders("WWW-Authenticate"); }); app.UseAuthentication(); app.UseMvc(); } } }
30.642857
78
0.518065
[ "Apache-2.0" ]
madeinchinalmc/IdentityBase
samples/AspNetCoreApi/Startup.cs
1,716
C#
namespace Glacie.CommandLine.UI { internal static class StringUtilities { /// <summary> /// Create excerpt string with number of characters. /// </summary> public static string? Excerpt(string? value, int count) { if (string.IsNullOrEmpty(value) || value.Length < count) return value; return value.Substring(0, count - 3) + "..."; } } }
24.444444
68
0.547727
[ "MIT" ]
Lixiss/Glacie
src/Glacie.CommandLine/UI/Rendering/StringUtilities.cs
442
C#
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0 { /// <summary> /// Defines identifiers corresponding to the hex digits 0,..,7 /// </summary> public enum Hex3Seq : byte { /// <summary> /// Identifies the hex value 0x00 := 0 /// </summary> x00 = 0x0, /// <summary> /// Identifies the hex value 0x01 := 1 /// </summary> x01 = 0x1, /// <summary> /// Identifies the hex value 0x02 := 2 /// </summary> x02 = 0x2, /// <summary> /// Identifies the hex value 0x03 := 3 /// </summary> x03 = 0x3, /// <summary> /// Identifies the hex value 0x04 := 4 /// </summary> x04 = 0x4, /// <summary> /// Identifies the hex value 0x05 := 5 /// </summary> x05 = 0x5, /// <summary> /// Identifies the hex value 0x06 := 6 /// </summary> x06 = 0x6, /// <summary> /// Identifies the hex value 0x07 := 7 /// </summary> x07 = 0x7, } }
24.615385
79
0.386719
[ "BSD-3-Clause" ]
0xCM/z0
src/root/src/symbols/literals/hex/Hex3Seq.cs
1,280
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using Acme.Biz; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Acme.Common; namespace Acme.Biz.Tests { [TestClass()] public class ProductTests { [TestMethod()] public void CalculateSuggestedPriceTest() { // Arrange var currentProduct = new Product(1, "Saw", ""); currentProduct.Cost = 50m; OperationResult<decimal> expected = new OperationResult<decimal>(55m, ""); // Act var actual = currentProduct.CalculateSuggestedPrice(10m); // Assert Assert.AreEqual(expected.Result, actual.Result); Assert.AreEqual(expected.Message, actual.Message); } [TestMethod()] public void Product_Null() { //Arrange Product currentProduct = null; var companyName = currentProduct?.ProductVendor?.CompanyName; string expected = null; //Act var actual = companyName; //Assert Assert.AreEqual(expected, actual); } [TestMethod()] public void ProductName_Format() { //Arrange var currentProduct = new Product(); currentProduct.ProductName = " Steel Hammer "; var expected = "Steel Hammer"; //Act var actual = currentProduct.ProductName; //Assert Assert.AreEqual(expected, actual); } [TestMethod()] public void ProductName_TooShort() { //Arrange var currentProduct = new Product(); currentProduct.ProductName = "aw"; string expected = null; string expectedMessage = "Product Name must be at least 3 characters"; //Act var actual = currentProduct.ProductName; var actualMessage = currentProduct.ValidationMessage; //Assert Assert.AreEqual(expected, actual); Assert.AreEqual(expectedMessage, actualMessage); } [TestMethod()] public void ProductName_TooLong() { //Arrange var currentProduct = new Product(); currentProduct.ProductName = "Steel Bladed Hand Saw"; string expected = null; string expectedMessage = "Product Name cannot be more than 20 characters"; //Act var actual = currentProduct.ProductName; var actualMessage = currentProduct.ValidationMessage; //Assert Assert.AreEqual(expected, actual); Assert.AreEqual(expectedMessage, actualMessage); } [TestMethod()] public void ProductName_JustRight() { //Arrange var currentProduct = new Product(); currentProduct.ProductName = "Saw"; string expected = "Saw"; string expectedMessage = null; //Act var actual = currentProduct.ProductName; var actualMessage = currentProduct.ValidationMessage; //Assert Assert.AreEqual(expected, actual); Assert.AreEqual(expectedMessage, actualMessage); } } }
27.463415
86
0.565719
[ "MIT" ]
nathanpabst/CSharpBP-Collections
AcmeApp/Tests/Acme.BizTests/ProductTests.cs
3,380
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("TwinkleIIDXExtract")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TwinkleIIDXExtract")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("b86b9579-0c16-4ed3-a606-7bb510a34309")] // 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.747339
[ "BSD-2-Clause" ]
SaxxonPike/scharfrichter
TwinkleIIDXExtract/Properties/AssemblyInfo.cs
1,412
C#
namespace NSW.EliteDangerous.API.Events { public class SystemsShutdownEvent : JournalEvent { internal static SystemsShutdownEvent Execute(string json, API.EliteDangerousAPI api) => api.ShipEvents.InvokeEvent(api.FromJson<SystemsShutdownEvent>(json)); } }
39.142857
165
0.770073
[ "MIT" ]
h0useRus/EliteDangerousAPI
EliteDangerousAPI/src/EliteDangerousAPI/Events/Ship/SystemsShutdownEvent.cs
274
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace EventSourcing.ForgettablePayloads.Extensions.DatabaseMigrations.Persistence.SqlServer { /// <summary> /// Provider of SQL Server database migration scripts /// </summary> public static class SqlServerDatabaseMigrationScriptsProvider { private const string ScriptResourceNamePrefix = "EventSourcing.ForgettablePayloads.Extensions.DatabaseMigrations.Persistence.SqlServer.Scripts."; private static Assembly CurrentAssembly { get; } = typeof(SqlServerDatabaseMigrationScriptsProvider).Assembly; private static IReadOnlyList<string> ResourceNames { get; } = CurrentAssembly .GetManifestResourceNames() .Where(name => name.StartsWith(ScriptResourceNamePrefix)) .OrderBy(name => name) .ToList(); /// <summary> /// Gets database migration scripts for SQL Server. /// </summary> /// <returns> /// A collection of database migration scripts for SQL Server. /// </returns> public static IReadOnlyList<SqlServerScript> GetDatabaseMigrationScripts() { var result = new List<SqlServerScript>(); foreach (var resourceName in ResourceNames) { using (var resourceStream = CurrentAssembly.GetManifestResourceStream(resourceName)) { if (resourceStream == null) { throw new InvalidOperationException($"Could not load resource stream with name {resourceName}"); } using (var streamReader = new StreamReader(resourceStream)) { var content = streamReader.ReadToEnd(); var script = new SqlServerScript( resourceName, content); result.Add(script); } } } return result; } /// <summary> /// Gets database migration scripts for SQL Server in an async manner. /// </summary> /// <returns> /// A task that will return a collection of database migration scripts for SQL Server. /// </returns> public static async Task<IReadOnlyList<SqlServerScript>> GetDatabaseMigrationScriptsAsync() { var result = new List<SqlServerScript>(); foreach (var resourceName in ResourceNames) { using (var resourceStream = CurrentAssembly.GetManifestResourceStream(resourceName)) { if (resourceStream == null) { throw new InvalidOperationException($"Could not load resource stream with name {resourceName}"); } using (var streamReader = new StreamReader(resourceStream)) { var content = await streamReader.ReadToEndAsync().ConfigureAwait(false); var script = new SqlServerScript( resourceName, content); result.Add(script); } } } return result; } } }
38.736264
153
0.547234
[ "MIT" ]
TheName/EventSourcing
EventSourcing.ForgettablePayloads/Persistence/SqlServer/Extensions.DatabaseMigrations.SqlServer/SqlServerDatabaseMigrationScriptsProvider.cs
3,527
C#
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ namespace Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime { internal static class Method { internal static System.Net.Http.HttpMethod Get = System.Net.Http.HttpMethod.Get; internal static System.Net.Http.HttpMethod Put = System.Net.Http.HttpMethod.Put; internal static System.Net.Http.HttpMethod Head = System.Net.Http.HttpMethod.Head; internal static System.Net.Http.HttpMethod Post = System.Net.Http.HttpMethod.Post; internal static System.Net.Http.HttpMethod Delete = System.Net.Http.HttpMethod.Delete; internal static System.Net.Http.HttpMethod Options = System.Net.Http.HttpMethod.Options; internal static System.Net.Http.HttpMethod Trace = System.Net.Http.HttpMethod.Trace; internal static System.Net.Http.HttpMethod Patch = new System.Net.Http.HttpMethod("PATCH"); } }
64.894737
100
0.62206
[ "MIT" ]
Agazoth/azure-powershell
src/StreamAnalytics/generated/runtime/Method.cs
1,215
C#
using System; using System.Activities; namespace Cogito.ServiceFabric.Activities.Test.Activities { public class WriteActivity : CodeActivity { protected override void Execute(CodeActivityContext context) { Console.WriteLine("foo"); } } }
15.789474
68
0.643333
[ "MIT" ]
alethic/Cogito.ServiceFabric.Activities
Cogito.ServiceFabric.Activities.Test.Activities/WriteActivity.cs
302
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Crystallography; using System.IO; namespace PDIndexer { public partial class FormExportGSAS : Form { public FormMain formMain; private DiffractionProfile profile; private void FormExportGSAS_Load(object sender, EventArgs e) { setGsasFileContents(); } public FormExportGSAS() { InitializeComponent(); } private void setGsasFileContents() { double div = 100; if (formMain.AxisMode == HorizontalAxis.NeutronTOF) div = 1; StringBuilder sb = new StringBuilder(); DiffractionProfile dp = (DiffractionProfile)((DataRowView)formMain.bindingSourceProfile.Current).Row[1]; ; //一行目 string str = dp.Name; sb.Append(str + "\r\n"); //二行目 int ptCount = dp.Profile.Pt.Count; double startAngle = dp.Profile.Pt[0].X * div; double stepAngle = (dp.Profile.Pt[1].X - dp.Profile.Pt[0].X) * div; str = "BANK 1 " + ptCount.ToString() + " " + ptCount.ToString() + " CONST " + startAngle.ToString("f2") + " " + stepAngle.ToString("f2") + " 0 0 FXYE"; sb.Append(str + "\r\n"); str = ""; bool validErr = false; if (dp.Profile.Err != null && dp.Profile.Err.Count == dp.Profile.Pt.Count) for (int i = 0; i < ptCount; i++) if (dp.Profile.Err[i].IsNaN && dp.Profile.Err[i].Y != 0) { validErr = true; break; } for (int i = 0; i < ptCount; i++) { string[] value = new string[3]; value[0] = (dp.Profile.Pt[i].X * div).ToString("g12"); value[1] = dp.Profile.Pt[i].Y.ToString("g12"); if (validErr) value[2] = dp.Profile.Err[i].Y.ToString("g12"); else value[2] = Math.Sqrt(dp.Profile.Pt[i].Y).ToString("g12"); string y = dp.Profile.Pt[i].Y.ToString("g7"); for (int j = 0; j < value.Length; j++) { if (value[j].Length > 11) value[j] = value[j].Substring(0, 11); if (value[j].EndsWith(".")) value[j] = " " + y.Substring(0, 10); while (value[j].Length < 11) value[j] = " " + value[j]; } sb.Append(" " + value[0] + " " + value[1] + " " + value[2] + "\r\n"); } richTextBoxGsa.Text = sb.ToString(); #region /* StringBuilder sb = new StringBuilder(); DiffractionProfile dp = (DiffractionProfile)((DataRowView)formMain.bindingSourceProfile.Current).Row[1]; ; //一行目 string str = dp.Name; while (str.Length < 80) str += " "; sb.Append(str+"\r\n"); //二行目 int ptCount = dp.Profile.Pt.Count; double startAngle = dp.Profile.Pt[0].X * 100; double stepAngle = (dp.Profile.Pt[1].X - dp.Profile.Pt[0].X) * 100; str = "BANK 1 " + ptCount.ToString() + " " + (ptCount / 5).ToString() + " CONST " + startAngle.ToString("f2") + " " + stepAngle.ToString("f2") + " 0 0 ESD"; while (str.Length < 80) str += " "; sb.Append(str + "\r\n"); str = ""; int n = 0; for (int i = 0; i < ptCount; i++) { n++; string y = dp.Profile.Pt[i].Y.ToString("g7"); string yErr = Math.Sqrt(dp.Profile.Pt[i].Y).ToString("g8"); if (y.Length > 7) y = y.Substring(0, 7); if (y.EndsWith(".")) y = " " + y.Substring(0, 6); while (y.Length < 7) y = " " + y; if (yErr.Length > 7) yErr = yErr.Substring(0, 7); if (yErr.EndsWith(".")) yErr = " " + yErr.Substring(0, 6); while (yErr.Length < 7) yErr = " " + yErr; str += " " + y + " " + yErr; if (n == 5) { sb.Append(str + "\r\n"); str = ""; n = 0; } else if (i == ptCount - 1) { while (str.Length < 80) str += " "; sb.Append(str + "\r\n"); } } richTextBoxGsa.Text = sb.ToString();*/ #endregion } private void buttonOpen_Click(object sender, EventArgs e) { using var dlg = new OpenFileDialog(); dlg.Filter = "*.exp|*.exp"; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) textBoxExpFilePath.Text = dlg.FileName; else textBoxExpFilePath.Text = ""; } private void textBoxExpFilePath_TextChanged(object sender, EventArgs e) { if(File.Exists(textBoxExpFilePath.Text)) { StreamReader sr = new StreamReader(textBoxExpFilePath.Text); string str; while ((str = sr.ReadLine()) != null) { richTextBoxExp.AppendText(str+"\r\n"); } } } private const string atmdat = ""; } }
37.236686
177
0.409185
[ "MIT" ]
seto77/PDIndexer
PDIndexer/FormExportGSAS.cs
6,319
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; namespace AdventOfCode.Solutions.Year2021 { class Day08 : ASolution { public Day08() : base(08, 2021, "") { } protected override string SolvePartOne(string input) { var lines = input.SplitByNewline(); int total = 0; foreach (var line in lines) { var inputDigits = line.Split(" | ")[0].Split(" "); var outputDigits = line.Split(" | ")[1].Split(" "); var lengths = new List<int>() { 2, 3, 4, 7 }; foreach (string digit in outputDigits) { for (int i = 0; i < lengths.Count; i++) { if (lengths[i] == digit.Length) { total++; } } } } return total.ToString(); } protected override string SolvePartTwo(string input) { var lines = input.SplitByNewline(); var sums = new List<int>(); foreach (var line in lines) { var numsToSegments = new Dictionary<int, HashSet<char>>(); for (int i = 0; i < 10; i++) { numsToSegments[i] = new HashSet<char>(); } var inputDigits = line.Split(" | ")[0].Split(" "); var outputDigits = line.Split(" | ")[1].Split(" "); var lengths = new Dictionary<int, int>(); lengths.Add(0, 6); lengths.Add(1, 2); lengths.Add(2, 5); lengths.Add(3, 5); lengths.Add(4, 4); lengths.Add(5, 5); lengths.Add(6, 6); lengths.Add(7, 3); lengths.Add(8, 7); lengths.Add(9, 6); var uniqueLengths = new List<int> { 1, 4, 7, 8}; foreach (string digit in inputDigits) { foreach (var num in uniqueLengths) { if (lengths[num] == digit.Length) { foreach (char c in digit) { numsToSegments[num].Add(c); } } } } foreach (string digit in inputDigits) { HashSet<char> digitSet = new HashSet<char>(); foreach (var c in digit) { digitSet.Add(c); } if (numsToSegments.Values.Contains(digitSet)) { continue; } else if (digitSet.Count == lengths[0] && digitSet.IsSupersetOf(numsToSegments[7]) && !digitSet.IsSupersetOf(numsToSegments[4])) { numsToSegments[0] = digitSet; } else if (digitSet.Count == lengths[3] && digitSet.IsSupersetOf(numsToSegments[7]) && !digitSet.IsSupersetOf(numsToSegments[4])) { numsToSegments[3] = digitSet; } else if (digitSet.Count == lengths[6] && !digitSet.IsSupersetOf(numsToSegments[7]) && !digitSet.IsSupersetOf(numsToSegments[4])) { numsToSegments[6] = digitSet; } else if (digitSet.Count == lengths[9] && digitSet.IsSupersetOf(numsToSegments[7]) && digitSet.IsSupersetOf(numsToSegments[4])) { numsToSegments[9] = digitSet; } else if (digitSet.Count == lengths[5]) { var intersetTest = digitSet.Intersect(numsToSegments[4]); if (intersetTest.Count() == 3) { numsToSegments[5] = digitSet; } else { numsToSegments[2] = digitSet; } } } string sumString = ""; foreach (string digit in outputDigits) { HashSet<char> digitSet = new HashSet<char>(); foreach (var c in digit) { digitSet.Add(c); } foreach (var entry in numsToSegments) { if (entry.Value.SetEquals(digitSet)) { sumString += entry.Key; } } } sums.Add(Convert.ToInt32(sumString)); } return sums.Sum().ToString(); } } }
31.085714
81
0.369301
[ "MIT" ]
SpiritBlues7/AdventOfCode
AdventOfCode/Solutions/Year2021/Day08/Day08.cs
5,440
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEditor; using UnityEngine; namespace ChartAndGraph { class EditorMenu { private static void InstanciateCanvas(string path) { Canvas[] canvases = GameObject.FindObjectsOfType<Canvas>(); if (canvases == null || canvases.Length == 0) { EditorUtility.DisplayDialog("No canvas in scene", "Please add a canvas to the scene and try again", "Ok"); return; } Canvas canvas = null; foreach(Canvas c in canvases) { if(c.transform.parent == null) { canvas = c; break; } } if (canvas == null) { EditorUtility.DisplayDialog("No canvas in scene", "Please add a canvas to the scene and try again", "Ok"); return; } GameObject obj = AssetDatabase.LoadAssetAtPath<GameObject>(path); GameObject newObj = (GameObject)GameObject.Instantiate(obj); newObj.transform.SetParent(canvas.transform,false); newObj.name = newObj.name.Replace("(Clone)",""); Undo.RegisterCreatedObjectUndo(newObj, "Create Object"); } private static void InstanciateWorldSpace(string path) { GameObject obj = AssetDatabase.LoadAssetAtPath<GameObject>(path); GameObject newObj = (GameObject)GameObject.Instantiate(obj); newObj.name = newObj.name.Replace("(Clone)", ""); Undo.RegisterCreatedObjectUndo(newObj, "Create Object"); } [MenuItem("Tools/Charts/Clear All")] public static void ClearChartGarbage() { ChartItem[] children = GameObject.FindObjectsOfType<ChartItem>(); for (int i = 0; i < children.Length; ++i) { if (children[i] != null) { ChartCommon.SafeDestroy(children[i].gameObject); } } } [MenuItem("Tools/Charts/Radar/Canvas")] public static void AddRadarChartCanvas() { InstanciateCanvas("Assets/Chart and Graph/Prefabs/MenuPrefabs/2DRadar.prefab"); } [MenuItem("Tools/Charts/Radar/3D")] public static void AddRadarChartWorldSpace() { InstanciateWorldSpace("Assets/Chart and Graph/Prefabs/MenuPrefabs/3DRadar.prefab"); } [MenuItem("Tools/Charts/Bar/Canvas/Simple")] public static void AddBarChartSimpleCanvas() { InstanciateCanvas("Assets/Chart and Graph/Prefabs/MenuPrefabs/BarCanvasSimple.prefab"); } [MenuItem("Tools/Charts/Bar/Canvas/Multiple Groups")] public static void AddBarChartMultipleCanvas() { InstanciateCanvas("Assets/Chart and Graph/Prefabs/MenuPrefabs/BarCanvasMultiple.prefab"); } [MenuItem("Tools/Charts/Bar/3D/Simple")] public static void AddBarChartSimple3D() { InstanciateWorldSpace("Assets/Chart and Graph/Prefabs/MenuPrefabs/Bar3DSimple.prefab"); } [MenuItem("Tools/Charts/Bar/3D/Multiple Groups")] public static void AddBarChartMultiple3D() { InstanciateWorldSpace("Assets/Chart and Graph/Prefabs/MenuPrefabs/Bar3DMultiple.prefab"); } [MenuItem("Tools/Charts/Torus/Canvas")] public static void AddTorusChartCanvas() { InstanciateCanvas("Assets/Chart and Graph/Prefabs/MenuPrefabs/TorusCanvas.prefab"); } [MenuItem("Tools/Charts/Pie/Canvas")] public static void AddPieChartCanvas() { InstanciateCanvas("Assets/Chart and Graph/Prefabs/MenuPrefabs/PieCanvas.prefab"); } [MenuItem("Tools/Charts/Torus/3D")] public static void AddTorusChart3D() { InstanciateWorldSpace("Assets/Chart and Graph/Prefabs/MenuPrefabs/Torus3D.prefab"); } [MenuItem("Tools/Charts/Pie/3D")] public static void AddPieChart3D() { InstanciateWorldSpace("Assets/Chart and Graph/Prefabs/MenuPrefabs/Pie3D.prefab"); } [MenuItem("Tools/Charts/Graph/Canvas/Simple")] public static void AddGraphSimple() { InstanciateCanvas("Assets/Chart and Graph/Prefabs/MenuPrefabs/GraphSimple.prefab"); } [MenuItem("Tools/Charts/Graph/Canvas/Multiple")] public static void AddGraphMultiple() { InstanciateCanvas("Assets/Chart and Graph/Prefabs/MenuPrefabs/GraphMultiple.prefab"); } [MenuItem("Tools/Charts/Bubble/3D")] public static void Add3DBubble() { InstanciateWorldSpace("Assets/Chart and Graph/Prefabs/MenuPrefabs/3DBubble.prefab"); } [MenuItem("Tools/Charts/Bubble/Canvas")] public static void AddCanvasBubble() { InstanciateCanvas("Assets/Chart and Graph/Prefabs/MenuPrefabs/2DBubble.prefab"); } [MenuItem("Tools/Charts/Graph/3D")] public static void AddGraph3D() { InstanciateWorldSpace("Assets/Chart and Graph/Prefabs/MenuPrefabs/3DGraph.prefab"); } [MenuItem("Tools/Charts/Legend")] public static void AddChartLegend() { InstanciateCanvas("Assets/Chart and Graph/Prefabs/MenuPrefabs/Legend.prefab"); } } }
35.201258
122
0.595676
[ "MIT" ]
bigdot-app/BigDOT
Assets/Editor/Chart And Graph/EditorMenu.cs
5,599
C#
using Checkout.ApiServices.Cards.RequestModels; using Checkout.ApiServices.Charges.RequestModels; using Checkout.ApiServices.Customers.RequestModels; using Checkout.ApiServices.Reporting.RequestModels; using Checkout.ApiServices.RecurringPayments.RequestModels; using Checkout.ApiServices.SharedModels; using Checkout.ApiServices.Tokens.RequestModels; using System; using System.Collections.Generic; using System.Linq; using Tests.Utils; using FilterAction = Checkout.ApiServices.SharedModels.Action; namespace Tests { public class TestHelper { private static RandomData _randomData; public static RandomData RandomData{ get{ return _randomData ?? (_randomData = new RandomData());} } #region Recurring Plans Helpers public static SinglePaymentPlanCreateRequest GetSinglePaymentPlanCreateModel(string value = null, string currency = null) { return new SinglePaymentPlanCreateRequest { PaymentPlans = new List<PaymentPlanCreate> { new PaymentPlanCreate { Name = RandomData.String, AutoCapTime = RandomData.GetNumber(0, 168), Currency = currency ?? "USD", PlanTrackId = RandomData.UniqueString, Value = value ?? RandomData.GetNumber(50, 500).ToString(), RecurringCount = RandomData.GetNumber(1, 19), Cycle = "1d" } } }; } public static PaymentPlanUpdate GetPaymentPlanUpdateModel(string value = null, string currency = null) { return new PaymentPlanUpdate { Name = RandomData.String, AutoCapTime = RandomData.GetNumber(0, 168), Currency = currency ?? "GBP", PlanTrackId = RandomData.UniqueString, Value = value ?? RandomData.GetNumber(50, 500).ToString(), RecurringCount = RandomData.GetNumber(1, 19), Cycle = "3d", Status = RecurringPlanStatus.Suspended }; } public static CustomerPaymentPlanCreate GetCustomerPaymentPlanCreateModel(string value = null, string currency = null) { return new CustomerPaymentPlanCreate { Name = RandomData.String, AutoCapTime = 0, PlanTrackId = RandomData.UniqueString, Value = value ?? RandomData.GetNumber(50, 500).ToString(), RecurringCount = RandomData.GetNumber(1, 19), Cycle = "3d" }; } public static CustomerPaymentPlanUpdate GetCustomerPaymentPlanUpdateModel(string cardId, RecurringPlanStatus status) { return new CustomerPaymentPlanUpdate { Status = status, CardId = cardId }; } public static CardCharge GetCardChargeCreateModelWithNewPaymentPlan(string customerEmail = null, string customerId = null) { return new CardCharge { CustomerId = customerId, Email = customerEmail, AutoCapture = "N", AutoCapTime = 0, Currency = "Usd", TrackId = "TRK12345", TransactionIndicator = "1", CustomerIp = "82.23.168.254", Description = RandomData.String, Value = RandomData.GetNumber(50, 500).ToString(), Card = GetCardCreateModel(), Descriptor = new BillingDescriptor { Name = "Amigo ltd.", City = "London" }, Products = GetProducts(), ShippingDetails = GetAddress(), Metadata = new Dictionary<string, string>() { { "extraInformation", RandomData.CompanyName } }, Udf1 = RandomData.String, Udf2 = RandomData.String, Udf3 = RandomData.String, Udf4 = RandomData.String, Udf5 = RandomData.String, PaymentPlans = new List<CustomerPaymentPlanCreate> { GetCustomerPaymentPlanCreateModel() } }; } public static CardCharge GetCardChargeCreateModelWithExistingPaymentPlan(string planId, string startDate = null, string customerEmail = null, string customerId = null) { return new CardCharge { CustomerId = customerId, Email = customerEmail, AutoCapture = "N", AutoCapTime = 0, Currency = "Usd", TrackId = "TRK12345", TransactionIndicator = "1", CustomerIp = "82.23.168.254", Description = RandomData.String, Value = RandomData.GetNumber(50, 500).ToString(), Card = GetCardCreateModel(), Descriptor = new BillingDescriptor { Name = "Amigo ltd.", City = "London" }, Products = GetProducts(), ShippingDetails = GetAddress(), Metadata = new Dictionary<string, string>() { { "extraInformation", RandomData.CompanyName } }, Udf1 = RandomData.String, Udf2 = RandomData.String, Udf3 = RandomData.String, Udf4 = RandomData.String, Udf5 = RandomData.String, PaymentPlans = new List<CustomerPaymentPlanCreate> { new CustomerPaymentPlan { PlanId = planId, StartDate = startDate} } }; } public static QueryPaymentPlanRequest GetCustomQueryPaymentPlanRequest(string propertyName, object value, string currency = null) { var queryRequest = new QueryPaymentPlanRequest(); ReflectionHelper.SetPropertyValue(queryRequest, propertyName, value); // set currency in request when querying by value if (propertyName == "Value") { queryRequest.Currency = currency; } return queryRequest; } public static QueryCustomerPaymentPlanRequest GetCustomQueryCustomerPaymentPlanRequest(string propertyName, object value, string currency = null) { var queryRequest = new QueryCustomerPaymentPlanRequest(); ReflectionHelper.SetPropertyValue(queryRequest, propertyName, value); // set currency in request when querying by value if (propertyName == "Value") { queryRequest.Currency = currency; } return queryRequest; } public static object GetRecurringPlanPropertyValue(object source, string propertyName) { var propertyValue = ReflectionHelper.GetPropertyValue(source, propertyName); // converts date into YYYY-MM-DD format if (propertyName.IndexOf("Date", StringComparison.OrdinalIgnoreCase) >= 0) { propertyValue = Convert.ToDateTime(propertyValue).ToString("yyyy-MM-dd"); } return propertyValue; } #endregion #region Token Helpers public static PaymentTokenCreate GetPaymentTokenCreateModel(string email, int chargeMode = 1, string currency = "usd") { return new PaymentTokenCreate() { Currency = currency, Value = RandomData.GetNumber(50, 500).ToString(), AutoCapTime = 1, AutoCapture = "N", ChargeMode = chargeMode, Email = email, CustomerIp = "82.23.168.254", TrackId = "TRK12345", Description = RandomData.String, Products = GetProducts(), ShippingDetails = GetAddress(), Metadata = new Dictionary<string, string>() { { "extraInformation", RandomData.CompanyName } }, Udf1 = RandomData.String, Udf2 = RandomData.String, Udf3 = RandomData.String, Udf4 = RandomData.String, Udf5 = RandomData.String, }; } #endregion #region Card Helpers public static Address GetAddressModel() { return new Address() { AddressLine1 = RandomData.StreetAddress, AddressLine2 = RandomData.String, City = RandomData.City, Country = RandomData.CountryISO2, Phone = GetPhone(), Postcode = RandomData.PostCode, State = RandomData.City }; } public static BaseCard GetBaseCardModel(CardProvider cardProvider=CardProvider.Visa) { if( cardProvider == CardProvider.Visa ) { return new BaseCard() { ExpiryMonth = "06", ExpiryYear = "2018", Name = RandomData.FullName, BillingDetails = GetAddressModel() }; }else { return new BaseCard() { ExpiryYear = "2017", ExpiryMonth = "06", Name = RandomData.FullName, BillingDetails = GetAddressModel() }; } } public static CardCreate GetCardCreateModel(CardProvider cardProvider=CardProvider.Visa) { CardCreate card=new CardCreate(); var baseCard = GetBaseCardModel(cardProvider); card.Name = baseCard.Name; card.ExpiryMonth = baseCard.ExpiryMonth; card.ExpiryYear = baseCard.ExpiryYear; card.BillingDetails = baseCard.BillingDetails; if (cardProvider == CardProvider.Visa) { card.Cvv = "100"; card.Number = "4242424242424242"; } else { card.Cvv = "257"; card.Number = "5313581000123430"; } return card; } public static CardUpdate GetCardUpdateModel(bool setDefaultCard=false) { CardUpdate card = new CardUpdate(); var baseCard = GetBaseCardModel(); card.Name = baseCard.Name; card.ExpiryMonth = baseCard.ExpiryMonth; card.ExpiryYear = baseCard.ExpiryYear; card.BillingDetails = baseCard.BillingDetails; card.DefaultCard = setDefaultCard; return card; } #endregion #region Customer Helpers public static CustomerCreate GetCustomerCreateModelWithCard(CardProvider cardProvider = CardProvider.Visa) { return new CustomerCreate() { Name = RandomData.FullName, Description = RandomData.String, Email = RandomData.Email, Phone = GetPhone(), Metadata = new Dictionary<string, string>() { { "channelInfo", RandomData.CompanyName } }, Card = GetCardCreateModel(cardProvider) }; } public static CustomerCreate GetCustomerCreateModelWithNoCard() { var customerCreateModel = GetCustomerCreateModelWithCard(); customerCreateModel.Card = null; return customerCreateModel; } public static CustomerUpdate GetCustomerUpdateModel() { return new CustomerUpdate() { Name = RandomData.FullName, Description = RandomData.String, Email = RandomData.Email, Phone = GetPhone(), Metadata = new Dictionary<string, string>() { { "channelInfo", RandomData.CompanyName } } }; } private static Phone GetPhone() { return new Phone() { CountryCode = "1", Number = "999 999 9999" }; } public static DefaultCardCharge GetCustomerDefaultCardChargeCreateModel(string customerId) { DefaultCardCharge defaultCardCharge = new DefaultCardCharge { CustomerId = customerId, AutoCapture = "Y", AutoCapTime = 10, Currency = "Usd", TrackId = "TRK12345", TransactionIndicator = "1", CustomerIp = "82.23.168.254", Description = RandomData.String, Value = RandomData.GetNumber(50, 500).ToString(), Descriptor = new BillingDescriptor { Name = "Amigo ltd.", City = "London" }, Products = GetProducts(), ShippingDetails = GetAddress(), Metadata = new Dictionary<string, string>() { { "extraInformation", RandomData.CompanyName } }, Udf1 = RandomData.String, Udf2 = RandomData.String, Udf3 = RandomData.String, Udf4 = RandomData.String, Udf5 = RandomData.String }; return defaultCardCharge; } #endregion #region Charge Helpers public static CardCharge GetCardChargeCreateModel(string customerEmail = null,string customerId = null) { return new CardCharge() { CustomerId = customerId, Email = customerEmail, AutoCapture = "N", AutoCapTime = 0, Currency = "Usd", TrackId = "TRK12345", TransactionIndicator="1", CustomerIp="82.23.168.254", Description = RandomData.String, Value = RandomData.GetNumber(50, 500).ToString(), Card = GetCardCreateModel(), Descriptor =new BillingDescriptor { Name = "Amigo ltd.", City = "London" }, Products = GetProducts(), ShippingDetails = GetAddress(), Metadata = new Dictionary<string, string>() { { "extraInformation", RandomData.CompanyName } }, Udf1 = RandomData.String, Udf2 = RandomData.String, Udf3 = RandomData.String, Udf4 = RandomData.String, Udf5 = RandomData.String, RiskCheck = true }; } public static Address GetAddress() { return new Address { AddressLine1 = RandomData.StreetAddress, AddressLine2 = RandomData.String, City = RandomData.City, Country = RandomData.CountryISO2, Phone = GetPhone(), Postcode = RandomData.PostCode, State = RandomData.City }; } public static List<Product> GetProducts(int numOfProducts = 1) { var productList = new List<Product>(); Product product; for (int i = 0; i <= numOfProducts; i++) { product = new Product { Description = RandomData.String, Image = "http://www.imageurl.com/me.png", Name = "test product" + i, Price = RandomData.GetNumber(50, 500), Quantity = RandomData.GetNumber(1, 100), ShippingCost = RandomData.GetDecimalNumber(), Sku = RandomData.UniqueString, TrackingUrl = "http://www.track.com?ref=12345" }; productList.Add(product); } return productList; } public static CardIdCharge GetCardIdChargeCreateModel(string cardId, string customerEmail = null, string customerId = null) { return new CardIdCharge() { CardId=cardId, Cvv = "100", CustomerId = customerId, Email = customerEmail, AutoCapture = "Y", AutoCapTime = 10, Currency = "Usd", Description = RandomData.String, Value = RandomData.GetNumber(50, 500).ToString(), Products = GetProducts(), ShippingDetails = GetAddress(), Metadata = new Dictionary<string, string>() { { "extraInformation", RandomData.CompanyName } }, Descriptor = new BillingDescriptor { Name = "Amigo ltd.", City = "London" } }; } public static CardTokenCharge GetCardTokenChargeCreateModel(string cardToken, string customerEmail = null, string customerId = null) { return new CardTokenCharge() { CardToken = cardToken, CustomerId = customerId, Email = customerEmail?? RandomData.Email, AutoCapture = "Y", AutoCapTime = 10, Currency = "Usd", Description = RandomData.String, Value = RandomData.GetNumber(50, 500).ToString(), Descriptor = new BillingDescriptor { Name = "Amigo ltd.", City = "London" } }; } public static BaseCharge GetBaseChargeModel(string customerEmail = null, string customerId = null) { return new BaseCharge() { CustomerId = customerId, Email = customerEmail, AutoCapture = "Y", AutoCapTime = 10, Currency = "Usd", Description = RandomData.String, Value = RandomData.GetNumber(50, 500).ToString() }; } public static ChargeRefund GetChargeRefundModel(string amount=null) { return new ChargeRefund() { Value = amount, TrackId = "TRK12345", Description = RandomData.String, Products = GetProducts(), Metadata = new Dictionary<string, string>() { { "extraInformation", RandomData.CompanyName } }, Udf1 = RandomData.String, Udf2 = RandomData.String, Udf3 = RandomData.String, Udf4 = RandomData.String, Udf5 = RandomData.String }; } public static ChargeUpdate GetChargeUpdateModel() { return new ChargeUpdate() { TrackId = "TRK12345", Description = RandomData.String, Metadata = new Dictionary<string, string>() { { "extraInformation", RandomData.CompanyName }, { "extraInformation2", RandomData.String } }, Udf1 = RandomData.String, Udf2 = RandomData.String, Udf3 = RandomData.String, Udf4 = RandomData.String, Udf5 = RandomData.String }; } public static PaymentTokenUpdate GetPaymentTokenUpdateModel() { return new PaymentTokenUpdate() { TrackId = "TRK12345", Description = RandomData.String, Metadata = new Dictionary<string, string>() { { "extraInformation", RandomData.CompanyName }, { "extraInformation2", RandomData.String } }, Udf1 = RandomData.String, Udf2 = RandomData.String, Udf3 = RandomData.String, Udf4 = RandomData.String, Udf5 = RandomData.String }; } public static ChargeCapture GetChargeCaptureModel(string amount=null) { return new ChargeCapture() { Value = amount, TrackId = "TRK12345", Description = RandomData.String, Products = GetProducts(), Metadata = new Dictionary<string, string>() { { "extraInformation", RandomData.CompanyName } }, Udf1 = RandomData.String, Udf2 = RandomData.String, Udf3 = RandomData.String, Udf4 = RandomData.String, Udf5 = RandomData.String }; } public static ChargeVoid GetChargeVoidModel() { return new ChargeVoid() { TrackId = "TRK12345", Description = RandomData.String, Products = GetProducts(), Metadata = new Dictionary<string, string>() { { "extraInformation", RandomData.CompanyName } }, Udf1 = RandomData.String, Udf2 = RandomData.String, Udf3 = RandomData.String, Udf4 = RandomData.String, Udf5 = RandomData.String }; } public static LocalPaymentCharge GetLocalPaymentChargeModel(string paymentToken, string lppId = "lpp_9", Dictionary<string, string> userData = null) { var localPayment = new LocalPaymentCharge { Email = RandomData.Email, LocalPayment = new LocalPaymentCreate { LppId = lppId, UserData = userData ?? new Dictionary <string, string> { { "issuerId", "INGBNL2A" } } }, PaymentToken = paymentToken }; return localPayment; } #endregion #region Reporting Helpers /// <summary> /// Creates a model for a dynamic reporting query /// </summary> /// <param name="searchValue"></param> /// <param name="fromDate"></param> /// <param name="toDate"></param> /// <param name="sortColumn"></param> /// <param name="sortOrder"></param> /// <param name="pageSize"></param> /// <param name="pageNumber"></param> /// <param name="filters"></param> /// <returns></returns> public static QueryRequest GetQueryRequest(string searchValue = null, DateTime? fromDate = null, DateTime? toDate = null, SortColumn? sortColumn = null, SortOrder? sortOrder = null, int? pageSize = null, string pageNumber = null, List<Filter> filters = null) { return new QueryRequest() { FromDate = fromDate, ToDate = toDate, PageSize = pageSize, PageNumber = pageNumber, SortColumn = sortColumn, SortOrder = sortOrder, Search = searchValue, Filters = filters }; } /// <summary> /// Creates a model for the transactions dynamic query using filters /// </summary> /// <param name="filters"></param> /// <returns></returns> public static QueryRequest GetQueryRequest(List<Filter> filters) { return GetQueryRequest(null, null, null, null, null, null, null, filters); } /// <summary> /// Creates an empty model for the transactions dynamic query /// </summary> /// <returns></returns> public static QueryRequest GetQueryRequest() { return GetQueryRequest(null); } #endregion /// <summary> /// Masks a card number to query transactions /// eg: 4242424242424242 -> 424242******4242 /// </summary> /// <param name="cardNumber"></param> /// <returns></returns> public static string MaskCardNumber(string cardNumber) { return cardNumber.Replace(6, 6, '*'); } } }
38.373817
156
0.5216
[ "MIT" ]
adrien117/client-sdk
Checkout.ApiClient.Tests/TestHelper.cs
24,331
C#
using System; // ReSharper disable once CheckNamespace namespace DlibDotNet { public sealed partial class PerspectiveWindow { public sealed class OverlayDot : DlibObject { #region Constructors public OverlayDot(Vector<double> point) : this(NativeMethods.perspective_window_overlay_dot_new(point.NativePtr)) { } public OverlayDot(Vector<double> point, byte pixel) : this(NativeMethods.perspective_window_overlay_dot_new2(point.NativePtr, NativeMethods.Array2DType.UInt8, ref pixel)) { } public OverlayDot(Vector<double> point, ushort pixel) : this(NativeMethods.perspective_window_overlay_dot_new2(point.NativePtr, NativeMethods.Array2DType.UInt16, ref pixel)) { } public OverlayDot(Vector<double> point, short pixel) : this(NativeMethods.perspective_window_overlay_dot_new2(point.NativePtr, NativeMethods.Array2DType.Int16, ref pixel)) { } public OverlayDot(Vector<double> point, int pixel) : this(NativeMethods.perspective_window_overlay_dot_new2(point.NativePtr, NativeMethods.Array2DType.Int32, ref pixel)) { } public OverlayDot(Vector<double> point, float pixel) : this(NativeMethods.perspective_window_overlay_dot_new2(point.NativePtr, NativeMethods.Array2DType.Float, ref pixel)) { } public OverlayDot(Vector<double> point, double pixel) : this(NativeMethods.perspective_window_overlay_dot_new2(point.NativePtr, NativeMethods.Array2DType.Double, ref pixel)) { } public OverlayDot(Vector<double> point, RgbPixel pixel) : this(NativeMethods.perspective_window_overlay_dot_new2(point.NativePtr, NativeMethods.Array2DType.RgbPixel, ref pixel)) { } public OverlayDot(Vector<double> point, RgbAlphaPixel pixel) : this(NativeMethods.perspective_window_overlay_dot_new2(point.NativePtr, NativeMethods.Array2DType.RgbAlphaPixel, ref pixel)) { } public OverlayDot(Vector<double> point, HsiPixel pixel) : this(NativeMethods.perspective_window_overlay_dot_new2(point.NativePtr, NativeMethods.Array2DType.HsiPixel, ref pixel)) { } internal OverlayDot(IntPtr ptr) { if (ptr == IntPtr.Zero) throw new ArgumentException("Can not pass IntPtr.Zero", nameof(ptr)); this.NativePtr = ptr; } #endregion #region Properties public RgbPixel Color { get { var color = new RgbPixel(); NativeMethods.perspective_window_overlay_dot_color(this.NativePtr, ref color); return color; } } public Vector<double> Point { get { NativeMethods.perspective_window_overlay_dot_p(this.NativePtr, out var point); return new Vector<double>(point); } } #endregion #region Methods #region Overrides /// <summary> /// Releases all unmanaged resources. /// </summary> protected override void DisposeUnmanaged() { base.DisposeUnmanaged(); if (this.NativePtr == IntPtr.Zero) return; NativeMethods.perspective_window_overlay_dot_delete(this.NativePtr); } #endregion #endregion } } }
31.629032
140
0.568587
[ "MIT" ]
LunaRyuko/DlibDotNet
src/DlibDotNet/GuiWidgets/OverlayDot.cs
3,924
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using System.Web; using AzureBlobFileSystem.Contract; using AzureBlobFileSystem.Extensions; using AzureBlobFileSystem.Model; using Microsoft.WindowsAzure.Storage.Blob; using FileInfo = AzureBlobFileSystem.Model.FileInfo; namespace AzureBlobFileSystem.Implementation { public class StorageFileService : IStorageFileService { private readonly IAzureStorageProvider _azureStorageProvider; private readonly IAzureBlobItemService _azureBlobItemService; private readonly IAzureCdnService _azureCdnService; private readonly IPathValidationService _pathValidationService; private readonly IFileInfoService _fileInfoService; private readonly IBlobMetadataService _blobMetadataService; private readonly IMetadataValidationService _metadataValidationService; public StorageFileService(IAzureStorageProvider azureStorageProvider, IAzureBlobItemService azureBlobItemService, IAzureCdnService azureCdnService, IPathValidationService pathValidationService, IFileInfoService fileInfoService, IBlobMetadataService blobMetadataService, IMetadataValidationService metadataValidationService) { _azureStorageProvider = azureStorageProvider; _azureBlobItemService = azureBlobItemService; _azureCdnService = azureCdnService; _pathValidationService = pathValidationService; _fileInfoService = fileInfoService; _blobMetadataService = blobMetadataService; _metadataValidationService = metadataValidationService; } public FileInfo Create(string path, BlobMetadata blobMetadata = null, Stream stream = null, bool preLoadToCdn = false) { _pathValidationService.ValidateNotEmpty(path); _metadataValidationService.ValidateMetadata(blobMetadata); CloudBlobContainer container = _azureStorageProvider.Container; path = container.EnsureFileDoesNotExist(path); var blob = container.GetBlockBlobReference(path); TrySetContentType(blob, path); TryUploadStream(stream, blob, blobMetadata); if (preLoadToCdn && stream != null) { _azureCdnService.LoadAsync(path).GetAwaiter(); } return new FileInfo { Metadata = blobMetadata, RelativePath = path }; } public List<FileInfo> List(string prefix, bool firstLevelOnly = false, bool includeMetadata = false) { var listingDetails = GetListingDetails(includeMetadata); var blobItems = _azureBlobItemService.ListBlobsAsync(prefix, listingDetails).Result; if (firstLevelOnly) { blobItems = FilterChildBlobItems(prefix, blobItems).ToList(); } return _fileInfoService.Build(blobItems, includeMetadata); } public async Task CopyAsync(string sourcePath, string destinationPath, bool keepSource = true, bool updateCdn = false) { var container = _azureStorageProvider.Container; await CopyAsync(container, sourcePath, destinationPath, keepSource, updateCdn); } public async Task CopyAsync(CloudBlobContainer container, string sourcePath, string destinationPath, bool keepSource) { await CopyAsync(container, sourcePath, destinationPath, keepSource, false); } public void Delete(string path, bool purgeCdn = false) { _pathValidationService.ValidateFileExists(path); var container = _azureStorageProvider.Container; if (!container.FileExists(path)) { return; } var blob = container.GetBlockBlobReference(path); DeleteAsync(blob, purgeCdn).GetAwaiter(); } public async Task DeleteAsync(CloudBlockBlob blob) { await DeleteAsync(blob, false); } private async Task DeleteAsync(CloudBlockBlob blob, bool purgeCdn) { blob.Delete(); if (purgeCdn) { await _azureCdnService.PurgeAsync(blob.Name); } } private static BlobListingDetails GetListingDetails(bool includeMetadata) { return includeMetadata ? BlobListingDetails.Metadata : BlobListingDetails.None; } private async Task CopyAsync(CloudBlobContainer container, string sourcePath, string destinationPath, bool keepSource, bool updateCdn) { _pathValidationService.ValidateFileExists(sourcePath, container); destinationPath = container.EnsureFileDoesNotExist(destinationPath); var source = container.GetBlockBlobReference(sourcePath); var target = container.GetBlockBlobReference(destinationPath); await target.StartCopyAsync(source); if (updateCdn) { await _azureCdnService.LoadAsync(destinationPath); } if (!keepSource) { source.Delete(); if (updateCdn) { await _azureCdnService.PurgeAsync(sourcePath); } } } private IEnumerable<IListBlobItem> FilterChildBlobItems(string prefix, List<IListBlobItem> blobItems) { prefix = $"{prefix}/"; foreach (var blobItem in blobItems) { var cloudBlockBlob = blobItem as CloudBlockBlob; if (cloudBlockBlob == null) { continue; } var temp = cloudBlockBlob.Name.Replace(prefix, string.Empty); if (temp.IndexOf("/", StringComparison.Ordinal) == -1) { yield return blobItem; } } } private static void TrySetContentType(CloudBlob blob, string path) { var contentType = MimeMapping.GetMimeMapping(path); if (!string.IsNullOrWhiteSpace(contentType)) { blob.Properties.ContentType = contentType; } } private void TryUploadStream(Stream stream, CloudBlockBlob blob, BlobMetadata blobMetadata) { if (stream == null) { blob.UploadFromByteArray(new byte[0], 0, 0); } else { _blobMetadataService.TrySet(blob, blobMetadata); blob.UploadFromStream(stream); } } } }
35.901042
142
0.619324
[ "MIT" ]
mihaicrisanbodea/azureFileSystem
AzureBlobFileSystem/Implementation/StorageFileService.cs
6,893
C#
namespace Fish_Aquarium_Project { partial class Form1 { /// <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 Windows Form 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.timer1 = new System.Windows.Forms.Timer(this.components); this.button2 = new System.Windows.Forms.Button(); this.button1 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // timer1 // this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // button2 // this.button2.BackColor = System.Drawing.Color.Transparent; this.button2.BackgroundImage = global::Fish_Aquarium_Project.Properties.Resources.shroom; this.button2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.button2.ForeColor = System.Drawing.SystemColors.ControlText; this.button2.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button2.Location = new System.Drawing.Point(20, 75); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(50, 50); this.button2.TabIndex = 2; this.button2.UseVisualStyleBackColor = false; this.button2.Click += new System.EventHandler(this.button2_Click); // // button1 // this.button1.BackColor = System.Drawing.SystemColors.ControlDarkDark; this.button1.BackgroundImage = global::Fish_Aquarium_Project.Properties.Resources.image0; this.button1.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.button1.ForeColor = System.Drawing.SystemColors.ControlText; this.button1.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft; this.button1.Location = new System.Drawing.Point(20, 19); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(50, 50); this.button1.TabIndex = 1; this.button1.UseVisualStyleBackColor = false; this.button1.Click += new System.EventHandler(this.button1_Click); // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.ActiveCaption; this.ClientSize = new System.Drawing.Size(997, 468); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Timer timer1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; } }
43.10989
108
0.58858
[ "Apache-2.0" ]
EthanLawr/ComputerScience
Computer Science/Year_2_CSharp/Fish_Aquarium_Project_Solution/Fish_Aquarium_Project/Form1.Designer.cs
3,925
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace RVHD.Models.ManageViewModels { public class AddPhoneNumberViewModel { [Required] [Phone] [Display(Name = "Phone number")] public string PhoneNumber { get; set; } } }
21.411765
47
0.695055
[ "Apache-2.0" ]
nguyendev/RVHD
Code/RVHD/Models/ManageViewModels/AddPhoneNumberViewModel.cs
366
C#
using MaSch.Console.Cli.Runtime; using MaSch.Console.Cli.Runtime.Validators; using MaSch.Core.Extensions; using MaSch.Test; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Moq.Language; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace MaSch.Console.Cli.UnitTests.Runtime { [TestClass] public class CliArgumentParserTests : TestClassBase { private delegate bool CliValidatorDelegate(CliExecutionContext context, object optionsObj, [MaybeNullWhen(true)] out IEnumerable<CliError>? errors); private delegate bool CliValidatableDelegate(CliExecutionContext context, [MaybeNullWhen(true)] out IEnumerable<CliError>? errors); private ICliCommandInfo? DefaultCommand { get => Cache.GetValue<ICliCommandInfo?>(() => null); set => Cache.SetValue(value); } private Mock<IServiceProvider> ServiceProvider => Cache.GetValue(() => Mocks.Create<IServiceProvider>())!; private List<ICliCommandInfo> Commands => Cache.GetValue(() => new List<ICliCommandInfo>())!; private Mock<ICliCommandInfoCollection> CommandsMock => Cache.GetValue(() => CreateCommandsMock(Commands))!; private CliApplicationOptions AppOptions => Cache.GetValue(() => new CliApplicationOptions())!; private Mock<ICliApplicationBase> ApplicationMock => Cache.GetValue(() => CreateApplicationMock())!; private List<ICliValidator<object>> Validators => Cache.GetValue(() => new List<ICliValidator<object>>())!; private CliArgumentParser Parser => Cache.GetValue(() => new CliArgumentParser(ApplicationMock.Object, Validators, ServiceProvider.Object))!; [TestMethod] [DataRow(true, DisplayName = "Args: null")] [DataRow(false, DisplayName = "Args: empty array")] public void Parse_NoCommand_NoDefaultCommand(bool nullArgs) { var result = CallParse(nullArgs ? null! : Array.Empty<string>()); AssertFailedParserResult(result, x => x.Type, CliErrorType.MissingCommand); } [TestMethod] [DataRow(true, DisplayName = "Args: null")] [DataRow(false, DisplayName = "Args: empty array")] public void Parse_NoCommand_WithDefaultCommand(bool nullArgs) { var command = Mocks.Create<ICliCommandInfo>(); _ = command.Setup(x => x.CommandType).Returns(typeof(DummyClass1)).Verifiable(Verifiables, Times.Once()); DefaultCommand = command.Object; var result = CallParse(nullArgs ? null! : Array.Empty<string>()); AssertSuccessfulParserResult<DummyClass1>(result, command.Object); } [TestMethod] public void Parse_NoCommand_WithDefaultCommand_WithValue() { var optionsInstance = new DummyClass1(); var value = CreateCliCommandValueMock<string>(0); var command = CreateCliCommandMock<DummyClass1>( new[] { "blub" }, values: new[] { value.Object }, optionsInstance: optionsInstance); _ = value.Setup(x => x.SetValue(optionsInstance, "blubbi")).Verifiable(Verifiables, Times.Once()); DefaultCommand = command.Object; var result = CallParse("blubbi"); AssertSuccessfulParserResult(result, command.Object, optionsInstance); } [TestMethod] public void Parse_UnknownCommand() { var result = CallParse("blub"); AssertFailedParserResult( result, x => (x.Type, x.CommandName), (CliErrorType.UnknownCommand, "blub")); } [TestMethod] [DataRow("HELP", null, false, false, DisplayName = "Different casing")] [DataRow("help", null, false, false, DisplayName = "No command")] [DataRow("help", "blubbi", false, true, DisplayName = "Unknown command")] [DataRow("help", "blub", true, false, DisplayName = "Known command")] public void Parse_HelpCommand(string helpCommand, string commandArg, bool commandExpected, bool hasUnknown) { var command = CreateCliCommandMock<DummyClass1>(new[] { "blub" }); Commands.Add(command.Object); AppOptions.ProvideHelpCommand = true; var result = commandArg == null ? CallParse(helpCommand) : CallParse(helpCommand, commandArg); var expectedErrors = !hasUnknown ? new[] { (CliErrorType.HelpRequested, commandExpected ? command.Object : null) } : new[] { (CliErrorType.HelpRequested, commandExpected ? command.Object : null), (CliErrorType.UnknownCommand, commandExpected ? command.Object : null), }; AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand), expectedErrors); } [TestMethod] [DataRow("VERSION", null, false, false, DisplayName = "Different casing")] [DataRow("version", null, false, false, DisplayName = "No command")] [DataRow("version", "blubbi", false, true, DisplayName = "Unknown command")] [DataRow("version", "blub", true, false, DisplayName = "Known command")] public void Parse_VersionCommand(string versionCommand, string commandArg, bool commandExpected, bool hasUnknown) { var command = CreateCliCommandMock<DummyClass1>(new[] { "blub" }); Commands.Add(command.Object); AppOptions.ProvideVersionCommand = true; var result = commandArg == null ? CallParse(versionCommand) : CallParse(versionCommand, commandArg); var expectedErrors = !hasUnknown ? new[] { (CliErrorType.VersionRequested, commandExpected ? command.Object : null) } : new[] { (CliErrorType.VersionRequested, commandExpected ? command.Object : null), (CliErrorType.UnknownCommand, commandExpected ? command.Object : null), }; AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand), expectedErrors); } [TestMethod] [DataRow("help")] [DataRow("version")] public void Parse_SpecialCommand_Disabled(string commandName) { AppOptions.ProvideHelpCommand = false; AppOptions.ProvideVersionCommand = false; var result = CallParse(commandName); AssertFailedParserResult( result, x => (x.Type, x.CommandName), (CliErrorType.UnknownCommand, commandName)); } [TestMethod] [DataRow("help")] [DataRow("version")] public void Parse_SpecialCommand_Existing(string commandName) { var command = CreateCliCommandMock<DummyClass1>(new[] { commandName }); Commands.Add(command.Object); AppOptions.ProvideHelpCommand = true; AppOptions.ProvideVersionCommand = true; var result = CallParse(commandName); AssertSuccessfulParserResult<DummyClass1>(result, command.Object); } [TestMethod] [DataRow("HELP")] [DataRow("help")] public void Parse_HelpOption_First(string helpCommand) { var command = CreateCliCommandMock<DummyClass1>(new[] { "blub" }); Commands.Add(command.Object); AppOptions.ProvideHelpCommand = true; var result = CallParse("--" + helpCommand); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand), (CliErrorType.HelpRequested, null)); } [TestMethod] [DataRow("VERSION")] [DataRow("version")] public void Parse_VersionOption_First(string versionCommand) { var command = CreateCliCommandMock<DummyClass1>(new[] { "blub" }); Commands.Add(command.Object); AppOptions.ProvideVersionCommand = true; var result = CallParse("--" + versionCommand); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand), (CliErrorType.VersionRequested, null)); } [TestMethod] [DataRow("help")] [DataRow("version")] public void Parse_SpecialOption_First_Disabled(string optionName) { AppOptions.ProvideHelpOptions = false; AppOptions.ProvideVersionOptions = false; var result = CallParse("--" + optionName); AssertFailedParserResult( result, x => (x.Type, x.CommandName), (CliErrorType.UnknownCommand, "--" + optionName)); } [TestMethod] [DataRow("HELP")] [DataRow("help")] public void Parse_HelpOption_OnRootCommand(string helpCommand) { var command = CreateCliCommandMock<DummyClass1>(new[] { "blub" }); Commands.Add(command.Object); AppOptions.ProvideHelpOptions = true; var result = CallParse("blub", "--" + helpCommand); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand), (CliErrorType.HelpRequested, command.Object)); } [TestMethod] [DataRow("VERSION")] [DataRow("version")] public void Parse_VersionOption_OnRootCommand(string versionCommand) { var command = CreateCliCommandMock<DummyClass1>(new[] { "blub" }); Commands.Add(command.Object); AppOptions.ProvideVersionOptions = true; var result = CallParse("blub", "--" + versionCommand); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand), (CliErrorType.VersionRequested, command.Object)); } [TestMethod] [DataRow("help")] [DataRow("version")] public void Parse_SpecialOption_OnRootCommand_ExistingOption(string optionName) { var option = CreateCliCommandOptionMock<bool>(new[] { optionName }); var command = CreateCliCommandMock<DummyClass1>(new[] { "blub" }, options: new[] { option.Object }); _ = option.Setup(x => x.SetValue(It.IsAny<DummyClass1>(), true)).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); AppOptions.ProvideHelpOptions = true; AppOptions.ProvideVersionOptions = true; var result = CallParse("blub", "--" + optionName); AssertSuccessfulParserResult<DummyClass1>(result, command.Object); } [TestMethod] [DataRow("help")] [DataRow("version")] public void Parse_SpecialOption_OnRootCommand_Disabled(string optionName) { var command = CreateCliCommandMock<DummyClass1>(new[] { "blub" }); Commands.Add(command.Object); AppOptions.ProvideHelpOptions = false; AppOptions.ProvideVersionOptions = false; var result = CallParse("blub", "--" + optionName); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.OptionName), (CliErrorType.UnknownOption, command.Object, "--" + optionName)); } [TestMethod] [DataRow("HELP")] [DataRow("help")] public void Parse_HelpOption_OnRootCommand_WithChildCommand(string helpCommand) { var childCommand = CreateCliCommandMock<DummyClass2>(new[] { "blib" }); var parentCommand = CreateCliCommandMock<DummyClass1>(new[] { "blub" }, childCommands: new[] { childCommand.Object }); Commands.Add(parentCommand.Object); AppOptions.ProvideHelpOptions = true; var result = CallParse("blub", "--" + helpCommand); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand), (CliErrorType.HelpRequested, parentCommand.Object)); } [TestMethod] [DataRow("VERSION")] [DataRow("version")] public void Parse_VersionOption_OnRootCommand_WithChildCommand(string versionCommand) { var childCommand = CreateCliCommandMock<DummyClass2>(new[] { "blib" }); var parentCommand = CreateCliCommandMock<DummyClass1>(new[] { "blub" }, childCommands: new[] { childCommand.Object }); Commands.Add(parentCommand.Object); AppOptions.ProvideVersionOptions = true; var result = CallParse("blub", "--" + versionCommand); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand), (CliErrorType.VersionRequested, parentCommand.Object)); } [TestMethod] [DataRow("help")] [DataRow("version")] public void Parse_SpecialOption_OnRootCommand_WithChildCommand_ExistingOption(string optionName) { var option = CreateCliCommandOptionMock<bool>(new[] { optionName }); var childCommand = CreateCliCommandMock<DummyClass2>(new[] { "blib" }); var parentCommand = CreateCliCommandMock<DummyClass1>(new[] { "blub" }, options: new[] { option.Object }, childCommands: new[] { childCommand.Object }); _ = option.Setup(x => x.SetValue(It.IsAny<DummyClass1>(), true)).Verifiable(Verifiables, Times.Once()); Commands.Add(parentCommand.Object); AppOptions.ProvideHelpOptions = true; AppOptions.ProvideVersionOptions = true; var result = CallParse("blub", "--" + optionName); AssertSuccessfulParserResult<DummyClass1>(result, parentCommand.Object); } [TestMethod] [DataRow("help")] [DataRow("version")] public void Parse_SpecialOption_OnRootCommand_WithChildCommand_Disabled(string optionName) { var childCommand = CreateCliCommandMock<DummyClass2>(new[] { "blib" }); var parentCommand = CreateCliCommandMock<DummyClass1>(new[] { "blub" }, childCommands: new[] { childCommand.Object }); Commands.Add(parentCommand.Object); AppOptions.ProvideHelpOptions = false; AppOptions.ProvideVersionOptions = false; var result = CallParse("blub", "--" + optionName); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.OptionName), (CliErrorType.UnknownOption, parentCommand.Object, "--" + optionName)); } [TestMethod] [DataRow("HELP")] [DataRow("help")] public void Parse_HelpOption_OnChildCommand(string helpCommand) { var childCommand = CreateCliCommandMock<DummyClass2>(new[] { "blib" }); var parentCommand = CreateCliCommandMock<DummyClass1>(new[] { "blub" }, childCommands: new[] { childCommand.Object }); Commands.Add(parentCommand.Object); AppOptions.ProvideHelpOptions = true; var result = CallParse("blub", "blib", "--" + helpCommand); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand), (CliErrorType.HelpRequested, childCommand.Object)); } [TestMethod] [DataRow("VERSION")] [DataRow("version")] public void Parse_VersionOption_OnChildCommand(string versionCommand) { var childCommand = CreateCliCommandMock<DummyClass2>(new[] { "blib" }); var parentCommand = CreateCliCommandMock<DummyClass1>(new[] { "blub" }, childCommands: new[] { childCommand.Object }); Commands.Add(parentCommand.Object); AppOptions.ProvideVersionOptions = true; var result = CallParse("blub", "blib", "--" + versionCommand); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand), (CliErrorType.VersionRequested, childCommand.Object)); } [TestMethod] [DataRow("help")] [DataRow("version")] public void Parse_SpecialOption_OnChildCommand_ExistingOption(string optionName) { var option = CreateCliCommandOptionMock<bool>(new[] { optionName }); var childCommand = CreateCliCommandMock<DummyClass2>(new[] { "blib" }, options: new[] { option.Object }); var parentCommand = CreateCliCommandMock<DummyClass1>(new[] { "blub" }, childCommands: new[] { childCommand.Object }); _ = option.Setup(x => x.SetValue(It.IsAny<DummyClass2>(), true)).Verifiable(Verifiables, Times.Once()); Commands.Add(parentCommand.Object); AppOptions.ProvideHelpOptions = true; AppOptions.ProvideVersionOptions = true; var result = CallParse("blub", "blib", "--" + optionName); AssertSuccessfulParserResult<DummyClass2>(result, childCommand.Object); } [TestMethod] [DataRow("help")] [DataRow("version")] public void Parse_SpecialOption_OnChildCommand_Disabled(string optionName) { var childCommand = CreateCliCommandMock<DummyClass2>(new[] { "blib" }); var parentCommand = CreateCliCommandMock<DummyClass1>(new[] { "blub" }, childCommands: new[] { childCommand.Object }); Commands.Add(parentCommand.Object); AppOptions.ProvideHelpOptions = false; AppOptions.ProvideVersionOptions = false; var result = CallParse("blub", "blib", "--" + optionName); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.OptionName), (CliErrorType.UnknownOption, childCommand.Object, "--" + optionName)); } [TestMethod] public void Parse_KnownCommand_NoOptionsOrValues() { var command = CreateCliCommandMock<DummyClass1>(new[] { "blub" }); Commands.Add(command.Object); var result = CallParse("blub"); AssertSuccessfulParserResult<DummyClass1>(result, command.Object); } [TestMethod] public void Parse_KnownChildCommand_OneLevel_NoOptionsOrValues() { var childCommand = CreateCliCommandMock<DummyClass2>(new[] { "blib" }); var parentCommand = CreateCliCommandMock<DummyClass1>(new[] { "blub" }, childCommands: new[] { childCommand.Object }); Commands.Add(parentCommand.Object); var result = CallParse("blub", "blib"); AssertSuccessfulParserResult<DummyClass2>(result, childCommand.Object); } [TestMethod] public void Parse_KnownChildCommand_MultipleLevels_NoOptionsOrValues() { var childCommand3 = CreateCliCommandMock<DummyClass4>(new[] { "blob" }); var childCommand2 = CreateCliCommandMock<DummyClass3>(new[] { "blab" }, childCommands: new[] { childCommand3.Object }); var childCommand1 = CreateCliCommandMock<DummyClass2>(new[] { "blib" }, childCommands: new[] { childCommand2.Object }); var parentCommand = CreateCliCommandMock<DummyClass1>(new[] { "blub" }, childCommands: new[] { childCommand1.Object }); Commands.Add(parentCommand.Object); var result = CallParse("blub", "blib", "blab", "blob"); AssertSuccessfulParserResult<DummyClass4>(result, childCommand3.Object); } [TestMethod] public void Parse_KnownCommand_WithValues() { var val1 = CreateCliCommandValueMock<string>(0); var command = CreateCliCommandMock<DummyClass1>(new[] { "blub" }, values: new[] { val1.Object }); _ = val1.Setup(x => x.SetValue(It.IsAny<DummyClass1>(), "blubbi")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("blub", "blubbi"); AssertSuccessfulParserResult<DummyClass1>(result, command.Object); } [TestMethod] public void Parse_KnownChildCommand_OneLevel_WithValues() { var val1 = CreateCliCommandValueMock<string>(0); var childCommand = CreateCliCommandMock<DummyClass2>(new[] { "blib" }, values: new[] { val1.Object }); var parentCommand = CreateCliCommandMock<DummyClass1>(new[] { "blub" }, childCommands: new[] { childCommand.Object }); _ = val1.Setup(x => x.SetValue(It.IsAny<DummyClass2>(), "blubbi")).Verifiable(Verifiables, Times.Once()); Commands.Add(parentCommand.Object); var result = CallParse("blub", "blib", "blubbi"); AssertSuccessfulParserResult<DummyClass2>(result, childCommand.Object); } [TestMethod] public void Parse_KnownChildCommand_MultipleLevels_WithValues() { var val1 = CreateCliCommandValueMock<string>(0); var childCommand3 = CreateCliCommandMock<DummyClass4>(new[] { "blob" }, values: new[] { val1.Object }); var childCommand2 = CreateCliCommandMock<DummyClass3>(new[] { "blab" }, childCommands: new[] { childCommand3.Object }); var childCommand1 = CreateCliCommandMock<DummyClass2>(new[] { "blib" }, childCommands: new[] { childCommand2.Object }); var parentCommand = CreateCliCommandMock<DummyClass1>(new[] { "blub" }, childCommands: new[] { childCommand1.Object }); _ = val1.Setup(x => x.SetValue(It.IsAny<DummyClass4>(), "blubbi")).Verifiable(Verifiables, Times.Once()); Commands.Add(parentCommand.Object); var result = CallParse("blub", "blib", "blab", "blob", "blubbi"); AssertSuccessfulParserResult<DummyClass4>(result, childCommand3.Object); } [TestMethod] public void Parse_KnownChildCommand_ValueBefore() { var val1 = CreateCliCommandValueMock<string>(0); var val2 = CreateCliCommandValueMock<string>(1); var childCommand = CreateCliCommandMock<DummyClass2>(new[] { "blib" }); var parentCommand = CreateCliCommandMock<DummyClass1>(new[] { "blub" }, values: new[] { val1.Object, val2.Object }, childCommands: new[] { childCommand.Object }); _ = val1.Setup(x => x.SetValue(It.IsAny<DummyClass1>(), "blubbi")).Verifiable(Verifiables, Times.Once()); _ = val2.Setup(x => x.SetValue(It.IsAny<DummyClass1>(), "blib")).Verifiable(Verifiables, Times.Once()); Commands.Add(parentCommand.Object); var result = CallParse("blub", "blubbi", "blib"); AssertSuccessfulParserResult<DummyClass1>(result, parentCommand.Object); } [TestMethod] public void Parse_KnownChildCommand_OptionBefore() { var val1 = CreateCliCommandValueMock<string>(0); var opt1 = CreateCliCommandOptionMock<string>(new[] { "blub" }); var childCommand = CreateCliCommandMock<DummyClass2>(new[] { "blib" }); var parentCommand = CreateCliCommandMock<DummyClass1>( new[] { "blub" }, options: new[] { opt1.Object }, values: new[] { val1.Object }, childCommands: new[] { childCommand.Object }); _ = opt1.Setup(x => x.SetValue(It.IsAny<DummyClass1>(), "blubbi")).Verifiable(Verifiables, Times.Once()); _ = val1.Setup(x => x.SetValue(It.IsAny<DummyClass1>(), "blib")).Verifiable(Verifiables, Times.Once()); Commands.Add(parentCommand.Object); var result = CallParse("blub", "--blub", "blubbi", "blib"); AssertSuccessfulParserResult<DummyClass1>(result, parentCommand.Object); } [TestMethod] public void Parse_BoolOption_LongAlias_NoOptionValue() { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<bool>(new[] { "my-bool" }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, true)).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "--my-bool"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_BoolOption_LongAlias_NoOptionValue_Nullable() { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<bool?>(new[] { "my-bool" }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, true)).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "--my-bool"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_BoolOption_LongAlias_WithOptionValue() { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<bool>(new[] { "my-bool" }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, "false")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "--my-bool", "false"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_BoolOption_ShortAlias_NoOptionValue() { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<bool>(new[] { "my-bool" }, new char[] { 'b' }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, true)).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "-b"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_BoolOption_ShortAlias_NoOptionValue_Nullable() { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<bool?>(new[] { "my-bool" }, new char[] { 'b' }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, true)).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "-b"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_BoolOption_ShortAlias_WithOptionValue() { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<bool>(new[] { "my-bool" }, new char[] { 'b' }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, "false")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "-b", "false"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_BoolOption_ShortAlias_Multiple_NoOptionValue() { var obj = new DummyClass1(); var option1 = CreateCliCommandOptionMock<bool>(new[] { "my-bool1" }, new char[] { 'b' }); var option2 = CreateCliCommandOptionMock<bool>(new[] { "my-bool2" }, new char[] { 'B' }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option1.Object, option2.Object }, optionsInstance: obj); _ = option1.Setup(x => x.SetValue(obj, true)).Verifiable(Verifiables, Times.Once()); _ = option2.Setup(x => x.SetValue(obj, true)).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "-bB"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_BoolOption_ShortAlias_Multiple_NoOptionValue_Nullable() { var obj = new DummyClass1(); var option1 = CreateCliCommandOptionMock<bool?>(new[] { "my-bool1" }, new char[] { 'b' }); var option2 = CreateCliCommandOptionMock<bool?>(new[] { "my-bool2" }, new char[] { 'B' }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option1.Object, option2.Object }, optionsInstance: obj); _ = option1.Setup(x => x.SetValue(obj, true)).Verifiable(Verifiables, Times.Once()); _ = option2.Setup(x => x.SetValue(obj, true)).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "-bB"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_Option_WrongOptionFormat() { var ex = new Exception(); var option = CreateCliCommandOptionMock<object>(new[] { "my-option" }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }); _ = option.Setup(x => x.SetValue(It.IsAny<DummyClass1>(), "my-option-value")).Throws(ex).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "--my-option", "my-option-value"); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.AffectedOption, x.Exception), (CliErrorType.WrongOptionFormat, command.Object, option.Object, ex)); } [TestMethod] public void Parse_Value_WrongOptionFormat() { var ex = new Exception(); var value = CreateCliCommandValueMock<object>(0); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, values: new[] { value.Object }); _ = value.Setup(x => x.SetValue(It.IsAny<DummyClass1>(), "my-value")).Throws(ex).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "my-value"); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.AffectedValue, x.Exception), (CliErrorType.WrongValueFormat, command.Object, value.Object, ex)); } [TestMethod] public void Parse_Value_TooManyValues_OneToMany() { var value = CreateCliCommandValueMock<object>(0); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, values: new[] { value.Object }); _ = value.Setup(x => x.SetValue(It.IsAny<DummyClass1>(), "my-value")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "my-value", "my-second-value"); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand), (CliErrorType.UnknownValue, command.Object)); } [TestMethod] public void Parse_Value_TooManyValues_TwoToMany() { var value = CreateCliCommandValueMock<object>(0); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, values: new[] { value.Object }); _ = value.Setup(x => x.SetValue(It.IsAny<DummyClass1>(), "my-value")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "my-value", "my-second-value", "my-third-value"); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand), (CliErrorType.UnknownValue, command.Object)); } [TestMethod] public void Parse_Value_TooManyValues_Ignored() { var obj = new DummyClass1(); var value = CreateCliCommandValueMock<object>(0); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, values: new[] { value.Object }, optionsInstance: obj); _ = value.Setup(x => x.SetValue(obj, "my-value")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); AppOptions.IgnoreAdditionalValues = true; var result = CallParse("my-command", "my-value", "my-second-value"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_Value_Escaped() { var obj = new DummyClass1(); var value = CreateCliCommandValueMock<object>(0); var option = CreateCliCommandOptionMock<object>(new[] { "my-option" }); var command = CreateCliCommandMock<DummyClass1>( new[] { "my-command" }, options: new[] { option.Object }, values: new[] { value.Object }, optionsInstance: obj); _ = value.Setup(x => x.SetValue(obj, "--my-option")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "--", "--my-option"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] [DataRow("--my-option")] [DataRow("-O")] public void Parse_Option_Unknown(string optionName) { var obj = new DummyClass1(); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, optionsInstance: obj); Commands.Add(command.Object); var result = CallParse("my-command", optionName); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.OptionName), (CliErrorType.UnknownOption, command.Object, optionName)); } [TestMethod] [DataRow("--my-option")] [DataRow("-O")] public void Parse_Option_Unknown_WithValue(string optionName) { var obj = new DummyClass1(); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, optionsInstance: obj); Commands.Add(command.Object); var result = CallParse("my-command", optionName, "my-value"); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.OptionName), (CliErrorType.UnknownOption, command.Object, optionName)); } [TestMethod] [DataRow("--my-option")] [DataRow("-O")] public void Parse_Option_Unknown_Ignore(string optionName) { var obj = new DummyClass1(); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, optionsInstance: obj); Commands.Add(command.Object); AppOptions.IgnoreUnknownOptions = true; var result = CallParse("my-command", optionName); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] [DataRow("--my-option")] [DataRow("-O")] public void Parse_Option_Unknown_WithValue_Ignore(string optionName) { var obj = new DummyClass1(); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, optionsInstance: obj); Commands.Add(command.Object); AppOptions.IgnoreUnknownOptions = true; var result = CallParse("my-command", optionName, "my-value"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] [DataRow("--my-option")] [DataRow("-O")] public void Parse_Option_Unknown_WithKnown(string optionName) { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<string>(new[] { "my-string" }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, "blub")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", optionName, "--my-string", "blub"); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.OptionName), (CliErrorType.UnknownOption, command.Object, optionName)); } [TestMethod] [DataRow("--my-option")] [DataRow("-O")] public void Parse_Option_Unknown_WithKnown_WithValue(string optionName) { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<string>(new[] { "my-string" }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, "blub")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", optionName, "my-value", "--my-string", "blub"); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.OptionName), (CliErrorType.UnknownOption, command.Object, optionName)); } [TestMethod] [DataRow("--my-option")] [DataRow("-O")] public void Parse_Option_Unknown_WithKnown_Ignore(string optionName) { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<string>(new[] { "my-string" }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, "blub")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); AppOptions.IgnoreUnknownOptions = true; var result = CallParse("my-command", optionName, "--my-string", "blub"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] [DataRow("--my-option")] [DataRow("-O")] public void Parse_Option_Unknown_WithKnown_WithValue_Ignore(string optionName) { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<string>(new[] { "my-string" }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, "blub")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); AppOptions.IgnoreUnknownOptions = true; var result = CallParse("my-command", optionName, "my-value", "--my-string", "blub"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_Option_Unknown_Multiple_LongAlias() { var obj = new DummyClass1(); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, optionsInstance: obj); Commands.Add(command.Object); var result = CallParse("my-command", "--my-option1", "--my-option2"); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.OptionName), (CliErrorType.UnknownOption, command.Object, "--my-option1"), (CliErrorType.UnknownOption, command.Object, "--my-option2")); } [TestMethod] public void Parse_Option_Unknown_Multiple_ShortAlias() { var obj = new DummyClass1(); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, optionsInstance: obj); Commands.Add(command.Object); var result = CallParse("my-command", "-Oo"); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.OptionName), (CliErrorType.UnknownOption, command.Object, "-o"), (CliErrorType.UnknownOption, command.Object, "-O")); } [TestMethod] public void Parse_Option_Unknown_Multiple_WithValue() { var obj = new DummyClass1(); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, optionsInstance: obj); Commands.Add(command.Object); var result = CallParse("my-command", "--my-option1", "my-value", "--my-option2", "my-value"); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.OptionName), (CliErrorType.UnknownOption, command.Object, "--my-option1"), (CliErrorType.UnknownOption, command.Object, "--my-option2")); } [TestMethod] public void Parse_Option_Unknown_Multiple_LongAlias_Ignore() { var obj = new DummyClass1(); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, optionsInstance: obj); Commands.Add(command.Object); AppOptions.IgnoreUnknownOptions = true; var result = CallParse("my-command", "--my-option1", "--my-option2"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_Option_Unknown_Multiple_ShortAlias_Ignore() { var obj = new DummyClass1(); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, optionsInstance: obj); Commands.Add(command.Object); AppOptions.IgnoreUnknownOptions = true; var result = CallParse("my-command", "-Oo"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_Option_Unknown_Multiple_WithValue_Ignore() { var obj = new DummyClass1(); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, optionsInstance: obj); Commands.Add(command.Object); AppOptions.IgnoreUnknownOptions = true; var result = CallParse("my-command", "--my-option1", "my-value", "--my-option2", "my-value"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_Option_Unknown_Multiple_LongAlias_WithKnown() { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<string>(new[] { "my-string" }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, "blub")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "--my-option1", "--my-option2", "--my-string", "blub"); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.OptionName), (CliErrorType.UnknownOption, command.Object, "--my-option1"), (CliErrorType.UnknownOption, command.Object, "--my-option2")); } [TestMethod] public void Parse_Option_Unknown_Multiple_ShortAlias_WithKnown() { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<string>(new[] { "my-string" }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, "blub")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "-Oo", "--my-string", "blub"); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.OptionName), (CliErrorType.UnknownOption, command.Object, "-o"), (CliErrorType.UnknownOption, command.Object, "-O")); } [TestMethod] public void Parse_Option_Unknown_Multiple_WithKnown_WithValue() { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<string>(new[] { "my-string" }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, "blub")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "--my-option1", "my-value", "--my-option2", "my-value", "--my-string", "blub"); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.OptionName), (CliErrorType.UnknownOption, command.Object, "--my-option1"), (CliErrorType.UnknownOption, command.Object, "--my-option2")); } [TestMethod] public void Parse_Option_Unknown_Multiple_LongAlias_WithKnown_Ignore() { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<string>(new[] { "my-string" }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, "blub")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); AppOptions.IgnoreUnknownOptions = true; var result = CallParse("my-command", "--my-option1", "--my-option2", "--my-string", "blub"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_Option_Unknown_Multiple_ShortAlias_WithKnown_Ignore() { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<string>(new[] { "my-string" }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, "blub")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); AppOptions.IgnoreUnknownOptions = true; var result = CallParse("my-command", "-Oo", "--my-string", "blub"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_Option_Unknown_Multiple_WithKnown_WithValue_Ignore() { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<string>(new[] { "my-string" }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, "blub")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); AppOptions.IgnoreUnknownOptions = true; var result = CallParse("my-command", "--my-option1", "my-value", "--my-option2", "my-value", "--my-string", "blub"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_Option_MissingValue() { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<string>(new[] { "my-string" }); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); Commands.Add(command.Object); var result = CallParse("my-command", "--my-string"); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.AffectedOption), (CliErrorType.MissingOptionValue, command.Object, option.Object)); } [TestMethod] [DataRow(typeof(IEnumerable))] [DataRow(typeof(IEnumerable<string>))] [DataRow(typeof(List<string>))] [DataRow(typeof(string[]))] [DataRow(typeof(Array))] public void Parse_Option_List(Type listType) { var obj = new DummyClass1(); var option = CreateCliCommandOptionMock(listType, new[] { "my-list" }, defaultValue: Array.Empty<object>()); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); _ = option.Setup(x => x.SetValue(obj, new[] { "item1", "item2", "item3", "-" })).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "--my-list", "item1", "item2", "item3", "-"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] [DataRow(typeof(IEnumerable))] [DataRow(typeof(IEnumerable<string>))] [DataRow(typeof(List<string>))] [DataRow(typeof(string[]))] [DataRow(typeof(Array))] public void Parse_Value_List(Type listType) { var obj = new DummyClass1(); var value = CreateCliCommandValueMock(listType, 0, defaultValue: Array.Empty<object>()); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, values: new[] { value.Object }, optionsInstance: obj); _ = value.Setup(x => x.SetValue(obj, new[] { "item1", "item2", "item3", "-" })).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "item1", "item2", "item3", "-"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_Value_List_InterruptedByOption() { var obj = new DummyClass1(); var value = CreateCliCommandValueMock<IEnumerable>(0); var option = CreateCliCommandOptionMock<string>(new[] { "my-string" }); var command = CreateCliCommandMock<DummyClass1>( new[] { "my-command" }, options: new[] { option.Object }, values: new[] { value.Object }, optionsInstance: obj); object? currentValue = null; _ = value.Setup(x => x.SetValue(obj, It.IsAny<object?>())).Callback<object?, object?>((_, x) => currentValue = x); _ = value.Setup(x => x.GetValue(obj)).Returns<object?>(_ => currentValue); _ = value.Setup(x => x.SetValue(obj, new[] { "item1", "item2", "item3", "-" })).Verifiable(Verifiables, Times.Once()); _ = option.Setup(x => x.SetValue(obj, "blub")).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command", "item1", "item2", "--my-string", "blub", "item3", "-"); AssertSuccessfulParserResult(result, command.Object, obj); } [TestMethod] public void Parse_RequiredOption_Missing() { Validators.Add(new RequiredValidator()); var obj = new DummyClass1(); var option = CreateCliCommandOptionMock<object>(new[] { "my-option" }, isRequired: true, hasValue: false); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, options: new[] { option.Object }, optionsInstance: obj); Commands.Add(command.Object); var result = CallParse("my-command"); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.AffectedOption), (CliErrorType.MissingOption, command.Object, option.Object)); } [TestMethod] public void Parse_RequiredValueMissing() { Validators.Add(new RequiredValidator()); var obj = new DummyClass1(); var value = CreateCliCommandValueMock<object>(0, isRequired: true, hasValue: false); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, values: new[] { value.Object }, optionsInstance: obj); Commands.Add(command.Object); var result = CallParse("my-command"); AssertFailedParserResult( result, x => (x.Type, x.AffectedCommand, x.AffectedValue), (CliErrorType.MissingValue, command.Object, value.Object)); } [TestMethod] public void Parse_CustomCommonValidatorFails() { var obj = new DummyClass1(); var validator = Mocks.Create<ICliValidator<object>>(); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, optionsInstance: obj); _ = SetupValidation(validator, command.Object, obj, false, new[] { new CliError("My Error") }).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); Validators.Add(validator.Object); var result = CallParse("my-command"); AssertFailedParserResult( result, x => (x.Type, x.CustomErrorMessage), (CliErrorType.Custom, "My Error")); } [TestMethod] public void Parse_OptionsInstanceValidatorFails() { var obj = Mocks.Create<ICliValidatable>(); var command = CreateCliCommandMock<object>(new[] { "my-command" }, optionsInstance: obj.Object); _ = SetupValidation(obj, command.Object, false, new[] { new CliError("My Error") }).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command"); AssertFailedParserResult( result, x => (x.Type, x.CustomErrorMessage), (CliErrorType.Custom, "My Error")); } [TestMethod] public void Parse_OptionsInstanceValidatorSucceeds() { var obj = Mocks.Create<ICliValidatable>(); var command = CreateCliCommandMock<object>(new[] { "my-command" }, optionsInstance: obj.Object); _ = SetupValidation(obj, command.Object, true, null).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command"); AssertSuccessfulParserResult(result, command.Object, obj.Object); } [TestMethod] public void Parse_CommandValidationFails() { var obj = new DummyClass1(); var command = CreateCliCommandMock<DummyClass1>(new[] { "my-command" }, optionsInstance: obj); _ = SetupValidation(command.As<ICliValidator<object>>(), command.Object, obj, false, new[] { new CliError("My Error") }).Verifiable(Verifiables, Times.Once()); Commands.Add(command.Object); var result = CallParse("my-command"); AssertFailedParserResult( result, x => (x.Type, x.CustomErrorMessage), (CliErrorType.Custom, "My Error")); } private CliArgumentParserResult CallParse(params string[] args) { return Parser.Parse(args); } private Mock<ICliCommandInfoCollection> CreateCommandsMock(ICollection<ICliCommandInfo> commands) { var result = Mocks.Create<ICliCommandInfoCollection>(); _ = result.Setup(x => x.GetEnumerator()).Returns(() => commands.GetEnumerator()); _ = result.Setup(x => x.GetRootCommands()).Returns(() => commands.Where(x => { try { return x.ParentCommand == null; } catch (MockException) { return true; } })); _ = result.Setup(x => x.DefaultCommand).Returns(() => DefaultCommand); return result; } private Mock<ICliApplicationBase> CreateApplicationMock() { var result = Mocks.Create<ICliApplicationBase>(); _ = result.Setup(x => x.Commands).Returns(new CliCommandInfoCollection.ReadOnly(CommandsMock.Object)); _ = result.Setup(x => x.Options).Returns(AppOptions); return result; } private Mock<ICliCommandInfo> CreateCliCommandMock<TCommandType>( string[] aliases, ICliCommandOptionInfo[]? options = null, ICliCommandValueInfo[]? values = null, object? optionsInstance = null, ICliCommandInfo[]? childCommands = null) { var command = Mocks.Create<ICliCommandInfo>(); _ = command.Setup(x => x.CommandType).Returns(typeof(TCommandType)); _ = command.Setup(x => x.Aliases).Returns(aliases); _ = command.Setup(x => x.Options).Returns(options ?? Array.Empty<ICliCommandOptionInfo>()); _ = command.Setup(x => x.Values).Returns(values ?? Array.Empty<ICliCommandValueInfo>()); _ = command.Setup(x => x.ChildCommands).Returns(childCommands ?? Array.Empty<ICliCommandInfo>()); _ = command.Setup(x => x.OptionsInstance).Returns(optionsInstance); _ = command.Setup(x => x.IsExecutable).Returns(true); _ = command.Setup(x => x.ParserOptions).Returns(new CliParserOptions()); _ = command.Setup(x => x.ParentCommand).Returns((ICliCommandInfo?)null); _ = SetupValidation(command.As<ICliValidator<object>>(), true, null); var instance = Activator.CreateInstance<TCommandType>(); _ = ServiceProvider.Setup(x => x.GetService(typeof(TCommandType))).Returns(instance); return command; } private Mock<ICliCommandValueInfo> CreateCliCommandValueMock<TProperty>( int order, bool isRequired = false, TProperty? currentValue = default, TProperty? defaultValue = default, bool hasValue = false) { return CreateCliCommandValueMock(typeof(TProperty), order, isRequired, currentValue, defaultValue, hasValue); } private Mock<ICliCommandValueInfo> CreateCliCommandValueMock( Type propertyType, int order, bool isRequired = false, object? currentValue = default, object? defaultValue = default, bool hasValue = false) { var value = Mocks.Create<ICliCommandValueInfo>(); _ = value.Setup(x => x.Order).Returns(order); _ = value.Setup(x => x.PropertyType).Returns(propertyType); _ = value.Setup(x => x.IsRequired).Returns(isRequired); _ = value.Setup(x => x.DefaultValue).Returns(defaultValue); _ = value.Setup(x => x.Command).Returns(Mocks.Create<ICliCommandInfo>().Object); _ = value.Setup(x => x.SetDefaultValue(It.IsAny<object>())); _ = value.Setup(x => x.SetValue(It.IsAny<object>(), defaultValue)); _ = value.Setup(x => x.GetValue(It.IsAny<object>())).Returns(currentValue); _ = value.Setup(x => x.HasValue(It.IsAny<object>())).Returns(hasValue); return value; } private Mock<ICliCommandOptionInfo> CreateCliCommandOptionMock<TProperty>( string[] aliases, char[]? shortAliases = null, bool isRequired = false, TProperty? currentValue = default, TProperty? defaultValue = default, bool hasValue = false) { return CreateCliCommandOptionMock(typeof(TProperty), aliases, shortAliases, isRequired, currentValue, defaultValue, hasValue); } private Mock<ICliCommandOptionInfo> CreateCliCommandOptionMock( Type propertyType, string[] aliases, char[]? shortAliases = null, bool isRequired = false, object? currentValue = default, object? defaultValue = default, bool hasValue = false) { var option = Mocks.Create<ICliCommandOptionInfo>(); _ = option.Setup(x => x.Aliases).Returns(aliases); _ = option.Setup(x => x.ShortAliases).Returns(shortAliases ?? Array.Empty<char>()); _ = option.Setup(x => x.PropertyType).Returns(propertyType); _ = option.Setup(x => x.IsRequired).Returns(isRequired); _ = option.Setup(x => x.DefaultValue).Returns(defaultValue); _ = option.Setup(x => x.Command).Returns(Mocks.Create<ICliCommandInfo>().Object); _ = option.Setup(x => x.SetDefaultValue(It.IsAny<object>())); _ = option.Setup(x => x.SetValue(It.IsAny<object>(), defaultValue)); _ = option.Setup(x => x.GetValue(It.IsAny<object>())).Returns(currentValue); _ = option.Setup(x => x.HasValue(It.IsAny<object>())).Returns(hasValue); return option; } private IVerifies SetupValidation<T>(Mock<ICliValidator<T>> mock, bool result, IEnumerable<CliError>? errors) { IEnumerable<CliError>? validationErrors; return mock .Setup(x => x.ValidateOptions(It.IsAny<CliExecutionContext>(), It.IsAny<T>(), out validationErrors)) .Returns(new CliValidatorDelegate((CliExecutionContext c, object o, out IEnumerable<CliError>? e) => { e = errors; return result; })); } private IVerifies SetupValidation<T>(Mock<ICliValidator<T>> mock, ICliCommandInfo command, T obj, bool result, IEnumerable<CliError>? errors) { IEnumerable<CliError>? validationErrors; return mock .Setup(x => x.ValidateOptions(It.Is<CliExecutionContext>(x => x.Command == command), obj, out validationErrors)) .Returns(new CliValidatorDelegate((CliExecutionContext c, object o, out IEnumerable<CliError>? e) => { e = errors; return result; })); } private IVerifies SetupValidation(Mock<ICliValidatable> mock, ICliCommandInfo command, bool result, IEnumerable<CliError>? errors) { IEnumerable<CliError>? validationErrors; return mock .Setup(x => x.ValidateOptions(It.Is<CliExecutionContext>(x => x.Command == command), out validationErrors)) .Returns(new CliValidatableDelegate((CliExecutionContext c, out IEnumerable<CliError>? e) => { e = errors; return result; })); } private void AssertSuccessfulParserResult<TExpectedOptionsType>( CliArgumentParserResult result, ICliCommandInfo expectedCommand, TExpectedOptionsType? expectedOptions = null) where TExpectedOptionsType : class { Assert.IsTrue(result.Success, "Parse failed unexpectedly."); Assert.AreSame(expectedCommand, result.ExecutionContext!.Command, "Parse resulted in wrong command."); _ = Assert.IsInstanceOfType<TExpectedOptionsType>(result.Options, "Options returned from parse have unexpected type."); if (expectedOptions is not null) { Assert.AreSame(expectedOptions, result.Options, "Options are not the expected ones."); } } private void AssertFailedParserResult<T>( CliArgumentParserResult result, Func<CliError, T> actualErrorTransformation, params T[] expectedErrorValues) { Assert.IsFalse(result.Success, "Parse succeeded unexpectedly."); Assert.AreCollectionsEquivalent( expectedErrorValues, result.Errors.Select(actualErrorTransformation), "Parse errors are not as expected."); } private class DummyClass1 { } private class DummyClass2 { } private class DummyClass3 { } private class DummyClass4 { } } }
44.713311
174
0.595298
[ "MIT" ]
MaSch0212/MaSch
test/Console.Cli.UnitTests/Runtime/CliArgumentParserTests.cs
65,507
C#
using System; using System.Linq; using Microsoft.EntityFrameworkCore; using DatabaseFirstLINQ.Models; namespace DatabaseFirstLINQ { class Problems { private ECommerceContext _context; public Problems() { _context = new ECommerceContext(); } public void RunLINQQueries() { //ProblemOne(); //ProblemTwo(); //ProblemThree(); // ProblemFour(); //ProblemFive(); //ProblemSix(); //ProblemSeven(); //ProblemEight(); //ProblemNine(); //ProblemTen(); //ProblemEleven(); //ProblemTwelve(); //ProblemThirteen(); //ProblemFourteen(); //ProblemFifteen(); //ProblemSixteen(); //ProblemSeventeen(); //ProblemEighteen(); //ProblemNineteen(); //ProblemTwenty(); //BonusOne(); //BonusTwo(); BonusThree(); } // <><><><><><><><> R Actions (Read) <><><><><><><><><> private int ProblemOne() { // Write a LINQ query that returns the number of users in the Users table. // HINT: .ToList().Count return _context.Users.ToList().Count; } private void ProblemTwo() { // Write a LINQ query that retrieves the users from the User tables then print each user's email to the console. var users = _context.Users; foreach (User user in users) { Console.WriteLine(user.Email); } } private void ProblemThree() { // Write a LINQ query that gets each product where the products price is greater than $150. // Then print the name and price of each product from the above query to the console. var products = _context.Products; var products150AndGreater = products.Where(p => p.Price > 150).ToList(); foreach (Product product in products150AndGreater) { Console.WriteLine(product.Name, product.Price); } } private void ProblemFour() { // Write a LINQ query that gets each product that contains an "s" in the products name. // Then print the name of each product from the above query to the console. var products = _context.Products; var productsThatContainS = products.Where(p => p.Name.Contains("s")); foreach (Product product in productsThatContainS) { Console.WriteLine(product.Name); } } private void ProblemFive() { // Write a LINQ query that gets all of the users who registered BEFORE 2016 // Then print each user's email and registration date to the console. DateTime endDate = new DateTime(2016, 01, 01); var users = _context.Users; var registeredBefore2016 = users.Where(u => u.RegistrationDate < endDate).ToList(); foreach (User user in registeredBefore2016) { //var date = user.RegistrationDate.ToString(); Console.WriteLine(user.Email + " " + user.RegistrationDate); //Console.WriteLine(user.RegistrationDate); } } private void ProblemSix() { // Write a LINQ query that gets all of the users who registered AFTER 2016 and BEFORE 2018 // Then print each user's email and registration date to the console. DateTime startDate = new DateTime(2017, 01, 01); DateTime endDate = new DateTime(2018, 01, 01); var users = _context.Users; var registeredAfter2016Before2018 = users.Where(u => u.RegistrationDate >= startDate && u.RegistrationDate < endDate ).ToList(); foreach (User user in registeredAfter2016Before2018) { Console.WriteLine(user.Email + " " + user.RegistrationDate); } } // <><><><><><><><> R Actions (Read) with Foreign Keys <><><><><><><><><> private void ProblemSeven() { // Write a LINQ query that retreives all of the users who are assigned to the role of Customer. // Then print the users email and role name to the console. var customerUsers = _context.UserRoles.Include(ur => ur.Role).Include(ur => ur.User).Where(ur => ur.Role.RoleName == "Customer"); foreach (UserRole userRole in customerUsers) { Console.WriteLine($"Email: {userRole.User.Email} Role: {userRole.Role.RoleName}"); } } private void ProblemEight() { // Write a LINQ query that retreives all of the products in the shopping cart of the user who has the email "afton@gmail.com". // Then print the product's name, price, and quantity to the console. var productsInCart = _context.ShoppingCarts.Include(p => p.User).Include(p => p.Product).Where(p => p.User.Email == "oda@gmail.com"); foreach (ShoppingCart product in productsInCart) { Console.WriteLine($"Product Name: {product.Product.Name} Product Price: {product.Product.Price} Quantity:{product.Quantity}"); } } private void ProblemNine() { // Write a LINQ query that retreives all of the products in the shopping cart of the user who has the email "oda@gmail.com" and returns the sum of all of the products prices. // HINT: End of query will be: .Select(sc => sc.Product.Price).Sum(); // Then print the total of the shopping cart to the console. var productsInCart = _context.ShoppingCarts.Include(p => p.User).Include(p => p.Product).Where(p => p.User.Id == 2).Select(sc => sc.Product.Price).Sum(); Console.WriteLine(productsInCart); } private void ProblemTen() { // Write a LINQ query that retreives all of the products in the shopping cart of users who have the role of "Employee". // Then print the user's email as well as the product's name, price, and quantity to the console. var userIds = _context.UserRoles.Include(u => u.Role).Include(u => u.User).Where(r => r.Role.RoleName == "Employee").Select(s => s.User.Id); var productsInCart = _context.ShoppingCarts.Include(p => p.User).Include(p => p.Product).Where(p => userIds.Contains(p.UserId)); foreach (ShoppingCart scRow in productsInCart) { Console.WriteLine($"User's Email: {scRow.User.Email} Product Name: {scRow.Product.Name} Product Price: {scRow.Product.Price} Quantity:{scRow.Quantity}"); } } // <><><><><><><><> CUD (Create, Update, Delete) Actions <><><><><><><><><> // <><> C Actions (Create) <><> private void ProblemEleven() { // Create a new User object and add that user to the Users table using LINQ. User newUser = new User() { Email = "david@gmail.com", Password = "DavidsPass123" }; _context.Users.Add(newUser); _context.SaveChanges(); } private void ProblemTwelve() { // Create a new Product object and add that product to the Products table using LINQ. Product newProduct = new Product() { Name = "Ibenez Gio Electric Guitar", Description = "Great guitar for beginners learning how to play electric guitar for the first time!", Price = 150 }; _context.Products.Add(newProduct); _context.SaveChanges(); } private void ProblemThirteen() { // Add the role of "Customer" to the user we just created in the UserRoles junction table using LINQ. var roleId = _context.Roles.Where(r => r.RoleName == "Customer").Select(r => r.Id).SingleOrDefault(); var userId = _context.Users.Where(u => u.Email == "david@gmail.com").Select(u => u.Id).SingleOrDefault(); UserRole newUserRole = new UserRole() { UserId = userId, RoleId = roleId }; _context.UserRoles.Add(newUserRole); _context.SaveChanges(); } private void ProblemFourteen() { // Add the product you create to the user we created in the ShoppingCart junction table using LINQ. var productID = _context.Products.Where(p => p.Name == "Ibenez Gio Electric Guitar").Select(p =>p.Id).SingleOrDefault(); var userId = _context.Users.Where(u => u.Email == "oda@gmail.com").Select(u => u.Id).SingleOrDefault(); ShoppingCart newProduct = new ShoppingCart() { UserId = userId, ProductId = productID, Quantity = 1 }; _context.ShoppingCarts.Add(newProduct); _context.SaveChanges(); } // <><> U Actions (Update) <><> private void ProblemFifteen() { // Update the email of the user we created to "mike@gmail.com" var user = _context.Users.Where(u => u.Email == "david@gmail.com").SingleOrDefault(); user.Email = "mike@gmail.com"; _context.Users.Update(user); _context.SaveChanges(); } private void ProblemSixteen() { // Update the price of the product you created to something different using LINQ. var product = _context.Products.Where(p => p.Name == "Ibenez Gio Electric Guitar").SingleOrDefault(); product.Price = 100; _context.Products.Update(product); _context.SaveChanges(); } private void ProblemSeventeen() { // Change the role of the user we created to "Employee" // HINT: You need to delete the existing role relationship and then create a new UserRole object and add it to the UserRoles table // See problem eighteen as an example of removing a role relationship var userRole = _context.UserRoles.Where(ur => ur.User.Email == "mike@gmail.com").SingleOrDefault(); _context.UserRoles.Remove(userRole); UserRole newUserRole = new UserRole() { UserId = _context.Users.Where(u => u.Email == "mike@gmail.com").Select(u => u.Id).SingleOrDefault(), RoleId = _context.Roles.Where(r => r.RoleName == "Employee").Select(r => r.Id).SingleOrDefault() }; _context.UserRoles.Add(newUserRole); _context.SaveChanges(); } // <><> D Actions (Delete) <><> private void ProblemEighteen() { // Delete the role relationship from the user who has the email "oda@gmail.com" using LINQ. var userRole = _context.UserRoles.Where(ur => ur.User.Email == "oda@gmail.com").SingleOrDefault(); _context.UserRoles.Remove(userRole); _context.SaveChanges(); } private void ProblemNineteen() { // Delete all of the product relationships to the user with the email "oda@gmail.com" in the ShoppingCart table using LINQ. // HINT: Loop var shoppingCartProducts = _context.ShoppingCarts.Where(sc => sc.User.Email == "oda@gmail.com"); foreach (ShoppingCart userProductRelationship in shoppingCartProducts) { _context.ShoppingCarts.Remove(userProductRelationship); } _context.SaveChanges(); } private void ProblemTwenty() { // Delete the user with the email "oda@gmail.com" from the Users table using LINQ. var userRecord = _context.Users.Where(u => u.Email == "oda@gmail.com"); foreach (User list in userRecord) { _context.Users.Remove(list); } _context.SaveChanges(); } // <><><><><><><><> BONUS PROBLEMS <><><><><><><><><> private void BonusOne() { // Prompt the user to enter in an email and password through the console. // Take the email and password and check if the there is a person that matches that combination. // Print "Signed In!" to the console if they exists and the values match otherwise print "Invalid Email or Password.". Console.WriteLine("Please enter email address."); string userEmail = Console.ReadLine(); Console.WriteLine("Please enter password."); string userPassword = Console.ReadLine(); var userExists = _context.Users.Where(u => u.Email.Contains(userEmail) && u.Password.Contains(userPassword)).SingleOrDefault(); if(userExists == null) { Console.WriteLine("Invaild Email or password."); } else if (userExists != null) { Console.WriteLine("Signed In!"); } } private void BonusTwo() { // Write a query that finds the total of every users shopping cart products using LINQ. var usersList = _context.Users.Select(u => u.Id).ToList(); decimal grandtotal = 0; foreach (var user in usersList) { var shoppingCartItems = _context.ShoppingCarts.Include(sc => sc.User).Where(sc => sc.UserId == user).Select(sc => sc.Product.Price).Sum(); // Display the total of each users shopping cart as well as the total of the toals to the console. Console.WriteLine($"Total of products: {shoppingCartItems} User Id: {user}"); grandtotal += shoppingCartItems; Console.WriteLine($"Running Total: {grandtotal}"); } } // BIG ONE private void BonusThree() { SignIn(); // 1. Create functionality for a user to sign in via the console void SignIn() { Console.WriteLine("Please enter email address."); string userEmail = Console.ReadLine(); Console.WriteLine("Please enter password."); string userPassword = Console.ReadLine(); var userExists = _context.Users.Where(u => u.Email.Contains(userEmail) && u.Password.Contains(userPassword)).SingleOrDefault(); if (userExists == null) { // 3. If the user does not succesfully sign in // a. Display "Invalid Email or Password" Console.WriteLine("Invaild Email or password."); // b. Re-prompt the user for credentials SignIn(); } else if (userExists != null) { // 2. If the user succesfully signs in Console.WriteLine("Signed In!"); MenuOptions(userEmail); } } // a. Give them a menu where they perform the following actions within the console void MenuOptions(string userData) { Console.WriteLine("Please choose an option 1 - View Shopping Cart 2 - View All Products 3 - Add Product To Shopping Cart 4 - Remove Product From Shopping Cart 5 - To Quit"); int choice = int.Parse(Console.ReadLine()); switch (choice) { // View the products in their shopping cart case 1: var productsInCart = _context.ShoppingCarts.Include(p => p.User).Include(p => p.Product).Where(p => p.User.Email == userData); foreach (ShoppingCart product in productsInCart) { Console.WriteLine($"Product Name: {product.Product.Name} Product Price: {product.Product.Price} Quantity:{product.Quantity}"); } MenuOptions(userData); break; // View all products in the Products table case 2: var allProducts = _context.Products; foreach (var product in allProducts) { Console.WriteLine($"Product Name: {product.Name} Product Description: {product.Description} Product Price: {product.Price}"); } MenuOptions(userData); break; // Add a product to the shopping cart (incrementing quantity if that product is already in their shopping cart) case 3: Console.WriteLine("Name of Product to be Added"); var productToBeAdded = Console.ReadLine(); var productAlreadyInCart = _context.ShoppingCarts.Include(sc => sc.Product).Include(sc => sc.User).Where(sc => sc.User.Email == userData && sc.Product.Name == productToBeAdded).SingleOrDefault(); if (productAlreadyInCart != null) { var product = _context.ShoppingCarts.Where(sc => sc.Product.Name == productToBeAdded).FirstOrDefault(); product.Quantity++; _context.SaveChanges(); } else if (productAlreadyInCart == null) { var productInfo = _context.Products.Where(p => p.Name == productToBeAdded).SingleOrDefault(); ShoppingCart newCartEntry = new ShoppingCart() { ProductId = productInfo.Id, UserId = _context.Users.Where(u => u.Email == userData).Select(u => u.Id).FirstOrDefault() }; _context.ShoppingCarts.Add(newCartEntry); _context.SaveChanges(); } MenuOptions(userData); break; // Remove a product from their shopping cart case 4: Console.WriteLine("Name of Product to be Removed"); var productToBeRemoved = Console.ReadLine(); var itemToRemove = _context.ShoppingCarts.Where(sc => sc.Product.Name == productToBeRemoved).SingleOrDefault(); _context.ShoppingCarts.Remove(itemToRemove); _context.SaveChanges(); MenuOptions(userData); break; case 5: Console.WriteLine("Bye!!"); break; //No valid option repromt for input default: Console.WriteLine("Please choose valid option!"); MenuOptions(userData); break; } } } } }
39.729459
220
0.531551
[ "MIT" ]
cmattox4846/C-Linq-Questions
DatabaseFirstLINQ/Problems.cs
19,827
C#
// MIT License // // Copyright(c) 2020 Pixel Precision LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. public class LLDNReference : LLDNBase { public ParamWireReference reference; public LLDNReference() : base() { } public LLDNReference(string guid) : base(guid) { } protected override void _Init() { this.reference = new ParamWireReference("Wiring", ""); this.reference.description = "Another Wiring document to reference the output of. Note that referencing something that will end up referencing the original wiring (i.e. cyclic referencing) is not allowed."; this.genParams.Add(this.reference); } public override PxPre.Phonics.GenBase SpawnGenerator( float freq, float beatsPerSec, int samplesPerSec, float amp, WiringDocument spawnFrom, WiringCollection collection) { if(string.IsNullOrEmpty(reference.referenceGUID) == true) return ZeroGen(); WiringDocument wd = collection.GetDocument(reference.referenceGUID); // The last one is a check against cyclic redundancy. There are // other things that prevent this, but if for some reason those // fail, we check one last time and just shut down the process // with a zero signal. if(wd == null || wd.Output == null || wd == spawnFrom) return ZeroGen(); return wd.Output.SpawnGenerator( freq, beatsPerSec, samplesPerSec, amp, spawnFrom, collection); } public override LLDNBase CloneType() { return new LLDNReference(); } public override NodeType nodeType => NodeType.Reference; public override Category GetCategory() => Category.Special; public override string description => "Reference the Output node of another Wiring document."; public override bool HasOutput() => true; }
35.126437
214
0.672448
[ "Unlicense" ]
Reavenk/PxPre-Phonics
LLDN/LLDNReference.cs
3,058
C#
// Licensed to Elasticsearch B.V under one or more agreements. // Elasticsearch B.V licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information using Elastic.Xunit.XunitPlumbing; using Nest; using System.ComponentModel; namespace Examples.Indices.Apis { public class ReloadAnalyzersPage : ExampleBase { [U(Skip = "Example not implemented")] [Description("indices/apis/reload-analyzers.asciidoc:12")] public void Line12() { // tag::b0015e63323171f38995b8e4aa2b52d5[] var response0 = new SearchResponse<object>(); // end::b0015e63323171f38995b8e4aa2b52d5[] response0.MatchesExample(@"POST /twitter/_reload_search_analyzers"); } [U(Skip = "Example not implemented")] [Description("indices/apis/reload-analyzers.asciidoc:98")] public void Line98() { // tag::db8cbfa2afece5d21b3ca69ffee8f5c0[] var response0 = new SearchResponse<object>(); // end::db8cbfa2afece5d21b3ca69ffee8f5c0[] response0.MatchesExample(@"PUT /my_index { ""settings"": { ""index"" : { ""analysis"" : { ""analyzer"" : { ""my_synonyms"" : { ""tokenizer"" : ""whitespace"", ""filter"" : [""synonym""] } }, ""filter"" : { ""synonym"" : { ""type"" : ""synonym_graph"", ""synonyms_path"" : ""analysis/synonym.txt"", <1> ""updateable"" : true <2> } } } } }, ""mappings"": { ""properties"": { ""text"": { ""type"": ""text"", ""analyzer"" : ""standard"", ""search_analyzer"": ""my_synonyms"" <3> } } } }"); } [U(Skip = "Example not implemented")] [Description("indices/apis/reload-analyzers.asciidoc:142")] public void Line142() { // tag::7554da505cc27f6bd0d028b66e85f4a5[] var response0 = new SearchResponse<object>(); // end::7554da505cc27f6bd0d028b66e85f4a5[] response0.MatchesExample(@"POST /my_index/_reload_search_analyzers"); } } }
30.657895
76
0.536052
[ "Apache-2.0" ]
magaum/elasticsearch-net
tests/Examples/Indices/Apis/ReloadAnalyzersPage.cs
2,330
C#
using FluentAssertions; using System; using Xunit; namespace ExplicitMapper.Tests.Mapping.NestedClassMapping.StandardConfiguration { [Collection("Integration tests")] [Trait("Mapping", "Nested class mapping")] public class NestedClassMappingTests : IDisposable { [Fact(DisplayName = "Use standard configuration")] public void UseStandardConfiguration_FieldsMapped() { MappingConfiguration.Add<ProductToProductViewModelStandardConfiguration>(); MappingConfiguration.Build(); var product = new Product() { Manufacturer = "Company", Name = "Good product", Size = new Size() { Width = 1, Height = 2, Depth = 3 } }; var productViewModel = Mapper.Map<ProductViewModel>(product); productViewModel.Should().NotBeNull(); productViewModel.Description.Should().Be("Company - Good product"); productViewModel.Size.Should().NotBeNull(); productViewModel.Size.Width.Should().Be("1m"); productViewModel.Size.Height.Should().Be("2m"); productViewModel.Size.Depth.Should().Be("3m"); } public void Dispose() { MappingConfiguration.Clear(); } } }
31.244444
87
0.568279
[ "MIT" ]
Taras-Tyrsa/explicit-mapper
src/ExplicitMapper/ExplicitMapper.Tests/Mapping/NestedClassMapping/StandardConfiguration/NestedClassMappingTests.cs
1,408
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; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.Infrastructure; using Xunit; // ReSharper disable UnusedVariable // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore { public abstract class ConcurrencyDetectorDisabledTestBase<TFixture> : ConcurrencyDetectorTestBase<TFixture> where TFixture : ConcurrencyDetectorTestBase<TFixture>.ConcurrencyDetectorFixtureBase, new() { protected ConcurrencyDetectorDisabledTestBase(TFixture fixture) : base(fixture) { } [ConditionalTheory] [MemberData(nameof(IsAsyncData))] public virtual async Task SaveChanges(bool async) { await ConcurrencyDetectorTest( async c => { c.Products.Add(new Product { Id = 3, Name = "Unicorn Horseshoe Protection Pack" }); return async ? await c.SaveChangesAsync() : c.SaveChanges(); }); using var ctx = CreateContext(); var newProduct = await ctx.Products.FindAsync(3); Assert.NotNull(newProduct); ctx.Products.Remove(newProduct); await ctx.SaveChangesAsync(); } protected override async Task ConcurrencyDetectorTest(Func<ConcurrencyDetectorDbContext, Task<object>> test) { using var context = CreateContext(); var concurrencyDetector = context.GetService<IConcurrencyDetector>(); IDisposable disposer = null; await Task.Run(() => disposer = concurrencyDetector.EnterCriticalSection()); using (disposer) { await test(context); } } } }
34.309091
116
0.63646
[ "MIT" ]
CameronAavik/efcore
test/EFCore.Specification.Tests/ConcurrencyDetectorDisabledTestBase.cs
1,889
C#
// Copyright (c) Argo Zhang (argo@163.com). All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. // Website: https://www.blazor.zone or https://argozhang.github.io/ using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; namespace BootstrapBlazor.Components; /// <summary> /// /// </summary> public partial class Button { /// <summary> /// 获得/设置 是否自动获取焦点 默认 false 不自动获取焦点 /// </summary> [Parameter] public bool IsAutoFocus { get; set; } /// <summary> /// 按钮点击回调方法,内置支持 IsAsync 开关 /// </summary> protected EventCallback<MouseEventArgs> OnClickButton { get; set; } /// <summary> /// 获得 ValidateForm 实例 /// </summary> [CascadingParameter] protected ValidateForm? ValidateForm { get; set; } /// <summary> /// 获得/设置 html button 实例 /// </summary> protected ElementReference ButtonElement { get; set; } /// <summary> /// OnInitialized 方法 /// </summary> protected override void OnInitialized() { base.OnInitialized(); OnClickButton = EventCallback.Factory.Create<MouseEventArgs>(this, async () => { if (IsAsync && ButtonType == ButtonType.Button) { IsAsyncLoading = true; ButtonIcon = LoadingIcon; IsDisabled = true; } Exception? exception = null; try { if (IsAsync) { await Task.Run(async () => await InvokeAsync(HandlerClick)); } else { await HandlerClick(); } } catch (Exception ex) { exception = ex; } // 恢复按钮 if (IsAsync && ButtonType == ButtonType.Button) { ButtonIcon = Icon; IsDisabled = false; IsAsyncLoading = false; } if (exception != null) { // 如果有异常发生强制按钮恢复 StateHasChanged(); throw exception; } }); if (IsAsync && ValidateForm != null) { // 开启异步操作时与 ValidateForm 联动 ValidateForm.RegisterAsyncSubmitButton(this); } } /// <summary> /// OnAfterRenderAsync 方法 /// </summary> /// <param name="firstRender"></param> /// <returns></returns> protected override async Task OnAfterRenderAsync(bool firstRender) { await base.OnAfterRenderAsync(firstRender); if (firstRender) { if (IsAutoFocus) { await FocusAsync(); } } } /// <summary> /// 自动获得焦点方法 /// </summary> /// <returns></returns> public ValueTask FocusAsync() => ButtonElement.FocusAsync(); /// <summary> /// 处理点击方法 /// </summary> /// <returns></returns> protected virtual async Task HandlerClick() { if (OnClickWithoutRender != null) { if (!IsAsync) { IsNotRender = true; } await OnClickWithoutRender.Invoke(); } if (OnClick.HasDelegate) { await OnClick.InvokeAsync(); } } /// <summary> /// 触发按钮异步操作方法 /// </summary> /// <param name="loading">true 时显示正在操作 false 时表示结束</param> internal void TriggerAsync(bool loading) { IsAsyncLoading = loading; ButtonIcon = loading ? LoadingIcon : Icon; SetDisable(loading); } }
24.892617
111
0.513076
[ "Apache-2.0" ]
First-Coder/BootstrapBlazor
src/BootstrapBlazor/Components/Button/Button.razor.cs
3,937
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 30.03.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_002__AS_STR.Multiply.Complete.Double.Int16{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Double; using T_DATA2 =System.Int16; //////////////////////////////////////////////////////////////////////////////// //class TestSet_R504AAB001__param public static class TestSet_R504AAB001__param { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=1; T_DATA2 vv2=2; var recs=db.testTable.Where(r => (string)(object)(vv1*vv1*vv2)=="2.000000000000000"); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=1; T_DATA2 vv2=2; var recs=db.testTable.Where(r => (string)(object)((vv1*vv1)*vv2)=="2.000000000000000"); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_002 //----------------------------------------------------------------------- [Test] public static void Test_003() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { T_DATA1 vv1=1; T_DATA2 vv2=2; var recs=db.testTable.Where(r => (string)(object)(vv1*(vv1*vv2))=="2.000000000000000"); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_003 };//class TestSet_R504AAB001__param //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_002__AS_STR.Multiply.Complete.Double.Int16
23.441748
136
0.522261
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_002__AS_STR/Multiply/Complete/Double/Int16/TestSet_R504AAB001__param.cs
4,831
C#
using DPE.Core.IRepository.Base; using DPE.Core.Model.Models; namespace DPE.Core.IRepository { public interface IExchangeTotalRepository : IBaseRepository<ExchangeTotal> { } }
19
78
0.757895
[ "MIT" ]
a465717049/mk
DPE.Core.IRepository/IExchangeTotalRepository.cs
192
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Snowflake.Filesystem { /// <summary> /// Represents the root of a Directory that can not be deleted, where each file that is access through a directory is /// associated with a GUID in the directory's manifest. /// /// When files are moved between IDirectories, the files GUID is preserved. /// Thus, metadata can be preserved throughout. /// </summary> public interface IIndelibleDirectory { /// <summary> /// Gets the name of the directory /// </summary> string Name { get; } /// <summary> /// Opens an existing descendant directory with the given name. /// If the directory does not exist, creates the directory. /// You can open a nested directory using '/' as the path separator, and it /// will be created relative to this current directory. /// </summary> /// <param name="name">The name of the existing directory</param> /// <returns>The directory if it exists, or null if it does not.</returns> IDirectory OpenDirectory(string name); /// <summary> /// Opens or creates a file, adding it to the manifest and assigning it a /// unique <see cref="Guid"/>. /// /// Unlike <see cref="OpenDirectory(string)"/>, you can not use the path separator to /// open a nested file. Paths will be truncated with <see cref="Path.GetFileName(string)"/>. /// /// Instead, use <see cref="OpenDirectory(string)"/> to open the directory of the desired file, /// then call <see cref="OpenFile(string)"/> on the returned instance. /// /// Keep in mind this does not actually create a file on the underlying file system. /// However, you can use <see cref="IFile.OpenStream()"/> and friends to create the file /// if it does not yet exist. /// </summary> /// <param name="file">The name of the file. If this is a path, will be truncated with <see cref="Path.GetFileName(string)"/></param> /// <returns>An object that associates a given file with a with a unique <see cref="Guid"/></returns> IFile OpenFile(string file); /// <summary> /// Copies a file from an unmanaged <see cref="FileInfo"/> that exists outside of /// a <see cref="IDirectory"/>. /// Do not use this method to copy from a managed <see cref="IDirectory"/>. /// Instead, use <see cref="CopyFrom(IReadOnlyFile)"/>. /// </summary> /// <exception cref="IOException">If a file with the same name exists in the target destination.</exception> /// <exception cref="FileNotFoundException">If the source file can not be found.</exception> /// <param name="source">The <see cref="FileInfo"/></param> /// <returns>The <see cref="IFile"/> that describes the file in the current <see cref="IDirectory"/>.</returns> IFile CopyFrom(FileInfo source); /// <summary> /// Copies a file from an unmanaged <see cref="FileInfo"/> that exists outside of /// a <see cref="IDirectory"/>. /// Do not use this method to copy from a managed <see cref="IDirectory"/>. /// Instead, use <see cref="CopyFrom(IReadOnlyFile)"/>. /// </summary> /// <exception cref="IOException">If a file with the same name exists in the target destination and <paramref name="overwrite"/> is false.</exception> /// <exception cref="FileNotFoundException">If the source file can not be found.</exception> /// <param name="source">The <see cref="FileInfo"/></param> /// <param name="overwrite">Overwrite the file if it already exists in this <see cref="IDirectory"/></param> /// <returns>The <see cref="IFile"/> that describes the file in the current <see cref="IDirectory"/>.</returns> IFile CopyFrom(FileInfo source, bool overwrite); /// <summary> /// Copies a file asynchronously from an unmanaged <see cref="FileInfo"/> that exists outside of /// a <see cref="IDirectory"/>. /// Do not use this method to copy from a managed <see cref="IDirectory"/>. /// Instead, use <see cref="IDirectory.CopyFrom(IReadOnlyFile)"/>. /// </summary> /// <exception cref="IOException">If a file with the same name exists in the target destination.</exception> /// <exception cref="FileNotFoundException">If the source file can not be found.</exception> /// <param name="source">The <see cref="FileInfo"/></param> /// <param name="cancellation">A cancellation token that is forwarded to the underlying <see cref="Task{TResult}"/>.</param> /// <returns>The <see cref="IFile"/> that describes the file in the current <see cref="IDirectory"/>.</returns> Task<IFile> CopyFromAsync(FileInfo source, CancellationToken cancellation = default); /// <summary> /// Copies a file asynchronously from an unmanaged <see cref="FileInfo"/> that exists outside of /// a <see cref="IDirectory"/>. /// Do not use this method to copy from a managed <see cref="IDirectory"/>. /// Instead, use <see cref="CopyFrom(IReadOnlyFile)"/>. /// </summary> /// <exception cref="IOException">If a file with the same name exists in the target destination and <paramref name="overwrite"/> is false.</exception> /// <exception cref="FileNotFoundException">If the source file can not be found.</exception> /// <param name="source">The <see cref="FileInfo"/></param> /// <param name="overwrite">Overwrite the file if it already exists in this <see cref="IDirectory"/></param> /// <param name="cancellation">A cancellation token that is forwarded to the underlying <see cref="Task{TResult}"/>.</param> /// <returns>The <see cref="IFile"/> that describes the file in the current <see cref="IDirectory"/>.</returns> Task<IFile> CopyFromAsync(FileInfo source, bool overwrite, CancellationToken cancellation = default); /// <summary> /// Moves a file between <see cref="IDirectory"/>, updating the /// manifests such that the resulting file has the same <see cref="IReadOnlyFile.FileGuid"/> as the source file. /// /// The source file will cease to exist in its original <see cref="IDirectory"/>. /// /// There is no asychronous equivalent by design, since <see cref="MoveFrom(IFile, bool)"/> is intended to /// be faster than <see cref="CopyFromAsync(IReadOnlyFile, CancellationToken)"/> if the <see cref="IDirectory"/> instances /// are on the same file system. Otherwise, you should use <see cref="CopyFromAsync(IReadOnlyFile, CancellationToken)"/>, /// then <see cref="IFile.Delete"/> the old file. /// </summary> /// <exception cref="IOException">If a file with the same name exists in the target destination.</exception> /// <exception cref="FileNotFoundException">If the source file can not be found.</exception> /// <param name="source">The <see cref="FileInfo"/></param> /// <returns>The <see cref="IFile"/> that describes the file in the current <see cref="IDirectory"/>.</returns> IFile MoveFrom(IFile source); /// <summary> /// Moves a file between <see cref="IDirectory"/>, updating the /// manifests such that the resulting file has the same <see cref="IReadOnlyFile.FileGuid"/> as the source file. /// /// The source file will cease to exist in its original <see cref="IDirectory"/>. /// /// There is no asychronous equivalent by design, since <see cref="MoveFrom(IFile, bool)"/> is intended to /// be faster than <see cref="CopyFromAsync(IReadOnlyFile, bool, CancellationToken)"/> if the <see cref="IDirectory"/> instances /// are on the same file system. Otherwise, you should use <see cref="CopyFromAsync(IReadOnlyFile, bool, CancellationToken)"/>, /// then <see cref="IFile.Delete"/> the old file. /// </summary> /// <exception cref="IOException">If a file with the same name exists in the target destination and <paramref name="overwrite"/> is false.</exception> /// <exception cref="FileNotFoundException">If the source file can not be found.</exception> /// <param name="source">The <see cref="FileInfo"/></param> /// <returns>The <see cref="IFile"/> that describes the file in the current <see cref="IDirectory"/>.</returns> /// <param name="overwrite">Overwrite the file if it already exists in this <see cref="IDirectory"/></param> IFile MoveFrom(IFile source, bool overwrite); /// <summary> /// Copies a file from a <see cref="IFile"/> from another <see cref="IDirectory"/>, updating the /// manifests such that the resulting file has the same <see cref="IReadOnlyFile.FileGuid"/> as the source file. /// </summary> /// <exception cref="IOException">If a file with the same name exists in the target destination.</exception> /// <exception cref="FileNotFoundException">If the source file can not be found.</exception> /// <param name="source">The <see cref="FileInfo"/></param> /// <returns>The <see cref="IFile"/> that describes the file in the current <see cref="IDirectory"/>.</returns> IFile CopyFrom(IReadOnlyFile source); /// <summary> /// Copies a file from a <see cref="IFile"/> from another <see cref="IDirectory"/>, updating the /// manifests such that the resulting file has the same <see cref="IReadOnlyFile.FileGuid"/> as the source file. /// </summary> /// <exception cref="IOException">If a file with the same name exists in the target destination and <paramref name="overwrite"/> is false.</exception> /// <exception cref="FileNotFoundException">If the source file can not be found.</exception> /// <param name="source">The <see cref="FileInfo"/></param> /// <param name="overwrite">Overwrite the file if it already exists in this <see cref="IDirectory"/></param> /// <returns>The <see cref="IFile"/> that describes the file in the current <see cref="IDirectory"/>.</returns> IFile CopyFrom(IReadOnlyFile source, bool overwrite); /// <summary> /// Copies a file asynchronously from a <see cref="IFile"/> from another <see cref="IDirectory"/>, updating the /// manifests such that the resulting file has the same <see cref="IReadOnlyFile.FileGuid"/> as the source file. /// </summary> /// <exception cref="IOException">If a file with the same name exists in the target destination.</exception> /// <exception cref="FileNotFoundException">If the source file can not be found.</exception> /// <param name="source">The <see cref="FileInfo"/></param> /// <param name="cancellation">Cancellation token for the asynchronous task.</param> /// <returns>The <see cref="IFile"/> that describes the file in the current <see cref="IDirectory"/>.</returns> Task<IFile> CopyFromAsync(IReadOnlyFile source, CancellationToken cancellation = default); /// <summary> /// Copies a file asynchronously from a <see cref="IFile"/> from another <see cref="IDirectory"/>, updating the /// manifests such that the resulting file has the same <see cref="IReadOnlyFile.FileGuid"/> as the source file. /// </summary> /// <exception cref="IOException">If a file with the same name exists in the target destination and <paramref name="overwrite"/> is false.</exception> /// <exception cref="FileNotFoundException">If the source file can not be found.</exception> /// <param name="source">The <see cref="FileInfo"/></param> /// <param name="overwrite">Overwrite the file if it already exists in this <see cref="IDirectory"/></param> /// <param name="cancellation">Cancellation token for the asynchronous task.</param> /// <returns>The <see cref="IReadOnlyFile"/> that describes the file in the current <see cref="IDirectory"/>.</returns> Task<IFile> CopyFromAsync(IReadOnlyFile source, bool overwrite, CancellationToken cancellation = default); /// <summary> /// Enumerates all direct child directories of this <see cref="IDirectory"/>. /// </summary> /// <returns>All direct children directories.</returns> IEnumerable<IDirectory> EnumerateDirectories(); /// <summary> /// Enumerates all files in this directory, /// </summary> /// <returns>All direct children files.</returns> IEnumerable<IFile> EnumerateFiles(); /// <summary> /// Recursively enumerates all files that are contained in this directory. /// /// This method is usually implemented as a Breadth-first search, but no order is guaranteed. /// </summary> /// <returns>All files contained within this directory, including descendant subfolders.</returns> IEnumerable<IFile> EnumerateFilesRecursive(); /// <summary> /// Whether or not this directory contains a file in its manifest. If provided a /// full path, this will truncate the path using <see cref="Path.GetFileName(string)"/> /// </summary> /// <param name="file">The name of the file to check.</param> /// <returns>Whether or not this directory contains the given file.</returns> bool ContainsFile(string file); /// <summary> /// Whether or not this directory contains directory as a direct child. /// full path, this will truncate the path using <see cref="Path.GetDirectoryName(string)"/> /// </summary> /// <param name="directory">The name of the directory to check.</param> /// <returns>Whether or not this directory contains the given directory.</returns> bool ContainsDirectory(string directory); /// <summary> /// Returns a read only view over this directory. /// </summary> /// <returns>A read only view over this directory.</returns> IReadOnlyDirectory AsReadOnly(); /// <summary> /// <para> /// Creates a link to an unmanaged <see cref="FileInfo"/> that exists outside of /// a <see cref="IDirectory"/>. Links are akin to shortcuts more than symbolic links, /// being represented as a text file with a real file path to another file on the file system. /// Do not ever link to another <see cref="IFile"/>. Instead, use <see cref="CopyFrom(IReadOnlyFile)"/>. /// </para> /// <para> /// Links are transparent, i.e. <see cref="IFile.OpenStream()"/> will open a stream to the linked file, and /// <see cref="IReadOnlyFile.UnsafeGetFilePath"/> will return the path of the linked file. The path of the shortcut /// remains inaccessible except for the internal method <see cref="IReadOnlyFile.UnsafeGetFilePointerPath"/>. /// <see cref="IDirectory"/> methods like <see cref="CopyFrom(IReadOnlyFile)"/> and <see cref="MoveFrom(IFile)"/> work as /// expected. /// </para> /// <para> /// Links differ semantically from Files in two ways: <see cref="IReadOnlyFile.IsLink"/> is always true for links, /// and always false for Files, and <see cref="IFile.OpenStream()"/> on a non existing file throws <see cref="FileNotFoundException"/> /// instead of creating a new file. The reasoning behind throwing an exception is that links should always point to /// a real file on the filesystem, and not be used as a method to escape the directory jail (although <see cref="IFile.OpenStream(FileMode, FileAccess, FileShare)"/> /// will work as expected. The intended action when encountering a broken link is not to create a new file, but instead to /// repair the link by recreating it with <see cref="LinkFrom(FileInfo)"/>. /// </para> /// <para> /// The underlying file that a link points to can only be modified through the stream. /// Calling <see cref="IFile.Delete"/> or <see cref="IFile.Rename(string)"/> will only rename /// or delete the link. If the file the link points to does not exist, /// calling <see cref="IFile.OpenStream()"/> will throw <see cref="FileNotFoundException"/>. /// </para> /// <para> /// Links are very powerful and allow a way for plugins to escape the filesystem jail that an <see cref="IDirectory"/> /// creates. Because they present the potential to modify files outside of the allocated directory, be very careful /// when using them. Prefer read-only access by using <see cref="IFile.AsReadOnly"/> whenever possible. /// </para> /// </summary> /// <exception cref="IOException">If a file with the same name exists in the target destination.</exception> /// <exception cref="FileNotFoundException">If the source file can not be found.</exception> /// <param name="source">The <see cref="FileInfo"/></param> /// <returns>The <see cref="IFile"/> that describes the file in the current <see cref="IDirectory"/>.</returns> IFile LinkFrom(FileInfo source); /// <summary> /// <para> /// Creates a link to an unmanaged <see cref="FileInfo"/> that exists outside of /// a <see cref="IDirectory"/>. Links are akin to shortcuts more than symbolic links, /// being represented as a text file with a real file path to another file on the file system. /// Do not ever link to another <see cref="IFile"/>. Instead, use <see cref="CopyFrom(IReadOnlyFile)"/>. /// </para> /// <para> /// Links are transparent, i.e. <see cref="IFile.OpenStream()"/> will open a stream to the linked file, and /// <see cref="IReadOnlyFile.UnsafeGetFilePath"/> will return the path of the linked file. The path of the shortcut /// remains inaccessible except for the internal method <see cref="IReadOnlyFile.UnsafeGetFilePointerPath"/>. /// <see cref="IDirectory"/> methods like <see cref="CopyFrom(IReadOnlyFile)"/> and <see cref="MoveFrom(IFile)"/> work as /// expected. /// </para> /// <para> /// Links differ semantically from Files in two ways: <see cref="IReadOnlyFile.IsLink"/> is always true for links, /// and always false for Files, and <see cref="IFile.OpenStream()"/> on a non existing file throws <see cref="FileNotFoundException"/> /// instead of creating a new file. The reasoning behind throwing an exception is that links should always point to /// a real file on the filesystem, and not be used as a method to escape the directory jail (although <see cref="IFile.OpenStream(FileMode, FileAccess, FileShare)"/> /// will work as expected. The intended action when encountering a broken link is not to create a new file, but instead to /// repair the link by recreating it with <see cref="LinkFrom(FileInfo, bool)"/> /// </para> /// <para> /// The underlying file that a link points to can only be modified through the stream. /// Calling <see cref="IFile.Delete"/> or <see cref="IFile.Rename(string)"/> will only rename /// or delete the link. If the file the link points to does not exist, /// calling <see cref="IFile.OpenStream()"/> will throw <see cref="FileNotFoundException"/>. /// </para> /// <para> /// Links are very powerful and allow a way for plugins to escape the filesystem jail that an <see cref="IDirectory"/> /// creates. Because they present the potential to modify files outside of the allocated directory, be very careful /// when using them. Prefer read-only access by using <see cref="IFile.AsReadOnly"/> whenever possible. /// </para> /// </summary> /// <exception cref="IOException">If a file with the same name exists in the target destination and <paramref name="overwrite"/> is false.</exception> /// <exception cref="FileNotFoundException">If the source file can not be found.</exception> /// <param name="source">The <see cref="FileInfo"/></param> /// <param name="overwrite">Overwrite the file if it already exists in this <see cref="IDirectory"/>. /// The new link will inherit the GUID of the previously existing file.</param> /// <returns>The <see cref="IFile"/> that describes the file in the current <see cref="IDirectory"/>.</returns> IFile LinkFrom(FileInfo source, bool overwrite); /// <summary> /// Gets the underlying <see cref="DirectoryInfo"/> where files are contained. /// /// This is very rarely necessary, and most IO tasks can be done efficiently and safely using the /// provided API. Manipulating the underlying file system will potentially desync the manifest, /// and cause loss of associated metadata. /// </summary> /// <returns>The underlying <see cref="DirectoryInfo"/> where files are contained.</returns> [Obsolete("Avoid accessing the underlying file path, and use the object methods instead.")] DirectoryInfo UnsafeGetPath(); } }
67.46395
173
0.647275
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
hafixo/snowflake-1
src/Snowflake.Framework.Primitives/Filesystem/IIndelibleDirectory.cs
21,523
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 Xemio.GamesLight.Games.Pong.Properties { /// <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", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Xemio.GamesLight.Games.Pong.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
39.041667
193
0.605478
[ "MIT" ]
haefele/XemioGameLight
games/Xemio.GamesLight.Games.Pong/Properties/Resources.Designer.cs
2,813
C#
namespace Framework.core { public class LoaderContext { private string path; public string Path { get { return path; } } private int contextId; public int ContextId { get { return contextId; } } public LoaderContext(string path, int contextId) { this.path = path; this.contextId = contextId; } } }
17.96
56
0.494432
[ "MIT" ]
ukyohpq/tolua
Assets/Script/Framework/core/LoaderContext.cs
449
C#
using UnityEngine; using UnityEngine.UIElements; using UnityEngine.InputSystem; using UnityEngine.SceneManagement; public class PauseMenu : MonoBehaviour { public GameObject PausePanel; bool isPaused = false; PlayerInputActions playerUIControls; InputAction escapeButton; private void Awake() { PausePanel.SetActive(false); playerUIControls = new PlayerInputActions(); escapeButton = playerUIControls.UI.Cancel; } private void OnEnable() { playerUIControls.Enable(); escapeButton.Enable(); } private void OnDisable() { playerUIControls.Disable(); escapeButton.Disable(); } private void Update() { if (escapeButton.triggered) { isPaused = !isPaused; } PauseGame(); } public void ResumeGame() { isPaused = false; Time.timeScale = 1f; } public void PauseGame() { if (isPaused) { PausePanel.SetActive(true); Time.timeScale = 0; } else { PausePanel.SetActive(false); Time.timeScale = 1f; } } public void Quit2MainMenu() { SceneManager.LoadScene(0); } }
18.042254
52
0.57299
[ "MIT" ]
ReubenU/OpenGameArtJam2022
Assets/GlobalScripts/PlayerUI/PauseMenu.cs
1,281
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using Timer = System.Windows.Forms.Timer; namespace EliteTradingGUI { public partial class MainForm : Form, IDisposable { private EdInfo _info; private List<RouteNode> _routes; private Dictionary<ulong, SystemPoint> _points; private Config _config = Config.Load(); private EdInfo.Location _currentLocation; private delegate void OnFinishedProcessingDelegate(); private delegate void ReportProgressDelegate(string s); private delegate void OnFinishedSearchingRoutesDelegate(); private EdInfo.Location CurrentLocation { get { return _currentLocation; } set { _currentLocation = value; CurrentLocationLabel.Text = CurrentLocationString; } } public string CurrentLocationString { get { if (CurrentLocation == null) return "(none)"; return CurrentLocation.ToString(); } } public MainForm() { InitializeComponent(); Shown += OnShow; CurrentLocation = null; } public new void Dispose() { if (_info != null) { _info.Dispose(); _info = null; } base.Dispose(); } private void OnShow(object sender, EventArgs e) { InitializeFromConfig(); var form = this; Tab.Enabled = false; if (!EdInfo.DatabaseExists()) { double maxDistance; ulong minProfit; using (var importDbForm = new ImportDbForm()) { importDbForm.ShowDialog(this); if (!importDbForm.Accepted) { Close(); return; } maxDistance = importDbForm.MaxDistance; minProfit = importDbForm.MinProfit; } var thread = new Thread(x => { _info = EdInfo.ImportData(form.ReportProgress); _info.RecomputeAllRoutes(maxDistance, minProfit); form.OnFinishedProcessing(); }); thread.Start(this); } else { var thread = new Thread(x => { _info = new EdInfo(form.ReportProgress); form.OnFinishedProcessing(); }); thread.Start(this); } } private void InitializeFromConfig() { cbOnlyLargeLanding.Checked = _config.OnlyLargeLandingPad; cbAvoidLoops.Checked = _config.AvoidLoops; CargoCapacityInput.Text = _config.CargoCapacity.ToString(); InitialCreditsInput.Text = _config.AvailableCredits.ToString(); RequiredStopsInput.Value = _config.RequiredStops; switch (_config.Optimization) { case OptimizationType.OptimizeEfficiency: OptimizeEfficiencyRadio.Checked = true; OptimizeProfitRadio.Checked = false; break; case OptimizationType.OptimizeProfit: OptimizeEfficiencyRadio.Checked = false; OptimizeProfitRadio.Checked = true; break; default: throw new ArgumentOutOfRangeException(); } MinProfitPerUnitInput.Text = _config.MinimumProfitPerUnit.ToString(); LadenJumpDistanceInput.Text = _config.LadenJumpDistance.ToString(); MaxPriceAgeInput.Value = _config.MaxPriceAgeDays; cbAvoidPermitSystems.Checked = _config.AvoidPermitSystems; SearchRadiusInput.Text = _config.SearchRadius.ToString(); cbAvoidPlanetaryStations.Checked = _config.AvoidPlanetaryStations; } public void OnFinishedProcessing() { if (InvokeRequired) { BeginInvoke((OnFinishedProcessingDelegate) OnFinishedProcessing); return; } _points = _info.GetSystemPointList().ToDictionary(x => x.SystemId); Tab.Enabled = true; ReportProgress("Ready"); } public void ReportProgress(string s) { if (InvokeRequired) { BeginInvoke((ReportProgressDelegate) ReportProgress, s); return; } toolStripStatusLabel1.Text = s; } private void SearchButton_Click(object sender, EventArgs e) { _config.OnlyLargeLandingPad = cbOnlyLargeLanding.Checked; _config.AvoidLoops = cbAvoidLoops.Checked; if (_currentLocation == null) { MessageBox.Show("You must select a current location.", "Parsing error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!int.TryParse(CargoCapacityInput.Text, out _config.CargoCapacity)) { MessageBox.Show("The cargo capacity must be an integer.", "Parsing error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!long.TryParse(InitialCreditsInput.Text, out _config.AvailableCredits)) { MessageBox.Show("The initial credits must be an integer.", "Parsing error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } _config.RequiredStops = Convert.ToUInt32(RequiredStopsInput.Value); if (OptimizeEfficiencyRadio.Checked) _config.Optimization = OptimizationType.OptimizeEfficiency; else if (OptimizeProfitRadio.Checked) _config.Optimization = OptimizationType.OptimizeProfit; else throw new Exception("Program in invalid state."); if (!ulong.TryParse(MinProfitPerUnitInput.Text, out _config.MinimumProfitPerUnit)) { MessageBox.Show("The minimum profit per unit must be a non-negative integer.", "Parsing error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (!double.TryParse(LadenJumpDistanceInput.Text, out _config.LadenJumpDistance)) { MessageBox.Show("The laden jump distance must be a real number.", "Parsing error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } _config.MaxPriceAgeDays = Convert.ToInt32(MaxPriceAgeInput.Value); _config.AvoidPermitSystems = cbAvoidPermitSystems.Checked; if (!double.TryParse(SearchRadiusInput.Text, out _config.SearchRadius)) { MessageBox.Show("The search radius must be a real number.", "Parsing error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } _config.AvoidPlanetaryStations = cbAvoidPlanetaryStations.Checked; _config.Save(); Tab.Enabled = false; var form = this; NativeEliteTrading.RouteSearchConstraints constraints = new NativeEliteTrading.RouteSearchConstraints { InitialFunds = Util.ToUlongWithInfinity(_config.AvailableCredits), MinimumProfitPerUnit = _config.MinimumProfitPerUnit, LadenJumpDistance = _config.LadenJumpDistance, MaxCapacity = Util.ToUintWithInfinity(_config.CargoCapacity), RequiredStops = _config.RequiredStops, Optimization = (uint)_config.Optimization, MaxPriceAgeDays = _config.MaxPriceAgeDays, RequireLargePad = Util.ToByte(_config.OnlyLargeLandingPad), AvoidLoops = Util.ToByte(_config.AvoidLoops), AvoidPermitSystems = Util.ToByte(_config.AvoidPermitSystems), AvoidPlanetaryStations = Util.ToByte(_config.AvoidPlanetaryStations), SearchRadius = _config.SearchRadius, }; var thread = new Thread(x => { var routes = _info.SearchRoutes(_currentLocation, constraints); form.OnFinishedSearchingRoutes(routes); }); thread.Start(); } private void SearchLocationsButton_Click(object sender, EventArgs e) { using (var locationSearch = new LocationSearchDialog(_info)) { locationSearch.ShowDialog(this); if (!locationSearch.Cancelled) { CurrentLocation = locationSearch.Result; CurrentLocationLabel.Text = CurrentLocationString; } } } private void OnFinishedSearchingRoutes(List<RouteNode> routes) { if (InvokeRequired) { BeginInvoke((OnFinishedSearchingRoutesDelegate)(() => OnFinishedSearchingRoutes(routes))); return; } Tab.Enabled = true; ReportProgress("Ready"); _routes = routes; PopulateListView(); } private void PopulateListView() { RouteDisplay.Items.Clear(); foreach (var routeNode in _routes.Take(100)) { var item = new ListViewItem(); item.Text = routeNode.GetNode(1).LocationString; item.SubItems.Add(new ListViewItem.ListViewSubItem { Text = routeNode.AccumulatedProfit.ToString() }); item.SubItems.Add(new ListViewItem.ListViewSubItem { Text = routeNode.Cost.ToString() }); item.SubItems.Add(new ListViewItem.ListViewSubItem { Text = routeNode.Efficiency.ToString() }); item.Tag = routeNode; RouteDisplay.Items.Add(item); } } private int SortByLocationString(RouteNode x, RouteNode y) { return String.Compare(x.LocationString, y.LocationString, StringComparison.InvariantCulture); } private int SortByProfit(RouteNode x, RouteNode y) { return -x.AccumulatedProfit.CompareTo(y.AccumulatedProfit); } private int SortByCost(RouteNode x, RouteNode y) { return x.Cost.CompareTo(y.Cost); } private int SortByEfficiency(RouteNode x, RouteNode y) { return -x.Efficiency.CompareTo(y.Efficiency); } private void RouteDisplay_ColumnClick(object sender, ColumnClickEventArgs e) { switch (RouteDisplay.Columns[e.Column].Text) { case "First Location": _routes.Sort(SortByLocationString); break; case "Profit": _routes.Sort(SortByProfit); break; case "Cost": _routes.Sort(SortByCost); break; case "Efficiency": _routes.Sort(SortByEfficiency); break; } PopulateListView(); } private void RouteDisplay_ItemActivate(object sender, EventArgs e) { if (RouteDisplay.SelectedItems.Count == 0) return; var node = (RouteNode) RouteDisplay.SelectedItems[0].Tag; var display = new RouteDisplay(node); display.Show(); var pointDisplay = new SystemDisplay(_points, node); pointDisplay.Show(); } } }
38.37386
157
0.535921
[ "BSD-2-Clause" ]
Helios-vmg/EliteTrading
EliteTradingGUI/MainForm.cs
12,627
C#
using Core; using System.Diagnostics; namespace WebHost.Logger { public class TraceLogger : ILogger { public void Log(string message) { Trace.TraceInformation(message); } public void Log(string message, params object[] args) { Trace.TraceInformation(message, args); } } }
19.888889
61
0.586592
[ "MIT" ]
Enttoi/enttoi-api-dotnet
src/WebHost/Logger/TraceLogger.cs
360
C#
namespace PipeChannelService { using System; using System.Reactive.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System.Reactive.Disposables; using TinyServer.ReactiveSocket; using System.Net; using System.Text; public class ServerWorker : IHostedService { readonly ILogger<ServerWorker> _logger; IDisposable disposable = Disposable.Empty; ISocketServer _socketServer; readonly ILoggerFactory _logFactory; public ServerWorker(ILogger<ServerWorker> logger, ILoggerFactory logFactory) { _logger = logger; _logFactory = logFactory; _socketServer = SocketServer.CreateServer(new IPEndPoint(IPAddress.Any, 8086), _logFactory); disposable = _socketServer.AcceptClientObservable.Subscribe(AccceptClient, PrintError, OnServerCompole); } public Task StartAsync(CancellationToken cancellationToken) { _socketServer.Start(); return Task.CompletedTask; } void AccceptClient(ISocketAcceptClient acceptClient) { acceptClient.RevicedObservable .Select(bytes => bytes.ToMessage()) .Subscribe(p=>PrintMessage(p,acceptClient), PrintError,OnClientCompole); } void PrintMessage(string message,ISocketAcceptClient client) { _logger.LogInformation(message); client.SendMessageAsync($"Server Reply:{DateTime.Now.ToString()}".ToMessageBuffer()); } void OnClientCompole() { _logger.LogInformation("client Done......"); } void OnServerCompole() { _logger.LogInformation("Server Done......"); } void PrintError(Exception exception) { Console.ForegroundColor = ConsoleColor.Red; _logger.LogError(exception.Message); Console.ResetColor(); } public Task StopAsync(CancellationToken cancellationToken) { _socketServer.Dispose(); disposable.Dispose(); _logger.LogInformation("停止......"); return Task.CompletedTask; } } }
26.483146
116
0.615613
[ "MIT" ]
fzf003/dockerfordotnet5
dotnetapi/PipeChannelService/ServerWorker.cs
2,361
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// This is the response object from the DeleteNetworkInsightsAccessScopeAnalysis operation. /// </summary> public partial class DeleteNetworkInsightsAccessScopeAnalysisResponse : AmazonWebServiceResponse { private string _networkInsightsAccessScopeAnalysisId; /// <summary> /// Gets and sets the property NetworkInsightsAccessScopeAnalysisId. /// <para> /// The ID of the Network Access Scope analysis. /// </para> /// </summary> public string NetworkInsightsAccessScopeAnalysisId { get { return this._networkInsightsAccessScopeAnalysisId; } set { this._networkInsightsAccessScopeAnalysisId = value; } } // Check to see if NetworkInsightsAccessScopeAnalysisId property is set internal bool IsSetNetworkInsightsAccessScopeAnalysisId() { return this._networkInsightsAccessScopeAnalysisId != null; } } }
33.280702
101
0.70427
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/DeleteNetworkInsightsAccessScopeAnalysisResponse.cs
1,897
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.ModelConfiguration.Internal.UnitTests { using System.Data.Common; /// <summary> /// Used with the FakeSqlConnection class to fake provider info so that Code First can create SSDL /// without having to hit a real store. /// </summary> public class FakeSqlProviderFactory : DbProviderFactory, IServiceProvider { public static readonly FakeSqlProviderFactory Instance = new FakeSqlProviderFactory(); public static void Initialize() { // Does nothing but ensures that the singleton instance has been created. } // ReSharper disable EmptyConstructor static FakeSqlProviderFactory() // ReSharper restore EmptyConstructor { // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit } public bool ForceNullConnection { get; set; } public object GetService(Type serviceType) { return FakeSqlProviderServices.Instance; } public override DbConnection CreateConnection() { return ForceNullConnection ? null : new FakeSqlConnection(); } } }
33.707317
134
0.647612
[ "Apache-2.0" ]
TerraVenil/entityframework
test/EntityFramework/UnitTests/TestHelpers/Fake/FakeSqlProviderFactory.cs
1,384
C#
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Web.Mvc; using Adxstudio.Xrm.AspNet.Cms; using Adxstudio.Xrm.Metadata; using Microsoft.Xrm.Sdk; namespace Adxstudio.Xrm.Web.Mvc.Liquid { public interface IPortalLiquidContext { HtmlHelper Html { get; } IOrganizationMoneyFormatInfo OrganizationMoneyFormatInfo { get; } IPortalViewContext PortalViewContext { get; } Random Random { get; } UrlHelper UrlHelper { get; } ContextLanguageInfo ContextLanguageInfo { get; } IOrganizationService PortalOrganizationService { get; } } }
22.193548
94
0.767442
[ "MIT" ]
Adoxio/xRM-Portals-Community-Edition
Framework/Adxstudio.Xrm/Web/Mvc/Liquid/IPortalLiquidContext.cs
688
C#
using UnityEngine; namespace Common.Unity.Cameras { public class SimpleCameraController : MonoBehaviour { class CameraState { public float yaw; public float pitch; public float roll; public float x; public float y; public float z; public void SetFromTransform(Transform t) { pitch = t.eulerAngles.x; yaw = t.eulerAngles.y; roll = t.eulerAngles.z; x = t.position.x; y = t.position.y; z = t.position.z; } public void Translate(Vector3 translation) { Vector3 rotatedTranslation = Quaternion.Euler(pitch, yaw, roll) * translation; x += rotatedTranslation.x; y += rotatedTranslation.y; z += rotatedTranslation.z; } public void LerpTowards(CameraState target, float positionLerpPct, float rotationLerpPct) { yaw = Mathf.Lerp(yaw, target.yaw, rotationLerpPct); pitch = Mathf.Lerp(pitch, target.pitch, rotationLerpPct); roll = Mathf.Lerp(roll, target.roll, rotationLerpPct); x = Mathf.Lerp(x, target.x, positionLerpPct); y = Mathf.Lerp(y, target.y, positionLerpPct); z = Mathf.Lerp(z, target.z, positionLerpPct); } public void UpdateTransform(Transform t) { t.eulerAngles = new Vector3(pitch, yaw, roll); t.position = new Vector3(x, y, z); } } CameraState m_TargetCameraState = new CameraState(); CameraState m_InterpolatingCameraState = new CameraState(); [Header("Movement Settings")] [Tooltip("Exponential boost factor on translation, controllable by mouse wheel.")] public float boost = 3.5f; [Tooltip("Time it takes to interpolate camera position 99% of the way to the target."), Range(0.001f, 1f)] public float positionLerpTime = 0.2f; [Header("Rotation Settings")] [Tooltip("X = Change in mouse position.\nY = Multiplicative factor for camera rotation.")] public AnimationCurve mouseSensitivityCurve = new AnimationCurve(new Keyframe(0f, 0.5f, 0f, 5f), new Keyframe(1f, 2.5f, 0f, 0f)); [Tooltip("Time it takes to interpolate camera rotation 99% of the way to the target."), Range(0.001f, 1f)] public float rotationLerpTime = 0.01f; [Tooltip("Whether or not to invert our Y axis for mouse input to rotation.")] public bool invertY = false; void OnEnable() { m_TargetCameraState.SetFromTransform(transform); m_InterpolatingCameraState.SetFromTransform(transform); } Vector3 GetInputTranslationDirection() { Vector3 direction = new Vector3(); if (Input.GetKey(KeyCode.W)) { direction += Vector3.forward; } if (Input.GetKey(KeyCode.S)) { direction += Vector3.back; } if (Input.GetKey(KeyCode.A)) { direction += Vector3.left; } if (Input.GetKey(KeyCode.D)) { direction += Vector3.right; } if (Input.GetKey(KeyCode.E)) { direction += Vector3.down; } if (Input.GetKey(KeyCode.Q)) { direction += Vector3.up; } return direction; } void Update() { // Hide and lock cursor when right mouse button pressed if (Input.GetMouseButtonDown(1)) { Cursor.lockState = CursorLockMode.Locked; } // Unlock and show cursor when right mouse button released if (Input.GetMouseButtonUp(1)) { Cursor.visible = true; Cursor.lockState = CursorLockMode.None; } // Rotation if (Input.GetMouseButton(1)) { var mouseMovement = new Vector2(Input.GetAxis("Mouse X"), Input.GetAxis("Mouse Y") * (invertY ? 1 : -1)); var mouseSensitivityFactor = mouseSensitivityCurve.Evaluate(mouseMovement.magnitude); m_TargetCameraState.yaw += mouseMovement.x * mouseSensitivityFactor; m_TargetCameraState.pitch += mouseMovement.y * mouseSensitivityFactor; } // Translation var translation = GetInputTranslationDirection() * Time.deltaTime; // Speed up movement when shift key held if (Input.GetKey(KeyCode.LeftShift)) { translation *= 10.0f; } // Modify movement by a boost factor (defined in Inspector and modified in play mode through the mouse scroll wheel) boost += Input.mouseScrollDelta.y * 0.2f; translation *= Mathf.Pow(2.0f, boost); m_TargetCameraState.Translate(translation); // Framerate-independent interpolation // Calculate the lerp amount, such that we get 99% of the way to our target in the specified time var positionLerpPct = 1f - Mathf.Exp((Mathf.Log(1f - 0.99f) / positionLerpTime) * Time.deltaTime); var rotationLerpPct = 1f - Mathf.Exp((Mathf.Log(1f - 0.99f) / rotationLerpTime) * Time.deltaTime); m_InterpolatingCameraState.LerpTowards(m_TargetCameraState, positionLerpPct, rotationLerpPct); m_InterpolatingCameraState.UpdateTransform(transform); } } }
36.7
137
0.549046
[ "MIT" ]
andybak/CGALUnity
Assets/CommonUnity/Cameras/SimpleCameraController.cs
5,874
C#
using Microsoft.Practices.ServiceLocation; using ProjectX.Common.Utility; using System; using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Data.Objects; using System.Data.SqlClient; using System.Data.SqlServerCe; namespace BlueWind.Crawler.Manga.Domain { public class MangaDataContext : DbContext { public DbSet<MangaChapter> Chapters { get; set; } public DbSet<ImageCache> ImageCaches { get; set; } public bool IsFirstInitialization { get; set; } public DbSet<MangaSeries> Series { get; set; } public DbSet<MangaSite> Sites { get; set; } public DbSet<VersionInfo> VersionInfos { get; set; } public class MangaDataContextInitializer : IDatabaseInitializer<MangaDataContext> { public Action<MangaDataContext> FirstInitializationCallback { get; set; } public void InitializeDatabase(MangaDataContext context) { if (!context.Database.Exists()) { Create(context); //context.Database.ExecuteSqlCommand("Alter Table MangaSites Add Unique (Name)"); //context.Database.ExecuteSqlCommand("Alter Table MangaSeries Add Unique (Name)"); //context.Database.ExecuteSqlCommand("Alter Table MangaChapters Add Unique (Name)"); //context.Database.ExecuteSqlCommand("Alter Table ImageCaches Add Unique (Url) With (IGNORE_DUP_KEY = ON)"); if (FirstInitializationCallback != null) FirstInitializationCallback(context); } else { } } private static void Create(MangaDataContext context) { context.Database.Create(); } } static MangaDataContext() { Database.SetInitializer(new MangaDataContextInitializer() { FirstInitializationCallback = (context) => { context.IsFirstInitialization = true; } }); } public MangaDataContext() : base(GetConnection(),false) { //this.ObjContext().CommandTimeout = 10000; } private MangaDataContext(DbConnection connection) : base(connection, false) { } public static DbConnection GetConnection() { var connectionString = GetConnectionString(); DbConnection connection = null; if (connectionString.Contains(".sdf")) { connection = new SqlCeConnection(connectionString); } else { connection = new SqlConnection(connectionString); } return connection; } public static MangaDataContext MangaContext(string connectionString) { return new MangaDataContext(GetConnection()); } public ObjectContext ObjContext() { return ((IObjectContextAdapter)this).ObjectContext; } public override int SaveChanges() { int result = 0; try { result = base.SaveChanges(); } catch (Exception ex) { Logger.Write(ex); } finally { this.ObjContext().AcceptAllChanges(); } return result; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<MangaChapter>(); modelBuilder.Entity<MangaSeries>().Property(p => p.Overview).HasColumnType("ntext").IsMaxLength(); modelBuilder.Entity<MangaSeries>().Property(p => p.FullText).HasColumnType("ntext").IsMaxLength(); modelBuilder.Entity<MangaSite>(); modelBuilder.Entity<ImageCache>().Property(p => p.Buffer).HasColumnType("image").IsMaxLength(); modelBuilder.Entity<ImageCache>().Property(p => p.Url).HasColumnType("ntext").IsMaxLength(); } private static string GetConnectionString() { MangaCrawlParameter crawlerParameter; //try //{ crawlerParameter = ServiceLocator.Current.GetInstance<MangaCrawlParameter>(); //} //catch //{ // return "data source=.\\SQLEXPRESS;database=Manga;multipleactiveresultsets=True;integrated security=true"; //} return crawlerParameter.ConnectionString; } } }
33.097222
129
0.567772
[ "Apache-2.0" ]
koneta/MangaPortal
trunk/src/BlueWind.Crawler.Manga/Domain/MangaDataContext.cs
4,768
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void LessThanOrEqualAllInt16() { var test = new VectorBooleanBinaryOpTest__LessThanOrEqualAllInt16(); // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class VectorBooleanBinaryOpTest__LessThanOrEqualAllInt16 { private struct DataTable { private byte[] inArray1; private byte[] inArray2; private GCHandle inHandle1; private GCHandle inHandle2; private ulong alignment; public DataTable(Int16[] inArray1, Int16[] inArray2, int alignment) { int sizeOfinArray1 = inArray1.Length * Unsafe.SizeOf<Int16>(); int sizeOfinArray2 = inArray2.Length * Unsafe.SizeOf<Int16>(); if ((alignment != 32 && alignment != 16 && alignment != 8) || (alignment * 2) < sizeOfinArray1 || (alignment * 2) < sizeOfinArray2) { throw new ArgumentException("Invalid value of alignment"); } this.inArray1 = new byte[alignment * 2]; this.inArray2 = new byte[alignment * 2]; this.inHandle1 = GCHandle.Alloc(this.inArray1, GCHandleType.Pinned); this.inHandle2 = GCHandle.Alloc(this.inArray2, GCHandleType.Pinned); this.alignment = (ulong)alignment; Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray1Ptr), ref Unsafe.As<Int16, byte>(ref inArray1[0]), (uint)sizeOfinArray1); Unsafe.CopyBlockUnaligned(ref Unsafe.AsRef<byte>(inArray2Ptr), ref Unsafe.As<Int16, byte>(ref inArray2[0]), (uint)sizeOfinArray2); } public void* inArray1Ptr => Align((byte*)(inHandle1.AddrOfPinnedObject().ToPointer()), alignment); public void* inArray2Ptr => Align((byte*)(inHandle2.AddrOfPinnedObject().ToPointer()), alignment); public void Dispose() { inHandle1.Free(); inHandle2.Free(); } private static unsafe void* Align(byte* buffer, ulong expectedAlignment) { return (void*)(((ulong)buffer + expectedAlignment - 1) & ~(expectedAlignment - 1)); } } private struct TestStruct { public Vector128<Int16> _fld1; public Vector128<Int16> _fld2; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref testStruct._fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); return testStruct; } public void RunStructFldScenario(VectorBooleanBinaryOpTest__LessThanOrEqualAllInt16 testClass) { var result = Vector128.LessThanOrEqualAll(_fld1, _fld2); testClass.ValidateResult(_fld1, _fld2, result); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static readonly int Op2ElementCount = Unsafe.SizeOf<Vector128<Int16>>() / sizeof(Int16); private static Int16[] _data1 = new Int16[Op1ElementCount]; private static Int16[] _data2 = new Int16[Op2ElementCount]; private static Vector128<Int16> _clsVar1; private static Vector128<Int16> _clsVar2; private Vector128<Int16> _fld1; private Vector128<Int16> _fld2; private DataTable _dataTable; static VectorBooleanBinaryOpTest__LessThanOrEqualAllInt16() { for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _clsVar2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); } public VectorBooleanBinaryOpTest__LessThanOrEqualAllInt16() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld1), ref Unsafe.As<Int16, byte>(ref _data1[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Int16>, byte>(ref _fld2), ref Unsafe.As<Int16, byte>(ref _data2[0]), (uint)Unsafe.SizeOf<Vector128<Int16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data1[i] = TestLibrary.Generator.GetInt16(); } for (var i = 0; i < Op2ElementCount; i++) { _data2[i] = TestLibrary.Generator.GetInt16(); } _dataTable = new DataTable(_data1, _data2, LargestVectorSize); } public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Vector128.LessThanOrEqualAll( Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) ); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, result); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var method = typeof(Vector128).GetMethod(nameof(Vector128.LessThanOrEqualAll), new Type[] { typeof(Vector128<Int16>), typeof(Vector128<Int16>) }); if (method is null) { method = typeof(Vector128).GetMethod(nameof(Vector128.LessThanOrEqualAll), 1, new Type[] { typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)), typeof(Vector128<>).MakeGenericType(Type.MakeGenericMethodParameter(0)) }); } if (method.IsGenericMethodDefinition) { method = method.MakeGenericMethod(typeof(Int16)); } var result = method.Invoke(null, new object[] { Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr), Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr) }); ValidateResult(_dataTable.inArray1Ptr, _dataTable.inArray2Ptr, (bool)(result)); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Vector128.LessThanOrEqualAll( _clsVar1, _clsVar2 ); ValidateResult(_clsVar1, _clsVar2, result); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var op1 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray1Ptr); var op2 = Unsafe.Read<Vector128<Int16>>(_dataTable.inArray2Ptr); var result = Vector128.LessThanOrEqualAll(op1, op2); ValidateResult(op1, op2, result); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new VectorBooleanBinaryOpTest__LessThanOrEqualAllInt16(); var result = Vector128.LessThanOrEqualAll(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Vector128.LessThanOrEqualAll(_fld1, _fld2); ValidateResult(_fld1, _fld2, result); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Vector128.LessThanOrEqualAll(test._fld1, test._fld2); ValidateResult(test._fld1, test._fld2, result); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } private void ValidateResult(Vector128<Int16> op1, Vector128<Int16> op2, bool result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), op1); Unsafe.WriteUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), op2); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(void* op1, void* op2, bool result, [CallerMemberName] string method = "") { Int16[] inArray1 = new Int16[Op1ElementCount]; Int16[] inArray2 = new Int16[Op2ElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray1[0]), ref Unsafe.AsRef<byte>(op1), (uint)Unsafe.SizeOf<Vector128<Int16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int16, byte>(ref inArray2[0]), ref Unsafe.AsRef<byte>(op2), (uint)Unsafe.SizeOf<Vector128<Int16>>()); ValidateResult(inArray1, inArray2, result, method); } private void ValidateResult(Int16[] left, Int16[] right, bool result, [CallerMemberName] string method = "") { bool succeeded = true; var expectedResult = true; for (var i = 0; i < Op1ElementCount; i++) { expectedResult &= (left[i] <= right[i]); } succeeded = (expectedResult == result); if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Vector128)}.{nameof(Vector128.LessThanOrEqualAll)}<Int16>(Vector128<Int16>, Vector128<Int16>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" left: ({string.Join(", ", left)})"); TestLibrary.TestFramework.LogInformation($" right: ({string.Join(", ", right)})"); TestLibrary.TestFramework.LogInformation($" result: ({result})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
42.297468
187
0.608035
[ "MIT" ]
333fred/runtime
src/tests/JIT/HardwareIntrinsics/General/Vector128/LessThanOrEqualAll.Int16.cs
13,366
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using JetBrains.Annotations; namespace LinqToDB { using Linq; using Expressions; using PN = LinqToDB.ProviderName; public static partial class Sql { public enum AggregateModifier { None, Distinct, All, } public enum From { None, First, Last } public enum Nulls { None, Respect, Ignore } public enum NullsPosition { None, First, Last } } [PublicAPI] public static class AnalyticFunctions { const string FunctionToken = "function"; #region Call Builders class OrderItemBuilder: Sql.IExtensionCallBuilder { public void Build(Sql.ISqExtensionBuilder builder) { var nulls = builder.GetValue<Sql.NullsPosition>("nulls"); switch (nulls) { case Sql.NullsPosition.None : break; case Sql.NullsPosition.First : builder.Expression = builder.Expression + " NULLS FIRST"; break; case Sql.NullsPosition.Last : builder.Expression = builder.Expression + " NULLS LAST"; break; default : throw new ArgumentOutOfRangeException(); } } } class ApplyAggregateModifier: Sql.IExtensionCallBuilder { public void Build(Sql.ISqExtensionBuilder builder) { var modifier = builder.GetValue<Sql.AggregateModifier>("modifier"); switch (modifier) { case Sql.AggregateModifier.None : break; case Sql.AggregateModifier.Distinct : builder.AddExpression("modifier", "DISTINCT"); break; case Sql.AggregateModifier.All : builder.AddExpression("modifier", "ALL"); break; default : throw new ArgumentOutOfRangeException(); } } } class ApplyNullsModifier: Sql.IExtensionCallBuilder { public void Build(Sql.ISqExtensionBuilder builder) { var nulls = builder.GetValue<Sql.Nulls>("nulls"); var nullsStr = GetNullsStr(nulls); if (!string.IsNullOrEmpty(nullsStr)) builder.AddExpression("modifier", nullsStr); } } static string GetNullsStr(Sql.Nulls nulls) { switch (nulls) { case Sql.Nulls.None : case Sql.Nulls.Respect: // no need to add RESPECT NULLS, as it is default behavior and token itself supported only by Oracle and Informix return string.Empty; case Sql.Nulls.Ignore : return "IGNORE NULLS"; default : throw new ArgumentOutOfRangeException(); } } static string GetFromStr(Sql.From from) { switch (from) { case Sql.From.None : break; case Sql.From.First : return "FROM FIRST"; case Sql.From.Last : return "FROM LAST"; default : throw new ArgumentOutOfRangeException(); } return string.Empty; } class ApplyFromAndNullsModifier: Sql.IExtensionCallBuilder { public void Build(Sql.ISqExtensionBuilder builder) { var nulls = builder.GetValue<Sql.Nulls>("nulls"); var from = builder.GetValue<Sql.From>("from"); var fromStr = GetFromStr(from); var nullsStr = GetNullsStr(nulls); if (!string.IsNullOrEmpty(fromStr)) builder.AddExpression("from", fromStr); if (!string.IsNullOrEmpty(nullsStr)) builder.AddExpression("nulls", nullsStr); } } #endregion #region API Interfaces public interface IReadyToFunction<out TR> { [Sql.Extension("", ChainPrecedence = 0)] TR ToValue(); } public interface IReadyToFunctionOrOverWithPartition<out TR> : IReadyToFunction<TR> { [Sql.Extension("OVER({query_partition_clause?})", TokenName = "over")] IOverMayHavePartition<TR> Over(); } public interface IOverWithPartitionNeeded<out TR> { [Sql.Extension("OVER({query_partition_clause?})", TokenName = "over")] IOverMayHavePartition<TR> Over(); } public interface INeedOrderByAndMaybeOverWithPartition<out TR> { [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr}", TokenName = "order_item")] IOrderedAcceptOverReadyToFunction<TR> OrderBy<TKey>([ExprParameter] TKey expr); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr}", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedAcceptOverReadyToFunction<TR> OrderBy<TKey>([ExprParameter] TKey expr, [SqlQueryDependent] Sql.NullsPosition nulls); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr} DESC", TokenName = "order_item")] IOrderedAcceptOverReadyToFunction<TR> OrderByDesc<TKey>([ExprParameter] TKey expr); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr} DESC", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedAcceptOverReadyToFunction<TR> OrderByDesc<TKey>([ExprParameter] TKey expr, [SqlQueryDependent] Sql.NullsPosition nulls); } public interface INeedSingleOrderByAndMaybeOverWithPartition<out TR> { [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr}", TokenName = "order_item")] IReadyToFunctionOrOverWithPartition<TR> OrderBy<TKey>([ExprParameter] TKey expr); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr} DESC", TokenName = "order_item")] IReadyToFunctionOrOverWithPartition<TR> OrderByDesc<TKey>([ExprParameter] TKey expr); } public interface IOrderedAcceptOverReadyToFunction<out TR> : IReadyToFunctionOrOverWithPartition<TR> { [Sql.Extension("{expr}", TokenName = "order_item")] IOrderedAcceptOverReadyToFunction<TR> ThenBy<TKey>([ExprParameter] TKey expr); [Sql.Extension("{expr}", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedAcceptOverReadyToFunction<TR> ThenBy<TKey>([ExprParameter] TKey expr, [SqlQueryDependent] Sql.NullsPosition nulls); [Sql.Extension("{expr} DESC", TokenName = "order_item")] IOrderedAcceptOverReadyToFunction<TR> ThenByDesc<TKey>([ExprParameter] TKey expr); [Sql.Extension("{expr} DESC", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedAcceptOverReadyToFunction<TR> ThenByDesc<TKey>([ExprParameter] TKey expr, [SqlQueryDependent] Sql.NullsPosition nulls); } public interface IOverMayHavePartition<out TR> : IReadyToFunction<TR> { [Sql.Extension("PARTITION BY {expr, ', '}", TokenName = "query_partition_clause")] IReadyToFunction<TR> PartitionBy([ExprParameter("expr")] params object[] expressions); } public interface IPartitionedMayHaveOrder<out TR> : IReadyToFunction<TR>, INeedsOrderByOnly<TR> { } public interface IOverMayHavePartitionAndOrder<out TR> : IReadyToFunction<TR>, INeedsOrderByOnly<TR> { [Sql.Extension("PARTITION BY {expr, ', '}", TokenName = "query_partition_clause")] IPartitionedMayHaveOrder<TR> PartitionBy([ExprParameter("expr")] params object[] expressions); } public interface IAnalyticFunction<out TR> { [Sql.Extension("{function} OVER({query_partition_clause?}{_}{order_by_clause?}{_}{windowing_clause?})", TokenName = "over", ChainPrecedence = 10, IsAggregate = true)] IReadyForFullAnalyticClause<TR> Over(); } public interface IAnalyticFunctionWithoutWindow<out TR> { [Sql.Extension("{function} OVER({query_partition_clause?}{_}{order_by_clause?})", TokenName = "over", ChainPrecedence = 10, IsAggregate = true)] IOverMayHavePartitionAndOrder<TR> Over(); } public interface IAggregateFunction<out TR> : IAnalyticFunction<TR> {} public interface IAggregateFunctionSelfContained<out TR> : IAggregateFunction<TR>, IReadyToFunction<TR> {} public interface IOrderedReadyToFunction<out TR> : IReadyToFunction<TR> { [Sql.Extension("{expr}", TokenName = "order_item")] IOrderedReadyToFunction<TR> ThenBy<TKey>([ExprParameter] TKey expr); [Sql.Extension("{expr}", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedReadyToFunction<TR> ThenBy<TKey>([ExprParameter] TKey expr, [SqlQueryDependent] Sql.NullsPosition nulls); [Sql.Extension("{expr} DESC", TokenName = "order_item")] IOrderedReadyToFunction<TR> ThenByDesc<TKey>([ExprParameter] TKey expr); [Sql.Extension("{expr} DESC", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedReadyToFunction<TR> ThenByDesc<TKey>([ExprParameter] TKey expr, [SqlQueryDependent] Sql.NullsPosition nulls); } public interface INeedsWithinGroupWithOrderOnly<out TR> { [Sql.Extension("WITHIN GROUP ({order_by_clause})", TokenName = "within_group")] INeedsOrderByOnly<TR> WithinGroup { get; } } public interface INeedsWithinGroupWithOrderAndMaybePartition<out TR> { [Sql.Extension("WITHIN GROUP ({order_by_clause}){_}{over?}", TokenName = "within_group")] INeedOrderByAndMaybeOverWithPartition<TR> WithinGroup { get; } } public interface INeedsWithinGroupWithSingleOrderAndMaybePartition<out TR> { [Sql.Extension("WITHIN GROUP ({order_by_clause}){_}{over?}", TokenName = "within_group")] INeedSingleOrderByAndMaybeOverWithPartition<TR> WithinGroup { get; } } public interface INeedsOrderByOnly<out TR> { [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr}", TokenName = "order_item")] IOrderedReadyToFunction<TR> OrderBy<TKey>([ExprParameter] TKey expr); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr}", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedReadyToFunction<TR> OrderBy<TKey>([ExprParameter] TKey expr, [SqlQueryDependent] Sql.NullsPosition nulls); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr} DESC", TokenName = "order_item")] IOrderedReadyToFunction<TR> OrderByDesc<TKey>([ExprParameter] TKey expr); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr} DESC", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedReadyToFunction<TR> OrderByDesc<TKey>([ExprParameter] TKey expr, [SqlQueryDependent] Sql.NullsPosition nulls); } #region Full Support public interface IReadyForSortingWithWindow<out TR> { [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr}", TokenName = "order_item")] IOrderedReadyToWindowing<TR> OrderBy<TKey>([ExprParameter("expr")] TKey keySelector); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr}", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedReadyToWindowing<TR> OrderBy<TKey>([ExprParameter("expr")] TKey keySelector, [SqlQueryDependent] Sql.NullsPosition nulls); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr} DESC", TokenName = "order_item")] IOrderedReadyToWindowing<TR> OrderByDesc<TKey>([ExprParameter("expr")] TKey keySelector); [Sql.Extension("ORDER BY {order_item, ', '}", TokenName = "order_by_clause")] [Sql.Extension("{expr} DESC", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedReadyToWindowing<TR> OrderByDesc<TKey>([ExprParameter("expr")] TKey keySelector, [SqlQueryDependent] Sql.NullsPosition nulls); } public interface IReadyForFullAnalyticClause<out TR> : IReadyToFunction<TR>, IReadyForSortingWithWindow<TR> { [Sql.Extension("PARTITION BY {expr, ', '}", TokenName = "query_partition_clause")] IPartitionDefinedReadyForSortingWithWindow<TR> PartitionBy([ExprParameter("expr")] params object[] expressions); } public interface IPartitionDefinedReadyForSortingWithWindow<out TR> : IReadyForSortingWithWindow<TR>, IReadyToFunction<TR> { } public interface IOrderedReadyToWindowing<out TR> : IReadyToFunction<TR> { [Sql.Extension("ROWS {boundary_clause}", TokenName = "windowing_clause")] IBoundaryExpected<TR> Rows { get; } [Sql.Extension("RANGE {boundary_clause}", TokenName = "windowing_clause")] IBoundaryExpected<TR> Range { get; } [Sql.Extension("{expr}", TokenName = "order_item")] IOrderedReadyToWindowing<TR> ThenBy<TKey>([ExprParameter] TKey expr); [Sql.Extension("{expr}", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedReadyToWindowing<TR> ThenBy<TKey>([ExprParameter] TKey expr, [SqlQueryDependent] Sql.NullsPosition nulls); [Sql.Extension("{expr} DESC", TokenName = "order_item")] IOrderedReadyToWindowing<TR> ThenByDesc<TKey>([ExprParameter] TKey expr); [Sql.Extension("{expr} DESC", TokenName = "order_item", BuilderType = typeof(OrderItemBuilder))] IOrderedReadyToWindowing<TR> ThenByDesc<TKey>([ExprParameter] TKey expr, [SqlQueryDependent] Sql.NullsPosition nulls); } public interface IBoundaryExpected<out TR> { [Sql.Extension("UNBOUNDED PRECEDING", TokenName = "boundary_clause")] IReadyToFunction<TR> UnboundedPreceding { get; } [Sql.Extension("CURRENT ROW", TokenName = "boundary_clause")] IReadyToFunction<TR> CurrentRow { get; } [Sql.Extension("{value_expr} PRECEDING", TokenName = "boundary_clause")] IReadyToFunction<TR> ValuePreceding<T>([ExprParameter("value_expr")] T value); [Sql.Extension("BETWEEN {start_boundary} AND {end_boundary}", TokenName = "boundary_clause")] IBetweenStartExpected<TR> Between { get; } } public interface IBetweenStartExpected<out TR> { [Sql.Extension("UNBOUNDED PRECEDING", TokenName = "start_boundary")] IAndExpected<TR> UnboundedPreceding { get; } [Sql.Extension("CURRENT ROW", TokenName = "start_boundary")] IAndExpected<TR> CurrentRow { get; } [Sql.Extension("{value_expr} PRECEDING", TokenName = "start_boundary")] IAndExpected<TR> ValuePreceding<T>([ExprParameter("value_expr")] T value); } public interface IAndExpected<out TR> { [Sql.Extension("")] ISecondBoundaryExpected<TR> And { get; } } public interface ISecondBoundaryExpected<out TR> { [Sql.Extension("UNBOUNDED FOLLOWING", TokenName = "end_boundary")] IReadyToFunction<TR> UnboundedFollowing { get; } [Sql.Extension("CURRENT ROW", TokenName = "end_boundary")] IReadyToFunction<TR> CurrentRow { get; } [Sql.Extension("{value_expr} PRECEDING", TokenName = "end_boundary")] IReadyToFunction<TR> ValuePreceding<T>([ExprParameter("value_expr")] T value); [Sql.Extension("{value_expr} FOLLOWING", TokenName = "end_boundary")] IReadyToFunction<TR> ValueFollowing<T>([ExprParameter("value_expr")] T value); } #endregion Full Support #endregion API Interfaces #region Analytic functions #region Average [Sql.Extension("AVG({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), IsAggregate = true, ChainPrecedence = 0)] public static double Average<TEntity, TV>(this IEnumerable<TEntity> source, [ExprParameter] Func<TEntity, TV> expr, [SqlQueryDependent] Sql.AggregateModifier modifier) { throw new LinqException($"'{nameof(Average)}' is server-side method."); } [Sql.Extension("AVG({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), IsAggregate = true, ChainPrecedence = 0)] public static double Average<TEntity, TV>([NotNull] this IQueryable<TEntity> source, [NotNull] [ExprParameter] Expression<Func<TEntity, TV>> expr, [SqlQueryDependent] Sql.AggregateModifier modifier) { if (source == null) throw new ArgumentNullException(nameof(source)); if (expr == null) throw new ArgumentNullException(nameof(expr)); var currentSource = LinqExtensions.ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.Execute<double>( Expression.Call( null, MethodHelper.GetMethodInfo(AnalyticFunctions.Average, source, expr, modifier), new Expression[] { currentSource.Expression, Expression.Quote(expr), Expression.Constant(modifier) } )); } [Sql.Extension("AVG({expr})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> Average<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new LinqException($"'{nameof(Average)}' is server-side method."); } [Sql.Extension("AVG({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> Average<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr, [SqlQueryDependent] Sql.AggregateModifier modifier) { throw new LinqException($"'{nameof(Average)}' is server-side method."); } #endregion Average #region Corr [Sql.Extension("CORR({expr1}, {expr2})", IsAggregate = true, ChainPrecedence = 0)] public static Decimal Corr<T>(this IEnumerable<T> source, [ExprParameter] Expression<Func<T, object>> expr1, [ExprParameter] Expression<Func<T, object>> expr2) { throw new LinqException($"'{nameof(Corr)}' is server-side method."); } [Sql.Extension("CORR({expr1}, {expr2})", IsAggregate = true, ChainPrecedence = 0)] public static Decimal Corr<TEntity>( [NotNull] this IQueryable<TEntity> source, [NotNull] [ExprParameter] Expression<Func<TEntity, object>> expr1, [NotNull] [ExprParameter] Expression<Func<TEntity, object>> expr2) { if (source == null) throw new ArgumentNullException(nameof(source)); if (expr1 == null) throw new ArgumentNullException(nameof(expr1)); if (expr2 == null) throw new ArgumentNullException(nameof(expr2)); var currentSource = LinqExtensions.ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.Execute<Decimal>( Expression.Call( null, MethodHelper.GetMethodInfo(AnalyticFunctions.Corr, source, expr1, expr2), new Expression[] { currentSource.Expression, Expression.Quote(expr1), Expression.Quote(expr2) } )); } [Sql.Extension("CORR({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> Corr<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new LinqException($"'{nameof(Corr)}' is server-side method."); } #endregion Corr #region Count [Sql.Extension("COUNT({expr})", IsAggregate = true, ChainPrecedence = 0)] public static int CountExt<TEntity>(this IEnumerable<TEntity> source, [ExprParameter] Func<TEntity, object> expr) { throw new LinqException($"'{nameof(CountExt)}' is server-side method."); } [Sql.Extension("COUNT({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), IsAggregate = true, ChainPrecedence = 0)] public static int CountExt<TEntity, TV>(this IEnumerable<TEntity> source, [ExprParameter] Func<TEntity, TV> expr, [SqlQueryDependent] Sql.AggregateModifier modifier) { throw new LinqException($"'{nameof(CountExt)}' is server-side method."); } [Sql.Extension("COUNT({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), IsAggregate = true, ChainPrecedence = 0)] public static int CountExt<TEntity, TV>([NotNull] this IQueryable<TEntity> source, [NotNull] [ExprParameter] Expression<Func<TEntity, TV>> expr, [SqlQueryDependent] Sql.AggregateModifier modifier = Sql.AggregateModifier.None) { if (source == null) throw new ArgumentNullException(nameof(source)); if (expr == null) throw new ArgumentNullException(nameof(expr)); var currentSource = LinqExtensions.ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.Execute<int>( Expression.Call( null, MethodHelper.GetMethodInfo(AnalyticFunctions.CountExt, source, expr, modifier), new Expression[] { currentSource.Expression, Expression.Quote(expr), Expression.Constant(modifier) } )); } [Sql.Extension("COUNT(*)", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<int> Count(this Sql.ISqlExtension ext) { throw new LinqException($"'{nameof(Count)}' is server-side method."); } [Sql.Extension("COUNT({expr})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<int> Count<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr) { throw new LinqException($"'{nameof(Count)}' is server-side method."); } [Sql.Extension("COUNT({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<int> Count(this Sql.ISqlExtension ext, [ExprParameter] object expr, [SqlQueryDependent] Sql.AggregateModifier modifier) { throw new LinqException($"'{nameof(Count)}' is server-side method."); } #endregion #region CovarPop [Sql.Extension("COVAR_POP({expr1}, {expr2})", IsAggregate = true, ChainPrecedence = 0)] public static Decimal CovarPop<T>(this IEnumerable<T> source, [ExprParameter] Expression<Func<T, object>> expr1, [ExprParameter] Expression<Func<T, object>> expr2) { throw new LinqException($"'{nameof(CovarPop)}' is server-side method."); } [Sql.Extension("COVAR_POP({expr1}, {expr2})", IsAggregate = true, ChainPrecedence = 0)] public static Decimal CovarPop<TEntity>( [NotNull] this IQueryable<TEntity> source, [NotNull] [ExprParameter] Expression<Func<TEntity, object>> expr1, [NotNull] [ExprParameter] Expression<Func<TEntity, object>> expr2) { if (source == null) throw new ArgumentNullException(nameof(source)); if (expr1 == null) throw new ArgumentNullException(nameof(expr1)); if (expr2 == null) throw new ArgumentNullException(nameof(expr2)); var currentSource = LinqExtensions.ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.Execute<Decimal>( Expression.Call( null, MethodHelper.GetMethodInfo(AnalyticFunctions.CovarPop, source, expr1, expr2), new Expression[] { currentSource.Expression, Expression.Quote(expr1), Expression.Quote(expr2) } )); } [Sql.Extension("COVAR_POP({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> CovarPop<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr1, [ExprParameter]T expr2) { throw new LinqException($"'{nameof(CovarPop)}' is server-side method."); } #endregion CovarPop #region CovarSamp [Sql.Extension("COVAR_SAMP({expr1}, {expr2})", IsAggregate = true, ChainPrecedence = 0)] public static Decimal CovarSamp<T>(this IEnumerable<T> source, [ExprParameter] Expression<Func<T, object>> expr1, [ExprParameter] Expression<Func<T, object>> expr2) { throw new LinqException($"'{nameof(CovarSamp)}' is server-side method."); } [Sql.Extension("COVAR_SAMP({expr1}, {expr2})", IsAggregate = true, ChainPrecedence = 0)] public static Decimal CovarSamp<TEntity>( [NotNull] this IQueryable<TEntity> source, [NotNull] [ExprParameter] Expression<Func<TEntity, object>> expr1, [NotNull] [ExprParameter] Expression<Func<TEntity, object>> expr2) { if (source == null) throw new ArgumentNullException(nameof(source)); if (expr1 == null) throw new ArgumentNullException(nameof(expr1)); if (expr2 == null) throw new ArgumentNullException(nameof(expr2)); var currentSource = LinqExtensions.ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.Execute<Decimal>( Expression.Call( null, MethodHelper.GetMethodInfo(AnalyticFunctions.CovarSamp, source, expr1, expr2), new Expression[] { currentSource.Expression, Expression.Quote(expr1), Expression.Quote(expr2) } )); } [Sql.Extension("COVAR_SAMP({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> CovarSamp<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr1, [ExprParameter]T expr2) { throw new LinqException($"'{nameof(CovarSamp)}' is server-side method."); } #endregion CovarSamp [Sql.Extension("CUME_DIST({expr, ', '}) {within_group}", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static INeedsWithinGroupWithOrderOnly<TR> CumeDist<TR>(this Sql.ISqlExtension ext, [ExprParameter] params object[] expr) { throw new LinqException($"'{nameof(CumeDist)}' is server-side method."); } [Sql.Extension("CUME_DIST()", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAnalyticFunctionWithoutWindow<TR> CumeDist<TR>(this Sql.ISqlExtension ext) { throw new LinqException($"'{nameof(CumeDist)}' is server-side method."); } [Sql.Extension("DENSE_RANK({expr1}, {expr2}) {within_group}", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static INeedsWithinGroupWithOrderOnly<long> DenseRank(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new LinqException($"'{nameof(DenseRank)}' is server-side method."); } [Sql.Extension("DENSE_RANK()", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAnalyticFunctionWithoutWindow<long> DenseRank(this Sql.ISqlExtension ext) { throw new LinqException($"'{nameof(DenseRank)}' is server-side method."); } [Sql.Extension("FIRST_VALUE({expr}{_}{modifier?})", TokenName = FunctionToken, BuilderType = typeof(ApplyNullsModifier), ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> FirstValue<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, [SqlQueryDependent] Sql.Nulls nulls) { throw new LinqException($"'{nameof(FirstValue)}' is server-side method."); } [Sql.Extension("LAG({expr}{_}{modifier?})", TokenName = FunctionToken, BuilderType = typeof(ApplyNullsModifier), ChainPrecedence = 1, IsAggregate = true)] public static IAnalyticFunctionWithoutWindow<T> Lag<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, [SqlQueryDependent] Sql.Nulls nulls) { throw new LinqException($"'{nameof(Lag)}' is server-side method."); } [Sql.Extension("LAG({expr}{_}{modifier?}, {offset}, {default})", TokenName = FunctionToken, BuilderType = typeof(ApplyNullsModifier), ChainPrecedence = 1, IsAggregate = true)] public static IAnalyticFunctionWithoutWindow<T> Lag<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, [SqlQueryDependent] Sql.Nulls nulls, [ExprParameter] int offset, [ExprParameter] int? @default) { throw new LinqException($"'{nameof(Lag)}' is server-side method."); } [Sql.Extension("LAST_VALUE({expr}{_}{modifier?})", TokenName = FunctionToken, BuilderType = typeof(ApplyNullsModifier), ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> LastValue<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, [SqlQueryDependent] Sql.Nulls nulls) { throw new LinqException($"'{nameof(LastValue)}' is server-side method."); } [Sql.Extension("LEAD({expr}{_}{modifier?})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAnalyticFunctionWithoutWindow<T> Lead<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, [SqlQueryDependent] Sql.Nulls nulls) { throw new LinqException($"'{nameof(Lead)}' is server-side method."); } [Sql.Extension("LEAD({expr}{_}{modifier?}, {offset}, {default})", TokenName = FunctionToken, BuilderType = typeof(ApplyNullsModifier), ChainPrecedence = 1, IsAggregate = true)] public static IAnalyticFunctionWithoutWindow<T> Lead<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, [SqlQueryDependent] Sql.Nulls nulls, [ExprParameter] int offset, [ExprParameter] int? @default) { throw new LinqException($"'{nameof(Lead)}' is server-side method."); } [Sql.Extension("LISTAGG({expr}) {within_group}", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static INeedsWithinGroupWithOrderAndMaybePartition<string> ListAgg<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr) { throw new LinqException($"'{nameof(ListAgg)}' is server-side method."); } [Sql.Extension("LISTAGG({expr}, {delimiter}) {within_group}", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static INeedsWithinGroupWithOrderAndMaybePartition<string> ListAgg<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, [ExprParameter] string delimiter) { throw new LinqException($"'{nameof(ListAgg)}' is server-side method."); } #region Max [Sql.Extension("MAX({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), IsAggregate = true, ChainPrecedence = 0)] public static TV Max<TEntity, TV>(this IEnumerable<TEntity> source, [ExprParameter] Func<TEntity, TV> expr, [SqlQueryDependent] Sql.AggregateModifier modifier) { throw new LinqException($"'{nameof(Max)}' is server-side method."); } [Sql.Extension("MAX({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), IsAggregate = true, ChainPrecedence = 0)] public static TV Max<TEntity, TV>([NotNull] this IQueryable<TEntity> source, [NotNull] [ExprParameter] Expression<Func<TEntity, TV>> expr, [SqlQueryDependent] Sql.AggregateModifier modifier) { if (source == null) throw new ArgumentNullException(nameof(source)); if (expr == null) throw new ArgumentNullException(nameof(expr)); var currentSource = LinqExtensions.ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.Execute<TV>( Expression.Call( null, MethodHelper.GetMethodInfo(AnalyticFunctions.Max, source, expr, modifier), new Expression[] { currentSource.Expression, Expression.Quote(expr), Expression.Constant(modifier) } )); } [Sql.Extension("MAX({expr})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> Max<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr) { throw new LinqException($"'{nameof(Max)}' is server-side method."); } [Sql.Extension("MAX({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> Max<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, [SqlQueryDependent] Sql.AggregateModifier modifier) { throw new LinqException($"'{nameof(Max)}' is server-side method."); } #endregion Max #region Median [Sql.Extension("MEDIAN({expr})", IsAggregate = true, ChainPrecedence = 0)] public static long Median<TEntity, T>(this IEnumerable<TEntity> source, [ExprParameter] Func<TEntity, T> expr) { throw new LinqException($"'{nameof(Median)}' is server-side method."); } [Sql.Extension("MEDIAN({expr})", IsAggregate = true, ChainPrecedence = 0)] public static long Median<TEntity, TV>([NotNull] this IQueryable<TEntity> source, [NotNull] [ExprParameter] Expression<Func<TEntity, TV>> expr) { if (source == null) throw new ArgumentNullException(nameof(source)); if (expr == null) throw new ArgumentNullException(nameof(expr)); var currentSource = LinqExtensions.ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.Execute<long>( Expression.Call( null, MethodHelper.GetMethodInfo(AnalyticFunctions.Median, source, expr), new Expression[] { currentSource.Expression, Expression.Quote(expr) } )); } [Sql.Extension("MEDIAN({expr}) {over}", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IReadyToFunctionOrOverWithPartition<T> Median<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr) { throw new LinqException($"'{nameof(Median)}' is server-side method."); } #endregion Median #region Min [Sql.Extension("MIN({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), IsAggregate = true, ChainPrecedence = 0)] public static TV Min<TEntity, TV>(this IEnumerable<TEntity> source, [ExprParameter] Func<TEntity, TV> expr, [SqlQueryDependent] Sql.AggregateModifier modifier) { throw new LinqException($"'{nameof(Min)}' is server-side method."); } [Sql.Extension("MIN({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), IsAggregate = true, ChainPrecedence = 0)] public static TV Min<TEntity, TV>([NotNull] this IQueryable<TEntity> source, [NotNull] [ExprParameter] Expression<Func<TEntity, TV>> expr, [SqlQueryDependent] Sql.AggregateModifier modifier) { if (source == null) throw new ArgumentNullException(nameof(source)); if (expr == null) throw new ArgumentNullException(nameof(expr)); var currentSource = LinqExtensions.ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.Execute<TV>( Expression.Call( null, MethodHelper.GetMethodInfo(AnalyticFunctions.Min, source, expr, modifier), new Expression[] { currentSource.Expression, Expression.Quote(expr), Expression.Constant(modifier) } )); } [Sql.Extension("MIN({expr})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> Min<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr) { throw new LinqException($"'{nameof(Min)}' is server-side method."); } [Sql.Extension("MIN({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> Min<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, [SqlQueryDependent] Sql.AggregateModifier modifier) { throw new LinqException($"'{nameof(Min)}' is server-side method."); } #endregion Min [Sql.Extension("NTH_VALUE({expr}, {n})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> NthValue<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, [ExprParameter] long n) { throw new LinqException($"'{nameof(NthValue)}' is server-side method."); } [Sql.Extension("NTH_VALUE({expr}, {n}){_}{from?}{_}{nulls?}", TokenName = FunctionToken, BuilderType = typeof(ApplyFromAndNullsModifier), ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> NthValue<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, [ExprParameter] long n, [SqlQueryDependent] Sql.From from, [SqlQueryDependent] Sql.Nulls nulls) { throw new LinqException($"'{nameof(NthValue)}' is server-side method."); } [Sql.Extension("NTILE({expr})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAnalyticFunctionWithoutWindow<T> NTile<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr) { throw new LinqException($"'{nameof(NTile)}' is server-side method."); } [Sql.Extension("PERCENT_RANK({expr, ', '}) {within_group}", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static INeedsWithinGroupWithOrderOnly<T> PercentRank<T>(this Sql.ISqlExtension ext, [ExprParameter] params object[] expr) { throw new LinqException($"'{nameof(PercentRank)}' is server-side method."); } [Sql.Extension("PERCENT_RANK()", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAnalyticFunctionWithoutWindow<T> PercentRank<T>(this Sql.ISqlExtension ext) { throw new LinqException($"'{nameof(PercentRank)}' is server-side method."); } [Sql.Extension("PERCENTILE_CONT({expr}) {within_group}", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static INeedsWithinGroupWithSingleOrderAndMaybePartition<T> PercentileCont<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new LinqException($"'{nameof(PercentileCont)}' is server-side method."); } //TODO: check nulls support when ordering [Sql.Extension("PERCENTILE_DISC({expr}) {within_group}", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static INeedsWithinGroupWithSingleOrderAndMaybePartition<T> PercentileDisc<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new LinqException($"'{nameof(PercentileDisc)}' is server-side method."); } [Sql.Extension("RANK({expr, ', '}) {within_group}", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static INeedsWithinGroupWithOrderOnly<long> Rank(this Sql.ISqlExtension ext, [ExprParameter] params object[] expr) { throw new LinqException($"'{nameof(Rank)}' is server-side method."); } [Sql.Extension("RANK()", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAnalyticFunctionWithoutWindow<long> Rank(this Sql.ISqlExtension ext) { throw new LinqException($"'{nameof(Rank)}' is server-side method."); } [Sql.Extension("RATIO_TO_REPORT({expr}) {over}", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IOverWithPartitionNeeded<TR> RatioToReport<TR>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new LinqException($"'{nameof(RatioToReport)}' is server-side method."); } #region REGR_ function [Sql.Extension("REGR_SLOPE({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> RegrSlope<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new LinqException($"'{nameof(RegrSlope)}' is server-side method."); } [Sql.Extension("REGR_INTERCEPT({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> RegrIntercept<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new LinqException($"'{nameof(RegrIntercept)}' is server-side method."); } [Sql.Extension("REGR_COUNT({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<long> RegrCount(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new LinqException($"'{nameof(RegrCount)}' is server-side method."); } [Sql.Extension("REGR_R2({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> RegrR2<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new LinqException($"'{nameof(RegrR2)}' is server-side method."); } [Sql.Extension("REGR_AVGX({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> RegrAvgX<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new LinqException($"'{nameof(RegrAvgX)}' is server-side method."); } [Sql.Extension("REGR_AVGY({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> RegrAvgY<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new LinqException($"'{nameof(RegrAvgY)}' is server-side method."); } // ReSharper disable once InconsistentNaming [Sql.Extension("REGR_SXX({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> RegrSXX<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new LinqException($"'{nameof(RegrSXX)}' is server-side method."); } // ReSharper disable once InconsistentNaming [Sql.Extension("REGR_SYY({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> RegrSYY<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new LinqException($"'{nameof(RegrSYY)}' is server-side method."); } // ReSharper disable once InconsistentNaming [Sql.Extension("REGR_SXY({expr1}, {expr2})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> RegrSXY<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr1, [ExprParameter] object expr2) { throw new LinqException($"'{nameof(RegrSXY)}' is server-side method."); } #endregion [Sql.Extension("ROW_NUMBER()", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAnalyticFunctionWithoutWindow<long> RowNumber(this Sql.ISqlExtension ext) { throw new LinqException($"'{nameof(RowNumber)}' is server-side method."); } #region StdDev [Sql.Extension( "STDEV({expr})", TokenName = FunctionToken, ChainPrecedence = 0, IsAggregate = true)] [Sql.Extension(PN.Oracle, "STDDEV({expr})", TokenName = FunctionToken, ChainPrecedence = 0, IsAggregate = true)] public static double StdDev<TEntity, TV>(this IEnumerable<TEntity> source, [ExprParameter] Func<TEntity, TV> expr) { throw new LinqException($"'{nameof(StdDev)}' is server-side method."); } [Sql.Extension( "STDEV({modifier?}{_}{expr})", TokenName = FunctionToken, BuilderType = typeof(ApplyAggregateModifier), ChainPrecedence = 0, IsAggregate = true)] [Sql.Extension(PN.Oracle, "STDDEV({modifier?}{_}{expr})", TokenName = FunctionToken, BuilderType = typeof(ApplyAggregateModifier), ChainPrecedence = 0, IsAggregate = true)] public static double StdDev<TEntity, TV>(this IEnumerable<TEntity> source, [ExprParameter] Func<TEntity, TV> expr, [SqlQueryDependent] Sql.AggregateModifier modifier) { throw new LinqException($"'{nameof(StdDev)}' is server-side method."); } [Sql.Extension( "STDEV({modifier?}{_}{expr})", TokenName = FunctionToken, BuilderType = typeof(ApplyAggregateModifier), ChainPrecedence = 0, IsAggregate = true)] [Sql.Extension(PN.Oracle, "STDDEV({modifier?}{_}{expr})", TokenName = FunctionToken, BuilderType = typeof(ApplyAggregateModifier), ChainPrecedence = 0, IsAggregate = true)] public static double StdDev<TEntity, TV>([NotNull] this IQueryable<TEntity> source, [NotNull] [ExprParameter] Expression<Func<TEntity, TV>> expr, [SqlQueryDependent] Sql.AggregateModifier modifier = Sql.AggregateModifier.None ) { if (source == null) throw new ArgumentNullException(nameof(source)); if (expr == null) throw new ArgumentNullException(nameof(expr)); var currentSource = LinqExtensions.ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.Execute<double>( Expression.Call( null, MethodHelper.GetMethodInfo(AnalyticFunctions.StdDev, source, expr, modifier), new Expression[] { currentSource.Expression, Expression.Quote(expr), Expression.Constant(modifier) } )); } [Sql.Extension( "STDEV({expr})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] [Sql.Extension(PN.Oracle, "STDDEV({expr})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> StdDev<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new LinqException($"'{nameof(StdDev)}' is server-side method."); } [Sql.Extension( "STDEV({modifier?}{_}{expr})", TokenName = FunctionToken, BuilderType = typeof(ApplyAggregateModifier), ChainPrecedence = 1, IsAggregate = true)] [Sql.Extension(PN.Oracle, "STDDEV({modifier?}{_}{expr})", TokenName = FunctionToken, BuilderType = typeof(ApplyAggregateModifier), ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> StdDev<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr, [SqlQueryDependent] Sql.AggregateModifier modifier) { throw new LinqException($"'{nameof(StdDev)}' is server-side method."); } #endregion StdDev #region StdDevPop [Sql.Extension("STDDEV_POP({expr})", IsAggregate = true, ChainPrecedence = 0)] public static decimal StdDevPop<TEntity, TV>(this IEnumerable<TEntity> source, [ExprParameter] Func<TEntity, TV> expr) { throw new LinqException($"'{nameof(StdDevPop)}' is server-side method."); } [Sql.Extension("STDDEV_POP({expr})", IsAggregate = true, ChainPrecedence = 0)] public static decimal StdDevPop<TEntity, TV>([NotNull] this IQueryable<TEntity> source, [NotNull] [ExprParameter] Expression<Func<TEntity, TV>> expr) { if (source == null) throw new ArgumentNullException(nameof(source)); if (expr == null) throw new ArgumentNullException(nameof(expr)); var currentSource = LinqExtensions.ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.Execute<decimal>( Expression.Call( null, MethodHelper.GetMethodInfo(AnalyticFunctions.StdDevPop, source, expr), new Expression[] { currentSource.Expression, Expression.Quote(expr) } )); } [Sql.Extension("STDDEV_POP({expr})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> StdDevPop<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new LinqException($"'{nameof(StdDevPop)}' is server-side method."); } #endregion StdDevPop #region StdDevSamp [Sql.Extension("STDDEV_SAMP({expr})", IsAggregate = true, ChainPrecedence = 0)] public static decimal StdDevSamp<TEntity, TV>(this IEnumerable<TEntity> source, [ExprParameter] Func<TEntity, TV> expr) { throw new LinqException($"'{nameof(StdDevSamp)}' is server-side method."); } [Sql.Extension("STDDEV_SAMP({expr})", IsAggregate = true, ChainPrecedence = 0)] public static decimal StdDevSamp<TEntity, TV>([NotNull] this IQueryable<TEntity> source, [NotNull] [ExprParameter] Expression<Func<TEntity, TV>> expr) { if (source == null) throw new ArgumentNullException(nameof(source)); if (expr == null) throw new ArgumentNullException(nameof(expr)); var currentSource = LinqExtensions.ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.Execute<decimal>( Expression.Call( null, MethodHelper.GetMethodInfo(AnalyticFunctions.StdDevSamp, source, expr), new Expression[] { currentSource.Expression, Expression.Quote(expr) } )); } [Sql.Extension("STDDEV_SAMP({expr})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> StdDevSamp<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new LinqException($"'{nameof(StdDevSamp)}' is server-side method."); } #endregion StdDevSamp [Sql.Extension("SUM({expr})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> Sum<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr) { throw new LinqException($"'{nameof(Sum)}' is server-side method."); } [Sql.Extension("SUM({modifier?}{_}{expr})" , BuilderType = typeof(ApplyAggregateModifier), TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> Sum<T>(this Sql.ISqlExtension ext, [ExprParameter] T expr, [SqlQueryDependent] Sql.AggregateModifier modifier) { throw new LinqException($"'{nameof(Sum)}' is server-side method."); } #region VarPop [Sql.Extension("VAR_POP({expr})", IsAggregate = true, ChainPrecedence = 0)] public static decimal VarPop<TEntity, TV>(this IEnumerable<TEntity> source, [ExprParameter] Func<TEntity, TV> expr) { throw new LinqException($"'{nameof(VarPop)}' is server-side method."); } [Sql.Extension("VAR_POP({expr})", IsAggregate = true, ChainPrecedence = 0)] public static decimal VarPop<TEntity, TV>([NotNull] this IQueryable<TEntity> source, [NotNull] [ExprParameter] Expression<Func<TEntity, TV>> expr) { if (source == null) throw new ArgumentNullException(nameof(source)); if (expr == null) throw new ArgumentNullException(nameof(expr)); var currentSource = LinqExtensions.ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.Execute<decimal>( Expression.Call( null, MethodHelper.GetMethodInfo(AnalyticFunctions.VarPop, source, expr), new Expression[] { currentSource.Expression, Expression.Quote(expr) } )); } [Sql.Extension("VAR_POP({expr})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> VarPop<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new LinqException($"'{nameof(VarPop)}' is server-side method."); } #endregion VarPop #region VarSamp [Sql.Extension("VAR_SAMP({expr})", IsAggregate = true, ChainPrecedence = 0)] public static decimal VarSamp<TEntity, TV>(this IEnumerable<TEntity> source, [ExprParameter] Func<TEntity, TV> expr) { throw new LinqException($"'{nameof(VarSamp)}' is server-side method."); } [Sql.Extension("VAR_SAMP({expr})", IsAggregate = true, ChainPrecedence = 0)] public static decimal VarSamp<TEntity, TV>([NotNull] this IQueryable<TEntity> source, [NotNull] [ExprParameter] Expression<Func<TEntity, TV>> expr) { if (source == null) throw new ArgumentNullException(nameof(source)); if (expr == null) throw new ArgumentNullException(nameof(expr)); var currentSource = LinqExtensions.ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.Execute<decimal>( Expression.Call( null, MethodHelper.GetMethodInfo(AnalyticFunctions.VarSamp, source, expr), new Expression[] { currentSource.Expression, Expression.Quote(expr) } )); } [Sql.Extension("VAR_SAMP({expr})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> VarSamp<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new LinqException($"'{nameof(VarSamp)}' is server-side method."); } #endregion VarSamp #region Variance [Sql.Extension("VARIANCE({expr})", IsAggregate = true, ChainPrecedence = 0)] public static TV Variance<TEntity, TV>(this IEnumerable<TEntity> source, [ExprParameter] Func<TEntity, TV> expr) { throw new LinqException($"'{nameof(Variance)}' is server-side method."); } [Sql.Extension("VARIANCE({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), IsAggregate = true, ChainPrecedence = 0)] public static TV Variance<TEntity, TV>(this IEnumerable<TEntity> source, [ExprParameter] Func<TEntity, TV> expr, [SqlQueryDependent] Sql.AggregateModifier modifier) { throw new LinqException($"'{nameof(Variance)}' is server-side method."); } [Sql.Extension("VARIANCE({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), IsAggregate = true, ChainPrecedence = 0)] public static TV Variance<TEntity, TV>([NotNull] this IQueryable<TEntity> source, [NotNull] [ExprParameter] Expression<Func<TEntity, TV>> expr, [SqlQueryDependent] Sql.AggregateModifier modifier = Sql.AggregateModifier.None) { if (source == null) throw new ArgumentNullException(nameof(source)); if (expr == null) throw new ArgumentNullException(nameof(expr)); var currentSource = LinqExtensions.ProcessSourceQueryable?.Invoke(source) ?? source; return currentSource.Provider.Execute<TV>( Expression.Call( null, MethodHelper.GetMethodInfo(AnalyticFunctions.Variance, source, expr, modifier), new Expression[] { currentSource.Expression, Expression.Quote(expr), Expression.Constant(modifier) } )); } [Sql.Extension("VARIANCE({expr})", TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> Variance<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr) { throw new LinqException($"'{nameof(Variance)}' is server-side method."); } [Sql.Extension("VARIANCE({modifier?}{_}{expr})", BuilderType = typeof(ApplyAggregateModifier), TokenName = FunctionToken, ChainPrecedence = 1, IsAggregate = true)] public static IAggregateFunctionSelfContained<T> Variance<T>(this Sql.ISqlExtension ext, [ExprParameter] object expr, [SqlQueryDependent] Sql.AggregateModifier modifier) { throw new LinqException($"'{nameof(Variance)}' is server-side method."); } #endregion [Sql.Extension("{function} KEEP (DENSE_RANK FIRST {order_by_clause}){_}{over?}", ChainPrecedence = 10, IsAggregate = true)] public static INeedOrderByAndMaybeOverWithPartition<TR> KeepFirst<TR>(this IAggregateFunction<TR> ext) { throw new LinqException($"'{nameof(KeepFirst)}' is server-side method."); } [Sql.Extension("{function} KEEP (DENSE_RANK LAST {order_by_clause}){_}{over?}", ChainPrecedence = 10, IsAggregate = true)] public static INeedOrderByAndMaybeOverWithPartition<TR> KeepLast<TR>(this IAggregateFunction<TR> ext) { throw new LinqException($"'{nameof(KeepLast)}' is server-side method."); } #endregion Analytic functions } }
46.828891
230
0.712827
[ "MIT" ]
FrancisChung/linq2db
Source/LinqToDB/Sql/Sql.Analytic.cs
53,302
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Sistema.Entidades.Almacen; using System; using System.Collections.Generic; using System.Text; namespace Sistema.Datos.Mapping.Almacen { public class DetalleIngresoMap : IEntityTypeConfiguration<DetalleIngreso> { public void Configure(EntityTypeBuilder<DetalleIngreso> builder) { builder.ToTable("detalle_ingreso") .HasKey(d => d.iddetalle_ingreso); } } }
27.368421
77
0.725
[ "Apache-2.0" ]
TIEMSOLUTIONS/backend.unilever
Sistema.Datos/Mapping/Almacen/DetalleIngreso.cs
522
C#
namespace That_One_Nerd.Unity.Games.ArcadeManiac.Misc.Extensions { public static class IsSimilarExtension { public static bool IsSimilar(this string a, string b) => a.Trim().ToLower() == b.Trim().ToLower(); } }
28.875
106
0.692641
[ "Apache-2.0" ]
That-One-Nerd/Arcade-Maniac
Source/Assets/Misc/Scripts/Extensions/IsSimilarExtension.cs
231
C#
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ namespace Adxstudio.Xrm.Visualizations { using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using Adxstudio.Xrm.Services.Query; /// <summary> /// Defines the data description of a CRM chart visualization (savedqueryvisualization). /// </summary> public class DataDefinition { /// <summary> /// Collection of <see cref="Fetch"/> /// </summary> public ICollection<Fetch> FetchCollection { get; set; } /// <summary> /// Collection of <see cref="Category"/> /// </summary> public ICollection<Category> CategoryCollection { get; set; } /// <summary> /// Parse data description XML string into a DataDefinition object. /// </summary> /// <param name="text">The data description XML string to be parsed.</param> /// <returns>The <see cref="DataDefinition"/> result from parsing the XML string.</returns> public static DataDefinition Parse(string text) { return text == null ? null : Parse(XElement.Parse(text)); } /// <summary> /// Parse data description XML into a DataDefinition object. /// </summary> /// <param name="element">The data description XML element to be parsed.</param> /// <returns>The <see cref="DataDefinition"/> result from parsing the XML.</returns> public static DataDefinition Parse(XElement element) { if (element == null) { return null; } var fetchCollectionElement = element.Element("fetchcollection"); if (fetchCollectionElement == null) { return null; } var fetchElements = fetchCollectionElement.Elements("fetch"); var categoryCollectionElement = element.Element("categorycollection"); if (categoryCollectionElement == null) { return null; } var categoryElements = categoryCollectionElement.Elements("category"); var categoryCollection = categoryElements.Select(Category.Parse).ToList(); var fetchCollection = fetchElements.Select(Fetch.Parse).ToList(); foreach (var fetch in fetchCollection) { // DateGrouping require us to also retrieve a datetime value so we can format series labels correctly. // Grouping by day for example with a date like 9/23/2016 will result in the value 23 to be stored in the data. // We must manually add this aggregate attribute into the fetch so we get the actual date value 9/23/2016 displayed in the chart series. var dateGroupingAttributes = fetch.Entity.Attributes.Where(a => a.DateGrouping != null && a.DateGrouping.Value == DateGroupingType.Day).ToArray(); foreach (var attribute in dateGroupingAttributes) { fetch.Entity.Attributes.Add(new FetchAttribute(attribute.Name, string.Format("{0}_dategroup_value", attribute.Alias), AggregateType.Max)); } } return new DataDefinition { CategoryCollection = categoryCollection, FetchCollection = fetchCollection }; } } }
32.333333
150
0.711008
[ "MIT" ]
Adoxio/xRM-Portals-Community-Edition
Framework/Adxstudio.Xrm/Visualizations/DataDefinition.cs
3,007
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EC2.Model { /// <summary> /// Describes the credit option for CPU usage of a T2, T3, or T3a instance. /// </summary> public partial class CreditSpecification { private string _cpuCredits; /// <summary> /// Gets and sets the property CpuCredits. /// <para> /// The credit option for CPU usage of a T2, T3, or T3a instance. Valid values are <code>standard</code> /// and <code>unlimited</code>. /// </para> /// </summary> public string CpuCredits { get { return this._cpuCredits; } set { this._cpuCredits = value; } } // Check to see if CpuCredits property is set internal bool IsSetCpuCredits() { return this._cpuCredits != null; } } }
30.5
113
0.628038
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/CreditSpecification.cs
1,769
C#
namespace System.Text.Json.Serialization { public class TimeSpanConverter : TimeSpanFormatConverter { public TimeSpanConverter() : base("c") { } } public class TimeSpanFormatConverter : JsonConverter<TimeSpan> { public TimeSpanFormatConverter(string formatStr) { if (string.IsNullOrWhiteSpace(formatStr)) throw new ArgumentNullException(nameof(formatStr)); Format = formatStr; } protected string Format { get; } public override TimeSpan Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (!TimeSpan.TryParse(reader.GetString(), out TimeSpan value)) { throw new FormatException("The JSON value is not in a supported TimeSpan format."); } return value; } public override void Write(Utf8JsonWriter writer, TimeSpan value, JsonSerializerOptions options) { writer.WriteStringValue(value.ToString(Format)); } } }
28.921053
115
0.616015
[ "Apache-2.0" ]
HEF-Sharp/HEF.Extensions.Serialization
src/HEF.Extensions.SystemTextJson/Converters/TimeSpanConverter.cs
1,101
C#
// Copyright (c) Xenko contributors (https://xenko.com) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using System.Threading; namespace Xenko.Core.Transactions { /// <summary> /// An interface representing a transaction currently in progress. The transaction must be /// completed in the same <see cref="SynchronizationContext"/> it was created. /// </summary> public interface ITransaction : IDisposable { /// <summary> /// Gets an unique identifier for the transaction. /// </summary> Guid Id { get; } /// <summary> /// Gets whether this transaction is empty. /// </summary> bool IsEmpty { get; } /// <summary> /// Continues the transaction when the current <see cref="SynchronizationContext"/> has changed, allowing to push additional operations or complete it. /// </summary> void Continue(); /// <summary> /// Completes the transaction by closing it and adding it to the transaction stack. /// </summary> /// <remarks>This method is invoked by the <see cref="IDisposable.Dispose"/> method.</remarks> void Complete(); /// <summary> /// Keep the transaction alive until an additional call to <see cref="Complete"/> is done. /// </summary> void AddReference(); } }
36.560976
159
0.628419
[ "MIT" ]
Aminator/xenko
sources/core/Xenko.Core.Design/Transactions/ITransaction.cs
1,499
C#
using System; namespace Sce.Pss.HighLevel.UI { public enum KeyEventType { Up, Down, LongPress, Repeat } }
9.076923
30
0.677966
[ "MIT" ]
weimingtom/Sakura
Sce.Pss.HighLevel/UI/KeyEventType.cs
118
C#
/*-----------------------------+------------------------------\ | | | !!!NOTICE!!! | | | | These libraries are under heavy development so they are | | subject to make many changes as development continues. | | For this reason, the libraries may not be well commented. | | THANK YOU for supporting forge with all your feedback | | suggestions, bug reports and comments! | | | | - The Forge Team | | Bearded Man Studios, Inc. | | | | This source code, project files, and associated files are | | copyrighted by Bearded Man Studios, Inc. (2012-2015) and | | may not be redistributed without written permission. | | | \------------------------------+-----------------------------*/ using BeardedManStudios.Source.Threading; using BeardedManStudios.Threading; using System; using System.Collections.Generic; using UnityEngine; namespace BeardedManStudios.Forge.Networking.Unity { public class MainThreadManager : MonoBehaviour, IThreadRunner { public enum UpdateType { FixedUpdate, Update, LateUpdate, } public delegate void UpdateEvent(); public static UpdateEvent unityFixedUpdate = null; public static UpdateEvent unityUpdate = null; public static UpdateEvent unityLateUpdate = null; /// <summary> /// The singleton instance of the Main Thread Manager /// </summary> private static MainThreadManager _instance; public static MainThreadManager Instance { get { if (_instance == null) Create(); return _instance; } } /// <summary> /// This will create a main thread manager if one is not already created /// </summary> public static void Create() { if (_instance != null) return; ThreadManagement.Initialize(); if (!ReferenceEquals(_instance, null)) return; new GameObject("Main Thread Manager").AddComponent<MainThreadManager>(); } private void OnDestroy() { _instance = null; } /// <summary> /// A dictionary of action queues for different updates. /// </summary> private static Dictionary<UpdateType, Queue<Action>> actionQueueDict = new Dictionary<UpdateType, Queue<Action>>(); private static Dictionary<UpdateType, Queue<Action>> actionRunnerDict = new Dictionary<UpdateType, Queue<Action>>(); // Setup the singleton in the Awake private void Awake() { // If an instance already exists then delete this copy if (_instance != null) { Destroy(gameObject); return; } // Assign the static reference to this object _instance = this; // This object should move through scenes DontDestroyOnLoad(gameObject); } public void Execute(Action action) { Run(action); } /// <summary> /// Add a function to the list of functions to call on the main thread via the Update function /// </summary> /// <param name="action">The method that is to be run on the main thread</param> public static void Run(Action action, UpdateType updateType = UpdateType.FixedUpdate) { // Only create this object on the main thread #if UNITY_WEBGL if (ReferenceEquals(Instance, null)) #else if (ReferenceEquals(Instance, null) && ThreadManagement.IsMainThread) #endif { Create(); } // Allocate new action queue by update type if there's no one exists. if (!actionQueueDict.ContainsKey(updateType)) { actionQueueDict.Add(updateType, new Queue<Action>()); // Since an action runner depends on the action queue, allocate new one here. actionRunnerDict.Add(updateType, new Queue<Action>()); } Queue<Action> mainThreadActions = actionQueueDict[updateType]; // Make sure to lock the mutex so that we don't override // other threads actions lock (mainThreadActions) { mainThreadActions.Enqueue(action); } } private void HandleActions(UpdateType updateType) { // Allocate new action queue by update type if there's no one exists. if (!actionQueueDict.ContainsKey(updateType)) { actionQueueDict.Add(updateType, new Queue<Action>()); // Since an action runner depends on the action queue, allocate new one here. actionRunnerDict.Add(updateType, new Queue<Action>()); } Queue<Action> mainThreadActions = actionQueueDict[updateType]; Queue<Action> mainThreadActionsRunner = actionRunnerDict[updateType]; lock (mainThreadActions) { // Flush the list to unlock the thread as fast as possible if (mainThreadActions.Count > 0) { while (mainThreadActions.Count > 0) mainThreadActionsRunner.Enqueue(mainThreadActions.Dequeue()); } } // If there are any functions in the list, then run // them all and then clear the list if (mainThreadActionsRunner.Count > 0) { while (mainThreadActionsRunner.Count > 0) mainThreadActionsRunner.Dequeue()(); } } private void FixedUpdate() { HandleActions(UpdateType.FixedUpdate); if (unityFixedUpdate != null) unityFixedUpdate(); } private void Update() { HandleActions(UpdateType.Update); if (unityUpdate != null) unityUpdate(); } private void LateUpdate() { HandleActions(UpdateType.LateUpdate); if (unityLateUpdate != null) unityLateUpdate(); } #if WINDOWS_UWP public static async void ThreadSleep(int length) #else public static void ThreadSleep(int length) #endif { #if WINDOWS_UWP await System.Threading.Tasks.Task.Delay(System.TimeSpan.FromSeconds(length)); #else System.Threading.Thread.Sleep(length); #endif } } }
27.863208
118
0.632131
[ "Apache-2.0" ]
mattnewport/ForgeNetworkingRemastered
Forge Networking Remastered Unity/Assets/Bearded Man Studios Inc/Scripts/MainThreadManager.cs
5,909
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.ContractsLight; using System.Diagnostics.Tracing; using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; using BuildXL.Native.IO; using BuildXL.Pips.Operations; using BuildXL.Storage; using BuildXL.ToolSupport; using BuildXL.Utilities; using BuildXL.Utilities.Configuration; using BuildXL.Utilities.Instrumentation.Common; using BuildXL.Utilities.Tracing; using HelpLevel = BuildXL.ToolSupport.HelpLevel; namespace BuildXL.Execution.Analyzer { internal class ConsoleEventListener : FormattingEventListener { public ConsoleEventListener(Events eventSource, DateTime baseTime, WarningMapper warningMapper = null, EventLevel level = EventLevel.Verbose, bool captureAllDiagnosticMessages = false, TimeDisplay timeDisplay = TimeDisplay.None, EventMask eventMask = null, DisabledDueToDiskWriteFailureEventHandler onDisabledDueToDiskWriteFailure = null, bool listenDiagnosticMessages = false, bool useCustomPipDescription = false) : base(eventSource, baseTime, warningMapper, level, captureAllDiagnosticMessages, timeDisplay, eventMask, onDisabledDueToDiskWriteFailure, listenDiagnosticMessages, useCustomPipDescription) { } protected override void Output(EventLevel level, EventWrittenEventArgs eventData, string text, bool doNotTranslatePaths = false) { Console.WriteLine($"[{DateTime.Now:HH:mm:ss.ff}] {text}"); } } internal sealed partial class Args : CommandLineUtilities { private static readonly string[] s_helpStrings = new[] { "?", "help" }; private readonly AnalysisMode? m_mode; private readonly AnalysisInput m_analysisInput; private AnalysisInput m_analysisInputOther; private readonly Analyzer m_analyzer; private readonly Analyzer m_analyzerOther; private readonly bool m_canHandleWorkerEvents = true; public readonly IEnumerable<Option> AnalyzerOptions; public readonly bool Help; public readonly LoggingContext LoggingContext = new LoggingContext("BuildXL.Execution.Analyzer"); public readonly TrackingEventListener TrackingEventListener = new TrackingEventListener(Events.Log); public readonly ConsoleEventListener ConsoleListener = new ConsoleEventListener(Events.Log, DateTime.UtcNow); // Variables that are unused without full telemetry private readonly bool m_telemetryDisabled = false; private readonly Stopwatch m_telemetryStopwatch = new Stopwatch(); public Args(string[] args) : base(args) { List<Option> analyzerOptions = new List<Option>(); string cachedGraphDirectory = null; // TODO: Embed HashType in XLG file and update analyzer to use that instead of setting HashType globally. ContentHashingUtilities.SetDefaultHashType(); foreach (Option opt in Options) { if (opt.Name.Equals("executionLog", StringComparison.OrdinalIgnoreCase) || opt.Name.Equals("xl", StringComparison.OrdinalIgnoreCase)) { if (string.IsNullOrEmpty(m_analysisInput.ExecutionLogPath)) { m_analysisInput.ExecutionLogPath = ParsePathOption(opt); } else { m_analysisInputOther.ExecutionLogPath = ParseSingletonPathOption(opt, m_analysisInputOther.ExecutionLogPath); } } else if (opt.Name.Equals("graphDirectory", StringComparison.OrdinalIgnoreCase) || opt.Name.Equals("gd", StringComparison.OrdinalIgnoreCase)) { cachedGraphDirectory = ParseSingletonPathOption(opt, cachedGraphDirectory); } else if (opt.Name.Equals("mode", StringComparison.OrdinalIgnoreCase) || opt.Name.Equals("m", StringComparison.OrdinalIgnoreCase)) { m_mode = ParseEnumOption<AnalysisMode>(opt); } else if (opt.Name.Equals("disableTelemetry")) { m_telemetryDisabled = true; } else if (opt.Name.Equals("disableWorkerEvents", StringComparison.OrdinalIgnoreCase)) { m_canHandleWorkerEvents = false; } else if (s_helpStrings.Any(s => opt.Name.Equals(s, StringComparison.OrdinalIgnoreCase))) { // If the analyzer was called with '/help' argument - print help and exit Help = true; WriteHelp(); return; } else { analyzerOptions.Add(opt); } } AnalyzerOptions = analyzerOptions; if (!m_mode.HasValue) { throw Error("Mode parameter is required"); } // Add required parameter errors here switch (m_mode.Value) { case AnalysisMode.ObservedAccess: { if (!analyzerOptions.Any(opt => opt.Name.Equals("o"))) { throw Error("When executing `ObservedAccess` mode, an `/o:PATH_TO_OUTPUT_FILE` parameter is required to store the generated output"); } break; } } // Only send telemetry if all arguments were valid TelemetryStartup(); switch (m_mode.Value) { case AnalysisMode.SpecClosure: var analyzer = InitializeSpecClosureAnalyzer(); analyzer.Analyze(); break; } if (string.IsNullOrEmpty(m_analysisInput.ExecutionLogPath) && string.IsNullOrEmpty(cachedGraphDirectory)) { // Try to find the last build log from the user if none was specied. var invocation = new global::BuildXL.Engine.Invocations().GetLastInvocation(LoggingContext); if (invocation == null || !Directory.Exists(invocation.Value.LogsFolder)) { throw Error("executionLog or graphDirectory parameter is required"); } Console.WriteLine("Using last build from: '{0}', you can use /executionLog or /graphDirectory arguments to explicitly choose a build", invocation.Value.LogsFolder); m_analysisInput.ExecutionLogPath = invocation.Value.LogsFolder; } if (m_mode.Value == AnalysisMode.LogCompare && string.IsNullOrEmpty(m_analysisInput.ExecutionLogPath)) { throw Error("Additional executionLog to compare parameter is required"); } // The fingerprint store based cache miss analyzer // only uses graph information from the newer build, so skip loading the graph for the earlier build if (m_mode.Value != AnalysisMode.CacheMiss) { if (!m_analysisInput.LoadCacheGraph(cachedGraphDirectory)) { throw Error($"Could not load cached graph from directory {cachedGraphDirectory}"); } } switch (m_mode.Value) { case AnalysisMode.Allowlist: case AnalysisMode.Whitelist: m_analyzer = InitializeAllowlistAnalyzer(); break; case AnalysisMode.BuildStatus: m_analyzer = InitializeBuildStatus(m_analysisInput); break; case AnalysisMode.CacheDump: m_analyzer = InitializeCacheDumpAnalyzer(m_analysisInput); break; #if FEATURE_VSTS_ARTIFACTSERVICES case AnalysisMode.CacheHitPredictor: m_analyzer = InitializeCacheHitPredictor(); break; #endif case AnalysisMode.CacheMiss: // This analyzer does not rely on the execution log if (!m_analysisInputOther.LoadCacheGraph(null)) { throw Error("Could not load second cached graph"); } m_analyzer = InitializeFingerprintStoreAnalyzer(m_analysisInput, m_analysisInputOther); break; case AnalysisMode.CacheMissLegacy: m_analyzer = InitializeCacheMissAnalyzer(m_analysisInput); if (!m_analysisInputOther.LoadCacheGraph(null)) { throw Error("Could not load second cached graph"); } m_analyzerOther = ((CacheMissAnalyzer)m_analyzer).GetDiffAnalyzer(m_analysisInputOther); break; case AnalysisMode.Codex: m_analyzer = InitializeCodexAnalyzer(); break; case AnalysisMode.CopyFile: m_analyzer = InitializeCopyFilesAnalyzer(); break; case AnalysisMode.CosineDumpPip: m_analyzer = InitializeCosineDumpPip(); break; case AnalysisMode.CosineJson: m_analyzer = InitializeCosineJsonExport(); break; case AnalysisMode.CriticalPath: m_analyzer = InitializeCriticalPathAnalyzer(); break; case AnalysisMode.DebugLogs: ConsoleListener.RegisterEventSource(ETWLogger.Log); ConsoleListener.RegisterEventSource(FrontEnd.Script.Debugger.ETWLogger.Log); m_analyzer = InitializeDebugLogsAnalyzer(); break; case AnalysisMode.DependencyAnalyzer: m_analyzer = InitializeDependencyAnalyzer(); break; case AnalysisMode.Dev: m_analyzer = InitializeDevAnalyzer(); break; case AnalysisMode.DirMembership: m_analyzer = InitializeDirMembershipAnalyzer(); break; case AnalysisMode.DumpMounts: m_analyzer = InitializeDumpMountsAnalyzer(); break; case AnalysisMode.DumpPip: m_analyzer = InitializeDumpPipAnalyzer(); break; case AnalysisMode.DumpPipLite: m_analyzer = InitializeDumpPipLiteAnalyzer(m_analysisInput); break; case AnalysisMode.DumpProcess: m_analyzer = InitializeDumpProcessAnalyzer(); break; case AnalysisMode.DumpStringTable: m_analyzer = InitializeDumpStringTableAnalyzer(); break; case AnalysisMode.EventStats: m_analyzer = InitializeEventStatsAnalyzer(); break; case AnalysisMode.ExportDgml: m_analyzer = InitializeExportDgmlAnalyzer(); break; case AnalysisMode.ExportGraph: m_analyzer = InitializePipGraphExporter(); break; case AnalysisMode.ExtraDependencies: m_analyzer = InitializeExtraDependenciesAnalyzer(); break; case AnalysisMode.FailedPipsDump: m_analyzer = InitializeFailedPipsDumpAnalyzer(); if (!string.IsNullOrEmpty(m_analysisInputOther.ExecutionLogPath)) { if (!m_analysisInputOther.LoadCacheGraph(null)) { throw Error("Could not load second cached graph"); } m_analyzerOther = ((FailedPipsDumpAnalyzer)m_analyzer).GetDiffAnalyzer(m_analysisInputOther); } break; case AnalysisMode.FailedPipInput: m_analyzer = InitializeFailedPipInputAnalyzer(); break; case AnalysisMode.FileConsumption: m_analyzer = InitializeFileConsumptionAnalyzer(); break; case AnalysisMode.FileChangeTracker: m_analyzer = InitializeFileChangeTrackerAnalyzer(); break; case AnalysisMode.FileImpact: m_analyzer = InitializeFileImpactAnalyzer(); break; case AnalysisMode.FilterLog: m_analyzer = InitializeFilterLogAnalyzer(); break; case AnalysisMode.FingerprintText: m_analyzer = InitializeFingerprintTextAnalyzer(); break; case AnalysisMode.GraphDiffAnalyzer: if (!m_analysisInputOther.LoadCacheGraph(null)) { throw Error("Could not load second cached graph"); } m_analyzer = InitializeGraphDiffAnalyzer(); break; case AnalysisMode.IdeGenerator: m_analyzer = InitializeIdeGenerator(); break; case AnalysisMode.IncrementalSchedulingState: m_analyzer = InitializeIncrementalSchedulingStateAnalyzer(); break; case AnalysisMode.InputTracker: m_analyzer = InitializeInputTrackerAnalyzer(); break; case AnalysisMode.JavaScriptDependencyFixer: m_analyzer = JavaScriptDependencyFixerAnalyzer(); break; case AnalysisMode.LogCompare: m_analyzer = InitializeSummaryAnalyzer(m_analysisInput); if (!m_analysisInputOther.LoadCacheGraph(null)) { throw Error("Could not load second cached graph"); } m_analyzerOther = InitializeSummaryAnalyzer(m_analysisInputOther, true); break; case AnalysisMode.ObservedAccess: m_analyzer = InitializeObservedAccessAnalyzer(); break; case AnalysisMode.ObservedInput: m_analyzer = InitializeObservedInputResult(); break; case AnalysisMode.ObservedInputSummary: m_analyzer = InitializeObservedInputSummaryResult(); break; case AnalysisMode.PackedExecutionExporter: m_analyzer = InitializePackedExecutionExporter(); break; case AnalysisMode.PerfSummary: m_analyzer = InitializePerfSummaryAnalyzer(); break; case AnalysisMode.PipExecutionPerformance: m_analyzer = InitializePipExecutionPerformanceAnalyzer(); break; case AnalysisMode.PipFilter: m_analyzer = InitializePipFilterAnalyzer(); break; case AnalysisMode.PipFingerprint: m_analyzer = InitializePipFingerprintAnalyzer(m_analysisInput); break; case AnalysisMode.ProcessDetouringStatus: m_analyzer = InitializeProcessDetouringStatusAnalyzer(); break; case AnalysisMode.ReportedProcesses: m_analyzer = InitializeReportedProcessesAnalyzer(); break; case AnalysisMode.ProcessRunScript: m_analyzer = InitializeProcessRunScriptAnalyzer(); break; case AnalysisMode.RequiredDependencies: m_analyzer = InitializeRequiredDependencyAnalyzer(); break; case AnalysisMode.ScheduledInputsOutputs: m_analyzer = InitializeScheduledInputsOutputsAnalyzer(); break; case AnalysisMode.Simulate: m_analyzer = InitializeBuildSimulatorAnalyzer(m_analysisInput); break; case AnalysisMode.ToolEnumeration: m_analyzer = InitializeToolEnumerationAnalyzer(); break; case AnalysisMode.WinIdeDependency: m_analyzer = InitializeWinIdeDependencyAnalyzer(); break; default: Contract.Assert(false, "Unhandled analysis mode"); break; } Contract.Assert(m_analyzer != null, "Analyzer must be set."); m_analyzer.LoggingContext = LoggingContext; m_analyzer.CanHandleWorkerEvents = m_canHandleWorkerEvents; if (m_analyzerOther != null) { m_analyzerOther.CanHandleWorkerEvents = m_canHandleWorkerEvents; } } private static void PrintInvalidXlgError(Exception e) { var originalColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine("ERROR: " + e.Message); Console.ForegroundColor = originalColor; var path = FileUtilities.GetTempFileName(); File.WriteAllText(path, e.ToString()); Console.WriteLine("Full stack trace saved to " + path); } public static void TruncatedXlgWarning() { ConsoleColor originalColor = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Yellow; Console.Error.WriteLine("WARNING: Execution log file possibly truncated, results may be incomplete!"); Console.ForegroundColor = originalColor; } public int Analyze() { if (m_analyzer == null) { return 0; } try { m_analyzer.Prepare(); bool dataIsComplete = true; if (m_analysisInput.ExecutionLogPath != null) { // NOTE: We call Prepare above so we don't need to prepare as a part of reading the execution log var reader = Task.Run(() => dataIsComplete &= m_analyzer.ReadExecutionLog(prepare: false)); if (m_mode == AnalysisMode.LogCompare) { m_analyzerOther.Prepare(); var otherReader = Task.Run(() => dataIsComplete &= m_analyzerOther.ReadExecutionLog()); otherReader.Wait(); } if (m_mode == AnalysisMode.FailedPipsDump && m_analyzerOther != null) { var start = DateTime.Now; Console.WriteLine($"[{start}] Reading compare to Log"); var otherReader = Task.Run(() => dataIsComplete &= m_analyzerOther.ReadExecutionLog()); otherReader.Wait(); var duration = DateTime.Now - start; Console.WriteLine($"Done reading compare to log : duration = [{duration}]"); } reader.Wait(); if (m_mode == AnalysisMode.CacheMissLegacy) { // First pass just to read in PipCacheMissType data var otherReader = Task.Run(() => dataIsComplete &= m_analyzerOther.ReadExecutionLog()); otherReader.Wait(); // Second pass to do fingerprint differences analysis otherReader = Task.Run(() => dataIsComplete &= m_analyzerOther.ReadExecutionLog()); otherReader.Wait(); } } if (!dataIsComplete) { TruncatedXlgWarning(); } var exitCode = m_analyzer.Analyze(); if (m_mode == AnalysisMode.FailedPipsDump && m_analyzerOther != null) { var failedPipsDump = (FailedPipsDumpAnalyzer)m_analyzer; exitCode = failedPipsDump.Compare(m_analyzerOther); } if (m_mode == AnalysisMode.LogCompare) { m_analyzerOther.Analyze(); SummaryAnalyzer summary = (SummaryAnalyzer)m_analyzer; exitCode = summary.Compare((SummaryAnalyzer)m_analyzerOther); } if (m_mode == AnalysisMode.CacheMissLegacy) { exitCode = m_analyzerOther.Analyze(); } return exitCode; } catch (InvalidDataException e) { PrintInvalidXlgError(e); return -1; } finally { m_analyzer?.Dispose(); m_analyzerOther?.Dispose(); TelemetryShutdown(); } } #region Telemetry private void HandleUnhandledFailure(Exception exception) { // Show the exception to the user ConsoleColor original = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Red; Console.Error.WriteLine(exception.ToString()); Console.ForegroundColor = original; // Log the exception to telemetry if (AriaV2StaticState.IsEnabled) { Tracing.Logger.Log.ExecutionAnalyzerCatastrophicFailure(LoggingContext, m_mode.ToString(), exception.ToString()); TelemetryShutdown(); } Environment.Exit(ExitCode.FromExitKind(ExitKind.InternalError)); } private void TelemetryStartup() { AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => { HandleUnhandledFailure( eventArgs.ExceptionObject as Exception ); }; if (!Debugger.IsAttached && !m_telemetryDisabled) { AriaV2StaticState.Enable(global::BuildXL.Tracing.AriaTenantToken.Key); TrackingEventListener.RegisterEventSource(ETWLogger.Log); m_telemetryStopwatch.Start(); } } private void TelemetryShutdown() { if (AriaV2StaticState.IsEnabled && !m_telemetryDisabled) { m_telemetryStopwatch.Stop(); Tracing.Logger.Log.ExecutionAnalyzerInvoked(LoggingContext, m_mode.ToString(), m_telemetryStopwatch.ElapsedMilliseconds, Environment.CommandLine); LogEventSummary(); // Analyzer telemetry is not critical to BuildXL, so no special handling for telemetry shutdown issues AriaV2StaticState.TryShutDown(TimeSpan.FromSeconds(10), out Exception telemetryShutdownException); } } #endregion Telemetry private AnalysisInput GetAnalysisInput() { return m_analysisInput; } private static void WriteHelp() { HelpWriter writer = new HelpWriter(); writer.WriteBanner($"{Branding.AnalyzerExecutableName} - Tool for performing analysis/transformation of cached pip graphs and execution logs."); writer.WriteLine(""); writer.WriteLine("Analysis Modes:"); writer.WriteLine(""); WriteFingerprintTextAnalyzerHelp(writer); writer.WriteLine(""); WritePipGraphExporterHelp(writer); writer.WriteLine(""); WriteDirMembershipHelp(writer); writer.WriteLine(""); WriteDumpProcessAnalyzerHelp(writer); writer.WriteLine(""); WriteExportDgmlAnalyzerHelp(writer); writer.WriteLine(""); WriteExtraDependenciesAnalyzerHelp(writer); writer.WriteLine(""); WriteObservedInputHelp(writer); writer.WriteLine(""); WriteProcessDetouringHelp(writer); writer.WriteLine(""); WriteReportedProcessesHelp(writer); writer.WriteLine(""); WritePipExecutionPerformanceAnalyzerHelp(writer); writer.WriteLine(""); WriteObservedInputSummaryHelp(writer); writer.WriteLine(""); WriteObservedAccessHelp(writer); writer.WriteLine(""); WriteToolEnumerationHelp(writer); writer.WriteLine(""); WriteCriticalPathAnalyzerHelp(writer); writer.WriteLine(""); WriteDumpPipAnalyzerHelp(writer); writer.WriteLine(""); WriteDumpPipLiteAnalyzerHelp(writer); writer.WriteLine(""); WriteDumpStringTableAnalyzerHelp(writer); writer.WriteLine(""); WriteProcessRunScriptAnalyzerHelp(writer); writer.WriteLine(""); WriteAllowlistAnalyzerHelp(writer); writer.WriteLine(""); WriteSummaryAnalyzerHelp(writer); writer.WriteLine(""); WriteBuildStatusHelp(writer); writer.WriteLine(""); WriteWinIdeDependencyAnalyzeHelp(writer); writer.WriteLine(""); WritePerfSummaryAnalyzerHelp(writer); writer.WriteLine(""); WriteEventStatsHelp(writer); writer.WriteLine(""); WriteIncrementalSchedulingStateAnalyzerHelp(writer); writer.WriteLine(""); WriteFileChangeTrackerAnalyzerHelp(writer); writer.WriteLine(""); WriteInputTrackerAnalyzerHelp(writer); writer.WriteLine(""); WriteFingerprintStoreAnalyzerHelp(writer); writer.WriteLine(""); WritePipFingerprintAnalyzerHelp(writer); writer.WriteLine(""); WriteCacheMissHelp(writer); writer.WriteLine(""); WriteCacheDumpHelp(writer); writer.WriteLine(""); WriteBuildSimulatorHelp(writer); #if FEATURE_VSTS_ARTIFACTSERVICES writer.WriteLine(""); WriteCacheHitPredictorHelp(writer); #endif writer.WriteLine(""); WriteDependencyAnalyzerHelp(writer); writer.WriteLine(""); WriteGraphDiffAnalyzerHelp(writer); writer.WriteLine(""); WriteDumpMountsAnalyzerHelp(writer); writer.WriteLine(""); WritePipFilterHelp(writer); writer.WriteLine(""); WriteFailedPipsDumpAnalyzerHelp(writer); writer.WriteLine(""); WriteCosineDumpPipHelp(writer); writer.WriteLine(""); WriteCopyFilesAnalyzerHelp(writer); writer.WriteLine(""); WriteJavaScriptDependencyFixerHelp(writer); writer.WriteLine(""); WriteFileConsumptionAnalyzerHelp(writer); } public void LogEventSummary() { Tracing.Logger.Log.ExecutionAnalyzerEventCount(LoggingContext, TrackingEventListener.ToEventCountDictionary()); } public long ParseSemistableHash(Option opt) { var adjustedOption = new Option() { Name = opt.Name, Value = opt.Value.ToUpper().Replace(Pip.SemiStableHashPrefix.ToUpper(), "") }; if (!Int64.TryParse(ParseStringOption(adjustedOption), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out long sshValue) || sshValue == 0) { throw Error("Invalid pip: {0}. Id must be a semistable hash that starts with Pip i.e.: PipC623BCE303738C69", opt.Value); } return sshValue; } } /// <summary> /// <see cref="HelpWriter"/> for analyzers. /// </summary> public static class HelpWriterExtensions { /// <summary> /// Writes the mode flag help for each analyzer. /// </summary> public static void WriteModeOption(this HelpWriter writer, string modeName, string description, HelpLevel level = HelpLevel.Standard) { writer.WriteOption("mode", string.Format("\"{0}\". {1}", modeName, description), level: level, shortName: "m"); } } }
42.090014
424
0.547083
[ "MIT" ]
BearerPipelineTest/BuildXL
Public/Src/Tools/Execution.Analyzer/Args.cs
29,926
C#
using System; using System.Collections; using System.Collections.Generic; using Jyx2; using UnityEngine; using XNode; [CreateNodeMenu("流程控制/休息")] [NodeWidth(150)] public class Jyx2RestNode : Jyx2SimpleNode { private void Reset() { name = "休息"; } protected override void DoExecute() { Jyx2LuaBridge.Rest(); } }
14.869565
42
0.687135
[ "MIT" ]
Alinccc/jynew
jyx2/Assets/Scripts/EventsGraph/Nodes/Jyx2RestNode.cs
358
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.AspNet.Builder; using Microsoft.AspNet.Mvc; using Microsoft.Framework.DependencyInjection; namespace CompositeViewEngineWebSite { public class Startup { // Set up application services public void ConfigureServices(IServiceCollection services) { // Add a view engine as the first one in the list. services.AddMvc() .ConfigureMvc(options => { options.ViewEngines.Insert(0, typeof(TestViewEngine)); }); } public void Configure(IApplicationBuilder app) { app.UseCultureReplacer(); // Add MVC to the request pipeline app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } } }
30.081081
111
0.576819
[ "Apache-2.0" ]
walkeeperY/ManagementSystem
test/WebSites/CompositeViewEngineWebSite/Startup.cs
1,115
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace System.Linq { public static partial class AsyncEnumerable { public static Task<int> Sum(this IAsyncEnumerable<int> source, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Aggregate(0, (x, y) => x + y, cancellationToken); } public static Task<long> Sum(this IAsyncEnumerable<long> source, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Aggregate(0L, (x, y) => x + y, cancellationToken); } public static Task<double> Sum(this IAsyncEnumerable<double> source, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Aggregate(0.0, (x, y) => x + y, cancellationToken); } public static Task<float> Sum(this IAsyncEnumerable<float> source, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Aggregate(0f, (x, y) => x + y, cancellationToken); } public static Task<decimal> Sum(this IAsyncEnumerable<decimal> source, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Aggregate(0m, (x, y) => x + y, cancellationToken); } public static Task<int?> Sum(this IAsyncEnumerable<int?> source, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Aggregate((int?)0, (x, y) => x + y.GetValueOrDefault(), cancellationToken); } public static Task<long?> Sum(this IAsyncEnumerable<long?> source, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Aggregate((long?)0, (x, y) => x + y.GetValueOrDefault(), cancellationToken); } public static Task<double?> Sum(this IAsyncEnumerable<double?> source, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Aggregate((double?)0, (x, y) => x + y.GetValueOrDefault(), cancellationToken); } public static Task<float?> Sum(this IAsyncEnumerable<float?> source, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Aggregate((float?)0, (x, y) => x + y.GetValueOrDefault(), cancellationToken); } public static Task<decimal?> Sum(this IAsyncEnumerable<decimal?> source, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Aggregate((decimal?)0, (x, y) => x + y.GetValueOrDefault(), cancellationToken); } public static Task<int> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, int> selector, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return source.Select(selector) .Sum(cancellationToken); } public static Task<long> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, long> selector, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return source.Select(selector) .Sum(cancellationToken); } public static Task<double> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, double> selector, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return source.Select(selector) .Sum(cancellationToken); } public static Task<float> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, float> selector, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return source.Select(selector) .Sum(cancellationToken); } public static Task<decimal> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, decimal> selector, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return source.Select(selector) .Sum(cancellationToken); } public static Task<int?> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, int?> selector, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return source.Select(selector) .Sum(cancellationToken); } public static Task<long?> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, long?> selector, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return source.Select(selector) .Sum(cancellationToken); } public static Task<double?> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, double?> selector, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return source.Select(selector) .Sum(cancellationToken); } public static Task<int> Sum(this IAsyncEnumerable<int> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return Sum(source, CancellationToken.None); } public static Task<long> Sum(this IAsyncEnumerable<long> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return Sum(source, CancellationToken.None); } public static Task<double> Sum(this IAsyncEnumerable<double> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return Sum(source, CancellationToken.None); } public static Task<float> Sum(this IAsyncEnumerable<float> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return Sum(source, CancellationToken.None); } public static Task<decimal> Sum(this IAsyncEnumerable<decimal> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return Sum(source, CancellationToken.None); } public static Task<int?> Sum(this IAsyncEnumerable<int?> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return Sum(source, CancellationToken.None); } public static Task<long?> Sum(this IAsyncEnumerable<long?> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return Sum(source, CancellationToken.None); } public static Task<double?> Sum(this IAsyncEnumerable<double?> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return Sum(source, CancellationToken.None); } public static Task<float?> Sum(this IAsyncEnumerable<float?> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return Sum(source, CancellationToken.None); } public static Task<decimal?> Sum(this IAsyncEnumerable<decimal?> source) { if (source == null) throw new ArgumentNullException(nameof(source)); return Sum(source, CancellationToken.None); } public static Task<int> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, int> selector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return Sum(source, selector, CancellationToken.None); } public static Task<long> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, long> selector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return Sum(source, selector, CancellationToken.None); } public static Task<double> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, double> selector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return Sum(source, selector, CancellationToken.None); } public static Task<float> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, float> selector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return Sum(source, selector, CancellationToken.None); } public static Task<decimal> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, decimal> selector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return Sum(source, selector, CancellationToken.None); } public static Task<int?> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, int?> selector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return Sum(source, selector, CancellationToken.None); } public static Task<long?> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, long?> selector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return Sum(source, selector, CancellationToken.None); } public static Task<double?> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, double?> selector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return Sum(source, selector, CancellationToken.None); } public static Task<float?> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, float?> selector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return Sum(source, selector, CancellationToken.None); } public static Task<decimal?> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, decimal?> selector) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return Sum(source, selector, CancellationToken.None); } public static Task<float?> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, float?> selector, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return source.Select(selector) .Sum(cancellationToken); } public static Task<decimal?> Sum<TSource>(this IAsyncEnumerable<TSource> source, Func<TSource, decimal?> selector, CancellationToken cancellationToken) { if (source == null) throw new ArgumentNullException(nameof(source)); if (selector == null) throw new ArgumentNullException(nameof(selector)); return source.Select(selector) .Sum(cancellationToken); } } }
38.439276
159
0.599825
[ "Apache-2.0" ]
LeeCampbell/Rx.NET
Ix.NET/Source/System.Interactive.Async/Sum.cs
14,878
C#
namespace snake_10.Model { /// <summary> /// ez jelzi a kígyó fejének irányát /// </summary> enum SnakeHeadDirerctionEnum { Up, Down, Left, Right, InPlace } }
18.090909
40
0.562814
[ "Unlicense" ]
akoskiss26/snake_10
snake_10/snake_10/Model/SnakeHeadDirectionEnum.cs
206
C#
// This file is generated. using System; using System.Diagnostics; namespace Vulkan { [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkInstance : IEquatable<VkInstance> { public readonly IntPtr Handle; public VkInstance(IntPtr existingHandle) { Handle = existingHandle; } public static VkInstance Null => new VkInstance(IntPtr.Zero); public static implicit operator VkInstance(IntPtr handle) => new VkInstance(handle); public static bool operator ==(VkInstance left, VkInstance right) => left.Handle == right.Handle; public static bool operator !=(VkInstance left, VkInstance right) => left.Handle != right.Handle; public static bool operator ==(VkInstance left, IntPtr right) => left.Handle == right; public static bool operator !=(VkInstance left, IntPtr right) => left.Handle != right; public bool Equals(VkInstance h) => Handle == h.Handle; public override bool Equals(object o) => o is VkInstance h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkInstance [0x{0}]", Handle.ToString("X")); } ///<summary>A dispatchable handle owned by a VkInstance.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkPhysicalDevice : IEquatable<VkPhysicalDevice> { public readonly IntPtr Handle; public VkPhysicalDevice(IntPtr existingHandle) { Handle = existingHandle; } public static VkPhysicalDevice Null => new VkPhysicalDevice(IntPtr.Zero); public static implicit operator VkPhysicalDevice(IntPtr handle) => new VkPhysicalDevice(handle); public static bool operator ==(VkPhysicalDevice left, VkPhysicalDevice right) => left.Handle == right.Handle; public static bool operator !=(VkPhysicalDevice left, VkPhysicalDevice right) => left.Handle != right.Handle; public static bool operator ==(VkPhysicalDevice left, IntPtr right) => left.Handle == right; public static bool operator !=(VkPhysicalDevice left, IntPtr right) => left.Handle != right; public bool Equals(VkPhysicalDevice h) => Handle == h.Handle; public override bool Equals(object o) => o is VkPhysicalDevice h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkPhysicalDevice [0x{0}]", Handle.ToString("X")); } ///<summary>A dispatchable handle owned by a VkPhysicalDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkDevice : IEquatable<VkDevice> { public readonly IntPtr Handle; public VkDevice(IntPtr existingHandle) { Handle = existingHandle; } public static VkDevice Null => new VkDevice(IntPtr.Zero); public static implicit operator VkDevice(IntPtr handle) => new VkDevice(handle); public static bool operator ==(VkDevice left, VkDevice right) => left.Handle == right.Handle; public static bool operator !=(VkDevice left, VkDevice right) => left.Handle != right.Handle; public static bool operator ==(VkDevice left, IntPtr right) => left.Handle == right; public static bool operator !=(VkDevice left, IntPtr right) => left.Handle != right; public bool Equals(VkDevice h) => Handle == h.Handle; public override bool Equals(object o) => o is VkDevice h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkDevice [0x{0}]", Handle.ToString("X")); } ///<summary>A dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkQueue : IEquatable<VkQueue> { public readonly IntPtr Handle; public VkQueue(IntPtr existingHandle) { Handle = existingHandle; } public static VkQueue Null => new VkQueue(IntPtr.Zero); public static implicit operator VkQueue(IntPtr handle) => new VkQueue(handle); public static bool operator ==(VkQueue left, VkQueue right) => left.Handle == right.Handle; public static bool operator !=(VkQueue left, VkQueue right) => left.Handle != right.Handle; public static bool operator ==(VkQueue left, IntPtr right) => left.Handle == right; public static bool operator !=(VkQueue left, IntPtr right) => left.Handle != right; public bool Equals(VkQueue h) => Handle == h.Handle; public override bool Equals(object o) => o is VkQueue h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkQueue [0x{0}]", Handle.ToString("X")); } ///<summary>A dispatchable handle owned by a VkCommandPool.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkCommandBuffer : IEquatable<VkCommandBuffer> { public readonly IntPtr Handle; public VkCommandBuffer(IntPtr existingHandle) { Handle = existingHandle; } public static VkCommandBuffer Null => new VkCommandBuffer(IntPtr.Zero); public static implicit operator VkCommandBuffer(IntPtr handle) => new VkCommandBuffer(handle); public static bool operator ==(VkCommandBuffer left, VkCommandBuffer right) => left.Handle == right.Handle; public static bool operator !=(VkCommandBuffer left, VkCommandBuffer right) => left.Handle != right.Handle; public static bool operator ==(VkCommandBuffer left, IntPtr right) => left.Handle == right; public static bool operator !=(VkCommandBuffer left, IntPtr right) => left.Handle != right; public bool Equals(VkCommandBuffer h) => Handle == h.Handle; public override bool Equals(object o) => o is VkCommandBuffer h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkCommandBuffer [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkDeviceMemory : IEquatable<VkDeviceMemory> { public readonly ulong Handle; public VkDeviceMemory(ulong existingHandle) { Handle = existingHandle; } public static VkDeviceMemory Null => new VkDeviceMemory(0); public static implicit operator VkDeviceMemory(ulong handle) => new VkDeviceMemory(handle); public static bool operator ==(VkDeviceMemory left, VkDeviceMemory right) => left.Handle == right.Handle; public static bool operator !=(VkDeviceMemory left, VkDeviceMemory right) => left.Handle != right.Handle; public static bool operator ==(VkDeviceMemory left, ulong right) => left.Handle == right; public static bool operator !=(VkDeviceMemory left, ulong right) => left.Handle != right; public bool Equals(VkDeviceMemory h) => Handle == h.Handle; public override bool Equals(object o) => o is VkDeviceMemory h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkDeviceMemory [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkCommandPool : IEquatable<VkCommandPool> { public readonly ulong Handle; public VkCommandPool(ulong existingHandle) { Handle = existingHandle; } public static VkCommandPool Null => new VkCommandPool(0); public static implicit operator VkCommandPool(ulong handle) => new VkCommandPool(handle); public static bool operator ==(VkCommandPool left, VkCommandPool right) => left.Handle == right.Handle; public static bool operator !=(VkCommandPool left, VkCommandPool right) => left.Handle != right.Handle; public static bool operator ==(VkCommandPool left, ulong right) => left.Handle == right; public static bool operator !=(VkCommandPool left, ulong right) => left.Handle != right; public bool Equals(VkCommandPool h) => Handle == h.Handle; public override bool Equals(object o) => o is VkCommandPool h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkCommandPool [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkBuffer : IEquatable<VkBuffer> { public readonly ulong Handle; public VkBuffer(ulong existingHandle) { Handle = existingHandle; } public static VkBuffer Null => new VkBuffer(0); public static implicit operator VkBuffer(ulong handle) => new VkBuffer(handle); public static bool operator ==(VkBuffer left, VkBuffer right) => left.Handle == right.Handle; public static bool operator !=(VkBuffer left, VkBuffer right) => left.Handle != right.Handle; public static bool operator ==(VkBuffer left, ulong right) => left.Handle == right; public static bool operator !=(VkBuffer left, ulong right) => left.Handle != right; public bool Equals(VkBuffer h) => Handle == h.Handle; public override bool Equals(object o) => o is VkBuffer h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkBuffer [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkBufferView : IEquatable<VkBufferView> { public readonly ulong Handle; public VkBufferView(ulong existingHandle) { Handle = existingHandle; } public static VkBufferView Null => new VkBufferView(0); public static implicit operator VkBufferView(ulong handle) => new VkBufferView(handle); public static bool operator ==(VkBufferView left, VkBufferView right) => left.Handle == right.Handle; public static bool operator !=(VkBufferView left, VkBufferView right) => left.Handle != right.Handle; public static bool operator ==(VkBufferView left, ulong right) => left.Handle == right; public static bool operator !=(VkBufferView left, ulong right) => left.Handle != right; public bool Equals(VkBufferView h) => Handle == h.Handle; public override bool Equals(object o) => o is VkBufferView h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkBufferView [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkImage : IEquatable<VkImage> { public readonly ulong Handle; public VkImage(ulong existingHandle) { Handle = existingHandle; } public static VkImage Null => new VkImage(0); public static implicit operator VkImage(ulong handle) => new VkImage(handle); public static bool operator ==(VkImage left, VkImage right) => left.Handle == right.Handle; public static bool operator !=(VkImage left, VkImage right) => left.Handle != right.Handle; public static bool operator ==(VkImage left, ulong right) => left.Handle == right; public static bool operator !=(VkImage left, ulong right) => left.Handle != right; public bool Equals(VkImage h) => Handle == h.Handle; public override bool Equals(object o) => o is VkImage h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkImage [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkImageView : IEquatable<VkImageView> { public readonly ulong Handle; public VkImageView(ulong existingHandle) { Handle = existingHandle; } public static VkImageView Null => new VkImageView(0); public static implicit operator VkImageView(ulong handle) => new VkImageView(handle); public static bool operator ==(VkImageView left, VkImageView right) => left.Handle == right.Handle; public static bool operator !=(VkImageView left, VkImageView right) => left.Handle != right.Handle; public static bool operator ==(VkImageView left, ulong right) => left.Handle == right; public static bool operator !=(VkImageView left, ulong right) => left.Handle != right; public bool Equals(VkImageView h) => Handle == h.Handle; public override bool Equals(object o) => o is VkImageView h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkImageView [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkShaderModule : IEquatable<VkShaderModule> { public readonly ulong Handle; public VkShaderModule(ulong existingHandle) { Handle = existingHandle; } public static VkShaderModule Null => new VkShaderModule(0); public static implicit operator VkShaderModule(ulong handle) => new VkShaderModule(handle); public static bool operator ==(VkShaderModule left, VkShaderModule right) => left.Handle == right.Handle; public static bool operator !=(VkShaderModule left, VkShaderModule right) => left.Handle != right.Handle; public static bool operator ==(VkShaderModule left, ulong right) => left.Handle == right; public static bool operator !=(VkShaderModule left, ulong right) => left.Handle != right; public bool Equals(VkShaderModule h) => Handle == h.Handle; public override bool Equals(object o) => o is VkShaderModule h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkShaderModule [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkPipeline : IEquatable<VkPipeline> { public readonly ulong Handle; public VkPipeline(ulong existingHandle) { Handle = existingHandle; } public static VkPipeline Null => new VkPipeline(0); public static implicit operator VkPipeline(ulong handle) => new VkPipeline(handle); public static bool operator ==(VkPipeline left, VkPipeline right) => left.Handle == right.Handle; public static bool operator !=(VkPipeline left, VkPipeline right) => left.Handle != right.Handle; public static bool operator ==(VkPipeline left, ulong right) => left.Handle == right; public static bool operator !=(VkPipeline left, ulong right) => left.Handle != right; public bool Equals(VkPipeline h) => Handle == h.Handle; public override bool Equals(object o) => o is VkPipeline h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkPipeline [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkPipelineLayout : IEquatable<VkPipelineLayout> { public readonly ulong Handle; public VkPipelineLayout(ulong existingHandle) { Handle = existingHandle; } public static VkPipelineLayout Null => new VkPipelineLayout(0); public static implicit operator VkPipelineLayout(ulong handle) => new VkPipelineLayout(handle); public static bool operator ==(VkPipelineLayout left, VkPipelineLayout right) => left.Handle == right.Handle; public static bool operator !=(VkPipelineLayout left, VkPipelineLayout right) => left.Handle != right.Handle; public static bool operator ==(VkPipelineLayout left, ulong right) => left.Handle == right; public static bool operator !=(VkPipelineLayout left, ulong right) => left.Handle != right; public bool Equals(VkPipelineLayout h) => Handle == h.Handle; public override bool Equals(object o) => o is VkPipelineLayout h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkPipelineLayout [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkSampler : IEquatable<VkSampler> { public readonly ulong Handle; public VkSampler(ulong existingHandle) { Handle = existingHandle; } public static VkSampler Null => new VkSampler(0); public static implicit operator VkSampler(ulong handle) => new VkSampler(handle); public static bool operator ==(VkSampler left, VkSampler right) => left.Handle == right.Handle; public static bool operator !=(VkSampler left, VkSampler right) => left.Handle != right.Handle; public static bool operator ==(VkSampler left, ulong right) => left.Handle == right; public static bool operator !=(VkSampler left, ulong right) => left.Handle != right; public bool Equals(VkSampler h) => Handle == h.Handle; public override bool Equals(object o) => o is VkSampler h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkSampler [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDescriptorPool.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkDescriptorSet : IEquatable<VkDescriptorSet> { public readonly ulong Handle; public VkDescriptorSet(ulong existingHandle) { Handle = existingHandle; } public static VkDescriptorSet Null => new VkDescriptorSet(0); public static implicit operator VkDescriptorSet(ulong handle) => new VkDescriptorSet(handle); public static bool operator ==(VkDescriptorSet left, VkDescriptorSet right) => left.Handle == right.Handle; public static bool operator !=(VkDescriptorSet left, VkDescriptorSet right) => left.Handle != right.Handle; public static bool operator ==(VkDescriptorSet left, ulong right) => left.Handle == right; public static bool operator !=(VkDescriptorSet left, ulong right) => left.Handle != right; public bool Equals(VkDescriptorSet h) => Handle == h.Handle; public override bool Equals(object o) => o is VkDescriptorSet h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkDescriptorSet [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkDescriptorSetLayout : IEquatable<VkDescriptorSetLayout> { public readonly ulong Handle; public VkDescriptorSetLayout(ulong existingHandle) { Handle = existingHandle; } public static VkDescriptorSetLayout Null => new VkDescriptorSetLayout(0); public static implicit operator VkDescriptorSetLayout(ulong handle) => new VkDescriptorSetLayout(handle); public static bool operator ==(VkDescriptorSetLayout left, VkDescriptorSetLayout right) => left.Handle == right.Handle; public static bool operator !=(VkDescriptorSetLayout left, VkDescriptorSetLayout right) => left.Handle != right.Handle; public static bool operator ==(VkDescriptorSetLayout left, ulong right) => left.Handle == right; public static bool operator !=(VkDescriptorSetLayout left, ulong right) => left.Handle != right; public bool Equals(VkDescriptorSetLayout h) => Handle == h.Handle; public override bool Equals(object o) => o is VkDescriptorSetLayout h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkDescriptorSetLayout [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkDescriptorPool : IEquatable<VkDescriptorPool> { public readonly ulong Handle; public VkDescriptorPool(ulong existingHandle) { Handle = existingHandle; } public static VkDescriptorPool Null => new VkDescriptorPool(0); public static implicit operator VkDescriptorPool(ulong handle) => new VkDescriptorPool(handle); public static bool operator ==(VkDescriptorPool left, VkDescriptorPool right) => left.Handle == right.Handle; public static bool operator !=(VkDescriptorPool left, VkDescriptorPool right) => left.Handle != right.Handle; public static bool operator ==(VkDescriptorPool left, ulong right) => left.Handle == right; public static bool operator !=(VkDescriptorPool left, ulong right) => left.Handle != right; public bool Equals(VkDescriptorPool h) => Handle == h.Handle; public override bool Equals(object o) => o is VkDescriptorPool h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkDescriptorPool [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkFence : IEquatable<VkFence> { public readonly ulong Handle; public VkFence(ulong existingHandle) { Handle = existingHandle; } public static VkFence Null => new VkFence(0); public static implicit operator VkFence(ulong handle) => new VkFence(handle); public static bool operator ==(VkFence left, VkFence right) => left.Handle == right.Handle; public static bool operator !=(VkFence left, VkFence right) => left.Handle != right.Handle; public static bool operator ==(VkFence left, ulong right) => left.Handle == right; public static bool operator !=(VkFence left, ulong right) => left.Handle != right; public bool Equals(VkFence h) => Handle == h.Handle; public override bool Equals(object o) => o is VkFence h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkFence [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkSemaphore : IEquatable<VkSemaphore> { public readonly ulong Handle; public VkSemaphore(ulong existingHandle) { Handle = existingHandle; } public static VkSemaphore Null => new VkSemaphore(0); public static implicit operator VkSemaphore(ulong handle) => new VkSemaphore(handle); public static bool operator ==(VkSemaphore left, VkSemaphore right) => left.Handle == right.Handle; public static bool operator !=(VkSemaphore left, VkSemaphore right) => left.Handle != right.Handle; public static bool operator ==(VkSemaphore left, ulong right) => left.Handle == right; public static bool operator !=(VkSemaphore left, ulong right) => left.Handle != right; public bool Equals(VkSemaphore h) => Handle == h.Handle; public override bool Equals(object o) => o is VkSemaphore h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkSemaphore [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkEvent : IEquatable<VkEvent> { public readonly ulong Handle; public VkEvent(ulong existingHandle) { Handle = existingHandle; } public static VkEvent Null => new VkEvent(0); public static implicit operator VkEvent(ulong handle) => new VkEvent(handle); public static bool operator ==(VkEvent left, VkEvent right) => left.Handle == right.Handle; public static bool operator !=(VkEvent left, VkEvent right) => left.Handle != right.Handle; public static bool operator ==(VkEvent left, ulong right) => left.Handle == right; public static bool operator !=(VkEvent left, ulong right) => left.Handle != right; public bool Equals(VkEvent h) => Handle == h.Handle; public override bool Equals(object o) => o is VkEvent h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkEvent [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkQueryPool : IEquatable<VkQueryPool> { public readonly ulong Handle; public VkQueryPool(ulong existingHandle) { Handle = existingHandle; } public static VkQueryPool Null => new VkQueryPool(0); public static implicit operator VkQueryPool(ulong handle) => new VkQueryPool(handle); public static bool operator ==(VkQueryPool left, VkQueryPool right) => left.Handle == right.Handle; public static bool operator !=(VkQueryPool left, VkQueryPool right) => left.Handle != right.Handle; public static bool operator ==(VkQueryPool left, ulong right) => left.Handle == right; public static bool operator !=(VkQueryPool left, ulong right) => left.Handle != right; public bool Equals(VkQueryPool h) => Handle == h.Handle; public override bool Equals(object o) => o is VkQueryPool h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkQueryPool [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkFramebuffer : IEquatable<VkFramebuffer> { public readonly ulong Handle; public VkFramebuffer(ulong existingHandle) { Handle = existingHandle; } public static VkFramebuffer Null => new VkFramebuffer(0); public static implicit operator VkFramebuffer(ulong handle) => new VkFramebuffer(handle); public static bool operator ==(VkFramebuffer left, VkFramebuffer right) => left.Handle == right.Handle; public static bool operator !=(VkFramebuffer left, VkFramebuffer right) => left.Handle != right.Handle; public static bool operator ==(VkFramebuffer left, ulong right) => left.Handle == right; public static bool operator !=(VkFramebuffer left, ulong right) => left.Handle != right; public bool Equals(VkFramebuffer h) => Handle == h.Handle; public override bool Equals(object o) => o is VkFramebuffer h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkFramebuffer [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkRenderPass : IEquatable<VkRenderPass> { public readonly ulong Handle; public VkRenderPass(ulong existingHandle) { Handle = existingHandle; } public static VkRenderPass Null => new VkRenderPass(0); public static implicit operator VkRenderPass(ulong handle) => new VkRenderPass(handle); public static bool operator ==(VkRenderPass left, VkRenderPass right) => left.Handle == right.Handle; public static bool operator !=(VkRenderPass left, VkRenderPass right) => left.Handle != right.Handle; public static bool operator ==(VkRenderPass left, ulong right) => left.Handle == right; public static bool operator !=(VkRenderPass left, ulong right) => left.Handle != right; public bool Equals(VkRenderPass h) => Handle == h.Handle; public override bool Equals(object o) => o is VkRenderPass h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkRenderPass [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkPipelineCache : IEquatable<VkPipelineCache> { public readonly ulong Handle; public VkPipelineCache(ulong existingHandle) { Handle = existingHandle; } public static VkPipelineCache Null => new VkPipelineCache(0); public static implicit operator VkPipelineCache(ulong handle) => new VkPipelineCache(handle); public static bool operator ==(VkPipelineCache left, VkPipelineCache right) => left.Handle == right.Handle; public static bool operator !=(VkPipelineCache left, VkPipelineCache right) => left.Handle != right.Handle; public static bool operator ==(VkPipelineCache left, ulong right) => left.Handle == right; public static bool operator !=(VkPipelineCache left, ulong right) => left.Handle != right; public bool Equals(VkPipelineCache h) => Handle == h.Handle; public override bool Equals(object o) => o is VkPipelineCache h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkPipelineCache [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkObjectTableNVX : IEquatable<VkObjectTableNVX> { public readonly ulong Handle; public VkObjectTableNVX(ulong existingHandle) { Handle = existingHandle; } public static VkObjectTableNVX Null => new VkObjectTableNVX(0); public static implicit operator VkObjectTableNVX(ulong handle) => new VkObjectTableNVX(handle); public static bool operator ==(VkObjectTableNVX left, VkObjectTableNVX right) => left.Handle == right.Handle; public static bool operator !=(VkObjectTableNVX left, VkObjectTableNVX right) => left.Handle != right.Handle; public static bool operator ==(VkObjectTableNVX left, ulong right) => left.Handle == right; public static bool operator !=(VkObjectTableNVX left, ulong right) => left.Handle != right; public bool Equals(VkObjectTableNVX h) => Handle == h.Handle; public override bool Equals(object o) => o is VkObjectTableNVX h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkObjectTableNVX [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkIndirectCommandsLayoutNVX : IEquatable<VkIndirectCommandsLayoutNVX> { public readonly ulong Handle; public VkIndirectCommandsLayoutNVX(ulong existingHandle) { Handle = existingHandle; } public static VkIndirectCommandsLayoutNVX Null => new VkIndirectCommandsLayoutNVX(0); public static implicit operator VkIndirectCommandsLayoutNVX(ulong handle) => new VkIndirectCommandsLayoutNVX(handle); public static bool operator ==(VkIndirectCommandsLayoutNVX left, VkIndirectCommandsLayoutNVX right) => left.Handle == right.Handle; public static bool operator !=(VkIndirectCommandsLayoutNVX left, VkIndirectCommandsLayoutNVX right) => left.Handle != right.Handle; public static bool operator ==(VkIndirectCommandsLayoutNVX left, ulong right) => left.Handle == right; public static bool operator !=(VkIndirectCommandsLayoutNVX left, ulong right) => left.Handle != right; public bool Equals(VkIndirectCommandsLayoutNVX h) => Handle == h.Handle; public override bool Equals(object o) => o is VkIndirectCommandsLayoutNVX h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkIndirectCommandsLayoutNVX [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkDescriptorUpdateTemplateKHR : IEquatable<VkDescriptorUpdateTemplateKHR> { public readonly ulong Handle; public VkDescriptorUpdateTemplateKHR(ulong existingHandle) { Handle = existingHandle; } public static VkDescriptorUpdateTemplateKHR Null => new VkDescriptorUpdateTemplateKHR(0); public static implicit operator VkDescriptorUpdateTemplateKHR(ulong handle) => new VkDescriptorUpdateTemplateKHR(handle); public static bool operator ==(VkDescriptorUpdateTemplateKHR left, VkDescriptorUpdateTemplateKHR right) => left.Handle == right.Handle; public static bool operator !=(VkDescriptorUpdateTemplateKHR left, VkDescriptorUpdateTemplateKHR right) => left.Handle != right.Handle; public static bool operator ==(VkDescriptorUpdateTemplateKHR left, ulong right) => left.Handle == right; public static bool operator !=(VkDescriptorUpdateTemplateKHR left, ulong right) => left.Handle != right; public bool Equals(VkDescriptorUpdateTemplateKHR h) => Handle == h.Handle; public override bool Equals(object o) => o is VkDescriptorUpdateTemplateKHR h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkDescriptorUpdateTemplateKHR [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkSamplerYcbcrConversionKHR : IEquatable<VkSamplerYcbcrConversionKHR> { public readonly ulong Handle; public VkSamplerYcbcrConversionKHR(ulong existingHandle) { Handle = existingHandle; } public static VkSamplerYcbcrConversionKHR Null => new VkSamplerYcbcrConversionKHR(0); public static implicit operator VkSamplerYcbcrConversionKHR(ulong handle) => new VkSamplerYcbcrConversionKHR(handle); public static bool operator ==(VkSamplerYcbcrConversionKHR left, VkSamplerYcbcrConversionKHR right) => left.Handle == right.Handle; public static bool operator !=(VkSamplerYcbcrConversionKHR left, VkSamplerYcbcrConversionKHR right) => left.Handle != right.Handle; public static bool operator ==(VkSamplerYcbcrConversionKHR left, ulong right) => left.Handle == right; public static bool operator !=(VkSamplerYcbcrConversionKHR left, ulong right) => left.Handle != right; public bool Equals(VkSamplerYcbcrConversionKHR h) => Handle == h.Handle; public override bool Equals(object o) => o is VkSamplerYcbcrConversionKHR h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkSamplerYcbcrConversionKHR [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkDevice.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkValidationCacheEXT : IEquatable<VkValidationCacheEXT> { public readonly ulong Handle; public VkValidationCacheEXT(ulong existingHandle) { Handle = existingHandle; } public static VkValidationCacheEXT Null => new VkValidationCacheEXT(0); public static implicit operator VkValidationCacheEXT(ulong handle) => new VkValidationCacheEXT(handle); public static bool operator ==(VkValidationCacheEXT left, VkValidationCacheEXT right) => left.Handle == right.Handle; public static bool operator !=(VkValidationCacheEXT left, VkValidationCacheEXT right) => left.Handle != right.Handle; public static bool operator ==(VkValidationCacheEXT left, ulong right) => left.Handle == right; public static bool operator !=(VkValidationCacheEXT left, ulong right) => left.Handle != right; public bool Equals(VkValidationCacheEXT h) => Handle == h.Handle; public override bool Equals(object o) => o is VkValidationCacheEXT h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkValidationCacheEXT [0x{0}]", Handle.ToString("X")); } [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkDisplayKHR : IEquatable<VkDisplayKHR> { public readonly ulong Handle; public VkDisplayKHR(ulong existingHandle) { Handle = existingHandle; } public static VkDisplayKHR Null => new VkDisplayKHR(0); public static implicit operator VkDisplayKHR(ulong handle) => new VkDisplayKHR(handle); public static bool operator ==(VkDisplayKHR left, VkDisplayKHR right) => left.Handle == right.Handle; public static bool operator !=(VkDisplayKHR left, VkDisplayKHR right) => left.Handle != right.Handle; public static bool operator ==(VkDisplayKHR left, ulong right) => left.Handle == right; public static bool operator !=(VkDisplayKHR left, ulong right) => left.Handle != right; public bool Equals(VkDisplayKHR h) => Handle == h.Handle; public override bool Equals(object o) => o is VkDisplayKHR h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkDisplayKHR [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkPhysicalDevice,VkDisplayKHR.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkDisplayModeKHR : IEquatable<VkDisplayModeKHR> { public readonly ulong Handle; public VkDisplayModeKHR(ulong existingHandle) { Handle = existingHandle; } public static VkDisplayModeKHR Null => new VkDisplayModeKHR(0); public static implicit operator VkDisplayModeKHR(ulong handle) => new VkDisplayModeKHR(handle); public static bool operator ==(VkDisplayModeKHR left, VkDisplayModeKHR right) => left.Handle == right.Handle; public static bool operator !=(VkDisplayModeKHR left, VkDisplayModeKHR right) => left.Handle != right.Handle; public static bool operator ==(VkDisplayModeKHR left, ulong right) => left.Handle == right; public static bool operator !=(VkDisplayModeKHR left, ulong right) => left.Handle != right; public bool Equals(VkDisplayModeKHR h) => Handle == h.Handle; public override bool Equals(object o) => o is VkDisplayModeKHR h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkDisplayModeKHR [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkInstance.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkSurfaceKHR : IEquatable<VkSurfaceKHR> { public readonly ulong Handle; public VkSurfaceKHR(ulong existingHandle) { Handle = existingHandle; } public static VkSurfaceKHR Null => new VkSurfaceKHR(0); public static implicit operator VkSurfaceKHR(ulong handle) => new VkSurfaceKHR(handle); public static bool operator ==(VkSurfaceKHR left, VkSurfaceKHR right) => left.Handle == right.Handle; public static bool operator !=(VkSurfaceKHR left, VkSurfaceKHR right) => left.Handle != right.Handle; public static bool operator ==(VkSurfaceKHR left, ulong right) => left.Handle == right; public static bool operator !=(VkSurfaceKHR left, ulong right) => left.Handle != right; public bool Equals(VkSurfaceKHR h) => Handle == h.Handle; public override bool Equals(object o) => o is VkSurfaceKHR h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkSurfaceKHR [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkSurfaceKHR.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkSwapchainKHR : IEquatable<VkSwapchainKHR> { public readonly ulong Handle; public VkSwapchainKHR(ulong existingHandle) { Handle = existingHandle; } public static VkSwapchainKHR Null => new VkSwapchainKHR(0); public static implicit operator VkSwapchainKHR(ulong handle) => new VkSwapchainKHR(handle); public static bool operator ==(VkSwapchainKHR left, VkSwapchainKHR right) => left.Handle == right.Handle; public static bool operator !=(VkSwapchainKHR left, VkSwapchainKHR right) => left.Handle != right.Handle; public static bool operator ==(VkSwapchainKHR left, ulong right) => left.Handle == right; public static bool operator !=(VkSwapchainKHR left, ulong right) => left.Handle != right; public bool Equals(VkSwapchainKHR h) => Handle == h.Handle; public override bool Equals(object o) => o is VkSwapchainKHR h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkSwapchainKHR [0x{0}]", Handle.ToString("X")); } ///<summary>A non-dispatchable handle owned by a VkInstance.</summary> [DebuggerDisplay("{DebuggerDisplay,nq}")] public partial struct VkDebugReportCallbackEXT : IEquatable<VkDebugReportCallbackEXT> { public readonly ulong Handle; public VkDebugReportCallbackEXT(ulong existingHandle) { Handle = existingHandle; } public static VkDebugReportCallbackEXT Null => new VkDebugReportCallbackEXT(0); public static implicit operator VkDebugReportCallbackEXT(ulong handle) => new VkDebugReportCallbackEXT(handle); public static bool operator ==(VkDebugReportCallbackEXT left, VkDebugReportCallbackEXT right) => left.Handle == right.Handle; public static bool operator !=(VkDebugReportCallbackEXT left, VkDebugReportCallbackEXT right) => left.Handle != right.Handle; public static bool operator ==(VkDebugReportCallbackEXT left, ulong right) => left.Handle == right; public static bool operator !=(VkDebugReportCallbackEXT left, ulong right) => left.Handle != right; public bool Equals(VkDebugReportCallbackEXT h) => Handle == h.Handle; public override bool Equals(object o) => o is VkDebugReportCallbackEXT h && Equals(h); public override int GetHashCode() => Handle.GetHashCode(); private string DebuggerDisplay => string.Format("VkDebugReportCallbackEXT [0x{0}]", Handle.ToString("X")); } }
68.339623
143
0.699245
[ "MIT" ]
NamelessHoodie/DSParamStudio
vk/src/vk/Generated/Handles.gen.cs
43,464
C#
using CommanderGQL.Models; using Microsoft.EntityFrameworkCore; namespace CommanderGQL.Data { public class AppDbContext: DbContext { public DbSet<Platform> Platforms { get; set; } public DbSet<Command> Commands { get; set; } public AppDbContext(DbContextOptions options): base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder){ modelBuilder .Entity<Platform>() .HasMany(p=> p.Commands) .WithOne(p => p.Platform!) .HasForeignKey(p => p.PlatformId); modelBuilder .Entity<Command>() .HasOne(c => c.Platform) .WithMany(c => c.Commands) .HasForeignKey(c => c.PlatformId); } } }
29.034483
75
0.546318
[ "MIT" ]
shashankvivek/dotnet-gql
CommanderGQL/Data/AppDbContext.cs
842
C#
using System; using System.Data; using JetBat.Client.Entities; using JetBat.Client.Metadata; using JetBat.Client.Metadata.Abstract; using JetBat.Client.Metadata.Definitions; using JetBat.Client.Metadata.Misc; using NUnit.Framework; namespace JetBat.Test.FunctionalTest { public class TwoGoodsInTwoIncomesTest : MealCalcFunctionalTest { private int incomeDocument; private int calcDayMenu; private int calcDayMealOne; private int calcDayMealTwo; private int calcDayMealThree; private int mealOneDishOne; private int mealOneDishTwo; private int mealOneDishThree; private int mealTwoDishOne; private int mealTwoDishTwo; private int mealTwoDishThree; private int mealThreeDishOne; private int mealThreeDishTwo; private int mealThreeDishThree; public TwoGoodsInTwoIncomesTest(IAccessAdapter adapter) : base(adapter) { } private void makeIncome() { var documentInstance = BusinessObjectHelper.CreateDocument(adapter, "MealCalc", "GoodIncomeDocument", delegate(ObjectInstance instance) { instance["SupplierID"] = supplier; instance["IncomeCalcDayID"] = calcDay; instance["DocumentDateTime"] = DateTime.Today; instance["InvoiceNumber"] = "123456789012345678901234567890"; }); incomeDocument = documentInstance.DocumentID; BusinessObjectHelper.CreatePlainObject(adapter, "MealCalc", "GoodIncomeDocumentDetail", delegate(ObjectInstance instance) { instance["DocumentVersionID"] = documentInstance.VersionID; instance["GoodID"] = goodOne; instance["GoodPackingUnitID"] = goodOneDefaultPackingUnit; instance["GoodCommodityName"] = "Торговое наименование первого товара"; instance["Price"] = (decimal)10; instance["Quantity"] = (decimal)2.25; instance["Comment"] = "Комментарий к товарной позиции"; instance["OrderNumber"] = DBNull.Value; }); BusinessObjectHelper.CreatePlainObject(adapter, "MealCalc", "GoodIncomeDocumentDetail", delegate(ObjectInstance instance) { instance["DocumentVersionID"] = documentInstance.VersionID; instance["GoodID"] = goodOne; instance["GoodPackingUnitID"] = goodOneDefaultPackingUnit; instance["GoodCommodityName"] = "Торговое наименование первого товара"; instance["Price"] = (decimal)10; instance["Quantity"] = (decimal)2.5; instance["Comment"] = "Комментарий к товарной позиции"; instance["OrderNumber"] = DBNull.Value; }); BusinessObjectHelper.CreatePlainObject(adapter, "MealCalc", "GoodIncomeDocumentDetail", delegate(ObjectInstance instance) { instance["DocumentVersionID"] = documentInstance.VersionID; instance["GoodID"] = goodTwo; instance["GoodPackingUnitID"] = goodTwoDefaultPackingUnit; instance["GoodCommodityName"] = "Торговое наименование второго товара"; instance["Price"] = (decimal)200; instance["Quantity"] = (decimal)45; instance["Comment"] = "Комментарий к товарной позиции"; instance["OrderNumber"] = DBNull.Value; }); documentInstance.UpdateVersion(); documentInstance.ConfirmEdit(); documentInstance.Commit(); } private void checkGoodBalance() { ObjectListViewDefinition storedQueryDefinition; DataTable result = adapter.ObjectFactory.LoadObjectListView("MealCalc", "GoodRemains", new AttributeValueSet(), out storedQueryDefinition); Assert.AreEqual(2, result.Rows.Count); Assert.AreEqual(5, storedQueryDefinition.Attributes.Count); Assert.AreEqual("Good One", result.Rows[0]["GoodName"]); Assert.AreEqual((decimal)4.5, result.Rows[0]["QuantityLeft"]); Assert.AreEqual((decimal)0, result.Rows[0]["QuantityReserved"]); Assert.AreEqual("Good Two", result.Rows[1]["GoodName"]); Assert.AreEqual((decimal)45, result.Rows[1]["QuantityLeft"]); Assert.AreEqual((decimal)0, result.Rows[1]["QuantityReserved"]); } private void checkGoodReserve() { ObjectListViewDefinition storedQueryDefinition; DataTable result = adapter.ObjectFactory.LoadObjectListView("MealCalc", "GoodRemains", new AttributeValueSet(), out storedQueryDefinition); Assert.AreEqual(2, result.Rows.Count); Assert.AreEqual(5, storedQueryDefinition.Attributes.Count); Assert.AreEqual("Good One", result.Rows[0]["GoodName"]); Assert.AreEqual((decimal)4.5, result.Rows[0]["QuantityLeft"]); Assert.AreEqual((decimal)4.5, result.Rows[0]["QuantityReserved"]); Assert.AreEqual("Good Two", result.Rows[1]["GoodName"]); Assert.AreEqual((decimal)45, result.Rows[1]["QuantityLeft"]); Assert.AreEqual((decimal)45, result.Rows[1]["QuantityReserved"]); } private void checkGoodWriteOff() { ObjectListViewDefinition storedQueryDefinition; DataTable result = adapter.ObjectFactory.LoadObjectListView("MealCalc", "GoodRemains", new AttributeValueSet(), out storedQueryDefinition); Assert.AreEqual(2, result.Rows.Count); Assert.AreEqual(5, storedQueryDefinition.Attributes.Count); Assert.AreEqual("Good One", result.Rows[0]["GoodName"]); Assert.AreEqual((decimal)0, result.Rows[0]["QuantityLeft"]); Assert.AreEqual((decimal)0, result.Rows[0]["QuantityReserved"]); Assert.AreEqual("Good Two", result.Rows[1]["GoodName"]); Assert.AreEqual((decimal)0, result.Rows[1]["QuantityLeft"]); Assert.AreEqual((decimal)0, result.Rows[1]["QuantityReserved"]); } private void checkZeroGoodBalance() { ObjectListViewDefinition storedQueryDefinition; DataTable result = adapter.ObjectFactory.LoadObjectListView("MealCalc", "GoodRemains", new AttributeValueSet(), out storedQueryDefinition); Assert.AreEqual(0, result.Rows.Count); Assert.AreEqual(5, storedQueryDefinition.Attributes.Count); } private void createCalcDayMenu() { #region CalcDayMenu (1) calcDayMenu = BusinessObjectHelper.CreatePlainObject(adapter, "MealCalc", "CalcDayMenu", delegate(ObjectInstance instance) { instance["CalcDayID"] = calcDay; instance["MenuID"] = menu; instance["Comment"] = "No comment"; }); #endregion #region Get CalcDayMeal ID's ObjectListViewDefinition storedQueryDefinition; var parameters = new AttributeValueSet { { "CalcDayMenuID", calcDayMenu } }; DataTable result = adapter.ObjectFactory.LoadObjectListView("MealCalc", "CalcDayMealList", parameters, out storedQueryDefinition); Assert.AreEqual(3, result.Rows.Count); calcDayMealOne = (int)result.Select("OrderIndex = 1")[0]["ID"]; calcDayMealTwo = (int)result.Select("OrderIndex = 2")[0]["ID"]; calcDayMealThree = (int)result.Select("OrderIndex = 3")[0]["ID"]; #endregion } private void addCalcDayMealDishes() { #region Dishes for calcDayMealOne mealOneDishOne = BusinessObjectHelper.CreatePlainObject(adapter, "MealCalc", "CalcDayMealDish", delegate(ObjectInstance instance) { instance["CalcDayMealID"] = calcDayMealOne; instance["DishID"] = dishOne; instance["PortionCount"] = 10; instance["Comment"] = "No comment"; }); mealOneDishTwo = BusinessObjectHelper.CreatePlainObject(adapter, "MealCalc", "CalcDayMealDish", delegate(ObjectInstance instance) { instance["CalcDayMealID"] = calcDayMealOne; instance["DishID"] = dishTwo; instance["PortionCount"] = 10; instance["Comment"] = "No comment"; }); mealOneDishThree = BusinessObjectHelper.CreatePlainObject(adapter, "MealCalc", "CalcDayMealDish", delegate(ObjectInstance instance) { instance["CalcDayMealID"] = calcDayMealOne; instance["DishID"] = dishThree; instance["PortionCount"] = 10; instance["Comment"] = "No comment"; }); #endregion #region Dishes for calcDayMealTwo mealTwoDishOne = BusinessObjectHelper.CreatePlainObject(adapter, "MealCalc", "CalcDayMealDish", delegate(ObjectInstance instance) { instance["CalcDayMealID"] = calcDayMealTwo; instance["DishID"] = dishOne; instance["PortionCount"] = 10; instance["Comment"] = "No comment"; }); mealTwoDishTwo = BusinessObjectHelper.CreatePlainObject(adapter, "MealCalc", "CalcDayMealDish", delegate(ObjectInstance instance) { instance["CalcDayMealID"] = calcDayMealTwo; instance["DishID"] = dishTwo; instance["PortionCount"] = 10; instance["Comment"] = "No comment"; }); mealTwoDishThree = BusinessObjectHelper.CreatePlainObject(adapter, "MealCalc", "CalcDayMealDish", delegate(ObjectInstance instance) { instance["CalcDayMealID"] = calcDayMealTwo; instance["DishID"] = dishThree; instance["PortionCount"] = 10; instance["Comment"] = "No comment"; }); #endregion #region Dishes for calcDayMealThree mealThreeDishOne = BusinessObjectHelper.CreatePlainObject(adapter, "MealCalc", "CalcDayMealDish", delegate(ObjectInstance instance) { instance["CalcDayMealID"] = calcDayMealThree; instance["DishID"] = dishOne; instance["PortionCount"] = 10; instance["Comment"] = "No comment"; }); mealThreeDishTwo = BusinessObjectHelper.CreatePlainObject(adapter, "MealCalc", "CalcDayMealDish", delegate(ObjectInstance instance) { instance["CalcDayMealID"] = calcDayMealThree; instance["DishID"] = dishTwo; instance["PortionCount"] = 10; instance["Comment"] = "No comment"; }); mealThreeDishThree = BusinessObjectHelper.CreatePlainObject(adapter, "MealCalc", "CalcDayMealDish", delegate(ObjectInstance instance) { instance["CalcDayMealID"] = calcDayMealThree; instance["DishID"] = dishThree; instance["PortionCount"] = 10; instance["Comment"] = "No comment"; }); #endregion } private void removeCalcDayMealDishes() { var calcDayMealDish = (PlainObjectInstance) adapter.ObjectFactory.New<PlainObjectDefinition>("MealCalc", "CalcDayMealDish"); calcDayMealDish.Load(new AttributeValueSet { { "ID", mealOneDishOne } }); calcDayMealDish.Delete(); calcDayMealDish.Load(new AttributeValueSet { { "ID", mealOneDishTwo } }); calcDayMealDish.Delete(); calcDayMealDish.Load(new AttributeValueSet { { "ID", mealOneDishThree } }); calcDayMealDish.Delete(); calcDayMealDish.Load(new AttributeValueSet { { "ID", mealTwoDishOne } }); calcDayMealDish.Delete(); calcDayMealDish.Load(new AttributeValueSet { { "ID", mealTwoDishTwo } }); calcDayMealDish.Delete(); calcDayMealDish.Load(new AttributeValueSet { { "ID", mealTwoDishThree } }); calcDayMealDish.Delete(); calcDayMealDish.Load(new AttributeValueSet { { "ID", mealThreeDishOne } }); calcDayMealDish.Delete(); calcDayMealDish.Load(new AttributeValueSet { { "ID", mealThreeDishTwo } }); calcDayMealDish.Delete(); calcDayMealDish.Load(new AttributeValueSet { { "ID", mealThreeDishThree } }); calcDayMealDish.Delete(); } private void createGoodSpendDocument() { var parameters = new AttributeValueSet { { "ID", calcDayMenu } }; adapter.AccessProvider.ExecuteProcedure("MealCalc", "CalcDayMenu", "CreateGoodSpendDocument", parameters, null); } private void approveCalcDayMenu() { var parameters = new AttributeValueSet { { "ID", calcDayMenu } }; adapter.AccessProvider.ExecuteProcedure("MealCalc", "CalcDayMenu", "Approve", parameters, null); } private void unapproveCalcDayMenu() { var parameters = new AttributeValueSet { { "ID", calcDayMenu } }; adapter.AccessProvider.ExecuteProcedure("MealCalc", "CalcDayMenu", "Unapprove", parameters, null); } private void commitGoodSpendDocument() { var parameters = new AttributeValueSet { {"StartDateTime", DateTime.Today}, {"EndDateTime", DateTime.Today.AddDays(1)} }; var result = adapter.ObjectFactory.LoadObjectListView("MealCalc", "GoodSpendDocumentList", parameters); Assert.AreEqual(1, result.Rows.Count); int documentID = (int) result.Rows[0]["ID"]; var document = (DocumentInstance) adapter.ObjectFactory.New<DocumentDefinition>("MealCalc", "GoodSpendDocument"); document.Load(documentID); document["DocumentNumber"] = "000-001"; document["Comment"] = "Comment"; document.UpdateVersion(); document.ConfirmEdit(); document.Commit(); } private void rollbackGoodSpendDocument() { var parameters = new AttributeValueSet { {"StartDateTime", DateTime.Today}, {"EndDateTime", DateTime.Today.AddDays(1)} }; var result = adapter.ObjectFactory.LoadObjectListView("MealCalc", "GoodSpendDocumentList", parameters); Assert.AreEqual(1, result.Rows.Count); var documentID = (int)result.Rows[0]["ID"]; var document = (DocumentInstance)adapter.ObjectFactory.New<DocumentDefinition>("MealCalc", "GoodSpendDocument"); document.Load(documentID); document.Rollback(); } private void deleteGoodSpendDocument() { var parameters = new AttributeValueSet { {"StartDateTime", DateTime.Today}, {"EndDateTime", DateTime.Today.AddDays(1)} }; var result = adapter.ObjectFactory.LoadObjectListView("MealCalc", "GoodSpendDocumentList", parameters); Assert.AreEqual(1, result.Rows.Count); var documentID = (int)result.Rows[0]["ID"]; var document = (DocumentInstance)adapter.ObjectFactory.New<DocumentDefinition>("MealCalc", "GoodSpendDocument"); document.Load(documentID); document.Delete(); } private void rollbackGoodIncomeDocument() { var parameters = new AttributeValueSet { {"StartDateTime", DateTime.Today}, {"EndDateTime", DateTime.Today.AddDays(1)} }; var result = adapter.ObjectFactory.LoadObjectListView("MealCalc", "GoodIncomeList", parameters); Assert.AreEqual(1, result.Rows.Count); var documentID = (int)result.Rows[0]["ID"]; var document = (DocumentInstance)adapter.ObjectFactory.New<DocumentDefinition>("MealCalc", "GoodIncomeDocument"); document.Load(documentID); document.Rollback(); } public void Test() { prepare(); composeDishes(); createMenu(); openCalcDay(); makeIncome(); checkGoodBalance(); createCalcDayMenu(); addCalcDayMealDishes(); checkGoodReserve(); approveCalcDayMenu(); createGoodSpendDocument(); commitGoodSpendDocument(); checkGoodWriteOff(); rollbackGoodSpendDocument(); deleteGoodSpendDocument(); checkGoodReserve(); unapproveCalcDayMenu(); removeCalcDayMealDishes(); checkGoodBalance(); rollbackGoodIncomeDocument(); checkZeroGoodBalance(); } } }
51.251889
143
0.506315
[ "BSD-3-Clause" ]
shestakov/jetbat
JetBat.Test/FunctionalTest/TwoGoodsInTwoIncomesTest.cs
20,529
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 30.03.2021. using System; using System.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_002__AS_STR.Multiply.Complete.Int32.Decimal{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Int32; using T_DATA2 =System.Decimal; //////////////////////////////////////////////////////////////////////////////// //class TestSet_R504AAB004__param____VN public static class TestSet_R504AAB004__param____VN { private const string c_NameOf__TABLE ="DUAL"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("ID")] public System.Int32? TEST_ID { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { string vv1="1"; string vv2=null; var recs=db.testTable.Where(r => (string)(object)(((T_DATA1)vv1.Length)*((T_DATA1)vv1.Length)*((T_DATA2)vv2.Length))==null); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { string vv1="1"; string vv2=null; var recs=db.testTable.Where(r => (string)(object)((((T_DATA1)vv1.Length)*((T_DATA1)vv1.Length))*((T_DATA2)vv2.Length))==null); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_002 //----------------------------------------------------------------------- [Test] public static void Test_003() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { string vv1="1"; string vv2=null; var recs=db.testTable.Where(r => (string)(object)(((T_DATA1)vv1.Length)*(((T_DATA1)vv1.Length)*((T_DATA2)vv2.Length)))==null); int nRecs=0; foreach(var r in recs) { Assert.AreEqual (0, nRecs); ++nRecs; Assert.IsTrue (r.TEST_ID.HasValue); Assert.AreEqual (1, r.TEST_ID.Value); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("d","ID").EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL() .T("WHERE ").P_BOOL("__Exec_V_V_0")); Assert.AreEqual (1, nRecs); }//using db tr.Commit(); }//using tr }//using cn }//Test_003 };//class TestSet_R504AAB004__param____VN //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_002__AS_STR.Multiply.Complete.Int32.Decimal
24.184466
137
0.527298
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_002__AS_STR/Multiply/Complete/Int32/Decimal/TestSet_R504AAB004__param____VN.cs
4,984
C#
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { [CompilerTrait(CompilerFeature.ReadOnlyReferences)] public class CodeGenReadOnlyStructTests : CompilingTestBase { [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyStaticField() { var text = @" class Program { static readonly S1 sf; static void Main() { System.Console.Write(sf.M1()); System.Console.Write(sf.ToString()); } readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 37 (0x25) .maxstack 1 IL_0000: ldsflda ""Program.S1 Program.sf"" IL_0005: call ""string Program.S1.M1()"" IL_000a: call ""void System.Console.Write(string)"" IL_000f: ldsflda ""Program.S1 Program.sf"" IL_0014: constrained. ""Program.S1"" IL_001a: callvirt ""string object.ToString()"" IL_001f: call ""void System.Console.Write(string)"" IL_0024: ret }"); comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 43 (0x2b) .maxstack 1 .locals init (Program.S1 V_0) IL_0000: ldsfld ""Program.S1 Program.sf"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call ""string Program.S1.M1()"" IL_000d: call ""void System.Console.Write(string)"" IL_0012: ldsfld ""Program.S1 Program.sf"" IL_0017: stloc.0 IL_0018: ldloca.s V_0 IL_001a: constrained. ""Program.S1"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.Write(string)"" IL_002a: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyStaticFieldMetadata() { var text1 = @" public readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } "; var comp1 = CreateCompilation(text1, assemblyName: "A"); var ref1 = comp1.EmitToImageReference(); var text = @" class Program { static readonly S1 sf; static void Main() { System.Console.Write(sf.M1()); System.Console.Write(sf.ToString()); } } "; var comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 37 (0x25) .maxstack 1 IL_0000: ldsflda ""S1 Program.sf"" IL_0005: call ""string S1.M1()"" IL_000a: call ""void System.Console.Write(string)"" IL_000f: ldsflda ""S1 Program.sf"" IL_0014: constrained. ""S1"" IL_001a: callvirt ""string object.ToString()"" IL_001f: call ""void System.Console.Write(string)"" IL_0024: ret }"); comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 43 (0x2b) .maxstack 1 .locals init (S1 V_0) IL_0000: ldsfld ""S1 Program.sf"" IL_0005: stloc.0 IL_0006: ldloca.s V_0 IL_0008: call ""string S1.M1()"" IL_000d: call ""void System.Console.Write(string)"" IL_0012: ldsfld ""S1 Program.sf"" IL_0017: stloc.0 IL_0018: ldloca.s V_0 IL_001a: constrained. ""S1"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.Write(string)"" IL_002a: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyInstanceField() { var text = @" class Program { readonly S1 f; static void Main() { var p = new Program(); System.Console.Write(p.f.M1()); System.Console.Write(p.f.ToString()); } readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 43 (0x2b) .maxstack 2 IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldflda ""Program.S1 Program.f"" IL_000b: call ""string Program.S1.M1()"" IL_0010: call ""void System.Console.Write(string)"" IL_0015: ldflda ""Program.S1 Program.f"" IL_001a: constrained. ""Program.S1"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""void System.Console.Write(string)"" IL_002a: ret }"); comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Main", @" { // Code size 49 (0x31) .maxstack 2 .locals init (Program.S1 V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldfld ""Program.S1 Program.f"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: call ""string Program.S1.M1()"" IL_0013: call ""void System.Console.Write(string)"" IL_0018: ldfld ""Program.S1 Program.f"" IL_001d: stloc.0 IL_001e: ldloca.s V_0 IL_0020: constrained. ""Program.S1"" IL_0026: callvirt ""string object.ToString()"" IL_002b: call ""void System.Console.Write(string)"" IL_0030: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyInstanceFieldGeneric() { var text = @" class Program { readonly S1<string> f; static void Main() { var p = new Program(); System.Console.Write(p.f.M1(""hello"")); System.Console.Write(p.f.ToString()); } readonly struct S1<T> { public T M1(T arg) { return arg; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 48 (0x30) .maxstack 3 IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldflda ""Program.S1<string> Program.f"" IL_000b: ldstr ""hello"" IL_0010: call ""string Program.S1<string>.M1(string)"" IL_0015: call ""void System.Console.Write(string)"" IL_001a: ldflda ""Program.S1<string> Program.f"" IL_001f: constrained. ""Program.S1<string>"" IL_0025: callvirt ""string object.ToString()"" IL_002a: call ""void System.Console.Write(string)"" IL_002f: ret }"); comp = CompileAndVerify(text, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (Program.S1<string> V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldfld ""Program.S1<string> Program.f"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: ldstr ""hello"" IL_0013: call ""string Program.S1<string>.M1(string)"" IL_0018: call ""void System.Console.Write(string)"" IL_001d: ldfld ""Program.S1<string> Program.f"" IL_0022: stloc.0 IL_0023: ldloca.s V_0 IL_0025: constrained. ""Program.S1<string>"" IL_002b: callvirt ""string object.ToString()"" IL_0030: call ""void System.Console.Write(string)"" IL_0035: ret }"); } [Fact] [CompilerTrait(CompilerFeature.PEVerifyCompat)] public void InvokeOnReadOnlyInstanceFieldGenericMetadata() { var text1 = @" readonly public struct S1<T> { public T M1(T arg) { return arg; } public override string ToString() { return ""2""; } } "; var comp1 = CreateCompilation(text1, assemblyName: "A"); var ref1 = comp1.EmitToImageReference(); var text = @" class Program { readonly S1<string> f; static void Main() { var p = new Program(); System.Console.Write(p.f.M1(""hello"")); System.Console.Write(p.f.ToString()); } } "; var comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular, verify: Verification.Fails, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 48 (0x30) .maxstack 3 IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldflda ""S1<string> Program.f"" IL_000b: ldstr ""hello"" IL_0010: call ""string S1<string>.M1(string)"" IL_0015: call ""void System.Console.Write(string)"" IL_001a: ldflda ""S1<string> Program.f"" IL_001f: constrained. ""S1<string>"" IL_0025: callvirt ""string object.ToString()"" IL_002a: call ""void System.Console.Write(string)"" IL_002f: ret }"); comp = CompileAndVerify(text, new[] { ref1 }, parseOptions: TestOptions.Regular.WithPEVerifyCompatFeature(), verify: Verification.Passes, expectedOutput: @"hello2"); comp.VerifyIL("Program.Main", @" { // Code size 54 (0x36) .maxstack 3 .locals init (S1<string> V_0) IL_0000: newobj ""Program..ctor()"" IL_0005: dup IL_0006: ldfld ""S1<string> Program.f"" IL_000b: stloc.0 IL_000c: ldloca.s V_0 IL_000e: ldstr ""hello"" IL_0013: call ""string S1<string>.M1(string)"" IL_0018: call ""void System.Console.Write(string)"" IL_001d: ldfld ""S1<string> Program.f"" IL_0022: stloc.0 IL_0023: ldloca.s V_0 IL_0025: constrained. ""S1<string>"" IL_002b: callvirt ""string object.ToString()"" IL_0030: call ""void System.Console.Write(string)"" IL_0035: ret }"); } [Fact] public void InvokeOnReadOnlyThis() { var text = @" class Program { static void Main() { Test(default(S1)); } static void Test(in S1 arg) { System.Console.Write(arg.M1()); System.Console.Write(arg.ToString()); } readonly struct S1 { public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.Test", @" { // Code size 29 (0x1d) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""string Program.S1.M1()"" IL_0006: call ""void System.Console.Write(string)"" IL_000b: ldarg.0 IL_000c: constrained. ""Program.S1"" IL_0012: callvirt ""string object.ToString()"" IL_0017: call ""void System.Console.Write(string)"" IL_001c: ret }"); } [Fact] public void InvokeOnThis() { var text = @" class Program { static void Main() { default(S1).Test(); } readonly struct S1 { public void Test() { System.Console.Write(this.M1()); System.Console.Write(ToString()); } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"12"); comp.VerifyIL("Program.S1.Test()", @" { // Code size 29 (0x1d) .maxstack 1 IL_0000: ldarg.0 IL_0001: call ""string Program.S1.M1()"" IL_0006: call ""void System.Console.Write(string)"" IL_000b: ldarg.0 IL_000c: constrained. ""Program.S1"" IL_0012: callvirt ""string object.ToString()"" IL_0017: call ""void System.Console.Write(string)"" IL_001c: ret }"); comp.VerifyIL("Program.Main()", @" { // Code size 15 (0xf) .maxstack 2 .locals init (Program.S1 V_0) IL_0000: ldloca.s V_0 IL_0002: dup IL_0003: initobj ""Program.S1"" IL_0009: call ""void Program.S1.Test()"" IL_000e: ret }"); } [Fact] public void InvokeOnThisBaseMethods() { var text = @" class Program { static void Main() { default(S1).Test(); } readonly struct S1 { public void Test() { System.Console.Write(this.GetType()); System.Console.Write(ToString()); } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"Program+S1Program+S1"); comp.VerifyIL("Program.S1.Test()", @" { // Code size 39 (0x27) .maxstack 1 IL_0000: ldarg.0 IL_0001: ldobj ""Program.S1"" IL_0006: box ""Program.S1"" IL_000b: call ""System.Type object.GetType()"" IL_0010: call ""void System.Console.Write(object)"" IL_0015: ldarg.0 IL_0016: constrained. ""Program.S1"" IL_001c: callvirt ""string object.ToString()"" IL_0021: call ""void System.Console.Write(string)"" IL_0026: ret }"); } [Fact] public void AssignThis() { var text = @" class Program { static void Main() { S1 v = new S1(42); System.Console.Write(v.x); S1 v2 = new S1(v); System.Console.Write(v2.x); } readonly struct S1 { public readonly int x; public S1(int i) { x = i; // OK } public S1(S1 arg) { this = arg; // OK } } } "; var comp = CompileAndVerify(text, parseOptions: TestOptions.Regular, verify: Verification.Passes, expectedOutput: @"4242"); comp.VerifyIL("Program.S1..ctor(int)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stfld ""int Program.S1.x"" IL_0007: ret }"); comp.VerifyIL("Program.S1..ctor(Program.S1)", @" { // Code size 8 (0x8) .maxstack 2 IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: stobj ""Program.S1"" IL_0007: ret }"); } [Fact] public void AssignThisErr() { var text = @" class Program { static void Main() { } static void TakesRef(ref S1 arg){} static void TakesRef(ref int arg){} readonly struct S1 { readonly int x; public S1(int i) { x = i; // OK } public S1(S1 arg) { this = arg; // OK } public void Test1() { this = default; // error } public void Test2() { TakesRef(ref this); // error } public void Test3() { TakesRef(ref this.x); // error } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (27,13): error CS1604: Cannot assign to 'this' because it is read-only // this = default; // error Diagnostic(ErrorCode.ERR_AssgReadonlyLocal, "this").WithArguments("this").WithLocation(27, 13), // (32,26): error CS1605: Cannot use 'this' as a ref or out value because it is read-only // TakesRef(ref this); // error Diagnostic(ErrorCode.ERR_RefReadonlyLocal, "this").WithArguments("this").WithLocation(32, 26), // (37,26): error CS0192: A readonly field cannot be used as a ref or out value (except in a constructor) // TakesRef(ref this.x); // error Diagnostic(ErrorCode.ERR_RefReadonly, "this.x").WithLocation(37, 26) ); } [Fact] public void AssignThisNestedMethods() { var text = @" using System; class Program { static void Main() { } static void TakesRef(ref S1 arg){} static void TakesRef(ref int arg){} readonly struct S1 { readonly int x; public S1(int i) { void F() { x = i;} // Error Action a = () => { x = i;}; // Error F(); } public S1(S1 arg) { void F() { this = arg;} // Error Action a = () => { this = arg;}; // Error F(); } public void Test1() { void F() { this = default;} // Error Action a = () => { this = default;}; // Error F(); } public void Test2() { void F() { TakesRef(ref this);} // Error Action a = () => { TakesRef(ref this);}; // Error F(); } public void Test3() { void F() { TakesRef(ref this.x);} // Error Action a = () => { TakesRef(ref this.x);}; // Error F(); } } } "; var comp = CreateCompilation(text); comp.VerifyDiagnostics( // (19,24): error CS1673: Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. // void F() { x = i;} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "x").WithLocation(19, 24), // (20,32): error CS1673: Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. // Action a = () => { x = i;}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "x").WithLocation(20, 32), // (26,24): error CS1673: Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. // void F() { this = arg;} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(26, 24), // (27,32): error CS1673: Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. // Action a = () => { this = arg;}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(27, 32), // (33,24): error CS1673: Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. // void F() { this = default;} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(33, 24), // (34,32): error CS1673: Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. // Action a = () => { this = default;}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(34, 32), // (40,37): error CS1673: Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. // void F() { TakesRef(ref this);} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(40, 37), // (41,45): error CS1673: Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. // Action a = () => { TakesRef(ref this);}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(41, 45), // (47,37): error CS1673: Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. // void F() { TakesRef(ref this.x);} // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(47, 37), // (48,45): error CS1673: Anonymous methods, lambda expressions, and query expressions inside structs cannot access instance members of 'this'. Consider copying 'this' to a local variable outside the anonymous method, lambda expression or query expression and using the local instead. // Action a = () => { TakesRef(ref this.x);}; // Error Diagnostic(ErrorCode.ERR_ThisStructNotInAnonMeth, "this").WithLocation(48, 45) ); } [Fact] public void ReadOnlyStructApi() { var text = @" class Program { readonly struct S1 { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } readonly struct S1<T> { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } struct S2 { public S2(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } class C1 { public C1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } delegate int D1(); } "; var comp = CreateCompilation(text, parseOptions: TestOptions.Regular); // S1 NamedTypeSymbol namedType = comp.GetTypeByMetadataName("Program+S1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); void validate(ModuleSymbol module) { var test = module.ContainingAssembly.GetTypeByMetadataName("Program+S1"); var peModule = (PEModuleSymbol)module; Assert.True(peModule.Module.HasIsReadOnlyAttribute(((PENamedTypeSymbol)test).Handle)); AssertDeclaresType(peModule, WellKnownType.System_Runtime_CompilerServices_IsReadOnlyAttribute, Accessibility.Internal); } CompileAndVerify(comp, symbolValidator: validate); // S1<T> namedType = comp.GetTypeByMetadataName("Program+S1`1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // T TypeSymbol type = namedType.TypeParameters[0]; Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S1<object> namedType = namedType.Construct(comp.ObjectType); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S2 namedType = comp.GetTypeByMetadataName("Program+S2"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("ToString").ThisParameter.RefKind); // C1 namedType = comp.GetTypeByMetadataName("Program+C1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("ToString").ThisParameter.RefKind); // D1 namedType = comp.GetTypeByMetadataName("Program+D1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("Invoke").ThisParameter.RefKind); // object[] type = comp.CreateArrayTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // dynamic type = comp.DynamicType; Assert.False(type.IsReadOnly); // object type = comp.ObjectType; Assert.False(type.IsReadOnly); // anonymous type type = (TypeSymbol)comp.CreateAnonymousTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType), ImmutableArray.Create("qq")); Assert.False(type.IsReadOnly); // pointer type type = (TypeSymbol)comp.CreatePointerTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // tuple type type = (TypeSymbol)comp.CreateTupleTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType, comp.ObjectType)); Assert.False(type.IsReadOnly); // S1 from image var clientComp = CreateCompilation("", references: new[] { comp.EmitToImageReference() }); NamedTypeSymbol s1 = clientComp.GetTypeByMetadataName("Program+S1"); Assert.True(s1.IsReadOnly); Assert.Empty(s1.GetAttributes()); Assert.Equal(RefKind.Out, s1.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, s1.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, s1.GetMethod("ToString").ThisParameter.RefKind); } [Fact] public void ReadOnlyStructApiMetadata() { var text1 = @" class Program { readonly struct S1 { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } readonly struct S1<T> { public S1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } struct S2 { public S2(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } class C1 { public C1(int dummy) { } public string M1() { return ""1""; } public override string ToString() { return ""2""; } } delegate int D1(); } "; var comp1 = CreateCompilation(text1, assemblyName: "A"); var ref1 = comp1.EmitToImageReference(); var comp = CreateCompilation("//NO CODE HERE", new[] { ref1 }, parseOptions: TestOptions.Regular); // S1 NamedTypeSymbol namedType = comp.GetTypeByMetadataName("Program+S1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S1<T> namedType = comp.GetTypeByMetadataName("Program+S1`1"); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // T TypeSymbol type = namedType.TypeParameters[0]; Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S1<object> namedType = namedType.Construct(comp.ObjectType); Assert.True(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.In, namedType.GetMethod("ToString").ThisParameter.RefKind); // S2 namedType = comp.GetTypeByMetadataName("Program+S2"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.Out, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.Ref, namedType.GetMethod("ToString").ThisParameter.RefKind); // C1 namedType = comp.GetTypeByMetadataName("Program+C1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("M1").ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("ToString").ThisParameter.RefKind); // D1 namedType = comp.GetTypeByMetadataName("Program+D1"); Assert.False(namedType.IsReadOnly); Assert.Equal(RefKind.None, namedType.Constructors[0].ThisParameter.RefKind); Assert.Equal(RefKind.None, namedType.GetMethod("Invoke").ThisParameter.RefKind); // object[] type = comp.CreateArrayTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // dynamic type = comp.DynamicType; Assert.False(type.IsReadOnly); // object type = comp.ObjectType; Assert.False(type.IsReadOnly); // anonymous type type = (TypeSymbol)comp.CreateAnonymousTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType), ImmutableArray.Create("qq")); Assert.False(type.IsReadOnly); // pointer type type = (TypeSymbol)comp.CreatePointerTypeSymbol(comp.ObjectType); Assert.False(type.IsReadOnly); // tuple type type = (TypeSymbol)comp.CreateTupleTypeSymbol(ImmutableArray.Create<ITypeSymbol>(comp.ObjectType, comp.ObjectType)); Assert.False(type.IsReadOnly); } [Fact] public void CorrectOverloadOfStackAllocSpanChosen() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { unsafe public static void Main() { bool condition = false; var span1 = condition ? stackalloc int[1] : new Span<int>(null, 2); Console.Write(span1.Length); var span2 = condition ? stackalloc int[1] : stackalloc int[4]; Console.Write(span2.Length); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "24", verify: Verification.Fails); } [Fact] public void StackAllocExpressionIL() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { Span<int> x = stackalloc int[10]; Console.WriteLine(x.Length); } }", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "10", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (System.Span<int> V_0) //x IL_0000: ldc.i4.s 40 IL_0002: conv.u IL_0003: localloc IL_0005: ldc.i4.s 10 IL_0007: newobj ""System.Span<int>..ctor(void*, int)"" IL_000c: stloc.0 IL_000d: ldloca.s V_0 IL_000f: call ""int System.Span<int>.Length.get"" IL_0014: call ""void System.Console.WriteLine(int)"" IL_0019: ret }"); } [Fact] public void StackAllocSpanLengthNotEvaluatedTwice() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { private static int length = 0; private static int GetLength() { return ++length; } public static void Main() { for (int i = 0; i < 5; i++) { Span<int> x = stackalloc int[GetLength()]; Console.Write(x.Length); } } }", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "12345", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 44 (0x2c) .maxstack 2 .locals init (int V_0, //i System.Span<int> V_1, //x int V_2) IL_0000: ldc.i4.0 IL_0001: stloc.0 IL_0002: br.s IL_0027 IL_0004: call ""int Test.GetLength()"" IL_0009: stloc.2 IL_000a: ldloc.2 IL_000b: conv.u IL_000c: ldc.i4.4 IL_000d: mul.ovf.un IL_000e: localloc IL_0010: ldloc.2 IL_0011: newobj ""System.Span<int>..ctor(void*, int)"" IL_0016: stloc.1 IL_0017: ldloca.s V_1 IL_0019: call ""int System.Span<int>.Length.get"" IL_001e: call ""void System.Console.Write(int)"" IL_0023: ldloc.0 IL_0024: ldc.i4.1 IL_0025: add IL_0026: stloc.0 IL_0027: ldloc.0 IL_0028: ldc.i4.5 IL_0029: blt.s IL_0004 IL_002b: ret }"); } [Fact] public void StackAllocSpanLengthConstantFolding() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { public static void Main() { const int a = 5, b = 6; Span<int> x = stackalloc int[a * b]; Console.Write(x.Length); } }", TestOptions.ReleaseExe); CompileAndVerify(comp, expectedOutput: "30", verify: Verification.Fails).VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 2 .locals init (System.Span<int> V_0) //x IL_0000: ldc.i4.s 120 IL_0002: conv.u IL_0003: localloc IL_0005: ldc.i4.s 30 IL_0007: newobj ""System.Span<int>..ctor(void*, int)"" IL_000c: stloc.0 IL_000d: ldloca.s V_0 IL_000f: call ""int System.Span<int>.Length.get"" IL_0014: call ""void System.Console.Write(int)"" IL_0019: ret }"); } [Fact] public void StackAllocSpanLengthOverflow() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; class Test { static void M() { Span<int> x = stackalloc int[int.MaxValue]; } public static void Main() { try { M(); } catch (OverflowException) { Console.WriteLine(""overflow""); } } }", TestOptions.ReleaseExe); var expectedIL = @" { // Code size 22 (0x16) .maxstack 2 IL_0000: ldc.i4 0x7fffffff IL_0005: conv.u IL_0006: ldc.i4.4 IL_0007: mul.ovf.un IL_0008: localloc IL_000a: ldc.i4 0x7fffffff IL_000f: newobj ""System.Span<int>..ctor(void*, int)"" IL_0014: pop IL_0015: ret }"; var isx86 = (IntPtr.Size == 4); if (isx86) { CompileAndVerify(comp, expectedOutput: "overflow", verify: Verification.Fails).VerifyIL("Test.M", expectedIL); } else { // On 64bit the native int does not overflow, so we get StackOverflow instead // therefore we will just check the IL CompileAndVerify(comp, verify: Verification.Fails).VerifyIL("Test.M", expectedIL); } } [Fact] public void ImplicitCastOperatorOnStackAllocIsLoweredCorrectly() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public static void Main() { Test obj1 = stackalloc int[10]; Console.Write(""|""); Test obj2 = stackalloc double[10]; } public static implicit operator Test(Span<int> value) { Console.Write(""SpanOpCalled""); return default(Test); } public static implicit operator Test(double* value) { Console.Write(""PointerOpCalled""); return default(Test); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "SpanOpCalled|PointerOpCalled", verify: Verification.Fails); } [Fact] public void ExplicitCastOperatorOnStackAllocIsLoweredCorrectly() { var comp = CreateCompilationWithMscorlibAndSpan(@" using System; unsafe class Test { public static void Main() { Test obj1 = (Test)stackalloc int[10]; } public static explicit operator Test(Span<int> value) { Console.Write(""SpanOpCalled""); return default(Test); } }", TestOptions.UnsafeReleaseExe); CompileAndVerify(comp, expectedOutput: "SpanOpCalled", verify: Verification.Fails); } } }
31.259146
300
0.581976
[ "Apache-2.0" ]
DustinCampbell/roslyn
src/Compilers/CSharp/Test/Emit/CodeGen/CodeGenReadonlyStructTests.cs
41,014
C#
 namespace SelfDC.Models { public class OrderItem { public string productCode { get; set; } public string barcode { get; set; } public int qta { get; set; } public OrderItem(string productCode, string barcode, int qta) { this.productCode = productCode; this.barcode = barcode; this.qta = qta; } public OrderItem(string productCode, int qta) { this.productCode = productCode; this.barcode = ""; this.qta = qta; } public OrderItem(string productCode) { this.productCode = productCode; this.barcode = ""; this.qta = 1; } override public string ToString() { return string.Format("{0,7} | {1,13} | {2,3}", this.productCode, this.barcode, this.qta); } } }
24.513514
101
0.513782
[ "Apache-2.0" ]
ginopc/SelfDC-Datalogic
Models/OrderItem.cs
909
C#
/* * RESTAPI Service * * RESTful API * * OpenAPI spec version: 2.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; namespace IO.Swagger.Model { /// <summary> /// Unauthorized /// </summary> [DataContract] public partial class ThresholdGetThresholdStatusUnauthorizedResponseBody : IEquatable<ThresholdGetThresholdStatusUnauthorizedResponseBody>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="ThresholdGetThresholdStatusUnauthorizedResponseBody" /> class. /// </summary> [JsonConstructorAttribute] protected ThresholdGetThresholdStatusUnauthorizedResponseBody() { } /// <summary> /// Initializes a new instance of the <see cref="ThresholdGetThresholdStatusUnauthorizedResponseBody" /> class. /// </summary> /// <param name="message">Message of error (required).</param> /// <param name="requestId">Request ID (required).</param> public ThresholdGetThresholdStatusUnauthorizedResponseBody(string message = default(string), string requestId = default(string)) { // to ensure "message" is required (not null) if (message == null) { throw new InvalidDataException("message is a required property for ThresholdGetThresholdStatusUnauthorizedResponseBody and cannot be null"); } else { this.Message = message; } // to ensure "requestId" is required (not null) if (requestId == null) { throw new InvalidDataException("requestId is a required property for ThresholdGetThresholdStatusUnauthorizedResponseBody and cannot be null"); } else { this.RequestId = requestId; } } /// <summary> /// Message of error /// </summary> /// <value>Message of error</value> [DataMember(Name="message", EmitDefaultValue=false)] public string Message { get; set; } /// <summary> /// Request ID /// </summary> /// <value>Request ID</value> [DataMember(Name="request_id", EmitDefaultValue=false)] public string RequestId { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ThresholdGetThresholdStatusUnauthorizedResponseBody {\n"); sb.Append(" Message: ").Append(Message).Append("\n"); sb.Append(" RequestId: ").Append(RequestId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as ThresholdGetThresholdStatusUnauthorizedResponseBody); } /// <summary> /// Returns true if ThresholdGetThresholdStatusUnauthorizedResponseBody instances are equal /// </summary> /// <param name="input">Instance of ThresholdGetThresholdStatusUnauthorizedResponseBody to be compared</param> /// <returns>Boolean</returns> public bool Equals(ThresholdGetThresholdStatusUnauthorizedResponseBody input) { if (input == null) return false; return ( this.Message == input.Message || (this.Message != null && this.Message.Equals(input.Message)) ) && ( this.RequestId == input.RequestId || (this.RequestId != null && this.RequestId.Equals(input.RequestId)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Message != null) hashCode = hashCode * 59 + this.Message.GetHashCode(); if (this.RequestId != null) hashCode = hashCode * 59 + this.RequestId.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
35.737805
163
0.585907
[ "MIT" ]
GeoSCADA/Driver-SELogger
IO.Swagger/Model/ThresholdGetThresholdStatusUnauthorizedResponseBody.cs
5,861
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; namespace MattermostAddinConnect.Mattermost.v4.Interface { public class Team { [JsonProperty("name")] public string Name { get; set; } [JsonProperty("id")] public string Id { get; set; } } }
19.842105
56
0.671088
[ "MIT" ]
casanovg/Mattermost-Addin
MattermostAddin-Connect/Mattermost/v4/Interface/Team.cs
379
C#
using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine; using UnityEngine.EventSystems; using InControl; public class ModeButton : MonoBehaviour, ISelectHandler { private GameplayManager GM; private Text ModeTitle; private Text ModeDesc; public string ModeTitleText; public string ModeDescText; bool canBack = true; public void Start() { GM = GameObject.Find("GameplayManager").GetComponent<GameplayManager>(); } public void OnSelect(BaseEventData eventData) { ModeTitle = transform.parent.Find("ModeTitle").gameObject.GetComponent<Text>(); ModeDesc = transform.parent.Find("ModeDesc").gameObject.GetComponent<Text>(); ModeTitle.text = ModeTitleText; ModeDesc.text = ModeDescText; } void Update() { if (!InputManager.Devices[0].Action2) { canBack = true; } if (InputManager.Devices[0].Action2.WasPressed && this.gameObject.name == "Mode2") { GM.firstSelected = GM.LevelModeMenus[GM.LevelSelected].transform.parent.gameObject; GM.LevelModeMenus[GM.LevelSelected].SetActive(false); GM.LevelSelectMenu.transform.Find("LevelTitle").gameObject.GetComponent<Text>().text = "SELECT LEVEL"; EventSystem.current.SetSelectedGameObject(GM.firstSelected); canBack = false; } else if (InputManager.Devices[0].Action2.WasPressed && this.gameObject.name == "Ready") { //GM.firstSelected = GM.LevelModeMenus[GM.LevelSelected].transform.Find("Mode1").gameObject; GM.firstSelected = GM.LevelModeMenus[GM.LevelSelected].transform.parent.gameObject; GM.ReadyMenu.SetActive(false); //GM.LevelModeMenus[GM.LevelSelected].SetActive(true); //GM.LevelSelectMenu.transform.Find("LevelTitle").gameObject.GetComponent<Text>().text = "SELECT MODE"; GM.LevelSelectMenu.transform.Find("LevelTitle").gameObject.GetComponent<Text>().text = "SELECT LEVEL"; EventSystem.current.SetSelectedGameObject(GM.firstSelected); canBack = false; } else if (InputManager.Devices[0].Action2.WasPressed && this.gameObject.name.Contains("LEVEL")) { GM.firstSelected = GM.MainMenu.transform.Find("PLAY").gameObject; GM.LevelSelectMenu.SetActive(false); GM.MainMenu.SetActive(true); EventSystem.current.SetSelectedGameObject(GM.firstSelected); canBack = false; } else if (InputManager.Devices[0].Action2.WasPressed && this.gameObject.name == "BACK") { GM.firstSelected = GM.MainMenu.transform.Find("CREDITS").gameObject; GM.MainMenu.transform.parent.Find("Credits").gameObject.SetActive(false); GM.MainMenu.SetActive(true); EventSystem.current.SetSelectedGameObject(GM.firstSelected); canBack = false; } else if (InputManager.ActiveDevice.Action2.WasPressed && this.transform.parent.gameObject.name =="Player Customisation") { GM.firstSelected = GM.MainMenu.transform.Find("PLAY").gameObject; GM.PlayerMenu.SetActive(false); GM.MainMenu.SetActive(true); EventSystem.current.SetSelectedGameObject(GM.firstSelected); canBack = false; } // else if (InputManager.Devices[0].Action2.WasPressed && this.gameObject.name.Contains("LEVEL")) // { // GM.firstSelected = GM.MainMenu.transform.Find("PLAY").gameObject; // GM.LevelSelectMenu.SetActive(false); // GM.LevelModeMenus[GM.LevelSelected].SetActive(false); // GM.MainMenu.SetActive(true); // EventSystem.current.SetSelectedGameObject(GM.firstSelected); // canBack = false; // } } }
33.245455
122
0.695379
[ "MIT" ]
gluyas/LEGS
Assets/Scripts/ModeButton.cs
3,659
C#
using Cli.Mail.Models; using Cli.Mail.Services; using Cli.Mail.Tests.Builders; using Cli.Mail.Wrappers; using MimeKit; using NSubstitute; using Xunit; namespace Cli.Mail.Tests.Services { public class MailServiceTests { private readonly ISmtpClientWrapper _client; private readonly MailOptions _options; public MailServiceTests() { _client = Substitute.For<ISmtpClientWrapper>(); _options = new MailOptionsBuilder().Build(); } [Fact] public void Should_create_new_mail_service_instance() { //Arrange var username = _options.Username; var password = _options.Password; //Act new MailService(_options, _client); //Assert _client.Received(1).Connect(Server.Host, Server.Port, Server.UseSsl); _client.Received(1).Authenticate(username, password); } [Fact] public void Should_send_email() { //Arrange var mailService = new MailService(_options, _client); //Act mailService.Send(); //Assert _client.Received(1).SendAsync(Arg.Any<MimeMessage>()); _client.Received(1).Disconnect(true); } } }
26.568627
81
0.57048
[ "MIT" ]
raschmitt/cli-mail
Cli.Mail/Cli.Mail.Tests/Services/MailServiceTests.cs
1,357
C#
using System; using System.Collections.Generic; using System.Text; using static tysos.ServerObject; namespace tysos.Interfaces { [libsupcs.AlwaysInvoke] public interface IVfs { RPCResult<bool> Mount(string mount_path); RPCResult<bool> Mount(string mount_path, string src); RPCResult<bool> Mount(string mount_path, IFileSystem src); RPCResult<tysos.lib.File> OpenFile(string path, System.IO.FileMode mode, System.IO.FileAccess access, System.IO.FileShare share, System.IO.FileOptions options); RPCResult<System.IO.FileAttributes> GetFileAttributes(string path); RPCResult<string[]> GetFileSystemEntries(string path, string path_with_pattern, int attrs, int mask); RPCResult<bool> CloseFile(tysos.lib.File handle); RPCResult<bool> RegisterAddHandler(string tag_name, string tag_value, int msg_id, bool run_for_current); RPCResult<bool> RegisterDeleteHandler(string tag_name, string tag_value, int msg_id); RPCResult<bool> RegisterTag(string tag, string path); } }
37.896552
109
0.715196
[ "MIT" ]
jncronin/tysos
tysos/Interfaces/IVfs.cs
1,101
C#
using System.Diagnostics; using System.IO; using TaskTesterConsole.Config; using TaskTesterCore.Constants; namespace TaskTesterCore { public static class Copililer { public static bool Compile(Config config) { Process process = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.WindowStyle = ProcessWindowStyle.Hidden; startInfo.FileName = FileConstants.CmdFile; if (File.Exists(config.Source + FileConstants.CppExtension)) { startInfo.Arguments = config.CPPCompiler + ' ' + config.Source + FileConstants.CppExtension + " -static-libstdc++ -static-libgcc -o " + config.OutputCompiledFileName; } if (File.Exists(config.Source + FileConstants.PascalExtension)) { config.OutputCompiledFileName = config.Source + FileConstants.ExeExtension; startInfo.Arguments = config.PascalCompiler + ' ' + config.Source + FileConstants.PascalExtension; } process.StartInfo = startInfo; process.Start(); if (!File.Exists(config.OutputCompiledFileName)) { throw new System.Exception($"We couldn't compile {config.Source} file!"); } return true; } } }
33.285714
114
0.597997
[ "MIT" ]
Andriy22/TaskTesterCore
TaskTesterCore/TaskTesterCore/Copililer.cs
1,400
C#
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *********************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; namespace Multiverse.Tools.WorldEditor { /// <summary> /// This command uses reflection to provide a general interface for property changes. /// /// This prevents having to have commands for each property that might be changed. /// </summary> public class PropertyChangeCommand : ICommand { private object previousValue; private object newValue; private object component; //private PropertyDescriptor propertyDescriptor; private WorldEditor app; private String propertyName; public PropertyChangeCommand(WorldEditor worldEditor, object component, PropertyDescriptor property, object newValue, object previousValue) { this.app = worldEditor; this.component = component; //this.propertyDescriptor = property; this.newValue = newValue; this.previousValue = previousValue; propertyName = property.Name; } #region ICommand Members public bool Undoable() { return true; } public void Execute() { PropertyDescriptor propertyDescriptor = TypeDescriptor.GetProperties(component)[propertyName]; propertyDescriptor.SetValue(component, newValue); app.UpdatePropertyGrid(); } public void UnExecute() { PropertyDescriptor propertyDescriptor = TypeDescriptor.GetProperties(component)[propertyName]; propertyDescriptor.SetValue(component, previousValue); app.UpdatePropertyGrid(); } #endregion } }
35.22093
147
0.67349
[ "MIT" ]
AustralianDisabilityLimited/MultiversePlatform
tools/WorldEditor/PropertyChangeCommand.cs
3,029
C#
using System; namespace Coldairarrow.Util { public static partial class Extention { /// <summary> /// int转Ascll字符 /// </summary> /// <param name="ascllCode"></param> /// <returns></returns> public static string ToAscllStr(this int ascllCode) { if (ascllCode >= 0 && ascllCode <= 255) { System.Text.ASCIIEncoding asciiEncoding = new System.Text.ASCIIEncoding(); byte[] byteArray = new byte[] { (byte)ascllCode }; string strCharacter = asciiEncoding.GetString(byteArray); return (strCharacter); } else { throw new Exception("ASCII Code is not valid."); } } /// <summary> /// jsGetTime转为DateTime /// </summary> /// <param name="jsGetTime">js中Date.getTime()</param> /// <returns></returns> public static DateTime ToDateTime_From_JsGetTime(this long jsGetTime) { DateTime dtStart = new DateTime(1970, 1, 1).ToLocalTime(); long lTime = long.Parse(jsGetTime + "0000"); //说明下,时间格式为13位后面补加4个"0",如果时间格式为10位则后面补加7个"0",至于为什么我也不太清楚,也是仿照人家写的代码转换的 TimeSpan toNow = new TimeSpan(lTime); DateTime dtResult = dtStart.Add(toNow); //得到转换后的时间 return dtResult; } } }
32.604651
128
0.544223
[ "MIT" ]
2644783865/Colder.Admin.AntdVue
src/Coldairarrow.Util/Extention/Extention.Int.cs
1,542
C#
using System.Net.Sockets; using System.Text; namespace Common.Connection { // State object for receiving data from remote device. public class StateObject { // Client socket. public Socket workSocket = null; // Size of receive buffer. public const int BufferSize = 256; // Receive buffer. public byte[] buffer = new byte[BufferSize]; // Received data string. public StringBuilder sb = new StringBuilder(); } }
26.842105
59
0.609804
[ "BSD-3-Clause" ]
jasinskib/Software_Engineering_2_ProjectGame
src/Common/Connection/StateObject.cs
512
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/DirectML.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.DirectX.UnitTests; /// <summary>Provides validation of the <see cref="DML_ACTIVATION_LINEAR_OPERATOR_DESC" /> struct.</summary> public static unsafe partial class DML_ACTIVATION_LINEAR_OPERATOR_DESCTests { /// <summary>Validates that the <see cref="DML_ACTIVATION_LINEAR_OPERATOR_DESC" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<DML_ACTIVATION_LINEAR_OPERATOR_DESC>(), Is.EqualTo(sizeof(DML_ACTIVATION_LINEAR_OPERATOR_DESC))); } /// <summary>Validates that the <see cref="DML_ACTIVATION_LINEAR_OPERATOR_DESC" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(DML_ACTIVATION_LINEAR_OPERATOR_DESC).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="DML_ACTIVATION_LINEAR_OPERATOR_DESC" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(DML_ACTIVATION_LINEAR_OPERATOR_DESC), Is.EqualTo(24)); } else { Assert.That(sizeof(DML_ACTIVATION_LINEAR_OPERATOR_DESC), Is.EqualTo(16)); } } }
38.953488
145
0.724179
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
tests/Interop/Windows/DirectX/um/DirectML/DML_ACTIVATION_LINEAR_OPERATOR_DESCTests.cs
1,677
C#
using System; using System.Windows.Forms; namespace BluetoothSerialServerTool { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { #if NETCOREAPP Application.SetHighDpiMode(HighDpiMode.SystemAware); #endif Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainForm()); } } }
24.043478
66
0.585895
[ "MIT" ]
tewarid/dotnet-tools
BluetoothSerialServerTool/Program.cs
555
C#
namespace StraightSql { using System; using System.Collections.Generic; using System.Threading.Tasks; public interface IContextualizedQuery : IQuery { Task<Boolean> AnyAsync(); Task<Int64> CountAsync(); Task ExecuteAsync(); Task<T> ExecuteScalarAsync<T>(); Task<T> FirstAsync<T>() where T : new(); Task<T> FirstAsync<T>(Func<IRow, T> reader); Task<T> FirstOrDefaultAsync<T>() where T : new(); Task<T> FirstOrDefaultAsync<T>(Func<IRow, T> reader); Task<IList<T>> ListAsync<T>() where T : new(); Task<IList<T>> ListAsync<T>(Func<IRow, T> reader); Task<T> SingleAsync<T>() where T : new(); Task<T> SingleAsync<T>(Func<IRow, T> reader); Task<T> SingleOrDefaultAsync<T>() where T : new(); Task<T> SingleOrDefaultAsync<T>(Func<IRow, T> reader); } }
31
57
0.66005
[ "MIT" ]
brendanjbaker/StraightSQL
src/StraightSql/IContextualizedQuery.cs
808
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.IO; using System.Diagnostics; using AssetStudio.Utils; namespace AssetStudio { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { //Single Instance var curProcess = Process.GetCurrentProcess(); foreach (var p in Process.GetProcessesByName(curProcess.ProcessName)) { if (p.Id != curProcess.Id) { if (args != null && args.Length > 0 && WinMsgUtil.SendMessage(p, args)) { return; } } } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); //Load files from commondline var form = new AssetStudioForm(); form.Show(); if (args != null && args.Length > 0) { if (Directory.Exists(args[0])) { form.LoadFolder(args[0]); } else if (File.Exists(args[0])) { form.LoadFiles( args.Where(x => !String.IsNullOrEmpty(x) && File.Exists(x)) .ToArray()); } } Application.Run(form); } } }
20.457627
72
0.604805
[ "MIT" ]
df32/AssetStudio
AssetStudio/Program.cs
1,209
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.DBforPostgreSQL.V20171201Preview { public static class GetServerSecurityAlertPolicy { /// <summary> /// A server security alert policy. /// </summary> public static Task<GetServerSecurityAlertPolicyResult> InvokeAsync(GetServerSecurityAlertPolicyArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetServerSecurityAlertPolicyResult>("azure-native:dbforpostgresql/v20171201preview:getServerSecurityAlertPolicy", args ?? new GetServerSecurityAlertPolicyArgs(), options.WithVersion()); } public sealed class GetServerSecurityAlertPolicyArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the resource group that contains the resource. You can obtain this value from the Azure Resource Manager API or the portal. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the security alert policy. /// </summary> [Input("securityAlertPolicyName", required: true)] public string SecurityAlertPolicyName { get; set; } = null!; /// <summary> /// The name of the server. /// </summary> [Input("serverName", required: true)] public string ServerName { get; set; } = null!; public GetServerSecurityAlertPolicyArgs() { } } [OutputType] public sealed class GetServerSecurityAlertPolicyResult { /// <summary> /// Specifies an array of alerts that are disabled. Allowed values are: Sql_Injection, Sql_Injection_Vulnerability, Access_Anomaly /// </summary> public readonly ImmutableArray<string> DisabledAlerts; /// <summary> /// Specifies that the alert is sent to the account administrators. /// </summary> public readonly bool? EmailAccountAdmins; /// <summary> /// Specifies an array of e-mail addresses to which the alert is sent. /// </summary> public readonly ImmutableArray<string> EmailAddresses; /// <summary> /// Fully qualified resource ID for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} /// </summary> public readonly string Id; /// <summary> /// The name of the resource /// </summary> public readonly string Name; /// <summary> /// Specifies the number of days to keep in the Threat Detection audit logs. /// </summary> public readonly int? RetentionDays; /// <summary> /// Specifies the state of the policy, whether it is enabled or disabled. /// </summary> public readonly string State; /// <summary> /// Specifies the identifier key of the Threat Detection audit storage account. /// </summary> public readonly string? StorageAccountAccessKey; /// <summary> /// Specifies the blob storage endpoint (e.g. https://MyAccount.blob.core.windows.net). This blob storage will hold all Threat Detection audit logs. /// </summary> public readonly string? StorageEndpoint; /// <summary> /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" /// </summary> public readonly string Type; [OutputConstructor] private GetServerSecurityAlertPolicyResult( ImmutableArray<string> disabledAlerts, bool? emailAccountAdmins, ImmutableArray<string> emailAddresses, string id, string name, int? retentionDays, string state, string? storageAccountAccessKey, string? storageEndpoint, string type) { DisabledAlerts = disabledAlerts; EmailAccountAdmins = emailAccountAdmins; EmailAddresses = emailAddresses; Id = id; Name = name; RetentionDays = retentionDays; State = state; StorageAccountAccessKey = storageAccountAccessKey; StorageEndpoint = storageEndpoint; Type = type; } } }
37.110236
239
0.634203
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/DBforPostgreSQL/V20171201Preview/GetServerSecurityAlertPolicy.cs
4,713
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace DSCMS.Views.Invoice { public partial class InvoiceGenarator { } }
24.944444
81
0.423163
[ "Apache-2.0" ]
Ruke45/DManagement
DSCMS/DSCMS/Views/Invoice/InvoiceGenarator.aspx.designer.cs
451
C#
using System; using System.Reactive.Concurrency; using System.Reactive.Linq; using Stethoscope.Common; namespace Stethoscope.Log.Internal { /// <summary> /// Storage for log entries. /// </summary> public interface IRegistryStorage { /// <summary> /// Access the log entries stored in this, stored in the order of <see cref="SortAttribute"/> /// </summary> IQbservable<ILogEntry> Entries { get; } /// <summary> /// The number of logs stored within this storage. /// </summary> int Count { get; } /// <summary> /// The log attribute used to sort entries. /// </summary> LogAttribute SortAttribute { get; } /// <summary> /// Scheduler for retrieving logs from storage. /// </summary> IScheduler LogScheduler { get; set; } /// <summary> /// Add a new log entry, sorting by <see cref="SortAttribute"/>. If the attribute does not contain the attribute, the log might not be added to the storage container. If this is the case, an empty GUID will be returned. /// </summary> /// <param name="entry">The log entry to add.</param> /// <returns>The <see cref="Guid"/> that internally identifies the log entry. An empty GUID means that the log was not added.</returns> Guid AddLogSorted(ILogEntry entry); /// <summary> /// Removes all log entries from the storage container. /// </summary> void Clear(); //XXX: close/shutdown? } }
34.8
227
0.598978
[ "MIT" ]
rcmaniac25/stethoscope
stethoscope/StethoscopeLib/Sources/LogComponents/Internal/IRegistryStorage.cs
1,568
C#
//Copyright ?2014 Sony Computer Entertainment America LLC. See License.txt. namespace Sce.Atf.Dom { /// <summary> /// Primitive types for attributes</summary> public enum AttributeTypes { /// <summary> /// Boolean</summary> Boolean, /// <summary> /// Array of Boolean</summary> BooleanArray, /// <summary> /// Int8</summary> Int8, /// <summary> /// Array of Int8</summary> Int8Array, /// <summary> /// UInt8</summary> UInt8, /// <summary> /// Array of UInt8</summary> UInt8Array, /// <summary> /// Int16</summary> Int16, /// <summary> /// Array of Int16</summary> Int16Array, /// <summary> /// UInt16</summary> UInt16, /// <summary> /// Array of UInt16</summary> UInt16Array, /// <summary> /// Int32</summary> Int32, /// <summary> /// Array of Int32</summary> Int32Array, /// <summary> /// UInt32</summary> UInt32, /// <summary> /// Array of UInt32</summary> UInt32Array, /// <summary> /// Int64</summary> Int64, /// <summary> /// Array of Int64</summary> Int64Array, /// <summary> /// UInt64</summary> UInt64, /// <summary> /// Array of UInt64</summary> UInt64Array, /// <summary> /// Single</summary> Single, /// <summary> /// Array of Single</summary> SingleArray, /// <summary> /// Double</summary> Double, /// <summary> /// Array of Double</summary> DoubleArray, /// <summary> /// Decimal</summary> Decimal, /// <summary> /// Array of Decimal</summary> DecimalArray, /// <summary> /// String</summary> String, /// <summary> /// Array of String</summary> StringArray, /// <summary> /// DateTime</summary> DateTime, /// <summary> /// NameString</summary> NameString, /// <summary> /// Uri</summary> Uri, /// <summary> /// Reference to another DOM node</summary> Reference, } }
19.838462
76
0.42342
[ "Apache-2.0" ]
blue3k/ATFClone
Framework/Atf.Core/Dom/AttributeTypes.cs
2,450
C#
using Microsoft.Extensions.DependencyInjection; using System; using System.Collections.Generic; using System.Text; namespace Chic.Core.Dependency { public interface IIocRegistrar { void RegisterSingleton<TService>() where TService : class; void RegisterSingleton(Type serviceType); void RegisterSingleton<TService, TImplementation>() where TService : class where TImplementation : class, TService; void RegisterSingleton(Type serviceType, Func<IServiceProvider, object> implementationFactory); void RegisterSingleton(Type serviceType, Type implementationType); void RegisterTransient<TService>() where TService : class; void RegisterTransient(Type serviceType); void RegisterTransient<TService, TImplementation>() where TService : class where TImplementation : class, TService; void RegisterTransient(Type serviceType, Func<IServiceProvider, object> implementationFactory); void RegisterTransient(Type serviceType, Type implementationType); bool IsRegistered(Type type); bool IsRegistered<TType>(); } }
30.432432
123
0.742451
[ "Apache-2.0" ]
huhouhua/Chic
src/Chic.Core/Dependency/IIocRegistrar.cs
1,128
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AutoMapper; using Crews.API.Data; using Crews.API.Data.Entities; using Crews.API.Models; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Logging; namespace Crews.API.Controllers; [ApiController] [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)] //[Route("api/v{version:apiVersion}/crews/{crewId:int}/[controller]")] [Route("api/crews/{crewId:int}/[controller]")] public class TrainingsController : ControllerBase { private readonly IMapper _mapper; private readonly IOneCrewRepository _repository; private readonly ILogger<TrainingsController> _logger; private readonly LinkGenerator _linkGenerator; public TrainingsController(IOneCrewRepository repository, IMapper mapper, ILogger<TrainingsController> logger, LinkGenerator linkGenerator) { _mapper = mapper; _logger = logger; _repository = repository; _linkGenerator = linkGenerator; } [HttpGet("{id:int}")] public async Task<ActionResult<TrainingViewModel>> GetTraining(int crewId, int id) { try { var training = await _repository.GetTrainingByCrewIdAsync(crewId, id); return training is not null ? Ok(_mapper.Map<TrainingViewModel>(training)) : NotFound(); } catch (Exception ex) { _logger.LogError("Failed to read training. {0}", ex); return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } [HttpGet] public async Task<ActionResult<IEnumerable<TrainingViewModel>>> GetCrewTrainings(int crewId) { try { var trainings = await _repository.GetTrainingsByCrewIdAsync(crewId); var viewModels = _mapper.Map<IEnumerable<TrainingViewModel>>(trainings); return viewModels.Any() ? Ok(viewModels) : NotFound(); } catch (Exception ex) { _logger.LogError("Failed to get trainings: {0}", ex); return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } [HttpPost] [Authorize(Policy = "CanAddTraining")] public async Task<IActionResult> Insert(int crewId, TrainingViewModel vm) { try { if (!ModelState.IsValid) return BadRequest("Can't Save"); var crew = await _repository.GetCrewByIdAsync(crewId, includeTrainings: true); if (crew is null) return BadRequest("Crew does not exist"); var training = crew.Trainings.FirstOrDefault(t => t.Id == vm.Id); if (training is null) { training = _mapper.Map<Training>(vm); training.Crew = crew; _repository.AddOrUpdate(training); } else { training = _mapper.Map(vm, training); } await _repository.SaveChangesAsync(); var location = _linkGenerator.GetPathByAction(HttpContext, "GetTraining", values: new { crewId, id = training.Id }); return Created(location, _mapper.Map<TrainingViewModel>(training)); } catch (Exception ex) { _logger.LogError("Failed to insert Training. {0}", ex); return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } [HttpPut("{id:int}")] [Authorize(Policy = "CanAddTraining")] public async Task<ActionResult<TrainingViewModel>> Update(int crewId, int id, TrainingViewModel model) { try { if (!ModelState.IsValid) return BadRequest("Can't Save"); var crew = await _repository.GetCrewByIdAsync(crewId, includeTrainings: true); if (crew is null) return BadRequest("Crew does not exist"); var training = crew.Trainings.FirstOrDefault(t => t.Id == model.Id); if (training is null) { return NotFound("The training does not exist."); } training = _mapper.Map(model, training); await _repository.SaveChangesAsync(); return Ok(_mapper.Map<TrainingViewModel>(training)); } catch (Exception ex) { _logger.LogError("Failed to update Training. {0}", ex); return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } [HttpDelete("{id:int}")] [Authorize(Roles = "Admin")] public async Task<ActionResult<TrainingViewModel>> Delete(int crewId, int id) { try { var training = await _repository.GetTrainingByCrewIdAsync(crewId, id); if (training is null) { return NotFound("The training does not exist."); } _repository.Delete(training); await _repository.SaveChangesAsync(); return Ok(); } catch (Exception ex) { _logger.LogError("Failed to delete Training. {0}", ex); return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } } }
32.593939
143
0.627371
[ "MIT" ]
SeRgI1982/PlaygroundAPI
src/Crews.API/Controllers/TrainingsController.cs
5,380
C#
using CueGen.Analysis; using System; using System.Collections.Generic; using System.Text; namespace CueGen { public class CuePoint { public double Time { get; set; } public string Name { get; set; } public int Energy { get; set; } public PhraseEntry Phrase { get; set; } } }
20.0625
47
0.629283
[ "MIT" ]
mganss/CueGen
CueGen/CuePoint.cs
323
C#
using System.Threading.Tasks; using Box.V2.Models; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Box.V2.Test.Integration { [TestClass] public class BoxCommentsManagerTestIntegration : BoxResourceManagerTestIntegration { [TestMethod] public async Task CommentsWorkflow_LiveSession_ValidResponse() { const string FileId = "16894947279"; const string Message = "this is a test Comment"; // Create a comment with message var addReq = new BoxCommentRequest() { Message = Message, Item = new BoxRequestEntity() { Id = FileId, Type = BoxType.file } }; BoxComment c = await Client.CommentsManager.AddCommentAsync(addReq); Assert.AreEqual(FileId, c.Item.Id, "Comment was added to incorrect file"); Assert.AreEqual(BoxType.file.ToString(), c.Item.Type, "Comment was not added to a file"); Assert.AreEqual(BoxType.comment.ToString(), c.Type, "Returned object is not a comment"); Assert.AreEqual(Message, c.Message, "Wrong comment added to file"); // Create a comment with tagged message var messageWithTag = "this is an tagged @[215917383:DisplayName] test comment"; var addReqWithTag = new BoxCommentRequest() { Message = messageWithTag, Item = new BoxRequestEntity() { Id = FileId, Type = BoxType.file } }; BoxComment cWithTag = await Client.CommentsManager.AddCommentAsync(addReqWithTag); Assert.AreEqual(FileId, cWithTag.Item.Id, "Comment was added to incorrect file"); Assert.AreEqual(BoxType.file.ToString(), cWithTag.Item.Type, "Comment was not added to a file"); Assert.AreEqual(BoxType.comment.ToString(), cWithTag.Type, "Returned object is not a comment"); Assert.AreEqual(messageWithTag, cWithTag.Message, "Wrong comment added to file"); // Get comment details BoxComment cInfo = await Client.CommentsManager.GetInformationAsync(c.Id); Assert.AreEqual(c.Id, cInfo.Id, "two comment objects have different ids"); Assert.AreEqual(BoxType.comment.ToString(), cInfo.Type, "returned object is not a comment"); // Update the comment const string UpdateMessage = "this is an updated test comment"; var updateReq = new BoxCommentRequest() { Message = UpdateMessage }; BoxComment cUpdate = await Client.CommentsManager.UpdateAsync(c.Id, updateReq); Assert.AreEqual(c.Id, cUpdate.Id, "Wrong comment was updated"); Assert.AreEqual(BoxType.comment.ToString(), cUpdate.Type, "returned type of update is not a comment"); Assert.AreEqual(UpdateMessage, cUpdate.Message, "Comment was not updated with correct string"); // Deleting a comment var success = await Client.CommentsManager.DeleteAsync(c.Id); Assert.AreEqual(true, success, "Unsuccessful comment delete"); } } }
41.765432
115
0.594443
[ "Apache-2.0" ]
box/box-windows-sdk-v2
Box.V2.Test.Integration/BoxCommentsManagerTestIntegration.cs
3,383
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Blish_HUD.Controls { public class Menu : Container, IMenuItem { private const int DEFAULT_ITEM_HEIGHT = 32; #region Load Static private static readonly Texture2D _textureMenuItemFade; static Menu() { _textureMenuItemFade = Content.GetTexture("156044"); } #endregion #region Events public event EventHandler<ControlActivatedEventArgs> ItemSelected; protected virtual void OnItemSelected(ControlActivatedEventArgs e) { this.ItemSelected?.Invoke(this, e); } #endregion protected int _menuItemHeight = DEFAULT_ITEM_HEIGHT; public int MenuItemHeight { get => _menuItemHeight; set { if (!SetProperty(ref _menuItemHeight, value)) return; foreach (var childMenuItem in _children.Cast<IMenuItem>()) { childMenuItem.MenuItemHeight = value; } } } protected bool _shouldShift = false; public bool ShouldShift { get => _shouldShift; set => SetProperty(ref _shouldShift, value, true); } private bool _canSelect; public bool CanSelect { get => _canSelect; set => SetProperty(ref _canSelect, value); } bool IMenuItem.Selected => false; private MenuItem _selectedMenuItem; public MenuItem SelectedMenuItem => _selectedMenuItem; void IMenuItem.Select() { throw new InvalidOperationException($"The root {nameof(Menu)} instance can not be selected."); } public void Select(MenuItem menuItem, List<IMenuItem> itemPath) { if (!_canSelect) { itemPath.ForEach(i => i.Deselect()); return; } foreach (var item in this.GetDescendants().Cast<IMenuItem>().Except(itemPath)) { item.Deselect(); } _selectedMenuItem = menuItem; OnItemSelected(new ControlActivatedEventArgs(menuItem)); } public void Select(MenuItem menuItem) { menuItem.Select(); } void IMenuItem.Deselect() { Select(null, null); } protected override void OnResized(ResizedEventArgs e) { foreach (var childMenuItem in _children) { childMenuItem.Width = e.CurrentSize.X; } base.OnResized(e); } protected override void OnChildAdded(ChildChangedEventArgs e) { if (!(e.ChangedChild is IMenuItem newChild)) { e.Cancel = true; return; } newChild.MenuItemHeight = this.MenuItemHeight; e.ChangedChild.Width = this.Width; // We'll bind the top of the control to the bottom of the last control we added var lastItem = _children.LastOrDefault(); if (lastItem != null) { Adhesive.Binding.CreateOneWayBinding(() => e.ChangedChild.Top, () => lastItem.Bottom, applyLeft: true); } ShouldShift = e.ResultingChildren.Any(mi => { MenuItem cmi = (MenuItem) mi; return cmi.CanCheck || cmi.Icon != null || cmi.Children.Any(); }); base.OnChildAdded(e); } public MenuItem AddMenuItem(string text, Texture2D icon = null) { return new MenuItem(text) { Icon = icon, Parent = this }; } public override void UpdateContainer(GameTime gameTime) { int totalItemHeight = 0; for (int i = 0; i < _children.Count; i++) { totalItemHeight = Math.Max(_children[i].Bottom, totalItemHeight); } this.Height = totalItemHeight; } public override void PaintBeforeChildren(SpriteBatch spriteBatch, Rectangle bounds) { // Draw items dark every other one for (int sec = 0; sec < _size.Y / MenuItemHeight; sec += 2) { spriteBatch.DrawOnCtrl(this, _textureMenuItemFade, new Rectangle(0, MenuItemHeight * sec - VerticalScrollOffset, _size.X, MenuItemHeight), Color.Black * 0.7f); } } } }
32.269737
116
0.520285
[ "MIT" ]
Archomeda/Blish-HUD
Blish HUD/Controls/Menu.cs
4,907
C#
using System; using Windows.System; using Windows.UI.Xaml.Media; namespace Windows.UI.Xaml { partial class UIElement { #if __NETSTD__ internal bool IsInLiveTree => IsLoading || IsLoaded; #elif __ANDROID__ internal bool IsInLiveTree => base.IsAttachedToWindow; #elif __IOS__ || __MACOS__ internal bool IsInLiveTree => base.Window != null; #else internal bool IsInLiveTree => throw new NotSupportedException(); #endif #if !__NETSTD__ internal void RemoveChild(UIElement viewToRemove) => VisualTreeHelper.RemoveChild(this, viewToRemove); internal void AddChild(UIElement viewToAdd) => VisualTreeHelper.AddChild(this, viewToAdd); internal UIElement ReplaceChild(int index, UIElement viewToRemove) => VisualTreeHelper.ReplaceChild(this, index, viewToRemove); #endif #if !HAS_UNO_WINUI // This is to ensure forward compatibility with WinUI private protected DispatcherQueue DispatcherQueue => DispatcherQueue.GetForCurrentThread(); #endif } }
29.212121
129
0.786307
[ "Apache-2.0" ]
AnthonyDParkhurst/uno
src/Uno.UI/UI/Xaml/UIElement.MuxInternal.cs
966
C#
using FakeViewModels.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace FakeViewModels.Core { public static class ViewModelFactory { #region public methods public static T CreateFakeViewModel<T>() where T : IViewModel, new() { T fakeViewModel = new T(); fakeViewModel.SetFakeData(); return fakeViewModel; } #endregion #region non-public methods private static string CreateLoremPixelUrl(FakeDataAttribute fakeDataAttribute) { FakeImageAttribute fakeImageAttribute = fakeDataAttribute as FakeImageAttribute; string imageUrl = null; if (fakeDataAttribute != null) { int imageWidth = fakeImageAttribute.Width ?? 500; int imageHeight = fakeImageAttribute.Height ?? 500; imageUrl = GetLoremPixelImageUrl(fakeImageAttribute.ImageType, imageWidth, imageHeight); } return imageUrl; } private static string GetLoremPixelImageUrl(FakeImageType fakeImageType, int imageWidth, int imageHeight) { Guid guid = Guid.NewGuid(); string loremPixelBaseUrl = "http://lorempixel.com"; string imageTypeString = fakeImageType.ToString().ToLower(); string imageUrl = $"{loremPixelBaseUrl}/{imageWidth}/{imageHeight}/{imageTypeString}?ignore={guid}"; return imageUrl; } private static bool HasDefaultConstructor(this Type type) { bool hasDefaultConstructor = type.GetTypeInfo().IsValueType || (type.GetConstructor(Type.EmptyTypes) != null); return hasDefaultConstructor; } private static bool IsGenericCollectionType(this Type type) { Type genericCollectionType = (from interfaceType in type.GetInterfaces() where interfaceType.GetTypeInfo().IsGenericType && (interfaceType.GetGenericTypeDefinition() == typeof(ICollection<>)) select interfaceType).FirstOrDefault(); bool isGenericCollectionType = genericCollectionType != null; return isGenericCollectionType; } private static void SetFakeData(this object instance, int level = 0) { Type viewModelType = instance.GetType(); foreach (PropertyInfo propertyInfo in viewModelType.GetProperties()) { Type propertyType = propertyInfo.PropertyType; TypeInfo propertyTypeInfo = propertyInfo.PropertyType.GetTypeInfo(); if (propertyType == typeof(string)) { instance.SetFakeStringProperty(propertyInfo); } else if (propertyTypeInfo.IsValueType) { instance.SetFakeValueProperty(propertyInfo); } else if (propertyType.IsGenericCollectionType()) { instance.SetFakeCollectionProperty(propertyInfo); } else if (propertyType.HasDefaultConstructor() && (level < 2)) { object innerInstance = Activator.CreateInstance(propertyType); innerInstance.SetFakeData(level + 1); } } } private static void SetFakeCollectionProperty(this object instance, PropertyInfo propertyInfo) { Type propertyType = propertyInfo.PropertyType; Type itemType = propertyType.GetGenericArguments().First(); MethodInfo addMethodInfo = propertyType.GetMethod(nameof(ICollection<object>.Add)); int itemCount = propertyInfo.GetCustomAttribute<FakeCollectionAttribute>()?.ItemCount ?? 10; if (propertyType.HasDefaultConstructor() && itemType.HasDefaultConstructor() && (addMethodInfo != null)) { object collection = Activator.CreateInstance(propertyType); for (int i = 0; i < itemCount; i++) { object item = Activator.CreateInstance(itemType); item.SetFakeData(); addMethodInfo.Invoke(collection, new[] { item }); } propertyInfo.SetValue(instance, collection); } } private static void SetFakeDateProperty(this object instance, PropertyInfo propertyInfo) { FakeDateAttribute fakeDateAttribute = propertyInfo.GetCustomAttribute<FakeDateAttribute>(); if (fakeDateAttribute != null) { FakeDateType dateType = fakeDateAttribute.DateType; switch (dateType) { case FakeDateType.Birthday: { propertyInfo.SetValue(instance, Faker.Date.Birthday()); break; } case FakeDateType.Future: { propertyInfo.SetValue(instance, Faker.Date.Between(DateTime.Now, DateTime.MaxValue)); break; } case FakeDateType.Past: { propertyInfo.SetValue(instance, Faker.Date.Between(DateTime.MinValue, DateTime.Now)); break; } } } else { propertyInfo.SetValue(instance, Faker.Date.Between(DateTime.MinValue, DateTime.Now)); } } public static void SetFakeStringProperty(this object instance, PropertyInfo propertyInfo) { FakeDataAttribute fakeDataAttribute = propertyInfo.GetCustomAttributes<FakeDataAttribute>().FirstOrDefault(); if (fakeDataAttribute is FakeImageAttribute) { string imageUrl = CreateLoremPixelUrl(fakeDataAttribute); propertyInfo.SetValue(instance, imageUrl); } else if (fakeDataAttribute is FakeNameAttribute) { FakeNameAttribute fakeNameAttribute = fakeDataAttribute as FakeNameAttribute; propertyInfo.SetValue(instance, fakeNameAttribute.Name ?? Faker.Name.FullName()); } else { propertyInfo.SetValue(instance, String.Join(Environment.NewLine, Faker.Lorem.Paragraphs(5))); } } public static void SetFakeValueProperty(this object instance, PropertyInfo propertyInfo) { Type propertyType = propertyInfo.PropertyType; if (propertyType == typeof(decimal)) { propertyInfo.SetValue(instance, (decimal)Faker.RandomNumber.NextDouble()); } else if (propertyType == typeof(DateTime)) { instance.SetFakeDateProperty(propertyInfo); } } #endregion } }
38.578378
160
0.57349
[ "MIT" ]
Ollienntsh/FakeViewModels
FakeViewModels/Core/ViewModelFactory.cs
7,139
C#
using System; using System.Collections.Generic; using System.Reflection; using DynamicTimelineFramework.Core; using DynamicTimelineFramework.Objects; using DynamicTimelineFramework.Objects.Attributes; namespace DynamicTimelineFramework.Internal { internal class SprigManager { public Spine Spine { get; } public int ObjectCount { get; private set; } public int UniverseCount { get; private set; } public readonly Multiverse Owner; public SprigManager(Diff rootDiff, Universe rootUniverse) { Spine = new Spine(rootDiff, rootUniverse); rootUniverse.Sprig.Manager = this; Owner = rootUniverse.Multiverse; UniverseCount++; } public Sprig BuildSprig(Diff diff) { var newSprig = Spine.AddBranch(diff.GetDiffChain()); newSprig.Manager = this; diff.InstallChanges(newSprig); UniverseCount++; return newSprig; } public void RegisterObject(DTFObject obj, out int referenceHash) { //Root the object in the root universe Owner.BaseUniverse.RootObject(obj); ObjectCount++; referenceHash = ObjectCount ^ 397; Owner.ClearPendingDiffs(); } public void UnregisterDiff(Diff diff) { //Remove the branch from the spine Spine.RemoveBranch(diff.GetDiffChain()); UniverseCount--; } } }
26.762712
72
0.589614
[ "MIT" ]
CrockettScience/Dynamic-Timeline-Framework-2
DynamicTimelineFramework/Internal/SprigManager.cs
1,579
C#
using Alpaca.Data.EFCore; using Alpaca.Data.Entities; using Alpaca.Infrastructure.Caching; using Alpaca.Infrastructure.Mapping; using Alpaca.Interfaces.Account.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Alpaca.Plugins.Account.OwnIntegration { public class UserMemoryCache { internal MemoryCache<int, UserModel> User { get; } = new MemoryCache<int, UserModel>(); internal MemoryCache<int, List<UserPermissionModel>> UserPermission { get; } = new MemoryCache<int, List<UserPermissionModel>>(); public UserMemoryCache(ADbContext dbContext) { var lstUser = dbContext.User.Where(u => !u.IsDeleted).ToList(); var mapperUser = new MapperWrapper<UserModel, User>(); lstUser.ForEach(u => { User.TryAdd(u.ID, id => mapperUser.GetModel(u)); }); var lstUserPermission = dbContext.UserPermission.Where(u => !u.IsDeleted).ToList(); var mapperUserPermission = new MapperWrapper<UserPermissionModel, UserPermission>(); lstUserPermission.GroupBy(up => up.UserID).ToList().ForEach(gup => { UserPermission.TryAdd(gup.Key, k => mapperUserPermission.GetModelList(gup.ToList())); }); } } }
35.102564
137
0.659606
[ "MIT" ]
doddgu/alpaca
src/Plugins/Account/Alpaca.Plugins.Account.OwnIntegration/UserMemoryCache.cs
1,371
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Foundatio.Jobs; using Foundatio.Messaging; using Foundatio.Queues; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Periscope.Core.Extensions; using Periscope.Data.Repositories; using Periscope.Events; using Periscope.Indexing.AddressIndexer.Host.Infrastructure.Jobs; namespace Periscope.Indexing.AddressIndexer.Host.Infrastructure.Hosting { public class AddressIndexerHost : BackgroundService { private readonly AddressRefresherJob _addressRefresherJob; private readonly AddressTransactedJob _addressTransactedJob; private readonly IMessageBus _bus; private readonly IQueue<AddressTransactedWorkItem> _queue; public AddressIndexerHost(ILoggerFactory loggerFactory, IMessageBus bus, IQueue<AddressTransactedWorkItem> queue, IAddressRepository addressRepository, AddressRefresherJob addressRefresherJob) { _bus = bus; _queue = queue; _addressTransactedJob = new AddressTransactedJob(_queue, loggerFactory, addressRepository); _addressRefresherJob = addressRefresherJob; } protected override async Task ExecuteAsync(CancellationToken stoppingToken) { List<Task> tasks = new() { _bus.SubscribeAsync<AddressesTransactedEvent>(async @event => { foreach (string address in @event.Addresses) { await _queue.EnqueueAsync(new AddressTransactedWorkItem {Address = address}).AnyContext(); } }, stoppingToken), _addressTransactedJob.RunContinuousAsync(cancellationToken: stoppingToken), _addressRefresherJob.RunContinuousAsync(TimeSpan.FromSeconds(15), cancellationToken: stoppingToken) }; await Task.WhenAll(tasks).AnyContext(); } } }
39.038462
121
0.693103
[ "Apache-2.0" ]
blocksentinel/periscope
src/Indexing/AddressIndexer/Host/Infrastructure/Hosting/AddressIndexerHost.cs
2,032
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Charlotte.Tools; namespace Charlotte.Optimizer.Utils { public class WrapCode { private static readonly string B64CODE_CHARS = StringTools.DECIMAL + StringTools.ALPHA + StringTools.alpha + "+/"; public string Wrap(string code) { code = CodeToBase64(code); char m = ArrayTools.Largest(B64CODE_CHARS .Where(v => code[0] != v && code[code.Length - 1] != v) // 2bs .Select(v => new { c = v, n = code.Where(w => w == v).Count() }), (a, b) => a.n - b.n).c; code = string.Join("" + m, code.Split(m).Reverse()); code = "var s=\"" + code + "\",m=\"" + m + "\";" + CodeEscape("eval(decodeURIComponent(escape(atob(s.split(m).reverse().join(m)))));"); return code; } private string CodeToBase64(string code) { for (; ; ) { string ret = new Base64Unit().Encode(Encoding.UTF8.GetBytes(code)); if (ret[ret.Length - 1] != '=') return ret; code += ' '; } } private string CodeEscape(string code) { StringBuilder buff = new StringBuilder(); foreach (char chr in code) { if ((StringTools.DECIMAL + StringTools.ALPHA + StringTools.alpha).Contains(chr)) buff.Append(string.Format("\\u{0:x4}", (int)chr)); else buff.Append(chr); } return buff.ToString(); } } }
22.459016
116
0.605839
[ "MIT" ]
stackprobe/Lunarwalk
Riot/Riot/Riot/Riot/Optimizer/Utils/WrapCode.cs
1,372
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Aws.CloudFront.Inputs { public sealed class CachePolicyParametersInCacheKeyAndForwardedToOriginCookiesConfigCookiesArgs : Pulumi.ResourceArgs { [Input("items")] private InputList<string>? _items; /// <summary> /// A list of item names (cookies, headers, or query strings). /// </summary> public InputList<string> Items { get => _items ?? (_items = new InputList<string>()); set => _items = value; } public CachePolicyParametersInCacheKeyAndForwardedToOriginCookiesConfigCookiesArgs() { } } }
29.71875
121
0.663512
[ "ECL-2.0", "Apache-2.0" ]
RafalSumislawski/pulumi-aws
sdk/dotnet/CloudFront/Inputs/CachePolicyParametersInCacheKeyAndForwardedToOriginCookiesConfigCookiesArgs.cs
951
C#
using System; using System.Xml.Serialization; using System.Collections.Generic; using Top.Api; namespace DingTalk.Api.Response { /// <summary> /// OapiSnsConversationInfoResponse. /// </summary> public class OapiSnsConversationInfoResponse : DingTalkResponse { /// <summary> /// 错误码 /// </summary> [XmlElement("errcode")] public long Errcode { get; set; } /// <summary> /// 错误信息 /// </summary> [XmlElement("errmsg")] public string Errmsg { get; set; } /// <summary> /// 结果数据 /// </summary> [XmlElement("result")] public SnsOpenGroupInfoResponseDomain Result { get; set; } /// <summary> /// 调用结果 /// </summary> [XmlElement("success")] public bool Success { get; set; } /// <summary> /// SnsOpenGroupInfoResponseDomain Data Structure. /// </summary> [Serializable] public class SnsOpenGroupInfoResponseDomain : TopObject { /// <summary> /// 群头像 /// </summary> [XmlElement("icon")] public string Icon { get; set; } /// <summary> /// 会话ID /// </summary> [XmlElement("open_conversation_id")] public string OpenConversationId { get; set; } /// <summary> /// 群主id /// </summary> [XmlElement("owner_unionid")] public string OwnerUnionid { get; set; } /// <summary> /// 机器人发消息地址 /// </summary> [XmlElement("robot_web_hook_url")] public string RobotWebHookUrl { get; set; } /// <summary> /// 模板id /// </summary> [XmlElement("template_id")] public string TemplateId { get; set; } /// <summary> /// 群名称 /// </summary> [XmlElement("title")] public string Title { get; set; } } } }
23.373494
67
0.513402
[ "MIT" ]
lee890720/YiShaAdmin
YiSha.Util/YsSha.Dingtalk/DingTalk/Response/OapiSnsConversationInfoResponse.cs
2,010
C#
// Inspector Gadgets // Copyright 2019 Kybernetik // // Assembly Definition files were introduced in Unity 2017.3. #if UNITY_2017_3_OR_NEWER using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("InspectorGadgets")] [assembly: AssemblyDescription("A variety of tools which enhance the Unity Editor.")] [assembly: AssemblyCompany("Kybernetik")] [assembly: AssemblyProduct("Inspector Gadgets Lite")] [assembly: AssemblyCopyright("Copyright © Kybernetik 2019")] [assembly: ComVisible(false)] [assembly: AssemblyVersion("1.0.0.0")] [assembly: SuppressMessage("Style", "IDE0016:Use 'throw' expression", Justification = "Not supported by older Unity versions.")] [assembly: SuppressMessage("Style", "IDE0018:Inline variable declaration", Justification = "Not supported by older Unity versions.")] [assembly: SuppressMessage("Style", "IDE0019:Use pattern matching", Justification = "Not supported by older Unity versions.")] [assembly: SuppressMessage("Style", "IDE0031:Use null propagation", Justification = "Not supported by older Unity versions.")] [assembly: SuppressMessage("Style", "IDE0034:Simplify 'default' expression", Justification = "Not supported by older Unity versions.")] [assembly: SuppressMessage("Style", "IDE0041:Use 'is null' check", Justification = "Not supported by older Unity versions.")] [assembly: SuppressMessage("Style", "IDE0044:Make field readonly", Justification = "Using the [SerializeField] attribute on a private field means Unity will set it from serialized data.")] [assembly: SuppressMessage("Code Quality", "IDE0051:Remove unused private members", Justification = "Unity messages can be private, but the IDE will not know that Unity can still call them.")] [assembly: SuppressMessage("Code Quality", "IDE0052:Remove unread private members", Justification = "Unity messages can be private and don't need to be called manually.")] [assembly: SuppressMessage("Style", "IDE0059:Value assigned to symbol is never used", Justification = "Inline variable declarations are not supported by older Unity versions.")] [assembly: SuppressMessage("Style", "IDE0060:Remove unused parameter", Justification = "Unity messages sometimes need specific signatures, even if you don't use all the parameters.")] [assembly: SuppressMessage("Style", "IDE1005:Delegate invocation can be simplified.", Justification = "Not supported by older Unity versions.")] // This suppression doesn't seem to actually work so we need to put #pragma warning disable in every file :( //[assembly: SuppressMessage("Code Quality", "CS0649:Field is never assigned to, and will always have its default value", // Justification = "Using the [SerializeField] attribute on a private field means Unity will set it from serialized data.")] #endif
59.604167
127
0.763719
[ "Apache-2.0" ]
EricVoll/RobotDynamicsLibrary
UnityExamples/RobotKinematics/Assets/Plugins/Inspector Gadgets/Misc/AssemblyInfo.cs
2,862
C#
using System; using System.Windows.Forms; namespace Tienda { public partial class FormMenu : Form { public FormMenu() { InitializeComponent(); } private void iniciarSesionToolStripMenuItem_Click(object sender, EventArgs e) { Login(); } private void Login() { foreach (Form childForm in MdiChildren) { childForm.Close(); } var formlogin = new FormLogin(); formlogin.ShowDialog(); if (Utilidades.UsuarioActual != null) { toolStripStatusLabel1.Text = "Usuario: " + Utilidades.UsuarioActual.Nombre; //mantCltesToolStripMenuItem.Visible = Utilidades.UsuarioActual.AccesaClientes; //mantProductosToolStripMenuItem.Visible = Utilidades.UsuarioActual.AccesaProductos; //facturasToolStripMenuItem.Visible = Utilidades.UsuarioActual.AccesaFacturas; //reportesToolStripMenuItem.Visible = Utilidades.UsuarioActual.AccesaReportes; usuariosToolStripMenuItem.Visible = Utilidades.UsuarioActual.UserAdmin; mantCltesToolStripMenuItem.Visible = Utilidades.UsuarioActual.AccesaClientes; mantProductosToolStripMenuItem.Visible = Utilidades.UsuarioActual.AccesaProductos; facturasToolStripMenuItem.Visible = Utilidades.UsuarioActual.AccesaFacturas; reportesToolStripMenuItem.Visible = Utilidades.UsuarioActual.AccesaReportes; //if (Utilidades.UsuarioActual.UserAdmin == true) //{ // usuariosToolStripMenuItem.Visible = true; //} //else //{ // usuariosToolStripMenuItem.Visible = Utilidades.UsuarioActual.UserAdmin; // mantCltesToolStripMenuItem.Visible = Utilidades.UsuarioActual.AccesaClientes; // mantProductosToolStripMenuItem.Visible = Utilidades.UsuarioActual.AccesaProductos; // facturasToolStripMenuItem.Visible = Utilidades.UsuarioActual.AccesaFacturas; // reportesToolStripMenuItem.Visible = Utilidades.UsuarioActual.AccesaReportes; //} } } private void ropaParaCaballeroToolStripMenuItem_Click(object sender, EventArgs e) { var formproductos_hombre = new FormTblCategorias(); formproductos_hombre.MdiParent = this; formproductos_hombre.Show(); } private void ropaParaNiñoToolStripMenuItem_Click(object sender, EventArgs e) { var formproductos_nino = new FormTblTiposPersonas(); formproductos_nino.MdiParent = this; formproductos_nino.Show(); } private void reporteDeInventarioToolStripMenuItem_Click(object sender, EventArgs e) { var formreporinventario = new FormReportInv(); formreporinventario.MdiParent = this; formreporinventario.Show(); } private void reporteDeClientesToolStripMenuItem_Click(object sender, EventArgs e) { var formreporcliente = new FormReporteClientes(); formreporcliente.MdiParent = this; formreporcliente.Show(); } private void reporteDeErroresToolStripMenuItem_Click(object sender, EventArgs e) { var formreporterror = new FormTBLTipoProd(); formreporterror.MdiParent = this; formreporterror.Show(); } private void administrarBaseDeDatosToolStripMenuItem_Click(object sender, EventArgs e) { var formadmbase = new FormAdminBD(); formadmbase.MdiParent = this; formadmbase.Show(); } private void formmenu_Load(object sender, EventArgs e) { Login(); } private void horizontalToolStripMenuItem_Click(object sender, EventArgs e) { LayoutMdi(MdiLayout.TileHorizontal); } private void verticalToolStripMenuItem_Click(object sender, EventArgs e) { LayoutMdi(MdiLayout.TileVertical); } private void cascadaToolStripMenuItem_Click(object sender, EventArgs e) { LayoutMdi(MdiLayout.Cascade); } private void cerrarTodoToolStripMenuItem_Click(object sender, EventArgs e) { foreach (Form childForm in MdiChildren) { childForm.Close(); } } private void reporteDeErroresToolStripMenuItem1_Click(object sender, EventArgs e) { var formreporterror = new FormTBLTipoProd(); formreporterror.MdiParent = this; formreporterror.Show(); } private void salirToolStripMenuItem_Click(object sender, EventArgs e) { Application.Exit(); } private void mantProductosToolStripMenuItem_Click(object sender, EventArgs e) { var formproductos = new FormProductos(); formproductos.MdiParent = this; formproductos.Show(); } private void mantCltesToolStripMenuItem_Click(object sender, EventArgs e) { var formclientes = new FormClientes(); formclientes.MdiParent = this; formclientes.Show(); } private void facturasToolStripMenuItem_Click(object sender, EventArgs e) { var formfacturas = new FormFacturas(); formfacturas.MdiParent = this; formfacturas.Show(); } private void reporteDeProductosToolStripMenuItem_Click(object sender, EventArgs e) { var formReporteProductos = new FormReporteProductos(); formReporteProductos.MdiParent = this; formReporteProductos.Show(); } private void reporteDeFacturasToolStripMenuItem_Click(object sender, EventArgs e) { var formReporteFacturas = new FormReporteFacturas(); formReporteFacturas.MdiParent = this; formReporteFacturas.Show(); } private void usuariosToolStripMenuItem_Click(object sender, EventArgs e) { var formUsuarios = new FormUsuarios(); formUsuarios.MdiParent = this; formUsuarios.Show(); } } }
35.657754
105
0.597031
[ "MIT" ]
marinaponce07/Dulce-Paraiso
FormMenu.cs
6,671
C#
//----------------------------------------------------------------------------- // Text.cs // // Spooker Open Source Game Framework // Copyright (C) Indie Armory. All rights reserved. // Website: http://indiearmory.com // Other Contributors: Laurent Gomila @ http://sfml-dev.org, omeg // License: MIT //----------------------------------------------------------------------------- using System; namespace Spooker.Graphics { /// <summary> /// Text. /// </summary> public class Text : Transformable, IDrawable { [Flags] public enum Styles : byte { /// <summary>Regular characters, no style</summary> Regular = 0, /// <summary> Characters are bold</summary> Bold = 1 << 0, /// <summary>Characters are in italic</summary> Italic = 1 << 1, /// <summary>Characters are underlined</summary> Underlined = 1 << 2 } #region Private fields private bool _needsUpdate; private string _displayedString; private int _characterSize; private Vector2 _size; private Font _font; #endregion #region Public fields public Color Color; public Styles Style; #endregion #region Properties public string DisplayedString { get { return _displayedString; } set { _displayedString = value; _needsUpdate = true; } } public int CharacterSize { get { return _characterSize; } set { _characterSize = value; _needsUpdate = true; } } public Font Font { get { return _font; } set { _font = value; _needsUpdate = true; } } public Vector2 Size { get { if (_needsUpdate) { if (Environment.OSVersion.Platform != PlatformID.Win32NT) if (_displayedString[_displayedString.Length - 1] != '\0') _displayedString += '\0'; var extents = new Point (0, Font.LineSpacing (CharacterSize)); foreach (var cur in DisplayedString) { if (cur == '\n' || cur == '\v') continue; extents.X += Font.Glyph(CharacterSize, cur, false).Advance; } _size = new Vector2 (extents.X, extents.Y); _needsUpdate = false; } return _size; } } public Rectangle DestRect { get { return new Rectangle ( (int)Position.X, (int)Position.Y, (int)Size.X, (int)Size.Y); } } #endregion #region Constructors public Text (Text copy) : base(copy) { DisplayedString = copy.DisplayedString; CharacterSize = copy.CharacterSize; Font = new Font(copy.Font); Color = new Color(copy.Color); Style = copy.Style; } public Text (Font font) { Font = new Font (font); Color = Color.White; Style = Styles.Regular; } #endregion #region Public methods public void Draw(SpriteBatch spriteBatch, SpriteEffects effects) { spriteBatch.Draw ( Font, DisplayedString, CharacterSize, Position, Color, Scale, Origin, Rotation, Style, effects); } #endregion } }
19.145695
79
0.601522
[ "MIT" ]
codeindie/spooker
Source/Graphics/Text.cs
2,891
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ChainOfResponsibilityPattern.Observable { public class ObserverOne : IObserver { public void Onnotify(string message) { Console.WriteLine($"ObserverOne got the message: {message}"); } } }
21.411765
73
0.68956
[ "MIT" ]
ParallelTask/DesignPatterns
ChainOfResponsibilityPattern/ChainOfResponsibilityPattern/Observable/ObserverOne.cs
366
C#
using System; using System.Linq; using System.Web.Mvc; using System.Web.Mvc.Html; using BeyondThemes.Bootstrap.ControlModels; using BeyondThemes.Bootstrap.Controls; using BeyondThemes.Bootstrap.Infrastructure; using BeyondThemes.Bootstrap.TypeExtensions; namespace BeyondThemes.Bootstrap.Renderers { internal static partial class Renderer { public static string RenderTextBox(HtmlHelper html, BootstrapTextBoxModel model, bool isPassword) { var combinedHtml = "{0}{1}{2}"; model.htmlAttributes.MergeHtmlAttributes(html.GetUnobtrusiveValidationAttributes(model.htmlFieldName, model.metadata)); model.htmlAttributes.AddOrMergeCssClass("class", "form-control"); if (!string.IsNullOrEmpty(model.id)) model.htmlAttributes.Add("id", model.id); if (model.tooltipConfiguration != null) model.htmlAttributes.MergeHtmlAttributes(model.tooltipConfiguration.ToDictionary()); if (model.tooltip != null) model.htmlAttributes.MergeHtmlAttributes(model.tooltip.ToDictionary()); if (model.typehead != null) model.htmlAttributes.MergeHtmlAttributes(model.typehead.ToDictionary(html)); // assign placeholder class if (!string.IsNullOrEmpty(model.placeholder)) model.htmlAttributes.Add("placeholder", model.placeholder); // assign size class model.htmlAttributes.AddOrMergeCssClass("class", BootstrapHelper.GetClassForInputSize(model.size)); if (model.disabled) model.htmlAttributes.Add("disabled", "disabled"); var widthlg = ""; if (model.InputWidthLg != 0) { var width = model.InputWidthLg.ToString(); widthlg = " col-lg-" + width; } var widthMd = ""; if (model.InputWidthMd != 0) { var width = model.InputWidthMd.ToString(); widthMd = " col-md-" + width; } var widthSm = ""; if (model.InputWidthSm != 0) { var width = model.InputWidthSm.ToString(); widthSm = " col-sm-" + width; } var widthXs = ""; if (model.InputWidthXs != 0) { var width = model.InputWidthXs.ToString(); widthXs = " col-xs-" + width; } var offsetlg = ""; if (model.InputOffsetLg != 0) { var offset = model.InputOffsetLg.ToString(); offsetlg = " col-lg-offset-" + offset; } var offsetMd = ""; if (model.InputOffsetMd != 0) { var offset = model.InputOffsetMd.ToString(); offsetMd = " col-md-offset-" + offset; } var offsetSm = ""; if (model.InputOffsetSm != 0) { var offset = model.InputOffsetSm.ToString(); offsetSm = " col-sm-offset-" + offset; } var offsetXs = ""; if (model.InputOffsetXs != 0) { var offset = model.InputOffsetXs.ToString(); offsetXs = " col-xs-offset-" + offset; } var widthoffset = widthlg + widthMd + widthSm + widthXs + offsetlg + offsetMd + offsetSm + offsetXs; // account for appendString, prependString, and AppendButtons if (!string.IsNullOrEmpty(model.prependString) || !string.IsNullOrEmpty(model.appendString) || model.prependButtons.Any() || model.appendButtons.Any() || !string.IsNullOrEmpty(model.iconPrepend) || !string.IsNullOrEmpty(model.iconAppend) || !string.IsNullOrEmpty(model.iconPrependCustomClass) || !string.IsNullOrEmpty(model.iconAppendCustomClass) || !string.IsNullOrEmpty(widthoffset)) { var appendPrependContainer = new TagBuilder("div"); var addOnPrependString = ""; var addOnAppendString = ""; var addOnPrependButtons = ""; var addOnAppendButtons = ""; var addOnPrependIcon = ""; var addOnAppendIcon = ""; var addOn = new TagBuilder("span"); addOn.AddCssClass("input-group-addon"); if (!string.IsNullOrEmpty(model.prependString)) { appendPrependContainer.AddOrMergeCssClass("input-group"); addOn.InnerHtml = model.prependString; addOnPrependString = addOn.ToString(); } if (!string.IsNullOrEmpty(model.appendString)) { appendPrependContainer.AddOrMergeCssClass("input-group"); addOn.InnerHtml = model.appendString; addOnAppendString = addOn.ToString(); } if (model.prependButtons.Count > 0) { appendPrependContainer.AddOrMergeCssClass("input-group"); var span = new TagBuilder("span"); span.AddOrMergeCssClass("input-group-btn"); model.prependButtons.ForEach(x => addOnPrependButtons += x.ToHtmlString()); span.InnerHtml = addOnPrependButtons; addOnPrependButtons = span.ToString(); } if (model.appendButtons.Count > 0) { appendPrependContainer.AddOrMergeCssClass("input-group"); var span = new TagBuilder("span"); span.AddOrMergeCssClass("input-group-btn"); model.appendButtons.ForEach(x => addOnAppendButtons += x.ToHtmlString()); span.InnerHtml = addOnAppendButtons; addOnAppendButtons = span.ToString(); } if (!string.IsNullOrEmpty(model.iconPrepend)) { appendPrependContainer.AddOrMergeCssClass("input-icon icon-left"); addOnPrependIcon = new BootstrapIcon(model.iconPrepend, model.iconPrependIsWhite).HtmlAttributes(new { @class = model.prependIconStyle }).ToHtmlString(); } if (!string.IsNullOrEmpty(model.iconAppend)) { appendPrependContainer.AddOrMergeCssClass("input-icon icon-right"); addOnAppendIcon = new BootstrapIcon(model.iconAppend, model.iconAppendIsWhite).HtmlAttributes(new { @class = model.appendIconStyle }).ToHtmlString(); } if (!string.IsNullOrEmpty(model.iconPrependCustomClass)) { appendPrependContainer.AddOrMergeCssClass("input-prepend"); var i = new TagBuilder("i"); i.AddCssClass(model.iconPrependCustomClass); addOn.InnerHtml = i.ToString(TagRenderMode.Normal); addOnPrependIcon = addOn.ToString(); } if (!string.IsNullOrEmpty(model.iconAppendCustomClass)) { appendPrependContainer.AddOrMergeCssClass("input-append"); var i = new TagBuilder("i"); i.AddCssClass(model.iconAppendCustomClass); addOn.InnerHtml = i.ToString(TagRenderMode.Normal); addOnAppendIcon = addOn.ToString(); } appendPrependContainer.AddOrMergeCssClass(widthlg + widthMd + widthSm + widthXs); appendPrependContainer.AddOrMergeCssClass(offsetlg + offsetMd + offsetSm + offsetXs); switch (model.size) { case InputSize.XSmall: appendPrependContainer.AddOrMergeCssClass("input-group-xs"); break; case InputSize.Small: appendPrependContainer.AddOrMergeCssClass("input-group-sm"); break; case InputSize.Large: appendPrependContainer.AddOrMergeCssClass("input-group-lg"); break; case InputSize.XLarge: appendPrependContainer.AddOrMergeCssClass("input-group-xl"); break; } appendPrependContainer.InnerHtml = addOnPrependButtons + addOnPrependString + "{0}" + addOnPrependIcon + addOnAppendString + addOnAppendIcon + addOnAppendButtons + "{1}"; combinedHtml = appendPrependContainer.ToString(TagRenderMode.Normal) + "{2}"; } // build html for input var input = isPassword ? html.Password(model.htmlFieldName, null, model.htmlAttributes.FormatHtmlAttributes()).ToHtmlString() : html.TextBox(model.htmlFieldName, model.value, model.htmlAttributes.FormatHtmlAttributes()).ToHtmlString(); var helpText = model.helpText != null ? model.helpText.ToHtmlString() : string.Empty; var validationMessage = ""; if (model.displayValidationMessage) { var validation = html.ValidationMessage(model.htmlFieldName).ToHtmlString(); validationMessage = new BootstrapHelpText(validation, model.validationMessageStyle).ToHtmlString(); } return MvcHtmlString.Create(string.Format(combinedHtml, input, helpText, validationMessage)).ToString(); } } }
46.061905
186
0.558462
[ "Apache-2.0" ]
PooyaAlamirpour/SmartCattle
Themes.Bootstrap/Renderers/Renderer.TextBox.cs
9,675
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("SByteDev.Xamarin.Plugins.WebBrowser.Demo.iOS")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("CompanyName")] [assembly: AssemblyProduct("SByteDev.Xamarin.Plugins.WebBrowser.Demo.iOS")] [assembly: AssemblyCopyright("Copyright © CompanyName Year")] [assembly: AssemblyTrademark("CompanyTrademark")] [assembly: AssemblyCulture("")] [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("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.413793
84
0.755906
[ "MIT" ]
SByteDev/Net.Xamarin.Plugins.WebBrowser
SByteDev.Xamarin.Plugins.WebBrowser.Demo/SByteDev.Xamarin.Plugins.WebBrowser.Demo.iOS/Properties/AssemblyInfo.cs
1,146
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/urlmon.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="IWinInetHttpTimeouts" /> struct.</summary> public static unsafe class IWinInetHttpTimeoutsTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="IWinInetHttpTimeouts" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(IWinInetHttpTimeouts).GUID, Is.EqualTo(IID_IWinInetHttpTimeouts)); } /// <summary>Validates that the <see cref="IWinInetHttpTimeouts" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<IWinInetHttpTimeouts>(), Is.EqualTo(sizeof(IWinInetHttpTimeouts))); } /// <summary>Validates that the <see cref="IWinInetHttpTimeouts" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(IWinInetHttpTimeouts).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="IWinInetHttpTimeouts" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(IWinInetHttpTimeouts), Is.EqualTo(8)); } else { Assert.That(sizeof(IWinInetHttpTimeouts), Is.EqualTo(4)); } } } }
37.826923
145
0.644637
[ "MIT" ]
Ethereal77/terrafx.interop.windows
tests/Interop/Windows/um/urlmon/IWinInetHttpTimeoutsTests.cs
1,969
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Firestore.Admin.V1.Snippets { using Google.Cloud.Firestore.Admin.V1; using System.Threading.Tasks; public sealed partial class GeneratedFirestoreAdminClientStandaloneSnippets { /// <summary>Snippet for GetIndexAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task GetIndexResourceNamesAsync() { // Create client FirestoreAdminClient firestoreAdminClient = await FirestoreAdminClient.CreateAsync(); // Initialize request argument(s) IndexName name = IndexName.FromProjectDatabaseCollectionIndex("[PROJECT]", "[DATABASE]", "[COLLECTION]", "[INDEX]"); // Make the request Index response = await firestoreAdminClient.GetIndexAsync(name); } } }
39.875
128
0.695298
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/firestore/admin/v1/google-cloud-firestore-admin-v1-csharp/Google.Cloud.Firestore.Admin.V1.StandaloneSnippets/FirestoreAdminClient.GetIndexResourceNamesAsyncSnippet.g.cs
1,595
C#
using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using vtFrontend.GUI.Controls.ViewModels; using vtFrontend.lib.Parameters.Base; namespace vtFrontend.GUI.Controls { public partial class ParameterPanel : UserControl { public static readonly DependencyProperty ItemSourceProperty = DependencyProperty.Register(nameof(Parameters), typeof(List<BaseParameter>), typeof(ParameterPanel), new FrameworkPropertyMetadata(null, new PropertyChangedCallback(PropertyChangedCallback))); private static void PropertyChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e) { // } public List<BaseParameter> Parameters { set => SetValue(ItemSourceProperty, value); get => (List<BaseParameter>)GetValue(ItemSourceProperty); } public event EventHandler<BaseParameter> OnParameterValueChanged; private void InitializeControls() { foreach (var parameter in Parameters) { var cParameter = new ParameterControl(); // ((ParameterControlViewModel)cParameter.DataContext).Parameter = parameter; cParameter.OnParameterValueChanged += CParameterOnOnParameterValueChanged; spParameters.Children.Add(cParameter); } } // TODO: Replace this quick and dirty hack down the road private void CParameterOnOnParameterValueChanged(object? sender, BaseParameter e) => OnParameterValueChanged?.Invoke(null, e); public ParameterPanel() { InitializeComponent(); } } }
31.160714
112
0.662464
[ "MIT" ]
jcapellman/vtFrontend
vtFrontend.GUI/Controls/ParameterPanel.xaml.cs
1,747
C#
using System.Collections; using System.Collections.Generic; using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice.Attributes; using NetOffice.CollectionsGeneric; using NetOffice.OutlookApi; namespace NetOffice.OutlookApi.Behind { /// <summary> /// DispatchInterface _Inspectors /// SupportByVersion Outlook, 9,10,11,12,14,15,16 /// </summary> public class _Inspectors : COMObject, NetOffice.OutlookApi._Inspectors { #pragma warning disable #region Type Information /// <summary> /// Contract Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type ContractType { get { if(null == _contractType) _contractType = typeof(NetOffice.OutlookApi._Inspectors); return _contractType; } } private static Type _contractType; /// <summary> /// Instance Type /// </summary> [EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden] public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(_Inspectors); return _type; } } #endregion #region Ctor /// <summary> /// Stub Ctor, not indented to use /// </summary> public _Inspectors() : base() { } #endregion #region Properties /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff867446.aspx </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] [BaseResult] public virtual NetOffice.OutlookApi._Application Application { get { return InvokerService.InvokeInternal.ExecuteBaseReferencePropertyGet<NetOffice.OutlookApi._Application>(this, "Application"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff862164.aspx </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public virtual NetOffice.OutlookApi.Enums.OlObjectClass Class { get { return InvokerService.InvokeInternal.ExecuteEnumPropertyGet<NetOffice.OutlookApi.Enums.OlObjectClass>(this, "Class"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff863287.aspx </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] [BaseResult] public virtual NetOffice.OutlookApi._NameSpace Session { get { return InvokerService.InvokeInternal.ExecuteBaseReferencePropertyGet<NetOffice.OutlookApi._NameSpace>(this, "Session"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// Unknown COM Proxy /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff869115.aspx </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16), ProxyResult] public virtual object Parent { get { return InvokerService.InvokeInternal.ExecuteReferencePropertyGet(this, "Parent"); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// Get /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff869287.aspx </remarks> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] public virtual Int32 Count { get { return InvokerService.InvokeInternal.ExecuteInt32PropertyGet(this, "Count"); } } #endregion #region Methods /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <param name="index">object index</param> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item"), IndexProperty] public virtual NetOffice.OutlookApi.Inspector this[object index] { get { return InvokerService.InvokeInternal.ExecuteKnownReferenceMethodGet<NetOffice.OutlookApi.Inspector>(this, "Item", typeof(NetOffice.OutlookApi.Inspector), index); } } /// <summary> /// SupportByVersion Outlook 9, 10, 11, 12, 14, 15, 16 /// </summary> /// <remarks> MSDN Online: http://msdn.microsoft.com/en-us/en-us/library/office/ff870047.aspx </remarks> /// <param name="item">object item</param> [SupportByVersion("Outlook", 9,10,11,12,14,15,16)] [BaseResult] public virtual NetOffice.OutlookApi._Inspector Add(object item) { return InvokerService.InvokeInternal.ExecuteBaseReferenceMethodGet<NetOffice.OutlookApi._Inspector>(this, "Add", item); } #endregion #region IEnumerableProvider<NetOffice.OutlookApi.Inspector> ICOMObject IEnumerableProvider<NetOffice.OutlookApi.Inspector>.GetComObjectEnumerator(ICOMObject parent) { return this; } IEnumerable IEnumerableProvider<NetOffice.OutlookApi.Inspector>.FetchVariantComObjectEnumerator(ICOMObject parent, ICOMObject enumerator) { NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable); foreach (NetOffice.OutlookApi.Inspector item in innerEnumerator) yield return item; } #endregion #region IEnumerable<NetOffice.OutlookApi.Inspector> /// <summary> /// SupportByVersion Outlook, 9,10,11,12,14,15,16 /// This is a custom enumerator from NetOffice /// </summary> [SupportByVersion("Outlook", 9, 10, 11, 12, 14, 15, 16)] [CustomEnumerator] public virtual IEnumerator<NetOffice.OutlookApi.Inspector> GetEnumerator() { NetRuntimeSystem.Collections.IEnumerable innerEnumerator = (this as NetRuntimeSystem.Collections.IEnumerable); foreach (NetOffice.OutlookApi.Inspector item in innerEnumerator) yield return item; } #endregion #region IEnumerable /// <summary> /// SupportByVersion Outlook, 9,10,11,12,14,15,16 /// This is a custom enumerator from NetOffice /// </summary> [SupportByVersion("Outlook", 9, 10, 11, 12, 14, 15, 16)] [CustomEnumerator] IEnumerator NetRuntimeSystem.Collections.IEnumerable.GetEnumerator() { int count = Count; object[] enumeratorObjects = new object[count]; for (int i = 0; i < count; i++) enumeratorObjects[i] = this[i + 1]; foreach (object item in enumeratorObjects) yield return item; } #endregion #pragma warning restore } }
29.834711
165
0.652632
[ "MIT" ]
igoreksiz/NetOffice
Source/Outlook/Behind/DispatchInterfaces/_Inspectors.cs
7,222
C#
using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using Epi.Cloud.DataConsistencyServices.Models; namespace Epi.Cloud.DataConsistencyServices { // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application. public class ApplicationUserManager : UserManager<ApplicationUser> { public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store) { } public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) { var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>())); // Configure validation logic for usernames manager.UserValidator = new UserValidator<ApplicationUser>(manager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Configure validation logic for passwords manager.PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, }; var dataProtectionProvider = options.DataProtectionProvider; if (dataProtectionProvider != null) { manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity")); } return manager; } } }
39.73913
146
0.659737
[ "Apache-2.0" ]
82ndAirborneDiv/Epi-Info-Cloud-Contact-Tracing
Cloud Enter/Epi.Cloud.DataConsistencyServicesAPI/App_Start/IdentityConfig.cs
1,830
C#