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
sequence
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Promitor.Agents.Core; using Promitor.Agents.ResourceDiscovery.Extensions; using Promitor.Agents.ResourceDiscovery.Health; using Promitor.Agents.Scraper.Extensions; namespace Promitor.Agents.ResourceDiscovery { public class Startup : AgentStartup { private const string ApiName = "Promitor - Resource Discovery API"; private const string ApiDescription = "Collection of APIs to provide automatic resource discovery for scraping resources with Promitor Scraper"; private const string ComponentName = "Promitor Resource Discovery"; private const string PrometheusBaseUri = "/metrics"; /// <summary> /// Initializes a new instance of the <see cref="Startup" /> class. /// </summary> public Startup(IConfiguration configuration) : base(configuration) { } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.UseWebApi() .AddMemoryCache() .AddRuntimeConfiguration(Configuration) .AddAzureResourceGraph(Configuration) .AddBackgroundJobs(Configuration) .AddUsability() .UseOpenApiSpecifications($"{ApiName} v1", ApiDescription, 1) .AddValidationRules() .AddHttpCorrelation(options => options.UpstreamService.ExtractFromRequest = true) .AddPrometheusMetrics() .AddHealthChecks() .AddCheck<AzureResourceGraphHealthCheck>("azure-resource-graph", failureStatus: HealthStatus.Unhealthy); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseExceptionHandling(); app.UseRequestTracking(); app.UseHttpCorrelation(); app.UseVersionMiddleware(); app.UseRouting(); app.ExposeOpenApiUi(ApiName); app.UsePrometheusMetrics(PrometheusBaseUri, logger); app.UseEndpoints(endpoints => endpoints.MapControllers()); UseSerilog(ComponentName, app.ApplicationServices); } } }
42.318841
152
0.667123
[ "MIT" ]
smholvoet/promitor-docs-poc
src/Promitor.Agents.ResourceDiscovery/Startup.cs
2,922
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Generic; namespace Azure.AI.TextAnalytics { /// <summary> Determines the set of actions that will get executed on the input documents.</summary> public class TextAnalyticsActions { /// <summary> /// Optional display name for the analysis operation. /// </summary> public string DisplayName { get; set; } /// <summary> /// Extract KeyPhrases actions configurations. /// </summary> public IReadOnlyCollection<ExtractKeyPhrasesOptions> ExtractKeyPhrasesOptions { get; set; } /// <summary> /// Recognize Entities actions configurations. /// </summary> public IReadOnlyCollection<RecognizeEntitiesOptions> RecognizeEntitiesOptions { get; set; } /// <summary> /// Recognize PII Entities actions configurations. /// </summary> public IReadOnlyCollection<RecognizePiiEntitiesOptions> RecognizePiiEntitiesOptions { get; set; } /// <summary> /// Recognize Linked Entities actions configurations. /// </summary> public IReadOnlyCollection<RecognizeLinkedEntitiesOptions> RecognizeLinkedEntitiesOptions { get; set; } /// <summary> /// Analyze Sentiment actions configurations. /// </summary> public IReadOnlyCollection<AnalyzeSentimentOptions> AnalyzeSentimentOptions { get; set; } } }
35.97619
111
0.663799
[ "MIT" ]
hivyas/azure-sdk-for-ne
sdk/textanalytics/Azure.AI.TextAnalytics/src/TextAnalyticsActions.cs
1,513
C#
namespace SoundFingerprinting.Query { using System.Collections.Generic; using SoundFingerprinting.Command; public class RealtimeQueryResult { public RealtimeQueryResult(IEnumerable<ResultEntry> successEntries, IEnumerable<ResultEntry> didNotPassThresholdEntries) { SuccessEntries = successEntries; DidNotPassThresholdEntries = didNotPassThresholdEntries; } /// <summary> /// Gets list of aggregated successful matches. /// </summary> public IEnumerable<ResultEntry> SuccessEntries { get; } /// <summary> /// Gets list of matches that did not pass the matches filter. /// </summary> /// <remarks> /// See implementations of <see cref="IRealtimeResultEntryFilter"/> interface. /// </remarks> public IEnumerable<ResultEntry> DidNotPassThresholdEntries { get; } } }
34.777778
128
0.641108
[ "MIT" ]
Source-Digital/soundfingerprinting
src/SoundFingerprinting/Query/RealtimeQueryResult.cs
939
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401 { using static Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Extensions; /// <summary>The custom domain assigned to this storage account. This can be set via Update.</summary> public partial class CustomDomain { /// <summary> /// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json); /// <summary> /// <c>AfterToJson</c> will be called after the json serialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject" /// /> before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject container); /// <summary> /// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of /// the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <paramref name= "returnNow" /> /// output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> /// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return /// instantly.</param> partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json, ref bool returnNow); /// <summary> /// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the /// object before it is serialized. /// If you wish to disable the default serialization entirely, return <c>true</c> in the <paramref name="returnNow" /> output /// parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject into a new instance of <see cref="CustomDomain" />. /// </summary> /// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject instance to deserialize from.</param> internal CustomDomain(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } {_name = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString>("name"), out var __jsonName) ? (string)__jsonName : (string)Name;} {_useSubDomainName = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonBoolean>("useSubDomainName"), out var __jsonUseSubDomainName) ? (bool?)__jsonUseSubDomainName : UseSubDomainName;} AfterFromJson(json); } /// <summary> /// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.ICustomDomain. /// </summary> /// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns> /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.ICustomDomain. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.ICustomDomain FromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode node) { return node is Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json ? new CustomDomain(json) : null; } /// <summary> /// Serializes this instance of <see cref="CustomDomain" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode" />. /// </summary> /// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="CustomDomain" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode" />. /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode serializationMode) { container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add ); AddIf( null != this._useSubDomainName ? (Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonBoolean((bool)this._useSubDomainName) : null, "useSubDomainName" ,container.Add ); AfterToJson(ref container); return container; } } }
68.490909
269
0.68755
[ "MIT" ]
AlanFlorance/azure-powershell
src/Functions/generated/api/Models/Api20190401/CustomDomain.json.cs
7,425
C#
namespace BlazorBoilerplate.Shared.SqlLocalizer { public static class Settings { public const string NeutralCulture = "en-US"; public static readonly string[] SupportedCultures = { NeutralCulture, "de-DE", "it-IT", "fa-IR", "pt-PT" }; public static readonly (string, string)[] SupportedCulturesWithName = new[] { ("English", NeutralCulture), ("Deutsch", "de-DE"), ("Italiano", "it-IT"), ("پارسی", "fa-IR"), ("Português", "pt-PT") }; } }
39.666667
205
0.636555
[ "MIT" ]
Kayira150/blazor_sample
src/Shared/BlazorBoilerplate.Shared/SqlLocalizer/Settings.cs
484
C#
// Copyright (c) 2007-2017 ppy Pty Ltd <[email protected]>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu-framework/master/LICENCE using System; using OpenTK; namespace osu.Framework.Graphics { public static class Vector2Extensions { /// <summary>Transform a Position by the given Matrix</summary> /// <param name="pos">The position to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed position</returns> public static Vector2 Transform(Vector2 pos, Matrix3 mat) { Vector2 result; Transform(ref pos, ref mat, out result); return result; } /// <summary>Transform a Position by the given Matrix</summary> /// <param name="pos">The position to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed vector</param> public static void Transform(ref Vector2 pos, ref Matrix3 mat, out Vector2 result) { result.X = mat.Row0.X * pos.X + mat.Row1.X * pos.Y + mat.Row2.X; result.Y = mat.Row0.Y * pos.X + mat.Row1.Y * pos.Y + mat.Row2.Y; } /// <summary> /// Compute the euclidean distance between two vectors. /// </summary> /// <param name="vec1">The first vector</param> /// <param name="vec2">The second vector</param> /// <returns>The distance</returns> public static float Distance(Vector2 vec1, Vector2 vec2) { float result; Distance(ref vec1, ref vec2, out result); return result; } /// <summary> /// Compute the euclidean distance between two vectors. /// </summary> /// <param name="vec1">The first vector</param> /// <param name="vec2">The second vector</param> /// <param name="result">The distance</param> public static void Distance(ref Vector2 vec1, ref Vector2 vec2, out float result) { result = (float)Math.Sqrt((vec2.X - vec1.X) * (vec2.X - vec1.X) + (vec2.Y - vec1.Y) * (vec2.Y - vec1.Y)); } /// <summary> /// Compute the squared euclidean distance between two vectors. /// </summary> /// <param name="vec1">The first vector</param> /// <param name="vec2">The second vector</param> /// <returns>The squared distance</returns> public static float DistanceSquared(Vector2 vec1, Vector2 vec2) { float result; DistanceSquared(ref vec1, ref vec2, out result); return result; } /// <summary> /// Compute the squared euclidean distance between two vectors. /// </summary> /// <param name="vec1">The first vector</param> /// <param name="vec2">The second vector</param> /// <param name="result">The squared distance</param> public static void DistanceSquared(ref Vector2 vec1, ref Vector2 vec2, out float result) { result = (vec2.X - vec1.X) * (vec2.X - vec1.X) + (vec2.Y - vec1.Y) * (vec2.Y - vec1.Y); } } }
40.82716
118
0.567886
[ "MIT" ]
KokaKiwi/osu-framework
osu.Framework/Graphics/Vector2Extensions.cs
3,309
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using Cican_Micro.Models; using Cican_Micro.Data; using Microsoft.AspNetCore.Http; using System.IO; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Authorization; namespace Cican_Micro.Controllers { public class ProduitsController : Controller { private readonly ApplicationDbContext _context; private readonly IHostingEnvironment _appEnvironment; public ProduitsController(ApplicationDbContext context, IHostingEnvironment appEnvironment) { _context = context; _appEnvironment = appEnvironment; } // GET: Produits public async Task<IActionResult> Index(string searchString, string categorie) { var Produit = from m in _context.Produits select m; if (!String.IsNullOrEmpty(searchString)) { Produit = Produit.Where(s => s.Nom.Contains(searchString)); } if (!String.IsNullOrEmpty(categorie) && categorie != "Tous") Produit = Produit.Where(x => x.Categorie.Contains(categorie)); ViewData["Categories"] = _context.Produits.Select(x => x.Categorie).Distinct(); return View(await Produit.ToListAsync()); } [Authorize] // GET: Produits/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var produits = await _context.Produits .FirstOrDefaultAsync(m => m.ID == id); if (produits == null) { return NotFound(); } return View(produits); } [Authorize(Roles ="Administrateur, Employe")] // GET: Produits/Create public IActionResult Create() { return View(); } // POST: Produits/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] [Authorize(Roles = "Administrateur, Employe")] public async Task<IActionResult> Create([Bind("ID,Nom,Modele,Categorie,Prix")] Produits produits, IFormFile image) { if (ModelState.IsValid) { if (image != null && image.Length > 0) { string rootPath = _appEnvironment.WebRootPath; string imagesPath = rootPath + "\\upload_images\\" + image.FileName; using (var stream = new FileStream(imagesPath, FileMode.Create)) { await image.CopyToAsync(stream); } produits.ImageUrl = image.FileName; } _context.Add(produits); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(produits); } // GET: Produits/Edit/5 [Authorize(Roles = "Administrateur, Employe")] public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var produits = await _context.Produits.FindAsync(id); if (produits == null) { return NotFound(); } return View(produits); } // POST: Produits/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] [Authorize(Roles = "Administrateur, Employe")] public async Task<IActionResult> Edit(int id, [Bind("ID,Nom,Modele,Categorie,Prix")] Produits produits, IFormFile image) { if (id != produits.ID) { return NotFound(); } if (ModelState.IsValid) { try { if ( image != null && image.Length > 0) { string rootPath = _appEnvironment.WebRootPath; string imagesPath = rootPath + "\\upload_images\\" + image.FileName; using (var stream = new FileStream(imagesPath, FileMode.Create)) { await image.CopyToAsync(stream); } produits.ImageUrl = image.FileName; } else { Produits ancienProduit = _context.Produits.FirstOrDefault(x => x.ID == produits.ID); if(ancienProduit != null) { produits.ImageUrl = ancienProduit.ImageUrl; } _context.Entry(ancienProduit).State = EntityState.Detached; } _context.Update(produits); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!ProduitsExists(produits.ID)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } return View(produits); } // GET: Produits/Delete/5 [Authorize(Roles = "Administrateur")] public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var produits = await _context.Produits .FirstOrDefaultAsync(m => m.ID == id); if (produits == null) { return NotFound(); } return View(produits); } // POST: Produits/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] [Authorize(Roles = "Administrateur")] public async Task<IActionResult> DeleteConfirmed(int id) { var produits = await _context.Produits.FindAsync(id); _context.Produits.Remove(produits); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } private bool ProduitsExists(int id) { return _context.Produits.Any(e => e.ID == id); } } }
34.15534
128
0.512791
[ "MIT" ]
maximefalardeau/Cican_Micro
Cican_Micro/Controllers/ProduitsController.cs
7,038
C#
using RuriLib.Legacy.Functions.Conditions; using RuriLib.Legacy.Models; using RuriLib.Models.Variables; using System.Collections.Generic; using System.Linq; namespace RuriLib.Legacy.LS { public class VariablesList { public List<Variable> Variables { get; private set; } public IEnumerable<StringVariable> Strings => Variables.Where(v => v is StringVariable).Cast<StringVariable>(); public IEnumerable<ListOfStringsVariable> Lists => Variables.Where(v => v is ListOfStringsVariable).Cast<ListOfStringsVariable>(); public IEnumerable<DictionaryOfStringsVariable> Dictionaries => Variables.Where(v => v is DictionaryOfStringsVariable).Cast<DictionaryOfStringsVariable>(); public VariablesList(List<Variable> initialVariables = null) { Variables = initialVariables ?? new(); } /// <summary> /// Gets a variable given its name. /// </summary> /// <param name="name">The name of the variable</param> /// <returns>The variable or null if it wasn't found.</returns> public Variable Get(string name) => Variables.FirstOrDefault(v => v.Name == name); /// <summary> /// Gets a variable given its name and type. /// </summary> /// <param name="name">The name of the variable</param> /// <param name="type">The type of the variable</param> /// <returns>The variable or null if it wasn't found.</returns> public T Get<T>(string name) where T : Variable => Variables.FirstOrDefault(v => v.Name == name) as T; /// <summary> /// Helper method that checks if a variable exists given its name. /// </summary> /// <param name="name">The name of the variable</param> /// <returns>True if the variable exists</returns> public bool VariableExists(string name) => Variables.Any(v => v.Name == name); /// <summary> /// Helper method that checks if a variable exists given its name and type. /// </summary> /// <param name="name">The name of the variable</param> /// <param name="type">The type of the variable</param> /// <returns>True if the variable exists and matches the given type</returns> public bool VariableExists<T>(string name) where T : Variable => Variables.Any(v => v.Name == name && v.GetType() == typeof(T)); public void Set(Variable variable) { // First of all remove any old variable with the same name Remove(variable.Name); // Then add the new one Variables.Add(variable); } /// <summary> /// Adds a <paramref name="variable"/> to the variables list only if no other variable with the same name exists. /// </summary> public void SetIfNew(Variable variable) { if (!VariableExists(variable.Name)) { Set(variable); } } /// <summary> /// Removes a variable given its name. /// </summary> public void Remove(string name) => Variables.RemoveAll(v => v.Name == name); /// <summary> /// Removes all variables that meet a given a condition. /// </summary> public void RemoveAll(Comparer comparer, string name, LSGlobals ls) => Variables.RemoveAll(v => Condition.ReplaceAndVerify(v.Name, comparer, name, ls)); } }
38.966667
121
0.600798
[ "MIT" ]
Diwi1992/OpenBullet2
RuriLib/Legacy/LS/VariablesList.cs
3,509
C#
using System; namespace ExileConfigurator.Data { /// <summary> /// Class representing a single in-game object for the purposes of generating the necessary /// configuration code. /// </summary> public class Item : IComparable<Item> { private const string FormatClassString = "class {0} {{ quality = {1}; price = {2}; }};"; private const string FormatGroupString = "{0} - {1}"; public string Mod { get; set; } public string Type { get; set; } public string Id { get; set; } public int Price { get; set; } public int Quality { get; set; } public string Description { get; set; } public Item() { } public Item(string mod, string type, string id, int price, int quality) : this(mod, type, id, price, quality, string.Empty) { } public Item(string mod, string type, string id, int price, int quality, string description) { Mod = mod; Type = type; Id = id; Price = price; Quality = quality; Description = description; } /// <summary> /// Generate the class definition string for this Item. /// </summary> /// <returns></returns> public string getClassString() { var classString = string.Format(FormatClassString, Id, Quality, Price); return classString; } /// <summary> /// Generate the organizational group string, consisting of the Mod and Type. /// /// This string is generally only used to provide useful human-readable labels /// for the groups of items with the same mod and type values. /// i.e. comments, vendor menu labels /// </summary> /// <returns></returns> public string getGroupString() { var group = string.Format(FormatGroupString, Mod, Type); return group; } /// <summary> /// Case-insensitive ID comparison /// </summary> /// <param name="i"></param> /// <returns></returns> public bool EqualsId(Item i) { return string.Equals(Id, i.Id, StringComparison.OrdinalIgnoreCase); } /// <summary> /// Case-insensitive ID comparison /// </summary> /// <param name="id"></param> /// <returns></returns> public bool EqualsId(string id) { return string.Equals(Id, id, StringComparison.OrdinalIgnoreCase); } #region Interfaces public int CompareTo(Item other) { if(other == null) return 1; return Id.CompareTo(other.Id); } #endregion #region Overrides public override string ToString() { return Id; } public override bool Equals(object obj) { if(obj == null) return false; var other = obj as Item; if(other != null) { return (Mod != null ? Mod.Equals(other.Mod) : other.Mod != null) && (Type != null ? Type.Equals(other.Type) : other.Type != null) && (Id != null ? Id.Equals(other.Id) : other.Id != null) && Price == other.Price && Quality == other.Quality; } throw new ArgumentException("Object is not an Item"); } public override int GetHashCode() { unchecked { int mult = 23; int hash = 17; if(Mod != null) hash = hash * mult + Mod.GetHashCode(); if(Type != null) hash = hash * mult + Type.GetHashCode(); if(Id != null) hash = hash * mult + Id.GetHashCode(); hash = hash * mult + Price.GetHashCode(); hash = hash * mult + Quality.GetHashCode(); return hash; } } #endregion } }
23.978102
93
0.629833
[ "MIT" ]
nemesisx00/exile-configurator
ExileConfigurator/Data/Item.cs
3,287
C#
using System; using System.Reflection; using Avatars; using Xunit; namespace Moq.Sdk.Tests { public class PropertyBehaviorTests { [Fact] public void AppliesToGet() { var behavior = new PropertyBehavior(); Assert.True(behavior.AppliesTo(new MethodInvocation( new PropertiesMock(), typeof(PropertiesMock).GetProperty(nameof(PropertiesMock.Id)).GetGetMethod()))); } [Fact] public void AppliesToSet() { var behavior = new PropertyBehavior(); Assert.True(behavior.AppliesTo(new MethodInvocation( new PropertiesMock(), typeof(PropertiesMock).GetProperty(nameof(PropertiesMock.Id)).GetSetMethod(), "foo"))); } [Fact] public void ImplementsBackingState() { var mock = new PropertiesMock(); mock.AddBehavior(new PropertyBehavior()); mock.Id = "foo"; Assert.Equal("foo", mock.Id); } [Fact] public void ThrowsIfNullInvocation() => Assert.Throws<ArgumentNullException>(() => new PropertyBehavior().Execute(null, () => throw new NotImplementedException())); [Fact] public void ThrowsIfTargetNotMocked() { var behavior = new PropertyBehavior(); Assert.Throws<ArgumentException>(() => behavior.Execute(new MethodInvocation( new object(), typeof(PropertiesMock).GetProperty(nameof(PropertiesMock.Id)).GetSetMethod()), () => throw new NotImplementedException())); } public class PropertiesMock : FakeMock { public string Id { get => Pipeline.Execute<string>(new MethodInvocation(this, MethodBase.GetCurrentMethod())); set => Pipeline.Execute(new MethodInvocation(this, MethodBase.GetCurrentMethod(), value)); } } } }
31.276923
107
0.56911
[ "MIT" ]
Ettery/moq
src/Moq.Sdk.Tests/PropertyBehaviorTests.cs
2,035
C#
using System; using System.ComponentModel.DataAnnotations; using NHSD.GPIT.BuyingCatalogue.EntityFramework.Ordering.Models; using NHSD.GPIT.BuyingCatalogue.EntityFramework.Users.Models; namespace NHSD.GPIT.BuyingCatalogue.EntityFramework.Catalogue.Models { public class MarketingContact : IAudited { public int Id { get; set; } public CatalogueItemId SolutionId { get; set; } [StringLength(35)] public string FirstName { get; set; } [StringLength(35)] public string LastName { get; set; } [StringLength(255)] [EmailAddress] public string Email { get; set; } [StringLength(35)] public string PhoneNumber { get; set; } [StringLength(50)] public string Department { get; set; } public DateTime LastUpdated { get; set; } public int? LastUpdatedBy { get; set; } public AspNetUser LastUpdatedByUser { get; set; } public virtual bool IsEmpty() => string.IsNullOrWhiteSpace(FirstName) && string.IsNullOrWhiteSpace(LastName) && string.IsNullOrWhiteSpace(Department) && string.IsNullOrWhiteSpace(PhoneNumber) && string.IsNullOrWhiteSpace(Email); public virtual void UpdateFrom(MarketingContact sourceContact) { if (sourceContact == null) throw new ArgumentNullException(nameof(sourceContact)); Department = sourceContact.Department; Email = sourceContact.Email; FirstName = sourceContact.FirstName; LastName = sourceContact.LastName; PhoneNumber = sourceContact.PhoneNumber; } public virtual bool NewAndValid() => Id == default && !IsEmpty(); } }
30.689655
73
0.635955
[ "MIT" ]
nhs-digital-gp-it-futures/GPITBuyingCatalogue
src/NHSD.GPIT.BuyingCatalogue.EntityFramework/Catalogue/Models/MarketingContact.cs
1,782
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Hosting; using Polly; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text.Json; using System.Threading.Tasks; using ZCI.Common.Exceptions; namespace ZCI.Infrastructure { public class ExceptionHandlingMiddleware { private readonly RequestDelegate _next; private readonly bool _isDevelopment; public ExceptionHandlingMiddleware(RequestDelegate next, IWebHostEnvironment env) { _next = next; _isDevelopment = env.IsDevelopment(); } public async Task Invoke(HttpContext httpContext) { try { await _next(httpContext); } catch (Exception ex) when (!httpContext.Response.HasStarted) { await HandleExceptionAsync(httpContext, ex); } } private Task HandleExceptionAsync(HttpContext context, Exception ex) { var exInfo = GetExceptionInfo(ex); context.Response.ContentType = "application/json"; context.Response.StatusCode = (int)exInfo.code; var result = _isDevelopment ? JsonSerializer.Serialize(new { message = exInfo.message, exception = ex.ToString() }) : JsonSerializer.Serialize(new { message = exInfo.message }); return context.Response.WriteAsync(result); } private (HttpStatusCode code, string message) GetExceptionInfo(Exception exception) { if (exception is ValidationException) return (HttpStatusCode.BadRequest, exception.Message); if (exception is ExternalServiceException || exception is ExecutionRejectedException) return (HttpStatusCode.FailedDependency, exception.Message); return (HttpStatusCode.InternalServerError, "InternalServerError"); } } // Extension method used to add the middleware to the HTTP request pipeline. public static class ExceptionHandlingMiddlewareExtensions { public static IApplicationBuilder UseExceptionHandlingMiddleware(this IApplicationBuilder builder) { return builder.UseMiddleware<ExceptionHandlingMiddleware>(); } } }
32.453333
106
0.656122
[ "MIT" ]
MrDywar/zip-code-info
src/ZCI/Infrastructure/ExceptionHandlingMiddleware.cs
2,436
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("SmartEncryption")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SmartEncryption")] [assembly: AssemblyCopyright("Copyright © Adam Caudill 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ab2578e4-99c4-4b10-98e3-eb26d0e12619")] // 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("0.1.0.0")] [assembly: AssemblyFileVersion("0.1.0.0")]
38.243243
84
0.747703
[ "MIT" ]
adamcaudill/SmartEncryption
SmartEncryption/Properties/AssemblyInfo.cs
1,418
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.Buffers; using System.Diagnostics; namespace En3Tho.HelperClasses.Json { /// <summary> /// Represents a heap-based, array-backed output sink into which <typeparam name="T"/> data can be written. /// </summary> public sealed class ArrayPoolBufferWriter : IBufferWriter<byte>, IDisposable { private byte[] _buffer; private int _index; private const int DefaultInitialBufferSize = 256; /// <summary> /// Creates an instance of an <see cref="ArrayBufferWriter{T}"/>, in which data can be written to, /// with an initial capacity specified. /// </summary> /// <param name="initialCapacity">The minimum capacity with which to initialize the underlying buffer.</param> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="initialCapacity"/> is not positive (i.e. less than or equal to 0). /// </exception> public ArrayPoolBufferWriter(int initialCapacity) { if (initialCapacity <= 0) throw new ArgumentException(null, nameof(initialCapacity)); _buffer = ArrayPool<byte>.Shared.Rent(initialCapacity); _index = 0; } /// <summary> /// Returns the data written to the underlying buffer so far, as a <see cref="ReadOnlyMemory{T}"/>. /// </summary> public ReadOnlyMemory<byte> WrittenMemory => _buffer.AsMemory(0, _index); /// <summary> /// Returns the data written to the underlying buffer so far, as a <see cref="ReadOnlySpan{T}"/>. /// </summary> public ReadOnlySpan<byte> WrittenSpan => _buffer.AsSpan(0, _index); /// <summary> /// Returns the amount of data written to the underlying buffer so far. /// </summary> public int WrittenCount => _index; /// <summary> /// Returns the total amount of space within the underlying buffer. /// </summary> public int Capacity => _buffer.Length; /// <summary> /// Returns the amount of space available that can still be written into without forcing the underlying buffer to grow. /// </summary> public int FreeCapacity => _buffer.Length - _index; /// <summary> /// Clears the data written to the underlying buffer. /// </summary> /// <remarks> /// You must clear the <see cref="ArrayBufferWriter{T}"/> before trying to re-use it. /// </remarks> public void Clear() { Debug.Assert(_buffer.Length >= _index); _buffer.AsSpan(0, _index).Clear(); _index = 0; } public void SetIndex(int index) { if (index < 0 || index > _buffer.Length) throw new ArgumentException(null, nameof(index)); _index = index; } /// <summary> /// Notifies <see cref="IBufferWriter{T}"/> that <paramref name="count"/> amount of data was written to the output <see cref="Span{T}"/>/<see cref="Memory{T}"/> /// </summary> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="count"/> is negative. /// </exception> /// <exception cref="InvalidOperationException"> /// Thrown when attempting to advance past the end of the underlying buffer. /// </exception> /// <remarks> /// You must request a new buffer after calling Advance to continue writing more data and cannot write to a previously acquired buffer. /// </remarks> public void Advance(int count) { if (count < 0) throw new ArgumentException(null, nameof(count)); if (_index > _buffer.Length - count) ThrowInvalidOperationException_AdvancedTooFar(_buffer.Length); _index += count; } /// <summary> /// Returns a <see cref="Memory{T}"/> to write to that is at least the requested length (specified by <paramref name="sizeHint"/>). /// If no <paramref name="sizeHint"/> is provided (or it's equal to <code>0</code>), some non-empty buffer is returned. /// </summary> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="sizeHint"/> is negative. /// </exception> /// <remarks> /// This will never return an empty <see cref="Memory{T}"/>. /// </remarks> /// <remarks> /// There is no guarantee that successive calls will return the same buffer or the same-sized buffer. /// </remarks> /// <remarks> /// You must request a new buffer after calling Advance to continue writing more data and cannot write to a previously acquired buffer. /// </remarks> public Memory<byte> GetMemory(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); Debug.Assert(_buffer.Length > _index); return _buffer.AsMemory(_index); } /// <summary> /// Returns a <see cref="Span{T}"/> to write to that is at least the requested length (specified by <paramref name="sizeHint"/>). /// If no <paramref name="sizeHint"/> is provided (or it's equal to <code>0</code>), some non-empty buffer is returned. /// </summary> /// <exception cref="ArgumentException"> /// Thrown when <paramref name="sizeHint"/> is negative. /// </exception> /// <remarks> /// This will never return an empty <see cref="Span{T}"/>. /// </remarks> /// <remarks> /// There is no guarantee that successive calls will return the same buffer or the same-sized buffer. /// </remarks> /// <remarks> /// You must request a new buffer after calling Advance to continue writing more data and cannot write to a previously acquired buffer. /// </remarks> public Span<byte> GetSpan(int sizeHint = 0) { CheckAndResizeBuffer(sizeHint); Debug.Assert(_buffer.Length > _index); return _buffer.AsSpan(_index); } private void CheckAndResizeBuffer(int sizeHint) { if (sizeHint < 0) throw new ArgumentException(nameof(sizeHint)); if (sizeHint == 0) { sizeHint = 1; } if (sizeHint > FreeCapacity) { int currentLength = _buffer.Length; int growBy = Math.Max(sizeHint, currentLength); if (currentLength == 0) { growBy = Math.Max(growBy, DefaultInitialBufferSize); } int newSize = currentLength + growBy; if ((uint)newSize > int.MaxValue) { newSize = currentLength + sizeHint; if ((uint)newSize > int.MaxValue) { ThrowOutOfMemoryException((uint)newSize); } } var _newBuffer = ArrayPool<byte>.Shared.Rent(newSize); _buffer.CopyTo(_newBuffer.AsSpan()); ArrayPool<byte>.Shared.Return(_buffer); _buffer = _newBuffer; } Debug.Assert(FreeCapacity > 0 && FreeCapacity >= sizeHint); } private static void ThrowInvalidOperationException_AdvancedTooFar(int capacity) => throw new InvalidOperationException($"BufferWriterAdvancedTooFar : {capacity}"); private static void ThrowOutOfMemoryException(uint capacity) => throw new OutOfMemoryException($"BufferMaximumSizeExceeded: {capacity}"); public void Dispose() { ArrayPool<byte>.Shared.Return(_buffer); } } }
39.925
171
0.577959
[ "MIT" ]
En3Tho/Something-obviously-useless
SomethingObviouslyUseless/En3Tho.HelperClasses/Json/ArrayPoolBufferWriter.cs
7,987
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Network.Models { using Azure; using Management; using Network; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Information gained from troubleshooting of specified resource. /// </summary> public partial class TroubleshootingDetails { /// <summary> /// Initializes a new instance of the TroubleshootingDetails class. /// </summary> public TroubleshootingDetails() { } /// <summary> /// Initializes a new instance of the TroubleshootingDetails class. /// </summary> /// <param name="id">The id of the get troubleshoot operation.</param> /// <param name="reasonType">Reason type of failure.</param> /// <param name="summary">A summary of troubleshooting.</param> /// <param name="detail">Details on troubleshooting results.</param> /// <param name="recommendedActions">List of recommended /// actions.</param> public TroubleshootingDetails(string id = default(string), string reasonType = default(string), string summary = default(string), string detail = default(string), IList<TroubleshootingRecommendedActions> recommendedActions = default(IList<TroubleshootingRecommendedActions>)) { Id = id; ReasonType = reasonType; Summary = summary; Detail = detail; RecommendedActions = recommendedActions; } /// <summary> /// Gets or sets the id of the get troubleshoot operation. /// </summary> [JsonProperty(PropertyName = "id")] public string Id { get; set; } /// <summary> /// Gets or sets reason type of failure. /// </summary> [JsonProperty(PropertyName = "reasonType")] public string ReasonType { get; set; } /// <summary> /// Gets or sets a summary of troubleshooting. /// </summary> [JsonProperty(PropertyName = "summary")] public string Summary { get; set; } /// <summary> /// Gets or sets details on troubleshooting results. /// </summary> [JsonProperty(PropertyName = "detail")] public string Detail { get; set; } /// <summary> /// Gets or sets list of recommended actions. /// </summary> [JsonProperty(PropertyName = "recommendedActions")] public IList<TroubleshootingRecommendedActions> RecommendedActions { get; set; } } }
36.325
283
0.628355
[ "MIT" ]
DiogenesPolanco/azure-sdk-for-net
src/ResourceManagement/Network/Microsoft.Azure.Management.Network/Generated/Models/TroubleshootingDetails.cs
2,906
C#
namespace Monads { public static class RetrievingValueEitherExtension { public static TData RightOrLeft<TData>(this Either<TData, TData> source) { return source.IsRight() ? source.ForceRight : source.ForceLeft ; } public static int RightOrZero<TLeft>(this Either<TLeft, int> source) { return source.RightOr(0); } public static string RightOrEmpty<TLeft>(this Either<TLeft, string> source) { return source.RightOr(string.Empty); } public static int LeftOrZero<TRight>(this Either<int, TRight> source) { return source.LeftOr(0); } public static string LeftOrEmpty<TRight>(this Either<string, TRight> source) { return source.LeftOr(string.Empty); } } }
27.612903
85
0.589953
[ "MIT" ]
Ja-rek/CleanMonads
Monads/Either/Extensions/RetrievingValueEitherExtension.cs
856
C#
using System; using System.Linq; using System.Collections.Generic; namespace TMS.Kunina.Homework8 { public class Store { private static Article[] GetAllArticle() { Article[] article = { new Article() { ID = 1, ProductName = "iPhone8", StoreName = "i-Store", Price = 1450 }, new Article() { ID = 2, ProductName = "iPhone8", StoreName = "MTS", Price = 1400 }, new Article() { ID = 3, ProductName = "iPgone11", StoreName = "Mobile", Price = 1750 }, new Article() { ID = 4, ProductName = "iPgone11", StoreName = "7435", Price = 1744.58 }, new Article() { ID = 5, ProductName = "iPhone12", StoreName = "TTH", Price = 2380 }, new Article() { ID = 6, ProductName = "iPgone11", StoreName = "RDK", Price = 1700 }, new Article() { ID = 7, ProductName = "iPhone8", StoreName = "A1", Price = 1400 }, new Article() { ID = 8, ProductName = "iPhoneXR", StoreName = "Online", Price = 1470 }, new Article() { ID = 9, ProductName = "iPhoneXR", StoreName = "i-Store", Price = 1799 }, new Article() { ID = 10, ProductName = "iPhoneXR", StoreName = "Mobile", Price = 1470 }, new Article() { ID = 11, ProductName = "iPhone12", StoreName = "Online", Price = 2500 }, new Article() { ID = 12, ProductName = "iPhone12", StoreName = "Agroup.by", Price = 2478.66 }, new Article() { ID = 13, ProductName = "iPhone12", StoreName = "i-Store", Price = 2899 }, new Article() { ID = 14, ProductName = "iPhone13", StoreName = "TTH", Price = 2765 }, new Article() { ID = 15, ProductName = "iPhone13", StoreName = "Mobile", Price = 2765 }, new Article() { ID = 16, ProductName = "iPhone13", StoreName = "RDK", Price = 3150 } }; return article; } public static Dictionary<int, Article> Article_ToDictionary() { var result = GetAllArticle().ToDictionary(k => k.ID); return result; } } }
51.926829
110
0.537811
[ "MIT" ]
KaterinaKunina/TMS-DotNet-Kunina
src/TMS.Kunina.Homework8/Store.cs
2,131
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore; public class DatabaseInMemoryTest { [ConditionalTheory] [InlineData(false)] [InlineData(true)] public async Task CanConnect_returns_true(bool async) { using var context = new SimpleContext(); Assert.True(async ? await context.Database.CanConnectAsync() : context.Database.CanConnect()); } [ConditionalFact] public async Task Can_add_update_delete_end_to_end() { var serviceProvider = new ServiceCollection() .AddEntityFrameworkInMemoryDatabase() .AddSingleton<ILoggerFactory>(new ListLoggerFactory()) .AddSingleton(TestModelSource.GetFactory(OnModelCreating)) .BuildServiceProvider(validateScopes: true); var options = new DbContextOptionsBuilder() .UseInternalServiceProvider(serviceProvider) .UseInMemoryDatabase(nameof(DatabaseInMemoryTest)) .Options; var customer = new Customer { Id = 42, Name = "Theon" }; using (var context = new DbContext(options)) { context.Add(customer); await context.SaveChangesAsync(); customer.Name = "Changed!"; } using (var context = new DbContext(options)) { var customerFromStore = context.Set<Customer>().Single(); Assert.Equal(42, customerFromStore.Id); Assert.Equal("Theon", customerFromStore.Name); } using (var context = new DbContext(options)) { customer.Name = "Theon Greyjoy"; context.Update(customer); await context.SaveChangesAsync(); } using (var context = new DbContext(options)) { var customerFromStore = context.Set<Customer>().Single(); Assert.Equal(42, customerFromStore.Id); Assert.Equal("Theon Greyjoy", customerFromStore.Name); } using (var context = new DbContext(options)) { context.Remove(customer); await context.SaveChangesAsync(); } using (var context = new DbContext(options)) { Assert.Equal(0, context.Set<Customer>().Count()); } } private class Customer { // ReSharper disable once UnusedMember.Local private Customer(object[] values) { Id = (int)values[0]; Name = (string)values[1]; } public Customer() { } public int Id { get; set; } public string Name { get; set; } } protected virtual void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity<Customer>(); [ConditionalFact] public async Task Can_share_instance_between_contexts_with_sugar_experience() { using (var db = new SimpleContext()) { db.Artists.Add( new SimpleContext.Artist { ArtistId = "JDId", Name = "John Doe" }); await db.SaveChangesAsync(); } using (var db = new SimpleContext()) { var data = db.Artists.ToList(); Assert.Single(data); Assert.Equal("JDId", data[0].ArtistId); Assert.Equal("John Doe", data[0].Name); } } private class SimpleContext : DbContext { // ReSharper disable once UnusedAutoPropertyAccessor.Local public DbSet<Artist> Artists { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseInternalServiceProvider(InMemoryFixture.DefaultServiceProvider) .UseInMemoryDatabase(nameof(SimpleContext)); protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity<Artist>().HasKey(a => a.ArtistId); public class Artist : ArtistBase<string> { } public class ArtistBase<TKey> { public TKey ArtistId { get; set; } public string Name { get; set; } } } }
29.468966
102
0.600749
[ "MIT" ]
Applesauce314/efcore
test/EFCore.InMemory.FunctionalTests/DatabaseInMemoryTest.cs
4,273
C#
// <auto-generated/> /* The MIT License (MIT) Copyright (c) 2016-2019 Maksim Volkau 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 AddOrUpdateServiceFactory 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. */ // ReSharper disable CoVariantArrayConversion /* // Lists the target platforms that are Not supported by FEC - simplifies the direct referencing of Expression.cs file #if !PCL && !NET35 && !NET40 && !NET403 && !NETSTANDARD1_0 && !NETSTANDARD1_1 && !NETSTANDARD1_2 && !NETCOREAPP1_0 && !NETCOREAPP1_1 #define SUPPORTS_FAST_EXPRESSION_COMPILER #endif #if SUPPORTS_FAST_EXPRESSION_COMPILER */ #if LIGHT_EXPRESSION namespace FastExpressionCompiler.LightExpression #else namespace FastExpressionCompiler #endif { using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Threading; /// <summary>Compiles expression to delegate ~20 times faster than Expression.Compile. /// Partial to extend with your things when used as source file.</summary> // ReSharper disable once PartialTypeWithSinglePart public static partial class ExpressionCompiler { #region Expression.CompileFast overloads for Delegate, Func, and Action /// <summary>Compiles lambda expression to TDelegate type. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static TDelegate CompileFast<TDelegate>(this LambdaExpression lambdaExpr, bool ifFastFailedReturnNull = false) where TDelegate : class => (TDelegate)(TryCompileBoundToFirstClosureParam(typeof(TDelegate) == typeof(Delegate) ? lambdaExpr.Type : typeof(TDelegate), lambdaExpr.Body, lambdaExpr.Parameters, GetClosureTypeToParamTypes(lambdaExpr.Parameters), lambdaExpr.ReturnType) ?? (ifFastFailedReturnNull ? null : lambdaExpr.CompileSys())); /// Compiles a static method to the passed IL Generator. /// Could be used as alternative for `CompileToMethod` like this <code><![CDATA[funcExpr.CompileFastToIL(methodBuilder.GetILGenerator())]]></code>. /// Check `IssueTests.Issue179_Add_something_like_LambdaExpression_CompileToMethod.cs` for example. public static bool CompileFastToIL(this LambdaExpression lambdaExpr, ILGenerator il, bool ifFastFailedReturnNull = false) { var closureInfo = new ClosureInfo(ClosureStatus.ShouldBeStaticMethod); var parentFlags = lambdaExpr.ReturnType == typeof(void) ? ParentFlags.IgnoreResult : ParentFlags.Empty; if (!EmittingVisitor.TryEmit(lambdaExpr.Body, lambdaExpr.Parameters, il, ref closureInfo, parentFlags)) return false; il.Emit(OpCodes.Ret); return true; } /// <summary>Compiles lambda expression to delegate. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static Delegate CompileFast(this LambdaExpression lambdaExpr, bool ifFastFailedReturnNull = false) => (Delegate)TryCompileBoundToFirstClosureParam(lambdaExpr.Type, lambdaExpr.Body, lambdaExpr.Parameters, GetClosureTypeToParamTypes(lambdaExpr.Parameters), lambdaExpr.ReturnType) ?? (ifFastFailedReturnNull ? null : lambdaExpr.CompileSys()); /// <summary>Unifies Compile for System.Linq.Expressions and FEC.LightExpression</summary> public static TDelegate CompileSys<TDelegate>(this Expression<TDelegate> lambdaExpr) where TDelegate : class => lambdaExpr #if LIGHT_EXPRESSION .ToLambdaExpression() #endif .Compile(); /// <summary>Unifies Compile for System.Linq.Expressions and FEC.LightExpression</summary> public static Delegate CompileSys(this LambdaExpression lambdaExpr) => lambdaExpr #if LIGHT_EXPRESSION .ToLambdaExpression() #endif .Compile(); /// <summary>Compiles lambda expression to TDelegate type. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static TDelegate CompileFast<TDelegate>(this Expression<TDelegate> lambdaExpr, bool ifFastFailedReturnNull = false) where TDelegate : class => ((LambdaExpression)lambdaExpr).CompileFast<TDelegate>(ifFastFailedReturnNull); /// <summary>Compiles lambda expression to delegate. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static Func<R> CompileFast<R>(this Expression<Func<R>> lambdaExpr, bool ifFastFailedReturnNull = false) => (Func<R>)TryCompileBoundToFirstClosureParam(typeof(Func<R>), lambdaExpr.Body, lambdaExpr.Parameters, _closureAsASingleParamType, typeof(R)) ?? (ifFastFailedReturnNull ? null : lambdaExpr.CompileSys()); /// <summary>Compiles lambda expression to delegate. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static Func<T1, R> CompileFast<T1, R>(this Expression<Func<T1, R>> lambdaExpr, bool ifFastFailedReturnNull = false) => (Func<T1, R>)TryCompileBoundToFirstClosureParam(typeof(Func<T1, R>), lambdaExpr.Body, lambdaExpr.Parameters, new[] { typeof(ArrayClosure), typeof(T1) }, typeof(R)) ?? (ifFastFailedReturnNull ? null : lambdaExpr.CompileSys()); /// <summary>Compiles lambda expression to TDelegate type. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static Func<T1, T2, R> CompileFast<T1, T2, R>(this Expression<Func<T1, T2, R>> lambdaExpr, bool ifFastFailedReturnNull = false) => (Func<T1, T2, R>)TryCompileBoundToFirstClosureParam(typeof(Func<T1, T2, R>), lambdaExpr.Body, lambdaExpr.Parameters, new[] { typeof(ArrayClosure), typeof(T1), typeof(T2) }, typeof(R)) ?? (ifFastFailedReturnNull ? null : lambdaExpr.CompileSys()); /// <summary>Compiles lambda expression to delegate. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static Func<T1, T2, T3, R> CompileFast<T1, T2, T3, R>( this Expression<Func<T1, T2, T3, R>> lambdaExpr, bool ifFastFailedReturnNull = false) => (Func<T1, T2, T3, R>)TryCompileBoundToFirstClosureParam(typeof(Func<T1, T2, T3, R>), lambdaExpr.Body, lambdaExpr.Parameters, new[] { typeof(ArrayClosure), typeof(T1), typeof(T2), typeof(T3) }, typeof(R)) ?? (ifFastFailedReturnNull ? null : lambdaExpr.CompileSys()); /// <summary>Compiles lambda expression to TDelegate type. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static Func<T1, T2, T3, T4, R> CompileFast<T1, T2, T3, T4, R>( this Expression<Func<T1, T2, T3, T4, R>> lambdaExpr, bool ifFastFailedReturnNull = false) => (Func<T1, T2, T3, T4, R>)TryCompileBoundToFirstClosureParam(typeof(Func<T1, T2, T3, T4, R>), lambdaExpr.Body, lambdaExpr.Parameters, new[] { typeof(ArrayClosure), typeof(T1), typeof(T2), typeof(T3), typeof(T4) }, typeof(R)) ?? (ifFastFailedReturnNull ? null : lambdaExpr.CompileSys()); /// <summary>Compiles lambda expression to delegate. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static Func<T1, T2, T3, T4, T5, R> CompileFast<T1, T2, T3, T4, T5, R>( this Expression<Func<T1, T2, T3, T4, T5, R>> lambdaExpr, bool ifFastFailedReturnNull = false) => (Func<T1, T2, T3, T4, T5, R>)TryCompileBoundToFirstClosureParam(typeof(Func<T1, T2, T3, T4, T5, R>), lambdaExpr.Body, lambdaExpr.Parameters, new[] { typeof(ArrayClosure), typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }, typeof(R)) ?? (ifFastFailedReturnNull ? null : lambdaExpr.CompileSys()); /// <summary>Compiles lambda expression to delegate. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static Func<T1, T2, T3, T4, T5, T6, R> CompileFast<T1, T2, T3, T4, T5, T6, R>( this Expression<Func<T1, T2, T3, T4, T5, T6, R>> lambdaExpr, bool ifFastFailedReturnNull = false) => (Func<T1, T2, T3, T4, T5, T6, R>)TryCompileBoundToFirstClosureParam(typeof(Func<T1, T2, T3, T4, T5, T6, R>), lambdaExpr.Body, lambdaExpr.Parameters, new[] { typeof(ArrayClosure), typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6) }, typeof(R)) ?? (ifFastFailedReturnNull ? null : lambdaExpr.CompileSys()); /// <summary>Compiles lambda expression to delegate. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static Action CompileFast(this Expression<Action> lambdaExpr, bool ifFastFailedReturnNull = false) => (Action)TryCompileBoundToFirstClosureParam(typeof(Action), lambdaExpr.Body, lambdaExpr.Parameters, _closureAsASingleParamType, typeof(void)) ?? (ifFastFailedReturnNull ? null : lambdaExpr.CompileSys()); /// <summary>Compiles lambda expression to delegate. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static Action<T1> CompileFast<T1>(this Expression<Action<T1>> lambdaExpr, bool ifFastFailedReturnNull = false) => (Action<T1>)TryCompileBoundToFirstClosureParam(typeof(Action<T1>), lambdaExpr.Body, lambdaExpr.Parameters, new[] { typeof(ArrayClosure), typeof(T1) }, typeof(void)) ?? (ifFastFailedReturnNull ? null : lambdaExpr.CompileSys()); /// <summary>Compiles lambda expression to delegate. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static Action<T1, T2> CompileFast<T1, T2>(this Expression<Action<T1, T2>> lambdaExpr, bool ifFastFailedReturnNull = false) => (Action<T1, T2>)TryCompileBoundToFirstClosureParam(typeof(Action<T1, T2>), lambdaExpr.Body, lambdaExpr.Parameters, new[] { typeof(ArrayClosure), typeof(T1), typeof(T2) }, typeof(void)) ?? (ifFastFailedReturnNull ? null : lambdaExpr.CompileSys()); /// <summary>Compiles lambda expression to delegate. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static Action<T1, T2, T3> CompileFast<T1, T2, T3>(this Expression<Action<T1, T2, T3>> lambdaExpr, bool ifFastFailedReturnNull = false) => (Action<T1, T2, T3>)TryCompileBoundToFirstClosureParam(typeof(Action<T1, T2, T3>), lambdaExpr.Body, lambdaExpr.Parameters, new[] { typeof(ArrayClosure), typeof(T1), typeof(T2), typeof(T3) }, typeof(void)) ?? (ifFastFailedReturnNull ? null : lambdaExpr.CompileSys()); /// <summary>Compiles lambda expression to delegate. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static Action<T1, T2, T3, T4> CompileFast<T1, T2, T3, T4>( this Expression<Action<T1, T2, T3, T4>> lambdaExpr, bool ifFastFailedReturnNull = false) => (Action<T1, T2, T3, T4>)TryCompileBoundToFirstClosureParam(typeof(Action<T1, T2, T3, T4>), lambdaExpr.Body, lambdaExpr.Parameters, new[] { typeof(ArrayClosure), typeof(T1), typeof(T2), typeof(T3), typeof(T4) }, typeof(void)) ?? (ifFastFailedReturnNull ? null : lambdaExpr.CompileSys()); /// <summary>Compiles lambda expression to delegate. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static Action<T1, T2, T3, T4, T5> CompileFast<T1, T2, T3, T4, T5>( this Expression<Action<T1, T2, T3, T4, T5>> lambdaExpr, bool ifFastFailedReturnNull = false) => (Action<T1, T2, T3, T4, T5>)TryCompileBoundToFirstClosureParam(typeof(Action<T1, T2, T3, T4, T5>), lambdaExpr.Body, lambdaExpr.Parameters, new[] { typeof(ArrayClosure), typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5) }, typeof(void)) ?? (ifFastFailedReturnNull ? null : lambdaExpr.CompileSys()); /// <summary>Compiles lambda expression to delegate. Use ifFastFailedReturnNull parameter to Not fallback to Expression.Compile, useful for testing.</summary> public static Action<T1, T2, T3, T4, T5, T6> CompileFast<T1, T2, T3, T4, T5, T6>( this Expression<Action<T1, T2, T3, T4, T5, T6>> lambdaExpr, bool ifFastFailedReturnNull = false) => (Action<T1, T2, T3, T4, T5, T6>)TryCompileBoundToFirstClosureParam(typeof(Action<T1, T2, T3, T4, T5, T6>), lambdaExpr.Body, lambdaExpr.Parameters, new[] { typeof(ArrayClosure), typeof(T1), typeof(T2), typeof(T3), typeof(T4), typeof(T5), typeof(T6) }, typeof(void)) ?? (ifFastFailedReturnNull ? null : lambdaExpr.CompileSys()); #endregion /// <summary>Tries to compile lambda expression to <typeparamref name="TDelegate"/></summary> public static TDelegate TryCompile<TDelegate>(this LambdaExpression lambdaExpr) where TDelegate : class => (TDelegate)TryCompileBoundToFirstClosureParam(typeof(TDelegate) == typeof(Delegate) ? lambdaExpr.Type : typeof(TDelegate), lambdaExpr.Body, lambdaExpr.Parameters, GetClosureTypeToParamTypes(lambdaExpr.Parameters), lambdaExpr.ReturnType); /// <summary>Tries to compile lambda expression to <typeparamref name="TDelegate"/> /// with the provided closure object and constant expressions (or lack there of) - /// Constant expression should be the in order of Fields in closure object! /// Note 1: Use it on your own risk - FEC won't verify the expression is compile-able with passed closure, it is up to you! /// Note 2: The expression with NESTED LAMBDA IS NOT SUPPORTED! /// Note 3: `Label` and `GoTo` are not supported in this case, because they need first round to collect out-of-order labels</summary> public static TDelegate TryCompileWithPreCreatedClosure<TDelegate>(this LambdaExpression lambdaExpr, params ConstantExpression[] closureConstantsExprs) where TDelegate : class { var constValues = new object[closureConstantsExprs.Length]; for (var i = 0; i < constValues.Length; i++) constValues[i] = closureConstantsExprs[i].Value; var closureInfo = new ClosureInfo(ClosureStatus.UserProvided | ClosureStatus.HasClosure, constValues); var closurePlusParamTypes = GetClosureTypeToParamTypes(lambdaExpr.Parameters); var method = new DynamicMethod(string.Empty, lambdaExpr.ReturnType, closurePlusParamTypes, typeof(ExpressionCompiler), skipVisibility: true); var il = method.GetILGenerator(); EmittingVisitor.EmitLoadConstantsAndNestedLambdasIntoVars(il, ref closureInfo); var parentFlags = lambdaExpr.ReturnType == typeof(void) ? ParentFlags.IgnoreResult : ParentFlags.Empty; if (!EmittingVisitor.TryEmit(lambdaExpr.Body, lambdaExpr.Parameters, il, ref closureInfo, parentFlags)) return null; il.Emit(OpCodes.Ret); var delegateType = typeof(TDelegate) != typeof(Delegate) ? typeof(TDelegate) : lambdaExpr.Type; var @delegate = (TDelegate)(object)method.CreateDelegate(delegateType, new ArrayClosure(constValues)); ReturnClosureTypeToParamTypesToPool(closurePlusParamTypes); return @delegate; } /// <summary>Tries to compile expression to "static" delegate, skipping the step of collecting the closure object.</summary> public static TDelegate TryCompileWithoutClosure<TDelegate>(this LambdaExpression lambdaExpr) where TDelegate : class { var closureInfo = new ClosureInfo(ClosureStatus.UserProvided); var closurePlusParamTypes = GetClosureTypeToParamTypes(lambdaExpr.Parameters); var method = new DynamicMethod(string.Empty, lambdaExpr.ReturnType, closurePlusParamTypes, typeof(ArrayClosure), skipVisibility: true); var il = method.GetILGenerator(); var parentFlags = lambdaExpr.ReturnType == typeof(void) ? ParentFlags.IgnoreResult : ParentFlags.Empty; if (!EmittingVisitor.TryEmit(lambdaExpr.Body, lambdaExpr.Parameters, il, ref closureInfo, parentFlags)) return null; il.Emit(OpCodes.Ret); var delegateType = typeof(TDelegate) != typeof(Delegate) ? typeof(TDelegate) : lambdaExpr.Type; var @delegate = (TDelegate)(object)method.CreateDelegate(delegateType, EmptyArrayClosure); ReturnClosureTypeToParamTypesToPool(closurePlusParamTypes); return @delegate; } #region Obsolete /// Obsolete [Obsolete("Not used - candidate for removal")] public static TDelegate TryCompile<TDelegate>( Expression bodyExpr, IReadOnlyList<ParameterExpression> paramExprs, Type[] paramTypes, Type returnType) where TDelegate : class => (TDelegate)TryCompile(typeof(TDelegate), bodyExpr, paramExprs, paramTypes, returnType); /// Obsolete [Obsolete("Not used - candidate for removal")] public static object TryCompile(Type delegateType, Expression bodyExpr, IReadOnlyList<ParameterExpression> paramExprs, Type[] paramTypes, Type returnType) => TryCompileBoundToFirstClosureParam( delegateType != typeof(Delegate) ? delegateType : Tools.GetFuncOrActionType(paramTypes, returnType), bodyExpr, paramExprs, GetClosureTypeToParamTypes(paramExprs), returnType); #endregion internal static object TryCompileBoundToFirstClosureParam(Type delegateType, Expression bodyExpr, IReadOnlyList<ParameterExpression> paramExprs, Type[] closurePlusParamTypes, Type returnType) { var closureInfo = new ClosureInfo(ClosureStatus.ToBeCollected); if (!TryCollectBoundConstants(ref closureInfo, bodyExpr, paramExprs, false, ref closureInfo)) return null; var nestedLambdas = closureInfo.NestedLambdas; if (nestedLambdas.Length != 0) for (var i = 0; i < nestedLambdas.Length; ++i) if (!TryCompileNestedLambda(ref closureInfo, i)) return null; var closure = (closureInfo.Status & ClosureStatus.HasClosure) == 0 ? EmptyArrayClosure : new ArrayClosure(closureInfo.GetArrayOfConstantsAndNestedLambdas()); var method = new DynamicMethod(string.Empty, returnType, closurePlusParamTypes, typeof(ArrayClosure), true); var il = method.GetILGenerator(); if (closure.ConstantsAndNestedLambdas != null) EmittingVisitor.EmitLoadConstantsAndNestedLambdasIntoVars(il, ref closureInfo); var parentFlags = returnType == typeof(void) ? ParentFlags.IgnoreResult : ParentFlags.Empty; if (!EmittingVisitor.TryEmit(bodyExpr, paramExprs, il, ref closureInfo, parentFlags)) return null; il.Emit(OpCodes.Ret); var @delegate = method.CreateDelegate(delegateType, closure); ReturnClosureTypeToParamTypesToPool(closurePlusParamTypes); return @delegate; } private static Type[] PrependClosureTypeToParamTypes(IReadOnlyList<ParameterExpression> paramExprs) { var count = paramExprs.Count; var closureAndParamTypes = new Type[count + 1]; closureAndParamTypes[0] = typeof(ArrayClosure); for (var i = 0; i < count; i++) { var parameterExpr = paramExprs[i]; closureAndParamTypes[i + 1] = parameterExpr.IsByRef ? parameterExpr.Type.MakeByRefType() : parameterExpr.Type; } return closureAndParamTypes; } private static readonly Type[] _closureAsASingleParamType = { typeof(ArrayClosure) }; private static readonly Type[][] _closureTypePlusParamTypesPool = new Type[8][]; private static Type[] GetClosureTypeToParamTypes(IReadOnlyList<ParameterExpression> paramExprs) { var paramCount = paramExprs.Count; if (paramCount == 0) return _closureAsASingleParamType; if (paramCount < _closureTypePlusParamTypesPool.Length) { var closureAndParamTypes = Interlocked.Exchange(ref _closureTypePlusParamTypesPool[paramCount], null); if (closureAndParamTypes != null) { for (var i = 0; i < paramExprs.Count; i++) { var parameterExpr = paramExprs[i]; closureAndParamTypes[i + 1] = parameterExpr.IsByRef ? parameterExpr.Type.MakeByRefType() : parameterExpr.Type; } return closureAndParamTypes; } } return PrependClosureTypeToParamTypes(paramExprs); } private static void ReturnClosureTypeToParamTypesToPool(Type[] closurePlusParamTypes) { var paramCount = closurePlusParamTypes.Length - 1; if (paramCount != 0 && paramCount < _closureTypePlusParamTypesPool.Length) Interlocked.Exchange(ref _closureTypePlusParamTypesPool[paramCount], closurePlusParamTypes); } private struct BlockInfo { public object VarExprs; // ParameterExpression | IReadOnlyList<ParameterExpression> public int[] VarIndexes; } [Flags] private enum ClosureStatus { ToBeCollected = 1, UserProvided = 1 << 1, HasClosure = 1 << 2, ShouldBeStaticMethod = 1 << 3 } /// Track the info required to build a closure object + some context information not directly related to closure. private struct ClosureInfo { public bool LastEmitIsAddress; /// Helpers to know if a Return GotoExpression's Label should be emitted. /// First set bit is ContainsReturnGoto, the rest is ReturnLabelIndex private int[] _tryCatchFinallyInfos; public int CurrentTryCatchFinallyIndex; /// Tracks the stack of blocks where are we in emit phase private LiveCountArray<BlockInfo> _blockStack; /// Dictionary for the used Labels in IL private KeyValuePair<LabelTarget, Label?>[] _labels; public ClosureStatus Status; /// Constant expressions to find an index (by reference) of constant expression from compiled expression. public LiveCountArray<object> Constants; /// Parameters not passed through lambda parameter list But used inside lambda body. /// The top expression should Not contain not passed parameters. public ParameterExpression[] NonPassedParameters; /// All nested lambdas recursively nested in expression public NestedLambdaInfo[] NestedLambdas; /// Constant usage count and variable index public LiveCountArray<int> ConstantUsage; /// Populates info directly with provided closure object and constants. public ClosureInfo(ClosureStatus status, object[] constValues = null) { Status = status; Constants = new LiveCountArray<object>(constValues ?? Tools.Empty<object>()); ConstantUsage = new LiveCountArray<int>(constValues == null ? Tools.Empty<int>() : new int[constValues.Length]); NonPassedParameters = Tools.Empty<ParameterExpression>(); NestedLambdas = Tools.Empty<NestedLambdaInfo>(); LastEmitIsAddress = false; CurrentTryCatchFinallyIndex = -1; _tryCatchFinallyInfos = null; _labels = null; _blockStack = new LiveCountArray<BlockInfo>(Tools.Empty<BlockInfo>()); } public void AddConstant(object value) { Status |= ClosureStatus.HasClosure; var constItems = Constants.Items; var constIndex = Constants.Count - 1; while (constIndex != -1 && !ReferenceEquals(constItems[constIndex], value)) --constIndex; if (constIndex == -1) { Constants.PushSlot(value); ConstantUsage.PushSlot(1); } else { ++ConstantUsage.Items[constIndex]; } } public void AddNonPassedParam(ParameterExpression expr) { Status |= ClosureStatus.HasClosure; if (NonPassedParameters.Length == 0) { NonPassedParameters = new[] { expr }; return; } var count = NonPassedParameters.Length; for (var i = 0; i < count; ++i) if (ReferenceEquals(NonPassedParameters[i], expr)) return; if (NonPassedParameters.Length == 1) NonPassedParameters = new[] { NonPassedParameters[0], expr }; else if (NonPassedParameters.Length == 2) NonPassedParameters = new[] { NonPassedParameters[0], NonPassedParameters[1], expr }; else { var newItems = new ParameterExpression[count + 1]; Array.Copy(NonPassedParameters, 0, newItems, 0, count); newItems[count] = expr; NonPassedParameters = newItems; } } public void AddNestedLambda(NestedLambdaInfo nestedLambdaInfo) { Status |= ClosureStatus.HasClosure; var nestedLambdas = NestedLambdas; var count = nestedLambdas.Length; if (count == 0) NestedLambdas = new[] { nestedLambdaInfo }; else if (count == 1) NestedLambdas = new[] { nestedLambdas[0], nestedLambdaInfo }; else if (count == 2) NestedLambdas = new[] { nestedLambdas[0], nestedLambdas[1], nestedLambdaInfo }; else { var newNestedLambdas = new NestedLambdaInfo[count + 1]; Array.Copy(nestedLambdas, 0, newNestedLambdas, 0, count); newNestedLambdas[count] = nestedLambdaInfo; NestedLambdas = newNestedLambdas; } } public void AddLabel(LabelTarget labelTarget) { if (labelTarget != null && GetLabelIndex(labelTarget) == -1) _labels = _labels.WithLast(new KeyValuePair<LabelTarget, Label?>(labelTarget, null)); } public Label GetOrCreateLabel(LabelTarget labelTarget, ILGenerator il) => GetOrCreateLabel(GetLabelIndex(labelTarget), il); public Label GetOrCreateLabel(int index, ILGenerator il) { var labelPair = _labels[index]; var label = labelPair.Value; if (!label.HasValue) _labels[index] = new KeyValuePair<LabelTarget, Label?>(labelPair.Key, label = il.DefineLabel()); return label.Value; } public int GetLabelIndex(LabelTarget labelTarget) { if (_labels != null) for (var i = 0; i < _labels.Length; ++i) if (_labels[i].Key == labelTarget) return i; return -1; } public void AddTryCatchFinallyInfo() { ++CurrentTryCatchFinallyIndex; var infos = _tryCatchFinallyInfos; if (infos == null) _tryCatchFinallyInfos = new int[1]; else if (infos.Length == 1) _tryCatchFinallyInfos = new[] { infos[0], 0 }; else if (infos.Length == 2) _tryCatchFinallyInfos = new[] { infos[0], infos[1], 0 }; else { var sourceLength = infos.Length; var newInfos = new int[sourceLength + 1]; Array.Copy(infos, newInfos, sourceLength); _tryCatchFinallyInfos = newInfos; } } public void MarkAsContainsReturnGotoExpression() { if (CurrentTryCatchFinallyIndex != -1) _tryCatchFinallyInfos[CurrentTryCatchFinallyIndex] |= 1; } public void MarkReturnLabelIndex(int index) { if (CurrentTryCatchFinallyIndex != -1) _tryCatchFinallyInfos[CurrentTryCatchFinallyIndex] |= index << 1; } public bool TryCatchFinallyContainsReturnGotoExpression() => _tryCatchFinallyInfos != null && (_tryCatchFinallyInfos[++CurrentTryCatchFinallyIndex] & 1) != 0; public object[] GetArrayOfConstantsAndNestedLambdas() { var constCount = Constants.Count; var nestedLambdas = NestedLambdas; if (constCount == 0) { if (nestedLambdas.Length == 0) return null; var nestedLambdaItems = new object[nestedLambdas.Length]; for (var i = 0; i < nestedLambdas.Length; i++) { var nestedLambda = nestedLambdas[i]; if (nestedLambda.ClosureInfo.NonPassedParameters.Length == 0) nestedLambdaItems[i] = nestedLambda.Lambda; else nestedLambdaItems[i] = new NestedLambdaWithConstantsAndNestedLambdas( nestedLambda.Lambda, nestedLambda.ClosureInfo.GetArrayOfConstantsAndNestedLambdas()); } return nestedLambdaItems; } var constItems = Constants.Items; if (nestedLambdas.Length == 0) return constItems; var itemCount = constCount + nestedLambdas.Length; var closureItems = constItems; if (itemCount > constItems.Length) { closureItems = new object[itemCount]; for (var i = 0; i < constCount; ++i) closureItems[i] = constItems[i]; } for (var i = 0; i < nestedLambdas.Length; i++) { var nestedLambda = nestedLambdas[i]; if (nestedLambda.ClosureInfo.NonPassedParameters.Length == 0) closureItems[constCount + i] = nestedLambda.Lambda; else closureItems[constCount + i] = new NestedLambdaWithConstantsAndNestedLambdas( nestedLambda.Lambda, nestedLambda.ClosureInfo.GetArrayOfConstantsAndNestedLambdas()); } return closureItems; } /// LocalVar maybe a `null` in collecting phase when we only need to decide if ParameterExpression is an actual parameter or variable public void PushBlockWithVars(ParameterExpression blockVarExpr) { ref var block = ref _blockStack.PushSlot(); block.VarExprs = blockVarExpr; } public void PushBlockWithVars(ParameterExpression blockVarExpr, int varIndex) { ref var block = ref _blockStack.PushSlot(); block.VarExprs = blockVarExpr; block.VarIndexes = new[] { varIndex }; } /// LocalVars maybe a `null` in collecting phase when we only need to decide if ParameterExpression is an actual parameter or variable public void PushBlockWithVars(IReadOnlyList<ParameterExpression> blockVarExprs, int[] localVarIndexes = null) { ref var block = ref _blockStack.PushSlot(); block.VarExprs = blockVarExprs; block.VarIndexes = localVarIndexes; } public void PushBlockAndConstructLocalVars(IReadOnlyList<ParameterExpression> blockVarExprs, ILGenerator il) { var localVars = new int[blockVarExprs.Count]; for (var i = 0; i < localVars.Length; i++) localVars[i] = il.GetNextLocalVarIndex(blockVarExprs[i].Type); PushBlockWithVars(blockVarExprs, localVars); } public void PopBlock() => _blockStack.Pop(); public bool IsLocalVar(object varParamExpr) { for (var i = _blockStack.Count - 1; i > -1; --i) { var varExprObj = _blockStack.Items[i].VarExprs; if (ReferenceEquals(varExprObj, varParamExpr)) return true; if (varExprObj is IReadOnlyList<ParameterExpression> varExprs) for (var j = 0; j < varExprs.Count; j++) if (ReferenceEquals(varExprs[j], varParamExpr)) return true; } return false; } public int GetDefinedLocalVarOrDefault(ParameterExpression varParamExpr) { for (var i = _blockStack.Count - 1; i > -1; --i) { ref var block = ref _blockStack.Items[i]; var varExprObj = block.VarExprs; if (ReferenceEquals(varExprObj, varParamExpr)) return block.VarIndexes[0]; if (varExprObj is IReadOnlyList<ParameterExpression> varExprs) for (var j = 0; j < varExprs.Count; j++) if (ReferenceEquals(varExprs[j], varParamExpr)) return block.VarIndexes[j]; } return -1; } public bool IsTryReturnLabel(int index) { var tryCatchFinallyInfos = _tryCatchFinallyInfos; if (tryCatchFinallyInfos != null) for (var i = 0; i < tryCatchFinallyInfos.Length; ++i) if (tryCatchFinallyInfos[i] >> 1 == index) return true; return false; } } #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member public static readonly ArrayClosure EmptyArrayClosure = new ArrayClosure(null); public static FieldInfo ArrayClosureArrayField = typeof(ArrayClosure).GetTypeInfo().GetDeclaredField(nameof(ArrayClosure.ConstantsAndNestedLambdas)); public static FieldInfo ArrayClosureWithNonPassedParamsField = typeof(ArrayClosureWithNonPassedParams).GetTypeInfo().GetDeclaredField(nameof(ArrayClosureWithNonPassedParams.NonPassedParams)); public static ConstructorInfo ArrayClosureWithNonPassedParamsConstructor = typeof(ArrayClosureWithNonPassedParams).GetTypeInfo().DeclaredConstructors.GetFirst(); public class ArrayClosure { public readonly object[] ConstantsAndNestedLambdas; public ArrayClosure(object[] constantsAndNestedLambdas) => ConstantsAndNestedLambdas = constantsAndNestedLambdas; } public sealed class ArrayClosureWithNonPassedParams : ArrayClosure { public readonly object[] NonPassedParams; public ArrayClosureWithNonPassedParams(object[] constantsAndNestedLambdas, object[] nonPassedParams) : base(constantsAndNestedLambdas) => NonPassedParams = nonPassedParams; } public sealed class NestedLambdaWithConstantsAndNestedLambdas { public static FieldInfo NestedLambdaField = typeof(NestedLambdaWithConstantsAndNestedLambdas).GetTypeInfo().GetDeclaredField(nameof(NestedLambda)); public static FieldInfo ConstantsAndNestedLambdasField = typeof(NestedLambdaWithConstantsAndNestedLambdas).GetTypeInfo().GetDeclaredField(nameof(ConstantsAndNestedLambdas)); public readonly object NestedLambda; public readonly object ConstantsAndNestedLambdas; public NestedLambdaWithConstantsAndNestedLambdas(object nestedLambda, object constantsAndNestedLambdas) { NestedLambda = nestedLambda; ConstantsAndNestedLambdas = constantsAndNestedLambdas; } } private sealed class NestedLambdaInfo { public readonly LambdaExpression LambdaExpression; public ClosureInfo ClosureInfo; public object Lambda; public int UsageCountOrVarIndex; public NestedLambdaInfo(LambdaExpression lambdaExpression) { LambdaExpression = lambdaExpression; ClosureInfo = new ClosureInfo(ClosureStatus.ToBeCollected); Lambda = null; } } internal static class CurryClosureFuncs { public static readonly MethodInfo[] Methods = typeof(CurryClosureFuncs).GetTypeInfo().DeclaredMethods.AsArray(); public static Func<R> Curry<C, R>(Func<C, R> f, C c) => () => f(c); public static Func<T1, R> Curry<C, T1, R>(Func<C, T1, R> f, C c) => t1 => f(c, t1); public static Func<T1, T2, R> Curry<C, T1, T2, R>(Func<C, T1, T2, R> f, C c) => (t1, t2) => f(c, t1, t2); public static Func<T1, T2, T3, R> Curry<C, T1, T2, T3, R>(Func<C, T1, T2, T3, R> f, C c) => (t1, t2, t3) => f(c, t1, t2, t3); public static Func<T1, T2, T3, T4, R> Curry<C, T1, T2, T3, T4, R>(Func<C, T1, T2, T3, T4, R> f, C c) => (t1, t2, t3, t4) => f(c, t1, t2, t3, t4); public static Func<T1, T2, T3, T4, T5, R> Curry<C, T1, T2, T3, T4, T5, R>(Func<C, T1, T2, T3, T4, T5, R> f, C c) => (t1, t2, t3, t4, t5) => f(c, t1, t2, t3, t4, t5); public static Func<T1, T2, T3, T4, T5, T6, R> Curry<C, T1, T2, T3, T4, T5, T6, R>(Func<C, T1, T2, T3, T4, T5, T6, R> f, C c) => (t1, t2, t3, t4, t5, t6) => f(c, t1, t2, t3, t4, t5, t6); } internal static class CurryClosureActions { public static readonly MethodInfo[] Methods = typeof(CurryClosureActions).GetTypeInfo().DeclaredMethods.AsArray(); public static Action Curry<C>(Action<C> a, C c) => () => a(c); public static Action<T1> Curry<C, T1>(Action<C, T1> f, C c) => t1 => f(c, t1); public static Action<T1, T2> Curry<C, T1, T2>(Action<C, T1, T2> f, C c) => (t1, t2) => f(c, t1, t2); public static Action<T1, T2, T3> Curry<C, T1, T2, T3>(Action<C, T1, T2, T3> f, C c) => (t1, t2, t3) => f(c, t1, t2, t3); public static Action<T1, T2, T3, T4> Curry<C, T1, T2, T3, T4>(Action<C, T1, T2, T3, T4> f, C c) => (t1, t2, t3, t4) => f(c, t1, t2, t3, t4); public static Action<T1, T2, T3, T4, T5> Curry<C, T1, T2, T3, T4, T5>(Action<C, T1, T2, T3, T4, T5> f, C c) => (t1, t2, t3, t4, t5) => f(c, t1, t2, t3, t4, t5); public static Action<T1, T2, T3, T4, T5, T6> Curry<C, T1, T2, T3, T4, T5, T6>(Action<C, T1, T2, T3, T4, T5, T6> f, C c) => (t1, t2, t3, t4, t5, t6) => f(c, t1, t2, t3, t4, t5, t6); } #region Collect Bound Constants /// Helps to identify constants as the one to be put into the Closure public static bool IsClosureBoundConstant(object value, TypeInfo type) => value is Delegate || !type.IsPrimitive && !type.IsEnum && value is string == false && value is Type == false && value is decimal == false; // @paramExprs is required for nested lambda compilation private static bool TryCollectBoundConstants(ref ClosureInfo closure, Expression expr, IReadOnlyList<ParameterExpression> paramExprs, bool isNestedLambda, ref ClosureInfo rootClosure) { while (true) { if (expr == null) return false; switch (expr.NodeType) { case ExpressionType.Constant: var constantExpr = (ConstantExpression)expr; var value = constantExpr.Value; if (value != null && IsClosureBoundConstant(value, value.GetType().GetTypeInfo())) closure.AddConstant(value); return true; case ExpressionType.Quote: //var operand = ((UnaryExpression)expr).Operand; //if (operand != null && IsClosureBoundConstant(operand, expr.Type.GetTypeInfo())) // closure.AddConstant(operand); return false; case ExpressionType.Parameter: // if parameter is used BUT is not in passed parameters and not in local variables, // it means parameter is provided by outer lambda and should be put in closure for current lambda var p = paramExprs.Count - 1; while (p != -1 && !ReferenceEquals(paramExprs[p], expr)) --p; if (p == -1 && !closure.IsLocalVar(expr)) { if (!isNestedLambda) return false; closure.AddNonPassedParam((ParameterExpression)expr); } return true; case ExpressionType.Call: var callExpr = (MethodCallExpression)expr; var callObjectExpr = callExpr.Object; #if LIGHT_EXPRESSION var fewCallArgCount = callExpr.FewArgumentCount; if (fewCallArgCount == 0) { if (callObjectExpr != null) { expr = callObjectExpr; continue; } return true; } if (fewCallArgCount > 0) { if (callObjectExpr != null && !TryCollectBoundConstants(ref closure, callObjectExpr, paramExprs, isNestedLambda, ref rootClosure)) return false; if (fewCallArgCount == 1) { expr = ((OneArgumentMethodCallExpression)callExpr).Argument; continue; } if (fewCallArgCount == 2) { var twoArgsExpr = (TwoArgumentsMethodCallExpression)callExpr; if (!TryCollectBoundConstants(ref closure, twoArgsExpr.Argument0, paramExprs, isNestedLambda, ref rootClosure)) return false; expr = twoArgsExpr.Argument1; continue; } if (fewCallArgCount == 3) { var threeArgsExpr = (ThreeArgumentsMethodCallExpression)callExpr; if (!TryCollectBoundConstants(ref closure, threeArgsExpr.Argument0, paramExprs, isNestedLambda, ref rootClosure) || !TryCollectBoundConstants(ref closure, threeArgsExpr.Argument1, paramExprs, isNestedLambda, ref rootClosure)) return false; expr = threeArgsExpr.Argument2; continue; } if (fewCallArgCount == 4) { var fourArgsExpr = (FourArgumentsMethodCallExpression)callExpr; if (!TryCollectBoundConstants(ref closure, fourArgsExpr.Argument0, paramExprs, isNestedLambda, ref rootClosure) || !TryCollectBoundConstants(ref closure, fourArgsExpr.Argument1, paramExprs, isNestedLambda, ref rootClosure) || !TryCollectBoundConstants(ref closure, fourArgsExpr.Argument2, paramExprs, isNestedLambda, ref rootClosure)) return false; expr = fourArgsExpr.Argument3; continue; } var fiveArgsExpr = (FiveArgumentsMethodCallExpression)callExpr; if (!TryCollectBoundConstants(ref closure, fiveArgsExpr.Argument0, paramExprs, isNestedLambda, ref rootClosure) || !TryCollectBoundConstants(ref closure, fiveArgsExpr.Argument1, paramExprs, isNestedLambda, ref rootClosure) || !TryCollectBoundConstants(ref closure, fiveArgsExpr.Argument2, paramExprs, isNestedLambda, ref rootClosure) || !TryCollectBoundConstants(ref closure, fiveArgsExpr.Argument3, paramExprs, isNestedLambda, ref rootClosure)) return false; expr = fiveArgsExpr.Argument4; continue; } #endif var methodArgs = callExpr.Arguments; var methodArgCount = methodArgs.Count; if (methodArgCount == 0) { if (callObjectExpr != null) { expr = callObjectExpr; continue; } return true; } if (callObjectExpr != null && !TryCollectBoundConstants(ref closure, callExpr.Object, paramExprs, isNestedLambda, ref rootClosure)) return false; for (var i = 0; i < methodArgCount - 1; i++) if (!TryCollectBoundConstants(ref closure, methodArgs[i], paramExprs, isNestedLambda, ref rootClosure)) return false; expr = methodArgs[methodArgCount - 1]; continue; case ExpressionType.MemberAccess: var memberExpr = ((MemberExpression)expr).Expression; if (memberExpr == null) return true; expr = memberExpr; continue; case ExpressionType.New: var newExpr = (NewExpression)expr; #if LIGHT_EXPRESSION var fewArgCount = newExpr.FewArgumentCount; if (fewArgCount == 0) return true; if (fewArgCount > 0) { if (fewArgCount == 1) { expr = ((OneArgumentNewExpression)newExpr).Argument; continue; } if (fewArgCount == 2) { var twoArgsExpr = (TwoArgumentsNewExpression)newExpr; if (!TryCollectBoundConstants(ref closure, twoArgsExpr.Argument0, paramExprs, isNestedLambda, ref rootClosure)) return false; expr = twoArgsExpr.Argument1; continue; } if (fewArgCount == 3) { var threeArgsExpr = (ThreeArgumentsNewExpression)newExpr; if (!TryCollectBoundConstants(ref closure, threeArgsExpr.Argument0, paramExprs, isNestedLambda, ref rootClosure) || !TryCollectBoundConstants(ref closure, threeArgsExpr.Argument1, paramExprs, isNestedLambda, ref rootClosure)) return false; expr = threeArgsExpr.Argument2; continue; } if (fewArgCount == 4) { var fourArgsExpr = (FourArgumentsNewExpression)newExpr; if (!TryCollectBoundConstants(ref closure, fourArgsExpr.Argument0, paramExprs, isNestedLambda, ref rootClosure) || !TryCollectBoundConstants(ref closure, fourArgsExpr.Argument1, paramExprs, isNestedLambda, ref rootClosure) || !TryCollectBoundConstants(ref closure, fourArgsExpr.Argument2, paramExprs, isNestedLambda, ref rootClosure)) return false; expr = fourArgsExpr.Argument3; continue; } if (fewArgCount == 4) { var fourArgsExpr = (FourArgumentsNewExpression)newExpr; if (!TryCollectBoundConstants(ref closure, fourArgsExpr.Argument0, paramExprs, isNestedLambda, ref rootClosure) || !TryCollectBoundConstants(ref closure, fourArgsExpr.Argument1, paramExprs, isNestedLambda, ref rootClosure) || !TryCollectBoundConstants(ref closure, fourArgsExpr.Argument2, paramExprs, isNestedLambda, ref rootClosure)) return false; expr = fourArgsExpr.Argument3; continue; } var fiveArgsExpr = (FiveArgumentsNewExpression)newExpr; if (!TryCollectBoundConstants(ref closure, fiveArgsExpr.Argument0, paramExprs, isNestedLambda, ref rootClosure) || !TryCollectBoundConstants(ref closure, fiveArgsExpr.Argument1, paramExprs, isNestedLambda, ref rootClosure) || !TryCollectBoundConstants(ref closure, fiveArgsExpr.Argument2, paramExprs, isNestedLambda, ref rootClosure) || !TryCollectBoundConstants(ref closure, fiveArgsExpr.Argument3, paramExprs, isNestedLambda, ref rootClosure)) return false; expr = fiveArgsExpr.Argument4; continue; } #endif var ctorArgs = ((NewExpression)expr).Arguments; var ctorLastArgIndex = ctorArgs.Count - 1; if (ctorLastArgIndex == -1) return true; for (var i = 0; i < ctorLastArgIndex; i++) if (!TryCollectBoundConstants(ref closure, ctorArgs[i], paramExprs, isNestedLambda, ref rootClosure)) return false; expr = ctorArgs[ctorLastArgIndex]; continue; case ExpressionType.NewArrayBounds: case ExpressionType.NewArrayInit: var elemExprs = ((NewArrayExpression)expr).Expressions; var elemExprsCount = elemExprs.Count; if (elemExprsCount == 0) return true; for (var i = 0; i < elemExprsCount - 1; i++) if (!TryCollectBoundConstants(ref closure, elemExprs[i], paramExprs, isNestedLambda, ref rootClosure)) return false; expr = elemExprs[elemExprsCount - 1]; continue; case ExpressionType.MemberInit: return TryCollectMemberInitExprConstants( ref closure, (MemberInitExpression)expr, paramExprs, isNestedLambda, ref rootClosure); case ExpressionType.Lambda: var nestedLambdaExpr = (LambdaExpression)expr; // Look for the already collected lambdas and if we have the same lambda, start from the root var nestedLambdas = rootClosure.NestedLambdas; if (nestedLambdas.Length != 0) { var foundLambdaInfo = FindAlreadyCollectedNestedLambdaInfo(nestedLambdas, nestedLambdaExpr, out var foundInLambdas); if (foundLambdaInfo != null) { // if the lambda is not found on the same level, then add it if (foundInLambdas == closure.NestedLambdas) { ++foundLambdaInfo.UsageCountOrVarIndex; } else { closure.AddNestedLambda(foundLambdaInfo); var foundLambdaNonPassedParams = foundLambdaInfo.ClosureInfo.NonPassedParameters; if (foundLambdaNonPassedParams.Length != 0) PropagateNonPassedParamsToOuterLambda(ref closure, paramExprs, nestedLambdaExpr.Parameters, foundLambdaNonPassedParams); } return true; } } var nestedLambdaInfo = new NestedLambdaInfo(nestedLambdaExpr); if (!TryCollectBoundConstants(ref nestedLambdaInfo.ClosureInfo, nestedLambdaExpr.Body, nestedLambdaExpr.Parameters, true, ref rootClosure)) return false; closure.AddNestedLambda(nestedLambdaInfo); var nestedNonPassedParams = nestedLambdaInfo.ClosureInfo.NonPassedParameters; if (nestedNonPassedParams.Length != 0) PropagateNonPassedParamsToOuterLambda(ref closure, paramExprs, nestedLambdaExpr.Parameters, nestedNonPassedParams); return true; case ExpressionType.Invoke: var invokeExpr = (InvocationExpression)expr; var invokeArgs = invokeExpr.Arguments; var invokeArgsCount = invokeArgs.Count; if (invokeArgsCount == 0) { // optimization #138: we inline the invoked lambda body (only for lambdas without arguments) // therefore we skipping collecting the lambda and invocation arguments and got directly to lambda body. // This approach is repeated in `TryEmitInvoke` expr = (invokeExpr.Expression as LambdaExpression)?.Body ?? invokeExpr.Expression; continue; } else if (!TryCollectBoundConstants(ref closure, invokeExpr.Expression, paramExprs, isNestedLambda, ref rootClosure)) return false; for (var i = 0; i < invokeArgs.Count - 1; i++) if (!TryCollectBoundConstants(ref closure, invokeArgs[i], paramExprs, isNestedLambda, ref rootClosure)) return false; expr = invokeArgs[invokeArgsCount - 1]; continue; case ExpressionType.Conditional: var condExpr = (ConditionalExpression)expr; if (!TryCollectBoundConstants(ref closure, condExpr.Test, paramExprs, isNestedLambda, ref rootClosure) || !TryCollectBoundConstants(ref closure, condExpr.IfFalse, paramExprs, isNestedLambda, ref rootClosure)) return false; expr = condExpr.IfTrue; continue; case ExpressionType.Block: #if LIGHT_EXPRESSION if (expr is OneVariableTwoExpressionBlockExpression simpleBlock) { closure.PushBlockWithVars(simpleBlock.Variable); if (!TryCollectBoundConstants(ref closure, simpleBlock.Expression1, paramExprs, isNestedLambda, ref rootClosure) || !TryCollectBoundConstants(ref closure, simpleBlock.Expression2, paramExprs, isNestedLambda, ref rootClosure)) return false; closure.PopBlock(); return true; } #endif var blockExpr = (BlockExpression)expr; var blockVarExprs = blockExpr.Variables; var blockExprs = blockExpr.Expressions; if (blockVarExprs.Count == 0) { for (var i = 0; i < blockExprs.Count - 1; i++) if (!TryCollectBoundConstants(ref closure, blockExprs[i], paramExprs, isNestedLambda, ref rootClosure)) return false; expr = blockExprs[blockExprs.Count - 1]; continue; } else { if (blockVarExprs.Count == 1) closure.PushBlockWithVars(blockVarExprs[0]); else closure.PushBlockWithVars(blockVarExprs); for (var i = 0; i < blockExprs.Count; i++) if (!TryCollectBoundConstants(ref closure, blockExprs[i], paramExprs, isNestedLambda, ref rootClosure)) return false; closure.PopBlock(); } return true; case ExpressionType.Loop: var loopExpr = (LoopExpression)expr; closure.AddLabel(loopExpr.BreakLabel); closure.AddLabel(loopExpr.ContinueLabel); expr = loopExpr.Body; continue; case ExpressionType.Index: var indexExpr = (IndexExpression)expr; var indexArgs = indexExpr.Arguments; for (var i = 0; i < indexArgs.Count; i++) if (!TryCollectBoundConstants(ref closure, indexArgs[i], paramExprs, isNestedLambda, ref rootClosure)) return false; if (indexExpr.Object == null) return true; expr = indexExpr.Object; continue; case ExpressionType.Try: return TryCollectTryExprConstants(ref closure, (TryExpression)expr, paramExprs, isNestedLambda, ref rootClosure); case ExpressionType.Label: var labelExpr = (LabelExpression)expr; var defaultValueExpr = labelExpr.DefaultValue; closure.AddLabel(labelExpr.Target); if (defaultValueExpr == null) return true; expr = defaultValueExpr; continue; case ExpressionType.Goto: var gotoExpr = (GotoExpression)expr; if (gotoExpr.Kind == GotoExpressionKind.Return) closure.MarkAsContainsReturnGotoExpression(); if (gotoExpr.Value == null) return true; expr = gotoExpr.Value; continue; case ExpressionType.Switch: var switchExpr = ((SwitchExpression)expr); if (!TryCollectBoundConstants(ref closure, switchExpr.SwitchValue, paramExprs, isNestedLambda, ref rootClosure) || switchExpr.DefaultBody != null && !TryCollectBoundConstants(ref closure, switchExpr.DefaultBody, paramExprs, isNestedLambda, ref rootClosure)) return false; var switchCases = switchExpr.Cases; for (var i = 0; i < switchCases.Count - 1; i++) if (!TryCollectBoundConstants(ref closure, switchCases[i].Body, paramExprs, isNestedLambda, ref rootClosure)) return false; expr = switchCases[switchCases.Count - 1].Body; continue; case ExpressionType.Extension: expr = expr.Reduce(); continue; case ExpressionType.Default: return true; default: if (expr is UnaryExpression unaryExpr) { expr = unaryExpr.Operand; continue; } if (expr is BinaryExpression binaryExpr) { if (!TryCollectBoundConstants(ref closure, binaryExpr.Left, paramExprs, isNestedLambda, ref rootClosure)) return false; expr = binaryExpr.Right; continue; } if (expr is TypeBinaryExpression typeBinaryExpr) { expr = typeBinaryExpr.Expression; continue; } return false; } } } private static void PropagateNonPassedParamsToOuterLambda( ref ClosureInfo closure, IReadOnlyList<ParameterExpression> paramExprs, IReadOnlyList<ParameterExpression> nestedLambdaParamExprs, ParameterExpression[] nestedNonPassedParams) { // If nested non passed parameter is not matched with any outer passed parameter, // then ensure it goes to outer non passed parameter. // But check that having a non-passed parameter in root expression is invalid. for (var i = 0; i < nestedNonPassedParams.Length; i++) { var nestedNonPassedParam = nestedNonPassedParams[i]; var isInNestedLambda = false; if (nestedLambdaParamExprs.Count != 0) for (var p = 0; !isInNestedLambda && p < nestedLambdaParamExprs.Count; ++p) isInNestedLambda = ReferenceEquals(nestedLambdaParamExprs[p], nestedNonPassedParam); var isInOuterLambda = false; if (paramExprs.Count != 0) for (var p = 0; !isInOuterLambda && p < paramExprs.Count; ++p) isInOuterLambda = ReferenceEquals(paramExprs[p], nestedNonPassedParam); if (!isInNestedLambda && !isInOuterLambda) closure.AddNonPassedParam(nestedNonPassedParam); } } private static NestedLambdaInfo FindAlreadyCollectedNestedLambdaInfo( NestedLambdaInfo[] nestedLambdas, LambdaExpression nestedLambdaExpr, out NestedLambdaInfo[] foundInLambdas) { for (var i = 0; i < nestedLambdas.Length; i++) { var lambdaInfo = nestedLambdas[i]; if (ReferenceEquals(lambdaInfo.LambdaExpression, nestedLambdaExpr)) { foundInLambdas = nestedLambdas; return lambdaInfo; } var deeperNestedLambdas = lambdaInfo.ClosureInfo.NestedLambdas; if (deeperNestedLambdas.Length != 0) { var deeperLambdaInfo = FindAlreadyCollectedNestedLambdaInfo(deeperNestedLambdas, nestedLambdaExpr, out foundInLambdas); if (deeperLambdaInfo != null) return deeperLambdaInfo; } } foundInLambdas = null; return null; } private static bool TryCompileNestedLambda(ref ClosureInfo outerClosureInfo, int nestedLambdaIndex) { // 1. Try to compile nested lambda in place // 2. Check that parameters used in compiled lambda are passed or closed by outer lambda // 3. Add the compiled lambda to closure of outer lambda for later invocation var nestedLambdaInfo = outerClosureInfo.NestedLambdas[nestedLambdaIndex]; if (nestedLambdaInfo.Lambda != null) return true; var nestedLambdaExpr = nestedLambdaInfo.LambdaExpression; ref var nestedLambdaClosureInfo = ref nestedLambdaInfo.ClosureInfo; var nestedLambdaParamExprs = nestedLambdaExpr.Parameters; var nestedLambdaNestedLambdas = nestedLambdaClosureInfo.NestedLambdas; if (nestedLambdaNestedLambdas.Length != 0) for (var i = 0; i < nestedLambdaNestedLambdas.Length; ++i) if (!TryCompileNestedLambda(ref nestedLambdaClosureInfo, i)) return false; ArrayClosure nestedLambdaClosure = null; if (nestedLambdaClosureInfo.NonPassedParameters.Length == 0) { if ((nestedLambdaClosureInfo.Status & ClosureStatus.HasClosure) == 0) nestedLambdaClosure = EmptyArrayClosure; else nestedLambdaClosure = new ArrayClosure(nestedLambdaClosureInfo.GetArrayOfConstantsAndNestedLambdas()); } var nestedReturnType = nestedLambdaExpr.ReturnType; var closurePlusParamTypes = GetClosureTypeToParamTypes(nestedLambdaParamExprs); var method = new DynamicMethod(string.Empty, nestedReturnType, closurePlusParamTypes, typeof(ArrayClosure), true); var il = method.GetILGenerator(); if ((nestedLambdaClosureInfo.Status & ClosureStatus.HasClosure) != 0) EmittingVisitor.EmitLoadConstantsAndNestedLambdasIntoVars(il, ref nestedLambdaClosureInfo); var parentFlags = nestedReturnType == typeof(void) ? ParentFlags.IgnoreResult : ParentFlags.Empty; if (!EmittingVisitor.TryEmit(nestedLambdaExpr.Body, nestedLambdaParamExprs, il, ref nestedLambdaClosureInfo, parentFlags)) return false; il.Emit(OpCodes.Ret); if (nestedLambdaClosure != null) { nestedLambdaInfo.Lambda = method.CreateDelegate(nestedLambdaExpr.Type, nestedLambdaClosure); } else { // Otherwise create a static or an open delegate to pass closure later with `TryEmitNestedLambda`, // constructing the new closure with non-passed arguments and the rest of items nestedLambdaInfo.Lambda = method.CreateDelegate( Tools.GetFuncOrActionType(closurePlusParamTypes, nestedReturnType), null); } ReturnClosureTypeToParamTypesToPool(closurePlusParamTypes); return true; } private static bool TryCollectMemberInitExprConstants(ref ClosureInfo closure, MemberInitExpression expr, IReadOnlyList<ParameterExpression> paramExprs, bool isNestedLambda, ref ClosureInfo rootClosure) { var newExpr = expr.NewExpression #if LIGHT_EXPRESSION ?? expr.Expression #endif ; if (!TryCollectBoundConstants(ref closure, newExpr, paramExprs, isNestedLambda, ref rootClosure)) return false; var memberBindings = expr.Bindings; for (var i = 0; i < memberBindings.Count; ++i) { var memberBinding = memberBindings[i]; if (memberBinding.BindingType == MemberBindingType.Assignment && !TryCollectBoundConstants( ref closure, ((MemberAssignment)memberBinding).Expression, paramExprs, isNestedLambda, ref rootClosure)) return false; } return true; } private static bool TryCollectTryExprConstants(ref ClosureInfo closure, TryExpression tryExpr, IReadOnlyList<ParameterExpression> paramExprs, bool isNestedLambda, ref ClosureInfo rootClosure) { closure.AddTryCatchFinallyInfo(); if (!TryCollectBoundConstants(ref closure, tryExpr.Body, paramExprs, isNestedLambda, ref rootClosure)) return false; var catchBlocks = tryExpr.Handlers; for (var i = 0; i < catchBlocks.Count; i++) { var catchBlock = catchBlocks[i]; var catchExVar = catchBlock.Variable; if (catchExVar != null) { closure.PushBlockWithVars(catchExVar); if (!TryCollectBoundConstants(ref closure, catchExVar, paramExprs, isNestedLambda, ref rootClosure)) return false; } if (catchBlock.Filter != null && !TryCollectBoundConstants(ref closure, catchBlock.Filter, paramExprs, isNestedLambda, ref rootClosure)) return false; if (!TryCollectBoundConstants(ref closure, catchBlock.Body, paramExprs, isNestedLambda, ref rootClosure)) return false; if (catchExVar != null) closure.PopBlock(); } if (tryExpr.Finally != null && !TryCollectBoundConstants(ref closure, tryExpr.Finally, paramExprs, isNestedLambda, ref rootClosure)) return false; --closure.CurrentTryCatchFinallyIndex; return true; } #endregion // The minimal context-aware flags set by parent [Flags] internal enum ParentFlags { Empty = 0, IgnoreResult = 1 << 1, Call = 1 << 2, MemberAccess = 1 << 3, // Any Parent Expression is a MemberExpression Arithmetic = 1 << 4, Coalesce = 1 << 5, InstanceAccess = 1 << 6, DupMemberOwner = 1 << 7, TryCatch = 1 << 8, InstanceCall = Call | InstanceAccess } internal static bool IgnoresResult(this ParentFlags parent) => (parent & ParentFlags.IgnoreResult) != 0; /// <summary>Supports emitting of selected expressions, e.g. lambdaExpr are not supported yet. /// When emitter find not supported expression it will return false from <see cref="TryEmit"/>, so I could fallback /// to normal and slow Expression.Compile.</summary> private static class EmittingVisitor { #if NETSTANDARD1_1 || NETSTANDARD1_2 || NETSTANDARD1_3 || NETSTANDARD1_4 || NETSTANDARD1_5 || NETSTANDARD1_6 private static readonly MethodInfo _getTypeFromHandleMethod = typeof(Type).GetTypeInfo().GetDeclaredMethod("GetTypeFromHandle"); private static readonly MethodInfo _objectEqualsMethod = GetObjectEquals(); private static MethodInfo GetObjectEquals() { var ms = typeof(object).GetTypeInfo().GetDeclaredMethods("Equals"); foreach (var m in ms) if (m.GetParameters().Length == 2) return m; throw new InvalidOperationException("object.Equals is not found"); } #else private static readonly MethodInfo _getTypeFromHandleMethod = ((Func<RuntimeTypeHandle, Type>)Type.GetTypeFromHandle).Method; private static readonly MethodInfo _objectEqualsMethod = ((Func<object, object, bool>)object.Equals).Method; #endif public static bool TryEmit(Expression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent, int byRefIndex = -1) { while (true) { closure.LastEmitIsAddress = false; switch (expr.NodeType) { case ExpressionType.Parameter: return (parent & ParentFlags.IgnoreResult) != 0 || TryEmitParameter((ParameterExpression)expr, paramExprs, il, ref closure, parent, byRefIndex); case ExpressionType.TypeAs: case ExpressionType.IsTrue: case ExpressionType.IsFalse: case ExpressionType.Increment: case ExpressionType.Decrement: case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.OnesComplement: case ExpressionType.UnaryPlus: case ExpressionType.Unbox: return TryEmitSimpleUnaryExpression((UnaryExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.Quote: //return TryEmitNotNullConstant(true, expr.Type, ((UnaryExpression)expr).Operand, il, ref closure); return false; case ExpressionType.TypeIs: return TryEmitTypeIs((TypeBinaryExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.Not: return TryEmitNot((UnaryExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.Convert: case ExpressionType.ConvertChecked: return TryEmitConvert((UnaryExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.ArrayIndex: var arrIndexExpr = (BinaryExpression)expr; return TryEmit(arrIndexExpr.Left, paramExprs, il, ref closure, parent) && TryEmit(arrIndexExpr.Right, paramExprs, il, ref closure, parent) && TryEmitArrayIndex(expr.Type, il); case ExpressionType.ArrayLength: var arrLengthExpr = (UnaryExpression)expr; return TryEmitArrayLength(arrLengthExpr, paramExprs, il, ref closure, parent); case ExpressionType.Constant: var constExpr = (ConstantExpression)expr; if ((parent & ParentFlags.IgnoreResult) != 0) return true; if (constExpr.Value == null) { il.Emit(OpCodes.Ldnull); return true; } return TryEmitNotNullConstant(true, constExpr.Type, constExpr.Value, il, ref closure); case ExpressionType.Call: return TryEmitMethodCall(expr, paramExprs, il, ref closure, parent); case ExpressionType.MemberAccess: return TryEmitMemberAccess((MemberExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.New: return TryEmitNew(expr, paramExprs, il, ref closure, parent); case ExpressionType.NewArrayBounds: case ExpressionType.NewArrayInit: return EmitNewArray((NewArrayExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.MemberInit: return EmitMemberInit((MemberInitExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.Lambda: return TryEmitNestedLambda((LambdaExpression)expr, paramExprs, il, ref closure); case ExpressionType.Invoke: // optimization #138: we inline the invoked lambda body (only for lambdas without arguments) if (((InvocationExpression)expr).Expression is LambdaExpression lambdaExpr && lambdaExpr.Parameters.Count == 0) { expr = lambdaExpr.Body; continue; } return TryEmitInvoke((InvocationExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: var binaryExpr = (BinaryExpression)expr; return TryEmitComparison(binaryExpr.Left, binaryExpr.Right, binaryExpr.NodeType, paramExprs, il, ref closure, parent); case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.Power: case ExpressionType.And: case ExpressionType.Or: case ExpressionType.ExclusiveOr: case ExpressionType.LeftShift: case ExpressionType.RightShift: var arithmeticExpr = (BinaryExpression)expr; return TryEmitArithmetic(arithmeticExpr, expr.NodeType, paramExprs, il, ref closure, parent); case ExpressionType.AndAlso: case ExpressionType.OrElse: return TryEmitLogicalOperator((BinaryExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.Coalesce: return TryEmitCoalesceOperator((BinaryExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.Conditional: return TryEmitConditional((ConditionalExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.PostIncrementAssign: case ExpressionType.PreIncrementAssign: case ExpressionType.PostDecrementAssign: case ExpressionType.PreDecrementAssign: return TryEmitIncDecAssign((UnaryExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.AddAssign: case ExpressionType.AddAssignChecked: case ExpressionType.SubtractAssign: case ExpressionType.SubtractAssignChecked: case ExpressionType.MultiplyAssign: case ExpressionType.MultiplyAssignChecked: case ExpressionType.DivideAssign: case ExpressionType.ModuloAssign: case ExpressionType.PowerAssign: case ExpressionType.AndAssign: case ExpressionType.OrAssign: case ExpressionType.ExclusiveOrAssign: case ExpressionType.LeftShiftAssign: case ExpressionType.RightShiftAssign: case ExpressionType.Assign: return TryEmitAssign((BinaryExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.Block: #if LIGHT_EXPRESSION if (expr is OneVariableTwoExpressionBlockExpression simpleBlockExpr) { closure.PushBlockWithVars(simpleBlockExpr.Variable, il.GetNextLocalVarIndex(simpleBlockExpr.Variable.Type)); if (!TryEmit(simpleBlockExpr.Expression1, paramExprs, il, ref closure, parent | ParentFlags.IgnoreResult) || !TryEmit(simpleBlockExpr.Expression2, paramExprs, il, ref closure, parent)) return false; closure.PopBlock(); return true; } #endif var blockExpr = (BlockExpression)expr; var blockVarExprs = blockExpr.Variables; var blockVarCount = blockVarExprs.Count; if (blockVarCount == 1) closure.PushBlockWithVars(blockVarExprs[0], il.GetNextLocalVarIndex(blockVarExprs[0].Type)); else if (blockVarCount > 1) closure.PushBlockAndConstructLocalVars(blockVarExprs, il); var statementExprs = blockExpr.Expressions; // Trim the expressions after the Throw - #196 var statementCount = statementExprs.Count; expr = statementExprs[statementCount - 1]; // The last (result) statement in block will provide the result // Try to trim the statements up to the Throw (if any) if (statementCount > 1) { var throwIndex = statementCount - 1; while (throwIndex != -1 && statementExprs[throwIndex].NodeType != ExpressionType.Throw) --throwIndex; // If we have a Throw and it is not the last one if (throwIndex != -1 && throwIndex != statementCount - 1) { // Change the Throw return type to match the one for the Block, and adjust the statement count expr = Expression.Throw(((UnaryExpression)statementExprs[throwIndex]).Operand, blockExpr.Type); statementCount = throwIndex + 1; } } // handle the all statements in block excluding the last one if (statementCount > 1) for (var i = 0; i < statementCount - 1; i++) if (!TryEmit(statementExprs[i], paramExprs, il, ref closure, parent | ParentFlags.IgnoreResult)) return false; if (blockVarCount == 0) continue; // OMG, no recursion, continue with last expression if (!TryEmit(expr, paramExprs, il, ref closure, parent)) return false; closure.PopBlock(); return true; case ExpressionType.Loop: return TryEmitLoop((LoopExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.Try: return TryEmitTryCatchFinallyBlock((TryExpression)expr, paramExprs, il, ref closure, parent | ParentFlags.TryCatch); case ExpressionType.Throw: { if (!TryEmit(((UnaryExpression)expr).Operand, paramExprs, il, ref closure, parent & ~ParentFlags.IgnoreResult)) return false; il.Emit(OpCodes.Throw); return true; } case ExpressionType.Default: if (expr.Type != typeof(void) && (parent & ParentFlags.IgnoreResult) == 0) EmitDefault(expr.Type, il); return true; case ExpressionType.Index: return TryEmitIndex((IndexExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.Goto: return TryEmitGoto((GotoExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.Label: return TryEmitLabel((LabelExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.Switch: return TryEmitSwitch((SwitchExpression)expr, paramExprs, il, ref closure, parent); case ExpressionType.Extension: expr = expr.Reduce(); continue; default: return false; } } } private static bool TryEmitNew(Expression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { var newExpr = (NewExpression)expr; #if LIGHT_EXPRESSION var argCount = newExpr.FewArgumentCount; if (argCount > 0) { var args = newExpr.Constructor.GetParameters(); if (argCount == 1) { var argExpr = ((OneArgumentNewExpression)newExpr).Argument; if (!TryEmit(argExpr, paramExprs, il, ref closure, parent, args[0].ParameterType.IsByRef ? 0 : -1)) return false; } else if (argCount == 2) { var twoArgsExpr = (TwoArgumentsNewExpression)newExpr; if (!TryEmit(twoArgsExpr.Argument0, paramExprs, il, ref closure, parent, args[0].ParameterType.IsByRef ? 0 : -1) || !TryEmit(twoArgsExpr.Argument1, paramExprs, il, ref closure, parent, args[1].ParameterType.IsByRef ? 1 : -1)) return false; } else if (argCount == 3) { var threeArgsExpr = (ThreeArgumentsNewExpression)newExpr; if (!TryEmit(threeArgsExpr.Argument0, paramExprs, il, ref closure, parent, args[0].ParameterType.IsByRef ? 0 : -1) || !TryEmit(threeArgsExpr.Argument1, paramExprs, il, ref closure, parent, args[1].ParameterType.IsByRef ? 1 : -1) || !TryEmit(threeArgsExpr.Argument2, paramExprs, il, ref closure, parent, args[2].ParameterType.IsByRef ? 2 : -1)) return false; } else if (argCount == 4) { var fourArgsExpr = (FourArgumentsNewExpression)newExpr; if (!TryEmit(fourArgsExpr.Argument0, paramExprs, il, ref closure, parent, args[0].ParameterType.IsByRef ? 0 : -1) || !TryEmit(fourArgsExpr.Argument1, paramExprs, il, ref closure, parent, args[1].ParameterType.IsByRef ? 1 : -1) || !TryEmit(fourArgsExpr.Argument2, paramExprs, il, ref closure, parent, args[2].ParameterType.IsByRef ? 2 : -1) || !TryEmit(fourArgsExpr.Argument3, paramExprs, il, ref closure, parent, args[3].ParameterType.IsByRef ? 3 : -1)) return false; } else if (argCount == 5) { var fourArgsExpr = (FiveArgumentsNewExpression)newExpr; if (!TryEmit(fourArgsExpr.Argument0, paramExprs, il, ref closure, parent, args[0].ParameterType.IsByRef ? 0 : -1) || !TryEmit(fourArgsExpr.Argument1, paramExprs, il, ref closure, parent, args[1].ParameterType.IsByRef ? 1 : -1) || !TryEmit(fourArgsExpr.Argument2, paramExprs, il, ref closure, parent, args[2].ParameterType.IsByRef ? 2 : -1) || !TryEmit(fourArgsExpr.Argument3, paramExprs, il, ref closure, parent, args[3].ParameterType.IsByRef ? 3 : -1) || !TryEmit(fourArgsExpr.Argument4, paramExprs, il, ref closure, parent, args[4].ParameterType.IsByRef ? 4 : -1)) return false; } // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (newExpr.Constructor != null) il.Emit(OpCodes.Newobj, newExpr.Constructor); else if (newExpr.Type.IsValueType()) EmitLoadLocalVariable(il, InitValueTypeVariable(il, newExpr.Type)); else return false; return true; } #endif var argExprs = newExpr.Arguments; if (argExprs.Count != 0) { var args = newExpr.Constructor.GetParameters(); for (var i = 0; i < args.Length; ++i) if (!TryEmit(argExprs[i], paramExprs, il, ref closure, parent, args[i].ParameterType.IsByRef ? i : -1)) return false; } // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (newExpr.Constructor != null) il.Emit(OpCodes.Newobj, newExpr.Constructor); else if (newExpr.Type.IsValueType()) EmitLoadLocalVariable(il, InitValueTypeVariable(il, newExpr.Type)); else return false; return true; } private static bool TryEmitArrayLength(UnaryExpression arrLengthExpr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { if (!TryEmit(arrLengthExpr.Operand, paramExprs, il, ref closure, parent)) return false; if ((parent & ParentFlags.IgnoreResult) == 0) { il.Emit(OpCodes.Ldlen); il.Emit(OpCodes.Conv_I4); } return true; } private static bool TryEmitLoop(LoopExpression loopExpr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { // Mark the start of the loop body: var loopBodyLabel = il.DefineLabel(); il.MarkLabel(loopBodyLabel); if (loopExpr.ContinueLabel != null) il.MarkLabel(closure.GetOrCreateLabel(loopExpr.ContinueLabel, il)); if (!TryEmit(loopExpr.Body, paramExprs, il, ref closure, parent)) return false; // If loop hasn't exited, jump back to start of its body: il.Emit(OpCodes.Br, loopBodyLabel); if (loopExpr.BreakLabel != null) il.MarkLabel(closure.GetOrCreateLabel(loopExpr.BreakLabel, il)); return true; } private static bool TryEmitIndex(IndexExpression indexExpr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { if (indexExpr.Object != null && !TryEmit(indexExpr.Object, paramExprs, il, ref closure, parent)) return false; var indexArgExprs = indexExpr.Arguments; for (var i = 0; i < indexArgExprs.Count; i++) if (!TryEmit(indexArgExprs[i], paramExprs, il, ref closure, parent, indexArgExprs[i].Type.IsByRef ? i : -1)) return false; var indexerProp = indexExpr.Indexer; if (indexerProp != null) return EmitMethodCall(il, indexerProp.DeclaringType.FindPropertyGetMethod(indexerProp.Name)); if (indexExpr.Arguments.Count == 1) // one dimensional array return TryEmitArrayIndex(indexExpr.Type, il); // multi dimensional array return EmitMethodCall(il, indexExpr.Object?.Type.FindMethod("Get")); } private static bool TryEmitLabel(LabelExpression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { var index = closure.GetLabelIndex(expr.Target); if (index == -1) return false; // should be found in first collecting constants round if (closure.IsTryReturnLabel(index)) return true; // label will be emitted by TryEmitTryCatchFinallyBlock // define a new label or use the label provided by the preceding GoTo expression var label = closure.GetOrCreateLabel(index, il); il.MarkLabel(label); return expr.DefaultValue == null || TryEmit(expr.DefaultValue, paramExprs, il, ref closure, parent); } private static bool TryEmitGoto(GotoExpression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { var index = closure.GetLabelIndex(expr.Target); if (index == -1) { if ((closure.Status & ClosureStatus.ToBeCollected) == 0) return false; // if no collection cycle then the labels may be not collected throw new InvalidOperationException("Cannot jump, no labels found"); } if (expr.Value != null && !TryEmit(expr.Value, paramExprs, il, ref closure, parent & ~ParentFlags.IgnoreResult)) return false; switch (expr.Kind) { case GotoExpressionKind.Break: case GotoExpressionKind.Continue: // use label defined by Label expression or define its own to use by subsequent Label il.Emit(OpCodes.Br, closure.GetOrCreateLabel(index, il)); return true; case GotoExpressionKind.Goto: if (expr.Value != null) goto case GotoExpressionKind.Return; // use label defined by Label expression or define its own to use by subsequent Label il.Emit(OpCodes.Br, closure.GetOrCreateLabel(index, il)); return true; case GotoExpressionKind.Return: // check that we are inside the Try-Catch-Finally block if ((parent & ParentFlags.TryCatch) != 0) { // Can't emit a Return inside a Try/Catch, so leave it to TryEmitTryCatchFinallyBlock // to emit the Leave instruction, return label and return result closure.MarkReturnLabelIndex(index); } else { // use label defined by Label expression or define its own to use by subsequent Label il.Emit(OpCodes.Ret, closure.GetOrCreateLabel(index, il)); } return true; default: return false; } } private static bool TryEmitCoalesceOperator(BinaryExpression exprObj, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { var labelFalse = il.DefineLabel(); var labelDone = il.DefineLabel(); var left = exprObj.Left; var right = exprObj.Right; if (!TryEmit(left, paramExprs, il, ref closure, parent | ParentFlags.Coalesce)) return false; var leftType = left.Type; if (leftType.IsValueType()) // Nullable -> It's the only ValueType comparable to null { var varIndex = EmitStoreLocalVariableAndLoadItsAddress(il, leftType); il.Emit(OpCodes.Call, leftType.FindNullableHasValueGetterMethod()); il.Emit(OpCodes.Brfalse, labelFalse); EmitLoadLocalVariableAddress(il, varIndex); il.Emit(OpCodes.Call, leftType.FindNullableGetValueOrDefaultMethod()); il.Emit(OpCodes.Br, labelDone); il.MarkLabel(labelFalse); if (!TryEmit(right, paramExprs, il, ref closure, parent | ParentFlags.Coalesce)) return false; il.MarkLabel(labelDone); return true; } il.Emit(OpCodes.Dup); // duplicate left, if it's not null, after the branch this value will be on the top of the stack il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Ceq); il.Emit(OpCodes.Brfalse, labelFalse); il.Emit(OpCodes.Pop); // left is null, pop its value from the stack if (!TryEmit(right, paramExprs, il, ref closure, parent | ParentFlags.Coalesce)) return false; if (right.Type != exprObj.Type) { if (right.Type.IsValueType()) il.Emit(OpCodes.Box, right.Type); } if (left.Type == exprObj.Type) il.MarkLabel(labelFalse); else { il.Emit(OpCodes.Br, labelDone); il.MarkLabel(labelFalse); il.Emit(OpCodes.Castclass, exprObj.Type); il.MarkLabel(labelDone); } return true; } private static void EmitDefault(Type type, ILGenerator il) { if (!type.GetTypeInfo().IsValueType) { il.Emit(OpCodes.Ldnull); } else if ( type == typeof(bool) || type == typeof(byte) || type == typeof(char) || type == typeof(sbyte) || type == typeof(int) || type == typeof(uint) || type == typeof(short) || type == typeof(ushort)) { il.Emit(OpCodes.Ldc_I4_0); } else if ( type == typeof(long) || type == typeof(ulong)) { il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Conv_I8); } else if (type == typeof(float)) il.Emit(OpCodes.Ldc_R4, default(float)); else if (type == typeof(double)) il.Emit(OpCodes.Ldc_R8, default(double)); else EmitLoadLocalVariable(il, InitValueTypeVariable(il, type)); } private static bool TryEmitTryCatchFinallyBlock(TryExpression tryExpr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { var containsReturnGotoExpression = closure.TryCatchFinallyContainsReturnGotoExpression(); il.BeginExceptionBlock(); if (!TryEmit(tryExpr.Body, paramExprs, il, ref closure, parent)) return false; var exprType = tryExpr.Type; var returnsResult = exprType != typeof(void) && (containsReturnGotoExpression || !parent.IgnoresResult()); var resultVarIndex = -1; if (returnsResult) EmitStoreLocalVariable(il, resultVarIndex = il.GetNextLocalVarIndex(exprType)); var catchBlocks = tryExpr.Handlers; for (var i = 0; i < catchBlocks.Count; i++) { var catchBlock = catchBlocks[i]; if (catchBlock.Filter != null) return false; // todo: Add support for filters in catch expression il.BeginCatchBlock(catchBlock.Test); // at the beginning of catch the Exception value is on the stack, // we will store into local variable. var exVarExpr = catchBlock.Variable; if (exVarExpr != null) { var exVarIndex = il.GetNextLocalVarIndex(exVarExpr.Type); closure.PushBlockWithVars(exVarExpr, exVarIndex); EmitStoreLocalVariable(il, exVarIndex); } if (!TryEmit(catchBlock.Body, paramExprs, il, ref closure, parent)) return false; if (exVarExpr != null) closure.PopBlock(); if (returnsResult) EmitStoreLocalVariable(il, resultVarIndex); } var finallyExpr = tryExpr.Finally; if (finallyExpr != null) { il.BeginFinallyBlock(); if (!TryEmit(finallyExpr, paramExprs, il, ref closure, parent)) return false; } il.EndExceptionBlock(); if (returnsResult) EmitLoadLocalVariable(il, resultVarIndex); --closure.CurrentTryCatchFinallyIndex; return true; } private static bool TryEmitParameter(ParameterExpression paramExpr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent, int byRefIndex = -1) { // if parameter is passed through, then just load it on stack var paramType = paramExpr.Type; var paramIndex = paramExprs.Count - 1; while (paramIndex != -1 && !ReferenceEquals(paramExprs[paramIndex], paramExpr)) --paramIndex; if (paramIndex != -1) { if ((closure.Status & ClosureStatus.ShouldBeStaticMethod) == 0) ++paramIndex; // shift parameter index by one, because the first one will be closure closure.LastEmitIsAddress = !paramExpr.IsByRef && paramType.IsValueType() && ((parent & ParentFlags.InstanceCall) == ParentFlags.InstanceCall || (parent & ParentFlags.MemberAccess) != 0); if (closure.LastEmitIsAddress) il.Emit(OpCodes.Ldarga_S, (byte)paramIndex); else { if (paramIndex == 0) il.Emit(OpCodes.Ldarg_0); else if (paramIndex == 1) il.Emit(OpCodes.Ldarg_1); else if (paramIndex == 2) il.Emit(OpCodes.Ldarg_2); else if (paramIndex == 3) il.Emit(OpCodes.Ldarg_3); else il.Emit(OpCodes.Ldarg_S, (byte)paramIndex); } if (paramExpr.IsByRef) { if ((parent & ParentFlags.MemberAccess) != 0 && paramType.IsClass() || (parent & ParentFlags.Coalesce) != 0) il.Emit(OpCodes.Ldind_Ref); else if ((parent & ParentFlags.Arithmetic) != 0) EmitDereference(il, paramType); } return true; } // If parameter isn't passed, then it is passed into some outer lambda or it is a local variable, // so it should be loaded from closure or from the locals. Then the closure is null will be an invalid state. // Parameter may represent a variable, so first look if this is the case var varIndex = closure.GetDefinedLocalVarOrDefault(paramExpr); if (varIndex != -1) { if (byRefIndex != -1 || paramType.IsValueType() && (parent & (ParentFlags.MemberAccess | ParentFlags.InstanceAccess)) != 0) EmitLoadLocalVariableAddress(il, varIndex); else EmitLoadLocalVariable(il, varIndex); return true; } if (paramExpr.IsByRef) { EmitLoadLocalVariableAddress(il, byRefIndex); return true; } // the only possibility that we are here is because we are in the nested lambda, // and it uses the parameter or variable from the outer lambda var nonPassedParams = closure.NonPassedParameters; var nonPassedParamIndex = nonPassedParams.Length - 1; while (nonPassedParamIndex != -1 && !ReferenceEquals(nonPassedParams[nonPassedParamIndex], paramExpr)) --nonPassedParamIndex; if (nonPassedParamIndex == -1) return false; // what??? no chance // Load non-passed argument from Closure - closure object is always a first argument il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, ArrayClosureWithNonPassedParamsField); EmitLoadConstantInt(il, nonPassedParamIndex); il.Emit(OpCodes.Ldelem_Ref); // source type is object, NonPassedParams is object array if (paramType.IsValueType()) il.Emit(OpCodes.Unbox_Any, paramType); return true; } private static void EmitDereference(ILGenerator il, Type type) { if (type == typeof(Int32)) il.Emit(OpCodes.Ldind_I4); else if (type == typeof(Int64)) il.Emit(OpCodes.Ldind_I8); else if (type == typeof(Int16)) il.Emit(OpCodes.Ldind_I2); else if (type == typeof(SByte)) il.Emit(OpCodes.Ldind_I1); else if (type == typeof(Single)) il.Emit(OpCodes.Ldind_R4); else if (type == typeof(Double)) il.Emit(OpCodes.Ldind_R8); else if (type == typeof(IntPtr)) il.Emit(OpCodes.Ldind_I); else if (type == typeof(UIntPtr)) il.Emit(OpCodes.Ldind_I); else if (type == typeof(Byte)) il.Emit(OpCodes.Ldind_U1); else if (type == typeof(UInt16)) il.Emit(OpCodes.Ldind_U2); else if (type == typeof(UInt32)) il.Emit(OpCodes.Ldind_U4); else il.Emit(OpCodes.Ldobj, type); //todo: UInt64 as there is no OpCodes? Ldind_Ref? } private static bool TryEmitSimpleUnaryExpression(UnaryExpression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { var exprType = expr.Type; // todo: support decimal here if (exprType == typeof(decimal)) return false; if (!TryEmit(expr.Operand, paramExprs, il, ref closure, parent)) return false; if ((parent & ParentFlags.IgnoreResult) != 0) il.Emit(OpCodes.Pop); else { if (expr.NodeType == ExpressionType.TypeAs) { il.Emit(OpCodes.Isinst, exprType); } else if (expr.NodeType == ExpressionType.IsFalse) { var falseLabel = il.DefineLabel(); var continueLabel = il.DefineLabel(); il.Emit(OpCodes.Brfalse, falseLabel); il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Br, continueLabel); il.MarkLabel(falseLabel); il.Emit(OpCodes.Ldc_I4_1); il.MarkLabel(continueLabel); } else if (expr.NodeType == ExpressionType.Increment) { if (!TryEmitNumberOne(il, exprType)) return false; il.Emit(OpCodes.Add); } else if (expr.NodeType == ExpressionType.Decrement) { if (!TryEmitNumberOne(il, exprType)) return false; il.Emit(OpCodes.Sub); } else if (expr.NodeType == ExpressionType.Negate || expr.NodeType == ExpressionType.NegateChecked) { il.Emit(OpCodes.Neg); } else if (expr.NodeType == ExpressionType.OnesComplement) { il.Emit(OpCodes.Not); } else if (expr.NodeType == ExpressionType.Unbox) { il.Emit(OpCodes.Unbox_Any, exprType); } else if (expr.NodeType == ExpressionType.IsTrue) { } else if (expr.NodeType == ExpressionType.UnaryPlus) { } } return true; } private static bool TryEmitTypeIs(TypeBinaryExpression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { if (!TryEmit(expr.Expression, paramExprs, il, ref closure, parent)) return false; if ((parent & ParentFlags.IgnoreResult) != 0) il.Emit(OpCodes.Pop); else { il.Emit(OpCodes.Isinst, expr.TypeOperand); il.Emit(OpCodes.Ldnull); il.Emit(OpCodes.Cgt_Un); } return true; } private static bool TryEmitNot(UnaryExpression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { if (!TryEmit(expr.Operand, paramExprs, il, ref closure, parent)) return false; if ((parent & ParentFlags.IgnoreResult) > 0) il.Emit(OpCodes.Pop); else { if (expr.Type == typeof(bool)) { il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Ceq); } else { il.Emit(OpCodes.Not); } } return true; } private static bool TryEmitConvert(UnaryExpression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { var opExpr = expr.Operand; var method = expr.Method; if (method != null && method.Name != "op_Implicit" && method.Name != "op_Explicit") { if (!TryEmit(opExpr, paramExprs, il, ref closure, parent & ~ParentFlags.IgnoreResult | ParentFlags.InstanceCall, 0)) return false; il.Emit(method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, method); if ((parent & ParentFlags.IgnoreResult) != 0 && method.ReturnType != typeof(void)) il.Emit(OpCodes.Pop); return true; } var sourceType = opExpr.Type; var sourceTypeIsNullable = sourceType.IsNullable(); var underlyingNullableSourceType = Nullable.GetUnderlyingType(sourceType); var targetType = expr.Type; if (sourceTypeIsNullable && targetType == underlyingNullableSourceType) { if (!TryEmit(opExpr, paramExprs, il, ref closure, parent & ~ParentFlags.IgnoreResult | ParentFlags.InstanceAccess)) return false; if (!closure.LastEmitIsAddress) EmitStoreLocalVariableAndLoadItsAddress(il, sourceType); il.Emit(OpCodes.Call, sourceType.FindValueGetterMethod()); if ((parent & ParentFlags.IgnoreResult) != 0) il.Emit(OpCodes.Pop); return true; } if (!TryEmit(opExpr, paramExprs, il, ref closure, parent & ~ParentFlags.IgnoreResult & ~ParentFlags.InstanceAccess)) return false; var targetTypeIsNullable = targetType.IsNullable(); var underlyingNullableTargetType = Nullable.GetUnderlyingType(targetType); if (targetTypeIsNullable && sourceType == underlyingNullableTargetType) { il.Emit(OpCodes.Newobj, targetType.GetTypeInfo().DeclaredConstructors.GetFirst()); return true; } if (sourceType == targetType || targetType == typeof(object)) { if (targetType == typeof(object) && sourceType.IsValueType()) il.Emit(OpCodes.Box, sourceType); if (IgnoresResult(parent)) il.Emit(OpCodes.Pop); return true; } // check implicit / explicit conversion operators on source and target types // for non-primitives and for non-primitive nullable - #73 if (!sourceTypeIsNullable && !sourceType.IsPrimitive()) { var actualTargetType = targetTypeIsNullable ? underlyingNullableTargetType : targetType; var convertOpMethod = method ?? sourceType.FindConvertOperator(sourceType, actualTargetType); if (convertOpMethod != null) { il.Emit(OpCodes.Call, convertOpMethod); if (targetTypeIsNullable) il.Emit(OpCodes.Newobj, targetType.GetTypeInfo().DeclaredConstructors.GetFirst()); if ((parent & ParentFlags.IgnoreResult) != 0) il.Emit(OpCodes.Pop); return true; } } else if (!targetTypeIsNullable) { var actualSourceType = sourceTypeIsNullable ? underlyingNullableSourceType : sourceType; var convertOpMethod = method ?? actualSourceType.FindConvertOperator(actualSourceType, targetType); if (convertOpMethod != null) { if (sourceTypeIsNullable) { EmitStoreLocalVariableAndLoadItsAddress(il, sourceType); il.Emit(OpCodes.Call, sourceType.FindValueGetterMethod()); } il.Emit(OpCodes.Call, convertOpMethod); if ((parent & ParentFlags.IgnoreResult) != 0) il.Emit(OpCodes.Pop); return true; } } if (!targetTypeIsNullable && !targetType.IsPrimitive()) { var actualSourceType = sourceTypeIsNullable ? underlyingNullableSourceType : sourceType; // ReSharper disable once ConstantNullCoalescingCondition var convertOpMethod = method ?? targetType.FindConvertOperator(actualSourceType, targetType); if (convertOpMethod != null) { if (sourceTypeIsNullable) { EmitStoreLocalVariableAndLoadItsAddress(il, sourceType); il.Emit(OpCodes.Call, sourceType.FindValueGetterMethod()); } il.Emit(OpCodes.Call, convertOpMethod); if ((parent & ParentFlags.IgnoreResult) != 0) il.Emit(OpCodes.Pop); return true; } } else if (!sourceTypeIsNullable) { var actualTargetType = targetTypeIsNullable ? underlyingNullableTargetType : targetType; var convertOpMethod = method ?? actualTargetType.FindConvertOperator(sourceType, actualTargetType); if (convertOpMethod != null) { il.Emit(OpCodes.Call, convertOpMethod); if (targetTypeIsNullable) il.Emit(OpCodes.Newobj, targetType.GetTypeInfo().DeclaredConstructors.GetFirst()); if ((parent & ParentFlags.IgnoreResult) != 0) il.Emit(OpCodes.Pop); return true; } } if (sourceType == typeof(object) && targetType.IsValueType()) { il.Emit(OpCodes.Unbox_Any, targetType); } else if (targetTypeIsNullable) { // Conversion to Nullable: `new Nullable<T>(T val);` if (!sourceTypeIsNullable) { if (!TryEmitValueConvert(underlyingNullableTargetType, il, isChecked: false)) return false; il.Emit(OpCodes.Newobj, targetType.GetTypeInfo().DeclaredConstructors.GetFirst()); } else { var sourceVarIndex = EmitStoreLocalVariableAndLoadItsAddress(il, sourceType); il.Emit(OpCodes.Call, sourceType.FindNullableHasValueGetterMethod()); var labelSourceHasValue = il.DefineLabel(); il.Emit(OpCodes.Brtrue_S, labelSourceHasValue); // jump where source has a value // otherwise, emit and load a `new Nullable<TTarget>()` struct (that's why a Init instead of New) EmitLoadLocalVariable(il, InitValueTypeVariable(il, targetType)); // jump to completion var labelDone = il.DefineLabel(); il.Emit(OpCodes.Br_S, labelDone); // if source nullable has a value: il.MarkLabel(labelSourceHasValue); EmitLoadLocalVariableAddress(il, sourceVarIndex); il.Emit(OpCodes.Call, sourceType.FindNullableGetValueOrDefaultMethod()); if (!TryEmitValueConvert(underlyingNullableTargetType, il, expr.NodeType == ExpressionType.ConvertChecked)) { var convertOpMethod = method ?? underlyingNullableTargetType.FindConvertOperator(underlyingNullableSourceType, underlyingNullableTargetType); if (convertOpMethod == null) return false; // nor conversion nor conversion operator is found il.Emit(OpCodes.Call, convertOpMethod); } il.Emit(OpCodes.Newobj, targetType.GetTypeInfo().DeclaredConstructors.GetFirst()); il.MarkLabel(labelDone); } } else { if (targetType.GetTypeInfo().IsEnum) targetType = Enum.GetUnderlyingType(targetType); // fixes #159 if (sourceTypeIsNullable) { EmitStoreLocalVariableAndLoadItsAddress(il, sourceType); il.Emit(OpCodes.Call, sourceType.FindValueGetterMethod()); } // cast as the last resort and let's it fail if unlucky if (!TryEmitValueConvert(targetType, il, expr.NodeType == ExpressionType.ConvertChecked)) il.Emit(OpCodes.Castclass, targetType); } if ((parent & ParentFlags.IgnoreResult) != 0) il.Emit(OpCodes.Pop); return true; } private static bool TryEmitValueConvert(Type targetType, ILGenerator il, bool isChecked) { if (targetType == typeof(int)) il.Emit(isChecked ? OpCodes.Conv_Ovf_I4 : OpCodes.Conv_I4); else if (targetType == typeof(float)) il.Emit(OpCodes.Conv_R4); else if (targetType == typeof(uint)) il.Emit(isChecked ? OpCodes.Conv_Ovf_U4 : OpCodes.Conv_U4); else if (targetType == typeof(sbyte)) il.Emit(isChecked ? OpCodes.Conv_Ovf_I1 : OpCodes.Conv_I1); else if (targetType == typeof(byte)) il.Emit(isChecked ? OpCodes.Conv_Ovf_U1 : OpCodes.Conv_U1); else if (targetType == typeof(short)) il.Emit(isChecked ? OpCodes.Conv_Ovf_I2 : OpCodes.Conv_I2); else if (targetType == typeof(ushort) || targetType == typeof(char)) il.Emit(isChecked ? OpCodes.Conv_Ovf_U2 : OpCodes.Conv_U2); else if (targetType == typeof(long)) il.Emit(isChecked ? OpCodes.Conv_Ovf_I8 : OpCodes.Conv_I8); else if (targetType == typeof(ulong)) il.Emit(isChecked ? OpCodes.Conv_Ovf_U8 : OpCodes.Conv_U8); else if (targetType == typeof(double)) il.Emit(OpCodes.Conv_R8); else return false; return true; } private static bool TryEmitNotNullConstant( bool considerClosure, Type exprType, object constantValue, ILGenerator il, ref ClosureInfo closure) { var constValueType = constantValue.GetType(); if (considerClosure && IsClosureBoundConstant(constantValue, constValueType.GetTypeInfo())) { var constItems = closure.Constants.Items; var constIndex = closure.Constants.Count - 1; while (constIndex != -1 && !ReferenceEquals(constItems[constIndex], constantValue)) --constIndex; if (constIndex == -1) return false; var varIndex = closure.ConstantUsage.Items[constIndex] - 1; if (varIndex > 0) EmitLoadLocalVariable(il, varIndex); else { il.Emit(OpCodes.Ldloc_0); // load constants array from variable EmitLoadConstantInt(il, constIndex); il.Emit(OpCodes.Ldelem_Ref); if (exprType.IsValueType()) il.Emit(OpCodes.Unbox_Any, exprType); } } else { if (constantValue is string s) { il.Emit(OpCodes.Ldstr, s); return true; } if (constantValue is Type t) { il.Emit(OpCodes.Ldtoken, t); il.Emit(OpCodes.Call, _getTypeFromHandleMethod); return true; } // get raw enum type to light if (constValueType.GetTypeInfo().IsEnum) constValueType = Enum.GetUnderlyingType(constValueType); if (!TryEmitNumberConstant(il, constantValue, constValueType)) return false; } var underlyingNullableType = Nullable.GetUnderlyingType(exprType); if (underlyingNullableType != null) il.Emit(OpCodes.Newobj, exprType.GetTypeInfo().DeclaredConstructors.GetFirst()); // boxing the value type, otherwise we can get a strange result when 0 is treated as Null. else if (exprType == typeof(object) && constValueType.IsValueType()) il.Emit(OpCodes.Box, constantValue.GetType()); // using normal type for Enum instead of underlying type return true; } // todo: can we do something about boxing? private static bool TryEmitNumberConstant(ILGenerator il, object constantValue, Type constValueType) { if (constValueType == typeof(int)) { EmitLoadConstantInt(il, (int)constantValue); } else if (constValueType == typeof(char)) { EmitLoadConstantInt(il, (char)constantValue); } else if (constValueType == typeof(short)) { EmitLoadConstantInt(il, (short)constantValue); } else if (constValueType == typeof(byte)) { EmitLoadConstantInt(il, (byte)constantValue); } else if (constValueType == typeof(ushort)) { EmitLoadConstantInt(il, (ushort)constantValue); } else if (constValueType == typeof(sbyte)) { EmitLoadConstantInt(il, (sbyte)constantValue); } else if (constValueType == typeof(uint)) { unchecked { EmitLoadConstantInt(il, (int)(uint)constantValue); } } else if (constValueType == typeof(long)) { il.Emit(OpCodes.Ldc_I8, (long)constantValue); } else if (constValueType == typeof(ulong)) { unchecked { il.Emit(OpCodes.Ldc_I8, (long)(ulong)constantValue); } } else if (constValueType == typeof(float)) { il.Emit(OpCodes.Ldc_R4, (float)constantValue); } else if (constValueType == typeof(double)) { il.Emit(OpCodes.Ldc_R8, (double)constantValue); } else if (constValueType == typeof(bool)) { il.Emit((bool)constantValue ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); } else if (constValueType == typeof(IntPtr)) { il.Emit(OpCodes.Ldc_I8, ((IntPtr)constantValue).ToInt64()); } else if (constValueType == typeof(UIntPtr)) { unchecked { il.Emit(OpCodes.Ldc_I8, (long)((UIntPtr)constantValue).ToUInt64()); } } else if (constValueType == typeof(decimal)) { EmitDecimalConstant((decimal)constantValue, il); } else { return false; } return true; } internal static bool TryEmitNumberOne(ILGenerator il, Type type) { if (type == typeof(int) || type == typeof(char) || type == typeof(short) || type == typeof(byte) || type == typeof(ushort) || type == typeof(sbyte) || type == typeof(uint)) { il.Emit(OpCodes.Ldc_I4_1); } else if (type == typeof(long) || type == typeof(ulong) || type == typeof(IntPtr) || type == typeof(UIntPtr)) { il.Emit(OpCodes.Ldc_I8, (long)1); } else if (type == typeof(float)) { il.Emit(OpCodes.Ldc_R4, 1f); } else if (type == typeof(double)) { il.Emit(OpCodes.Ldc_R8, 1d); } else { return false; } return true; } internal static void EmitLoadConstantsAndNestedLambdasIntoVars(ILGenerator il, ref ClosureInfo closure) { // Load constants array field from Closure and store it into the variable il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, ArrayClosureArrayField); EmitStoreLocalVariable(il, il.GetNextLocalVarIndex(typeof(object[]))); var constItems = closure.Constants.Items; var constCount = closure.Constants.Count; var constUsage = closure.ConstantUsage.Items; int varIndex; for (var i = 0; i < constCount; i++) { if (constUsage[i] > 1) { il.Emit(OpCodes.Ldloc_0);// load array field variable on a stack EmitLoadConstantInt(il, i); il.Emit(OpCodes.Ldelem_Ref); var varType = constItems[i].GetType(); if (varType.IsValueType()) il.Emit(OpCodes.Unbox_Any, varType); varIndex = il.GetNextLocalVarIndex(varType); constUsage[i] = varIndex + 1; // to distinguish from the default 1 EmitStoreLocalVariable(il, varIndex); } } var nestedLambdas = closure.NestedLambdas; for (var i = 0; i < nestedLambdas.Length; i++) { var nestedLambda = nestedLambdas[i]; if (nestedLambda.UsageCountOrVarIndex > 1) { il.Emit(OpCodes.Ldloc_0);// load array field variable on a stack EmitLoadConstantInt(il, constCount + i); il.Emit(OpCodes.Ldelem_Ref); varIndex = il.GetNextLocalVarIndex(nestedLambda.Lambda.GetType()); nestedLambda.UsageCountOrVarIndex = varIndex + 1; EmitStoreLocalVariable(il, varIndex); } } } private static void EmitDecimalConstant(decimal value, ILGenerator il) { //check if decimal has decimal places, if not use shorter IL code (constructor from int or long) if (value % 1 == 0) { if (value >= int.MinValue && value <= int.MaxValue) { EmitLoadConstantInt(il, decimal.ToInt32(value)); il.Emit(OpCodes.Newobj, typeof(decimal).FindSingleParamConstructor(typeof(int))); return; } if (value >= long.MinValue && value <= long.MaxValue) { il.Emit(OpCodes.Ldc_I8, decimal.ToInt64(value)); il.Emit(OpCodes.Newobj, typeof(decimal).FindSingleParamConstructor(typeof(long))); return; } } if (value == decimal.MinValue) { il.Emit(OpCodes.Ldsfld, typeof(decimal).GetTypeInfo().GetDeclaredField(nameof(decimal.MinValue))); return; } if (value == decimal.MaxValue) { il.Emit(OpCodes.Ldsfld, typeof(decimal).GetTypeInfo().GetDeclaredField(nameof(decimal.MaxValue))); return; } var parts = decimal.GetBits(value); var sign = (parts[3] & 0x80000000) != 0; var scale = (byte)((parts[3] >> 16) & 0x7F); EmitLoadConstantInt(il, parts[0]); EmitLoadConstantInt(il, parts[1]); EmitLoadConstantInt(il, parts[2]); il.Emit(sign ? OpCodes.Ldc_I4_1 : OpCodes.Ldc_I4_0); EmitLoadConstantInt(il, scale); il.Emit(OpCodes.Conv_U1); il.Emit(OpCodes.Newobj, _decimalCtor.Value); } private static readonly Lazy<ConstructorInfo> _decimalCtor = new Lazy<ConstructorInfo>(() => { foreach (var ctor in typeof(decimal).GetTypeInfo().DeclaredConstructors) if (ctor.GetParameters().Length == 5) return ctor; return null; }); private static int InitValueTypeVariable(ILGenerator il, Type exprType) { var locVarIndex = il.GetNextLocalVarIndex(exprType); EmitLoadLocalVariableAddress(il, locVarIndex); il.Emit(OpCodes.Initobj, exprType); return locVarIndex; } private static bool EmitNewArray(NewArrayExpression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { var arrayType = expr.Type; var elems = expr.Expressions; var elemType = arrayType.GetElementType(); if (elemType == null) return false; var rank = arrayType.GetArrayRank(); if (rank == 1) // one dimensional { EmitLoadConstantInt(il, elems.Count); } else // multi dimensional { for (var i = 0; i < elems.Count; i++) if (!TryEmit(elems[i], paramExprs, il, ref closure, parent, i)) return false; il.Emit(OpCodes.Newobj, arrayType.GetTypeInfo().DeclaredConstructors.GetFirst()); return true; } il.Emit(OpCodes.Newarr, elemType); var isElemOfValueType = elemType.IsValueType(); for (int i = 0, n = elems.Count; i < n; i++) { il.Emit(OpCodes.Dup); EmitLoadConstantInt(il, i); // loading element address for later copying of value into it. if (isElemOfValueType) il.Emit(OpCodes.Ldelema, elemType); if (!TryEmit(elems[i], paramExprs, il, ref closure, parent)) return false; if (isElemOfValueType) il.Emit(OpCodes.Stobj, elemType); // store element of value type by array element address else il.Emit(OpCodes.Stelem_Ref); } return true; } private static bool TryEmitArrayIndex(Type exprType, ILGenerator il) { if (exprType.IsValueType()) il.Emit(OpCodes.Ldelem, exprType); else il.Emit(OpCodes.Ldelem_Ref); return true; } private static bool EmitMemberInit(MemberInitExpression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { var valueVarIndex = -1; if (expr.Type.IsValueType()) valueVarIndex = il.GetNextLocalVarIndex(expr.Type); var newExpr = expr.NewExpression; #if LIGHT_EXPRESSION if (newExpr == null) { if (!TryEmit(expr.Expression, paramExprs, il, ref closure, parent)) return false; } else #endif { var argExprs = newExpr.Arguments; for (var i = 0; i < argExprs.Count; i++) if (!TryEmit(argExprs[i], paramExprs, il, ref closure, parent, i)) return false; var ctor = newExpr.Constructor; // ReSharper disable once ConditionIsAlwaysTrueOrFalse if (ctor != null) il.Emit(OpCodes.Newobj, ctor); else if (newExpr.Type.IsValueType()) { if (valueVarIndex == -1) valueVarIndex = il.GetNextLocalVarIndex(expr.Type); EmitLoadLocalVariableAddress(il, valueVarIndex); il.Emit(OpCodes.Initobj, newExpr.Type); } else return false; // null constructor and not a value type, better to fallback } var bindings = expr.Bindings; for (var i = 0; i < bindings.Count; i++) { var binding = bindings[i]; if (binding.BindingType != MemberBindingType.Assignment) return false; if (valueVarIndex != -1) // load local value address, to set its members EmitLoadLocalVariableAddress(il, valueVarIndex); else il.Emit(OpCodes.Dup); // duplicate member owner on stack if (!TryEmit(((MemberAssignment)binding).Expression, paramExprs, il, ref closure, parent) || !EmitMemberAssign(il, binding.Member)) return false; } if (valueVarIndex != -1) EmitLoadLocalVariable(il, valueVarIndex); return true; } private static bool EmitMemberAssign(ILGenerator il, MemberInfo member) { if (member is PropertyInfo prop) { var method = prop.DeclaringType.FindPropertySetMethod(prop.Name); if (method == null) return false; il.Emit(method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, method); return true; } if (member is FieldInfo field) { il.Emit(field.IsStatic ? OpCodes.Stsfld : OpCodes.Stfld, field); return true; } return false; } private static bool TryEmitIncDecAssign(UnaryExpression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { var operandExpr = expr.Operand; MemberExpression memberAccess; var useLocalVar = false; int localVarIndex, paramIndex = -1; var isParameterOrVariable = operandExpr.NodeType == ExpressionType.Parameter; var usesResult = (parent & ParentFlags.IgnoreResult) == 0; if (isParameterOrVariable) { localVarIndex = closure.GetDefinedLocalVarOrDefault((ParameterExpression)operandExpr); if (localVarIndex != -1) { EmitLoadLocalVariable(il, localVarIndex); useLocalVar = true; } else { paramIndex = paramExprs.Count - 1; while (paramIndex != -1 && !ReferenceEquals(paramExprs[paramIndex], operandExpr)) --paramIndex; if (paramIndex == -1) return false; il.Emit(OpCodes.Ldarg, paramIndex + 1); } memberAccess = null; } else if (operandExpr.NodeType == ExpressionType.MemberAccess) { memberAccess = (MemberExpression)operandExpr; if (!TryEmitMemberAccess(memberAccess, paramExprs, il, ref closure, parent | ParentFlags.DupMemberOwner)) return false; useLocalVar = memberAccess.Expression != null && (usesResult || memberAccess.Member is PropertyInfo); localVarIndex = useLocalVar ? il.GetNextLocalVarIndex(operandExpr.Type) : -1; } else return false; switch (expr.NodeType) { case ExpressionType.PreIncrementAssign: il.Emit(OpCodes.Ldc_I4_1); il.Emit(OpCodes.Add); StoreIncDecValue(il, usesResult, isParameterOrVariable, localVarIndex); break; case ExpressionType.PostIncrementAssign: StoreIncDecValue(il, usesResult, isParameterOrVariable, localVarIndex); il.Emit(OpCodes.Ldc_I4_1); il.Emit(OpCodes.Add); break; case ExpressionType.PreDecrementAssign: il.Emit(OpCodes.Ldc_I4_1); il.Emit(OpCodes.Sub); StoreIncDecValue(il, usesResult, isParameterOrVariable, localVarIndex); break; case ExpressionType.PostDecrementAssign: StoreIncDecValue(il, usesResult, isParameterOrVariable, localVarIndex); il.Emit(OpCodes.Ldc_I4_1); il.Emit(OpCodes.Sub); break; } if (isParameterOrVariable && paramIndex != -1) il.Emit(OpCodes.Starg_S, paramIndex + 1); else if (isParameterOrVariable || useLocalVar && !usesResult) EmitStoreLocalVariable(il, localVarIndex); if (isParameterOrVariable) return true; if (useLocalVar && !usesResult) EmitLoadLocalVariable(il, localVarIndex); if (!EmitMemberAssign(il, memberAccess.Member)) return false; if (useLocalVar && usesResult) EmitLoadLocalVariable(il, localVarIndex); return true; } private static void StoreIncDecValue(ILGenerator il, bool usesResult, bool isVar, int localVarIndex) { if (!usesResult) return; if (isVar || localVarIndex == -1) il.Emit(OpCodes.Dup); else { EmitStoreLocalVariable(il, localVarIndex); EmitLoadLocalVariable(il, localVarIndex); } } private static bool TryEmitAssign(BinaryExpression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { var left = expr.Left; var right = expr.Right; var leftNodeType = expr.Left.NodeType; var nodeType = expr.NodeType; // if this assignment is part of a single body-less expression or the result of a block // we should put its result to the evaluation stack before the return, otherwise we are // somewhere inside the block, so we shouldn't return with the result var flags = parent & ~ParentFlags.IgnoreResult; switch (leftNodeType) { case ExpressionType.Parameter: var leftParamExpr = (ParameterExpression)left; var paramIndex = paramExprs.Count - 1; while (paramIndex != -1 && !ReferenceEquals(paramExprs[paramIndex], leftParamExpr)) --paramIndex; var arithmeticNodeType = nodeType; switch (nodeType) { case ExpressionType.AddAssign: arithmeticNodeType = ExpressionType.Add; break; case ExpressionType.AddAssignChecked: arithmeticNodeType = ExpressionType.AddChecked; break; case ExpressionType.SubtractAssign: arithmeticNodeType = ExpressionType.Subtract; break; case ExpressionType.SubtractAssignChecked: arithmeticNodeType = ExpressionType.SubtractChecked; break; case ExpressionType.MultiplyAssign: arithmeticNodeType = ExpressionType.Multiply; break; case ExpressionType.MultiplyAssignChecked: arithmeticNodeType = ExpressionType.MultiplyChecked; break; case ExpressionType.DivideAssign: arithmeticNodeType = ExpressionType.Divide; break; case ExpressionType.ModuloAssign: arithmeticNodeType = ExpressionType.Modulo; break; case ExpressionType.PowerAssign: arithmeticNodeType = ExpressionType.Power; break; case ExpressionType.AndAssign: arithmeticNodeType = ExpressionType.And; break; case ExpressionType.OrAssign: arithmeticNodeType = ExpressionType.Or; break; case ExpressionType.ExclusiveOrAssign: arithmeticNodeType = ExpressionType.ExclusiveOr; break; case ExpressionType.LeftShiftAssign: arithmeticNodeType = ExpressionType.LeftShift; break; case ExpressionType.RightShiftAssign: arithmeticNodeType = ExpressionType.RightShift; break; } if (paramIndex != -1) { // shift parameter index by one, because the first one will be closure if ((closure.Status & ClosureStatus.ShouldBeStaticMethod) == 0) ++paramIndex; if (leftParamExpr.IsByRef) { if (paramIndex == 0) il.Emit(OpCodes.Ldarg_0); else if (paramIndex == 1) il.Emit(OpCodes.Ldarg_1); else if (paramIndex == 2) il.Emit(OpCodes.Ldarg_2); else if (paramIndex == 3) il.Emit(OpCodes.Ldarg_3); else il.Emit(OpCodes.Ldarg_S, (byte)paramIndex); } if (arithmeticNodeType == nodeType) { if (!TryEmit(right, paramExprs, il, ref closure, flags)) return false; } else if (!TryEmitArithmetic(expr, arithmeticNodeType, paramExprs, il, ref closure, parent)) return false; if ((parent & ParentFlags.IgnoreResult) == 0) il.Emit(OpCodes.Dup); // duplicate value to assign and return if (leftParamExpr.IsByRef) EmitByRefStore(il, leftParamExpr.Type); else il.Emit(OpCodes.Starg_S, paramIndex); return true; } else if (arithmeticNodeType != nodeType) { var localVarIdx = closure.GetDefinedLocalVarOrDefault(leftParamExpr); if (localVarIdx != -1) { if (!TryEmitArithmetic(expr, arithmeticNodeType, paramExprs, il, ref closure, parent)) return false; EmitStoreLocalVariable(il, localVarIdx); return true; } } // if parameter isn't passed, then it is passed into some outer lambda or it is a local variable, // so it should be loaded from closure or from the locals. Then the closure is null will be an invalid state. // if it's a local variable, then store the right value in it var localVariableIdx = closure.GetDefinedLocalVarOrDefault(leftParamExpr); if (localVariableIdx != -1) { if (!TryEmit(right, paramExprs, il, ref closure, flags)) return false; if ((right as ParameterExpression)?.IsByRef == true) il.Emit(OpCodes.Ldind_I4); if ((parent & ParentFlags.IgnoreResult) == 0) // if we have to push the result back, duplicate the right value il.Emit(OpCodes.Dup); EmitStoreLocalVariable(il, localVariableIdx); return true; } // check that it's a captured parameter by closure var nonPassedParams = closure.NonPassedParameters; var nonPassedParamIndex = nonPassedParams.Length - 1; while (nonPassedParamIndex != -1 && !ReferenceEquals(nonPassedParams[nonPassedParamIndex], leftParamExpr)) --nonPassedParamIndex; if (nonPassedParamIndex == -1) return false; // what??? no chance il.Emit(OpCodes.Ldarg_0); // closure is always a first argument if ((parent & ParentFlags.IgnoreResult) == 0) { if (!TryEmit(right, paramExprs, il, ref closure, flags)) return false; var valueVarIndex = il.GetNextLocalVarIndex(expr.Type); // store left value in variable EmitStoreLocalVariable(il, valueVarIndex); // load array field and param item index il.Emit(OpCodes.Ldfld, ArrayClosureWithNonPassedParamsField); EmitLoadConstantInt(il, nonPassedParamIndex); EmitLoadLocalVariable(il, valueVarIndex); if (expr.Type.IsValueType()) il.Emit(OpCodes.Box, expr.Type); il.Emit(OpCodes.Stelem_Ref); // put the variable into array EmitLoadLocalVariable(il, valueVarIndex); } else { // load array field and param item index il.Emit(OpCodes.Ldfld, ArrayClosureWithNonPassedParamsField); EmitLoadConstantInt(il, nonPassedParamIndex); if (!TryEmit(right, paramExprs, il, ref closure, flags)) return false; if (expr.Type.IsValueType()) il.Emit(OpCodes.Box, expr.Type); il.Emit(OpCodes.Stelem_Ref); // put the variable into array } return true; case ExpressionType.MemberAccess: var assignFromLocalVar = right.NodeType == ExpressionType.Try; var resultLocalVarIndex = -1; if (assignFromLocalVar) { resultLocalVarIndex = il.GetNextLocalVarIndex(right.Type); if (!TryEmit(right, paramExprs, il, ref closure, ParentFlags.Empty)) return false; EmitStoreLocalVariable(il, resultLocalVarIndex); } var memberExpr = (MemberExpression)left; var objExpr = memberExpr.Expression; if (objExpr != null && !TryEmit(objExpr, paramExprs, il, ref closure, flags | ParentFlags.MemberAccess | ParentFlags.InstanceAccess)) return false; if (assignFromLocalVar) EmitLoadLocalVariable(il, resultLocalVarIndex); else if (!TryEmit(right, paramExprs, il, ref closure, ParentFlags.Empty)) return false; var member = memberExpr.Member; if ((parent & ParentFlags.IgnoreResult) != 0) return EmitMemberAssign(il, member); il.Emit(OpCodes.Dup); var rightVarIndex = il.GetNextLocalVarIndex(expr.Type); // store right value in variable EmitStoreLocalVariable(il, rightVarIndex); if (!EmitMemberAssign(il, member)) return false; EmitLoadLocalVariable(il, rightVarIndex); return true; case ExpressionType.Index: var indexExpr = (IndexExpression)left; var obj = indexExpr.Object; if (obj != null && !TryEmit(obj, paramExprs, il, ref closure, flags)) return false; var indexArgExprs = indexExpr.Arguments; for (var i = 0; i < indexArgExprs.Count; i++) if (!TryEmit(indexArgExprs[i], paramExprs, il, ref closure, flags, i)) return false; if (!TryEmit(right, paramExprs, il, ref closure, flags)) return false; if ((parent & ParentFlags.IgnoreResult) != 0) return TryEmitIndexAssign(indexExpr, obj?.Type, expr.Type, il); var varIndex = il.GetNextLocalVarIndex(expr.Type); // store value in variable to return il.Emit(OpCodes.Dup); EmitStoreLocalVariable(il, varIndex); if (!TryEmitIndexAssign(indexExpr, obj?.Type, expr.Type, il)) return false; EmitLoadLocalVariable(il, varIndex); return true; default: // todo: not yet support assignment targets return false; } } private static void EmitByRefStore(ILGenerator il, Type type) { if (type == typeof(int) || type == typeof(uint)) il.Emit(OpCodes.Stind_I4); else if (type == typeof(byte)) il.Emit(OpCodes.Stind_I1); else if (type == typeof(short) || type == typeof(ushort)) il.Emit(OpCodes.Stind_I2); else if (type == typeof(long) || type == typeof(ulong)) il.Emit(OpCodes.Stind_I8); else if (type == typeof(float)) il.Emit(OpCodes.Stind_R4); else if (type == typeof(double)) il.Emit(OpCodes.Stind_R8); else if (type == typeof(object)) il.Emit(OpCodes.Stind_Ref); else if (type == typeof(IntPtr) || type == typeof(UIntPtr)) il.Emit(OpCodes.Stind_I); else il.Emit(OpCodes.Stobj, type); } private static bool TryEmitIndexAssign(IndexExpression indexExpr, Type instType, Type elementType, ILGenerator il) { if (indexExpr.Indexer != null) return EmitMemberAssign(il, indexExpr.Indexer); if (indexExpr.Arguments.Count == 1) // one dimensional array { if (elementType.IsValueType()) il.Emit(OpCodes.Stelem, elementType); else il.Emit(OpCodes.Stelem_Ref); return true; } // multi dimensional array return EmitMethodCall(il, instType?.FindMethod("Set")); } private static bool TryEmitMethodCall(Expression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { var flags = parent & ~ParentFlags.IgnoreResult | ParentFlags.Call; var callExpr = (MethodCallExpression)expr; var objExpr = callExpr.Object; var method = callExpr.Method; var methodParams = method.GetParameters(); var objIsValueType = false; if (objExpr != null) { if (!TryEmit(objExpr, paramExprs, il, ref closure, flags | ParentFlags.InstanceAccess)) return false; objIsValueType = objExpr.Type.IsValueType(); if (objIsValueType && objExpr.NodeType != ExpressionType.Parameter && !closure.LastEmitIsAddress) EmitStoreLocalVariableAndLoadItsAddress(il, objExpr.Type); } #if LIGHT_EXPRESSION var fewArgCount = callExpr.FewArgumentCount; if (fewArgCount >= 0) { if (fewArgCount == 1) { if (!TryEmit(((OneArgumentMethodCallExpression)callExpr).Argument, paramExprs, il, ref closure, flags, methodParams[0].ParameterType.IsByRef ? 0 : -1)) return false; } else if (fewArgCount == 2) { var twoArgsExpr = (TwoArgumentsMethodCallExpression)callExpr; if (!TryEmit(twoArgsExpr.Argument0, paramExprs, il, ref closure, flags, methodParams[0].ParameterType.IsByRef ? 0 : -1) || !TryEmit(twoArgsExpr.Argument1, paramExprs, il, ref closure, flags, methodParams[1].ParameterType.IsByRef ? 1 : -1)) return false; } else if (fewArgCount == 3) { var threeArgsExpr = (ThreeArgumentsMethodCallExpression)callExpr; if (!TryEmit(threeArgsExpr.Argument0, paramExprs, il, ref closure, flags, methodParams[0].ParameterType.IsByRef ? 0 : -1) || !TryEmit(threeArgsExpr.Argument1, paramExprs, il, ref closure, flags, methodParams[1].ParameterType.IsByRef ? 1 : -1) || !TryEmit(threeArgsExpr.Argument2, paramExprs, il, ref closure, flags, methodParams[2].ParameterType.IsByRef ? 2 : -1)) return false; } else if (fewArgCount == 4) { var fourArgsExpr = (FourArgumentsMethodCallExpression)callExpr; if (!TryEmit(fourArgsExpr.Argument0, paramExprs, il, ref closure, flags, methodParams[0].ParameterType.IsByRef ? 0 : -1) || !TryEmit(fourArgsExpr.Argument1, paramExprs, il, ref closure, flags, methodParams[1].ParameterType.IsByRef ? 1 : -1) || !TryEmit(fourArgsExpr.Argument2, paramExprs, il, ref closure, flags, methodParams[2].ParameterType.IsByRef ? 2 : -1) || !TryEmit(fourArgsExpr.Argument3, paramExprs, il, ref closure, flags, methodParams[3].ParameterType.IsByRef ? 3 : -1)) return false; } else if (fewArgCount == 5) { var fiveArgsExpr = (FiveArgumentsMethodCallExpression)callExpr; if (!TryEmit(fiveArgsExpr.Argument0, paramExprs, il, ref closure, flags, methodParams[0].ParameterType.IsByRef ? 0 : -1) || !TryEmit(fiveArgsExpr.Argument1, paramExprs, il, ref closure, flags, methodParams[1].ParameterType.IsByRef ? 1 : -1) || !TryEmit(fiveArgsExpr.Argument2, paramExprs, il, ref closure, flags, methodParams[2].ParameterType.IsByRef ? 2 : -1) || !TryEmit(fiveArgsExpr.Argument3, paramExprs, il, ref closure, flags, methodParams[3].ParameterType.IsByRef ? 3 : -1) || !TryEmit(fiveArgsExpr.Argument4, paramExprs, il, ref closure, flags, methodParams[4].ParameterType.IsByRef ? 4 : -1)) return false; } if (objIsValueType && method.IsVirtual) il.Emit(OpCodes.Constrained, objExpr.Type); il.Emit(method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, method); if (parent.IgnoresResult() && method.ReturnType != typeof(void)) il.Emit(OpCodes.Pop); closure.LastEmitIsAddress = false; return true; } #endif var args = callExpr.Arguments; for (var i = 0; i < methodParams.Length; i++) if (!TryEmit(args[i], paramExprs, il, ref closure, flags, methodParams[i].ParameterType.IsByRef ? i : -1)) return false; if (objIsValueType && method.IsVirtual) il.Emit(OpCodes.Constrained, objExpr.Type); il.Emit(method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, method); if (parent.IgnoresResult() && method.ReturnType != typeof(void)) il.Emit(OpCodes.Pop); closure.LastEmitIsAddress = false; return true; } private static bool TryEmitMemberAccess(MemberExpression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { if (expr.Member is PropertyInfo prop) { var instanceExpr = expr.Expression; if (instanceExpr != null) { if (!TryEmit(instanceExpr, paramExprs, il, ref closure, ~ParentFlags.IgnoreResult & ~ParentFlags.DupMemberOwner & (parent | ParentFlags.Call | ParentFlags.MemberAccess | ParentFlags.InstanceAccess))) return false; if ((parent & ParentFlags.DupMemberOwner) != 0) il.Emit(OpCodes.Dup); // Value type special treatment to load address of value instance in order to access a field or call a method. // Parameter should be excluded because it already loads an address via `LDARGA`, and you don't need to. // And for field access no need to load address, cause the field stored on stack nearby if (!closure.LastEmitIsAddress && instanceExpr.NodeType != ExpressionType.Parameter && instanceExpr.Type.IsValueType()) EmitStoreLocalVariableAndLoadItsAddress(il, instanceExpr.Type); } closure.LastEmitIsAddress = false; var propGetter = prop.DeclaringType.FindPropertyGetMethod(prop.Name); if (propGetter == null) return false; il.Emit(propGetter.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, propGetter); return true; } if (expr.Member is FieldInfo field) { var instanceExpr = expr.Expression; if (instanceExpr != null) { if (!TryEmit(instanceExpr, paramExprs, il, ref closure, ~ParentFlags.IgnoreResult & ~ParentFlags.DupMemberOwner & (parent | ParentFlags.MemberAccess | ParentFlags.InstanceAccess))) return false; if ((parent & ParentFlags.DupMemberOwner) != 0) il.Emit(OpCodes.Dup); closure.LastEmitIsAddress = field.FieldType.IsValueType() && (parent & ParentFlags.InstanceAccess) != 0; il.Emit(closure.LastEmitIsAddress ? OpCodes.Ldflda : OpCodes.Ldfld, field); } else if (field.IsLiteral) { var fieldValue = field.GetValue(null); if (fieldValue != null) return TryEmitNotNullConstant(false, field.FieldType, fieldValue, il, ref closure); il.Emit(OpCodes.Ldnull); } else { il.Emit(OpCodes.Ldsfld, field); } return true; } return false; } // ReSharper disable once FunctionComplexityOverflow private static bool TryEmitNestedLambda(LambdaExpression lambdaExpr, IReadOnlyList<ParameterExpression> outerParamExprs, ILGenerator il, ref ClosureInfo closure) { // First, find in closed compiled lambdas the one corresponding to the current lambda expression. // Situation with not found lambda is not possible/exceptional, // it means that we somehow skipped the lambda expression while collecting closure info. var outerNestedLambdas = closure.NestedLambdas; var outerNestedLambdaIndex = outerNestedLambdas.Length - 1; while (outerNestedLambdaIndex != -1 && !ReferenceEquals(outerNestedLambdas[outerNestedLambdaIndex].LambdaExpression, lambdaExpr)) --outerNestedLambdaIndex; if (outerNestedLambdaIndex == -1) return false; var nestedLambdaInfo = closure.NestedLambdas[outerNestedLambdaIndex]; var nestedLambda = nestedLambdaInfo.Lambda; var nestedLambdaInClosureIndex = outerNestedLambdaIndex + closure.Constants.Count; var varIndex = nestedLambdaInfo.UsageCountOrVarIndex - 1; if (varIndex > 0) EmitLoadLocalVariable(il, varIndex); else { il.Emit(OpCodes.Ldloc_0); EmitLoadConstantInt(il, nestedLambdaInClosureIndex); il.Emit(OpCodes.Ldelem_Ref); // load the array item object } // If lambda does not use any outer parameters to be set in closure, then we're done ref var nestedClosureInfo = ref nestedLambdaInfo.ClosureInfo; var nestedNonPassedParams = nestedClosureInfo.NonPassedParameters; if (nestedNonPassedParams.Length == 0) return true; //------------------------------------------------------------------- // For the lambda with non-passed parameters (or variables) in closure // we have loaded `NestedLambdaWithConstantsAndNestedLambdas` pair. if (varIndex > 0) { // we are already have variable loaded il.Emit(OpCodes.Ldfld, NestedLambdaWithConstantsAndNestedLambdas.NestedLambdaField); EmitLoadLocalVariable(il, varIndex); // load the variable for the second time il.Emit(OpCodes.Ldfld, NestedLambdaWithConstantsAndNestedLambdas.ConstantsAndNestedLambdasField); } else { var nestedLambdaAndClosureItemsVarIndex = il.GetNextLocalVarIndex(typeof(NestedLambdaWithConstantsAndNestedLambdas)); EmitStoreLocalVariable(il, nestedLambdaAndClosureItemsVarIndex); // - load the `NestedLambda` field EmitLoadLocalVariable(il, nestedLambdaAndClosureItemsVarIndex); il.Emit(OpCodes.Ldfld, NestedLambdaWithConstantsAndNestedLambdas.NestedLambdaField); // - load the `ConstantsAndNestedLambdas` field EmitLoadLocalVariable(il, nestedLambdaAndClosureItemsVarIndex); il.Emit(OpCodes.Ldfld, NestedLambdaWithConstantsAndNestedLambdas.ConstantsAndNestedLambdasField); } // - create `NonPassedParameters` array EmitLoadConstantInt(il, nestedNonPassedParams.Length); // size of array il.Emit(OpCodes.Newarr, typeof(object)); // - populate the `NonPassedParameters` array var outerNonPassedParams = closure.NonPassedParameters; for (var nestedParamIndex = 0; nestedParamIndex < nestedNonPassedParams.Length; ++nestedParamIndex) { var nestedParam = nestedNonPassedParams[nestedParamIndex]; // Duplicate nested array on stack to store the item, and load index to where to store il.Emit(OpCodes.Dup); EmitLoadConstantInt(il, nestedParamIndex); var outerParamIndex = outerParamExprs.Count - 1; while (outerParamIndex != -1 && !ReferenceEquals(outerParamExprs[outerParamIndex], nestedParam)) --outerParamIndex; if (outerParamIndex != -1) // load parameter from input outer params { // Add `+1` to index because the `0` index is for the closure argument if (outerParamIndex == 0) il.Emit(OpCodes.Ldarg_1); else if (outerParamIndex == 1) il.Emit(OpCodes.Ldarg_2); else if (outerParamIndex == 2) il.Emit(OpCodes.Ldarg_3); else il.Emit(OpCodes.Ldarg_S, (byte)(1 + outerParamIndex)); if (nestedParam.Type.IsValueType()) il.Emit(OpCodes.Box, nestedParam.Type); } else // load parameter from outer closure or from the local variables { if (outerNonPassedParams.Length == 0) return false; // impossible, better to throw? var variableIdx = closure.GetDefinedLocalVarOrDefault(nestedParam); if (variableIdx != -1) // it's a local variable { EmitLoadLocalVariable(il, variableIdx); } else // it's a parameter from the outer closure { var outerNonPassedParamIndex = outerNonPassedParams.Length - 1; while (outerNonPassedParamIndex != -1 && !ReferenceEquals(outerNonPassedParams[outerNonPassedParamIndex], nestedParam)) --outerNonPassedParamIndex; if (outerNonPassedParamIndex == -1) return false; // impossible // Load the parameter from outer closure `Items` array il.Emit(OpCodes.Ldarg_0); // closure is always a first argument il.Emit(OpCodes.Ldfld, ArrayClosureWithNonPassedParamsField); EmitLoadConstantInt(il, outerNonPassedParamIndex); il.Emit(OpCodes.Ldelem_Ref); } } // Store the item into nested lambda array il.Emit(OpCodes.Stelem_Ref); } // - create `ArrayClosureWithNonPassedParams` out of the both above il.Emit(OpCodes.Newobj, ArrayClosureWithNonPassedParamsConstructor); // - call `Curry` method with nested lambda and array closure to produce a closed lambda with the expected signature var lambdaTypeArgs = nestedLambda.GetType().GetTypeInfo().GenericTypeArguments; var closureMethod = nestedLambdaInfo.LambdaExpression.ReturnType == typeof(void) ? CurryClosureActions.Methods[lambdaTypeArgs.Length - 1].MakeGenericMethod(lambdaTypeArgs) : CurryClosureFuncs.Methods[lambdaTypeArgs.Length - 2].MakeGenericMethod(lambdaTypeArgs); il.Emit(OpCodes.Call, closureMethod); return true; } private static bool TryEmitInvoke(InvocationExpression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { var lambda = expr.Expression; if (!TryEmit(lambda, paramExprs, il, ref closure, parent & ~ParentFlags.IgnoreResult)) return false; var argExprs = expr.Arguments; for (var i = 0; i < argExprs.Count; i++) if (!TryEmit(argExprs[i], paramExprs, il, ref closure, parent & ~ParentFlags.IgnoreResult & ~ParentFlags.InstanceAccess, argExprs[i].Type.IsByRef ? i : -1)) return false; var delegateInvokeMethod = lambda.Type.FindDelegateInvokeMethod(); il.Emit(OpCodes.Call, delegateInvokeMethod); if ((parent & ParentFlags.IgnoreResult) != 0 && delegateInvokeMethod.ReturnType != typeof(void)) il.Emit(OpCodes.Pop); return true; } private static bool TryEmitSwitch(SwitchExpression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { // todo: //- use switch statement for int comparison (if int difference is less or equal 3 -> use IL switch) //- TryEmitComparison should not emit "CEQ" so we could use Beq_S instead of Brtrue_S (not always possible (nullable)) //- if switch SwitchValue is a nullable parameter, we should call getValue only once and store the result. //- use comparison methods (when defined) var endLabel = il.DefineLabel(); var labels = new Label[expr.Cases.Count]; for (var index = 0; index < expr.Cases.Count; index++) { var switchCase = expr.Cases[index]; labels[index] = il.DefineLabel(); foreach (var switchCaseTestValue in switchCase.TestValues) { if (!TryEmitComparison(expr.SwitchValue, switchCaseTestValue, ExpressionType.Equal, paramExprs, il, ref closure, parent)) return false; il.Emit(OpCodes.Brtrue, labels[index]); } } if (expr.DefaultBody != null) { if (!TryEmit(expr.DefaultBody, paramExprs, il, ref closure, parent)) return false; il.Emit(OpCodes.Br, endLabel); } for (var index = 0; index < expr.Cases.Count; index++) { var switchCase = expr.Cases[index]; il.MarkLabel(labels[index]); if (!TryEmit(switchCase.Body, paramExprs, il, ref closure, parent)) return false; if (index != expr.Cases.Count - 1) il.Emit(OpCodes.Br, endLabel); } il.MarkLabel(endLabel); return true; } private static bool TryEmitComparison(Expression exprLeft, Expression exprRight, ExpressionType expressionType, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { var leftOpType = exprLeft.Type; var leftIsNullable = leftOpType.IsNullable(); var rightOpType = exprRight.Type; if (exprRight is ConstantExpression c && c.Value == null && exprRight.Type == typeof(object)) rightOpType = leftOpType; int lVarIndex = -1, rVarIndex = -1; if (!TryEmit(exprLeft, paramExprs, il, ref closure, parent & ~ParentFlags.IgnoreResult & ~ParentFlags.InstanceAccess)) return false; if (leftIsNullable) { lVarIndex = EmitStoreLocalVariableAndLoadItsAddress(il, leftOpType); il.Emit(OpCodes.Call, leftOpType.FindNullableGetValueOrDefaultMethod()); leftOpType = Nullable.GetUnderlyingType(leftOpType); } if (!TryEmit(exprRight, paramExprs, il, ref closure, parent & ~ParentFlags.IgnoreResult & ~ParentFlags.InstanceAccess)) return false; if (leftOpType != rightOpType) { if (leftOpType.IsClass() && rightOpType.IsClass() && (leftOpType == typeof(object) || rightOpType == typeof(object))) { if (expressionType == ExpressionType.Equal) { il.Emit(OpCodes.Ceq); if ((parent & ParentFlags.IgnoreResult) != 0) il.Emit(OpCodes.Pop); } else if (expressionType == ExpressionType.NotEqual) { il.Emit(OpCodes.Ceq); il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Ceq); } else return false; if ((parent & ParentFlags.IgnoreResult) != 0) il.Emit(OpCodes.Pop); return true; } } if (rightOpType.IsNullable()) { rVarIndex = EmitStoreLocalVariableAndLoadItsAddress(il, rightOpType); il.Emit(OpCodes.Call, rightOpType.FindNullableGetValueOrDefaultMethod()); // ReSharper disable once AssignNullToNotNullAttribute rightOpType = Nullable.GetUnderlyingType(rightOpType); } var leftOpTypeInfo = leftOpType.GetTypeInfo(); if (!leftOpTypeInfo.IsPrimitive && !leftOpTypeInfo.IsEnum) { var methodName = expressionType == ExpressionType.Equal ? "op_Equality" : expressionType == ExpressionType.NotEqual ? "op_Inequality" : expressionType == ExpressionType.GreaterThan ? "op_GreaterThan" : expressionType == ExpressionType.GreaterThanOrEqual ? "op_GreaterThanOrEqual" : expressionType == ExpressionType.LessThan ? "op_LessThan" : expressionType == ExpressionType.LessThanOrEqual ? "op_LessThanOrEqual" : null; if (methodName == null) return false; // todo: for now handling only parameters of the same type var methods = leftOpTypeInfo.DeclaredMethods.AsArray(); for (var i = 0; i < methods.Length; i++) { var m = methods[i]; if (m.IsSpecialName && m.IsStatic && m.Name == methodName && IsComparisonOperatorSignature(leftOpType, m.GetParameters())) { il.Emit(OpCodes.Call, m); return true; } } if (expressionType != ExpressionType.Equal && expressionType != ExpressionType.NotEqual) return false; il.Emit(OpCodes.Call, _objectEqualsMethod); if (expressionType == ExpressionType.NotEqual) // invert result for not equal { il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Ceq); } if (leftIsNullable) goto nullCheck; if ((parent & ParentFlags.IgnoreResult) > 0) il.Emit(OpCodes.Pop); return true; } // handle primitives comparison switch (expressionType) { case ExpressionType.Equal: il.Emit(OpCodes.Ceq); break; case ExpressionType.NotEqual: il.Emit(OpCodes.Ceq); il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Ceq); break; case ExpressionType.LessThan: il.Emit(OpCodes.Clt); break; case ExpressionType.GreaterThan: il.Emit(OpCodes.Cgt); break; case ExpressionType.GreaterThanOrEqual: case ExpressionType.LessThanOrEqual: var ifTrueLabel = il.DefineLabel(); if (rightOpType == typeof(uint) || rightOpType == typeof(ulong) || rightOpType == typeof(ushort) || rightOpType == typeof(byte)) il.Emit(expressionType == ExpressionType.GreaterThanOrEqual ? OpCodes.Bge_Un_S : OpCodes.Ble_Un_S, ifTrueLabel); else il.Emit(expressionType == ExpressionType.GreaterThanOrEqual ? OpCodes.Bge_S : OpCodes.Ble_S, ifTrueLabel); il.Emit(OpCodes.Ldc_I4_0); var doneLabel = il.DefineLabel(); il.Emit(OpCodes.Br_S, doneLabel); il.MarkLabel(ifTrueLabel); il.Emit(OpCodes.Ldc_I4_1); il.MarkLabel(doneLabel); break; default: return false; } nullCheck: if (leftIsNullable) { var leftNullableHasValueGetterMethod = exprLeft.Type.FindNullableHasValueGetterMethod(); EmitLoadLocalVariableAddress(il, lVarIndex); il.Emit(OpCodes.Call, leftNullableHasValueGetterMethod); // ReSharper disable once AssignNullToNotNullAttribute EmitLoadLocalVariableAddress(il, rVarIndex); il.Emit(OpCodes.Call, leftNullableHasValueGetterMethod); switch (expressionType) { case ExpressionType.Equal: il.Emit(OpCodes.Ceq); // compare both HasValue calls il.Emit(OpCodes.And); // both results need to be true break; case ExpressionType.NotEqual: il.Emit(OpCodes.Ceq); il.Emit(OpCodes.Ldc_I4_0); il.Emit(OpCodes.Ceq); il.Emit(OpCodes.Or); break; case ExpressionType.LessThan: case ExpressionType.GreaterThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThanOrEqual: il.Emit(OpCodes.Ceq); il.Emit(OpCodes.Ldc_I4_1); il.Emit(OpCodes.Ceq); il.Emit(OpCodes.And); break; default: return false; } } if ((parent & ParentFlags.IgnoreResult) > 0) il.Emit(OpCodes.Pop); return true; } private static bool IsComparisonOperatorSignature(Type t, ParameterInfo[] pars) => pars.Length == 2 && pars[0].ParameterType == t && pars[1].ParameterType == t; private static bool TryEmitArithmetic(BinaryExpression expr, ExpressionType exprNodeType, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { var flags = parent & ~ParentFlags.IgnoreResult & ~ParentFlags.InstanceCall | ParentFlags.Arithmetic; var leftNoValueLabel = default(Label); var leftExpr = expr.Left; var lefType = leftExpr.Type; var leftIsNullable = lefType.IsNullable(); if (leftIsNullable) { leftNoValueLabel = il.DefineLabel(); if (!TryEmit(leftExpr, paramExprs, il, ref closure, flags | ParentFlags.InstanceCall)) return false; if (!closure.LastEmitIsAddress) EmitStoreLocalVariableAndLoadItsAddress(il, lefType); il.Emit(OpCodes.Dup); il.Emit(OpCodes.Call, lefType.FindNullableHasValueGetterMethod()); il.Emit(OpCodes.Brfalse, leftNoValueLabel); il.Emit(OpCodes.Call, lefType.FindNullableGetValueOrDefaultMethod()); } else if (!TryEmit(leftExpr, paramExprs, il, ref closure, flags)) return false; var rightNoValueLabel = default(Label); var rightExpr = expr.Right; var rightType = rightExpr.Type; var rightIsNullable = rightType.IsNullable(); if (rightIsNullable) { rightNoValueLabel = il.DefineLabel(); if (!TryEmit(rightExpr, paramExprs, il, ref closure, flags | ParentFlags.InstanceCall)) return false; if (!closure.LastEmitIsAddress) EmitStoreLocalVariableAndLoadItsAddress(il, rightType); il.Emit(OpCodes.Dup); il.Emit(OpCodes.Call, rightType.FindNullableHasValueGetterMethod()); il.Emit(OpCodes.Brfalse, rightNoValueLabel); il.Emit(OpCodes.Call, rightType.FindNullableGetValueOrDefaultMethod()); } else if (!TryEmit(rightExpr, paramExprs, il, ref closure, flags)) return false; var exprType = expr.Type; if (!TryEmitArithmeticOperation(expr, exprNodeType, exprType, il)) return false; if (leftIsNullable || rightIsNullable) { var valueLabel = il.DefineLabel(); il.Emit(OpCodes.Br, valueLabel); if (rightIsNullable) il.MarkLabel(rightNoValueLabel); il.Emit(OpCodes.Pop); if (leftIsNullable) il.MarkLabel(leftNoValueLabel); il.Emit(OpCodes.Pop); if (exprType.IsNullable()) { var endL = il.DefineLabel(); var locIndex = InitValueTypeVariable(il, exprType); EmitLoadLocalVariable(il, locIndex); il.Emit(OpCodes.Br_S, endL); il.MarkLabel(valueLabel); il.Emit(OpCodes.Newobj, exprType.GetTypeInfo().DeclaredConstructors.GetFirst()); il.MarkLabel(endL); } else { il.Emit(OpCodes.Ldc_I4_0); il.MarkLabel(valueLabel); } } return true; } private static bool TryEmitArithmeticOperation(BinaryExpression expr, ExpressionType exprNodeType, Type exprType, ILGenerator il) { if (!exprType.IsPrimitive()) { if (exprType.IsNullable()) exprType = Nullable.GetUnderlyingType(exprType); if (!exprType.IsPrimitive()) { MethodInfo method = null; if (exprType == typeof(string)) { var paraType = typeof(string); if (expr.Left.Type != expr.Right.Type || expr.Left.Type != typeof(string)) paraType = typeof(object); var methods = typeof(string).GetTypeInfo().DeclaredMethods.AsArray(); for (var i = 0; i < methods.Length; i++) { var m = methods[i]; if (m.IsStatic && m.Name == "Concat" && m.GetParameters().Length == 2 && m.GetParameters()[0].ParameterType == paraType) { method = m; break; } } } else { var methodName = exprNodeType == ExpressionType.Add ? "op_Addition" : exprNodeType == ExpressionType.AddChecked ? "op_Addition" : exprNodeType == ExpressionType.Subtract ? "op_Subtraction" : exprNodeType == ExpressionType.SubtractChecked ? "op_Subtraction" : exprNodeType == ExpressionType.Multiply ? "op_Multiply" : exprNodeType == ExpressionType.MultiplyChecked ? "op_Multiply" : exprNodeType == ExpressionType.Divide ? "op_Division" : exprNodeType == ExpressionType.Modulo ? "op_Modulus" : null; if (methodName != null) { var methods = exprType.GetTypeInfo().DeclaredMethods.AsArray(); for (var i = 0; method == null && i < methods.Length; i++) { var m = methods[i]; if (m.IsSpecialName && m.IsStatic && m.Name == methodName) method = m; } } } if (method == null) return false; il.Emit(method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, method); return true; } } switch (exprNodeType) { case ExpressionType.Add: case ExpressionType.AddAssign: il.Emit(OpCodes.Add); return true; case ExpressionType.AddChecked: case ExpressionType.AddAssignChecked: il.Emit(exprType.IsUnsigned() ? OpCodes.Add_Ovf_Un : OpCodes.Add_Ovf); return true; case ExpressionType.Subtract: case ExpressionType.SubtractAssign: il.Emit(OpCodes.Sub); return true; case ExpressionType.SubtractChecked: case ExpressionType.SubtractAssignChecked: il.Emit(exprType.IsUnsigned() ? OpCodes.Sub_Ovf_Un : OpCodes.Sub_Ovf); return true; case ExpressionType.Multiply: case ExpressionType.MultiplyAssign: il.Emit(OpCodes.Mul); return true; case ExpressionType.MultiplyChecked: case ExpressionType.MultiplyAssignChecked: il.Emit(exprType.IsUnsigned() ? OpCodes.Mul_Ovf_Un : OpCodes.Mul_Ovf); return true; case ExpressionType.Divide: case ExpressionType.DivideAssign: il.Emit(OpCodes.Div); return true; case ExpressionType.Modulo: case ExpressionType.ModuloAssign: il.Emit(OpCodes.Rem); return true; case ExpressionType.And: case ExpressionType.AndAssign: il.Emit(OpCodes.And); return true; case ExpressionType.Or: case ExpressionType.OrAssign: il.Emit(OpCodes.Or); return true; case ExpressionType.ExclusiveOr: case ExpressionType.ExclusiveOrAssign: il.Emit(OpCodes.Xor); return true; case ExpressionType.LeftShift: case ExpressionType.LeftShiftAssign: il.Emit(OpCodes.Shl); return true; case ExpressionType.RightShift: case ExpressionType.RightShiftAssign: il.Emit(OpCodes.Shr); return true; case ExpressionType.Power: il.Emit(OpCodes.Call, typeof(Math).FindMethod("Pow")); return true; } return false; } private static bool TryEmitLogicalOperator(BinaryExpression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { if (!TryEmit(expr.Left, paramExprs, il, ref closure, parent)) return false; var labelSkipRight = il.DefineLabel(); il.Emit(expr.NodeType == ExpressionType.AndAlso ? OpCodes.Brfalse : OpCodes.Brtrue, labelSkipRight); if (!TryEmit(expr.Right, paramExprs, il, ref closure, parent)) return false; var labelDone = il.DefineLabel(); il.Emit(OpCodes.Br, labelDone); il.MarkLabel(labelSkipRight); // label the second branch il.Emit(expr.NodeType == ExpressionType.AndAlso ? OpCodes.Ldc_I4_0 : OpCodes.Ldc_I4_1); il.MarkLabel(labelDone); return true; } private static bool TryEmitConditional(ConditionalExpression expr, IReadOnlyList<ParameterExpression> paramExprs, ILGenerator il, ref ClosureInfo closure, ParentFlags parent) { var testExpr = TryReduceCondition(expr.Test); // detect a special simplistic case of comparison with `null` var comparedWithNull = false; if (testExpr is BinaryExpression b) { if (b.NodeType == ExpressionType.Equal || b.NodeType == ExpressionType.NotEqual || !b.Left.Type.IsNullable() && !b.Right.Type.IsNullable()) { if (b.Right is ConstantExpression r && r.Value == null) { // the null comparison for nullable is actually a `nullable.HasValue` check, // which implies member access on nullable struct - therefore loading it by address if (b.Left.Type.IsNullable()) parent |= ParentFlags.MemberAccess; comparedWithNull = TryEmit(b.Left, paramExprs, il, ref closure, parent & ~ParentFlags.IgnoreResult); } else if (b.Left is ConstantExpression l && l.Value == null) { // the null comparison for nullable is actually a `nullable.HasValue` check, // which implies member access on nullable struct - therefore loading it by address if (b.Right.Type.IsNullable()) parent |= ParentFlags.MemberAccess; comparedWithNull = TryEmit(b.Right, paramExprs, il, ref closure, parent & ~ParentFlags.IgnoreResult); } } } if (!comparedWithNull) { if (!TryEmit(testExpr, paramExprs, il, ref closure, parent & ~ParentFlags.IgnoreResult)) return false; } var labelIfFalse = il.DefineLabel(); il.Emit(comparedWithNull && testExpr.NodeType == ExpressionType.Equal ? OpCodes.Brtrue : OpCodes.Brfalse, labelIfFalse); var ifTrueExpr = expr.IfTrue; if (!TryEmit(ifTrueExpr, paramExprs, il, ref closure, parent & ParentFlags.IgnoreResult)) return false; var ifFalseExpr = expr.IfFalse; if (ifFalseExpr.NodeType == ExpressionType.Default && ifFalseExpr.Type == typeof(void)) { il.MarkLabel(labelIfFalse); return true; } var labelDone = il.DefineLabel(); il.Emit(OpCodes.Br, labelDone); il.MarkLabel(labelIfFalse); if (!TryEmit(ifFalseExpr, paramExprs, il, ref closure, parent & ParentFlags.IgnoreResult)) return false; il.MarkLabel(labelDone); return true; } private static Expression TryReduceCondition(Expression testExpr) { if (testExpr is BinaryExpression b) { if (b.NodeType == ExpressionType.OrElse || b.NodeType == ExpressionType.Or) { if (b.Left is ConstantExpression l && l.Value is bool lb) return lb ? b.Left : TryReduceCondition(b.Right); if (b.Right is ConstantExpression r && r.Value is bool rb && rb == false) return TryReduceCondition(b.Left); } else if (b.NodeType == ExpressionType.AndAlso || b.NodeType == ExpressionType.And) { if (b.Left is ConstantExpression l && l.Value is bool lb) return !lb ? b.Left : TryReduceCondition(b.Right); if (b.Right is ConstantExpression r && r.Value is bool rb && rb) return TryReduceCondition(b.Left); } } return testExpr; } private static bool EmitMethodCall(ILGenerator il, MethodInfo method, ParentFlags parent = ParentFlags.Empty) { if (method == null) return false; il.Emit(method.IsVirtual ? OpCodes.Callvirt : OpCodes.Call, method); if ((parent & ParentFlags.IgnoreResult) != 0 && method.ReturnType != typeof(void)) il.Emit(OpCodes.Pop); return true; } private static void EmitLoadConstantInt(ILGenerator il, int i) { switch (i) { case -1: il.Emit(OpCodes.Ldc_I4_M1); break; case 0: il.Emit(OpCodes.Ldc_I4_0); break; case 1: il.Emit(OpCodes.Ldc_I4_1); break; case 2: il.Emit(OpCodes.Ldc_I4_2); break; case 3: il.Emit(OpCodes.Ldc_I4_3); break; case 4: il.Emit(OpCodes.Ldc_I4_4); break; case 5: il.Emit(OpCodes.Ldc_I4_5); break; case 6: il.Emit(OpCodes.Ldc_I4_6); break; case 7: il.Emit(OpCodes.Ldc_I4_7); break; case 8: il.Emit(OpCodes.Ldc_I4_8); break; default: if (i > -129 && i < 128) il.Emit(OpCodes.Ldc_I4_S, (sbyte)i); else il.Emit(OpCodes.Ldc_I4, i); break; } } private static void EmitLoadLocalVariableAddress(ILGenerator il, int location) { if (location < 256) il.Emit(OpCodes.Ldloca_S, (byte)location); else il.Emit(OpCodes.Ldloca, location); } private static void EmitLoadLocalVariable(ILGenerator il, int location) { if (location == 0) il.Emit(OpCodes.Ldloc_0); else if (location == 1) il.Emit(OpCodes.Ldloc_1); else if (location == 2) il.Emit(OpCodes.Ldloc_2); else if (location == 3) il.Emit(OpCodes.Ldloc_3); else if (location < 256) il.Emit(OpCodes.Ldloc_S, (byte)location); else il.Emit(OpCodes.Ldloc, location); } private static void EmitStoreLocalVariable(ILGenerator il, int location) { if (location == 0) il.Emit(OpCodes.Stloc_0); else if (location == 1) il.Emit(OpCodes.Stloc_1); else if (location == 2) il.Emit(OpCodes.Stloc_2); else if (location == 3) il.Emit(OpCodes.Stloc_3); else if (location < 256) il.Emit(OpCodes.Stloc_S, (byte)location); else il.Emit(OpCodes.Stloc, location); } private static int EmitStoreLocalVariableAndLoadItsAddress(ILGenerator il, Type type) { var varIndex = il.GetNextLocalVarIndex(type); if (varIndex == 0) { il.Emit(OpCodes.Stloc_0); il.Emit(OpCodes.Ldloca_S, (byte)0); } else if (varIndex == 1) { il.Emit(OpCodes.Stloc_1); il.Emit(OpCodes.Ldloca_S, (byte)1); } else if (varIndex == 2) { il.Emit(OpCodes.Stloc_2); il.Emit(OpCodes.Ldloca_S, (byte)2); } else if (varIndex == 3) { il.Emit(OpCodes.Stloc_3); il.Emit(OpCodes.Ldloca_S, (byte)3); } else if (varIndex < 256) { il.Emit(OpCodes.Stloc_S, (byte)varIndex); il.Emit(OpCodes.Ldloca_S, (byte)varIndex); } else { il.Emit(OpCodes.Stloc, varIndex); il.Emit(OpCodes.Ldloca, varIndex); } return varIndex; } } } // Helpers targeting the performance. Extensions method names may be a bit funny (non standard), // in order to prevent conflicts with YOUR helpers with standard names internal static class Tools { internal static bool IsValueType(this Type type) => type.GetTypeInfo().IsValueType; internal static bool IsPrimitive(this Type type) => type.GetTypeInfo().IsPrimitive; internal static bool IsClass(this Type type) => type.GetTypeInfo().IsClass; internal static bool IsUnsigned(this Type type) => type == typeof(byte) || type == typeof(ushort) || type == typeof(uint) || type == typeof(ulong); internal static bool IsNullable(this Type type) => type.GetTypeInfo().IsGenericType && type.GetTypeInfo().GetGenericTypeDefinition() == typeof(Nullable<>); internal static MethodInfo FindMethod(this Type type, string methodName) { var methods = type.GetTypeInfo().DeclaredMethods.AsArray(); for (var i = 0; i < methods.Length; i++) if (methods[i].Name == methodName) return methods[i]; return type.GetTypeInfo().BaseType?.FindMethod(methodName); } internal static MethodInfo DelegateTargetGetterMethod = typeof(Delegate).FindPropertyGetMethod("Target"); internal static MethodInfo FindDelegateInvokeMethod(this Type type) => type.FindMethod("Invoke"); internal static MethodInfo FindNullableGetValueOrDefaultMethod(this Type type) { var methods = type.GetTypeInfo().DeclaredMethods.AsArray(); for (var i = 0; i < methods.Length; i++) { var m = methods[i]; if (m.GetParameters().Length == 0 && m.Name == "GetValueOrDefault") return m; } return null; } internal static MethodInfo FindValueGetterMethod(this Type type) => type.FindPropertyGetMethod("Value"); internal static MethodInfo FindNullableHasValueGetterMethod(this Type type) => type.FindPropertyGetMethod("HasValue"); internal static MethodInfo FindPropertyGetMethod(this Type propHolderType, string propName) { var methods = propHolderType.GetTypeInfo().DeclaredMethods.AsArray(); for (var i = 0; i < methods.Length; i++) { var method = methods[i]; if (method.IsSpecialName) { var methodName = method.Name; if (methodName.Length == propName.Length + 4 && methodName[0] == 'g' && methodName[3] == '_') { var j = propName.Length - 1; while (j != -1 && propName[j] == methodName[j + 4]) --j; if (j == -1) return method; } } } return propHolderType.GetTypeInfo().BaseType?.FindPropertyGetMethod(propName); } internal static MethodInfo FindPropertySetMethod(this Type propHolderType, string propName) { var methods = propHolderType.GetTypeInfo().DeclaredMethods.AsArray(); for (var i = 0; i < methods.Length; i++) { var method = methods[i]; if (method.IsSpecialName) { var methodName = method.Name; if (methodName.Length == propName.Length + 4 && methodName[0] == 's' && methodName[3] == '_') { var j = propName.Length - 1; while (j != -1 && propName[j] == methodName[j + 4]) --j; if (j == -1) return method; } } } return propHolderType.GetTypeInfo().BaseType?.FindPropertySetMethod(propName); } internal static MethodInfo FindConvertOperator(this Type type, Type sourceType, Type targetType) { var methods = type.GetTypeInfo().DeclaredMethods.AsArray(); for (var i = 0; i < methods.Length; i++) { var m = methods[i]; if (m.IsStatic && m.IsSpecialName && m.ReturnType == targetType) { var n = m.Name; // n == "op_Implicit" || n == "op_Explicit" if (n.Length == 11 && n[2] == '_' && n[5] == 'p' && n[6] == 'l' && n[7] == 'i' && n[8] == 'c' && n[9] == 'i' && n[10] == 't' && m.GetParameters()[0].ParameterType == sourceType) return m; } } return null; } internal static ConstructorInfo FindSingleParamConstructor(this Type type, Type paramType) { var ctors = type.GetTypeInfo().DeclaredConstructors.AsArray(); for (var i = 0; i < ctors.Length; i++) { var ctor = ctors[i]; var parameters = ctor.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType == paramType) return ctor; } return null; } public static T[] AsArray<T>(this IEnumerable<T> xs) { if (xs is T[] array) return array; return xs == null ? null : xs.ToArray(); } private static class EmptyArray<T> { public static readonly T[] Value = new T[0]; } public static T[] Empty<T>() => EmptyArray<T>.Value; public static T[] WithLast<T>(this T[] source, T value) { if (source == null || source.Length == 0) return new[] { value }; if (source.Length == 1) return new[] { source[0], value }; if (source.Length == 2) return new[] { source[0], source[1], value }; var sourceLength = source.Length; var result = new T[sourceLength + 1]; Array.Copy(source, 0, result, 0, sourceLength); result[sourceLength] = value; return result; } public static Type[] GetParamTypes(IReadOnlyList<ParameterExpression> paramExprs) { if (paramExprs == null || paramExprs.Count == 0) return Empty<Type>(); if (paramExprs.Count == 1) return new[] { paramExprs[0].IsByRef ? paramExprs[0].Type.MakeByRefType() : paramExprs[0].Type }; var paramTypes = new Type[paramExprs.Count]; for (var i = 0; i < paramTypes.Length; i++) { var parameterExpr = paramExprs[i]; paramTypes[i] = parameterExpr.IsByRef ? parameterExpr.Type.MakeByRefType() : parameterExpr.Type; } return paramTypes; } public static Type GetFuncOrActionType(Type[] paramTypes, Type returnType) { if (returnType == typeof(void)) { switch (paramTypes.Length) { case 0: return typeof(Action); case 1: return typeof(Action<>).MakeGenericType(paramTypes); case 2: return typeof(Action<,>).MakeGenericType(paramTypes); case 3: return typeof(Action<,,>).MakeGenericType(paramTypes); case 4: return typeof(Action<,,,>).MakeGenericType(paramTypes); case 5: return typeof(Action<,,,,>).MakeGenericType(paramTypes); case 6: return typeof(Action<,,,,,>).MakeGenericType(paramTypes); case 7: return typeof(Action<,,,,,,>).MakeGenericType(paramTypes); default: throw new NotSupportedException( $"Action with so many ({paramTypes.Length}) parameters is not supported!"); } } switch (paramTypes.Length) { case 0: return typeof(Func<>).MakeGenericType(returnType); case 1: return typeof(Func<,>).MakeGenericType(paramTypes[0], returnType); case 2: return typeof(Func<,,>).MakeGenericType(paramTypes[0], paramTypes[1], returnType); case 3: return typeof(Func<,,,>).MakeGenericType(paramTypes[0], paramTypes[1], paramTypes[2], returnType); case 4: return typeof(Func<,,,,>).MakeGenericType(paramTypes[0], paramTypes[1], paramTypes[2], paramTypes[3], returnType); case 5: return typeof(Func<,,,,,>).MakeGenericType(paramTypes[0], paramTypes[1], paramTypes[2], paramTypes[3], paramTypes[4], returnType); case 6: return typeof(Func<,,,,,,>).MakeGenericType(paramTypes[0], paramTypes[1], paramTypes[2], paramTypes[3], paramTypes[4], paramTypes[5], returnType); case 7: return typeof(Func<,,,,,,,>).MakeGenericType(paramTypes[0], paramTypes[1], paramTypes[2], paramTypes[3], paramTypes[4], paramTypes[5], paramTypes[6], returnType); default: throw new NotSupportedException( $"Func with so many ({paramTypes.Length}) parameters is not supported!"); } } public static T GetFirst<T>(this IEnumerable<T> source) { // This is pretty much Linq.FirstOrDefault except it does not need to check // if source is IPartition<T> (but should it?) if (source is IList<T> list) return list.Count == 0 ? default : list[0]; using (var items = source.GetEnumerator()) return items.MoveNext() ? items.Current : default; } public static T GetFirst<T>(this IList<T> source) { return source.Count == 0 ? default : source[0]; } public static T GetFirst<T>(this T[] source) { return source.Length == 0 ? default : source[0]; } } /// Hey public static class ILGeneratorHacks { /* // Original methods from ILGenerator.cs public virtual LocalBuilder DeclareLocal(Type localType) { return this.DeclareLocal(localType, false); } public virtual LocalBuilder DeclareLocal(Type localType, bool pinned) { MethodBuilder methodBuilder = this.m_methodBuilder as MethodBuilder; if ((MethodInfo)methodBuilder == (MethodInfo)null) throw new NotSupportedException(); if (methodBuilder.IsTypeCreated()) throw new InvalidOperationException(SR.InvalidOperation_TypeHasBeenCreated); if (localType == (Type)null) throw new ArgumentNullException(nameof(localType)); if (methodBuilder.m_bIsBaked) throw new InvalidOperationException(SR.InvalidOperation_MethodBaked); this.m_localSignature.AddArgument(localType, pinned); LocalBuilder localBuilder = new LocalBuilder(this.m_localCount, localType, (MethodInfo)methodBuilder, pinned); ++this.m_localCount; return localBuilder; } */ /// Not allocating the LocalBuilder class /// emitting this: /// il.m_localSignature.AddArgument(type); /// return PostInc(ref il.LocalCount); public static Func<ILGenerator, Type, int> CompileGetNextLocalVarIndex() { if (LocalCountField == null || LocalSignatureField == null || AddArgumentMethod == null) return (i, t) => i.DeclareLocal(t).LocalIndex; var method = new DynamicMethod(string.Empty, typeof(int), new[] { typeof(ExpressionCompiler.ArrayClosure), typeof(ILGenerator), typeof(Type) }, typeof(ExpressionCompiler.ArrayClosure), skipVisibility: true); var il = method.GetILGenerator(); il.Emit(OpCodes.Ldarg_1); // load `il` argument il.Emit(OpCodes.Ldfld, LocalSignatureField); il.Emit(OpCodes.Ldarg_2); // load `type` argument il.Emit(OpCodes.Ldc_I4_0); // load `pinned: false` argument il.Emit(OpCodes.Call, AddArgumentMethod); il.Emit(OpCodes.Ldarg_1); // load `il` argument il.Emit(OpCodes.Ldflda, LocalCountField); il.Emit(OpCodes.Call, PostIncMethod); il.Emit(OpCodes.Ret); return (Func<ILGenerator, Type, int>)method.CreateDelegate(typeof(Func<ILGenerator, Type, int>), ExpressionCompiler.EmptyArrayClosure); } internal static int PostInc(ref int i) => i++; public static readonly MethodInfo PostIncMethod = typeof(ILGeneratorHacks).GetTypeInfo() .GetDeclaredMethod(nameof(PostInc)); /// Get via reflection public static readonly FieldInfo LocalSignatureField = typeof(ILGenerator).GetTypeInfo() .GetDeclaredField("m_localSignature"); /// Get via reflection public static readonly FieldInfo LocalCountField = typeof(ILGenerator).GetTypeInfo() .GetDeclaredField("m_localCount"); /// Get via reflection public static readonly MethodInfo AddArgumentMethod = typeof(SignatureHelper).GetTypeInfo() .GetDeclaredMethods(nameof(SignatureHelper.AddArgument)).First(m => m.GetParameters().Length == 2); private static readonly Func<ILGenerator, Type, int> _getNextLocalVarIndex = CompileGetNextLocalVarIndex(); /// Does the job public static int GetNextLocalVarIndex(this ILGenerator il, Type t) => _getNextLocalVarIndex(il, t); } internal struct LiveCountArray<T> { public int Count; public T[] Items; public LiveCountArray(T[] items) { Items = items; Count = items.Length; } public ref T PushSlot() { if (++Count > Items.Length) Items = Expand(Items); return ref Items[Count - 1]; } public void PushSlot(T item) { if (++Count > Items.Length) Items = Expand(Items); Items[Count - 1] = item; } public void Pop() => --Count; private static T[] Expand(T[] items) { if (items.Length == 0) return new T[4]; var count = items.Length; var newItems = new T[count << 1]; // count x 2 Array.Copy(items, 0, newItems, 0, count); return newItems; } } } //#endif
49.247995
187
0.505848
[ "MIT" ]
MarchingCube/FastExpressionCompiler
src/FastExpressionCompiler/FastExpressionCompiler.cs
233,337
C#
using System.IO; using System.Text; using System.Threading.Tasks; namespace SimpleSiteCrawler.Lib.Reader { internal abstract class AbstractSitePageReader : ISitePageReader { protected Stream Response { get; } protected AbstractSitePageReader(Stream response) { Response = response; } protected abstract Stream CreateReadStream(); public async Task<string> Read() { using (var stream = CreateReadStream()) { using (var reader = new StreamReader(stream, Encoding.UTF8)) { return await reader.ReadToEndAsync() .ConfigureAwait(false); } } } } }
25.366667
76
0.557162
[ "MIT" ]
alexkuznetsov/SimpleSiteCrawler
SimpleSiteCrawler.Lib/Reader/AbstractSitePageReader.cs
763
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. #if DNXCORE50 using Microsoft.AspNet.WebUtilities; using System; using System.Linq; using System.Collections; using System.Collections.Generic; namespace System.Net.Http.Formatting { public class FormDataCollection : IEnumerable<KeyValuePair<string, string>> { private readonly IList<KeyValuePair<string, string>> _values; public FormDataCollection(string query) { var parsedQuery = QueryHelpers.ParseQuery(query); var values = new List<KeyValuePair<string, string>>(); foreach (var kvp in parsedQuery) { foreach (var value in kvp.Value) { values.Add(new KeyValuePair<string, string>(kvp.Key, value)); } } _values = values; } public IEnumerator<KeyValuePair<string, string>> GetEnumerator() { return _values.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _values.GetEnumerator(); } } } #endif
26.893617
111
0.619462
[ "Apache-2.0" ]
walkeeperY/ManagementSystem
src/Microsoft.AspNet.Mvc.WebApiCompatShim/ContentNegotiator/FormDataCollection.cs
1,266
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjectRevolution : MonoBehaviour { [SerializeField] private float Orbit; [SerializeField] private float RevolutionPeriod; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } }
15.615385
52
0.647783
[ "MIT" ]
FabriceChiron/Galaxy-Map-VR
Assets/Scripts/World/ObjectRevolution.cs
406
C#
// <auto-generated/> #pragma warning disable 1591 #pragma warning disable 0414 #pragma warning disable 0649 #pragma warning disable 0169 namespace RadzenBlazorDemos.Pages { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #nullable restore #line 1 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\_Imports.razor" using System.Net.Http; #line default #line hidden #nullable disable #nullable restore #line 2 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\_Imports.razor" using Microsoft.AspNetCore.Components.Forms; #line default #line hidden #nullable disable #nullable restore #line 3 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\_Imports.razor" using Microsoft.AspNetCore.Components.Routing; #line default #line hidden #nullable disable #nullable restore #line 4 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\_Imports.razor" using Microsoft.AspNetCore.Components.Web; #line default #line hidden #nullable disable #nullable restore #line 5 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\_Imports.razor" using Microsoft.AspNetCore.Components.Authorization; #line default #line hidden #nullable disable #nullable restore #line 6 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\_Imports.razor" using Microsoft.JSInterop; #line default #line hidden #nullable disable #nullable restore #line 2 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\_Imports.razor" using Radzen; #line default #line hidden #nullable disable #nullable restore #line 3 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\_Imports.razor" using Radzen.Blazor; #line default #line hidden #nullable disable #nullable restore #line 4 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\_Imports.razor" using RadzenBlazorDemos; #line default #line hidden #nullable disable #nullable restore #line 5 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\_Imports.razor" using RadzenBlazorDemos.Shared; #line default #line hidden #nullable disable [Microsoft.AspNetCore.Components.LayoutAttribute(typeof(MainLayout))] public partial class EditAppointmentPage : Microsoft.AspNetCore.Components.ComponentBase { #pragma warning disable 1998 protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) { } #pragma warning restore 1998 #nullable restore #line 38 "D:\c#\blazor\vtl-nvp\RadzenBlazorDemos\Pages\EditAppointmentPage.razor" [Parameter] public Appointment Appointment { get; set; } Appointment model = new Appointment(); protected override void OnParametersSet() { model = Appointment; } void OnSubmit(Appointment model) { DialogService.Close(model); } #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Components.InjectAttribute] private DialogService DialogService { get; set; } } } #pragma warning restore 1591
25.059322
118
0.764288
[ "MIT" ]
longvutam/vtl-nvp
RadzenBlazorDemos/obj/Debug/net5.0/RazorDeclaration/Pages/EditAppointmentPage.razor.g.cs
2,957
C#
using System; using System.Text; using System.Collections.Generic; using System.Data; namespace Models { [Serializable] public class AdminOrders { /// <summary> /// ID /// </summary> private int _id; public int ID { get { return _id; } set { _id = value; } } /// <summary> /// Osn /// </summary> private string _osn; public string Osn { get { return _osn; } set { _osn = value; } } /// <summary> /// Uid /// </summary> private int _uid; public int Uid { get { return _uid; } set { _uid = value; } } /// <summary> /// OrderState /// </summary> private int _orderstate; public int OrderState { get { return _orderstate; } set { _orderstate = value; } } /// <summary> /// TypeID /// </summary> private int _typeid; public int TypeID { get { return _typeid; } set { _typeid = value; } } private int _count; public int Count { get { return _count; } set { _count = value; } } /// <summary> /// OrderAmount /// </summary> private decimal _orderamount; public decimal OrderAmount { get { return _orderamount; } set { _orderamount = value; } } /// <summary> /// CDate /// </summary> private DateTime _cdate; public DateTime CDate { get { return _cdate; } set { _cdate = value; } } /// <summary> /// PaySn /// </summary> private string _paysn = ""; public string PaySn { get { return _paysn; } set { _paysn = value; } } /// <summary> /// PayName /// </summary> private string _payname = "支付宝"; public string PayName { get { return _payname; } set { _payname = value; } } /// <summary> /// PayTime /// </summary> private DateTime _paytime = new DateTime(1900, 1, 1); public DateTime PayTime { get { return _paytime; } set { _paytime = value; } } } }
23.453704
61
0.422029
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
tst20170901/test2
Model/AdminOrders.cs
2,541
C#
using System; using Android.App; using Android.Content; using Android.Content.PM; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; namespace GetRich.Droid { [Activity(Label = "GetRich.Droid", Icon = "@drawable/icon", Theme = "@style/MyTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); global::Xamarin.Forms.Forms.Init(this, bundle); LoadApplication(new App()); } } }
28.172414
188
0.69033
[ "MIT" ]
jonathanpeppers/GetRich
Droid/MainActivity.cs
819
C#
namespace Data.Types.TimeCalculator { public class TimeValueGroup : ITimeMathComponent { #region Constants const double DAYS_IN_MONTH = 365.0 / 12.0; const double WEEKS_IN_YEAR = 365.0 / 7.0; const double DAYS_IN_WEEK = 365.0 / WEEKS_IN_YEAR; #endregion #region Properties public List<TimeValue> TimeValues { get; set; } = new List<TimeValue>(); /// <summary> /// Used to serve as the index of the operand in an equation. /// </summary> public int EquationIndex { get; set; } #endregion #region Methods public TimeSpan ToTimeSpan() { if (TimeValues.Count == 1 && TimeValues[0].Type is null) return TimeSpan.FromMilliseconds(double.Parse(TimeValues[0].Number)); return TimeSpan.FromMilliseconds( TimeValues.Sum(o => o.ToTimeSpan().TotalMilliseconds) ); } public static TimeValueGroup FromTimeSpan(TimeSpan timeSpan) { var group = new TimeValueGroup(); int years = 0, months = 0, weeks = 0; if (timeSpan.TotalDays / 365 >= 1) { years = (int)(timeSpan.TotalDays / 365.0); if (years > 0) group.TimeValues.Add(new TimeValue { Number = years.ToString(), Type = TimeValueType.Year }); } if (timeSpan.TotalDays / DAYS_IN_MONTH >= 1) { months = (int)(timeSpan.TotalDays / DAYS_IN_MONTH) - years * 12; if (months > 0) group.TimeValues.Add(new TimeValue { Number = months.ToString(), Type = TimeValueType.Month }); } if (timeSpan.TotalDays / DAYS_IN_WEEK >= 1) { weeks = (int)System.Math.Floor(timeSpan.TotalDays / DAYS_IN_WEEK - months * 4 - years * 52); if (weeks > 0) group.TimeValues.Add(new TimeValue { Number = weeks.ToString(), Type = TimeValueType.Week }); } if (timeSpan.TotalDays > 0) { var days = (int)System.Math.Floor(timeSpan.TotalDays - weeks * 7 - months * 30 - years * 365); if (days > 0) group.TimeValues.Add(new TimeValue { Number = days.ToString(), Type = TimeValueType.Day }); } if (timeSpan.Hours > 0) { group.TimeValues.Add(new TimeValue { Number = timeSpan.Hours.ToString(), Type = TimeValueType.Hour }); } if (timeSpan.Minutes > 0) { group.TimeValues.Add(new TimeValue { Number = timeSpan.Minutes.ToString(), Type = TimeValueType.Min }); } if (timeSpan.Seconds > 0) { group.TimeValues.Add(new TimeValue { Number = timeSpan.Seconds.ToString(), Type = TimeValueType.Sec }); } if (timeSpan.Milliseconds > 0) { group.TimeValues.Add(new TimeValue { Number = timeSpan.Milliseconds.ToString(), Type = TimeValueType.MSec }); } return group; } public override string ToString() { return TimeValues .Select(x => x.ToString()) .Aggregate("", (accum, curr) => accum + " " + curr); } #endregion } }
35.614583
125
0.525885
[ "MIT" ]
Polarts/BlazingTimeCalculator
Data/Types/TimeCalculator/TimeValueGroup.cs
3,419
C#
 using System; using System.Collections.Generic; using System.Web; using IF.Payment.Abstracts; using IF.Payment.Common; using IF.Payment.Concrete.AliPay.Model; using IF.Payment.Model; using IF.Payment.Util.AliPay; namespace IF.Payment.Concrete.AliPay { public class AliPay : PayBase { PayRst rst = new PayRst(); /// <summary> /// 第三方支付 /// </summary> /// <param name="query"></param> /// <returns></returns> protected override PayRst Pay(QueryBase query) { var Payparam = query as AliQuery; if (!Verification(Payparam)) { return rst; } string Order_num = Payparam.order_no; string total_fee = String.Format("{0:F}", Payparam.Money); string subject = Payparam.ProductName; //收银台页面上,商品展示的超链接,必填 string show_url = (HttpContext.Current.Request.UrlReferrer == null) ? "" : HttpContext.Current.Request.UrlReferrer.ToString(); string url = "https://mapi.alipay.com/gateway.do?"; //把请求参数打包成数组 SortedDictionary<string, string> sParaTemp = new SortedDictionary<string, string>(); sParaTemp.Add("partner", Payparam.Partner); sParaTemp.Add("seller_id", Payparam.Seller_id); sParaTemp.Add("_input_charset", "utf-8"); sParaTemp.Add("service", "alipay.wap.create.direct.pay.by.user"); sParaTemp.Add("payment_type", "1"); sParaTemp.Add("notify_url", Payparam.NotifyUrl); sParaTemp.Add("return_url", Payparam.ReturnUrl); sParaTemp.Add("out_trade_no", Order_num); sParaTemp.Add("subject", subject); sParaTemp.Add("total_fee", total_fee); sParaTemp.Add("show_url", show_url); //sParaTemp.Add("app_pay","Y");//启用此参数可唤起钱包APP支付。 sParaTemp.Add("body", ""); //其他业务参数根据在线开发文档,添加参数.文档地址:https://doc.open.alipay.com/doc2/detail.htm?spm=a219a.7629140.0.0.2Z6TSk&treeId=60&articleId=103693&docType=1 //如sParaTemp.Add("参数名","参数值"); foreach (KeyValuePair<string, string> temp in sParaTemp) { Log.log("AliPayLogger", "key:" + temp.Key + " value:" + temp.Value); } //建立请求 string sHtmlText = Submit.BuildRequest(sParaTemp, "get", "确认", Payparam.Key, url); rst.Status = true; rst.Content = sHtmlText; return rst; } private bool Verification(AliQuery info) { if (info == null) { rst.Status = false; rst.ErrorMsg = "支付参数不能为空"; return false; } if (info.Partner == null || info.Partner == "") { rst.Status = false; rst.ErrorMsg = "合作者ID不能为空"; return false; } if (info.Seller_id == null || info.Seller_id == "") { rst.Status = false; rst.ErrorMsg = "合作者ID不能为空"; return false; } if (info.Key == null || info.Key == "") { rst.Status = false; rst.ErrorMsg = "秘钥不能为空"; return false; } if (info.NotifyUrl == null || info.NotifyUrl == "") { rst.Status = false; rst.ErrorMsg = "商户订单号无效,无法发起本次交易,交易已取消"; return false; } if (info.ReturnUrl == null || info.ReturnUrl == "") { rst.Status = false; rst.ErrorMsg = "商品描述无效,无法发起本次交易,交易已取消"; return false; } if (info.Money == null || info.Money == "") { rst.Status = false; rst.ErrorMsg = "支付金额不能为空"; return false; } if (info.order_no == null || info.order_no == "") { rst.Status = false; rst.ErrorMsg = "订单号不能为空"; return false; } if (info.ProductName == null || info.ProductName == "") { rst.Status = false; rst.ErrorMsg = "产品名称不能为空"; return false; } double money = 0; if (!double.TryParse(info.Money, out money)) { rst.Status = false; rst.ErrorMsg = "支付金额错误!"; return false; } return true; } } }
47.024096
148
0.581091
[ "MIT" ]
mzqs5/citest
aspnet-core/src/IF.Payment/Concrete/AliPay/AliPay.cs
4,263
C#
using System; using Uno; namespace Windows.UI.Xaml.Automation; [NotImplemented] public class SelectionPatternIdentifiers { [NotImplemented(new string[] { "__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__" })] public static AutomationProperty CanSelectMultipleProperty { get { throw new NotImplementedException("The member AutomationProperty SelectionPatternIdentifiers.CanSelectMultipleProperty is not implemented in Uno."); } } [NotImplemented(new string[] { "__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__" })] public static AutomationProperty IsSelectionRequiredProperty { get { throw new NotImplementedException("The member AutomationProperty SelectionPatternIdentifiers.IsSelectionRequiredProperty is not implemented in Uno."); } } [NotImplemented(new string[] { "__ANDROID__", "__IOS__", "NET461", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__", "__MACOS__" })] public static AutomationProperty SelectionProperty { get { throw new NotImplementedException("The member AutomationProperty SelectionPatternIdentifiers.SelectionProperty is not implemented in Uno."); } } }
33.583333
153
0.772539
[ "MIT" ]
ljcollins25/Codeground
src/UnoApp/UnoDecompile/Uno.UI/Windows.UI.Xaml.Automation/SelectionPatternIdentifiers.cs
1,209
C#
/* * BSD 3-Clause License * * Copyright (c) 2018-2021 * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Reflection; using System.Numerics; using NumpyLib; #if NPY_INTP_64 using npy_intp = System.Int64; #else using npy_intp = System.Int32; #endif namespace NumpyDotNet { /// <summary> /// Implements the Numpy python 'ndarray' class /// </summary> public partial class ndarray : IEnumerable<object>, NumpyDotNet.IArray { #region Explicit conversion to single element data types /// special case for bools. Tries to convert all data types to true/false value public static explicit operator bool(ndarray arr) { int val = NpyCoreApi.ArrayBool(arr); if (val < 0) { NpyCoreApi.CheckError(); return false; } else { return val != 0; } } public static explicit operator byte(ndarray nd) { if (nd.TypeNum != NPY_TYPES.NPY_UBYTE) throw new Exception("ndarray does not contain bytes"); CheckElementCount(nd); return (byte)nd.GetItem(0); } public static explicit operator sbyte(ndarray nd) { if (nd.TypeNum != NPY_TYPES.NPY_BYTE) throw new Exception("ndarray does not contain sbytes"); CheckElementCount(nd); return (sbyte)nd.GetItem(0); } public static explicit operator UInt16(ndarray nd) { if (nd.TypeNum != NPY_TYPES.NPY_UINT16) throw new Exception("ndarray does not contain UInt16s"); CheckElementCount(nd); return (UInt16)nd.GetItem(0); } public static explicit operator Int16(ndarray nd) { if (nd.TypeNum != NPY_TYPES.NPY_INT16) throw new Exception("ndarray does not contain Int16s"); CheckElementCount(nd); return (Int16)nd.GetItem(0); } public static explicit operator UInt32(ndarray nd) { if (nd.TypeNum != NPY_TYPES.NPY_UINT32) throw new Exception("ndarray does not contain UInt32s"); CheckElementCount(nd); return (UInt32)nd.GetItem(0); } public static explicit operator Int32(ndarray nd) { if (nd.TypeNum != NPY_TYPES.NPY_INT32) throw new Exception("ndarray does not contain Int32s"); CheckElementCount(nd); return (Int32)nd.GetItem(0); } public static explicit operator UInt64(ndarray nd) { if (nd.TypeNum != NPY_TYPES.NPY_UINT64) throw new Exception("ndarray does not contain UInt64s"); CheckElementCount(nd); return (UInt64)nd.GetItem(0); } public static explicit operator Int64(ndarray nd) { if (nd.TypeNum != NPY_TYPES.NPY_INT64) throw new Exception("ndarray does not contain Int64s"); CheckElementCount(nd); return (Int64)nd.GetItem(0); } public static explicit operator float(ndarray nd) { if (nd.TypeNum != NPY_TYPES.NPY_FLOAT) throw new Exception("ndarray does not contain floats"); CheckElementCount(nd); return (float)nd.GetItem(0); } public static explicit operator double(ndarray nd) { if (nd.TypeNum != NPY_TYPES.NPY_DOUBLE) throw new Exception("ndarray does not contain doubles"); CheckElementCount(nd); return (double)nd.GetItem(0); } public static explicit operator decimal(ndarray nd) { if (nd.TypeNum != NPY_TYPES.NPY_DECIMAL) throw new Exception("ndarray does not contain decimals"); CheckElementCount(nd); return (decimal)nd.GetItem(0); } public static explicit operator System.Numerics.Complex(ndarray nd) { if (nd.TypeNum != NPY_TYPES.NPY_COMPLEX) throw new Exception("ndarray does not contain complex numbers"); CheckElementCount(nd); return (System.Numerics.Complex)nd.GetItem(0); } public static explicit operator System.Numerics.BigInteger(ndarray nd) { if (nd.TypeNum != NPY_TYPES.NPY_BIGINT) throw new Exception("ndarray does not contain BigIntegers"); CheckElementCount(nd); return (System.Numerics.BigInteger)nd.GetItem(0); } //public static explicit operator System.Object(ndarray nd) //{ // if (nd.TypeNum != NPY_TYPES.NPY_OBJECT) // throw new Exception("ndarray does not contain Objects"); // CheckElementCount(nd); // return (System.Object)nd.GetItem(0); //} public static explicit operator System.String(ndarray nd) { if (nd.TypeNum != NPY_TYPES.NPY_STRING) throw new Exception("ndarray does not contain Strings"); CheckElementCount(nd); return (System.String)nd.GetItem(0); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static void CheckElementCount(ndarray nd) { //if (nd.Array.data.datap.GetElementCount() != 1) // throw new Exception("ndarray is not a single element array"); } #endregion internal NpyArray core; public ndarray() { } internal ndarray(NpyArray a) { if (a == null) { throw new Exception("Attempt to create ndarray with null object"); } core = a; } #region Public interfaces (must match CPython) private static Func<ndarray, string> reprFunction; private static Func<ndarray, string> strFunction; /// <summary> /// User assigned name for allocated ndarray /// </summary> public string Name { get { return core.Name; } set { core.Name = value; } } /// <summary> /// Sets a function to be triggered for the repr() operator or null to default to the /// built-in version. /// </summary> internal static Func<ndarray, string> ReprFunction { get { return reprFunction; } private set { reprFunction = (value != null) ? value : x => x.BuildStringRepr(true); } } /// <summary> /// Sets a function to be triggered on the str() operator or ToString() method. Null defaults to /// the built-in version. /// </summary> internal static Func<ndarray, string> StrFunction { get { return strFunction; } private set { strFunction = (value != null) ? value : x => x.BuildStringRepr(false); } } static ndarray() { ReprFunction = null; StrFunction = null; } #region Operators internal static ndarray BinaryOp(ndarray a, object b, NpyUFuncObject UFunc) { return NpyCoreApi.PerformNumericOp(a, UFunc.ops, np.asanyarray(b), false); } internal static object BinaryOpInPlace(ndarray a, object b, NpyUFuncObject UFunc, ndarray ret) { ndarray numericOpResult = NpyCoreApi.PerformNumericOp(a, UFunc.ops, np.asanyarray(b), true); if (numericOpResult != null && ret != null) { NpyCoreApi.CopyAnyInto(ret, numericOpResult); } return numericOpResult; } internal static ndarray BinaryOp(ndarray a, object b, UFuncOperation op) { var f = NpyCoreApi.GetNumericOp(op); return BinaryOp(a, b, f); } public static object BinaryOpInPlace(ndarray a, object b, UFuncOperation op, ndarray ret) { var f = NpyCoreApi.GetNumericOp(op); return BinaryOpInPlace(a, b, f, ret); } internal static object UnaryOp(ndarray a, UFuncOperation op) { return NpyCoreApi.PerformNumericOp(a, op, 0, false); } internal static object UnaryOpInPlace(ndarray a, UFuncOperation op, ndarray ret) { ndarray numericOpResult = NpyCoreApi.PerformNumericOp(a, op, 0, true); if (numericOpResult != null && ret != null) { NpyCoreApi.CopyAnyInto(ret, numericOpResult); } return numericOpResult; } public static object operator +(ndarray a) { return a; } public static ndarray operator +(ndarray a, object operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.add, operand); } public static ndarray operator +(object a, ndarray operand) { return NpyCoreApi.PerformNumericOp(np.asanyarray(a), UFuncOperation.add, operand); } public static ndarray operator +(ndarray a, ndarray b) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.add, b); } [SpecialName] public ndarray InPlaceAdd(ndarray b) { return NpyCoreApi.PerformNumericOp(this, UFuncOperation.add, b, true); } public static ndarray operator -(ndarray a, object operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.subtract, operand); } public static ndarray operator -(object a, ndarray operand) { return NpyCoreApi.PerformNumericOp(np.asanyarray(a), UFuncOperation.subtract, operand); } public static ndarray operator -(ndarray a, ndarray b) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.subtract, b); } [SpecialName] public ndarray InPlaceSubtract(ndarray b) { return NpyCoreApi.PerformNumericOp(this, UFuncOperation.subtract, b, true); } public static ndarray operator -(ndarray a) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.negative, 0); } public static ndarray operator *(ndarray a, object operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.multiply, operand); } public static ndarray operator *(object a, ndarray operand) { return NpyCoreApi.PerformNumericOp(np.asanyarray(a), UFuncOperation.multiply, operand); } public static ndarray operator *(ndarray a, ndarray b) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.multiply, b); } [SpecialName] public ndarray InPlaceMultiply(ndarray b) { return NpyCoreApi.PerformNumericOp(this, UFuncOperation.multiply, b, true); } public static ndarray operator /(ndarray a, object operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.divide, operand); } public static ndarray operator /(object a, ndarray operand) { return NpyCoreApi.PerformNumericOp(np.asanyarray(a), UFuncOperation.divide, operand); } public static object operator /(ndarray a, ndarray b) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.divide, b); } [SpecialName] public ndarray InPlaceDivide(ndarray b) { return NpyCoreApi.PerformNumericOp(this, UFuncOperation.divide, b, true); } [SpecialName] public ndarray InPlaceTrueDivide(ndarray b) { return NpyCoreApi.PerformNumericOp(this, UFuncOperation.true_divide, b, true); } [SpecialName] public ndarray InPlaceFloorDivide(ndarray b) { return NpyCoreApi.PerformNumericOp(this, UFuncOperation.floor_divide, b, true); } public static ndarray operator %(ndarray a, object operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.remainder, operand); } public static ndarray operator %(object a, ndarray operand) { return NpyCoreApi.PerformNumericOp(np.asanyarray(a), UFuncOperation.remainder, operand); } public static ndarray operator %(ndarray a, ndarray b) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.remainder, b); } public static ndarray operator &(ndarray a, Int64 operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.bitwise_and, operand); } public static ndarray operator &(Int64 operand, ndarray a) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.bitwise_and, operand); } public static ndarray operator &(ndarray a, ndarray b) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.bitwise_and, b); } [SpecialName] public ndarray InPlaceBitwiseAnd(ndarray b) { return NpyCoreApi.PerformNumericOp(this, UFuncOperation.bitwise_and, b, true); } public static ndarray operator |(ndarray a, Int64 operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.bitwise_or, operand); } public static ndarray operator |(Int64 operand, ndarray a) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.bitwise_or, operand); } public static ndarray operator |(ndarray a, ndarray b) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.bitwise_or, b); } [SpecialName] public ndarray InPlaceBitwiseOr(ndarray b) { return NpyCoreApi.PerformNumericOp(this, UFuncOperation.bitwise_or, b, true); } public static ndarray operator ^(ndarray a, Int64 operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.bitwise_xor, operand); } public static ndarray operator ^(Int64 operand, ndarray a) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.bitwise_xor, operand); } public static object operator ^(ndarray a, ndarray b) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.bitwise_xor, b); } public static ndarray operator <<(ndarray a, int shift) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.left_shift, shift); } public static ndarray operator >>(ndarray a, int shift) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.right_shift, shift); } public static ndarray operator <(ndarray a, object operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.less, operand); } public static ndarray operator <=(ndarray a, object operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.less_equal, operand); } public static ndarray operator >(ndarray a, object operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.greater, operand); } public static ndarray operator >=(ndarray a, object operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.greater_equal, operand); } public static ndarray operator ==(ndarray a, double operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.equal, operand); } public static ndarray operator ==(ndarray a, float operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.equal, operand); } public static ndarray operator ==(ndarray a, Int64 operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.equal, operand); } public static ndarray operator ==(ndarray a, Int32 operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.equal, operand); } public static ndarray operator ==(ndarray a, bool operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.equal, operand); } public static ndarray operator ==(ndarray a, decimal operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.equal, operand); } public static ndarray operator ==(ndarray a, Complex operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.equal, operand); } public static ndarray operator ==(ndarray a, BigInteger operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.equal, operand); } [SpecialName] public ndarray Equals(ndarray b) { return NpyCoreApi.PerformNumericOp(this, UFuncOperation.equal, b); } [SpecialName] public ndarray Equals(string b) { return NpyCoreApi.PerformNumericOp(this, UFuncOperation.equal, b); } public static ndarray operator !=(ndarray a, double operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.not_equal, operand); } public static ndarray operator !=(ndarray a, float operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.not_equal, operand); } public static ndarray operator !=(ndarray a, Int64 operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.not_equal, operand); } public static ndarray operator !=(ndarray a, Int32 operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.not_equal, operand); } public static ndarray operator !=(ndarray a, bool operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.not_equal, operand); } public static ndarray operator !=(ndarray a, decimal operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.not_equal, operand); } public static ndarray operator !=(ndarray a, Complex operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.not_equal, operand); } public static ndarray operator !=(ndarray a, BigInteger operand) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.not_equal, operand); } [SpecialName] public ndarray NotEquals(ndarray b) { return NpyCoreApi.PerformNumericOp(this, UFuncOperation.not_equal, b); } [SpecialName] public ndarray NotEquals(string b) { return NpyCoreApi.PerformNumericOp(this, UFuncOperation.not_equal, b); } [SpecialName] public ndarray InPlaceExclusiveOr(ndarray b) { return NpyCoreApi.PerformNumericOp(this, UFuncOperation.bitwise_xor, b, true); } public static ndarray operator ~(ndarray a) { return NpyCoreApi.PerformNumericOp(a, UFuncOperation.invert, 0); } //public static implicit operator String(ndarray a) { // return StrFunction(a); //} #endregion #region indexing public object this[int index] { get { return GetArrayItem((npy_intp)index); } set { SetArrayItem((npy_intp)index, value); } } public object this[long index] { get { return GetArrayItem((npy_intp)index); } set { SetArrayItem((npy_intp)index, value); } } public object this[BigInteger index] { get { npy_intp lIndex = (npy_intp)index; return GetArrayItem(lIndex); } set { npy_intp lIndex = (npy_intp)index; SetArrayItem(lIndex, value); } } /// <summary> /// slicing/indexing function to set a breakpoint in /// </summary> /// <param name="args"></param> /// <returns></returns> public Object SliceMe(params object[] args) { return this[args]; } /// <summary> /// sliced/indexed array cast to ndarray. Throws exception if result is not ndarray. Maybe better than casting to ndarray everwhere. /// </summary> /// <param name="args"></param> /// <returns></returns> public ndarray A(params object[] args) { ndarray ret = this[args] as ndarray; if (ret == null) { throw new Exception("This operation did not result in an expected ndarray"); } return ret; } public Object this[params object[] args] { get { if (args == null) { args = new object[] { null }; } NpyIndexes indexes = new NpyIndexes(); { NpyUtil_IndexProcessing.IndexConverter(this, args, indexes); if (indexes.IsSingleItem(ndim)) { // Optimization for single item index. npy_intp offset = 0; npy_intp[] dims = this.dims; npy_intp[] s = strides; for (int i = 0; i < ndim; i++) { npy_intp d = dims[i]; npy_intp val = indexes.GetIntP(i); if (val < 0) { val += d; } if (val < 0 || val >= d) { throw new IndexOutOfRangeException(); } offset += val * s[i]; } return this.GetItem(offset >> this.ItemSizeDiv); } else if (indexes.IsMultiField) { throw new Exception("Don't currenty support multi-fields"); } ndarray result = null; if (indexes.IsAdvancedIndexing) { // advanced subscript case. NpyCoreApi.Incref(Array); //var newDType = NpyCoreApi.DescrFromType(this.Array.ItemType); //NpyCoreApi.DescrReplaceSubarray(newDType, this.Dtype, result.dims); result = new ndarray(NpyCoreApi.ArraySubscript(this, indexes)); result = NpyCoreApi.FromArray(result, null, NPYARRAYFLAGS.NPY_ENSURECOPY); NpyCoreApi.Decref(Array); } else { // General subscript case. NpyCoreApi.Incref(Array); result = new ndarray(NpyCoreApi.ArraySubscript(this, indexes)); NpyCoreApi.Decref(Array); } if (result.ndim == 0) { // We only want to return a scalar if there are not elipses bool noelipses = true; int n = indexes.NumIndexes; for (int i = 0; i < n; i++) { NpyIndexType t = indexes.IndexType(i); if (t == NpyIndexType.NPY_INDEX_ELLIPSIS || t == NpyIndexType.NPY_INDEX_STRING || t == NpyIndexType.NPY_INDEX_BOOL) { noelipses = false; break; } } if (noelipses) { return result.GetItem(0); } } return result; } } set { if (!ChkFlags(NPYARRAYFLAGS.NPY_WRITEABLE)) { throw new RuntimeException("array is not writeable."); } if (args == null) { args = new object[] { null }; } //else //{ // if (args.Length == 1 && args[0] is PythonTuple) // { // PythonTuple pt = (PythonTuple)args[0]; // args = pt.ToArray(); // } // if (args.Length == 1 && args[0] is string) // { // string field = (string)args[0]; // if (!ChkFlags(NPYARRAYFLAGS.NPY_WRITEABLE)) // { // throw new RuntimeException("array is not writeable."); // } // NpyArray_Descr descr = null; // int offset = NpyCoreApi.GetFieldOffset(Dtype, field, ref descr); // if (offset < 0) // { // throw new ArgumentException(String.Format("field name '{0}' not found.", field)); // } // np.SetField(this, descr, offset, value); // return; // } //} NpyIndexes indexes = new NpyIndexes(); { NpyUtil_IndexProcessing.IndexConverter(this, args, indexes); // Special case for boolean on 0-d arrays. if (ndim == 0 && indexes.NumIndexes == 1 && indexes.IndexType(0) == NpyIndexType.NPY_INDEX_BOOL) { if (indexes.GetBool(0)) { SetItem(value, 0); } return; } // Special case for single assignment. npy_intp single_offset = indexes.SingleAssignOffset(this); if (single_offset >= 0 && np.IsNumericType(value)) { // This is a single item assignment. Use SetItem. SetItem(value, single_offset >> this.ItemSizeDiv); return; } if (indexes.IsSimple) { ndarray view = null; try { if (GetType() == typeof(ndarray)) { view = NpyCoreApi.IndexSimple(this, indexes); } else { throw new Exception("not an ndarray"); } if (view != null) { np.CopyObject(view, value); } } finally { if (view != null) { } } } else { ndarray array_value = np.FromAny(value, Dtype, 0, 0, NPYARRAYFLAGS.NPY_FORCECAST, null); try { // KM: this hack lets the IndexFancyAssign work if (array_value.Array.nd == 0) { array_value.Array.nd = 1; array_value.Array.dimensions = new npy_intp[1] { 1 }; array_value.Array.strides = new npy_intp[1] { array_value.ItemSize }; } // KM: this hack lets the IndexFancyAssign work NpyCoreApi.Incref(array_value.Array); if (NpyCoreApi.IndexFancyAssign(this, indexes, array_value) < 0) { NpyCoreApi.CheckError(); } } finally { NpyCoreApi.Decref(array_value.Array); } } } } } #endregion #region properties /// <summary> /// Number of dimensions in the array /// </summary> public int ndim { get { return core.nd; } } /// <summary> /// the shape of the array /// </summary> public shape shape { get { return new shape(this.dims, this.ndim); } } /// <summary> /// Total number of elements in the array. /// </summary> public npy_intp size { get { return NpyCoreApi.ArraySize(this); } } /// <summary> /// returns a raw pointer of the ndarray data. /// </summary> /// <param name="index"></param> /// <returns></returns> public VoidPtr rawdata(npy_intp index = 0) { var flattened = this.ravel(); return numpyAPI.NpyArray_Index2Ptr(flattened.Array, index); } public ndarray __array_wrap__(ndarray a) { return a; } /// <summary> /// The type descriptor object for this array /// </summary> public dtype Dtype { get { if (core == null) return null; return new dtype(core.descr); } set { NpyCoreApi.ArraySetDescr(this, value); } } /// <summary> /// The type descriptor object for this array /// </summary> public object dtype { get { return this.Dtype; } //set { // dtype descr = value as dtype; // if (descr == null) { // descr = NpyDescr.DescrConverter(NpyUtil_Python.DefaultContext, value); // } // NpyCoreApi.ArraySetDescr(this, descr); //} } /// <summary> /// Flags for this array /// </summary> public flagsobj flags { get { return new flagsobj(this); } } public object flat { get { return NpyCoreApi.IterNew(this); } set { // Assing like a.flat[:] = value flatiter it = NpyCoreApi.IterNew(this); it[new Slice(null)] = value; } } /// <summary> /// size in bytes of the data items stored in this array /// </summary> public int ItemSize { get { if (core == null) return 0; return core.descr.elsize; } } /// <summary> /// value used to convert data_offset to an index. "data_offset >> ItemSizeDiv" /// </summary> public int ItemSizeDiv { get { if (core == null) return 0; return core.descr.eldivshift; } } /// <summary> /// The data type of this ndarray /// </summary> public NPY_TYPES TypeNum { get { if (core == null) return NPY_TYPES.NPY_OBJECT; return core.descr.type_num; } } /// <summary> /// total number of bytes in the ndarray /// </summary> public long nbytes { get { return ItemSize * Size; } } /// <summary> /// transpose this array /// </summary> public ndarray T { get { return this.Transpose(); } } #endregion #region methods /// <summary> /// Copy of the array, cast to a specified type. /// </summary> /// <param name="dtype">data type to cast to</param> /// <param name="copy"></param> /// <returns></returns> public ndarray astype(dtype dtype = null, bool copy = true) { if (dtype == this.Dtype && this.BaseArray == null) { return this; } if (this.Dtype.HasNames) { // CastToType doesn't work properly for // record arrays, so we use FromArray. NPYARRAYFLAGS flags = NPYARRAYFLAGS.NPY_FORCECAST; if (IsFortran) { flags |= NPYARRAYFLAGS.NPY_FORTRAN; } return NpyCoreApi.FromArray(this, dtype, flags); } return NpyCoreApi.CastToType(this, dtype, this.IsFortran); } /// <summary> /// Swap the bytes of the array elements /// </summary> /// <param name="inplace">If True, swap bytes in-place, default is False.</param> /// <returns></returns> public ndarray byteswap(bool inplace = false) { return NpyCoreApi.Byteswap(this, inplace); } /// <summary> /// Return an array copy of the given object. /// </summary> /// <param name="order">{‘C’, ‘F’, ‘A’, ‘K’}, optional</param> /// <returns></returns> public ndarray Copy(NPY_ORDER order = NPY_ORDER.NPY_CORDER) { return NpyCoreApi.NewCopy(this, order); } /// <summary> /// Dot product of two arrays. /// </summary> /// <param name="other">array to calculate dot product with</param> /// <returns></returns> public ndarray dot(object other) { return np.MatrixProduct(this, other); } /// <summary> /// Fill the array with a scalar value. /// </summary> /// <param name="scalar">value to file array with</param> public void fill(object scalar) { FillWithScalar(scalar); } /// <summary> /// Return a copy of the array collapsed into one dimension. /// </summary> /// <param name="order">{‘C’, ‘F’, ‘A’, ‘K’}, optional</param> /// <returns></returns> public ndarray flatten(NPY_ORDER order = NPY_ORDER.NPY_CORDER) { return this.Flatten(order); } public object item(params object[] args) { if (args != null && args.Length == 1 && args[0] is PythonTuple) { PythonTuple t = (PythonTuple)args[0]; args = t.ToArray(); } if (args == null || args.Length == 0) { if (ndim == 0 || Size == 1) { return GetItem(0); } else { throw new ArgumentException("can only convert an array of size 1 to a Python scalar"); } } else { NpyIndexes indexes = new NpyIndexes(); { NpyUtil_IndexProcessing.IndexConverter(this, args, indexes); if (args.Length == 1) { if (indexes.IndexType(0) != NpyIndexType.NPY_INDEX_INTP) { throw new ArgumentException("invalid integer"); } // Do flat indexing return Flat.Get(indexes.GetIntP(0)); } else { if (indexes.IsSingleItem(ndim)) { npy_intp offset = indexes.SingleAssignOffset(this); return GetItem(offset >> this.ItemSizeDiv); } else { throw new ArgumentException("Incorrect number of indices for the array"); } } } } } public void itemset(params object[] args) { // Convert args to value and args if (args == null || args.Length == 0) { throw new ArgumentException("itemset must have at least one argument"); } object value = args.Last(); args = args.Take(args.Length - 1).ToArray(); if (args.Length == 1 && args[0] is PythonTuple) { PythonTuple t = (PythonTuple)args[0]; args = t.ToArray(); } if (args.Length == 0) { if (ndim == 0 || Size == 1) { SetItem(value, 0); } else { throw new ArgumentException("can only convert an array of size 1 to a Python scalar"); } } else { NpyIndexes indexes = new NpyIndexes(); { NpyUtil_IndexProcessing.IndexConverter(this, args, indexes); if (args.Length == 1) { if (indexes.IndexType(0) != NpyIndexType.NPY_INDEX_INTP) { throw new ArgumentException("invalid integer"); } // Do flat indexing Flat.SingleAssign(indexes.GetIntP(0), value); } else { if (indexes.IsSingleItem(ndim)) { npy_intp offset = indexes.SingleAssignOffset(this); SetItem(value, offset >> this.ItemSizeDiv); } else { throw new ArgumentException("Incorrect number of indices for the array"); } } } } } /// <summary> /// Return the array with the same data viewed with a different byte order. /// </summary> /// <param name="new_order"></param> /// <returns></returns> public ndarray newbyteorder(string new_order = null) { dtype newtype = NpyCoreApi.DescrNewByteorder(Dtype, NpyUtil_ArgProcessing.ByteorderConverter(new_order)); return NpyCoreApi.View(this, newtype, null); } /// <summary> /// Replaces specified elements of an array with given values. /// </summary> /// <param name="indices">Target indices, interpreted as integers.</param> /// <param name="values">Values to place in a at target indices. </param> /// <param name="mode">{‘raise’, ‘wrap’, ‘clip’}, optional</param> /// <returns></returns> public int put(object indices, object values, NPY_CLIPMODE mode = NPY_CLIPMODE.NPY_RAISE) { return np.put(this, indices, values, mode); } /// <summary> /// Return a flattened array. /// </summary> /// <param name="order">{‘C’,’F’, ‘A’, ‘K’}, optional</param> /// <returns></returns> public ndarray ravel(NPY_ORDER order = NPY_ORDER.NPY_CORDER) { return this.Ravel(order); } /// <summary> /// Gives a new shape to an array without changing its data. /// </summary> /// <param name="shape">The new shape should be compatible with the original shape.</param> /// <param name="order">{‘C’, ‘F’, ‘A’}, optional</param> /// <returns></returns> public ndarray reshape(IEnumerable<npy_intp> shape, NPY_ORDER order = NPY_ORDER.NPY_ANYORDER) { npy_intp[] newshape = shape.Select(x => (npy_intp)x).ToArray(); return NpyCoreApi.Newshape(this, newshape, order); } /// <summary> /// Gives a new shape to an array without changing its data. /// </summary> /// <param name="shape">The new shape should be compatible with the original shape.</param> /// <param name="order">{‘C’, ‘F’, ‘A’}, optional</param> /// <returns></returns> public ndarray reshape(int shape, NPY_ORDER order = NPY_ORDER.NPY_ANYORDER) { npy_intp[] newshape = new npy_intp[] { shape }; return NpyCoreApi.Newshape(this, newshape, order); } /// <summary> /// Set array flags WRITEABLE, ALIGNED, (WRITEBACKIFCOPY and UPDATEIFCOPY), respectively. /// </summary> /// <param name="write"></param> /// <param name="align"></param> /// <param name="uic"></param> public void setflags(object write = null, object align = null, object uic = null) { NPYARRAYFLAGS flags = RawFlags; if (align != null) { bool bAlign = NpyUtil_ArgProcessing.BoolConverter(align); if (bAlign) { flags |= NPYARRAYFLAGS.NPY_ALIGNED; } else { if (!NpyCoreApi.IsAligned(this)) { throw new ArgumentException("cannot set aligned flag of mis-aligned array to True"); } flags &= ~NPYARRAYFLAGS.NPY_ALIGNED; } } if (uic != null) { bool bUic = NpyUtil_ArgProcessing.BoolConverter(uic); if (bUic) { throw new ArgumentException("cannot set UPDATEIFCOPY flag to True"); } else { NpyCoreApi.ClearUPDATEIFCOPY(this); } } if (write != null) { bool bWrite = NpyUtil_ArgProcessing.BoolConverter(write); if (bWrite) { if (!NpyCoreApi.IsWriteable(this)) { throw new ArgumentException("cannot set WRITEABLE flag to true on this array"); } flags |= NPYARRAYFLAGS.NPY_WRITEABLE; } else { flags &= ~NPYARRAYFLAGS.NPY_WRITEABLE; } } RawFlags = flags; } /// <summary> /// copies array data into byte[]. Can change the ordering. /// </summary> /// <param name="order">{‘C’, ‘F’, ‘A’}, optional</param> /// <returns></returns> public byte[] tobytes(NPY_ORDER order = NPY_ORDER.NPY_ANYORDER) { return ToString(order); } #endregion #endregion /// <summary> /// Number of elements in the array. /// </summary> public npy_intp Size { get { return NpyCoreApi.ArraySize(this); } } /// <summary> /// Return the real part of the complex argument. /// </summary> public ndarray Real { get { return NpyCoreApi.GetReal(this); } } /// <summary> /// Return the imaginary part of the complex argument. /// </summary> public ndarray Imag { get { return NpyCoreApi.GetImag(this); } } /// <summary> /// returns printable string representation of ndarray /// </summary> /// <returns></returns> public override string ToString() { return StrFunction(this); } /// <summary> /// A 1-D iterator over the array. /// </summary> public flatiter Flat { get { return NpyCoreApi.IterNew(this); } } internal ndarray NewCopy(NPY_ORDER order = NPY_ORDER.NPY_CORDER) { return NpyCoreApi.NewCopy(this, order); } /// <summary> /// Directly accesses the array memory and returns the object at that /// offset. No checks are made, caller can easily crash the program /// or retrieve garbage data. /// </summary> /// <param name="offset">Offset into data array in bytes</param> /// <returns>Contents of the location</returns> public object GetItem(npy_intp offset) { return numpyAPI.GetItem(this.Array, offset); } /// <summary> /// Directly sets a given location in the data array. No checks are /// made to make sure the offset is sensible or the data is valid in /// anyway -- caller beware. /// 'internal' because this is a security vulnerability. /// </summary> /// <param name="src">Value to write</param> /// <param name="offset">Offset into array in bytes</param> public void SetItem(object src, npy_intp offset) { numpyAPI.SetItem(this.Array, offset, src); } /// <summary> /// Handle to the core representation. /// </summary> internal NpyArray Array { get { return core; } } /// <summary> /// Base address of the array data memory. Use with caution. /// </summary> internal VoidPtr DataAddress { get { return core.data; } } /// <summary> /// Returns an array of the sizes of each dimension. This property allocates /// a new array with each call and must make a managed-to-native call so it's /// worth caching the results if used in a loop. /// </summary> public npy_intp[] dims { get { return NpyCoreApi.GetArrayDimsOrStrides(this, true); } } /// <summary> /// the strides of the array. /// </summary> public npy_intp[] strides { get { return NpyCoreApi.GetArrayDimsOrStrides(this, false); } } /// <summary> /// Returns the stride of a given dimension. For looping over all dimensions, /// use 'strides'. This is more efficient if only one dimension is of interest. /// </summary> /// <param name="dimension">Dimension to query</param> /// <returns>Data stride in bytes</returns> public npy_intp Dim(int dimension) { return this.Array.dimensions[dimension]; } /// <summary> /// Returns the stride of a given dimension. For looping over all dimensions, /// use 'strides'. This is more efficient if only one dimension is of interest. /// </summary> /// <param name="dimension">Dimension to query</param> /// <returns>Data stride in bytes</returns> public npy_intp Stride(int dimension) { return this.Array.strides[dimension]; } /// <summary> /// True if memory layout of array is contiguous /// </summary> public bool IsContiguous { get { return ChkFlags(NPYARRAYFLAGS.NPY_CONTIGUOUS); } } public bool IsOneSegment { get { return ndim == 0 || ChkFlags(NPYARRAYFLAGS.NPY_FORTRAN) || ChkFlags(NPYARRAYFLAGS.NPY_CARRAY); } } /// <summary> /// true of array is a slice/view into another array. /// </summary> public bool IsASlice { get { return BaseArray != null; } } /// <summary> /// true if array is a single element array /// </summary> public bool IsAScalar { get { return Array.IsScalar; } } /// <summary> /// True if memory layout is Fortran order, false implies C order /// </summary> public bool IsFortran { get { return ChkFlags(NPYARRAYFLAGS.NPY_FORTRAN) && ndim > 1; } } /// <summary> /// true of byte order is not swapped /// </summary> public bool IsNotSwapped { get { return Dtype.IsNativeByteOrder; } } /// <summary> /// true if byte order is swapped /// </summary> public bool IsByteSwapped { get { return !IsNotSwapped; } } /// <summary> /// true of array is ordered in "C" format /// </summary> public bool IsCArray { get { return ChkFlags(NPYARRAYFLAGS.NPY_CARRAY) && IsNotSwapped; } } /// <summary> /// true if array is ordered in "C" formation and Read Only /// </summary> public bool IsCArray_RO { get { return ChkFlags(NPYARRAYFLAGS.NPY_CARRAY_RO) && IsNotSwapped; } } /// <summary> /// returns true of array is ordered in "F"ortran order /// </summary> public bool IsFArray { get { return ChkFlags(NPYARRAYFLAGS.NPY_FARRAY) && IsNotSwapped; } } /// <summary> /// returns true of array is ordered in "F"ortran order and Read Only /// </summary> public bool IsFArray_RO { get { return ChkFlags(NPYARRAYFLAGS.NPY_FARRAY_RO) && IsNotSwapped; } } /// <summary> /// returns true of data type is aligned, writable and machine byte-order /// </summary> public bool IsBehaved { get { return ChkFlags(NPYARRAYFLAGS.NPY_BEHAVED) && IsNotSwapped; } } /// <summary> /// returns true of data type is aligned and machine byte-order /// </summary> public bool IsBehaved_RO { get { return ChkFlags(NPYARRAYFLAGS.NPY_ALIGNED) && IsNotSwapped; } } /// <summary> /// return true if data type is a complex number /// </summary> internal bool IsComplex { get { return NpyDefs.IsComplex(TypeNum); } } /// <summary> /// returns true if data type is a "BigInteger" /// </summary> internal bool IsBigInt { get { return NpyDefs.IsBigInt(TypeNum); } } /// <summary> /// returns true if data type is Decimal /// </summary> internal bool IsDecimal { get { return NpyDefs.IsDecimal(TypeNum); } } /// <summary> /// returns true if data type is an integer value /// </summary> internal bool IsInteger { get { return NpyDefs.IsInteger(TypeNum); } } /// <summary> /// returns true if data type is a floating point value /// </summary> internal bool IsFloatingPoint { get { return NpyDefs.IsFloat(TypeNum); } } /// <summary> /// returns true if data type is inexact (i.e. floating point or complex) /// </summary> internal bool IsInexact { get { return IsFloatingPoint || IsComplex; } } /// <summary> /// returns true of data type is string /// </summary> public bool IsFlexible { get { return NpyDefs.IsFlexible(TypeNum); } } /// <summary> /// returns true of internal math functions can be operated on the data type /// </summary> public bool IsMathFunctionCapable { get { switch (TypeNum) { case NPY_TYPES.NPY_OBJECT: case NPY_TYPES.NPY_STRING: return false; default: return true; } } } /// <summary> /// always false since matrix types obsolete and not supported /// </summary> internal bool IsMatrix { get { return false; } } /// <summary> /// true if array is not Read Only /// </summary> public bool IsWriteable { get { return ChkFlags(NPYARRAYFLAGS.NPY_WRITEABLE); } } /// <summary> /// return true if data type is a string /// </summary> public bool IsString { get { return TypeNum == NPY_TYPES.NPY_STRING; } } /// <summary> /// TODO: What does this return? /// </summary> internal int ElementStrides { get { return NpyCoreApi.ElementStrides(this); } } /// <summary> /// check for ndarray flag == true /// </summary> /// <param name="flag"></param> /// <returns></returns> private bool ChkFlags(NPYARRAYFLAGS flag) { return ((RawFlags & flag) == flag); } // These operators are useful from other C# code and also turn into the // appropriate Python functions (+ goes to __add__, etc). #region IEnumerable<object> interface public IEnumerator<object> GetEnumerator() { return new ndarray_Enumerator(this); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new ndarray_Enumerator(this); } #endregion #region Internal methods private string BuildStringRepr(bool repr) { // Equivalent to array_repr_builtin (arrayobject.c) List<string> sb = new List<string>(); if (repr) sb.Append("array("); DumpData.DumpArray(sb, this.Array, repr); if (repr) { if (NpyDefs.IsExtended(this.TypeNum)) { sb.Add(String.Format(", '{0}{1}')", (char)Dtype.Type, this.ItemSize)); } else { sb.Add(String.Format(", '{0}')", (char)Dtype.Type)); } } StringBuilder sb1 = new StringBuilder(); foreach (var s in sb) { sb1.Append(s); } return sb1.ToString(); } /// <summary> /// Indexes an array by a single long and returns either an item or a sub-array. /// </summary> /// <param name="index">The index into the array</param> object GetArrayItem(npy_intp index) { if (ndim == 1) { if (Math.Abs(index) >= this.shape.iDims[0]) { throw new Exception("index exceeds size of array"); } if (index < 0) { index += this.shape.iDims[0]; } return numpyAPI.GetItem(this.Array, index); } else { return NpyCoreApi.ArrayItem(this, index); } } /// <summary> /// Indexes an array by a single long and returns either an item or a sub-array. /// </summary> /// <param name="index">The index into the array</param> void SetArrayItem(npy_intp index, object value) { if (ndim == 1) { numpyAPI.SetItem(this.Array, index, value); } else { var item = NpyCoreApi.ArrayItem(this, index); if (item is ndarray) { try { ndarray itemarr = item as ndarray; np.copyto(itemarr, value); } catch (Exception ex) { } } // todo: set the array items with the value?? } } internal NPYARRAYFLAGS RawFlags { get { return Array.flags; } set { Array.flags = value; } } internal ndarray BaseArray { get { if (core.base_arr == null) return null; return new ndarray(core.base_arr); } //set //{ // lock (this) // { // core.SetBase(value.core); // NpyCoreApi.Decref(value.core); // } //} } #endregion } internal class ndarray_Enumerator : IEnumerator<object> { public ndarray_Enumerator(ndarray a) { arr = a; index = -1; if (arr.ndim <= 1) { UseLocalCache = true; } } public object Current { get { if (UseLocalCache) { if (LocalCacheIndex >= LocalCacheLength) { ReLoadLocalCache(); } return LocalCache[LocalCacheIndex++]; } return arr[index]; } } public void Dispose() { arr = null; LocalCache = null; } public bool MoveNext() { index += 1; return (index < arr.dims[0]); } public void Reset() { index = -1; LocalCache = null; } private void ReLoadLocalCache() { LocalCacheLength = Math.Min(arr.size - index, MaxCacheSize); if (LocalCache == null) { LocalCache = new object[LocalCacheLength]; } NpyCoreApi.GetItems(arr, LocalCache, index, LocalCacheLength); LocalCacheIndex = 0; } private ndarray arr; private npy_intp index; bool UseLocalCache = false; npy_intp MaxCacheSize = 10000; npy_intp LocalCacheLength = 0; object[] LocalCache = null; int LocalCacheIndex = 0; } internal class CSharpTuple { public long? index1 = null; public long? index2 = null; public long? index3 = null; public CSharpTuple(long index1) { this.index1 = index1; } public CSharpTuple(long index1, long index2) { this.index1 = index1; this.index2 = index2; } public CSharpTuple(long index1, long index2, long index3) { this.index1 = index1; this.index2 = index2; this.index3 = index3; } } }
32.525184
141
0.497427
[ "BSD-3-Clause" ]
AvenSun/numpy.net
src/NumpyDotNet/NumpyDotNet/ndarray.cs
62,091
C#
namespace CustomComparator { using System.Collections.Generic; internal class Comparator : IComparer<int> { public int Compare(int x, int y) { if (x % 2 == 0 && y % 2 != 0) { return -1; } else if (y % 2 == 0 && x % 2 != 0) { return 1; } else { if (x < y) { return -1; } else { return 1; } } } } }
20.466667
46
0.281759
[ "MIT" ]
BoykoNeov/C-Sharp-Advanced---SoftUni
FunctionalProgramming/CustomComparator/Comparator.cs
616
C#
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using MultiIndexCollection.Tests.Data; namespace MultiIndexCollection.Tests { [TestClass] public class FilteringTests { [TestMethod] public void WhereEquals() { var users = new[] { new User { Name = "John", Age = 20 }, new User { Name = "Fred", Age = 30 }, new User { Name = "Alice", Age = 20 }, }; var expected = users.Where(u => u.Age == 20); var indexed = users.IndexBy(u => u.Age); var actual = indexed.Where(u => u.Age == 20); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereSortedEquals() { var users = new[] { new User { Name = "John", Age = 20 }, new User { Name = "Fred", Age = 30 }, new User { Name = "Alice", Age = 20 }, }; var expected = users.Where(u => u.Age == 20); var indexed = users.IndexBy(u => u.Age, true); var actual = indexed.Where(u => u.Age == 20); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereIsNull() { var users = new[] { new User { Name = "John", Age = 20 }, new User { Name = "Fred", Age = 30 }, new User { Name = "Alice", Age = null }, }; var expected = users.Where(u => u.Age == null); var indexed = users.IndexBy(u => u.Age); var actual = indexed.Where(u => u.Age == null); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereSortedIsNull() { var users = new[] { new User { Name = "John", Age = 20 }, new User { Name = "Fred", Age = 30 }, new User { Name = "Alice", Age = null }, }; var expected = users.Where(u => u.Age == null); var indexed = users.IndexBy(u => u.Age, true); var actual = indexed.Where(u => u.Age == null); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereGreaterThan() { var users = new[] { new User { Name = "John", Age = 20 }, new User { Name = "Fred", Age = 30 }, new User { Name = "Alice", Age = 30 }, }; var expected = users.Where(u => u.Age > 20); var indexed = users .IndexBy(u => u.Age, true); var actual = indexed.Where(u => u.Age > 20); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereGreaterThanOrEqual() { var users = new[] { new User { Name = "John", Age = 20 }, new User { Name = "Fred", Age = 30 }, new User { Name = "Alice", Age = 30 }, }; var expected = users.Where(u => u.Age >= 30); var indexed = users .IndexBy(u => u.Age, true); var actual = indexed.Where(u => u.Age >= 30); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereLessThan() { var users = new[] { new User { Name = "John", Age = 20 }, new User { Name = "Fred", Age = 30 }, new User { Name = "Alice", Age = 30 }, }; var expected = users.Where(u => u.Age < 30); var indexed = users .IndexBy(u => u.Age, true); var actual = indexed.Where(u => u.Age < 30); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereLessThanOrEqual() { var users = new[] { new User { Name = "John", Age = 20 }, new User { Name = "Fred", Age = 30 }, new User { Name = "Alice", Age = 30 }, }; var expected = users.Where(u => u.Age <= 20); var indexed = users .IndexBy(u => u.Age, true); var actual = indexed.Where(u => u.Age <= 20); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereAndAlso() { var users = new[] { new User { Name = "John", Age = 20 }, new User { Name = "Fred", Age = 30 }, new User { Name = "John", Age = 30 }, }; var expected = users.Where(u => u.Name == "John" && u.Age == 30); var indexed = users .IndexBy(u => u.Name) .IndexBy(u => u.Age, true); var actual = indexed.Where(u => u.Name == "John" && u.Age == 30); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereOrElse() { var users = new[] { new User { Name = "John", Age = 20 }, new User { Name = "Fred", Age = 30 }, new User { Name = "John", Age = 30 }, }; var expected = users.Where(u => u.Name == "John" || u.Age == 30).ToArray(); var indexed = users .IndexBy(u => u.Name) .IndexBy(u => u.Age, true); var actual = indexed.Where(u => u.Name == "John" || u.Age == 30).ToArray(); Assert.That.SetEquals(expected, actual); } #region WhereBeetween [TestMethod] public void WhereBeetween() { var users = new[] { new User { Name = "John", Age = 15 }, new User { Name = "Fred", Age = 20 }, new User { Name = "Alice", Age = 30 }, new User { Name = "Bob", Age = 35 }, new User { Name = "Sara", Age = 40 }, }; var expected = users.Where(u => u.Age >= 20 && u.Age <= 35); var indexed = users.IndexBy(u => u.Age, true); var actual = indexed.Where(u => u.Age >= 20 && u.Age <= 35); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereBeetweenGreaterExclusive() { var users = new[] { new User { Name = "John", Age = 15 }, new User { Name = "Fred", Age = 20 }, new User { Name = "Alice", Age = 30 }, new User { Name = "Bob", Age = 35 }, new User { Name = "Sara", Age = 40 }, }; var expected = users.Where(u => u.Age >= 20 && u.Age < 35); var indexed = users.IndexBy(u => u.Age, true); var actual = indexed.Where(u => u.Age >= 20 && u.Age < 35); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereBeetweenLessExclusive() { var users = new[] { new User { Name = "John", Age = 15 }, new User { Name = "Fred", Age = 20 }, new User { Name = "Alice", Age = 30 }, new User { Name = "Bob", Age = 35 }, new User { Name = "Sara", Age = 40 }, }; var expected = users.Where(u => u.Age > 20 && u.Age <= 35); var indexed = users.IndexBy(u => u.Age, true); var actual = indexed.Where(u => u.Age > 20 && u.Age <= 35); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereBeetweenExclusive() { var users = new[] { new User { Name = "John", Age = 15 }, new User { Name = "Fred", Age = 20 }, new User { Name = "Alice", Age = 30 }, new User { Name = "Bob", Age = 35 }, new User { Name = "Sara", Age = 40 }, }; var expected = users.Where(u => u.Age > 20 && u.Age < 35); var indexed = users.IndexBy(u => u.Age, true); var actual = indexed.Where(u => u.Age > 20 && u.Age < 35); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereBeetweenInclusive() { var users = new[] { new User { Name = "John", Age = 15 }, new User { Name = "Fred", Age = 20 }, new User { Name = "Alice", Age = 30 }, new User { Name = "Bob", Age = 35 }, new User { Name = "Sara", Age = 40 }, }; var expected = users.Where(u => u.Age <= 35 && u.Age >= 20); var indexed = users.IndexBy(u => u.Age, true); var actual = indexed.Where(u => u.Age <= 35 && u.Age >= 20); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereBeetweenGreaterInclusive() { var users = new[] { new User { Name = "John", Age = 15 }, new User { Name = "Fred", Age = 20 }, new User { Name = "Alice", Age = 30 }, new User { Name = "Bob", Age = 35 }, new User { Name = "Sara", Age = 40 }, }; var expected = users.Where(u => u.Age <= 35 && u.Age > 20); var indexed = users.IndexBy(u => u.Age, true); var actual = indexed.Where(u => u.Age <= 35 && u.Age > 20); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereBeetweenLessInclusive() { var users = new[] { new User { Name = "John", Age = 15 }, new User { Name = "Fred", Age = 20 }, new User { Name = "Alice", Age = 30 }, new User { Name = "Bob", Age = 35 }, new User { Name = "Sara", Age = 40 }, }; var expected = users.Where(u => u.Age < 35 && u.Age >= 20); var indexed = users.IndexBy(u => u.Age, true); var actual = indexed.Where(u => u.Age < 35 && u.Age >= 20); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereBeetweenExclusiveReverse() { var users = new[] { new User { Name = "John", Age = 15 }, new User { Name = "Fred", Age = 20 }, new User { Name = "Alice", Age = 30 }, new User { Name = "Bob", Age = 35 }, new User { Name = "Sara", Age = 40 }, }; var expected = users.Where(u => u.Age < 35 && u.Age > 20); var indexed = users.IndexBy(u => u.Age, true); var actual = indexed.Where(u => u.Age < 35 && u.Age > 20); Assert.That.SetEquals(expected, actual); } #endregion [TestMethod] public void WhereStringStartsWith() { var users = new[] { new User { Name = "Alice", Age = 30 }, new User { Name = "Bob", Age = 35 }, new User { Name = "Bill", Age = 40 }, }; var expected = users.Where(u => u.Name.StartsWith("B")); var indexed = users.IndexBy(u => u.Name, true); var actual = indexed.Where(u => u.Name.StartsWith("B")); Assert.That.SetEquals(expected, actual); } [TestMethod] public void WhereStringStartsWithIgnoreCase() { var users = new[] { new User { Name = "Alice", Age = 30 }, new User { Name = "bob", Age = 35 }, new User { Name = "Bill", Age = 40 }, }; var expected = users.Where(u => u.Name .StartsWith("B", StringComparison.InvariantCultureIgnoreCase)); var indexed = users.IndexByIgnoreCase(u => u.Name); var actual = indexed.Where(u => u.Name.StartsWith("B")); Assert.That.SetEquals(expected, actual); } } }
29.790974
87
0.431749
[ "MIT" ]
gnaeus/MultiIndexCollection
MultiIndexCollection.Tests/FilteringTests.cs
12,544
C#
using System; namespace UpdateManager { public class UpdateManagerUpdateable : IUpdateable { private UpdateManagerUpdateable() { } private static UpdateManagerUpdateable _Instance { get; set; } public static UpdateManagerUpdateable Instance { get { if (_Instance == null) _Instance = new UpdateManagerUpdateable(); return _Instance; } } public string UpdateName { get { return "Update Manager"; } } public string XMLURL { get { return "http://livesplit.org/update/update.updater.xml"; } } public string UpdateURL { get { return "http://livesplit.org/update/"; } } public Version Version { get { return Version.Parse("2.0.2"); } } } }
22.047619
76
0.512959
[ "MIT" ]
Ajarmar/LiveSplit
LiveSplit/UpdateManager/UpdateManagerUpdateable.cs
928
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.R_kvstore.Transform; using Aliyun.Acs.R_kvstore.Transform.V20150101; namespace Aliyun.Acs.R_kvstore.Model.V20150101 { public class RenewMultiInstanceRequest : RpcAcsRequest<RenewMultiInstanceResponse> { public RenewMultiInstanceRequest() : base("R-kvstore", "2015-01-01", "RenewMultiInstance", "redisa", "openAPI") { } private long? resourceOwnerId; private long? period; private bool? autoPay; private string fromApp; private string resourceOwnerAccount; private string ownerAccount; private string couponNo; private long? ownerId; private string securityToken; private string instanceIds; private string businessInfo; public long? ResourceOwnerId { get { return resourceOwnerId; } set { resourceOwnerId = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString()); } } public long? Period { get { return period; } set { period = value; DictionaryUtil.Add(QueryParameters, "Period", value.ToString()); } } public bool? AutoPay { get { return autoPay; } set { autoPay = value; DictionaryUtil.Add(QueryParameters, "AutoPay", value.ToString()); } } public string FromApp { get { return fromApp; } set { fromApp = value; DictionaryUtil.Add(QueryParameters, "FromApp", value); } } public string ResourceOwnerAccount { get { return resourceOwnerAccount; } set { resourceOwnerAccount = value; DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value); } } public string OwnerAccount { get { return ownerAccount; } set { ownerAccount = value; DictionaryUtil.Add(QueryParameters, "OwnerAccount", value); } } public string CouponNo { get { return couponNo; } set { couponNo = value; DictionaryUtil.Add(QueryParameters, "CouponNo", value); } } public long? OwnerId { get { return ownerId; } set { ownerId = value; DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString()); } } public string SecurityToken { get { return securityToken; } set { securityToken = value; DictionaryUtil.Add(QueryParameters, "SecurityToken", value); } } public string InstanceIds { get { return instanceIds; } set { instanceIds = value; DictionaryUtil.Add(QueryParameters, "InstanceIds", value); } } public string BusinessInfo { get { return businessInfo; } set { businessInfo = value; DictionaryUtil.Add(QueryParameters, "BusinessInfo", value); } } public override RenewMultiInstanceResponse GetResponse(UnmarshallerContext unmarshallerContext) { return RenewMultiInstanceResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
19.778846
103
0.640253
[ "Apache-2.0" ]
bitType/aliyun-openapi-net-sdk
aliyun-net-sdk-r-kvstore/R_kvstore/Model/V20150101/RenewMultiInstanceRequest.cs
4,114
C#
namespace inventory { partial class formnewitem { /// <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(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle2 = new System.Windows.Forms.DataGridViewCellStyle(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(formnewitem)); this.dgv = new System.Windows.Forms.DataGridView(); this.Itm = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.cls = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.sub = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.mnfctr = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.mod = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.sn = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.props = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.Specs = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.sof = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.cacquisition = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.date = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.etly = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.qty = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.label4 = new System.Windows.Forms.Label(); this.timer1 = new System.Windows.Forms.Timer(this.components); this.lbldate = new System.Windows.Forms.Label(); this.btnsave = new System.Windows.Forms.Button(); this.btndel = new System.Windows.Forms.Button(); this.txtprop = new System.Windows.Forms.TextBox(); this.txtmod = new System.Windows.Forms.TextBox(); this.btnadd = new System.Windows.Forms.Button(); this.cmbsof = new System.Windows.Forms.ComboBox(); this.txtest = new System.Windows.Forms.TextBox(); this.cmbsub = new System.Windows.Forms.ComboBox(); this.cmbac = new System.Windows.Forms.ComboBox(); this.datepick = new System.Windows.Forms.DateTimePicker(); this.txtqty = new System.Windows.Forms.TextBox(); this.txtspec = new System.Windows.Forms.TextBox(); this.txtsn = new System.Windows.Forms.TextBox(); this.txtman = new System.Windows.Forms.TextBox(); this.txtitemname = new System.Windows.Forms.TextBox(); this.txtcoa = new System.Windows.Forms.TextBox(); this.label18 = new System.Windows.Forms.Label(); this.label15 = new System.Windows.Forms.Label(); this.label14 = new System.Windows.Forms.Label(); this.label13 = new System.Windows.Forms.Label(); this.label12 = new System.Windows.Forms.Label(); this.label10 = new System.Windows.Forms.Label(); this.label9 = new System.Windows.Forms.Label(); this.label8 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.label6 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.lblcounter = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.lblofficer = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.dgv)).BeginInit(); this.SuspendLayout(); // // dgv // this.dgv.AllowUserToAddRows = false; dataGridViewCellStyle1.BackColor = System.Drawing.Color.White; dataGridViewCellStyle1.ForeColor = System.Drawing.Color.Black; dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.MenuHighlight; dataGridViewCellStyle1.SelectionForeColor = System.Drawing.Color.White; this.dgv.AlternatingRowsDefaultCellStyle = dataGridViewCellStyle1; this.dgv.BackgroundColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(45)))), ((int)(((byte)(48))))); this.dgv.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dgv.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.Itm, this.cls, this.sub, this.mnfctr, this.mod, this.sn, this.props, this.Specs, this.sof, this.cacquisition, this.date, this.etly, this.qty}); this.dgv.Location = new System.Drawing.Point(14, 249); this.dgv.MultiSelect = false; this.dgv.Name = "dgv"; this.dgv.ReadOnly = true; dataGridViewCellStyle2.BackColor = System.Drawing.Color.White; dataGridViewCellStyle2.ForeColor = System.Drawing.Color.Black; dataGridViewCellStyle2.SelectionBackColor = System.Drawing.SystemColors.MenuHighlight; dataGridViewCellStyle2.SelectionForeColor = System.Drawing.Color.White; this.dgv.RowsDefaultCellStyle = dataGridViewCellStyle2; this.dgv.RowTemplate.DefaultCellStyle.BackColor = System.Drawing.Color.White; this.dgv.RowTemplate.DefaultCellStyle.ForeColor = System.Drawing.Color.Black; this.dgv.RowTemplate.DefaultCellStyle.SelectionBackColor = System.Drawing.SystemColors.MenuHighlight; this.dgv.RowTemplate.DefaultCellStyle.SelectionForeColor = System.Drawing.Color.White; this.dgv.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dgv.Size = new System.Drawing.Size(625, 227); this.dgv.TabIndex = 0; this.dgv.CellDoubleClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgv_CellDoubleClick); this.dgv.RowStateChanged += new System.Windows.Forms.DataGridViewRowStateChangedEventHandler(this.dgv_RowStateChanged); // // Itm // this.Itm.HeaderText = "Item"; this.Itm.Name = "Itm"; this.Itm.ReadOnly = true; // // cls // this.cls.HeaderText = "Classification"; this.cls.Name = "cls"; this.cls.ReadOnly = true; // // sub // this.sub.HeaderText = "Sub Class"; this.sub.Name = "sub"; this.sub.ReadOnly = true; // // mnfctr // this.mnfctr.HeaderText = "Manufacturer"; this.mnfctr.Name = "mnfctr"; this.mnfctr.ReadOnly = true; // // mod // this.mod.HeaderText = "Model"; this.mod.Name = "mod"; this.mod.ReadOnly = true; // // sn // this.sn.HeaderText = "Serial"; this.sn.Name = "sn"; this.sn.ReadOnly = true; // // props // this.props.HeaderText = "Property Number"; this.props.Name = "props"; this.props.ReadOnly = true; // // Specs // this.Specs.HeaderText = "Specification"; this.Specs.Name = "Specs"; this.Specs.ReadOnly = true; // // sof // this.sof.HeaderText = "Funds"; this.sof.Name = "sof"; this.sof.ReadOnly = true; // // cacquisition // this.cacquisition.HeaderText = "Cost"; this.cacquisition.Name = "cacquisition"; this.cacquisition.ReadOnly = true; // // date // this.date.HeaderText = "Date"; this.date.Name = "date"; this.date.ReadOnly = true; // // etly // this.etly.HeaderText = "Est. Total Life Years"; this.etly.Name = "etly"; this.etly.ReadOnly = true; // // qty // this.qty.HeaderText = "Quantity"; this.qty.Name = "qty"; this.qty.ReadOnly = true; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Roboto", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label4.Location = new System.Drawing.Point(264, 9); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(95, 19); this.label4.TabIndex = 54; this.label4.Text = "New Entries"; // // timer1 // this.timer1.Enabled = true; this.timer1.Tick += new System.EventHandler(this.timer1_Tick); // // lbldate // this.lbldate.AutoSize = true; this.lbldate.Font = new System.Drawing.Font("Roboto", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lbldate.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.lbldate.Location = new System.Drawing.Point(442, 14); this.lbldate.Name = "lbldate"; this.lbldate.Size = new System.Drawing.Size(31, 14); this.lbldate.TabIndex = 55; this.lbldate.Text = "date"; // // btnsave // this.btnsave.BackColor = System.Drawing.Color.Lime; this.btnsave.Enabled = false; this.btnsave.ForeColor = System.Drawing.Color.Black; this.btnsave.Location = new System.Drawing.Point(560, 198); this.btnsave.Name = "btnsave"; this.btnsave.Size = new System.Drawing.Size(69, 26); this.btnsave.TabIndex = 81; this.btnsave.Text = "Register"; this.btnsave.UseVisualStyleBackColor = false; this.btnsave.Click += new System.EventHandler(this.btnsave_Click); // // btndel // this.btndel.ForeColor = System.Drawing.SystemColors.ControlText; this.btndel.Location = new System.Drawing.Point(470, 198); this.btndel.Name = "btndel"; this.btndel.Size = new System.Drawing.Size(69, 26); this.btndel.TabIndex = 82; this.btndel.Text = "Delete"; this.btndel.UseVisualStyleBackColor = true; this.btndel.Click += new System.EventHandler(this.btndel_Click); // // txtprop // this.txtprop.Location = new System.Drawing.Point(116, 195); this.txtprop.MaxLength = 10; this.txtprop.Name = "txtprop"; this.txtprop.Size = new System.Drawing.Size(184, 21); this.txtprop.TabIndex = 66; this.txtprop.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtqty_KeyPress); // // txtmod // this.txtmod.Location = new System.Drawing.Point(117, 151); this.txtmod.Name = "txtmod"; this.txtmod.Size = new System.Drawing.Size(183, 21); this.txtmod.TabIndex = 62; // // btnadd // this.btnadd.ForeColor = System.Drawing.SystemColors.ControlText; this.btnadd.Location = new System.Drawing.Point(395, 198); this.btnadd.Name = "btnadd"; this.btnadd.Size = new System.Drawing.Size(69, 26); this.btnadd.TabIndex = 79; this.btnadd.Text = "Add"; this.btnadd.UseVisualStyleBackColor = true; this.btnadd.Click += new System.EventHandler(this.btnadd_Click); // // cmbsof // this.cmbsof.Font = new System.Drawing.Font("Roboto", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cmbsof.FormattingEnabled = true; this.cmbsof.Location = new System.Drawing.Point(431, 81); this.cmbsof.Name = "cmbsof"; this.cmbsof.Size = new System.Drawing.Size(183, 22); this.cmbsof.TabIndex = 70; // // txtest // this.txtest.Location = new System.Drawing.Point(431, 148); this.txtest.MaxLength = 3; this.txtest.Name = "txtest"; this.txtest.Size = new System.Drawing.Size(85, 21); this.txtest.TabIndex = 75; this.txtest.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtqty_KeyPress); // // cmbsub // this.cmbsub.Font = new System.Drawing.Font("Roboto", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cmbsub.FormattingEnabled = true; this.cmbsub.Location = new System.Drawing.Point(117, 106); this.cmbsub.Name = "cmbsub"; this.cmbsub.Size = new System.Drawing.Size(183, 22); this.cmbsub.TabIndex = 60; // // cmbac // this.cmbac.Font = new System.Drawing.Font("Roboto", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.cmbac.FormattingEnabled = true; this.cmbac.Location = new System.Drawing.Point(117, 83); this.cmbac.Name = "cmbac"; this.cmbac.Size = new System.Drawing.Size(183, 22); this.cmbac.TabIndex = 58; this.cmbac.SelectedIndexChanged += new System.EventHandler(this.cmbac_SelectedIndexChanged); // // datepick // this.datepick.Format = System.Windows.Forms.DateTimePickerFormat.Short; this.datepick.ImeMode = System.Windows.Forms.ImeMode.NoControl; this.datepick.Location = new System.Drawing.Point(431, 126); this.datepick.Name = "datepick"; this.datepick.Size = new System.Drawing.Size(83, 21); this.datepick.TabIndex = 74; this.datepick.Value = new System.DateTime(2021, 3, 4, 0, 0, 0, 0); // // txtqty // this.txtqty.Location = new System.Drawing.Point(431, 171); this.txtqty.MaxLength = 3; this.txtqty.Name = "txtqty"; this.txtqty.Size = new System.Drawing.Size(30, 21); this.txtqty.TabIndex = 77; this.txtqty.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtqty_KeyPress); // // txtspec // this.txtspec.Location = new System.Drawing.Point(431, 59); this.txtspec.Name = "txtspec"; this.txtspec.Size = new System.Drawing.Size(183, 21); this.txtspec.TabIndex = 68; // // txtsn // this.txtsn.Location = new System.Drawing.Point(117, 173); this.txtsn.MaxLength = 10; this.txtsn.Name = "txtsn"; this.txtsn.Size = new System.Drawing.Size(183, 21); this.txtsn.TabIndex = 65; this.txtsn.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtqty_KeyPress); // // txtman // this.txtman.Location = new System.Drawing.Point(117, 129); this.txtman.Name = "txtman"; this.txtman.Size = new System.Drawing.Size(183, 21); this.txtman.TabIndex = 61; // // txtitemname // this.txtitemname.Location = new System.Drawing.Point(117, 61); this.txtitemname.Name = "txtitemname"; this.txtitemname.ShortcutsEnabled = false; this.txtitemname.Size = new System.Drawing.Size(183, 21); this.txtitemname.TabIndex = 56; // // txtcoa // this.txtcoa.Location = new System.Drawing.Point(431, 104); this.txtcoa.Name = "txtcoa"; this.txtcoa.Size = new System.Drawing.Size(121, 21); this.txtcoa.TabIndex = 72; // // label18 // this.label18.AutoSize = true; this.label18.Font = new System.Drawing.Font("Roboto", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label18.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label18.Location = new System.Drawing.Point(372, 176); this.label18.Name = "label18"; this.label18.Size = new System.Drawing.Size(53, 13); this.label18.TabIndex = 84; this.label18.Text = "Quantity:"; // // label15 // this.label15.AutoSize = true; this.label15.Font = new System.Drawing.Font("Roboto", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label15.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label15.Location = new System.Drawing.Point(306, 154); this.label15.Name = "label15"; this.label15.Size = new System.Drawing.Size(118, 13); this.label15.TabIndex = 83; this.label15.Text = "Estm.Total Life Years:"; // // label14 // this.label14.AutoSize = true; this.label14.Font = new System.Drawing.Font("Roboto", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label14.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label14.Location = new System.Drawing.Point(319, 132); this.label14.Name = "label14"; this.label14.Size = new System.Drawing.Size(105, 13); this.label14.TabIndex = 80; this.label14.Text = "Date of Acquisition:"; // // label13 // this.label13.AutoSize = true; this.label13.Font = new System.Drawing.Font("Roboto", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label13.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label13.Location = new System.Drawing.Point(319, 110); this.label13.Name = "label13"; this.label13.Size = new System.Drawing.Size(105, 13); this.label13.TabIndex = 78; this.label13.Text = "Cost of Acquisition:"; // // label12 // this.label12.AutoSize = true; this.label12.Font = new System.Drawing.Font("Roboto", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label12.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label12.Location = new System.Drawing.Point(339, 87); this.label12.Name = "label12"; this.label12.Size = new System.Drawing.Size(85, 13); this.label12.TabIndex = 76; this.label12.Text = "Source of Fund:"; // // label10 // this.label10.AutoSize = true; this.label10.Font = new System.Drawing.Font("Roboto", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label10.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label10.Location = new System.Drawing.Point(17, 198); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(96, 13); this.label10.TabIndex = 73; this.label10.Text = "Property Number:"; // // label9 // this.label9.AutoSize = true; this.label9.Font = new System.Drawing.Font("Roboto", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label9.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label9.Location = new System.Drawing.Point(349, 64); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(76, 13); this.label9.TabIndex = 71; this.label9.Text = "Specification:"; // // label8 // this.label8.AutoSize = true; this.label8.Font = new System.Drawing.Font("Roboto", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label8.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label8.Location = new System.Drawing.Point(30, 176); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(82, 13); this.label8.TabIndex = 69; this.label8.Text = "Serial Number:"; // // label7 // this.label7.AutoSize = true; this.label7.Font = new System.Drawing.Font("Roboto", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label7.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label7.Location = new System.Drawing.Point(68, 154); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(41, 13); this.label7.TabIndex = 67; this.label7.Text = "Model:"; // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Roboto", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label6.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label6.Location = new System.Drawing.Point(35, 132); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(78, 13); this.label6.TabIndex = 64; this.label6.Text = "Manufacturer:"; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Roboto", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label5.Location = new System.Drawing.Point(80, 66); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(33, 13); this.label5.TabIndex = 63; this.label5.Text = "Item:"; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Roboto", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label3.Location = new System.Drawing.Point(46, 110); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(67, 13); this.label3.TabIndex = 59; this.label3.Text = "Sub - Class:"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Roboto", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label2.Location = new System.Drawing.Point(34, 88); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(79, 13); this.label2.TabIndex = 57; this.label2.Text = "Classification:"; // // lblcounter // this.lblcounter.AutoSize = true; this.lblcounter.Font = new System.Drawing.Font("Roboto", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblcounter.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.lblcounter.Location = new System.Drawing.Point(102, 78); this.lblcounter.Name = "lblcounter"; this.lblcounter.Size = new System.Drawing.Size(13, 14); this.lblcounter.TabIndex = 85; this.lblcounter.Text = "c"; this.lblcounter.Visible = false; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Roboto", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.label1.Location = new System.Drawing.Point(16, 229); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(109, 13); this.label1.TabIndex = 86; this.label1.Text = "Accountable Officer:"; // // lblofficer // this.lblofficer.AutoSize = true; this.lblofficer.Font = new System.Drawing.Font("Roboto", 9F, ((System.Drawing.FontStyle)((System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Underline))), System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblofficer.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.lblofficer.Location = new System.Drawing.Point(124, 229); this.lblofficer.Name = "lblofficer"; this.lblofficer.Size = new System.Drawing.Size(42, 14); this.lblofficer.TabIndex = 87; this.lblofficer.Text = "Officer"; // // formnewitem // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(45)))), ((int)(((byte)(45)))), ((int)(((byte)(48))))); this.ClientSize = new System.Drawing.Size(651, 486); this.Controls.Add(this.lblofficer); this.Controls.Add(this.label1); this.Controls.Add(this.btnsave); this.Controls.Add(this.btndel); this.Controls.Add(this.txtprop); this.Controls.Add(this.txtmod); this.Controls.Add(this.btnadd); this.Controls.Add(this.cmbsof); this.Controls.Add(this.txtest); this.Controls.Add(this.cmbsub); this.Controls.Add(this.cmbac); this.Controls.Add(this.datepick); this.Controls.Add(this.txtqty); this.Controls.Add(this.txtspec); this.Controls.Add(this.txtsn); this.Controls.Add(this.txtman); this.Controls.Add(this.txtitemname); this.Controls.Add(this.txtcoa); this.Controls.Add(this.label18); this.Controls.Add(this.label15); this.Controls.Add(this.label14); this.Controls.Add(this.label13); this.Controls.Add(this.label12); this.Controls.Add(this.label10); this.Controls.Add(this.label9); this.Controls.Add(this.label8); this.Controls.Add(this.label7); this.Controls.Add(this.label6); this.Controls.Add(this.label5); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.lblcounter); this.Controls.Add(this.lbldate); this.Controls.Add(this.label4); this.Controls.Add(this.dgv); this.Font = new System.Drawing.Font("Roboto", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ForeColor = System.Drawing.SystemColors.ControlLightLight; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "formnewitem"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Item/s"; this.Load += new System.EventHandler(this.formnewitem_Load); ((System.ComponentModel.ISupportInitialize)(this.dgv)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.DataGridView dgv; private System.Windows.Forms.DataGridViewTextBoxColumn Itm; private System.Windows.Forms.DataGridViewTextBoxColumn cls; private System.Windows.Forms.DataGridViewTextBoxColumn sub; private System.Windows.Forms.DataGridViewTextBoxColumn mnfctr; private System.Windows.Forms.DataGridViewTextBoxColumn mod; private System.Windows.Forms.DataGridViewTextBoxColumn sn; private System.Windows.Forms.DataGridViewTextBoxColumn props; private System.Windows.Forms.DataGridViewTextBoxColumn Specs; private System.Windows.Forms.DataGridViewTextBoxColumn sof; private System.Windows.Forms.DataGridViewTextBoxColumn cacquisition; private System.Windows.Forms.DataGridViewTextBoxColumn date; private System.Windows.Forms.DataGridViewTextBoxColumn etly; private System.Windows.Forms.DataGridViewTextBoxColumn qty; private System.Windows.Forms.Label label4; private System.Windows.Forms.Timer timer1; private System.Windows.Forms.Label lbldate; private System.Windows.Forms.Button btnsave; private System.Windows.Forms.Button btndel; private System.Windows.Forms.TextBox txtprop; private System.Windows.Forms.TextBox txtmod; private System.Windows.Forms.Button btnadd; private System.Windows.Forms.ComboBox cmbsof; private System.Windows.Forms.TextBox txtest; private System.Windows.Forms.ComboBox cmbsub; private System.Windows.Forms.ComboBox cmbac; private System.Windows.Forms.DateTimePicker datepick; private System.Windows.Forms.TextBox txtqty; private System.Windows.Forms.TextBox txtspec; private System.Windows.Forms.TextBox txtsn; private System.Windows.Forms.TextBox txtman; private System.Windows.Forms.TextBox txtitemname; private System.Windows.Forms.TextBox txtcoa; private System.Windows.Forms.Label label18; private System.Windows.Forms.Label label15; private System.Windows.Forms.Label label14; private System.Windows.Forms.Label label13; private System.Windows.Forms.Label label12; private System.Windows.Forms.Label label10; private System.Windows.Forms.Label label9; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label7; private System.Windows.Forms.Label label6; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label lblcounter; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label lblofficer; } }
50.834835
222
0.577505
[ "Unlicense" ]
Frissons/CSharpInventoryRdlc2021-
inventory/formnewitem.Designer.cs
33,858
C#
using System; using System.Collections.Generic; namespace fastJSON { public sealed class DatasetSchema { public List<string> Info ;//{ get; set; } public string Name ;//{ get; set; } } }
19
50
0.592105
[ "Apache-2.0" ]
FantasyTianyu/FantasyFramework
FantasyFramework/ThirdParty/fastJSON/Getters.cs
230
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DomainDrivenDesign.CoreEcommerce.Ef; namespace DomainDrivenDesign.CoreEcommerce.Services { public class OrderPromotionServices { public static OrderPromotion CalculateForDiscount(Guid shoppingCartId) { using (var db =new CoreEcommerceDbContext()) { var temp = db.OrderPromotions.OrderByDescending(i=>i.CreatedDate).FirstOrDefault(i => i.Actived); var cart = db.ShoppingCarts.SingleOrDefault(i => i.Id == shoppingCartId); if (cart != null && temp != null && cart.CartTotal >= temp.AmountToDiscount) { return temp; } return temp; } } public static OrderPromotion CalculateForShipping(Guid shoppingCartId) { using (var db = new CoreEcommerceDbContext()) { var temp = db.OrderPromotions.OrderByDescending(i => i.CreatedDate).FirstOrDefault(i => i.Actived); var cart = db.ShoppingCarts.SingleOrDefault(i => i.Id == shoppingCartId); if (cart != null && temp!=null && cart.CartTotal >= temp.AmountToDiscount) { return temp; } } return null; } } }
35.6
115
0.574438
[ "MIT" ]
badpaybad/opendotnet-ecommerce-platform
DomainDrivenDesign.CoreEcommerce/Services/OrderPromotionServices.cs
1,426
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class GuardBehaviour : MonoBehaviour { public float chaseSpeed; public float patrolSpeed; private GameObject player; public List<GameObject> patrolPoints; public bool chasing = false; public bool attacking = false; GameObject nextPoint; private int currentPoint = 0; private float timeLastAttacked; private float attackCooldown = 1f; public bool facingLeft = false; public bool facingRight = true; public bool stunned = false; public float timeStunned; private float stunLenght = 2f; public int health; public Animator anim; private _boardManager manager; void Start() { timeLastAttacked = Time.time; player = GameObject.FindWithTag("Player"); manager = GameObject.FindGameObjectWithTag("Manager").GetComponent<_boardManager>(); } void FixedUpdate() { if (!stunned) { if (!chasing) { anim.SetBool("catched", false); Patrol(); } } else { if (timeStunned + stunLenght < Time.time) { stunned = false; anim.SetBool("stunned", false); } else { anim.SetBool("stunned", true); anim.SetBool("catched", false); } } if (health <= 0) { Destroy(this.gameObject); } } void Patrol() { var pointsFromListToArray = patrolPoints.ToArray(); var point = pointsFromListToArray[currentPoint]; var distanceToPoint = Vector2.Distance(transform.position, point.transform.position); if (distanceToPoint > 0.1) { var pos = transform.position; transform.position = Vector2.MoveTowards(transform.position, point.transform.position, patrolSpeed * Time.deltaTime); if (pos.x > transform.position.x) { transform.rotation = Quaternion.Euler(0, 180, 0); facingLeft = true; facingRight = false; } else { transform.rotation = Quaternion.Euler(0, 0, 0); facingLeft = false; facingRight = true; } } else { if (currentPoint < pointsFromListToArray.Length - 1) { currentPoint++; } else { currentPoint = 0; } } } void ChasePlayer() { if (player == null) { player = GameObject.FindWithTag("Player"); } var dist = Vector2.Distance(transform.position, player.transform.position); if (dist < 0.6f) { attacking = true; anim.SetBool("catched", true); player.GetComponent<PlayerController>().canMove = false; if (timeLastAttacked + attackCooldown < Time.time) { manager.health -= 10; timeLastAttacked = Time.time; } } else { attacking = false; player.GetComponent<PlayerController>().canMove = true; } if (!attacking) { transform.position = Vector2.MoveTowards(transform.position, player.transform.position, chaseSpeed * Time.deltaTime); } } }
25
129
0.527832
[ "MIT" ]
ggj-2020-plovdiv/MrHacker
Assets/Scripts/GuardBehaviour.cs
3,577
C#
using VRTK.Core.Data.Type.Transformation; namespace Test.VRTK.Core.Data.Type.Transformation { using UnityEngine; using NUnit.Framework; using Test.VRTK.Core.Utility.Mock; public class FloatMultiplierTest { private GameObject containingObject; private FloatMultiplier subject; [SetUp] public void SetUp() { containingObject = new GameObject(); subject = containingObject.AddComponent<FloatMultiplier>(); } [TearDown] public void TearDown() { Object.DestroyImmediate(subject); Object.DestroyImmediate(containingObject); } [Test] public void Transform() { UnityEventListenerMock transformedListenerMock = new UnityEventListenerMock(); subject.Transformed.AddListener(transformedListenerMock.Listen); subject.SetMultiplier(2f); Assert.AreEqual(0f, subject.Result); Assert.IsFalse(transformedListenerMock.Received); float result = subject.Transform(2f); Assert.AreEqual(4f, result); Assert.AreEqual(4f, subject.Result); Assert.IsTrue(transformedListenerMock.Received); } [Test] public void TransformInactiveGameObject() { UnityEventListenerMock transformedListenerMock = new UnityEventListenerMock(); subject.Transformed.AddListener(transformedListenerMock.Listen); subject.SetMultiplier(2f); subject.gameObject.SetActive(false); Assert.AreEqual(0f, subject.Result); Assert.IsFalse(transformedListenerMock.Received); float result = subject.Transform(2f); Assert.AreEqual(0f, result); Assert.AreEqual(0f, subject.Result); Assert.IsFalse(transformedListenerMock.Received); } [Test] public void TransformInactiveComponent() { UnityEventListenerMock transformedListenerMock = new UnityEventListenerMock(); subject.Transformed.AddListener(transformedListenerMock.Listen); subject.SetMultiplier(2f); subject.gameObject.SetActive(false); Assert.AreEqual(0f, subject.Result); Assert.IsFalse(transformedListenerMock.Received); float result = subject.Transform(2f); Assert.AreEqual(0f, result); Assert.AreEqual(0f, subject.Result); Assert.IsFalse(transformedListenerMock.Received); } } }
32.901235
91
0.612008
[ "MIT" ]
rgarat/VRTK.Unity.Core
Tests/Editor/Data/Type/Transformation/FloatMultiplierTest.cs
2,667
C#
#region references using System.Collections.Generic; using Newtonsoft.Json; using Dynamo.Graph.Nodes; using Camber.Civil.Styles.Labels; using Camber.Civil.Styles.Labels.MatchLine; #endregion namespace Camber.UI { [NodeName("Match Line Left Label Styles")] [NodeCategory("Camber.Civil 3D.Styles.Label Styles.Match Line")] [NodeDescription("Select Match Line Left Label Style.")] [IsDesignScriptCompatible] public class MatchLineLeftLabelStylesDropDown : LabelStyleDropDownBase { private const string OutputName = "matchLineLeftLabelStyle"; private static string LabelStyleCollection = LabelStyleCollections.MatchLineLabelStyles.ToString() + "." + MatchLineLabelStyles.LeftLabelStyles.ToString(); private static string LabelStyleType = typeof(MatchLineLeftLabelStyle).ToString(); public MatchLineLeftLabelStylesDropDown() : base(OutputName, LabelStyleCollection, LabelStyleType) { } [JsonConstructor] public MatchLineLeftLabelStylesDropDown(IEnumerable<PortModel> inPorts, IEnumerable<PortModel> outPorts) : base(OutputName, LabelStyleCollection, LabelStyleType, inPorts, outPorts) { } } [NodeName("Match Line Right Label Styles")] [NodeCategory("Camber.Civil 3D.Styles.Label Styles.Match Line")] [NodeDescription("Select Match Line Right Label Style.")] [IsDesignScriptCompatible] public class MatchLineRightLabelStylesDropDown : LabelStyleDropDownBase { private const string OutputName = "matchLineRightLabelStyle"; private static string LabelStyleCollection = LabelStyleCollections.MatchLineLabelStyles.ToString() + "." + MatchLineLabelStyles.RightLabelStyles.ToString(); private static string LabelStyleType = typeof(MatchLineRightLabelStyle).ToString(); public MatchLineRightLabelStylesDropDown() : base(OutputName, LabelStyleCollection, LabelStyleType) { } [JsonConstructor] public MatchLineRightLabelStylesDropDown(IEnumerable<PortModel> inPorts, IEnumerable<PortModel> outPorts) : base(OutputName, LabelStyleCollection, LabelStyleType, inPorts, outPorts) { } } }
47.822222
164
0.759294
[ "BSD-3-Clause" ]
mzjensen/Camber
CamberUI/Civil/Styles/Label Styles/MatchLineLabelStyleDropDowns.cs
2,154
C#
/* Copyright (c) 2016 Acrolinx GmbH */ using System; namespace Acrolinx.Sdk.Sidebar.Documents { public interface IRange { int End { get; } int Length { get; } int Start { get; } } }
16.923077
40
0.572727
[ "MIT", "Apache-2.0", "BSD-3-Clause" ]
acrolinx/sidebar-sdk-dotnet
Acrolinx.Sidebar/Documents/IRange.cs
222
C#
using Dapper.Contrib.Extensions; using FluentAssertions; using SFA.DAS.EmployerIncentives.Data.ApprenticeshipIncentives.Models; using SFA.DAS.EmployerIncentives.Functions.PaymentsProcess.Orchestrators; using SFA.DAS.EmployerIncentives.Functions.TestHelpers; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Net; using System.Threading.Tasks; using TechTalk.SpecFlow; using WireMock.RequestBuilders; using WireMock.ResponseBuilders; namespace SFA.DAS.EmployerIncentives.Functions.PaymentsProcess.AcceptanceTests.Steps { [Binding] [Scope(Feature = "SendPayments")] public partial class SendPaymentsSteps { private readonly TestContext _testContext; private ValidatePaymentsSteps.ValidatePaymentData _validatePaymentData; private string _orchestratorInstanceId; private const short CollectionPeriodYear = 2021; private const byte CollectionPeriod = 6; public SendPaymentsSteps(TestContext testContext) { _testContext = testContext; } [Given(@"payments exist for a legal entity")] public async Task GivenPaymentsExistForALegalEntity() { _validatePaymentData = new ValidatePaymentsSteps.ValidatePaymentData(_testContext); await _validatePaymentData.Create(); await RunPaymentsProcess(); } [Given(@"clawbacks exist for a legal entity")] public async Task GivenClawbacksExistForALegalEntity() { _validatePaymentData = new ValidatePaymentsSteps.ValidatePaymentData(_testContext); _validatePaymentData.AddClawbackPayment(false); await _validatePaymentData.Create(); await RunPaymentsProcess(); } [When(@"the payments have been approved")] public async Task WhenPaymentsAreApproved() { _testContext.PaymentsApi.MockServer .Given( Request .Create() .WithPath($"/payments/requests") .WithHeader("Content-Type", "application/payments-data") .WithParam("api-version", "2020-10-01") .UsingPost() ) .RespondWith(Response.Create() .WithStatusCode(HttpStatusCode.Accepted) .WithHeader("Content-Type", "application/json")); await ApprovePayments(); } [When(@"the payments have been rejected")] public async Task WhenPaymentsAreRejected() { await RejectPayments(); } [Then(@"the payments are sent to Business Central")] public async Task ThenThePaymentsAreSent() { var paymentRequestCount = _testContext.PaymentsApi.MockServer.LogEntries.Count(l => l.RequestMessage.AbsolutePath == "/payments/requests"); paymentRequestCount.Should().Be(2); await using var connection = new SqlConnection(_testContext.SqlDatabase.DatabaseInfo.ConnectionString); var payments = await connection.GetAllAsync<Payment>(); var results = payments .Where(x => x.ApprenticeshipIncentiveId == _validatePaymentData.ApprenticeshipIncentiveModel.Id && x.PaymentPeriod <= CollectionPeriod).ToList(); results.Count.Should().Be(2); results.Any(x => !x.PaidDate.HasValue).Should().BeFalse(); } [Then(@"the clawbacks are sent to Business Central")] public async Task ThenTheClawbacksAreSent() { var paymentRequestCount = _testContext.PaymentsApi.MockServer.LogEntries.Count(l => l.RequestMessage.AbsolutePath == "/payments/requests"); paymentRequestCount.Should().Be(3); await using var connection = new SqlConnection(_testContext.SqlDatabase.DatabaseInfo.ConnectionString); var clawbacks = await connection.GetAllAsync<ClawbackPayment>(); var results = clawbacks .Where(x => x.ApprenticeshipIncentiveId == _validatePaymentData.ApprenticeshipIncentiveModel.Id && x.CollectionPeriod <= CollectionPeriod).ToList(); results.Count.Should().Be(1); results.Any(x => !x.DateClawbackSent.HasValue).Should().BeFalse(); } [Then(@"the payments are not sent to Business Central")] public async Task ThenThePaymentsAreNotSent() { var paymentRequestCount = _testContext.PaymentsApi.MockServer.LogEntries.Count(); paymentRequestCount.Should().Be(0); await using var connection = new SqlConnection(_testContext.SqlDatabase.DatabaseInfo.ConnectionString); var payments = await connection.GetAllAsync<Payment>(); var results = payments .Where(x => x.ApprenticeshipIncentiveId == _validatePaymentData.ApprenticeshipIncentiveModel.Id && x.PaymentPeriod <= CollectionPeriod).ToList(); results.Count.Should().Be(2); results.Any(x => x.PaidDate.HasValue).Should().BeFalse(); } [Then(@"the clawbacks are not sent to Business Central")] public async Task ThenTheClawbacksAreNotSent() { var paymentRequestCount = _testContext.PaymentsApi.MockServer.LogEntries.Count(); paymentRequestCount.Should().Be(0); await using var connection = new SqlConnection(_testContext.SqlDatabase.DatabaseInfo.ConnectionString); var clawbacks = await connection.GetAllAsync<ClawbackPayment>(); var results = clawbacks .Where(x => x.ApprenticeshipIncentiveId == _validatePaymentData.ApprenticeshipIncentiveModel.Id && x.CollectionPeriod <= CollectionPeriod).ToList(); results.Count.Should().Be(1); results.Any(x => x.DateClawbackSent.HasValue).Should().BeFalse(); } private async Task RunPaymentsProcess() { await _testContext.SetActiveCollectionCalendarPeriod(new CollectionPeriod() { Period = CollectionPeriod, Year = CollectionPeriodYear }); await _testContext.TestFunction.Start( new OrchestrationStarterInfo( "IncentivePaymentOrchestrator_HttpStart", nameof(IncentivePaymentOrchestrator), new Dictionary<string, object> { ["req"] = new DummyHttpRequest { Path = $"/api/orchestrators/IncentivePaymentOrchestrator" } }, expectedCustomStatus: "WaitingForPaymentApproval" )); _testContext.TestFunction.LastResponse.StatusCode.Should().Be(HttpStatusCode.Accepted); var orchestratorStartResponse = await _testContext.TestFunction.GetOrchestratorStartResponse(); _orchestratorInstanceId = orchestratorStartResponse.Id; } private async Task ApprovePayments() { await _testContext.TestFunction.Start( new OrchestrationStarterInfo( "PaymentApproval_HttpStart", nameof(IncentivePaymentOrchestrator), new Dictionary<string, object> { ["req"] = new DummyHttpRequest { Path = $"/api/orchestrators/approvePayments/{_orchestratorInstanceId}" }, ["instanceId"] = _orchestratorInstanceId } )); _testContext.TestFunction.LastResponse.StatusCode.Should().Be(HttpStatusCode.OK); } private async Task RejectPayments() { await _testContext.TestFunction.Start( new OrchestrationStarterInfo( "PaymentRejection_HttpStart", nameof(IncentivePaymentOrchestrator), new Dictionary<string, object> { ["req"] = new DummyHttpRequest { Path = $"/api/orchestrators/rejectPayments/{_orchestratorInstanceId}" }, ["instanceId"] = _orchestratorInstanceId } )); _testContext.TestFunction.LastResponse.StatusCode.Should().Be(HttpStatusCode.OK); } } }
44.46114
164
0.61205
[ "MIT" ]
uk-gov-mirror/SkillsFundingAgency.das-employer-incentives
src/tests/SFA.DAS.EmployerIncentives.Functions.PaymentsProcess.AcceptanceTests/Steps/SendPaymentsSteps.cs
8,583
C#
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Task = System.Threading.Tasks.Task; using Timer = System.Timers.Timer; using Cosmos.Debug.Common; using Cosmos.Debug.DebugConnectors; using Cosmos.VS.Windows.ToolWindows; namespace Cosmos.VS.Windows { [Guid(Guids.PackageGuidString)] [PackageRegistration(UseManagedResourcesOnly = true, AllowsBackgroundLoading = true)] [ProvideMenuResource("Menus.ctmenu", 1)] [ProvideToolWindow(typeof(AssemblyToolWindow))] [ProvideToolWindow(typeof(RegistersToolWindow))] [ProvideToolWindow(typeof(StackTW))] [ProvideToolWindow(typeof(InternalTW))] [ProvideToolWindow(typeof(ConsoleTW))] public sealed class CosmosWindowsPackage: AsyncPackage { private readonly Queue<ushort> mCommand; private readonly Queue<byte[]> mMessage; private readonly Timer mTimer; private PipeServer mPipeDown; public StateStorer StateStorer { get; } private readonly Type[] mAllChannelWindowTypes = { typeof(ConsoleTW) }; public CosmosWindowsPackage() { StateStorer = new StateStorer(); mCommand = new Queue<ushort>(); mMessage = new Queue<byte[]>(); // There are a lot of threading issues in VSIP, and the WPF dispatchers do not work. // So instead we use a stack and a timer to poll it for data. mTimer = new Timer(100); mTimer.AutoReset = true; mTimer.Elapsed += (sender, e) => JoinableTaskFactory.RunAsync(() => ProcessMessageAsync(sender, e)); mTimer.Start(); mPipeDown = new PipeServer(Pipes.DownName); mPipeDown.DataPacketReceived += PipeThread_DataPacketReceived; mPipeDown.Start(); } protected override async Task InitializeAsync( CancellationToken cancellationToken, IProgress<ServiceProgressData> progress) { await base.InitializeAsync(cancellationToken, progress); await JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken); var xOutputWindow = (IVsOutputWindow)await GetServiceAsync(typeof(SVsOutputWindow)); var xCosmosPaneGuid = Guid.NewGuid(); ErrorHandler.ThrowOnFailure( xOutputWindow.CreatePane(ref xCosmosPaneGuid, "Cosmos", Convert.ToInt32(true), Convert.ToInt32(true))); ErrorHandler.ThrowOnFailure(xOutputWindow.GetPane(ref xCosmosPaneGuid, out var xOutputPane)); Global.OutputPane = xOutputPane; xOutputPane.OutputString($"Debugger windows loaded.{Environment.NewLine}"); CosmosMenuCmdSet.Initialize(this); } protected override void Dispose(bool disposing) { if (disposing) { mTimer?.Dispose(); } base.Dispose(disposing); } private async Task ProcessMessageAsync(object sender, EventArgs e) { ushort xCmd; byte[] xMsg; while (true) { lock (mCommand) { if (mCommand.Count == 0) { break; } xCmd = mCommand.Dequeue(); xMsg = mMessage.Dequeue(); } if (xCmd <= 127) { // debug channel switch (xCmd) { case Debugger2Windows.Noop: break; case Debugger2Windows.Stack: await UpdateWindowAsync(typeof(StackTW), "STACK", xMsg); break; case Debugger2Windows.Frame: await UpdateWindowAsync(typeof(StackTW), "FRAME", xMsg); break; case Debugger2Windows.Registers: await UpdateWindowAsync(typeof(RegistersToolWindow), null, xMsg); break; case Debugger2Windows.Quit: break; case Debugger2Windows.AssemblySource: await UpdateWindowAsync(typeof(AssemblyToolWindow), null, xMsg); break; case Debugger2Windows.PongVSIP: await UpdateWindowAsync(typeof(InternalTW), null, Encoding.UTF8.GetBytes("Pong from VSIP")); break; case Debugger2Windows.PongDebugStub: await UpdateWindowAsync(typeof(InternalTW), null, Encoding.UTF8.GetBytes("Pong from DebugStub")); break; case Debugger2Windows.OutputPane: await JoinableTaskFactory.SwitchToMainThreadAsync(); Global.OutputPane.OutputString(Encoding.UTF8.GetString(xMsg)); break; case Debugger2Windows.OutputClear: await JoinableTaskFactory.SwitchToMainThreadAsync(); Global.OutputPane.Clear(); StateStorer.ClearState(); break; } } else { await UpdateChannelWindowsAsync(xCmd, xMsg); } } } void PipeThread_DataPacketReceived(ushort aCmd, byte[] aMsg) { lock (mCommand) { mCommand.Enqueue(aCmd); mMessage.Enqueue(aMsg); } } public ToolWindowPane2 FindWindow(Type aWindowType) { // Get the instance number 0 of this tool window. // Our windows are single instance so this instance will be the only one. // The last flag is set to true so that if the tool window does not exists it will be created. var xWindow = FindToolWindow(aWindowType, 0, true); if (xWindow?.Frame == null) { throw new NotSupportedException("Failed to create the Cosmos tool window."); } return xWindow as ToolWindowPane2; } public async Task<ToolWindowPane2> FindWindowAsync(Type aWindowType) { // Get the instance number 0 of this tool window. // Our windows are single instance so this instance will be the only one. // The last flag is set to true so that if the tool window does not exists it will be created. var xWindow = await FindToolWindowAsync(aWindowType, 0, true, default); if (xWindow?.Frame == null) { throw new NotSupportedException("Failed to create the Cosmos tool window."); } return xWindow as ToolWindowPane2; } public ToolWindowPaneChannel FindChannelWindow(Type aWindowType) { // Get the instance number 0 of this tool window. // Our windows are single instance so this instance will be the only one. // The last flag is set to true so that if the tool window does not exists it will be created. var xWindow = FindToolWindow(aWindowType, 0, true); if (xWindow?.Frame == null) { throw new NotSupportedException("Failed to create the Cosmos tool window."); } return xWindow as ToolWindowPaneChannel; } public async Task<ToolWindowPaneChannel> FindChannelWindowAsync(Type aWindowType) { // Get the instance number 0 of this tool window. // Our windows are single instance so this instance will be the only one. // The last flag is set to true so that if the tool window does not exists it will be created. var xWindow = await FindToolWindowAsync(aWindowType, 0, true, default); if (xWindow?.Frame == null) { throw new NotSupportedException("Failed to create the Cosmos tool window."); } return xWindow as ToolWindowPaneChannel; } public async Task UpdateChannelWindowsAsync(ushort aChannelAndCommand, byte[] aData) { await JoinableTaskFactory.SwitchToMainThreadAsync(); foreach (var xType in mAllChannelWindowTypes) { var xWindow = await FindChannelWindowAsync(xType); xWindow.UserControl.Package = this; xWindow.UserControl.HandleChannelMessage(aChannelAndCommand, aData); } } private async Task UpdateWindowAsync(Type aWindowType, string aTag, byte[] aData) { await JoinableTaskFactory.SwitchToMainThreadAsync(); var xWindow = await FindWindowAsync(aWindowType); xWindow.UserControl.Package = this; xWindow.UserControl.Update(aTag, aData); } public void StoreAllStates() { var cWindow = FindWindow(typeof(StackTW)); byte[] aData = cWindow.UserControl.GetCurrentState(); StateStorer.StoreState("StackTW", aData == null ? null : (byte[])aData.Clone()); cWindow = FindWindow(typeof(RegistersToolWindow)); aData = cWindow.UserControl.GetCurrentState(); StateStorer.StoreState("RegistersTW", aData == null ? null : (byte[])aData.Clone()); } public void RestoreAllStates() { var cWindow = FindWindow(typeof(StackTW)); byte[] aData = StateStorer.RetrieveState(StateStorer.CurrLineId, "StackTW"); cWindow.UserControl.SetCurrentState(aData == null ? null : (byte[])aData.Clone()); cWindow = FindWindow(typeof(RegistersToolWindow)); aData = StateStorer.RetrieveState(StateStorer.CurrLineId, "RegistersTW"); cWindow.UserControl.SetCurrentState(aData == null ? null : (byte[])aData.Clone()); } } }
39.293233
125
0.573287
[ "BSD-3-Clause" ]
AcaiBerii/Cosmos
source/Cosmos.VS.Windows/CosmosWindowsPackage.cs
10,454
C#
using System.Collections.Generic; namespace AutoFixture.AutoFakeItEasy { internal class MethodCallResult { private IList<PositionedValue> outAndRefValues; private readonly object returnValue; public MethodCallResult(object returnValue) { this.returnValue = returnValue; } public void ApplyToCall(FakeObjectCall fakeObjectCall) { fakeObjectCall.SetReturnValue(this.returnValue); if (this.outAndRefValues == null) return; foreach (var positionedValue in this.outAndRefValues) { fakeObjectCall.SetArgumentValue(positionedValue.Position, positionedValue.Value); } } public void AddOutOrRefValue(int i, object value) { if (this.outAndRefValues == null) { this.outAndRefValues = new List<PositionedValue>(); } this.outAndRefValues.Add(new PositionedValue(i, value)); } private class PositionedValue { public int Position { get; } public object Value { get; } public PositionedValue(int position, object value) { this.Position = position; this.Value = value; } } } }
27.285714
97
0.575916
[ "MIT" ]
AutoFixture/AutoFixture
Src/AutoFakeItEasy/MethodCallResult.cs
1,339
C#
using CCXT.NET.Shared.Coin; using CCXT.NET.Shared.Converter; using System; using System.Collections.Generic; using Xunit; namespace XUnit { public partial class PrivateApi { [Fact] public async void Korbit() { var _api_key = TestConfig.GetConnectionKey("Korbit"); var _args = new Dictionary<string, object>(); var _timeframe = "1d"; var _since = 0; //1514764800000; var _limit = 100; if (String.IsNullOrEmpty(_api_key.secret_key) == false || XApiClient.TestXUnitMode == XUnitMode.UseJsonFile) { var _private_api = new CCXT.NET.Korbit.Private.PrivateApi(_api_key.connect_key, _api_key.secret_key, _api_key.user_name, _api_key.password); #if DEBUG if (XApiClient.TestXUnitMode != XUnitMode.UseExchangeServer) await _private_api.publicApi.LoadMarketsAsync(false, GetJsonContent(_private_api.privateClient, tRootFolder.Replace(@"\private", @"\public"), "fetchMarkets", _args)); #endif var _new_address = await _private_api.CreateAddressAsync("XRP", GetJsonContent(_private_api.privateClient, "createAddress", _args)); if ((_new_address.supported == true || TestConfig.SupportedCheck == true) && _new_address.message.IndexOf("assign address not allowed") < 0) { this.WriteJson(_private_api.privateClient, _new_address); Assert.NotNull(_new_address); Assert.True(_new_address.success, $"create an address return error: {_new_address.message}"); Assert.True(_new_address.message == "success"); Assert.False(String.IsNullOrEmpty(_new_address.result.currency)); Assert.False(String.IsNullOrEmpty(_new_address.result.address)); } var _address = await _private_api.FetchAddressAsync("XRP", GetJsonContent(_private_api.privateClient, "fetchAddress", _args)); if (_address.supported == true || TestConfig.SupportedCheck == true) { this.WriteJson(_private_api.privateClient, _address); Assert.NotNull(_address); Assert.True(_address.success, $"fetch an address return error: {_address.message}"); Assert.True(_address.message == "success"); Assert.False(String.IsNullOrEmpty(_address.result.currency)); Assert.False(String.IsNullOrEmpty(_address.result.address)); } var _addresses = await _private_api.FetchAddressesAsync(GetJsonContent(_private_api.privateClient, "fetchAddresses", _args)); if (_addresses.supported == true || TestConfig.SupportedCheck == true) { this.WriteJson(_private_api.privateClient, _addresses); Assert.NotNull(_addresses); Assert.True(_addresses.success, $"fetch addresses return error: {_addresses.message}"); Assert.True(_addresses.message == "success"); Assert.True(_addresses.result.Count >= 0); foreach (var _d in _addresses.result) { Assert.False(String.IsNullOrEmpty(_d.currency)); Assert.False(String.IsNullOrEmpty(_d.address)); } } #if DEBUG if (XApiClient.TestXUnitMode != XUnitMode.UseExchangeServer) { var _withdraw = await _private_api.CoinWithdrawAsync("XRP", "rN9qNpgnBaZwqCg8CvUZRPqCcPPY7wfWep", "3162679978", 10.0m, GetJsonContent(_private_api.privateClient, "coinWithdraw", _args)); if ((_withdraw.supported == true || TestConfig.SupportedCheck == true) && _withdraw.statusCode != 400) { this.WriteJson(_private_api.privateClient, _withdraw); Assert.NotNull(_withdraw); Assert.True(_withdraw.success, $"withdraw return error: {_withdraw.message}"); Assert.True(_withdraw.message == "success"); Assert.False(String.IsNullOrEmpty(_withdraw.result.transferId)); } if (String.IsNullOrEmpty(_withdraw.result.transferId) == true) _withdraw.result.transferId = _private_api.privateClient.GenerateNonceString(13); var _cancel_withdraw = await _private_api.CancelCoinWithdrawAsync("XRP", _withdraw.result.transferId, GetJsonContent(_private_api.privateClient, "cancelCoinWithdraw", _args)); if ((_cancel_withdraw.supported == true || TestConfig.SupportedCheck == true) && _cancel_withdraw.message.IndexOf("not_found") < 0) { this.WriteJson(_private_api.privateClient, _cancel_withdraw); Assert.NotNull(_cancel_withdraw); Assert.True(_cancel_withdraw.success, $"cancel withdraw return error: {_cancel_withdraw.message}"); Assert.True(_cancel_withdraw.message == "success"); Assert.False(String.IsNullOrEmpty(_cancel_withdraw.result.transferId)); } } #endif var _fetch_transfers = await _private_api.FetchTransfersAsync("XRP", _timeframe, _since, _limit, GetJsonContent(_private_api.privateClient, "fetchTransfers", _args)); if (_fetch_transfers.supported == true || TestConfig.SupportedCheck == true) { this.WriteJson(_private_api.privateClient, _fetch_transfers); Assert.NotNull(_fetch_transfers); Assert.True(_fetch_transfers.success, $"fetch transfers return error: {_fetch_transfers.message}"); Assert.True(_fetch_transfers.message == "success"); foreach (var _d in _fetch_transfers.result) { Assert.False(String.IsNullOrEmpty(_d.transferId)); Assert.False(String.IsNullOrEmpty(_d.transactionId)); Assert.False(String.IsNullOrEmpty(_d.fromAddress) && String.IsNullOrEmpty(_d.toAddress)); Assert.True(_d.timestamp >= 1000000000000 && _d.timestamp <= 9999999999999); } } var _transfer_id = ""; if (_fetch_transfers.result.Count > 0) _transfer_id = _fetch_transfers.result[0].transferId; else _transfer_id = Guid.NewGuid().ToString(); var _fetch_transfer = await _private_api.FetchTransferAsync("XRP", _transfer_id, GetJsonContent(_private_api.privateClient, "fetchTransfer", _args)); if (_fetch_transfer.supported == true || TestConfig.SupportedCheck == true) { this.WriteJson(_private_api.privateClient, _fetch_transfer); Assert.NotNull(_fetch_transfer); Assert.True(_fetch_transfer.success, $"fetch transfer return error: {_fetch_transfer.message}"); Assert.True(_fetch_transfer.message == "success"); Assert.False(String.IsNullOrEmpty(_fetch_transfer.result.transferId)); Assert.False(String.IsNullOrEmpty(_fetch_transfer.result.transactionId)); Assert.False(String.IsNullOrEmpty(_fetch_transfer.result.fromAddress) && String.IsNullOrEmpty(_fetch_transfer.result.toAddress)); Assert.True(_fetch_transfer.result.timestamp >= 1000000000000 && _fetch_transfer.result.timestamp <= 9999999999999); } var _fetch_all_transfers = await _private_api.FetchAllTransfersAsync(_timeframe, _since, _limit, GetJsonContent(_private_api.privateClient, "fetchAllTransfers", _args)); if (_fetch_all_transfers.supported == true || TestConfig.SupportedCheck == true) { this.WriteJson(_private_api.privateClient, _fetch_all_transfers); Assert.NotNull(_fetch_all_transfers); Assert.True(_fetch_all_transfers.success, $"fetch all transfers return error: {_fetch_all_transfers.message}"); Assert.True(_fetch_all_transfers.message == "success"); foreach (var _d in _fetch_all_transfers.result) { Assert.False(String.IsNullOrEmpty(_d.transferId)); Assert.False(String.IsNullOrEmpty(_d.transactionId)); Assert.False(String.IsNullOrEmpty(_d.fromAddress) && String.IsNullOrEmpty(_d.toAddress)); Assert.True(_d.timestamp >= 1000000000000 && _d.timestamp <= 9999999999999); } } var _balance = await _private_api.FetchBalanceAsync("XRP", "", GetJsonContent(_private_api.privateClient, "fetchBalance", _args)); if (_balance.supported == true || TestConfig.SupportedCheck == true) { this.WriteJson(_private_api.privateClient, _balance); Assert.NotNull(_balance); Assert.True(_balance.success, $"fetch balances return error: {_balance.message}"); Assert.True(_balance.message == "success"); Assert.True(_balance.result.currency == "XRP"); Assert.True(Numerical.CompareDecimal(_balance.result.total, _balance.result.free + _balance.result.used)); } var _balances = await _private_api.FetchBalancesAsync(GetJsonContent(_private_api.privateClient, "fetchBalances", _args)); if (_balances.supported == true || TestConfig.SupportedCheck == true) { this.WriteJson(_private_api.privateClient, _balances); Assert.NotNull(_balances); Assert.True(_balances.success, $"fetch all balances return error: {_balances.message}"); Assert.True(_balances.message == "success"); Assert.True(_balances.result.Count >= 0); foreach (var _b in _balances.result) { Assert.True(Numerical.CompareDecimal(_b.total, _b.free + _b.used)); } } var _wallet = await _private_api.FetchWalletAsync("XRP", "USD", GetJsonContent(_private_api.privateClient, "fetchWallet", _args)); if (_wallet.supported == true || TestConfig.SupportedCheck == true) { this.WriteJson(_private_api.privateClient, _wallet); Assert.NotNull(_wallet); Assert.True(_wallet.success, $"fetch wallet return error: {_wallet.message}"); Assert.True(_wallet.message == "success"); Assert.False(String.IsNullOrEmpty(_wallet.result.balance.currency)); Assert.True(Numerical.CompareDecimal(_wallet.result.balance.total, _wallet.result.balance.free + _wallet.result.balance.used)); } var _wallets = await _private_api.FetchWalletsAsync(_api_key.user_id, GetJsonContent(_private_api.privateClient, "fetchWallets", _args)); if (_wallets.supported == true || TestConfig.SupportedCheck == true) { this.WriteJson(_private_api.privateClient, _wallets); Assert.NotNull(_wallets); Assert.True(_wallets.success, $"fetch wallets return error: {_wallets.message}"); Assert.True(_wallets.message == "success"); foreach (var _b in _balances.result) { Assert.True(Numerical.CompareDecimal(_b.total, _b.free + _b.used)); } } } } } }
56.511628
206
0.592181
[ "MIT" ]
ccxt-net/ccxt.net
tests/ccxt.test/private/korbit.cs
12,150
C#
// // Serializer for byps.test.api.remote.BRequest_RemoteArrayTypes1dim_getDate // // THIS FILE HAS BEEN GENERATED. DO NOT MODIFY. // using System; using System.Collections.Generic; using byps; namespace byps.test.api.remote { public class BSerializer_2033462920 : BSerializer { public readonly static BSerializer instance = new BSerializer_2033462920(); public BSerializer_2033462920() : base(2033462920) {} public BSerializer_2033462920(int typeId) : base(typeId) {} public override Object read(Object obj1, BInput bin1, long version) { BInputBin bin = (BInputBin)bin1; BRequest_RemoteArrayTypes1dim_getDate obj = (BRequest_RemoteArrayTypes1dim_getDate)(obj1 != null ? obj1 : bin.onObjectCreated(new BRequest_RemoteArrayTypes1dim_getDate())); BBufferBin bbuf = bin.bbuf; return obj; } } } // namespace
23.459459
175
0.737327
[ "MIT" ]
markusessigde/byps
csharp/bypstest-ser/src-ser/byps/test/api/remote/BSerializer_2033462920.cs
870
C#
/* * Description: 单例模板类 * Author: tanghuan * Create Date: 2018/09/02 */ using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace XbufferExcelToData { /// <summary> /// 模板单例 /// </summary> /// <typeparam name="T"></typeparam> public class SingletonTemplate<T> where T : class, new() { public static T Singleton { get { if (mSingleton == null) { mSingleton = new T(); } return mSingleton; } } protected static T mSingleton = null; protected SingletonTemplate() { } } }
19.025
60
0.467806
[ "Apache-2.0" ]
fqkw6/ILRuntimeMyFrame
ILRunTimeTool/XbufferExcelToData/XbufferExcelToData/Core/Singleton/SingletonTemplate.cs
781
C#
using System; using System.Collections.Generic; using System.Linq; using AElf.Kernel; using AElf.Kernel.SmartContract; using AElf.Kernel.SmartContract.Application; using AElf.Kernel.SmartContract.Sdk; using Xunit; using Shouldly; using AElf.Sdk.CSharp.Tests.TestContract; using AElf.Types; using Google.Protobuf.WellKnownTypes; namespace AElf.Sdk.CSharp.Tests { public sealed class ContractTest : SdkCSharpTestBase { private List<Address> AddressList { get; } = SampleAddress.AddressList.ToList(); private TokenContract Contract { get; } = new TokenContract(); private IStateProvider StateProvider { get; } private IHostSmartContractBridgeContext BridgeContext { get; } public ContractTest() { StateProvider = GetRequiredService<IStateProviderFactory>().CreateStateProvider(); BridgeContext = GetRequiredService<IHostSmartContractBridgeContextService>().Create(); Contract.InternalInitialize(BridgeContext); //Contract.SetStateProvider(StateProvider); var transactionContext = new TransactionContext() { Transaction = new Transaction() { From = AddressList[1], To = AddressList[0] } }; BridgeContext.TransactionContext = transactionContext; //StateProvider.TransactionContext = transactionContext; } private void Init_Test() { Contract.Initialize("ELF", "elf test token", 1000000, 9); Contract.Symbol().ShouldBe("ELF"); Contract.TokenName().ShouldBe("elf test token"); Contract.TotalSupply().ShouldBe(1000000UL); Contract.Decimals().ShouldBe(9U); var balance = Contract.BalanceOf(AddressList[1]); balance.ShouldBe(1000000UL); } [Fact] public void Init_Again_Test() { Init_Test(); Should.Throw<AssertionException>(() => { Contract.Initialize("ELF", "elf test token again", 1000000, 0); }); } [Fact] public void Transfer_With_Enough_Token() { Init_Test(); Contract.Transfer(AddressList[2], 100UL); var balance = Contract.BalanceOf(AddressList[2]); balance.ShouldBe(100UL); } [Fact] public void Transfer_Without_Enough_Token() { Init_Test(); Contract.Transfer(AddressList[2], 100UL); SwitchOwner(AddressList[2]); Should.Throw<AssertionException>(() => { Contract.Transfer(AddressList[3], 200UL); }); } [Fact] public void Transfer_To_Null_User_Test() { Init_Test(); Should.Throw<Exception>(() => { Contract.Transfer(null, 100UL); }); } [Fact] public void Approve_Test() { Init_Test(); Contract.Approve(AddressList[2], 1000UL); var allowance = Contract.Allowance(AddressList[1], AddressList[2]); allowance.ShouldBe(1000UL); } [Fact] public void UnApprove_Test() { Init_Test(); Contract.Approve(AddressList[2], 1000UL); Contract.UnApprove(AddressList[2], 500UL); var allowance = Contract.Allowance(AddressList[1], AddressList[2]); allowance.ShouldBe(500UL); } [Fact] public void UnApprove_Available_Token_Test() { Init_Test(); Contract.Approve(AddressList[2], 500UL); Contract.UnApprove(AddressList[2], 1000UL); var allowance = Contract.Allowance(AddressList[1], AddressList[2]); allowance.ShouldBe(0UL); } [Fact] public void TransferFrom_Available_Token_Test() { Init_Test(); Contract.Approve(AddressList[2], 500UL); SwitchOwner(AddressList[2]); Contract.TransferFrom(AddressList[1], AddressList[2], 500UL); var balance1 = Contract.BalanceOf(AddressList[1]); var balance2 = Contract.BalanceOf(AddressList[2]); balance1.ShouldBe(Contract.TotalSupply() - 500UL); balance2.ShouldBe(500UL); } [Fact] public void TransferFrom_Over_Token_Test() { Init_Test(); Contract.Approve(AddressList[2], 500UL); SwitchOwner(AddressList[2]); Should.Throw<AssertionException>(() => { Contract.TransferFrom(AddressList[1], AddressList[2], 1000UL); }); } [Fact] public void TransferFrom_MultipleTimes_Available_Token_Test() { Init_Test(); Contract.Approve(AddressList[2], 1000UL); SwitchOwner(AddressList[2]); Contract.TransferFrom(AddressList[1], AddressList[2], 300UL); Contract.TransferFrom(AddressList[1], AddressList[2], 500UL); var balance2 = Contract.BalanceOf(AddressList[2]); balance2.ShouldBe(800UL); } [Fact] public void Burn_Test() { Init_Test(); Contract.Burn(1000UL); var balance = Contract.BalanceOf(AddressList[1]); Contract.TotalSupply().ShouldBe(999000UL); balance.ShouldBe(999000UL); //over token Should.Throw<AssertionException>(() => { Contract.Burn(100000000UL); }); } [Fact] public void SetMethodFee_Test() { Init_Test(); var fee = Contract.GetMethodFee("Transfer"); fee.ShouldBe(0UL); Contract.SetMethodFee("Transfer", 10UL); var fee1 = Contract.GetMethodFee("Transfer"); fee1.ShouldBe(10UL); Contract.SetMethodFee("Transfer", 20UL); var fee2 = Contract.GetMethodFee("Transfer"); fee2.ShouldBe(20UL); } [Fact] public void GetVirtualAddressHash_Test() { var hash = Contract.GetVirtualAddressHash(10); hash.ShouldNotBeNull(); var hash1 = Contract.GetVirtualAddressHash(10); hash1.ShouldBe(hash); var hash2 = Contract.GetVirtualAddressHash(100); hash2.ShouldNotBe(hash); } [Fact] public void GetVirtualAddress_Test() { var address = Contract.GetVirtualAddress(10); address.Value.ShouldNotBeNull(); var address1 = Contract.GetVirtualAddress(10); address1.ShouldBe(address); var address2 = Contract.GetVirtualAddress(100); address2.ShouldNotBe(address); } [Fact] public void CannotResetNativeTokenSymbol_Test() { const string newSymbol = "TEST"; Init_Test(); Contract.ResetNativeTokenSymbol(newSymbol); Contract.NativeTokenSymbol().ShouldNotBe(newSymbol); } private void SwitchOwner(Address address) { var transactionContext = new TransactionContext() { Transaction = new Transaction() { From = address, To = AddressList[0] } }; BridgeContext.TransactionContext = transactionContext; //StateProvider.TransactionContext = transactionContext; } } }
32.459574
120
0.56699
[ "MIT" ]
380086154/AElf
test/AElf.Sdk.CSharp.Tests/ContractTest.cs
7,628
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudfront-2019-03-26.normal.json service model. */ using System; using System.Net; using Amazon.Runtime; namespace Amazon.CloudFront.Model { ///<summary> /// CloudFront exception /// </summary> #if !PCL && !NETSTANDARD [Serializable] #endif public class TooManyCookieNamesInWhiteListException : AmazonCloudFrontException { /// <summary> /// Constructs a new TooManyCookieNamesInWhiteListException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public TooManyCookieNamesInWhiteListException(string message) : base(message) {} /// <summary> /// Construct instance of TooManyCookieNamesInWhiteListException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public TooManyCookieNamesInWhiteListException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of TooManyCookieNamesInWhiteListException /// </summary> /// <param name="innerException"></param> public TooManyCookieNamesInWhiteListException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of TooManyCookieNamesInWhiteListException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public TooManyCookieNamesInWhiteListException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of TooManyCookieNamesInWhiteListException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public TooManyCookieNamesInWhiteListException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !PCL && !NETSTANDARD /// <summary> /// Constructs a new instance of the TooManyCookieNamesInWhiteListException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected TooManyCookieNamesInWhiteListException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { } #endif } }
44.938144
180
0.664143
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/TooManyCookieNamesInWhiteListException.cs
4,359
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using Xunit; namespace System.Net.Http.WinHttpHandlerUnitTests { public class WinHttpResponseHeaderReaderTest { private static readonly KeyValuePair<string, string>[] s_emptyHeaders = Array.Empty< KeyValuePair<string, string> >(); [Fact] public void ReadHeader_WithStatusLine_CanSkipStatusLineAndReadHeader() { char[] array = "HTTP/1.0 200 OK\r\nServer: Apache".ToCharArray(); var reader = new WinHttpResponseHeaderReader(array, 0, array.Length); Assert.True(reader.ReadLine()); string name; string value; Assert.True(reader.ReadHeader(out name, out value)); Assert.Equal("Server", name); Assert.Equal("Apache", value); } [Fact] public void ReadHeader_KnownHeaderName_SameKnownHeaderNameObjectReturned() { char[] array = "Server: Apache".ToCharArray(); var reader = new WinHttpResponseHeaderReader(array, 0, array.Length); string name; string value; Assert.True(reader.ReadHeader(out name, out value)); Assert.Same(HttpKnownHeaderNames.Server, name); } [Theory] [InlineData("Content-Encoding: gzip")] [InlineData("Content-Encoding: deflate")] public void ReadHeader_KnownHeaderValue_SameHeaderValueObjectReturned(string header) { char[] array = (header + "\r\n" + header).ToCharArray(); var reader = new WinHttpResponseHeaderReader(array, 0, array.Length); string name1; string value1; Assert.True(reader.ReadHeader(out name1, out value1)); string name2; string value2; Assert.True(reader.ReadHeader(out name2, out value2)); Assert.Same(value1, value2); } [Theory] [MemberData(nameof(HeaderData))] public void ReadHeader_VariousInputs_MatchesExpectedBehavior( string raw, KeyValuePair<string, string>[] expectedHeaders ) { char[] array = raw.ToCharArray(); var reader = new WinHttpResponseHeaderReader(array, 0, array.Length); string name; string value; for (int i = 0; i < expectedHeaders.Length; i++) { string expectedName = expectedHeaders[i].Key; string expectedValue = expectedHeaders[i].Value; Assert.True(reader.ReadHeader(out name, out value)); Assert.Equal(expectedName, name); Assert.Equal(expectedValue, value); } Assert.False(reader.ReadHeader(out name, out value)); Assert.Null(name); Assert.Null(value); } public static object[][] HeaderData = { new object[] { "", s_emptyHeaders }, new object[] { " ", s_emptyHeaders }, new object[] { "\t", s_emptyHeaders }, new object[] { "\r\n", s_emptyHeaders }, new object[] { "\r\n\r\n", s_emptyHeaders }, new object[] { "\r\n\r\n\r\n", s_emptyHeaders }, new object[] { "Content-Length: 50", new[] { CreateHeader("Content-Length", "50") } }, new object[] { "X-Custom-Header: Foo", new[] { CreateHeader("X-Custom-Header", "Foo") } }, new object[] { "Content-Length: 50\r\n" + "Content-Encoding: gzip\r\n" + "X-Powered-By: .NET", new[] { CreateHeader("Content-Length", "50"), CreateHeader("Content-Encoding", "gzip"), CreateHeader("X-Powered-By", ".NET") } }, // No colon in a line, should be skipped new object[] { "Content-Length: 50\r\n" + "no colon, should be skipped\r\n" + "X-Powered-By: .NET", new[] { CreateHeader("Content-Length", "50"), CreateHeader("X-Powered-By", ".NET") } }, // Empty lines (middle line) should be skipped new object[] { "Content-Length: 50\r\n" + "\r\n" + "X-Powered-By: .NET", new[] { CreateHeader("Content-Length", "50"), CreateHeader("X-Powered-By", ".NET") } }, new object[] { "Content-Length: 50\r\n" + "" + "X-Powered-By: .NET", new[] { CreateHeader("Content-Length", "50"), CreateHeader("X-Powered-By", ".NET") } }, // Empty lines (last line) should be skipped new object[] { "Content-Length: 50\r\n" + "Content-Encoding: deflate\r\n" + "X-Powered-By: .NET\r\n", new[] { CreateHeader("Content-Length", "50"), CreateHeader("Content-Encoding", "deflate"), CreateHeader("X-Powered-By", ".NET") } }, // Values should be trimmed new object[] { "Content-Length: 50 \r\n" + "Content-Encoding: brotli \r\n" + "X-Powered-By: .NET ", new[] { CreateHeader("Content-Length", "50"), CreateHeader("Content-Encoding", "brotli"), CreateHeader("X-Powered-By", ".NET") } } }; private static KeyValuePair<string, string> CreateHeader(string name, string value) { return new KeyValuePair<string, string>(name, value); } } }
36.75
100
0.509209
[ "MIT" ]
belav/runtime
src/libraries/System.Net.Http.WinHttpHandler/tests/UnitTests/WinHttpResponseHeaderReaderTest.cs
6,027
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/wincodec.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("00000105-A8F2-4877-BA0A-FD2B6645FB94")] public unsafe partial struct IWICBitmapFrameEncode { public void** lpVtbl; [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject) { return ((delegate* stdcall<IWICBitmapFrameEncode*, Guid*, void**, int>)(lpVtbl[0]))((IWICBitmapFrameEncode*)Unsafe.AsPointer(ref this), riid, ppvObject); } [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* stdcall<IWICBitmapFrameEncode*, uint>)(lpVtbl[1]))((IWICBitmapFrameEncode*)Unsafe.AsPointer(ref this)); } [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* stdcall<IWICBitmapFrameEncode*, uint>)(lpVtbl[2]))((IWICBitmapFrameEncode*)Unsafe.AsPointer(ref this)); } [return: NativeTypeName("HRESULT")] public int Initialize([NativeTypeName("IPropertyBag2 *")] IPropertyBag2* pIEncoderOptions) { return ((delegate* stdcall<IWICBitmapFrameEncode*, IPropertyBag2*, int>)(lpVtbl[3]))((IWICBitmapFrameEncode*)Unsafe.AsPointer(ref this), pIEncoderOptions); } [return: NativeTypeName("HRESULT")] public int SetSize([NativeTypeName("UINT")] uint uiWidth, [NativeTypeName("UINT")] uint uiHeight) { return ((delegate* stdcall<IWICBitmapFrameEncode*, uint, uint, int>)(lpVtbl[4]))((IWICBitmapFrameEncode*)Unsafe.AsPointer(ref this), uiWidth, uiHeight); } [return: NativeTypeName("HRESULT")] public int SetResolution(double dpiX, double dpiY) { return ((delegate* stdcall<IWICBitmapFrameEncode*, double, double, int>)(lpVtbl[5]))((IWICBitmapFrameEncode*)Unsafe.AsPointer(ref this), dpiX, dpiY); } [return: NativeTypeName("HRESULT")] public int SetPixelFormat([NativeTypeName("WICPixelFormatGUID *")] Guid* pPixelFormat) { return ((delegate* stdcall<IWICBitmapFrameEncode*, Guid*, int>)(lpVtbl[6]))((IWICBitmapFrameEncode*)Unsafe.AsPointer(ref this), pPixelFormat); } [return: NativeTypeName("HRESULT")] public int SetColorContexts([NativeTypeName("UINT")] uint cCount, [NativeTypeName("IWICColorContext **")] IWICColorContext** ppIColorContext) { return ((delegate* stdcall<IWICBitmapFrameEncode*, uint, IWICColorContext**, int>)(lpVtbl[7]))((IWICBitmapFrameEncode*)Unsafe.AsPointer(ref this), cCount, ppIColorContext); } [return: NativeTypeName("HRESULT")] public int SetPalette([NativeTypeName("IWICPalette *")] IWICPalette* pIPalette) { return ((delegate* stdcall<IWICBitmapFrameEncode*, IWICPalette*, int>)(lpVtbl[8]))((IWICBitmapFrameEncode*)Unsafe.AsPointer(ref this), pIPalette); } [return: NativeTypeName("HRESULT")] public int SetThumbnail([NativeTypeName("IWICBitmapSource *")] IWICBitmapSource* pIThumbnail) { return ((delegate* stdcall<IWICBitmapFrameEncode*, IWICBitmapSource*, int>)(lpVtbl[9]))((IWICBitmapFrameEncode*)Unsafe.AsPointer(ref this), pIThumbnail); } [return: NativeTypeName("HRESULT")] public int WritePixels([NativeTypeName("UINT")] uint lineCount, [NativeTypeName("UINT")] uint cbStride, [NativeTypeName("UINT")] uint cbBufferSize, [NativeTypeName("BYTE *")] byte* pbPixels) { return ((delegate* stdcall<IWICBitmapFrameEncode*, uint, uint, uint, byte*, int>)(lpVtbl[10]))((IWICBitmapFrameEncode*)Unsafe.AsPointer(ref this), lineCount, cbStride, cbBufferSize, pbPixels); } [return: NativeTypeName("HRESULT")] public int WriteSource([NativeTypeName("IWICBitmapSource *")] IWICBitmapSource* pIBitmapSource, [NativeTypeName("WICRect *")] WICRect* prc) { return ((delegate* stdcall<IWICBitmapFrameEncode*, IWICBitmapSource*, WICRect*, int>)(lpVtbl[11]))((IWICBitmapFrameEncode*)Unsafe.AsPointer(ref this), pIBitmapSource, prc); } [return: NativeTypeName("HRESULT")] public int Commit() { return ((delegate* stdcall<IWICBitmapFrameEncode*, int>)(lpVtbl[12]))((IWICBitmapFrameEncode*)Unsafe.AsPointer(ref this)); } [return: NativeTypeName("HRESULT")] public int GetMetadataQueryWriter([NativeTypeName("IWICMetadataQueryWriter **")] IWICMetadataQueryWriter** ppIMetadataQueryWriter) { return ((delegate* stdcall<IWICBitmapFrameEncode*, IWICMetadataQueryWriter**, int>)(lpVtbl[13]))((IWICBitmapFrameEncode*)Unsafe.AsPointer(ref this), ppIMetadataQueryWriter); } } }
50.647059
204
0.674603
[ "MIT" ]
john-h-k/terrafx.interop.windows
sources/Interop/Windows/um/wincodec/IWICBitmapFrameEncode.cs
5,168
C#
// Copyright (c) Microsoft. All rights reserved. namespace NetworkController { using System; using System.Collections.Generic; using System.IO; using Microsoft.Azure.Devices.Client; using Microsoft.Azure.Devices.Edge.ModuleUtil; using Microsoft.Azure.Devices.Edge.ModuleUtil.NetworkController; using Microsoft.Azure.Devices.Edge.Util; using Microsoft.Extensions.Configuration; class Settings { internal static Settings Current = Create(); const string StartAfterPropertyName = "StartAfter"; const string DockerUriPropertyName = "DockerUri"; const string FrequencyPropertyName = "RunFrequencies"; const string NetworkIdPropertyName = "NetworkId"; const string TestResultCoordinatorEndpointPropertyName = "TestResultCoordinatorEndpoint"; const string TrackingIdPropertyName = "TrackingId"; const string ModuleIdPropertyName = "IOTEDGE_MODULEID"; const string IotHubHostnamePropertyName = "IOTEDGE_IOTHUBHOSTNAME"; const string ParentHostnamePropertyName = "IOTEDGE_PARENTHOSTNAME"; const string DefaultProfilesPropertyName = "DefaultProfiles"; const string TransportTypePropertyName = "TransportType"; Settings( TimeSpan startAfter, string dockerUri, string networkId, IList<Frequency> frequencies, NetworkProfile runProfileSettings, Uri testResultCoordinatorEndpoint, string trackingId, string moduleId, string iothubHostname, string parentHostname, TransportType transportType) { this.StartAfter = startAfter; this.Frequencies = frequencies; this.DockerUri = Preconditions.CheckNonWhiteSpace(dockerUri, nameof(dockerUri)); this.NetworkId = Preconditions.CheckNonWhiteSpace(networkId, nameof(networkId)); this.TestResultCoordinatorEndpoint = Preconditions.CheckNotNull(testResultCoordinatorEndpoint, nameof(testResultCoordinatorEndpoint)); this.NetworkRunProfile = Preconditions.CheckNotNull(runProfileSettings, nameof(runProfileSettings)); Preconditions.CheckRange<uint>(this.NetworkRunProfile.ProfileSetting.PackageLoss, 0, 101, nameof(this.NetworkRunProfile)); this.TrackingId = Preconditions.CheckNonWhiteSpace(trackingId, nameof(trackingId)); this.ModuleId = Preconditions.CheckNonWhiteSpace(moduleId, nameof(moduleId)); this.IotHubHostname = Preconditions.CheckNonWhiteSpace(iothubHostname, nameof(iothubHostname)); this.ParentHostname = Preconditions.CheckNotNull(parentHostname, nameof(parentHostname)); this.TransportType = transportType; } public TimeSpan StartAfter { get; } public IList<Frequency> Frequencies { get; } public string DockerUri { get; } public string NetworkId { get; } public Uri TestResultCoordinatorEndpoint { get; } public NetworkProfile NetworkRunProfile { get; } public string TrackingId { get; } public string ModuleId { get; } public string IotHubHostname { get; } public string ParentHostname { get; } public TransportType TransportType { get; } static Settings Create() { IConfiguration configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("config/settings.json") .AddEnvironmentVariables() .Build(); var frequencies = new List<Frequency>(); configuration.GetSection(FrequencyPropertyName).Bind(frequencies); string runProfileName = configuration.GetValue<string>(TestConstants.NetworkController.RunProfilePropertyName); NetworkProfile runProfileSettings = configuration.GetSection($"{DefaultProfilesPropertyName}:{runProfileName}").Get<NetworkProfile>(); if (runProfileSettings == null) { runProfileSettings = NetworkProfile.Online; } return new Settings( configuration.GetValue<TimeSpan>(StartAfterPropertyName), configuration.GetValue<string>(DockerUriPropertyName), configuration.GetValue<string>(NetworkIdPropertyName), frequencies, runProfileSettings, configuration.GetValue<Uri>(TestResultCoordinatorEndpointPropertyName), configuration.GetValue<string>(TrackingIdPropertyName), configuration.GetValue<string>(ModuleIdPropertyName), configuration.GetValue<string>(IotHubHostnamePropertyName), configuration.GetValue<string>(ParentHostnamePropertyName, string.Empty), configuration.GetValue(TransportTypePropertyName, TransportType.Amqp_Tcp_Only)); } } class Frequency { public TimeSpan OfflineFrequency { get; set; } public TimeSpan OnlineFrequency { get; set; } public int RunsCount { get; set; } } }
43.411765
146
0.678281
[ "MIT" ]
Azure/iotedge
test/connectivity/modules/NetworkController/Settings.cs
5,166
C#
namespace Solicitacao_de_Ambulancias { partial class Reagendar { /// <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() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Reagendar)); this.panel1 = new System.Windows.Forms.Panel(); this.Enviar = new System.Windows.Forms.Button(); this.dataAgendar = new System.Windows.Forms.DateTimePicker(); this.label1 = new System.Windows.Forms.Label(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // panel1 // this.panel1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(229)))), ((int)(((byte)(252)))), ((int)(((byte)(194))))); this.panel1.Controls.Add(this.Enviar); this.panel1.Controls.Add(this.dataAgendar); this.panel1.Controls.Add(this.label1); this.panel1.Location = new System.Drawing.Point(12, 12); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(260, 237); this.panel1.TabIndex = 0; // // Enviar // this.Enviar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.Enviar.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(214)))), ((int)(((byte)(95)))), ((int)(((byte)(95))))); this.Enviar.Font = new System.Drawing.Font("Arial", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Enviar.ForeColor = System.Drawing.Color.WhiteSmoke; this.Enviar.Location = new System.Drawing.Point(58, 188); this.Enviar.Name = "Enviar"; this.Enviar.Size = new System.Drawing.Size(144, 46); this.Enviar.TabIndex = 98; this.Enviar.Text = "Concluir"; this.Enviar.UseVisualStyleBackColor = false; this.Enviar.Click += new System.EventHandler(this.Enviar_Click); // // dataAgendar // this.dataAgendar.CustomFormat = "dd/MM/yyyy HH:mm"; this.dataAgendar.Format = System.Windows.Forms.DateTimePickerFormat.Custom; this.dataAgendar.Location = new System.Drawing.Point(3, 96); this.dataAgendar.Name = "dataAgendar"; this.dataAgendar.Size = new System.Drawing.Size(254, 20); this.dataAgendar.TabIndex = 1; // // label1 // this.label1.Anchor = System.Windows.Forms.AnchorStyles.Top; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ImageAlign = System.Drawing.ContentAlignment.TopCenter; this.label1.Location = new System.Drawing.Point(15, 12); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(229, 51); this.label1.TabIndex = 0; this.label1.Text = "Selecione a data que voce deseja propor ao solicitante:"; // // Reagendar // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(157)))), ((int)(((byte)(224)))), ((int)(((byte)(173))))); this.ClientSize = new System.Drawing.Size(284, 261); this.Controls.Add(this.panel1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Reagendar"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Reagendar"; this.panel1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Panel panel1; private System.Windows.Forms.DateTimePicker dataAgendar; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button Enviar; } }
47.536364
168
0.590553
[ "MIT" ]
vinidg/sistema-solicitacao-ambulancias
Solicitacao de Ambulancias/Reagendar.Designer.cs
5,231
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.19448 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace AH.ModuleController.UI.IPD.Reports.ReportUI { using System; using System.ComponentModel; using CrystalDecisions.Shared; using CrystalDecisions.ReportSource; using CrystalDecisions.CrystalReports.Engine; public class rptAdmissionCard : ReportClass { public rptAdmissionCard() { } public override string ResourceName { get { return "rptAdmissionCard.rpt"; } set { // Do nothing } } public override bool NewGenerator { get { return true; } set { // Do nothing } } public override string FullResourceName { get { return "AH.ModuleController.UI.IPD.Reports.ReportUI.rptAdmissionCard.rpt"; } set { // Do nothing } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section Section1 { get { return this.ReportDefinition.Sections[0]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section Section2 { get { return this.ReportDefinition.Sections[1]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section Section3 { get { return this.ReportDefinition.Sections[2]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section Section4 { get { return this.ReportDefinition.Sections[3]; } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public CrystalDecisions.CrystalReports.Engine.Section Section5 { get { return this.ReportDefinition.Sections[4]; } } } [System.Drawing.ToolboxBitmapAttribute(typeof(CrystalDecisions.Shared.ExportOptions), "report.bmp")] public class CachedrptAdmissionCard : Component, ICachedReport { public CachedrptAdmissionCard() { } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public virtual bool IsCacheable { get { return true; } set { // } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public virtual bool ShareDBLogonInfo { get { return false; } set { // } } [Browsable(false)] [DesignerSerializationVisibilityAttribute(System.ComponentModel.DesignerSerializationVisibility.Hidden)] public virtual System.TimeSpan CacheTimeOut { get { return CachedReportConstants.DEFAULT_TIMEOUT; } set { // } } public virtual CrystalDecisions.CrystalReports.Engine.ReportDocument CreateReport() { rptAdmissionCard rpt = new rptAdmissionCard(); rpt.Site = this.Site; return rpt; } public virtual string GetCustomizedCacheKey(RequestContext request) { String key = null; // // The following is the code used to generate the default // // cache key for caching report jobs in the ASP.NET Cache. // // Feel free to modify this code to suit your needs. // // Returning key == null causes the default cache key to // // be generated. // // key = RequestContext.BuildCompleteCacheKey( // request, // null, // sReportFilename // this.GetType(), // this.ShareDBLogonInfo ); return key; } } }
33.649351
112
0.549788
[ "Apache-2.0" ]
atiq-shumon/DotNetProjects
Hospital_ERP_VS13-WCF_WF/AH.ModuleController/UI/IPD/Reports/ReportUI/rptAdmissionCard.cs
5,184
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\IMethodRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The interface IManagedDeviceRemoteLockRequestBuilder. /// </summary> public partial interface IManagedDeviceRemoteLockRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> IManagedDeviceRemoteLockRequest Request(IEnumerable<Option> options = null); } }
37.448276
153
0.588398
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IManagedDeviceRemoteLockRequestBuilder.cs
1,086
C#
namespace AcceptanceTestsRestSharp.Helpers { public static class Constants { public const string BaseRoute = "/api/v1"; public const string Movies = "/api/v1/movies"; } }
13.375
54
0.61215
[ "MIT" ]
ECatalin/blackslope.net
src/BlackSlope.Api.IntegrationTests/AcceptanceTestsRestSharp/Helpers/Constants.cs
216
C#
using System; using Arctium.Connection.Tls.Protocol.HandshakeProtocol.Extensions; using Arctium.Connection.Tls.Protocol.BinarOps.HandshakeBuilders.ExtensionsBuilders; namespace Arctium.Connection.Tls.Protocol.BinaryOps.Builder.HandshakeBuilders.ExtensionsBuilders { class SignatureAlgorithmsExtensionBuilder : IExtensionBuilder { public HandshakeExtension BuildExtension(ExtensionFormatData extData) { //validate length, // signature and hash algo is a byte pair, first byte indicates hash, second sign. if (extData.Length % 2 != 0) throw new Exception("Invalid length of the signature algorithms extension"); if (extData.Length == 0) throw new Exception("Not sure to throw this but something is wrong that in SignatureAlgorithms extension sign/hash pair is emtpy"); int pairsCount = extData.Length / 2; SignatureAlgorithmsExtension.SignatureAndHashAlgorithm[] hashSignPairs = new SignatureAlgorithmsExtension.SignatureAndHashAlgorithm[pairsCount]; int next = 0; for (int i = 0; i < extData.Length; i += 2) { hashSignPairs[next] = ExtensionsBuildConsts.GetSignatureHashAlgoPair(extData.Buffer[i + extData.DataOffset],extData.Buffer[i + 1 + extData.DataOffset]); next++; } return new SignatureAlgorithmsExtension(hashSignPairs); } } }
45.0625
168
0.697642
[ "MIT" ]
NeuroXiq/Arctium
src/Arctium/Arctium.Connection/Tls/Protocol/BinaryOps/Builder/HandshakeBuilders/ExtensionsBuilders/SignatureAlgorithmsExtensionBuilder.cs
1,444
C#
namespace FeelingSpa.Web.Tests { using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Testing; using Xunit; public class WebTests : IClassFixture<WebApplicationFactory<Startup>> { private readonly WebApplicationFactory<Startup> server; public WebTests(WebApplicationFactory<Startup> server) { this.server = server; } [Fact(Skip = "Example test. Disabled for CI.")] public async Task IndexPageShouldReturnStatusCode200WithTitle() { var client = this.server.CreateClient(); var response = await client.GetAsync("/"); response.EnsureSuccessStatusCode(); var responseContent = await response.Content.ReadAsStringAsync(); Assert.Contains("<title>", responseContent); } [Fact(Skip = "Example test. Disabled for CI.")] public async Task AccountManagePageRequiresAuthorization() { var client = this.server.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); var response = await client.GetAsync("Identity/Account/Manage"); Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); } } }
33.631579
120
0.650235
[ "MIT" ]
Desislav74/Feeling-Spa
Tests/FeelingSpa.Web.Tests/WebTests.cs
1,280
C#
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using CGALDotNetGeometry.Numerics; using CGALDotNetGeometry.Shapes; namespace CGALDotNet.Triangulations { internal class DelaunayTriangulationKernel2_EEK : DelaunayTriangulationKernel2 { internal override string Name => "EEK"; internal static readonly DelaunayTriangulationKernel2 Instance = new DelaunayTriangulationKernel2_EEK(); internal override IntPtr Create() { return DelaunayTriangulation2_EEK_Create(); } internal override void Release(IntPtr ptr) { DelaunayTriangulation2_EEK_Release(ptr); } internal override void Clear(IntPtr ptr) { DelaunayTriangulation2_EEK_Clear(ptr); } internal override IntPtr Copy(IntPtr ptr) { return DelaunayTriangulation2_EEK_Copy(ptr); } internal override void SetIndices(IntPtr ptr) { DelaunayTriangulation2_EEK_SetIndices(ptr); } internal override int BuildStamp(IntPtr ptr) { return DelaunayTriangulation2_EEK_BuildStamp(ptr); } internal override bool IsValid(IntPtr ptr, int level) { return DelaunayTriangulation2_EEK_IsValid(ptr, level); } internal override int VertexCount(IntPtr ptr) { return DelaunayTriangulation2_EEK_VertexCount(ptr); } internal override int FaceCount(IntPtr ptr) { return DelaunayTriangulation2_EEK_FaceCount(ptr); } internal override void InsertPoint(IntPtr ptr, Point2d point) { DelaunayTriangulation2_EEK_InsertPoint(ptr, point); } internal override void InsertPoints(IntPtr ptr, Point2d[] points, int count) { DelaunayTriangulation2_EEK_InsertPoints(ptr, points, count); } internal override void InsertPolygon(IntPtr triPtr, IntPtr polyPtr) { DelaunayTriangulation2_EEK_InsertPolygon(triPtr, polyPtr); } internal override void InsertPolygonWithHoles(IntPtr triPtr, IntPtr pwhPtr) { DelaunayTriangulation2_EEK_InsertPolygonWithHoles(triPtr, pwhPtr); } internal override void GetPoints(IntPtr ptr, Point2d[] points, int count) { DelaunayTriangulation2_EEK_GetPoints(ptr, points, count); } internal override void GetIndices(IntPtr ptr, int[] indices, int count) { DelaunayTriangulation2_EEK_GetIndices(ptr, indices, count); } internal override bool GetVertex(IntPtr ptr, int index, out TriVertex2 vertex) { return DelaunayTriangulation2_EEK_GetVertex(ptr, index, out vertex); } internal override void GetVertices(IntPtr ptr, TriVertex2[] vertices, int count) { DelaunayTriangulation2_EEK_GetVertices(ptr, vertices, count); } internal override bool GetFace(IntPtr ptr, int index, out TriFace2 face) { return DelaunayTriangulation2_EEK_GetFace(ptr, index, out face); } internal override bool GetSegment(IntPtr ptr, int faceIndex, int neighbourIndex, out Segment2d segment) { return DelaunayTriangulation2_EEK_GetSegment(ptr, faceIndex, neighbourIndex, out segment); } internal override bool GetTriangle(IntPtr ptr, int faceIndex, out Triangle2d triangle) { return DelaunayTriangulation2_EEK_GetTriangle(ptr, faceIndex, out triangle); } internal override void GetTriangles(IntPtr ptr, Triangle2d[] triangles, int count) { DelaunayTriangulation2_EEK_GetTriangles(ptr, triangles, count); } internal override bool GetCircumcenter(IntPtr ptr, int faceIndex, out Point2d circumcenter) { return DelaunayTriangulation2_EEK_GetCircumcenter(ptr, faceIndex, out circumcenter); } internal override void GetCircumcenters(IntPtr ptr, [Out] Point2d[] circumcenters,int count) { DelaunayTriangulation2_EEK_GetCircumcenters(ptr, circumcenters, count); } internal override void GetFaces(IntPtr ptr, TriFace2[] faces, int count) { DelaunayTriangulation2_EEK_GetFaces(ptr, faces, count); } internal override int NeighbourIndex(IntPtr ptr, int faceIndex, int index) { return DelaunayTriangulation2_EEK_NeighbourIndex(ptr, faceIndex, index); } internal override bool LocateFace(IntPtr ptr, Point2d point, out TriFace2 face) { return DelaunayTriangulation2_EEK_LocateFace(ptr, point, out face); } internal override bool MoveVertex(IntPtr ptr, int index, Point2d point, bool ifNoCollision, out TriVertex2 vertex) { return DelaunayTriangulation2_EEK_MoveVertex(ptr, index, point, ifNoCollision, out vertex); } internal override bool RemoveVertex(IntPtr ptr, int index) { return DelaunayTriangulation2_EEK_RemoveVertex(ptr, index); } internal override bool FlipEdge(IntPtr ptr, int faceIndex, int neighbour) { return DelaunayTriangulation2_EEK_FlipEdge(ptr, faceIndex, neighbour); } //Delaunay only internal override int VoronoiSegmentCount(IntPtr ptr) { return DelaunayTriangulation2_EEK_VoronoiSegmentCount(ptr); } internal override int VoronoiRayCount(IntPtr ptr) { return DelaunayTriangulation2_EEK_VoronoiRayCount(ptr); } internal override void GetVoronoiSegments(IntPtr ptr, Segment2d[] segments, int count) { DelaunayTriangulation2_EEK_GetVoronoiSegments(ptr, segments, count); } internal override void GetVoronoiRays(IntPtr ptr, Ray2d[] rays, int count) { DelaunayTriangulation2_EEK_GetVoronoiRays(ptr, rays, count); } internal override void VoronoiCount(IntPtr ptr, out int numSegments, out int numRays) { DelaunayTriangulation2_EEK_VoronoiCount(ptr, out numSegments, out numRays); } internal override void Transform(IntPtr ptr, Point2d translation, double rotation, double scale) { DelaunayTriangulation2_EEK_Transform(ptr, translation, rotation, scale); } [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern IntPtr DelaunayTriangulation2_EEK_Create(); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_Release(IntPtr ptr); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_Clear(IntPtr ptr); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern IntPtr DelaunayTriangulation2_EEK_Copy(IntPtr ptr); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_SetIndices(IntPtr ptr); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern int DelaunayTriangulation2_EEK_BuildStamp(IntPtr ptr); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern bool DelaunayTriangulation2_EEK_IsValid(IntPtr ptr, int level); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern int DelaunayTriangulation2_EEK_VertexCount(IntPtr ptr); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern int DelaunayTriangulation2_EEK_FaceCount(IntPtr ptr); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_InsertPoint(IntPtr ptr, Point2d point); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_InsertPoints(IntPtr ptr, [In] Point2d[] points, int count); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_InsertPolygon(IntPtr triPtr, IntPtr polyPtr); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_InsertPolygonWithHoles(IntPtr triPtr, IntPtr pwhPtr); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_GetPoints(IntPtr ptr, [Out] Point2d[] points, int count); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_GetIndices(IntPtr ptr, [Out] int[] indices, int count); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern bool DelaunayTriangulation2_EEK_GetVertex(IntPtr ptr, int index, [Out] out TriVertex2 vertex); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_GetVertices(IntPtr ptr, [Out] TriVertex2[] vertices, int count); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern bool DelaunayTriangulation2_EEK_GetFace(IntPtr ptr, int index, [Out] out TriFace2 triFace); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_GetFaces(IntPtr ptr, [Out] TriFace2[] faces, int count); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern bool DelaunayTriangulation2_EEK_GetSegment(IntPtr ptr, int faceIndex, int neighbourIndex, [Out] out Segment2d segment); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern bool DelaunayTriangulation2_EEK_GetTriangle(IntPtr ptr, int faceIndex, [Out] out Triangle2d triangle); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_GetTriangles(IntPtr ptr, [Out] Triangle2d[] triangles, int count); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern bool DelaunayTriangulation2_EEK_GetCircumcenter(IntPtr ptr, int faceIndex, [Out] out Point2d circumcenter); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_GetCircumcenters(IntPtr ptr, [Out] Point2d[] circumcenters, int count); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern int DelaunayTriangulation2_EEK_NeighbourIndex(IntPtr ptr, int faceIndex, int index); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern bool DelaunayTriangulation2_EEK_LocateFace(IntPtr ptr, Point2d point, [Out] out TriFace2 face); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern bool DelaunayTriangulation2_EEK_MoveVertex(IntPtr ptr, int index, Point2d point, bool ifNoCollision, [Out] out TriVertex2 vertex); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern bool DelaunayTriangulation2_EEK_RemoveVertex(IntPtr ptr, int index); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern bool DelaunayTriangulation2_EEK_FlipEdge(IntPtr ptr, int faceIndex, int neighbour); //Delaunay only [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern int DelaunayTriangulation2_EEK_VoronoiSegmentCount(IntPtr ptr); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern int DelaunayTriangulation2_EEK_VoronoiRayCount(IntPtr ptr); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_GetVoronoiSegments(IntPtr ptr, [Out] Segment2d[] segments, int count); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_GetVoronoiRays(IntPtr ptr, [Out] Ray2d[] rays, int count); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_VoronoiCount(IntPtr ptr, [Out] out int numSegments, [Out] out int numRays); [DllImport(DLL_NAME, CallingConvention = CDECL)] private static extern void DelaunayTriangulation2_EEK_Transform(IntPtr ptr, Point2d translation, double rotation, double scale); } }
41.299342
160
0.702748
[ "MIT" ]
unitycoder/CGALDotNet
CGALDotNet/Triangulations/DelaunayTriangulationKernel2_EEK.cs
12,557
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; namespace Meision.Database { [XmlRoot(ElementName = PrimaryKeyConstraintModel.XmlElement_Tag)] public class PrimaryKeyConstraintModel : ConstraintModel { #region Field & Property private string[] _columns; public string[] Columns { get { return this._columns; } set { this._columns = value; } } #endregion Field & Property #region Constructor public PrimaryKeyConstraintModel() { } public PrimaryKeyConstraintModel(string[] columns) : this(null, columns) { } public PrimaryKeyConstraintModel(string name, string[] columns) : base(name) { this._columns = columns; } #endregion Constructor #region IXmlSerializable Members internal const string XmlElement_Tag = "PrimaryKey"; internal const string XmlAttribute_Columns = "Columns"; public override void ReadXml(System.Xml.XmlReader reader) { // Attributes while (reader.MoveToNextAttribute()) { switch (reader.Name) { case XmlAttribute_Name: this.Name = reader.Value; break; case XmlAttribute_Columns: this.Columns = reader.Value.Split(new string[] { DatabaseHelper.Separator }, StringSplitOptions.RemoveEmptyEntries); break; } } reader.MoveToContent(); // Element if (!reader.IsEmptyElement) { reader.ReadStartElement(); reader.ReadEndElement(); } else { reader.Read(); } } public override void WriteXml(System.Xml.XmlWriter writer) { if (this.Name != default(string)) { writer.WriteAttributeString(XmlAttribute_Name, this.Name); } if (this.Columns != null) { writer.WriteAttributeString(XmlAttribute_Columns, string.Join(DatabaseHelper.Separator, this.Columns)); } } #endregion IXmlSerializable Members } }
27.602151
140
0.523179
[ "MIT" ]
meision/Lever
Code/9-Extensions/Lever.VisualStudioExtensions/Function/Database/PrimaryKeyConstraintModel.cs
2,569
C#
/* * Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Text; namespace Sensor.Models { /// <summary> /// The Ultraviolet Sensor Data View Model /// </summary> public class UltravioletSensorViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private float index = 0.0f; /// <summary> /// Updates ultraviolet index value view with the new value. /// </summary> /// <value> The ultraviolet index. </value> public float Index { get { return index; } set { index = value; RaisePropertyChanged(); } } public void RaisePropertyChanged([CallerMemberName]string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } }
31.16
86
0.686136
[ "Apache-2.0" ]
Inhong/Tizen-CSharp-Samples
Mobile/Xamarin.Forms/Sensor/src/Sensor/Sensor/Models/UltravioletSensorViewModel.cs
1,560
C#
using System; using System.CodeDom.Compiler; using TobascoTest.IGenerateRepository; using static Dapper.SqlMapper; using Dapper; using System.Linq; using TobascoTest.GeneratedEntity; using Tobasco; namespace TobascoTest.IGenerateRepository { [GeneratedCode("Tobasco", "1.0.0.0")] public partial interface ICPK18Repository { CPK18 Save(CPK18 cpk18); CPK18 GetById(long id); } }
20.473684
42
0.784062
[ "Apache-2.0" ]
VictordeBaare/Tobasco
TobascoTest/IGenerateRepository/ICPK18Repository_Generated.cs
391
C#
// Copyright 2018 Cohesity Inc. using System.Management.Automation; using Cohesity.Powershell.Common; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Cohesity.Powershell.Cmdlets.ProtectionSource { /// <summary> /// <para type="synopsis"> /// Registers a new SMB file share as protection source with the Cohesity Cluster. /// </para> /// <para type="description"> /// Registers a new SMB file share as protection source with the Cohesity Cluster. /// </para> /// </summary> /// <example> /// <para>PS&gt;</para> /// <code> /// Register-CohesityProtectionSourceSMB -MountPath "\\smb-server.example.com\share -Credential (Get-Credential)" /// </code> /// <para> /// Registers a new SMB file share with mount path "\\smb-server.example.com\share" with the Cohesity Cluster. /// </para> /// </example> [Cmdlet(VerbsLifecycle.Register, "CohesityProtectionSourceSMB")] [OutputType(typeof(Model.ProtectionSource))] public class RegisterCohesityProtectionSourceSMB : PSCmdlet { private Session Session { get { if (!(SessionState.PSVariable.GetValue("Session") is Session result)) { result = new Session(); SessionState.PSVariable.Set("Session", result); } return result; } } #region Params /// <summary> /// <para type="description"> /// NFS Mount path. /// </para> /// </summary> [Parameter(Mandatory = true)] public string MountPath { get; set; } = null; /// <summary> /// <para type="description"> /// User credentials for accessing the SMB file share. /// </para> /// </summary> [Parameter(Mandatory = true)] public PSCredential Credential { get; set; } = null; /// <summary> /// <para type="description"> /// Skip SMB validation registration /// </para> /// </summary> [Parameter(Mandatory = false)] public bool SkipValidation = false; #endregion #region Processing protected override void BeginProcessing() { base.BeginProcessing(); Session.AssertAuthentication(); } protected override void ProcessRecord() { var networkCredential = Credential.GetNetworkCredential(); var domain = networkCredential.Domain; var requestData = JsonConvert.SerializeObject(new { entity = new { type = 11, genericNasEntity = new { protocol = 2, type = 1, path = MountPath } }, entityInfo = new { endpoint = MountPath, type = 11, credentials = new { nasMountCredentials = new { protocol = 2, username = networkCredential.UserName, password = networkCredential.Password, domainName = domain } } }, registeredEntityParams = new { genericNasParams = new { skipValidation = SkipValidation } } }); // POST /backupsources var registerUrl = $"/backupsources"; var result = Session.ApiClient.Post(registerUrl, requestData); JObject protectionSourceObject = JObject.Parse(result); string protectionSourceId = (string)protectionSourceObject["id"]; if(!string.IsNullOrEmpty(protectionSourceId)) { // GET /protectionSources/{id} var getProtectionSourcesUrl = $"/public/protectionSources/objects/{protectionSourceId}"; var response = Session.ApiClient.Get<Model.ProtectionSource>(getProtectionSourcesUrl); WriteObject(response); } else { WriteObject($"Registered {MountPath} Successfully"); } } #endregion } }
32.727941
117
0.512694
[ "Apache-2.0" ]
DavidSeaton/cohesity-powershell-module
src/Cohesity.Powershell/Cmdlets/ProtectionSource/RegisterCohesityProtectionSourceSMB.cs
4,453
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Agent.Sdk; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Text; using Microsoft.TeamFoundation.DistributedTask.WebApi; using Microsoft.VisualStudio.Services.Agent.Util; using Microsoft.VisualStudio.Services.Agent.Capabilities; using Microsoft.Win32; using System.Diagnostics; using System.Linq; using System.Globalization; using System.Threading; using System.Threading.Tasks; using Agent.Sdk.Knob; using Pipelines = Microsoft.TeamFoundation.DistributedTask.Pipelines; namespace Microsoft.VisualStudio.Services.Agent.Worker { [ServiceLocator(Default = typeof(DiagnosticLogManager))] public interface IDiagnosticLogManager : IAgentService { Task UploadDiagnosticLogsAsync(IExecutionContext executionContext, Pipelines.AgentJobRequestMessage message, DateTime jobStartTimeUtc); } // This class manages gathering data for support logs, zipping the data, and uploading it. // The files are created with the following folder structure: // ..\_layout\_work\_temp // \[job name]-support (supportRootFolder) // \files (supportFolder) // ... // support.zip public sealed class DiagnosticLogManager : AgentService, IDiagnosticLogManager { public async Task UploadDiagnosticLogsAsync(IExecutionContext executionContext, Pipelines.AgentJobRequestMessage message, DateTime jobStartTimeUtc) { ArgUtil.NotNull(executionContext, nameof(executionContext)); ArgUtil.NotNull(message, nameof(message)); executionContext.Debug("Starting diagnostic file upload."); // Setup folders // \_layout\_work\_temp\[jobname-support] executionContext.Debug("Setting up diagnostic log folders."); string tempDirectory = HostContext.GetDirectory(WellKnownDirectory.Temp); ArgUtil.Directory(tempDirectory, nameof(tempDirectory)); string supportRootFolder = Path.Combine(tempDirectory, message.JobName + "-support"); Directory.CreateDirectory(supportRootFolder); // \_layout\_work\_temp\[jobname-support]\files executionContext.Debug("Creating diagnostic log files folder."); string supportFilesFolder = Path.Combine(supportRootFolder, "files"); Directory.CreateDirectory(supportFilesFolder); // Create the environment file // \_layout\_work\_temp\[jobname-support]\files\environment.txt var configurationStore = HostContext.GetService<IConfigurationStore>(); AgentSettings settings = configurationStore.GetSettings(); int agentId = settings.AgentId; string agentName = settings.AgentName; int poolId = settings.PoolId; executionContext.Debug("Creating diagnostic log environment file."); string environmentFile = Path.Combine(supportFilesFolder, "environment.txt"); string content = await GetEnvironmentContent(agentId, agentName, message.Steps); File.WriteAllText(environmentFile, content); // Create the capabilities file var capabilitiesManager = HostContext.GetService<ICapabilitiesManager>(); Dictionary<string, string> capabilities = await capabilitiesManager.GetCapabilitiesAsync(configurationStore.GetSettings(), default(CancellationToken)); executionContext.Debug("Creating capabilities file."); string capabilitiesFile = Path.Combine(supportFilesFolder, "capabilities.txt"); string capabilitiesContent = GetCapabilitiesContent(capabilities); File.WriteAllText(capabilitiesFile, capabilitiesContent); // Copy worker diag log files List<string> workerDiagLogFiles = GetWorkerDiagLogFiles(HostContext.GetDirectory(WellKnownDirectory.Diag), jobStartTimeUtc); executionContext.Debug($"Copying {workerDiagLogFiles.Count()} worker diag logs."); foreach (string workerLogFile in workerDiagLogFiles) { ArgUtil.File(workerLogFile, nameof(workerLogFile)); string destination = Path.Combine(supportFilesFolder, Path.GetFileName(workerLogFile)); File.Copy(workerLogFile, destination); } // Copy agent diag log files List<string> agentDiagLogFiles = GetAgentDiagLogFiles(HostContext.GetDirectory(WellKnownDirectory.Diag), jobStartTimeUtc); executionContext.Debug($"Copying {agentDiagLogFiles.Count()} agent diag logs."); foreach (string agentLogFile in agentDiagLogFiles) { ArgUtil.File(agentLogFile, nameof(agentLogFile)); string destination = Path.Combine(supportFilesFolder, Path.GetFileName(agentLogFile)); File.Copy(agentLogFile, destination); } // Read and add to logs waagent.conf settings on Linux if (PlatformUtil.RunningOnLinux) { executionContext.Debug("Dumping of waagent.conf file"); string waagentDumpFile = Path.Combine(supportFilesFolder, "waagentConf.txt"); string configFileName = "waagent.conf"; try { string filePath = Directory.GetFiles("/etc", configFileName).FirstOrDefault(); if (!string.IsNullOrWhiteSpace(filePath)) { string waagentContent = File.ReadAllText(filePath); File.AppendAllText(waagentDumpFile, "waagent.conf settings"); File.AppendAllText(waagentDumpFile, Environment.NewLine); File.AppendAllText(waagentDumpFile, waagentContent); executionContext.Debug("Dumping waagent.conf file is completed."); } else { executionContext.Debug("waagent.conf file wasn't found. Dumping was not done."); } } catch (Exception ex) { string warningMessage = $"Dumping of waagent.conf was not completed successfully. Error message: {ex.Message}"; executionContext.Warning(warningMessage); } } // Copy cloud-init log files from linux machines if (PlatformUtil.RunningOnLinux) { executionContext.Debug("Dumping cloud-init logs."); string logsFilePath = $"{HostContext.GetDirectory(WellKnownDirectory.Diag)}/cloudinit-{jobStartTimeUtc.ToString("yyyyMMdd-HHmmss")}-logs.tar.gz"; string resultLogs = await DumpCloudInitLogs(logsFilePath); executionContext.Debug(resultLogs); if (File.Exists(logsFilePath)) { string destination = Path.Combine(supportFilesFolder, Path.GetFileName(logsFilePath)); File.Copy(logsFilePath, destination); executionContext.Debug("Cloud-init logs added to the diagnostics archive."); } else { executionContext.Debug("Cloud-init logs were not found."); } executionContext.Debug("Dumping cloud-init logs is ended."); } // Copy event logs for windows machines bool dumpJobEventLogs = AgentKnobs.DumpJobEventLogs.GetValue(executionContext).AsBoolean(); if (dumpJobEventLogs && PlatformUtil.RunningOnWindows) { executionContext.Debug("Dumping event viewer logs for current job."); try { string eventLogsFile = $"{HostContext.GetDirectory(WellKnownDirectory.Diag)}/EventViewer-{ jobStartTimeUtc.ToString("yyyyMMdd-HHmmss") }.log"; await DumpCurrentJobEventLogs(executionContext, eventLogsFile, jobStartTimeUtc); string destination = Path.Combine(supportFilesFolder, Path.GetFileName(eventLogsFile)); File.Copy(eventLogsFile, destination); } catch (Exception ex) { executionContext.Debug("Failed to dump event viewer logs. Skipping."); executionContext.Debug($"Error message: {ex}"); } } bool dumpPackagesVerificationResult = AgentKnobs.DumpPackagesVerificationResult.GetValue(executionContext).AsBoolean(); if (dumpPackagesVerificationResult && PlatformUtil.RunningOnLinux && !PlatformUtil.RunningOnRHEL6) { executionContext.Debug("Dumping info about invalid MD5 sums of installed packages."); var debsums = WhichUtil.Which("debsums"); if (debsums == null) { executionContext.Debug("Debsums is not installed on the system. Skipping broken packages check."); } else { try { string packageVerificationResults = await GetPackageVerificationResult(debsums); IEnumerable<string> brokenPackagesInfo = packageVerificationResults .Split("\n") .Where((line) => !String.IsNullOrEmpty(line) && !line.EndsWith("OK")); string brokenPackagesLogsPath = $"{HostContext.GetDirectory(WellKnownDirectory.Diag)}/BrokenPackages-{ jobStartTimeUtc.ToString("yyyyMMdd-HHmmss") }.log"; File.AppendAllLines(brokenPackagesLogsPath, brokenPackagesInfo); string destination = Path.Combine(supportFilesFolder, Path.GetFileName(brokenPackagesLogsPath)); File.Copy(brokenPackagesLogsPath, destination); } catch (Exception ex) { executionContext.Debug("Failed to dump broken packages logs. Skipping."); executionContext.Debug($"Error message: {ex}"); } } } else { executionContext.Debug("The platform is not based on Debian - skipping debsums check."); } try { executionContext.Debug("Starting dumping Agent Azure VM extension logs."); bool logsSuccessfullyDumped = DumpAgentExtensionLogs(executionContext, supportFilesFolder, jobStartTimeUtc); if (logsSuccessfullyDumped) { executionContext.Debug("Agent Azure VM extension logs successfully dumped."); } else { executionContext.Debug("Agent Azure VM extension logs not found. Skipping."); } } catch (Exception ex) { executionContext.Debug("Failed to dump Agent Azure VM extension logs. Skipping."); executionContext.Debug($"Error message: {ex}"); } executionContext.Debug("Zipping diagnostic files."); string buildNumber = executionContext.Variables.Build_Number ?? "UnknownBuildNumber"; string buildName = $"Build {buildNumber}"; string phaseName = executionContext.Variables.System_PhaseDisplayName ?? "UnknownPhaseName"; // zip the files string diagnosticsZipFileName = $"{buildName}-{phaseName}.zip"; string diagnosticsZipFilePath = Path.Combine(supportRootFolder, diagnosticsZipFileName); ZipFile.CreateFromDirectory(supportFilesFolder, diagnosticsZipFilePath); // upload the json metadata file executionContext.Debug("Uploading diagnostic metadata file."); string metadataFileName = $"diagnostics-{buildName}-{phaseName}.json"; string metadataFilePath = Path.Combine(supportFilesFolder, metadataFileName); string phaseResult = GetTaskResultAsString(executionContext.Result); IOUtil.SaveObject(new DiagnosticLogMetadata(agentName, agentId, poolId, phaseName, diagnosticsZipFileName, phaseResult), metadataFilePath); executionContext.QueueAttachFile(type: CoreAttachmentType.DiagnosticLog, name: metadataFileName, filePath: metadataFilePath); executionContext.QueueAttachFile(type: CoreAttachmentType.DiagnosticLog, name: diagnosticsZipFileName, filePath: diagnosticsZipFilePath); executionContext.Debug("Diagnostic file upload complete."); } /// <summary> /// Dumping Agent Azure VM extension logs to the support files folder. /// </summary> /// <param name="executionContext">Execution context to write debug messages.</param> /// <param name="supportFilesFolder">Destination folder for files to be dumped.</param> /// <param name="jobStartTimeUtc">Date and time to create timestamp.</param> /// <returns>true, if logs have been dumped successfully; otherwise returns false.</returns> private bool DumpAgentExtensionLogs(IExecutionContext executionContext, string supportFilesFolder, DateTime jobStartTimeUtc) { string pathToLogs = String.Empty; string archiveName = String.Empty; string timestamp = jobStartTimeUtc.ToString("yyyyMMdd-HHmmss"); if (PlatformUtil.RunningOnWindows) { // the extension creates a subfolder with a version number on Windows, and we're taking the latest one string pathToExtensionVersions = ExtensionPaths.WindowsPathToExtensionVersions; if (!Directory.Exists(pathToExtensionVersions)) { executionContext.Debug("Path to subfolders with Agent Azure VM Windows extension logs (of its different versions) does not exist."); executionContext.Debug($"(directory \"{pathToExtensionVersions}\" not found)"); return false; } string[] subDirs = Directory.GetDirectories(pathToExtensionVersions).Select(dir => Path.GetFileName(dir)).ToArray(); if (subDirs.Length == 0) { executionContext.Debug("Path to Agent Azure VM Windows extension logs (of its different versions) does not contain subfolders."); executionContext.Debug($"(directory \"{pathToExtensionVersions}\" does not contain subdirectories with logs)"); return false; } Version[] versions = subDirs.Select(dir => new Version(dir)).ToArray(); Version maxVersion = versions.Max(); pathToLogs = Path.Combine(pathToExtensionVersions, maxVersion.ToString()); archiveName = $"AgentWindowsExtensionLogs-{timestamp}-utc.zip"; } else if (PlatformUtil.RunningOnLinux) { // the extension does not create a subfolder with a version number on Linux, and we're just taking this folder pathToLogs = ExtensionPaths.LinuxPathToExtensionLogs; if (!Directory.Exists(pathToLogs)) { executionContext.Debug("Path to Agent Azure VM Linux extension logs does not exist."); executionContext.Debug($"(directory \"{pathToLogs}\" not found)"); return false; } archiveName = $"AgentLinuxExtensionLogs-{timestamp}-utc.zip"; } else { executionContext.Debug("Dumping Agent Azure VM extension logs implemented for Windows and Linux only."); return false; } executionContext.Debug($"Path to agent extension logs: {pathToLogs}"); string archivePath = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Diag), archiveName); executionContext.Debug($"Archiving agent extension logs to: {archivePath}"); ZipFile.CreateFromDirectory(pathToLogs, archivePath); string copyPath = Path.Combine(supportFilesFolder, archiveName); executionContext.Debug($"Copying archived agent extension logs to: {copyPath}"); File.Copy(archivePath, copyPath); return true; } /// <summary> /// Dumping cloud-init logs to diag folder of agent if cloud-init is installed on current machine. /// </summary> /// <param name="logsFile">Path to collect cloud-init logs</param> /// <returns>Returns the method execution logs</returns> private async Task<string> DumpCloudInitLogs(string logsFile) { var builder = new StringBuilder(); string cloudInit = WhichUtil.Which("cloud-init", trace: Trace); if (string.IsNullOrEmpty(cloudInit)) { return "Cloud-init isn't found on current machine."; } string arguments = $"collect-logs -t \"{logsFile}\""; try { using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs args) => { builder.AppendLine(args.Data); }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs args) => { builder.AppendLine(args.Data); }; await processInvoker.ExecuteAsync( workingDirectory: HostContext.GetDirectory(WellKnownDirectory.Bin), fileName: cloudInit, arguments: arguments, environment: null, requireExitCodeZero: false, outputEncoding: null, killProcessOnCancel: false, cancellationToken: default(CancellationToken)); } } catch (Exception ex) { builder.AppendLine(ex.Message); } return builder.ToString(); } private string GetCapabilitiesContent(Dictionary<string, string> capabilities) { var builder = new StringBuilder(); builder.AppendLine("Capabilities"); builder.AppendLine(""); foreach (string key in capabilities.Keys) { builder.Append(key); if (!string.IsNullOrEmpty(capabilities[key])) { builder.Append($" = {capabilities[key]}"); } builder.AppendLine(); } return builder.ToString(); } private string GetTaskResultAsString(TaskResult? taskResult) { if (!taskResult.HasValue) { return "Unknown"; } return taskResult.ToString(); } // The current solution is a hack. We need to rethink this and find a better one. // The list of worker log files isn't available from the logger. It's also nested several levels deep. // For this solution we deduce the applicable worker log files by comparing their create time to the start time of the job. private List<string> GetWorkerDiagLogFiles(string diagFolder, DateTime jobStartTimeUtc) { // Get all worker log files with a timestamp equal or greater than the start of the job var workerLogFiles = new List<string>(); var directoryInfo = new DirectoryInfo(diagFolder); // Sometimes the timing is off between the job start time and the time the worker log file is created. // This adds a small buffer that provides some leeway in case the worker log file was created slightly // before the time we log as job start time. int bufferInSeconds = -30; DateTime searchTimeUtc = jobStartTimeUtc.AddSeconds(bufferInSeconds); foreach (FileInfo file in directoryInfo.GetFiles().Where(f => f.Name.StartsWith("Worker_"))) { // The format of the logs is: // Worker_20171003-143110-utc.log DateTime fileCreateTime = DateTime.ParseExact(s: file.Name.Substring(startIndex: 7, length: 15), format: "yyyyMMdd-HHmmss", provider: CultureInfo.InvariantCulture); if (fileCreateTime >= searchTimeUtc) { workerLogFiles.Add(file.FullName); } } return workerLogFiles; } private List<string> GetAgentDiagLogFiles(string diagFolder, DateTime jobStartTimeUtc) { // Get the newest agent log file that created just before the start of the job var agentLogFiles = new List<string>(); var directoryInfo = new DirectoryInfo(diagFolder); // The agent log that record the start point of the job should created before the job start time. // The agent log may get paged if it reach size limit. // We will only need upload 1 agent log file in 99%. // There might be 1% we need to upload 2 agent log files. String recentLog = null; DateTime recentTimeUtc = DateTime.MinValue; foreach (FileInfo file in directoryInfo.GetFiles().Where(f => f.Name.StartsWith("Agent_"))) { // The format of the logs is: // Agent_20171003-143110-utc.log if (DateTime.TryParseExact(s: file.Name.Substring(startIndex: 6, length: 15), format: "yyyyMMdd-HHmmss", provider: CultureInfo.InvariantCulture, style: DateTimeStyles.None, result: out DateTime fileCreateTime)) { // always add log file created after the job start. if (fileCreateTime >= jobStartTimeUtc) { agentLogFiles.Add(file.FullName); } else if (fileCreateTime > recentTimeUtc) { recentLog = file.FullName; recentTimeUtc = fileCreateTime; } } } if (!String.IsNullOrEmpty(recentLog)) { agentLogFiles.Add(recentLog); } return agentLogFiles; } private async Task<string> GetEnvironmentContent(int agentId, string agentName, IList<Pipelines.JobStep> steps) { if (PlatformUtil.RunningOnWindows) { return await GetEnvironmentContentWindows(agentId, agentName, steps); } return await GetEnvironmentContentNonWindows(agentId, agentName, steps); } private async Task<string> GetEnvironmentContentWindows(int agentId, string agentName, IList<Pipelines.JobStep> steps) { var builder = new StringBuilder(); builder.AppendLine($"Environment file created at(UTC): {DateTime.UtcNow}"); // TODO: Format this like we do in other places. builder.AppendLine($"Agent Version: {BuildConstants.AgentPackage.Version}"); builder.AppendLine($"Agent Id: {agentId}"); builder.AppendLine($"Agent Name: {agentName}"); builder.AppendLine($"OS: {System.Runtime.InteropServices.RuntimeInformation.OSDescription}"); builder.AppendLine("Steps:"); foreach (Pipelines.TaskStep task in steps.OfType<Pipelines.TaskStep>()) { builder.AppendLine($"\tName: {task.Reference.Name} Version: {task.Reference.Version}"); } // windows defender on/off builder.AppendLine($"Defender enabled: {IsDefenderEnabled()}"); // firewall on/off builder.AppendLine($"Firewall enabled: {IsFirewallEnabled()}"); // $psversiontable builder.AppendLine("Powershell Version Info:"); builder.AppendLine(await GetPsVersionInfo()); builder.AppendLine(await GetLocalGroupMembership()); return builder.ToString(); } // Returns whether or not Windows Defender is running. private bool IsDefenderEnabled() { return Process.GetProcessesByName("MsMpEng.exe").FirstOrDefault() != null; } // Returns whether or not the Windows firewall is enabled. private bool IsFirewallEnabled() { try { using (RegistryKey key = Registry.LocalMachine.OpenSubKey("System\\CurrentControlSet\\Services\\SharedAccess\\Parameters\\FirewallPolicy\\StandardProfile")) { if (key == null) { return false; } Object o = key.GetValue("EnableFirewall"); if (o == null) { return false; } int firewall = (int)o; if (firewall == 1) { return true; } return false; } } catch { return false; } } private async Task<string> GetPsVersionInfo() { var builder = new StringBuilder(); string powerShellExe = HostContext.GetService<IPowerShellExeUtil>().GetPath(); string arguments = @"Write-Host ($PSVersionTable | Out-String)"; using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs args) => { builder.AppendLine(args.Data); }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs args) => { builder.AppendLine(args.Data); }; await processInvoker.ExecuteAsync( workingDirectory: HostContext.GetDirectory(WellKnownDirectory.Bin), fileName: powerShellExe, arguments: arguments, environment: null, requireExitCodeZero: false, outputEncoding: null, killProcessOnCancel: false, cancellationToken: default(CancellationToken)); } return builder.ToString(); } /// <summary> /// Gathers a list of local group memberships for the current user. /// </summary> private async Task<string> GetLocalGroupMembership() { var builder = new StringBuilder(); string powerShellExe = HostContext.GetService<IPowerShellExeUtil>().GetPath(); string scriptFile = Path.Combine(HostContext.GetDirectory(WellKnownDirectory.Bin), "powershell", "Get-LocalGroupMembership.ps1").Replace("'", "''"); ArgUtil.File(scriptFile, nameof(scriptFile)); string arguments = $@"-NoLogo -Sta -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command "". '{scriptFile}'"""; try { using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs args) => { builder.AppendLine(args.Data); }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs args) => { builder.AppendLine(args.Data); }; await processInvoker.ExecuteAsync( workingDirectory: HostContext.GetDirectory(WellKnownDirectory.Bin), fileName: powerShellExe, arguments: arguments, environment: null, requireExitCodeZero: false, outputEncoding: null, killProcessOnCancel: false, cancellationToken: default(CancellationToken)); } } catch (Exception ex) { builder.AppendLine(ex.Message); } return builder.ToString(); } private async Task<string> GetEnvironmentContentNonWindows(int agentId, string agentName, IList<Pipelines.JobStep> steps) { var builder = new StringBuilder(); builder.AppendLine($"Environment file created at(UTC): {DateTime.UtcNow}"); // TODO: Format this like we do in other places. builder.AppendLine($"Agent Version: {BuildConstants.AgentPackage.Version}"); builder.AppendLine($"Agent Id: {agentId}"); builder.AppendLine($"Agent Name: {agentName}"); builder.AppendLine($"OS: {System.Runtime.InteropServices.RuntimeInformation.OSDescription}"); builder.AppendLine($"User groups: {await GetUserGroupsOnNonWindows()}"); builder.AppendLine("Steps:"); foreach (Pipelines.TaskStep task in steps.OfType<Pipelines.TaskStep>()) { builder.AppendLine($"\tName: {task.Reference.Name} Version: {task.Reference.Version}"); } return builder.ToString(); } /// <summary> /// Get user groups on a non-windows platform using core utility "id". /// </summary> /// <returns>Returns the string with user groups</returns> private async Task<string> GetUserGroupsOnNonWindows() { var idUtil = WhichUtil.Which("id"); var stringBuilder = new StringBuilder(); try { using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs mes) => { stringBuilder.AppendLine(mes.Data); }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs mes) => { stringBuilder.AppendLine(mes.Data); }; await processInvoker.ExecuteAsync( workingDirectory: HostContext.GetDirectory(WellKnownDirectory.Bin), fileName: idUtil, arguments: "-nG", environment: null, requireExitCodeZero: false, outputEncoding: null, killProcessOnCancel: false, cancellationToken: default(CancellationToken) ); } } catch (Exception ex) { stringBuilder.AppendLine(ex.Message); } return stringBuilder.ToString(); } // Collects Windows event logs that appeared during the job execution. // Dumps the gathered info into a separate file since the logs are long. private async Task DumpCurrentJobEventLogs(IExecutionContext executionContext, string logFile, DateTime jobStartTimeUtc) { string powerShellExe = HostContext.GetService<IPowerShellExeUtil>().GetPath(); string arguments = $@" Get-WinEvent -ListLog * ` | ForEach-Object {{ Get-WinEvent -ErrorAction SilentlyContinue -FilterHashtable @{{ LogName=$_.LogName; StartTime='{ jobStartTimeUtc.ToLocalTime() }'; EndTime='{ DateTime.Now }';}} }} ` | Format-List > { logFile }"; using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { await processInvoker.ExecuteAsync( workingDirectory: HostContext.GetDirectory(WellKnownDirectory.Bin), fileName: powerShellExe, arguments: arguments, environment: null, requireExitCodeZero: false, outputEncoding: null, killProcessOnCancel: false, cancellationToken: default(CancellationToken)); } } /// <summary> /// Git package verification result using the "debsums" utility. /// </summary> /// <returns>String with the "debsums" output</returns> private async Task<string> GetPackageVerificationResult(string debsumsPath) { var stringBuilder = new StringBuilder(); using (var processInvoker = HostContext.CreateService<IProcessInvoker>()) { processInvoker.OutputDataReceived += (object sender, ProcessDataReceivedEventArgs mes) => { stringBuilder.AppendLine(mes.Data); }; processInvoker.ErrorDataReceived += (object sender, ProcessDataReceivedEventArgs mes) => { stringBuilder.AppendLine(mes.Data); }; await processInvoker.ExecuteAsync( workingDirectory: HostContext.GetDirectory(WellKnownDirectory.Bin), fileName: debsumsPath, arguments: string.Empty, environment: null, requireExitCodeZero: false, outputEncoding: null, killProcessOnCancel: false, cancellationToken: default(CancellationToken) ); } return stringBuilder.ToString(); } } internal static class ExtensionPaths { public static readonly String WindowsPathToExtensionVersions = "C:\\WindowsAzure\\Logs\\Plugins\\Microsoft.VisualStudio.Services.TeamServicesAgent"; public static readonly String LinuxPathToExtensionLogs = "/var/log/azure/Microsoft.VisualStudio.Services.TeamServicesAgentLinux"; } }
46.634899
226
0.587888
[ "MIT" ]
82amp/azure-pipelines-agent
src/Agent.Worker/DiagnosticLogManager.cs
34,743
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; using System.Collections.Generic; using System.Linq; namespace EF.Console.App.Data { public partial class ApplicationContext : DbContext { public ApplicationContext() { } public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.HasDefaultSchema("private"); OnModelCreatingPartial(modelBuilder); } partial void OnModelCreatingPartial(ModelBuilder modelBuilder); } }
26.178571
95
0.703956
[ "MIT" ]
BoBoBaSs84/TestSolution
EF.Console.App/Data/ApplicationContext.cs
735
C#
// ---------------------------------------------------------------- // Open Source Code on the MIT License (MIT) // Copyright (c) 2015 NUEGY SARL // https://github.com/NueGy/NgLib // ---------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Nglib.FORMAT.MORE { public static class GeoTools { //Console.WriteLine(distance(32.9697, -96.80322, 29.46786, -98.53506, "K")); public static double distance(double lat1, double lon1, double lat2, double lon2, char unit = 'K') { double theta = lon1 - lon2; double dist = Math.Sin(deg2rad(lat1)) * Math.Sin(deg2rad(lat2)) + Math.Cos(deg2rad(lat1)) * Math.Cos(deg2rad(lat2)) * Math.Cos(deg2rad(theta)); dist = Math.Acos(dist); dist = rad2deg(dist); dist = dist * 60 * 1.1515; if (unit == 'K') { dist = dist * 1.609344; } else if (unit == 'N') { dist = dist * 0.8684; } return (dist); } //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //:: This function converts decimal degrees to radians ::: //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: public static double deg2rad(double deg) { return (deg * Math.PI / 180.0); } //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //:: This function converts radians to decimal degrees ::: //::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: public static double rad2deg(double rad) { return (rad / Math.PI * 180.0); } /* private static double GetDistancePoint(PointF point1, PointF point2) { //pythagorean theorem c^2 = a^2 + b^2 //thus c = square root(a^2 + b^2) double a = (double)(point2.X - point1.X); double b = (double)(point2.Y - point1.Y); return Math.Sqrt(a * a + b * b); }*/ } }
33.463768
106
0.406236
[ "MIT" ]
NueGy/NGLib
dev/Nglib/FORMAT/MORE/GeoTools.cs
2,311
C#
//------------------------------------------------------------------------------ // <auto-generated> // Bu kod araç tarafından oluşturuldu. // Çalışma Zamanı Sürümü:4.0.30319.42000 // // Bu dosyada yapılacak değişiklikler yanlış davranışa neden olabilir ve // kod yeniden oluşturulursa kaybolur. // </auto-generated> //------------------------------------------------------------------------------ namespace Playtroy.Properties { using System; /// <summary> /// Yerelleştirilmiş dizeleri aramak gibi işlemler için, türü kesin olarak belirtilmiş kaynak sınıfı. /// </summary> // Bu sınıf ResGen veya Visual Studio gibi bir araç kullanılarak StronglyTypedResourceBuilder // sınıfı tarafından otomatik olarak oluşturuldu. // Üye eklemek veya kaldırmak için .ResX dosyanızı düzenleyin ve sonra da ResGen // komutunu /str seçeneğiyle yeniden çalıştırın veya VS projenizi yeniden oluşturun. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Bu sınıf tarafından kullanılan, önbelleğe alınmış ResourceManager örneğini döndürür. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Playtroy.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Tümü için geçerli iş parçacığının CurrentUICulture özelliğini geçersiz kular /// CurrentUICulture özelliğini tüm kaynak aramaları için geçersiz kılar. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap desen { get { object obj = ResourceManager.GetObject("desen", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap desen_w { get { object obj = ResourceManager.GetObject("desen-w", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap forward_b { get { object obj = ResourceManager.GetObject("forward_b", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap forward_w { get { object obj = ResourceManager.GetObject("forward_w", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap list_b { get { object obj = ResourceManager.GetObject("list_b", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap list_w { get { object obj = ResourceManager.GetObject("list_w", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap noalbumart { get { object obj = ResourceManager.GetObject("noalbumart", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap noalbumart_w { get { object obj = ResourceManager.GetObject("noalbumart_w", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap nosound_b { get { object obj = ResourceManager.GetObject("nosound_b", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap nosound_w { get { object obj = ResourceManager.GetObject("nosound_w", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap pause_b { get { object obj = ResourceManager.GetObject("pause_b", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap pause_w { get { object obj = ResourceManager.GetObject("pause_w", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap play_b { get { object obj = ResourceManager.GetObject("play_b", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap play_w { get { object obj = ResourceManager.GetObject("play_w", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap Playtroy { get { object obj = ResourceManager.GetObject("Playtroy", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap rdis_b { get { object obj = ResourceManager.GetObject("rdis-b", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap rdis_w { get { object obj = ResourceManager.GetObject("rdis-w", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap refresh_b { get { object obj = ResourceManager.GetObject("refresh_b", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap refresh_w { get { object obj = ResourceManager.GetObject("refresh_w", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap rewind_b { get { object obj = ResourceManager.GetObject("rewind_b", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap rewind_w { get { object obj = ResourceManager.GetObject("rewind_w", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap sound_b { get { object obj = ResourceManager.GetObject("sound_b", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap sound_w { get { object obj = ResourceManager.GetObject("sound_w", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap stop_b { get { object obj = ResourceManager.GetObject("stop_b", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// System.Drawing.Bitmap türünde yerelleştirilmiş bir kaynak arar. /// </summary> internal static System.Drawing.Bitmap stop_w { get { object obj = ResourceManager.GetObject("stop_w", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
38.815287
174
0.555054
[ "MIT" ]
Haltroy/Playtroy
Playtroy Desktop/Properties/Resources.Designer.cs
12,375
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using Azure.AI.TextAnalytics.Tests; using Azure.Core.TestFramework; using NUnit.Framework; namespace Azure.AI.TextAnalytics.Samples { [LiveOnly] public partial class TextAnalyticsSamples: SamplesBase<TextAnalyticsTestEnvironment> { [Test] public void Sample7_AnalyzeHealthcareEntities_Cancellation() { string endpoint = TestEnvironment.Endpoint; string apiKey = TestEnvironment.ApiKey; var client = new TextAnalyticsClient(new Uri(endpoint), new AzureKeyCredential(apiKey)); #region Snippet:TextAnalyticsSampleHealthcareCancellation string document = @"RECORD #333582770390100 | MH | 85986313 | | 054351 | 2/14/2001 12:00:00 AM | CORONARY ARTERY DISEASE | Signed | DIS | \ Admission Date: 5/22/2001 Report Status: Signed Discharge Date: 4/24/2001 ADMISSION DIAGNOSIS: CORONARY ARTERY DISEASE. \ HISTORY OF PRESENT ILLNESS: The patient is a 54-year-old gentleman with a history of progressive angina over the past several months. \ The patient had a cardiac catheterization in July of this year revealing total occlusion of the RCA and 50% left main disease ,\ with a strong family history of coronary artery disease with a brother dying at the age of 52 from a myocardial infarction and \ another brother who is status post coronary artery bypass grafting. The patient had a stress echocardiogram done on July , 2001 , \ which showed no wall motion abnormalities , but this was a difficult study due to body habitus. The patient went for six minutes with \ minimal ST depressions in the anterior lateral leads , thought due to fatigue and wrist pain , his anginal equivalent. Due to the patient's \ increased symptoms and family history and history left main disease with total occasional of his RCA was referred for revascularization with open heart surgery."; var batchDocument = new List<string>(); for (var i = 0; i < 10; i++) { batchDocument.Add(document); } AnalyzeHealthcareEntitiesOperation healthOperation = client.StartAnalyzeHealthcareEntities(batchDocument, "en"); healthOperation.Cancel(); } #endregion } }
53.755102
194
0.657175
[ "MIT" ]
AME-Redmond/azure-sdk-for-net
sdk/textanalytics/Azure.AI.TextAnalytics/tests/samples/Sample7_AnalyzeHealthcareEntities_Cancellation.cs
2,636
C#
// <auto-generated /> using System; using CodeSnippets.AspNet.SecurityAndIdentity.Develop.Razor.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace CodeSnippets.AspNet.SecurityAndIdentity.Develop.Razor.Migrations { [DbContext(typeof(DevelopContext))] [Migration("20200413085204_CreateIdentitySchema")] partial class CreateIdentitySchema { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.3") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("CodeSnippets.AspNet.SecurityAndIdentity.Develop.Razor.Areas.Identity.Data.AppUser", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Email") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<bool>("EmailConfirmed") .HasColumnType("bit"); b.Property<bool>("LockoutEnabled") .HasColumnType("bit"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("NormalizedEmail") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<bool>("PhoneNumberConfirmed") .HasColumnType("bit"); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(max)"); b.Property<bool>("TwoFactorEnabled") .HasColumnType("bit"); b.Property<string>("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("RoleId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(max)"); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderDisplayName") .HasColumnType("nvarchar(max)"); b.Property<string>("UserId") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("RoleId") .HasColumnType("nvarchar(450)"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId") .HasColumnType("nvarchar(450)"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Name") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("CodeSnippets.AspNet.SecurityAndIdentity.Develop.Razor.Areas.Identity.Data.AppUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("CodeSnippets.AspNet.SecurityAndIdentity.Develop.Razor.Areas.Identity.Data.AppUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("CodeSnippets.AspNet.SecurityAndIdentity.Develop.Razor.Areas.Identity.Data.AppUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("CodeSnippets.AspNet.SecurityAndIdentity.Develop.Razor.Areas.Identity.Data.AppUser", null) .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
38.643885
125
0.481244
[ "MIT" ]
zhaobingwang/sample
src-snippets/CodeSnippets.AspNet.SecurityAndIdentity.Develop.Razor/Migrations/20200413085204_CreateIdentitySchema.Designer.cs
10,745
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.CCC.Transform; using Aliyun.Acs.CCC.Transform.V20170705; namespace Aliyun.Acs.CCC.Model.V20170705 { public class ListSurveysRequest : RpcAcsRequest<ListSurveysResponse> { public ListSurveysRequest() : base("CCC", "2017-07-05", "ListSurveys", "ccc", "openAPI") { } private string instanceId; private string scenarioId; public string InstanceId { get { return instanceId; } set { instanceId = value; DictionaryUtil.Add(QueryParameters, "InstanceId", value); } } public string ScenarioId { get { return scenarioId; } set { scenarioId = value; DictionaryUtil.Add(QueryParameters, "ScenarioId", value); } } public override bool CheckShowJsonItemName() { return false; } public override ListSurveysResponse GetResponse(UnmarshallerContext unmarshallerContext) { return ListSurveysResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
25.923077
96
0.691889
[ "Apache-2.0" ]
fossabot/aliyun-openapi-net-sdk
aliyun-net-sdk-ccc/CCC/Model/V20170705/ListSurveysRequest.cs
2,022
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Iot.Device.Lsm9Ds1 { // Register for Magnetometer internal enum RegisterM : byte { OffsetX = 0x05, // 16-bit, OFFSET_X_REG_H_M (0x05) OFFSET_X_REG_H_M (0x06) OffsetY = 0x07, // 16-bit, OFFSET_Y_REG_H_M (0x07) OFFSET_Y_REG_H_M (0x08) OffsetZ = 0x09, // 16-bit, OFFSET_Z_REG_H_M (0x09) OFFSET_Z_REG_H_M (0x0A) WhoAmI = 0x0F, // WHO_AM_I Control1 = 0x20, // CTRL_REG1_M Control2 = 0x21, // CTRL_REG2_M Control3 = 0x22, // CTRL_REG3_M Control4 = 0x23, // CTRL_REG4_M Control5 = 0x24, // CTRL_REG5_M Status = 0x27, // STATUS_REG_M OutX = 0x28, // 16-bit, OUT_X_L_M (0x28), OUT_X_H_M (0x29) OutY = 0x2A, // 16-bit, OUT_Y_L_M (0x2A), OUT_Y_H_M (0x2B) OutZ = 0x2C, // 16-bit, OUT_Z_L_M (0x2C), OUT_Z_H_M (0x2D) InterruptConfig = 0x30, // INT_CFG_M InterruptSource = 0x31, // INT_SRC_M InterruptThreshold = 0x32, // 16-bit, INT_THS_L (0x32), INT_THS_H (0x33) } }
42.444444
82
0.63438
[ "MIT" ]
CarlosSardo/nanoFramework.IoT.Device
devices/Lsm9Ds1/RegisterM.cs
1,146
C#
using System; using System.Threading; using System.Threading.Tasks; using DLCS.Core; using DLCS.Core.Collections; using DLCS.Model.Assets; using DLCS.Web.Requests.AssetDelivery; using DLCS.Web.Response; using IIIF; using IIIF.Presentation; using IIIF.Presentation.V2.Strings; using IIIF.Presentation.V3.Strings; using IIIF.Serialisation; using MediatR; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orchestrator.Infrastructure.IIIF; using Orchestrator.Infrastructure.Mediatr; using Orchestrator.Models; using Orchestrator.Settings; using IIIF2 = IIIF.Presentation.V2; using IIIF3 = IIIF.Presentation.V3; using Version = IIIF.Presentation.Version; namespace Orchestrator.Features.Manifests.Requests { /// <summary> /// Mediatr request for generating basic single-item manifest for specified image /// </summary> public class GetManifestForAsset : IRequest<DescriptionResourceResponse>, IGenericAssetRequest { public string FullPath { get; } public BaseAssetRequest AssetRequest { get; set; } public Version IIIFPresentationVersion { get; } public GetManifestForAsset(string path, Version iiifVersion) { FullPath = path; IIIFPresentationVersion = iiifVersion; } } public class GetManifestForAssetHandler : IRequestHandler<GetManifestForAsset, DescriptionResourceResponse> { private readonly IAssetRepository assetRepository; private readonly IAssetPathGenerator assetPathGenerator; private readonly IIIFCanvasFactory canvasFactory; private readonly ILogger<GetManifestForAssetHandler> logger; private readonly OrchestratorSettings orchestratorSettings; public GetManifestForAssetHandler( IAssetRepository assetRepository, IAssetPathGenerator assetPathGenerator, IOptions<OrchestratorSettings> orchestratorSettings, IIIFCanvasFactory canvasFactory, ILogger<GetManifestForAssetHandler> logger) { this.assetRepository = assetRepository; this.assetPathGenerator = assetPathGenerator; this.canvasFactory = canvasFactory; this.orchestratorSettings = orchestratorSettings.Value; this.logger = logger; } public async Task<DescriptionResourceResponse> Handle(GetManifestForAsset request, CancellationToken cancellationToken) { var assetId = request.AssetRequest.GetAssetId(); var asset = await assetRepository.GetAsset(assetId); if (asset is not { Family: AssetFamily.Image }) { logger.LogDebug("Request iiif-manifest for asset {AssetId} but is not found or not an image", assetId); return DescriptionResourceResponse.Empty; } JsonLdBase manifest = request.IIIFPresentationVersion == Version.V3 ? await GenerateV3Manifest(request.AssetRequest, asset) : await GenerateV2Manifest(request.AssetRequest, asset); return DescriptionResourceResponse.Open(manifest.AsJson()); } private async Task<IIIF3.Manifest> GenerateV3Manifest(BaseAssetRequest assetRequest, Asset asset) { var fullyQualifiedImageId = GetFullyQualifiedId(assetRequest, orchestratorSettings.Proxy.ImagePath); var manifest = new IIIF3.Manifest { Id = fullyQualifiedImageId, Context = Context.Presentation3Context, Label = new LanguageMap("en", "Generated by DLCS"), Metadata = new LabelValuePair("en", "Generated On", DateTime.UtcNow.ToString()).AsList(), Items = await canvasFactory.CreateV3Canvases(asset.AsList(), assetRequest.Customer) }; return manifest; } private async Task<IIIF2.Manifest> GenerateV2Manifest(BaseAssetRequest assetRequest, Asset asset) { var fullyQualifiedImageId = GetFullyQualifiedId(assetRequest, orchestratorSettings.Proxy.ImagePath); var manifest = new IIIF2.Manifest { Id = fullyQualifiedImageId, Context = Context.Presentation2Context, Label = new MetaDataValue("Generated by DLCS"), Metadata = new IIIF2.Metadata { Label = new MetaDataValue("Generated On"), Value = new MetaDataValue(DateTime.UtcNow.ToString()) } .AsList(), Sequences = new IIIF2.Sequence { Id = string.Concat(fullyQualifiedImageId, "/sequence/s0"), Label = new MetaDataValue("Sequence 0"), ViewingHint = "paged", Canvases = await canvasFactory.CreateV2Canvases(asset.AsList(), assetRequest.Customer) }.AsList() }; return manifest; } private string GetFullyQualifiedId(BaseAssetRequest baseAssetRequest, string prefix) => assetPathGenerator.GetFullPathForRequest( baseAssetRequest, (assetRequest, template) => { var request = assetRequest as BaseAssetRequest; return DlcsPathHelpers.GeneratePathFromTemplate( template, prefix, request.CustomerPathValue, request.Space.ToString(), request.AssetId); }); } }
41.205674
120
0.622547
[ "MIT" ]
dlcs/protagonist
Orchestrator/Features/Manifests/Requests/GetManifestForAsset.cs
5,812
C#
using System; using System.Collections.Generic; using System.Linq; namespace Glimpse.Core.Extensibility { /// <summary> /// An abstract <see cref="IAlternateType{T}"/> implementation that handles the most common <c>TryCreate</c> scenarios. /// </summary> /// <typeparam name="T">The type to retrieve and alternate for.</typeparam> public abstract class AlternateType<T> : IAlternateType<T> where T : class { /// <summary> /// Initializes a new instance of the <see cref="AlternateType{T}" /> class. /// </summary> /// <param name="proxyFactory">The proxy factory.</param> /// <exception cref="System.ArgumentNullException">Throws and exception if <paramref name="proxyFactory"/> is <c>null</c>.</exception> protected AlternateType(IProxyFactory proxyFactory) { if (proxyFactory == null) { throw new ArgumentNullException("proxyFactory"); } ProxyFactory = proxyFactory; } /// <summary> /// Gets or sets the proxy factory. /// </summary> /// <value> /// The proxy factory. /// </value> public IProxyFactory ProxyFactory { get; set; } /// <summary> /// Gets all methods for the proxy to override. /// </summary> /// <value> /// All methods. /// </value> public abstract IEnumerable<IAlternateMethod> AllMethods { get; } /// <summary> /// Tries to create an alternate type. /// </summary> /// <param name="originalObj">The original object.</param> /// <param name="newObj">The new object.</param> /// <returns>A proxied implementation of the <paramref name="originalObj"/>.</returns> public bool TryCreate(T originalObj, out T newObj) { return TryCreate(originalObj, out newObj, null, null); } /// <summary> /// Tries to create an alternate type with mixins. /// </summary> /// <param name="originalObj">The original object.</param> /// <param name="newObj">The new object.</param> /// <param name="mixins">The mixins.</param> /// <returns> /// A proxied implementation of the <paramref name="originalObj" />. /// </returns> public bool TryCreate(T originalObj, out T newObj, IEnumerable<object> mixins) { return TryCreate(originalObj, out newObj, mixins, null); } /// <summary> /// Tries to create an alternate type with mixins and constructor arguments. /// </summary> /// <param name="originalObj">The original object.</param> /// <param name="newObj">The new object.</param> /// <param name="mixins">The mixins.</param> /// <param name="constructorArguments">The constructor arguments.</param> /// <returns> /// A proxied implementation of the <paramref name="originalObj" />. /// </returns> public virtual bool TryCreate(T originalObj, out T newObj, IEnumerable<object> mixins, object[] constructorArguments) { var allMethods = AllMethods; if (mixins == null) { mixins = Enumerable.Empty<object>(); } if (ProxyFactory.IsWrapInterfaceEligible<T>(typeof(T))) { newObj = ProxyFactory.WrapInterface(originalObj, allMethods, mixins); return true; } if (ProxyFactory.IsWrapClassEligible(typeof(T))) { try { newObj = ProxyFactory.WrapClass(originalObj, allMethods, mixins, constructorArguments); return true; } catch { newObj = null; return false; } } newObj = null; return false; } } }
35.619469
142
0.548323
[ "Apache-2.0" ]
Alexandre-Busarello/Glimpse
source/Glimpse.Core/Extensibility/AlternateType.cs
4,027
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable namespace Azure.IoT.Hub.Service.Models { /// <summary> The Json query request. </summary> public partial class QuerySpecification { /// <summary> Initializes a new instance of QuerySpecification. </summary> public QuerySpecification() { } /// <summary> The query string. </summary> public string Query { get; set; } } }
23.772727
82
0.640535
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/iot/Azure.IoT.Hub.Service/src/Generated/Models/QuerySpecification.cs
523
C#
using System; using System.Globalization; namespace Abp.Localization { /// <summary> /// Represents a string that can be localized. /// </summary> [Serializable] public class LocalizableString : ILocalizableString { /// <summary> /// Unique name of the localization source. /// </summary> public virtual string SourceName { get; private set; } /// <summary> /// Unique Name of the string to be localized. /// </summary> public virtual string Name { get; private set; } /// <summary> /// Needed for serialization. /// </summary> private LocalizableString() { } /// <param name="name">Unique Name of the string to be localized</param> /// <param name="sourceName">Unique name of the localization source</param> public LocalizableString(string name, string sourceName) { if (name == null) { throw new ArgumentNullException("name"); } if (sourceName == null) { throw new ArgumentNullException("sourceName"); } Name = name; SourceName = sourceName; } public string Localize(ILocalizationContext context) { return context.LocalizationManager.GetString(SourceName, Name); } public string Localize(ILocalizationContext context, CultureInfo culture) { return context.LocalizationManager.GetString(SourceName, Name, culture); } public override string ToString() { return string.Format("[LocalizableString: {0}, {1}]", Name, SourceName); } } }
27.671875
84
0.559571
[ "MIT" ]
12321/aspnetboilerplate
src/Abp/Localization/LocalizableString.cs
1,771
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace LGen { using System.Threading; using System; using System.IO; public class LeakGenThrd { internal int myObj; internal int Cv_iCounter = 0; internal int Cv_iRep; public static int Main(System.String[] Args) { int iRep = 2; int iObj = 15; //the number of MB memory will be allocted in MakeLeak() // synchronized console output Console.SetOut(TextWriter.Synchronized(Console.Out)); Console.Out.WriteLine("Test should return with ExitCode 100 ..."); switch (Args.Length) { case 1: if (!Int32.TryParse(Args[0], out iRep)) { iRep = 2; } break; case 2: if (!Int32.TryParse(Args[0], out iRep)) { iRep = 2; } if (!Int32.TryParse(Args[1], out iObj)) { iObj = 15; } break; default: iRep = 2; iObj = 15; break; } LeakGenThrd Mv_Leak = new LeakGenThrd(); if (Mv_Leak.runTest(iRep, iObj)) { Console.WriteLine("Test Passed"); return 100; } else { Console.WriteLine("Test Failed"); return 1; } } public bool runTest(int iRep, int iObj) { Cv_iRep = iRep; myObj = iObj; Thread Mv_Thread = new Thread(new ThreadStart(this.ThreadStart)); Mv_Thread.Start(); for (int i = 0; i < iRep; i++) { MakeLeak(iObj); } return true; } public void ThreadStart() { if (Cv_iCounter < Cv_iRep) { LeakObject[] Mv_Obj = new LeakObject[myObj]; for (int i = 0; i < myObj; i++) { Mv_Obj[i] = new LeakObject(i); } Cv_iCounter += 1; Thread Mv_Thread = new Thread(new ThreadStart(this.ThreadStart)); Mv_Thread.Start(); } } public void MakeLeak(int iObj) { LeakObject[] Mv_Obj = new LeakObject[iObj]; for (int i = 0; i < iObj; i++) { Mv_Obj[i] = new LeakObject(i); } } } public class LeakObject { internal int[] mem; public static int icFinal = 0; public LeakObject(int num) { mem = new int[1024 * 250]; //nearly 1MB memory, larger than this will get assert failure. mem[0] = num; mem[mem.Length - 1] = num; } ~LeakObject() { LeakObject.icFinal++; } } }
26.162602
101
0.426352
[ "MIT" ]
belav/runtime
src/tests/GC/Scenarios/LeakGen/leakgenthrd.cs
3,218
C#
using StoreDB.Models; using StoreDB; using System.Collections.Generic; using System; namespace StoreLib { public class OrderService { private IOrderRepo repo; public OrderService(IOrderRepo repo) { this.repo = repo; } public void AddOrder(Order order) { repo.AddOrder(order); } public void UpdateOrder(Order order) { repo.UpdateOrder(order); } public Order GetOrderById(int id) { Order order = repo.GetOrderById(id); return order; } public Order GetOrderByUserId(int id) { Order order = repo.GetOrderByUserId(id); return order; } public Order GetOrderByLocationId(int id) { Order order = repo.GetOrderByLocationId(id); return order; } public List<Order> GetAllOrdersByLocationId(int id) { List<Order> orders = repo.GetAllOrdersByLocationId(id); return orders; } public List<Order> GetAllOrdersByUserId(int id) { List<Order> orders = repo.GetAllOrdersByUserId(id); return orders; } public void DeleteOrder(Order order) { repo.DeleteOrder(order); } public List<Order> GetAllOrdersByUserIdDateAsc(int id) { List<Order> orders = repo.GetAllOrdersByUserIdDateAsc(id); return orders; } public List<Order> GetAllOrdersByUserIdDateDesc(int id) { List<Order> orders = repo.GetAllOrdersByUserIdDateDesc(id); return orders; } public List<Order> GetAllOrdersByUserIdPriceAsc(int id) { List<Order> orders = repo.GetAllOrdersByUserIdPriceAsc(id); return orders; } public List<Order> GetAllOrdersByUserIdPriceDesc(int id) { List<Order> orders = repo.GetAllOrdersByUserIdPriceDesc(id); return orders; } public Order GetOrderByDate(DateTime dateTime) { Order order = repo.GetOrderByDate(dateTime); return order; } } }
31.632353
72
0.588099
[ "MIT" ]
lw3b3r/ConsoleBookStore
StoreLib/OrderService.cs
2,151
C#
using MediatR; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Ordering.Application.Features.Commands.CheckoutOrder; using Ordering.Application.Features.Commands.DeleteOrder; using Ordering.Application.Features.Commands.UpdateOrder; using Ordering.Application.Features.Queries.GetOrdersList; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; namespace Ordering.Api.Controllers { [ApiController] [Route("api/v1/[controller]")] public class OrderController : ControllerBase { private readonly IMediator _mediator; public OrderController(IMediator mediator) { _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator)); } [HttpGet("{userName}", Name = "GetOrder")] [ProducesResponseType(typeof(IEnumerable<OrdersVm>), (int)HttpStatusCode.OK)] public async Task<ActionResult<IEnumerable<OrdersVm>>> GetOrdersByUserName(string userName) { var query = new GetOrdersListQuery(userName); var orders = await _mediator.Send(query); return Ok(orders); } // testing purpose [HttpPost(Name = "CheckoutOrder")] [ProducesResponseType((int)HttpStatusCode.OK)] public async Task<ActionResult<int>> CheckoutOrder([FromBody] CheckoutOrderCommand command) { var result = await _mediator.Send(command); return Ok(result); } [HttpPut(Name = "UpdateOrder")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesDefaultResponseType] public async Task<ActionResult> UpdateOrder([FromBody] UpdateOrderCommand command) { await _mediator.Send(command); return NoContent(); } [HttpDelete("{id}", Name = "DeleteOrder")] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] [ProducesDefaultResponseType] public async Task<ActionResult> DeleteOrder(int id) { var command = new DeleteOrderCommand() { Id = id }; await _mediator.Send(command); return NoContent(); } } }
35.102941
99
0.677419
[ "MIT" ]
Loominex/AspCoreMicroService_Udemy
MicroService_Udemy/Services/Ordering/Ordering.Api/Controllers/OrderController.cs
2,389
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Endless2DTerrain { public static class Extensions { public static IEnumerable<TSource> DistinctBy<TSource, TKey> (this IEnumerable<TSource> source, Func<TSource, TKey> keySelector) { HashSet<TKey> seenKeys = new HashSet<TKey>(); foreach (TSource element in source) { if (seenKeys.Add(keySelector(element))) { yield return element; } } } } }
24
75
0.563333
[ "MIT" ]
Wartz/Gunbound-Clone
Assets/Endless2DTerrain/Core/Scripts/Extensions.cs
602
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Threading; using System.Threading.Tasks; using Xunit; using static Interop; namespace System.Windows.Forms.Tests { public class ScreenDcCacheTests { [Fact(Skip = "Run manually, takes a few minutes and is very resource intensive.")] public void StessTest() { Random random = new Random(); using ScreenDcCache cache = new ScreenDcCache(); for (int i = 0; i < 10000; i++) { Thread.Sleep(random.Next(5)); Task.Run(() => { using var screen = cache.Acquire(); Assert.False(screen.HDC.IsNull); Thread.Sleep(random.Next(5)); }); } } } }
29.606061
90
0.560901
[ "MIT" ]
Amy-Li03/winforms
src/System.Windows.Forms/tests/UnitTests/System/Windows/Forms/ScreenDcCacheTests.cs
979
C#
using System.Collections.Generic; using UnityEngine.Events; namespace UnityEngine.Rendering { /// <summary> /// Command Buffer Pool /// </summary> public static class CommandBufferPool { static ObjectPool<CommandBuffer> s_BufferPool = new ObjectPool<CommandBuffer>(null, x => x.Clear()); /// <summary> /// Get a new Command Buffer. /// </summary> /// <returns></returns> public static CommandBuffer Get() { var cmd = s_BufferPool.Get(); // Set to empty on purpose, does not create profiling markers. cmd.name = ""; return cmd; } /// <summary> /// Get a new Command Buffer and assign a name to it. /// Named Command Buffers will add profiling makers implicitly for the buffer execution. /// </summary> /// <param name="name"></param> /// <returns></returns> public static CommandBuffer Get(string name) { var cmd = s_BufferPool.Get(); cmd.name = name; return cmd; } /// <summary> /// Release a Command Buffer. /// </summary> /// <param name="buffer"></param> public static void Release(CommandBuffer buffer) { s_BufferPool.Release(buffer); } } }
28.354167
108
0.544453
[ "MIT" ]
ACBGZM/JasonMaToonRenderPipeline
Packages/[email protected]/Runtime/Common/CommandBufferPool.cs
1,361
C#
using KaLib.Brigadier.Context; namespace KaLib.Brigadier { public delegate TS SingleRedirectModifier<TS>(CommandContext<TS> context); }
23.5
78
0.794326
[ "MIT" ]
ItsArcal139/KaLib
KaLib.Brigadier/SingleRedirectModifier.cs
143
C#
namespace GwebberAPI.Areas.HelpPage.ModelDescriptions { public class DictionaryModelDescription : KeyValuePairModelDescription { } }
24
74
0.791667
[ "Unlicense" ]
ricksanchezisagoodman/how-to-create-a-.net-api
GwebberAPI/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs
144
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace Netension.NHibernate.Prometheus.Example { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
26
70
0.593407
[ "MIT" ]
Netension/nhibernate
examples/Netension.NHibernate.Prometheus.Example/Program.cs
546
C#
using System; using Legacy.Core.Configuration; using Legacy.Core.Entities.Items; using Legacy.Core.PartyManagement; using Legacy.Core.StaticData; using UnityEngine; using Object = System.Object; namespace Legacy.Game.MMGUI.PartyCreate { [AddComponentMenu("MM Legacy/MMGUI/PartyCreate/PartyCreationAttributes")] public class PartyCreationAttributes : MonoBehaviour { [SerializeField] private UILabel m_nameLabel; [SerializeField] private UILabel m_raceClassLabel; [SerializeField] private UISprite m_portrait; [SerializeField] private UISprite m_body; [SerializeField] private UILabel m_PointsLeftLabel; [SerializeField] private AttributeChanger m_mightAC; [SerializeField] private AttributeChanger m_magicAC; [SerializeField] private AttributeChanger m_perceptionAC; [SerializeField] private AttributeChanger m_destinyAC; [SerializeField] private AttributeChanger m_vitalityAC; [SerializeField] private AttributeChanger m_spiritAC; [SerializeField] private UILabel m_health; [SerializeField] private UILabel m_mana; private PartyCreator m_partyCreator; public void Init(PartyCreator p_partyCreator) { Cleanup(); m_partyCreator = p_partyCreator; m_mightAC.OnAttributeRaised += OnAttributeRaised; m_magicAC.OnAttributeRaised += OnAttributeRaised; m_perceptionAC.OnAttributeRaised += OnAttributeRaised; m_destinyAC.OnAttributeRaised += OnAttributeRaised; m_vitalityAC.OnAttributeRaised += OnAttributeRaised; m_spiritAC.OnAttributeRaised += OnAttributeRaised; m_mightAC.OnAttributeLowered += OnAttributeLowered; m_magicAC.OnAttributeLowered += OnAttributeLowered; m_perceptionAC.OnAttributeLowered += OnAttributeLowered; m_destinyAC.OnAttributeLowered += OnAttributeLowered; m_vitalityAC.OnAttributeLowered += OnAttributeLowered; m_spiritAC.OnAttributeLowered += OnAttributeLowered; } public void Cleanup() { m_mightAC.OnAttributeRaised -= OnAttributeRaised; m_magicAC.OnAttributeRaised -= OnAttributeRaised; m_perceptionAC.OnAttributeRaised -= OnAttributeRaised; m_destinyAC.OnAttributeRaised -= OnAttributeRaised; m_vitalityAC.OnAttributeRaised -= OnAttributeRaised; m_spiritAC.OnAttributeRaised -= OnAttributeRaised; m_mightAC.OnAttributeLowered -= OnAttributeLowered; m_magicAC.OnAttributeLowered -= OnAttributeLowered; m_perceptionAC.OnAttributeLowered -= OnAttributeLowered; m_destinyAC.OnAttributeLowered -= OnAttributeLowered; m_vitalityAC.OnAttributeLowered -= OnAttributeLowered; m_spiritAC.OnAttributeLowered -= OnAttributeLowered; } public void OnAfterActivate() { NGUITools.SetActive(gameObject, true); UpdateCharacter(); UpdateAttributes(); } public void UndoSelection() { DummyCharacter selectedDummyCharacter = m_partyCreator.GetSelectedDummyCharacter(); selectedDummyCharacter.ResetAttributes(); } public void OnResetClick() { DummyCharacter selectedDummyCharacter = m_partyCreator.GetSelectedDummyCharacter(); selectedDummyCharacter.ResetAttributes(); UpdateCharacter(); UpdateAttributes(); } public void OnDefaultClick() { DummyCharacter selectedDummyCharacter = m_partyCreator.GetSelectedDummyCharacter(); selectedDummyCharacter.SetDefaultAttributes(); UpdateCharacter(); UpdateAttributes(); } public void OnAttributeLowered(Object p_sender, EventArgs p_args) { DummyCharacter selectedDummyCharacter = m_partyCreator.GetSelectedDummyCharacter(); EPotionTarget attribute = (p_sender as AttributeChanger).Attribute; if (attribute == EPotionTarget.MIGHT) { selectedDummyCharacter.DecreaseMight(); } else if (attribute == EPotionTarget.MAGIC) { selectedDummyCharacter.DecreaseMagic(); } else if (attribute == EPotionTarget.PERCEPTION) { selectedDummyCharacter.DecreasePerception(); } else if (attribute == EPotionTarget.DESTINY) { selectedDummyCharacter.DecreaseDestiny(); } else if (attribute == EPotionTarget.VITALITY) { selectedDummyCharacter.DecreaseVitality(); } else if (attribute == EPotionTarget.SPIRIT) { selectedDummyCharacter.DecreaseSpirit(); } UpdateCharacter(); UpdateAttributes(); } private void OnAttributeRaised(Object p_sender, EventArgs p_args) { DummyCharacter selectedDummyCharacter = m_partyCreator.GetSelectedDummyCharacter(); EPotionTarget attribute = (p_sender as AttributeChanger).Attribute; if (attribute == EPotionTarget.MIGHT) { selectedDummyCharacter.IncreaseMight(); } else if (attribute == EPotionTarget.MAGIC) { selectedDummyCharacter.IncreaseMagic(); } else if (attribute == EPotionTarget.PERCEPTION) { selectedDummyCharacter.IncreasePerception(); } else if (attribute == EPotionTarget.DESTINY) { selectedDummyCharacter.IncreaseDestiny(); } else if (attribute == EPotionTarget.VITALITY) { selectedDummyCharacter.IncreaseVitality(); } else if (attribute == EPotionTarget.SPIRIT) { selectedDummyCharacter.IncreaseSpirit(); } UpdateCharacter(); UpdateAttributes(); } private void UpdateCharacter() { DummyCharacter selectedDummyCharacter = m_partyCreator.GetSelectedDummyCharacter(); if (selectedDummyCharacter.Class != EClass.NONE) { CharacterClassStaticData staticData = StaticDataHandler.GetStaticData<CharacterClassStaticData>(EDataType.CHARACTER_CLASS, (Int32)selectedDummyCharacter.Class); m_nameLabel.text = selectedDummyCharacter.Name; String text = staticData.NameKey; if (selectedDummyCharacter.Gender == EGender.MALE) { text += "_M"; } else { text += "_F"; } m_raceClassLabel.text = LocaManager.GetText(selectedDummyCharacter.GetRaceKey()) + " " + LocaManager.GetText(text); m_portrait.spriteName = selectedDummyCharacter.GetPortrait(); m_body.spriteName = selectedDummyCharacter.GetBodySprite(); } } private void UpdateAttributes() { DummyCharacter selectedDummyCharacter = m_partyCreator.GetSelectedDummyCharacter(); String arg = "[000000]"; if (selectedDummyCharacter.GetAttributesToPickLeft() > 0) { arg = "[008000]"; } m_PointsLeftLabel.text = LocaManager.GetText("GUI_POINTS_LEFT", arg, selectedDummyCharacter.GetAttributesToPickLeft()); if (selectedDummyCharacter.Class != EClass.NONE) { Attributes classAttributes = selectedDummyCharacter.GetClassAttributes(); GameConfig game = ConfigManager.Instance.Game; m_mightAC.Init(LocaManager.GetText("CHARACTER_ATTRIBUTE_MIGHT"), LocaManager.GetText("CHARACTER_ATTRIBUTE_MIGHT_TT", game.HealthPerMight), EPotionTarget.MIGHT, classAttributes.Might, selectedDummyCharacter.BaseAttributes.Might, selectedDummyCharacter, null); m_magicAC.Init(LocaManager.GetText("CHARACTER_ATTRIBUTE_MAGIC"), LocaManager.GetText("CHARACTER_ATTRIBUTE_MAGIC_TT", game.ManaPerMagic), EPotionTarget.MAGIC, classAttributes.Magic, selectedDummyCharacter.BaseAttributes.Magic, selectedDummyCharacter, null); m_perceptionAC.Init(LocaManager.GetText("CHARACTER_ATTRIBUTE_PERCEPTION"), LocaManager.GetText("CHARACTER_ATTRIBUTE_PERCEPTION_TT"), EPotionTarget.PERCEPTION, classAttributes.Perception, selectedDummyCharacter.BaseAttributes.Perception, selectedDummyCharacter, null); m_destinyAC.Init(LocaManager.GetText("CHARACTER_ATTRIBUTE_DESTINY"), LocaManager.GetText("CHARACTER_ATTRIBUTE_DESTINY_TT"), EPotionTarget.DESTINY, classAttributes.Destiny, selectedDummyCharacter.BaseAttributes.Destiny, selectedDummyCharacter, null); m_vitalityAC.Init(LocaManager.GetText("CHARACTER_ATTRIBUTE_VITALITY"), LocaManager.GetText("CHARACTER_ATTRIBUTE_VITALITY_TT", selectedDummyCharacter.GetHPPerVitality()), EPotionTarget.VITALITY, classAttributes.Vitality, selectedDummyCharacter.BaseAttributes.Vitality, selectedDummyCharacter, null); m_spiritAC.Init(LocaManager.GetText("CHARACTER_ATTRIBUTE_SPIRIT"), LocaManager.GetText("CHARACTER_ATTRIBUTE_SPIRIT_TT", game.ManaPerSpirit), EPotionTarget.SPIRIT, classAttributes.Spirit, selectedDummyCharacter.BaseAttributes.Spirit, selectedDummyCharacter, null); m_health.text = selectedDummyCharacter.BaseAttributes.HealthPoints.ToString(); m_mana.text = selectedDummyCharacter.BaseAttributes.ManaPoints.ToString(); } } } }
36.28821
302
0.781588
[ "MIT" ]
Albeoris/MMXLegacy
Legacy.Game/Game/MMGUI/PartyCreate/PartyCreationAttributes.cs
8,312
C#
// Copyright (c) Pomelo Foundation. All rights reserved. // Licensed under the MIT. See LICENSE in the project root for license information. using System; using System.Linq.Expressions; using System.Reflection; using System.Text.Json; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using MySqlConnector; using Pomelo.EntityFrameworkCore.MySql.Infrastructure.Internal; using Pomelo.EntityFrameworkCore.MySql.Storage.Internal; namespace Pomelo.EntityFrameworkCore.MySql.Json.Microsoft.Storage.Internal { public class MySqlJsonMicrosoftTypeMapping<T> : MySqlJsonTypeMapping<T> { // Called via reflection. // ReSharper disable once UnusedMember.Global public MySqlJsonMicrosoftTypeMapping( [NotNull] string storeType, [CanBeNull] ValueConverter valueConverter, [CanBeNull] ValueComparer valueComparer, [NotNull] IMySqlOptions options) : base( storeType, valueConverter, valueComparer, options) { } protected MySqlJsonMicrosoftTypeMapping( RelationalTypeMappingParameters parameters, MySqlDbType mySqlDbType, IMySqlOptions options) : base(parameters, mySqlDbType, options) { } protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new MySqlJsonMicrosoftTypeMapping<T>(parameters, MySqlDbType, Options); public override Expression GenerateCodeLiteral(object value) { var defaultJsonDocumentOptions = new Lazy<Expression>(() => Expression.New(typeof(JsonDocumentOptions))); var parseMethod = new Lazy<MethodInfo>(() => typeof(JsonDocument).GetMethod(nameof(JsonDocument.Parse), new[] {typeof(string), typeof(JsonDocumentOptions)})); return value switch { JsonDocument document => Expression.Call(parseMethod.Value, Expression.Constant(document.RootElement.ToString()), defaultJsonDocumentOptions.Value), JsonElement element => Expression.Property( Expression.Call(parseMethod.Value, Expression.Constant(element.ToString()), defaultJsonDocumentOptions.Value), nameof(JsonDocument.RootElement)), string s => Expression.Constant(s), _ => throw new NotSupportedException("Cannot generate code literals for JSON POCOs.") }; } } }
42.238095
170
0.684329
[ "MIT" ]
Artrilogic/Pomelo.EntityFrameworkCore.MySql
src/EFCore.MySql.Json.Microsoft/Storage/Internal/MySqlJsonMicrosoftTypeMapping.cs
2,663
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Trampoline : MonoBehaviour { [Header("Trampoline Variables")] public float bounceForce; public float stayUpTime; private float stayUpCounter; private SpriteRenderer theSR; public Sprite downSprite, upSprite; void Start() { theSR = GetComponent<SpriteRenderer>(); } void Update() { //Changing Sprite of Trampoline depending on stayUpCounter if (stayUpCounter > 0) { stayUpCounter -= Time.deltaTime; //Change sprite to down sprite if (stayUpCounter <= 0) { theSR.sprite = downSprite; } } } private void OnTriggerEnter2D(Collider2D other) { if (other.tag == "Player") { theSR.sprite = upSprite; stayUpCounter = stayUpTime; AudioManager.instance.PlaySFXAdjusted(7); Rigidbody2D player = other.GetComponent<Rigidbody2D>(); player.velocity = new Vector2(player.velocity.x, bounceForce); } } }
24.361702
74
0.59738
[ "MIT" ]
BioSparkDreamer/CASUAL-GAME-BLACK-CAT
The Black Cat/Assets/Scripts/Trampoline.cs
1,145
C#
using System.ComponentModel; using TwitterBootstrapMVC.Infrastructure; namespace TwitterBootstrapMVC { public class Tabs : HtmlElement { [EditorBrowsable(EditorBrowsableState.Never)] public string _id { get; set; } [EditorBrowsable(EditorBrowsableState.Never)] public NavType Type { get; set; } [EditorBrowsable(EditorBrowsableState.Never)] public int _activeTabIndex { get; set; } public Tabs(string id) : base("div") { this._id = id; EnsureClass("tabbable"); this.Type = NavType.Tabs; } public Tabs Position(Direction position) { switch (position) { case Direction.Left: EnsureClass("tabs-left"); break; case Direction.Right: EnsureClass("tabs-right"); break; case Direction.Bottom: EnsureClass("tabs-below"); break; } return this; } public Tabs ActiveTab(int activeTabIndex) { _activeTabIndex = activeTabIndex; return this; } public Tabs Style(NavType type) { this.Type = type; return this; } } }
25.018182
53
0.503634
[ "Apache-2.0" ]
DmitryEfimenko/TwitterBootstrapMvc
TwitterBootstrapMVC/Controls/Tabs.cs
1,378
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("XYWPF.Skin")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("XYWPF.Skin")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] //将 ComVisible 设置为 false 将使此程序集中的类型 //对 COM 组件不可见。 如果需要从 COM 访问此程序集中的类型, //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] //若要开始生成可本地化的应用程序,请设置 //.csproj 文件中的 <UICulture>CultureYouAreCodingWith</UICulture> //例如,如果您在源文件中使用的是美国英语, //使用的是美国英语,请将 <UICulture> 设置为 en-US。 然后取消 //对以下 NeutralResourceLanguage 特性的注释。 更新 //以下行中的“en-US”以匹配项目文件中的 UICulture 设置。 //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly:ThemeInfo( ResourceDictionaryLocation.None, //主题特定资源词典所处位置 //(未在页面中找到资源时使用, //或应用程序资源字典中找到时使用) ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置 //(未在页面中找到资源时使用, //、应用程序或任何主题专用资源字典中找到时使用) )] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // //可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值 //通过使用 "*",如下所示: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
27.910714
91
0.678183
[ "Apache-2.0" ]
go2sleep/XYWPF
XYWPF.Skin/Properties/AssemblyInfo.cs
2,224
C#
using System; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Threading; using System.Threading.Tasks; using Manatee.Json.Internal; namespace Manatee.Json.Parsing { internal class NullParser : IJsonParser { private const string _unexpectedEndOfInput = "Unexpected end of input."; public bool Handles(char c) { return c == 'n' || c == 'N'; } public bool TryParse(string source, ref int index, [NotNullWhen(true)] out JsonValue? value, [NotNullWhen(false)] out string? errorMessage, bool allowExtraChars) { value = null; if (index + 4 > source.Length) { errorMessage = _unexpectedEndOfInput; return false; } if (source.IndexOf("null", index, 4, StringComparison.OrdinalIgnoreCase) != index) { errorMessage = $"Value not recognized: '{source.Substring(index, 4)}'."; return false; } index += 4; value = JsonValue.Null; errorMessage = null; return true; } public bool TryParse(TextReader stream, [NotNullWhen(true)] out JsonValue? value, [NotNullWhen(false)] out string? errorMessage) { value = null; var buffer = SmallBufferCache.Acquire(4); var charsRead = stream.ReadBlock(buffer, 0, 4); if (charsRead != 4) { SmallBufferCache.Release(buffer); errorMessage = _unexpectedEndOfInput; return false; } if ((buffer[0] == 'n' || buffer[0] == 'N') && (buffer[1] == 'u' || buffer[1] == 'U') && (buffer[2] == 'l' || buffer[2] == 'L') && (buffer[3] == 'l' || buffer[3] == 'L')) value = JsonValue.Null; else { errorMessage = $"Value not recognized: '{new string(buffer).Trim('\0')}'."; return false; } SmallBufferCache.Release(buffer); errorMessage = null; return true; } public async Task<(string? errorMessage, JsonValue? value)> TryParseAsync(TextReader stream, CancellationToken token) { var buffer = SmallBufferCache.Acquire(4); var count = await stream.ReadBlockAsync(buffer, 0, 4); if (count < 4) { SmallBufferCache.Release(buffer); return ("Unexpected end of input.", null); } JsonValue? value = null; string? errorMessage = null; if ((buffer[0] == 'n' || buffer[0] == 'N') && (buffer[1] == 'u' || buffer[1] == 'U') && (buffer[2] == 'l' || buffer[2] == 'L') && (buffer[3] == 'l' || buffer[3] == 'L')) value = JsonValue.Null; else errorMessage = $"Value not recognized: '{new string(buffer).Trim('\0')}'."; SmallBufferCache.Release(buffer); return (errorMessage, value); } } }
28.204301
164
0.607701
[ "MIT" ]
Magicianred/Manatee.Json
Manatee.Json/Parsing/NullParser.cs
2,625
C#
using System.Xml.Linq; using Skybrud.Essentials.Xml.Extensions; namespace Skybrud.Social.Flickr.Models.Places { /// <summary> /// Class representing the response body as returned by the <c>flickr.places.findByLatLon</c> API method. /// </summary> /// <see> /// <cref>https://www.flickr.com/services/api/flickr.places.findByLatLon.html</cref> /// </see> public class FlickrPlacesFindByLatLonResponseBody : FlickrResponseBody { #region Properties /// <summary> /// Gets a reference to a collection of the places matching the latitude and longitude as specified in the /// request to the <c>flickr.places.findByLatLon</c> API method. /// </summary> public FlickrPlacesFindByLatLonCollection Places { get; } #endregion #region Constructor /// <summary> /// Initializes a new instance from the specified <paramref name="xml"/>. /// </summary> /// <param name="xml">The instance of <see cref="XElement"/> representing the object.</param> protected FlickrPlacesFindByLatLonResponseBody(XElement xml) : base(xml) { Places = xml.GetElement("places", FlickrPlacesFindByLatLonCollection.Parse); } #endregion #region Static methods /// <summary> /// Gets an instance of <see cref="FlickrPlacesFindByLatLonResponseBody"/> from the specified /// <paramref name="xml"/>. /// </summary> /// <param name="xml">The instance of <see cref="XElement"/> to parse.</param> /// <returns>An instance of <see cref="FlickrPlacesFindByLatLonResponseBody"/>.</returns> public static FlickrPlacesFindByLatLonResponseBody Parse(XElement xml) { return xml == null ? null : new FlickrPlacesFindByLatLonResponseBody(xml); } #endregion } }
36.192308
114
0.641339
[ "MIT" ]
abjerner/Skybrud.Social.Flickr
src/Skybrud.Social.Flickr/Models/Places/FlickrPlacesFindByLatLonResponseBody.cs
1,884
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Faker.Resources { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class App { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal App() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Faker.Resources.App", typeof(App).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to {Name.FullName};{Company.Name}. /// </summary> internal static string Author { get { return ResourceManager.GetString("Author", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Redhold;Treeflex;Trippledex;Kanlam;Bigtax;Daltfresh;Toughjoyfax;Mat Lam Tam;Otcom;Tres-Zap;Y-Solowarm;Tresom;Voltsillam;Biodex;Greenlam;Viva;Matsoft;Temp;Zoolab;Subin;Rank;Job;Stringtough;Tin;It;Home Ing;Zamit;Sonsing;Konklab;Alpha;Latlux;Voyatouch;Alphazap;Holdlamis;Zaam-Dox;Sub-Ex;Quo Lux;Bamity;Ventosanzap;Lotstring;Hatity;Tempsoft;Overhold;Fixflex;Konklux;Zontrax;Tampflex;Span;Namfix;Transcof;Stim;Fix San;Sonair;Stronghold;Fintone;Y-find;Opela;Lotlux;Ronstring;Zathin;Duobam;Keylex. /// </summary> internal static string Name { get { return ResourceManager.GetString("Name", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 0.#.#;0.##;#.##;#.#;#.#.#. /// </summary> internal static string VersionFormat { get { return ResourceManager.GetString("VersionFormat", resourceCulture); } } } }
44.274725
543
0.619757
[ "MIT" ]
AdmiringWorm/Faker.NET.Portable
src/Faker/Resources/App.Designer.cs
4,031
C#
#nullable enable using System; using System.Collections.Generic; using UniRx; using UnityEngine; namespace Playdux.src.Store { /// <summary> /// A Playdux state container. The core of Playdux. /// Includes capability to dispatch actions to the store, get the current state, get the current state narrowed by /// a selector, and get an IObservable to the "selected" state. /// </summary> public sealed class Store<TRootState> : IDisposable, IStore<TRootState> where TRootState : class { /// The current state within the store. public TRootState State => stateStream.Value; /// Reduces state according to actions dispatched to the store. private readonly Func<TRootState, IAction, TRootState> rootReducer; /// Holds actions in a defined FIFO order to ensure actions are processed in the order that they are received. private readonly ActionQueue actionQueue; /// A stream of the current state within the store. /// This stream is safely shared to consumers (via ObservableFor) in such a way that consumer cancellation and errors are isolated from the main stream. private readonly BehaviorSubject<TRootState> stateStream; /// Holds side effectors in a collection that preserves priority while also providing fast addition and removal. private readonly SideEffectorCollection<TRootState> sideEffectors = new(); /// Create a new store with a given initial state and reducer public Store(TRootState initialState, Func<TRootState, IAction, TRootState> rootReducer, IEnumerable<ISideEffector<TRootState>>? initialSideEffectors = null) { this.rootReducer = rootReducer; stateStream = new BehaviorSubject<TRootState>(initialState); actionQueue = new ActionQueue(DispatchInternal); if (initialSideEffectors is null) return; foreach (var sideEffector in initialSideEffectors) RegisterSideEffector(sideEffector); Dispatch(new InitializeAction<TRootState>(initialState)); } /// <inheritdoc cref="IActionDispatcher{TRootState}.Dispatch"/> public void Dispatch(IAction action) { ValidateInitializeAction(action); actionQueue.Dispatch(new DispatchedAction(action)); } /// Handles a single dispatched action from the queue, activating pre effects, reducing state, updating state, then activating post effects. private void DispatchInternal(DispatchedAction dispatchedAction) { // Pre Effects foreach (var sideEffector in sideEffectors.ByPriority) { try { var shouldAllow = sideEffector.PreEffect(dispatchedAction, this); if (!shouldAllow) dispatchedAction = dispatchedAction with { IsCanceled = true }; } catch (Exception e) { Debug.LogException(new SideEffectorExecutionException(SideEffectorType.Pre, e)); } } if (dispatchedAction.IsCanceled) return; // Reduce var action = dispatchedAction.Action; var state = State; if (action is InitializeAction<TRootState> castAction) state = castAction.InitialState; state = rootReducer(state, action); // Update State stateStream.OnNext(state); // Post Effects foreach (var sideEffector in sideEffectors.ByPriority) { try { sideEffector.PostEffect(dispatchedAction, this); } catch (Exception e) { Debug.LogException(new SideEffectorExecutionException(SideEffectorType.Post, e)); } } } /// <inheritdoc cref="IActionDispatcher{TRootState}.RegisterSideEffector"/> public Guid RegisterSideEffector(ISideEffector<TRootState> sideEffector) => sideEffectors.Register(sideEffector); /// <inheritdoc cref="IActionDispatcher{TRootState}.UnregisterSideEffector"/> public void UnregisterSideEffector(Guid sideEffectorId) => sideEffectors.Unregister(sideEffectorId); /// <inheritdoc cref="IStateContainer{TRootState}.Select{TSelectedState}"/> public TSelectedState Select<TSelectedState>(Func<TRootState, TSelectedState> selector) => selector(State); /// <inheritdoc cref="IStateContainer{TRootState}.ObservableFor{TSelectedState}"/> public IObservable<TSelectedState> ObservableFor<TSelectedState>(Func<TRootState, TSelectedState> selector, bool notifyImmediately = false) => Observable.Create<TRootState>(observer => stateStream.Subscribe( onNext: next => { try { observer.OnNext(next); } catch (Exception e) { observer.OnError(e); } }, observer.OnError, observer.OnCompleted )) .StartWith(State) .Select(selector) .DistinctUntilChanged() .Skip(notifyImmediately ? 0 : 1); /// Throws an error if an incorrectly typed InitializeAction is dispatched to this store. private static void ValidateInitializeAction(IAction action) { var actionType = action.GetType(); var isInitializeAction = actionType.IsGenericType && actionType.GetGenericTypeDefinition() == typeof(InitializeAction<>); var isInitializeActionCorrectType = isInitializeAction && action is InitializeAction<TRootState>; if (isInitializeAction && !isInitializeActionCorrectType) throw new InitializeTypeMismatchException(actionType.GetGenericArguments()[0], typeof(TRootState)); } /// <inheritdoc cref="IDisposable.Dispose"/> public void Dispose() => stateStream.Dispose(); } }
47.685484
169
0.657534
[ "MIT" ]
schultzcole/AReSSO
src/Store/Store.cs
5,913
C#
using System; namespace Reactor.API.Attributes { [Obsolete("Use IManager.GetMod(string modId).Instance to communicate between the mods instead." + "\nThis will be removed in Centrifuge 4.0.")] [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = false)] public class MessageHandlerAttribute : Attribute { public string SourceModID { get; } public string MessageName { get; } public MessageHandlerAttribute(string sourceModId, string messageName) { SourceModID = sourceModId; MessageName = messageName; } } }
31.6
101
0.664557
[ "MIT" ]
Centrifuge-Modding-Framework/Centrifuge
Reactor.API/Attributes/MessageHandlerAttribute.cs
634
C#
using System.Collections.Generic; using UnityEngine; using Toolkits.NodeEditor; namespace TimeStranded.Quests { /// <summary> /// Stores data for the quest node editor. /// </summary> [CreateAssetMenu(fileName = "NewQuestEditorData", menuName = "Time Stranded/Quests/Quest Editor Data")] public class QuestEditorDataSO : BaseEditorDataSO { /// <summary> /// The list of all quest nodes used by the editor. /// </summary> public List<QuestNodeData> QuestNodes = new List<QuestNodeData>(); /// <summary> /// The quests organized by their guid. /// </summary> private Dictionary<string, QuestSO> _questsByGuid = null; /// <summary> /// Gets a quest by guid. /// </summary> /// <param name="guid">The quest's guid.</param> /// <returns>The quest.</returns> public QuestSO GetQuest(string guid) { if (_questsByGuid == null) { _questsByGuid = new Dictionary<string, QuestSO>(); for (int i = QuestNodes.Count - 1; i >= 0; i--) { QuestNodeData questData = QuestNodes[i]; _questsByGuid.Add(questData.Guid, questData.Quest); } } return _questsByGuid[guid]; } } }
30.355556
107
0.554173
[ "CC0-1.0" ]
wdmatthews/time-stranded
Assets/TimeStranded/Scripts/Quests/QuestEditorDataSO.cs
1,366
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.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Text; using Silk.NET.Core; using Silk.NET.Core.Native; using Silk.NET.Core.Attributes; using Silk.NET.Core.Contexts; using Silk.NET.Core.Loader; using Silk.NET.OpenGLES; using Extension = Silk.NET.Core.Attributes.ExtensionAttribute; #pragma warning disable 1591 namespace Silk.NET.OpenGLES.Extensions.EXT { [Extension("EXT_external_buffer")] public unsafe partial class ExtExternalBuffer : NativeExtension<GL> { public const string ExtensionName = "EXT_external_buffer"; [NativeApi(EntryPoint = "glBufferStorageExternalEXT")] public partial void BufferStorageExternal([Flow(FlowDirection.In)] EXT target, [Flow(FlowDirection.In)] nint offset, [Flow(FlowDirection.In)] nuint size, [Flow(FlowDirection.In)] nint clientBuffer, [Flow(FlowDirection.In)] uint flags); [NativeApi(EntryPoint = "glBufferStorageExternalEXT")] public partial void BufferStorageExternal([Flow(FlowDirection.In)] EXT target, [Flow(FlowDirection.In)] nint offset, [Flow(FlowDirection.In)] nuint size, [Flow(FlowDirection.In)] nint clientBuffer, [Flow(FlowDirection.In)] BufferStorageMask flags); [NativeApi(EntryPoint = "glNamedBufferStorageExternalEXT")] public partial void NamedBufferStorageExternal([Flow(FlowDirection.In)] uint buffer, [Flow(FlowDirection.In)] nint offset, [Flow(FlowDirection.In)] nuint size, [Flow(FlowDirection.In)] nint clientBuffer, [Flow(FlowDirection.In)] uint flags); [NativeApi(EntryPoint = "glNamedBufferStorageExternalEXT")] public partial void NamedBufferStorageExternal([Flow(FlowDirection.In)] uint buffer, [Flow(FlowDirection.In)] nint offset, [Flow(FlowDirection.In)] nuint size, [Flow(FlowDirection.In)] nint clientBuffer, [Flow(FlowDirection.In)] BufferStorageMask flags); public ExtExternalBuffer(INativeContext ctx) : base(ctx) { } } }
50.47619
262
0.75283
[ "MIT" ]
DmitryGolubenkov/Silk.NET
src/OpenGL/Extensions/Silk.NET.OpenGLES.Extensions.EXT/ExtExternalBuffer.gen.cs
2,120
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Http; namespace Essensoft.AspNetCore.Payment.Alipay { /// <summary> /// Alipay 通知解析客户端。 /// </summary> public interface IAlipayNotifyClient { /// <summary> /// 执行Alipay通知请求解析。 /// </summary> /// <typeparam name="T">领域对象</typeparam> /// <param name="request">控制器的请求</param> /// <returns>领域对象</returns> Task<T> ExecuteAsync<T>(HttpRequest request) where T : AlipayNotify; /// <summary> /// 执行Alipay通知请求解析。 /// </summary> /// <typeparam name="T">领域对象</typeparam> /// <param name="request">控制器的请求</param> /// <param name="optionsName">配置选项名称</param> /// <returns>领域对象</returns> Task<T> ExecuteAsync<T>(HttpRequest request, string optionsName) where T : AlipayNotify; } }
30.034483
96
0.586682
[ "MIT" ]
AkonCoder/Payment
src/Essensoft.AspNetCore.Payment.Alipay/IAlipayNotifyClient.cs
993
C#
/* * Copyright 2012-2021 The Pkcs11Interop Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <[email protected]> */ using System; using System.Collections.Generic; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.HighLevelAPI; using NUnit.Framework; // Note: Code in this file is maintained manually. namespace Net.Pkcs11Interop.Tests.HighLevelAPI { /// <summary> /// Pkcs11UriUtils tests /// </summary> [TestFixture()] public partial class _27_Pkcs11UriUtilsTest { /// <summary> /// Demonstration of PKCS#11 URI usage in a signature creation application /// </summary> [Test()] public void _01_Pkcs11UriInSignatureCreationApplication() { // PKCS#11 URI can be acquired i.e. from configuration file as a simple string... string uri = @"<pkcs11:serial=7BFF2737350B262C; type=private; object=John%20Doe ?module-path=pkcs11.dll& pin-value=11111111>"; Assert.IsNotNull(uri); // ...or it can be easily constructed with Pkcs11UriBuilder Pkcs11UriBuilder pkcs11UriBuilder = new Pkcs11UriBuilder(); pkcs11UriBuilder.Serial = "7BFF2737350B262C"; pkcs11UriBuilder.Type = CKO.CKO_PRIVATE_KEY; pkcs11UriBuilder.Object = "John Doe"; pkcs11UriBuilder.ModulePath = "pkcs11.dll"; pkcs11UriBuilder.PinValue = "11111111"; uri = pkcs11UriBuilder.ToString(); Assert.IsNotNull(uri); // Warning: Please note that PIN stored in PKCS#11 URI can pose a security risk and therefore other options // should be carefully considered. For example an application may ask for a PIN with a GUI dialog etc. // Use PKCS#11 URI acquired from Settings class to identify private key in signature creation method byte[] signature = SignData(ConvertUtils.Utf8StringToBytes("Hello world"), Settings.PrivateKeyUri); // Do something interesting with the signature Assert.IsNotNull(signature); } /// <summary> /// Creates the PKCS#1 v1.5 RSA signature with SHA-1 mechanism /// </summary> /// <param name="data">Data that should be signed</param> /// <param name="uri">PKCS#11 URI identifying PKCS#11 library, token and private key</param> /// <returns>PKCS#1 v1.5 RSA signature</returns> private byte[] SignData(byte[] data, string uri) { // Verify input parameters if (data == null) throw new ArgumentNullException("data"); if (string.IsNullOrEmpty(uri)) throw new ArgumentNullException("uri"); // Parse PKCS#11 URI Pkcs11Uri pkcs11Uri = new Pkcs11Uri(uri); // Verify that URI contains all information required to perform this operation if (pkcs11Uri.ModulePath == null) throw new Exception("PKCS#11 URI does not specify PKCS#11 library"); if (pkcs11Uri.PinValue == null) throw new Exception("PKCS#11 URI does not specify PIN"); if (!pkcs11Uri.DefinesObject || pkcs11Uri.Type != CKO.CKO_PRIVATE_KEY) throw new Exception("PKCS#11 URI does not specify private key"); // Load and initialize PKCS#11 library specified by URI using (IPkcs11Library pkcs11Library = Settings.Factories.Pkcs11LibraryFactory.LoadPkcs11Library(Settings.Factories, pkcs11Uri.ModulePath, AppType.MultiThreaded)) { // Obtain a list of all slots with tokens that match URI List<ISlot> slots = Pkcs11UriUtils.GetMatchingSlotList(pkcs11Uri, pkcs11Library, SlotsType.WithTokenPresent); if ((slots == null) || (slots.Count == 0)) throw new Exception("None of the slots matches PKCS#11 URI"); // Open read only session with first token that matches URI using (ISession session = slots[0].OpenSession(SessionType.ReadOnly)) { // Login as normal user with PIN acquired from URI session.Login(CKU.CKU_USER, pkcs11Uri.PinValue); // Get list of object attributes for the private key specified by URI List<IObjectAttribute> searchTemplate = Pkcs11UriUtils.GetObjectAttributes(pkcs11Uri, session.Factories.ObjectAttributeFactory); // Find private key specified by URI List<IObjectHandle> foundObjects = session.FindAllObjects(searchTemplate); if ((foundObjects == null) || (foundObjects.Count == 0)) throw new Exception("None of the private keys match PKCS#11 URI"); // Create signature with the private key specified by URI using (IMechanism mechanism = session.Factories.MechanismFactory.Create(CKM.CKM_SHA1_RSA_PKCS)) return session.Sign(mechanism, foundObjects[0], data); } } } } }
44.090909
173
0.623368
[ "Apache-2.0" ]
Pkcs11Interop/Pkcs11Interop
src/Pkcs11Interop.Tests/HighLevelAPI/_27_Pkcs11UriUtilsTest.cs
5,822
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace com.csutil.http.apis { public static class GoogleSheetsV4 { public static async Task<List<List<string>>> GetSheet(string apiKey, string spreadsheetId, string sheetName) { Response resp = await GetApiUrlFor(apiKey, spreadsheetId, sheetName).SendGET().GetResult<Response>(); return resp.values; } /// <summary> Loads the sheet content </summary> /// <param name="apiKey"> Create your key at https://console.developers.google.com/apis/credentials </param> /// <param name="spreadsheetId"> The sheet id from the link, e.g.: https://docs.google.com/spreadsheets/d/abcd123 </param> public static async Task<Response> GetDocument(string apiKey, string spreadsheetId, string sheetName) { return await GetApiUrlFor(apiKey, spreadsheetId, sheetName).SendGET().GetResult<Response>(); } public static Uri GetShareLinkFor(string spreadsheetId) { return new Uri("https://docs.google.com/spreadsheets/d/" + spreadsheetId); } /// <summary> See https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets.values/get </summary> public static Uri GetApiUrlFor(string apiKey, string spreadsheetId, string sheetName) { return new Uri($"https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{sheetName}?key={apiKey}"); } public class Response { public string range { get; set; } public string majorDimension { get; set; } public List<List<string>> values { get; set; } } } }
43.871795
130
0.668615
[ "Apache-2.0" ]
cs-util-com/cscore
CsCore/PlainNetClassLib/src/Plugins/CsCore/com/csutil/http/apis/GoogleSheetsV4.cs
1,711
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using Microsoft.Azure.Devices.Client; using Newtonsoft.Json; using System.Text; using System.Threading.Tasks; namespace VibrationDevice { class Program { // Telemetry globals. private const int intervalInMilliseconds = 2000; // Time interval required by wait function. // IoT Hub global variables. private static DeviceClient deviceClient; // The device connection string to authenticate the device with your IoT hub. private readonly static string deviceConnectionString = "<your device connection string>"; private static void Main(string[] args) { ConsoleHelper.WriteColorMessage("Vibration sensor device app.\n", ConsoleColor.Yellow); // Connect to the IoT hub using the MQTT protocol. deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, TransportType.Mqtt); SendDeviceToCloudMessagesAsync(); Console.ReadLine(); } // Async method to send simulated telemetry. private static async void SendDeviceToCloudMessagesAsync() { var conveyor = new ConveyorBeltSimulator(intervalInMilliseconds); // Simulate the vibration telemetry of a conveyor belt. while (true) { var vibration = conveyor.ReadVibration(); await CreateTelemetryMessage(conveyor, vibration); await CreateLoggingMessage(conveyor, vibration); await Task.Delay(intervalInMilliseconds); } } private static async Task CreateTelemetryMessage(ConveyorBeltSimulator conveyor, double vibration) { var telemetryDataPoint = new { vibration = vibration, }; var telemetryMessageString = JsonConvert.SerializeObject(telemetryDataPoint); var telemetryMessage = new Message(Encoding.ASCII.GetBytes(telemetryMessageString)); // Add a custom application property to the message. This is used to route the message. telemetryMessage.Properties.Add("sensorID", "VSTel"); // Send an alert if the belt has been stopped for more than five seconds. telemetryMessage.Properties.Add("beltAlert", (conveyor.BeltStoppedSeconds > 5) ? "true" : "false"); Console.WriteLine($"Telemetry data: {telemetryMessageString}"); // Send the telemetry message. await deviceClient.SendEventAsync(telemetryMessage); ConsoleHelper.WriteGreenMessage($"Telemetry sent {DateTime.Now.ToShortTimeString()}"); } private static async Task CreateLoggingMessage(ConveyorBeltSimulator conveyor, double vibration) { // Create the logging JSON message. var loggingDataPoint = new { vibration = Math.Round(vibration, 2), packages = conveyor.PackageCount, speed = conveyor.BeltSpeed.ToString(), temp = Math.Round(conveyor.Temperature, 2), }; var loggingMessageString = JsonConvert.SerializeObject(loggingDataPoint); var loggingMessage = new Message(Encoding.ASCII.GetBytes(loggingMessageString)); // Add a custom application property to the message. This is used to route the message. loggingMessage.Properties.Add("sensorID", "VSLog"); // Send an alert if the belt has been stopped for more than five seconds. loggingMessage.Properties.Add("beltAlert", (conveyor.BeltStoppedSeconds > 5) ? "true" : "false"); Console.WriteLine($"Log data: {loggingMessageString}"); // Send the logging message. await deviceClient.SendEventAsync(loggingMessage); ConsoleHelper.WriteGreenMessage("Log data sent\n"); } } internal class ConveyorBeltSimulator { Random rand = new Random(); private readonly int intervalInSeconds; // Conveyor belt globals. public enum SpeedEnum { stopped, slow, fast } private int packageCount = 0; // Count of packages leaving the conveyor belt. private SpeedEnum beltSpeed = SpeedEnum.stopped; // Initial state of the conveyor belt. private readonly double slowPackagesPerSecond = 1; // Packages completed at slow speed/ per second private readonly double fastPackagesPerSecond = 2; // Packages completed at fast speed/ per second private double beltStoppedSeconds = 0; // Time the belt has been stopped. private double temperature = 60; // Ambient temperature of the facility. private double seconds = 0; // Time conveyor belt is running. // Vibration globals. private double forcedSeconds = 0; // Time since forced vibration started. private double increasingSeconds = 0; // Time since increasing vibration started. private double naturalConstant; // Constant identifying the severity of natural vibration. private double forcedConstant = 0; // Constant identifying the severity of forced vibration. private double increasingConstant = 0; // Constant identifying the severity of increasing vibration. public double BeltStoppedSeconds { get => beltStoppedSeconds; } public int PackageCount { get => packageCount; } public double Temperature { get => temperature; } public SpeedEnum BeltSpeed { get => beltSpeed; } internal ConveyorBeltSimulator(int intervalInMilliseconds) { // Create a number between 2 and 4, as a constant for normal vibration levels. naturalConstant = 2 + 2 * rand.NextDouble(); intervalInSeconds = intervalInMilliseconds / 1000; // Time interval in seconds. } internal double ReadVibration() { double vibration; // Randomly adjust belt speed. switch (beltSpeed) { case SpeedEnum.fast: if (rand.NextDouble() < 0.01) { beltSpeed = SpeedEnum.stopped; } if (rand.NextDouble() > 0.95) { beltSpeed = SpeedEnum.slow; } break; case SpeedEnum.slow: if (rand.NextDouble() < 0.01) { beltSpeed = SpeedEnum.stopped; } if (rand.NextDouble() > 0.95) { beltSpeed = SpeedEnum.fast; } break; case SpeedEnum.stopped: if (rand.NextDouble() > 0.75) { beltSpeed = SpeedEnum.slow; } break; } // Set vibration levels. if (beltSpeed == SpeedEnum.stopped) { // If the belt is stopped, all vibration comes to a halt. forcedConstant = 0; increasingConstant = 0; vibration = 0; // Record how much time the belt is stopped, in case we need to send an alert. beltStoppedSeconds += intervalInSeconds; } else { // Conveyor belt is running. beltStoppedSeconds = 0; // Check for random starts in unwanted vibrations. // Check forced vibration. if (forcedConstant == 0) { if (rand.NextDouble() < 0.1) { // Forced vibration starts. forcedConstant = 1 + 6 * rand.NextDouble(); // A number between 1 and 7. if (beltSpeed == SpeedEnum.slow) forcedConstant /= 2; // Lesser vibration if slower speeds. forcedSeconds = 0; ConsoleHelper.WriteRedMessage($"Forced vibration starting with severity: {Math.Round(forcedConstant, 2)}"); } } else { if (rand.NextDouble() > 0.99) { forcedConstant = 0; ConsoleHelper.WriteGreenMessage("Forced vibration stopped"); } else { ConsoleHelper.WriteRedMessage($"Forced vibration: {Math.Round(forcedConstant, 1)} started at: {DateTime.Now.ToShortTimeString()}"); } } // Check increasing vibration. if (increasingConstant == 0) { if (rand.NextDouble() < 0.05) { // Increasing vibration starts. increasingConstant = 100 + 100 * rand.NextDouble(); // A number between 100 and 200. if (beltSpeed == SpeedEnum.slow) increasingConstant *= 2; // Longer period if slower speeds. increasingSeconds = 0; ConsoleHelper.WriteRedMessage($"Increasing vibration starting with severity: {Math.Round(increasingConstant, 2)}"); } } else { if (rand.NextDouble() > 0.99) { increasingConstant = 0; ConsoleHelper.WriteGreenMessage("Increasing vibration stopped"); } else { ConsoleHelper.WriteRedMessage($"Increasing vibration: {Math.Round(increasingConstant, 1)} started at: {DateTime.Now.ToShortTimeString()}"); } } // Apply the vibrations, starting with natural vibration. vibration = naturalConstant * Math.Sin(seconds); if (forcedConstant > 0) { // Add forced vibration. vibration += forcedConstant * Math.Sin(0.75 * forcedSeconds) * Math.Sin(10 * forcedSeconds); forcedSeconds += intervalInSeconds; } if (increasingConstant > 0) { // Add increasing vibration. vibration += (increasingSeconds / increasingConstant) * Math.Sin(increasingSeconds); increasingSeconds += intervalInSeconds; } } // Increment the time since the conveyor belt app started. seconds += intervalInSeconds; // Count the packages that have completed their journey. switch (beltSpeed) { case SpeedEnum.fast: packageCount += (int)(fastPackagesPerSecond * intervalInSeconds); break; case SpeedEnum.slow: packageCount += (int)(slowPackagesPerSecond * intervalInSeconds); break; case SpeedEnum.stopped: // No packages! break; } // Randomly vary ambient temperature. temperature += rand.NextDouble() - 0.5d; return vibration; } } internal static class ConsoleHelper { internal static void WriteColorMessage(string text, ConsoleColor clr) { Console.ForegroundColor = clr; Console.WriteLine(text); Console.ResetColor(); } internal static void WriteGreenMessage(string text) { WriteColorMessage(text, ConsoleColor.Green); } internal static void WriteRedMessage(string text) { WriteColorMessage(text, ConsoleColor.Red); } } }
41.151613
163
0.529278
[ "MIT" ]
ChrisHowd/MSLearnLabs-AZ-220-Microsoft-Azure-IoT-Developer
Allfiles/Labs/07-Device Message Routing/Starter/VibrationDevice/Program.cs
12,759
C#
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using dnlib.DotNet; using dnSpy.Analyzer.Properties; using dnSpy.Contracts.Highlighting; using dnSpy.Contracts.Images; using dnSpy.Contracts.Languages; using dnSpy.Contracts.TreeView; using dnSpy.Decompiler.Shared; using dnSpy.Shared.Files.TreeView; using dnSpy.Shared.Highlighting; namespace dnSpy.Analyzer.TreeNodes { sealed class EventNode : EntityNode { readonly EventDef analyzedEvent; readonly bool hidesParent; public EventNode(EventDef analyzedEvent, bool hidesParent = false) { if (analyzedEvent == null) throw new ArgumentNullException("analyzedEvent"); this.analyzedEvent = analyzedEvent; this.hidesParent = hidesParent; } public override void Initialize() { this.TreeNode.LazyLoading = true; } public override IMemberRef Member { get { return analyzedEvent; } } public override IMDTokenProvider Reference { get { return analyzedEvent; } } protected override ImageReference GetIcon(IDotNetImageManager dnImgMgr) { return dnImgMgr.GetImageReference(analyzedEvent); } protected override void Write(ISyntaxHighlightOutput output, ILanguage language) { if (hidesParent) { output.Write("(", TextTokenKind.Operator); output.Write(dnSpy_Analyzer_Resources.HidesParent, TextTokenKind.Text); output.Write(")", TextTokenKind.Operator); output.WriteSpace(); } language.WriteType(output, analyzedEvent.DeclaringType, true); output.Write(".", TextTokenKind.Operator); new NodePrinter().Write(output, language, analyzedEvent, Context.ShowToken); } public override IEnumerable<ITreeNodeData> CreateChildren() { if (analyzedEvent.AddMethod != null) yield return new EventAccessorNode(analyzedEvent.AddMethod, dnSpy_Analyzer_Resources.EventAdderTreeNodeName); if (analyzedEvent.RemoveMethod != null) yield return new EventAccessorNode(analyzedEvent.RemoveMethod, dnSpy_Analyzer_Resources.EventRemoverTreeNodeName); foreach (var accessor in analyzedEvent.OtherMethods) yield return new EventAccessorNode(accessor, null); if (EventFiredByNode.CanShow(analyzedEvent)) yield return new EventFiredByNode(analyzedEvent); if (EventOverridesNode.CanShow(analyzedEvent)) yield return new EventOverridesNode(analyzedEvent); if (InterfaceEventImplementedByNode.CanShow(analyzedEvent)) yield return new InterfaceEventImplementedByNode(analyzedEvent); } public static IAnalyzerTreeNodeData TryCreateAnalyzer(IMemberRef member, ILanguage language) { if (CanShow(member, language)) return new EventNode(member as EventDef); else return null; } public static bool CanShow(IMemberRef member, ILanguage language) { var eventDef = member as EventDef; if (eventDef == null) return false; return !language.ShowMember(eventDef.AddMethod ?? eventDef.RemoveMethod) || EventOverridesNode.CanShow(eventDef); } } }
37.546296
118
0.771147
[ "MIT" ]
blackunixteam/dnSpy
Analyzer/TreeNodes/EventNode.cs
4,057
C#