content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// This code was generated by Hypar. // Edits to this code will be overwritten the next time you run 'hypar init'. // DO NOT EDIT THIS FILE. using Amazon; using Amazon.Lambda.Core; using Hypar.Functions.Execution; using Hypar.Functions.Execution.AWS; using System; using System.IO; using System.Reflection; using System.Threading.Tasks; [assembly: LambdaSerializer(typeof(Amazon.Lambda.Serialization.Json.JsonSerializer))] namespace EnvelopBySketchNew { public class Function { // Cache the model store for use by subsequent // executions of this lambda. private IModelStore<EnvelopBySketchNewInputs> store; public async Task<EnvelopBySketchNewOutputs> Handler(EnvelopBySketchNewInputs args, ILambdaContext context) { if(this.store == null) { // Preload the dependencies (if they exist), // so that they are available during model deserialization. var asmLocation = this.GetType().Assembly.Location; var asmDir = Path.GetDirectoryName(asmLocation); var asmName = Path.GetFileNameWithoutExtension(asmLocation); var depPath = Path.Combine(asmDir, $"{asmName}.Dependencies.dll"); if(File.Exists(depPath)) { Console.WriteLine($"Loading dependencies from assembly: {depPath}..."); Assembly.LoadFrom(depPath); Console.WriteLine("Dependencies assembly loaded."); } this.store = new S3ModelStore<EnvelopBySketchNewInputs>(RegionEndpoint.USWest1); } var l = new InvocationWrapper<EnvelopBySketchNewInputs,EnvelopBySketchNewOutputs>(store, EnvelopBySketchNew.Execute); var output = await l.InvokeAsync(args); return output; } } }
38.918367
129
0.636078
[ "MIT" ]
tkahng/HyparFunctionsTests
EnvelopBySketchNew/src/Function.g.cs
1,907
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ #nullable enable namespace DependentSchemasDraft202012Feature.BooleanSubschemas { using System; using System.Collections.Immutable; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using Corvus.Json; /// <summary> /// A type generated from a JsonSchema specification. /// </summary> public readonly struct Schema : IJsonObject<Schema>, IEquatable<Schema> { private static readonly ImmutableDictionary<string, PropertyValidator<Schema>> __CorvusDependentSchema = CreateDependentSchemaValidators(); private readonly JsonElement jsonElementBacking; private readonly ImmutableDictionary<string, JsonAny>? objectBacking; /// <summary> /// Initializes a new instance of the <see cref="Schema"/> struct. /// </summary> /// <param name="value">The backing <see cref="JsonElement"/>.</param> public Schema(JsonElement value) { this.jsonElementBacking = value; this.objectBacking = default; } /// <summary> /// Initializes a new instance of the <see cref="Schema"/> struct. /// </summary> /// <param name="value">A property dictionary.</param> public Schema(ImmutableDictionary<string, JsonAny> value) { this.jsonElementBacking = default; this.objectBacking = value; } /// <summary> /// Initializes a new instance of the <see cref="Schema"/> struct. /// </summary> /// <param name="jsonObject">The <see cref="JsonObject"/> from which to construct the value.</param> public Schema(JsonObject jsonObject) { if (jsonObject.HasJsonElement) { this.jsonElementBacking = jsonObject.AsJsonElement; this.objectBacking = default; } else { this.jsonElementBacking = default; this.objectBacking = jsonObject.AsPropertyDictionary; } } /// <summary> /// Gets a value indicating whether this is backed by a JSON element. /// </summary> public bool HasJsonElement => this.objectBacking is null ; /// <summary> /// Gets the value as a JsonElement. /// </summary> public JsonElement AsJsonElement { get { if (this.objectBacking is ImmutableDictionary<string, JsonAny> objectBacking) { return JsonObject.PropertiesToJsonElement(objectBacking); } return this.jsonElementBacking; } } /// <inheritdoc/> public JsonValueKind ValueKind { get { if (this.objectBacking is ImmutableDictionary<string, JsonAny>) { return JsonValueKind.Object; } return this.jsonElementBacking.ValueKind; } } /// <inheritdoc/> public JsonAny AsAny { get { if (this.objectBacking is ImmutableDictionary<string, JsonAny> objectBacking) { return new JsonAny(objectBacking); } return new JsonAny(this.jsonElementBacking); } } /// <summary> /// Conversion from any. /// </summary> /// <param name="value">The value from which to convert.</param> public static implicit operator Schema(JsonAny value) { if (value.HasJsonElement) { return new Schema(value.AsJsonElement); } return value.As<Schema>(); } /// <summary> /// Conversion to any. /// </summary> /// <param name="value">The value from which to convert.</param> public static implicit operator JsonAny(Schema value) { return value.AsAny; } /// <summary> /// Conversion from object. /// </summary> /// <param name="value">The value from which to convert.</param> public static implicit operator Schema(JsonObject value) { return new Schema(value); } /// <summary> /// Conversion to object. /// </summary> /// <param name="value">The value from which to convert.</param> public static implicit operator JsonObject(Schema value) { return value.AsObject; } /// <summary> /// Implicit conversion to a property dictionary. /// </summary> /// <param name="value">The value from which to convert.</param> public static implicit operator ImmutableDictionary<string, JsonAny>(Schema value) { return value.AsObject.AsPropertyDictionary; } /// <summary> /// Implicit conversion from a property dictionary. /// </summary> /// <param name="value">The value from which to convert.</param> public static implicit operator Schema (ImmutableDictionary<string, JsonAny> value) { return new Schema (value); } /// <summary> /// Standard equality operator. /// </summary> /// <param name="lhs">The left hand side of the comparison.</param> /// <param name="rhs">The right hand side of the comparison.</param> /// <returns>True if they are equal.</returns> public static bool operator ==(Schema lhs, Schema rhs) { return lhs.Equals(rhs); } /// <summary> /// Standard inequality operator. /// </summary> /// <param name="lhs">The left hand side of the comparison.</param> /// <param name="rhs">The right hand side of the comparison.</param> /// <returns>True if they are not equal.</returns> public static bool operator !=(Schema lhs, Schema rhs) { return !lhs.Equals(rhs); } /// <inheritdoc/> public override bool Equals(object? obj) { if (obj is Schema entity) { return this.Equals(entity); } return false; } /// <inheritdoc/> public override int GetHashCode() { JsonValueKind valueKind = this.ValueKind; return valueKind switch { JsonValueKind.Object => this.AsObject.GetHashCode(), JsonValueKind.Array => this.AsArray().GetHashCode(), JsonValueKind.Number => this.AsNumber().GetHashCode(), JsonValueKind.String => this.AsString().GetHashCode(), JsonValueKind.True or JsonValueKind.False => this.AsBoolean().GetHashCode(), JsonValueKind.Null => JsonNull.NullHashCode, _ => JsonAny.UndefinedHashCode, }; } /// <summary> /// Writes the object to the <see cref="Utf8JsonWriter"/>. /// </summary> /// <param name="writer">The writer to which to write the object.</param> public void WriteTo(Utf8JsonWriter writer) { if (this.objectBacking is ImmutableDictionary<string, JsonAny> objectBacking) { JsonObject.WriteProperties(objectBacking, writer); return; } if (this.jsonElementBacking.ValueKind != JsonValueKind.Undefined) { this.jsonElementBacking.WriteTo(writer); return; } writer.WriteNullValue(); } /// <inheritdoc/> public JsonObjectEnumerator EnumerateObject() { return this.AsObject.EnumerateObject(); } /// <inheritdoc/> public bool TryGetProperty(string name, out JsonAny value) { return this.AsObject.TryGetProperty(name, out value); } /// <inheritdoc/> public bool TryGetProperty(ReadOnlySpan<char> name, out JsonAny value) { return this.AsObject.TryGetProperty(name, out value); } /// <inheritdoc/> public bool TryGetProperty(ReadOnlySpan<byte> utf8name, out JsonAny value) { return this.AsObject.TryGetProperty(utf8name, out value); } /// <inheritdoc/> public bool Equals<T>(T other) where T : struct, IJsonValue { JsonValueKind valueKind = this.ValueKind; if (other.ValueKind != valueKind) { return false; } return valueKind switch { JsonValueKind.Object => this.AsObject.Equals(other.AsObject()), JsonValueKind.Array => this.AsArray().Equals(other.AsArray()), JsonValueKind.Number => this.AsNumber().Equals(other.AsNumber()), JsonValueKind.String => this.AsString().Equals(other.AsString()), JsonValueKind.True or JsonValueKind.False => this.AsBoolean().Equals(other.AsBoolean()), JsonValueKind.Null => true, _ => false, }; } /// <inheritdoc/> public bool Equals(Schema other) { JsonValueKind valueKind = this.ValueKind; if (other.ValueKind != valueKind) { return false; } return valueKind switch { JsonValueKind.Object => this.AsObject.Equals(other.AsObject), JsonValueKind.Array => this.AsArray().Equals(other.AsArray()), JsonValueKind.Number => this.AsNumber().Equals(other.AsNumber()), JsonValueKind.String => this.AsString().Equals(other.AsString()), JsonValueKind.True or JsonValueKind.False => this.AsBoolean().Equals(other.AsBoolean()), JsonValueKind.Null => true, _ => false, }; } /// <inheritdoc/> public bool HasProperty(string name) { if (this.objectBacking is ImmutableDictionary<string, JsonAny> properties) { return properties.TryGetValue(name, out _); } if (this.jsonElementBacking.ValueKind == JsonValueKind.Object) { return this.jsonElementBacking.TryGetProperty(name.ToString(), out JsonElement _); } return false; } /// <inheritdoc/> public bool HasProperty(ReadOnlySpan<char> name) { if (this.objectBacking is ImmutableDictionary<string, JsonAny> properties) { return properties.TryGetValue(name.ToString(), out _); } if (this.jsonElementBacking.ValueKind == JsonValueKind.Object) { return this.jsonElementBacking.TryGetProperty(name, out JsonElement _); } return false; } /// <inheritdoc/> public bool HasProperty(ReadOnlySpan<byte> utf8name) { if (this.objectBacking is ImmutableDictionary<string, JsonAny> properties) { return properties.TryGetValue(System.Text.Encoding.UTF8.GetString(utf8name), out _); } if (this.jsonElementBacking.ValueKind == JsonValueKind.Object) { return this.jsonElementBacking.TryGetProperty(utf8name, out JsonElement _); } return false; } /// <inheritdoc/> public Schema SetProperty<TValue>(string name, TValue value) where TValue : struct, IJsonValue { if (this.ValueKind == JsonValueKind.Object || this.ValueKind == JsonValueKind.Undefined) { return this.AsObject.SetProperty(name, value); } return this; } /// <inheritdoc/> public Schema SetProperty<TValue>(ReadOnlySpan<char> name, TValue value) where TValue : struct, IJsonValue { if (this.ValueKind == JsonValueKind.Object || this.ValueKind == JsonValueKind.Undefined) { return this.AsObject.SetProperty(name, value); } return this; } /// <inheritdoc/> public Schema SetProperty<TValue>(ReadOnlySpan<byte> utf8name, TValue value) where TValue : struct, IJsonValue { if (this.ValueKind == JsonValueKind.Object || this.ValueKind == JsonValueKind.Undefined) { return this.AsObject.SetProperty(utf8name, value); } return this; } /// <inheritdoc/> public Schema RemoveProperty(string name) { if (this.ValueKind == JsonValueKind.Object) { return this.AsObject.RemoveProperty(name); } return this; } /// <inheritdoc/> public Schema RemoveProperty(ReadOnlySpan<char> name) { if (this.ValueKind == JsonValueKind.Object) { return this.AsObject.RemoveProperty(name); } return this; } /// <inheritdoc/> public Schema RemoveProperty(ReadOnlySpan<byte> utf8Name) { if (this.ValueKind == JsonValueKind.Object) { return this.AsObject.RemoveProperty(utf8Name); } return this; } /// <inheritdoc/> public T As<T>() where T : struct, IJsonValue { return this.As<Schema, T>(); } /// <inheritdoc/> public ValidationContext Validate(in ValidationContext? validationContext = null, ValidationLevel level = ValidationLevel.Flag) { ValidationContext result = validationContext ?? ValidationContext.ValidContext; if (level != ValidationLevel.Flag) { result = result.UsingStack(); } JsonValueKind valueKind = this.ValueKind; result = this.ValidateObject(valueKind, result, level); if (level == ValidationLevel.Flag && !result.IsValid) { return result; } return result; } /// <summary> /// Gets the value as a <see cref="JsonObject"/>. /// </summary> private JsonObject AsObject { get { if (this.objectBacking is ImmutableDictionary<string, JsonAny> objectBacking) { return new JsonObject(objectBacking); } return new JsonObject(this.jsonElementBacking); } } private static ImmutableDictionary<string, PropertyValidator<Schema>> CreateDependentSchemaValidators() { ImmutableDictionary<string, PropertyValidator<Schema>>.Builder builder = ImmutableDictionary.CreateBuilder<string, PropertyValidator<Schema>>(); builder.Add( "foo", __CorvusValidateDependentSchema1); builder.Add( "bar", __CorvusValidateDependentSchema2); return builder.ToImmutable(); } private static ValidationContext __CorvusValidateDependentSchema1(in Schema that, in ValidationContext validationContext, ValidationLevel level) { return that.As<Corvus.Json.JsonAny>().Validate(validationContext, level); } private static ValidationContext __CorvusValidateDependentSchema2(in Schema that, in ValidationContext validationContext, ValidationLevel level) { return that.As<Corvus.Json.JsonNotAny>().Validate(validationContext, level); } private ValidationContext ValidateObject(JsonValueKind valueKind, in ValidationContext validationContext, ValidationLevel level) { ValidationContext result = validationContext; if (valueKind != JsonValueKind.Object) { return result; } int propertyCount = 0; foreach (Property property in this.EnumerateObject()) { string propertyName = property.Name; if (__CorvusDependentSchema.TryGetValue(propertyName, out PropertyValidator<Schema>? dependentSchemaValidator)) { result = result.WithLocalProperty(propertyCount); result = dependentSchemaValidator(this, result, level); if (level == ValidationLevel.Flag && !result.IsValid) { return result; } } propertyCount++; } return result; } } }
28.169184
160
0.509063
[ "Apache-2.0" ]
corvus-dotnet/Corvus.JsonSchema
Solutions/Corvus.JsonSchema.Benchmarking/202012/DependentSchemasDraft202012/BooleanSubschemas/Schema.cs
18,648
C#
// Copyright (c) 2018 Jon P Smith, GitHub: JonPSmith, web: http://www.thereformedprogrammer.net/ // Licensed under MIT license. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using BizLogic.Orders; using DataLayer.EfClasses; using GenericBizRunner; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using StatusGeneric; namespace ServiceLayer.OrderServices { public class WebChangeDeliveryDto : GenericActionToBizDto<BizChangeDeliverDto, WebChangeDeliveryDto> { public int OrderId { get; set; } public string UserId { get; set; } public DateTime NewDeliveryDate { get; set; } //--------------------------------------------- //Presentation layer items public string OrderNumber => $"SO{OrderId:D6}"; public DateTime DateOrderedUtc { get; private set; } public DateTime OriginalDeliveryDate { get; private set; } public List<string> BookTitles { get; private set; } public SelectList PossibleDeliveryDates { get; private set; } /// <summary> /// This is set if there are any errors. It is there to stop the Razor page /// accessing the properties, as they won't be set up properly /// </summary> public bool HasErrors { get; private set; } /// <summary> /// This is called by the BizRunner’s GetOriginal or ResetDto methods. /// It sets up the presentation layer properties /// </summary> /// <param name="db">The DbContext to allow access to the database</param> /// <param name="status">The BizActionStatus so you can register errors</param> protected override void SetupSecondaryData(object repository, IStatusGenericHandler status) { if (OrderId == 0) throw new InvalidOperationException("You must set the OrderId before you call SetupSecondaryData"); if (UserId == null) throw new InvalidOperationException("You must set the UserId before you call SetupSecondaryData"); var order = ((DbContext)repository).Set<Order>() .Include(x => x.LineItems).ThenInclude(x => x.ChosenBook) .SingleOrDefault(x => x.OrderId == OrderId); if (order == null) { status.AddError("Sorry, I could not find the order you asked for."); HasErrors = true; //Log possible hacking return; } DateOrderedUtc = order.DateOrderedUtc; OriginalDeliveryDate = order.ExpectedDeliveryDate; NewDeliveryDate = OriginalDeliveryDate < DateTime.Today ? DateTime.Today : OriginalDeliveryDate; BookTitles = order.LineItems.Select(x => x.ChosenBook.Title).ToList(); PossibleDeliveryDates = new SelectList(FormPossibleDeliveryDates(DateTime.Today)); var selected = PossibleDeliveryDates.FirstOrDefault(x => x.Text == NewDeliveryDate.ToString("d")); if (selected != null) selected.Selected = true; } private IEnumerable<string> FormPossibleDeliveryDates(DateTime startDate) { for (int i = 0; i < 10; i++) { yield return startDate.ToString("d"); startDate = startDate.AddDays(1); } } } }
39.303371
115
0.618067
[ "MIT" ]
tchpeng/GenericBizRunner
ServiceLayer/OrderServices/WebChangeDeliveryDto.cs
3,502
C#
// "Therefore those skilled at the unorthodox // are infinite as heaven and earth, // inexhaustible as the great rivers. // When they come to an end, // they begin again, // like the days and months; // they die and are reborn, // like the four seasons." // // - Sun Tsu, // "The Art of War" using DA.HtmlRenderer.Adapters; using PdfSharp.Drawing; namespace DA.HtmlRenderer.PdfSharp.Adapters { /// <summary> /// Adapter for WinForms Image object for core. /// </summary> internal sealed class ImageAdapter : RImage { /// <summary> /// the underline win-forms image. /// </summary> private readonly XImage _image; /// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> public ImageAdapter(XImage image) { _image = image; } /// <summary> /// the underline win-forms image. /// </summary> public XImage Image { get { return _image; } } public override double Width { get { return _image.PixelWidth; } } public override double Height { get { return _image.PixelHeight; } } public override void Dispose() { _image.Dispose(); } } }
23.169492
82
0.553036
[ "BSD-3-Clause" ]
digitalalien/HTML-Renderer
Source/HtmlRenderer.PdfSharp/Adapters/ImageAdapter.cs
1,369
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.17379 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Microsoft.Samples.Kinect.SkeletonBasics.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.Samples.Kinect.SkeletonBasics.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to No ready Kinect found!. /// </summary> internal static string NoKinectReady { get { return ResourceManager.GetString("NoKinectReady", resourceCulture); } } } }
43.068493
205
0.609415
[ "Apache-2.0" ]
rocky20798/SkeletonBasics-WPF
Properties/Resources.Designer.cs
3,144
C#
#if NETFX_CORE using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Media.Animation; #else #endif namespace Charts.WPF.ChartControls { using System.Windows; using System.Windows.Controls; using System.Windows.Media; /// <summary> /// The pie piece label. /// </summary> public class PiePieceLabel : Control { /// <summary> /// The caption property. /// </summary> public static readonly DependencyProperty CaptionProperty = DependencyProperty.Register( "Caption", typeof(string), typeof(PiePieceLabel), new PropertyMetadata(null)); /// <summary> /// The value property. /// </summary> public static readonly DependencyProperty ValueProperty = DependencyProperty.Register( "Value", typeof(double), typeof(PiePieceLabel), new PropertyMetadata(0.0, OnValueChanged)); /// <summary> /// The on value changed. /// </summary> /// <param name="d"> /// The d. /// </param> /// <param name="e"> /// The e. /// </param> private static void OnValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { } /// <summary> /// The percentage property. /// </summary> public static readonly DependencyProperty PercentageProperty = DependencyProperty.Register( "Percentage", typeof(double), typeof(PiePieceLabel), new PropertyMetadata(null)); /// <summary> /// The item brush property. /// </summary> public static readonly DependencyProperty ItemBrushProperty = DependencyProperty.Register( "ItemBrush", typeof(Brush), typeof(PiePieceLabel), new PropertyMetadata(null)); /// <summary> /// Initializes static members of the <see cref="PiePieceLabel"/> class. /// </summary> static PiePieceLabel() { #if NETFX_CORE // do nothing #elif SILVERLIGHT // do nothing #else DefaultStyleKeyProperty.OverrideMetadata(typeof(PiePieceLabel), new FrameworkPropertyMetadata(typeof(PiePieceLabel))); #endif } /// <summary> /// Initializes a new instance of the <see cref="PiePieceLabel"/> class. /// </summary> public PiePieceLabel() { #if NETFX_CORE this.DefaultStyleKey = typeof(PiePieceLabel); #elif SILVERLIGHT this.DefaultStyleKey = typeof(PiePieceLabel); #else // do nothing #endif } /// <summary> /// Gets or sets the caption. /// </summary> public string Caption { get => (string)this.GetValue(CaptionProperty); set => this.SetValue(CaptionProperty, value); } /// <summary> /// Gets or sets the value. /// </summary> public double Value { get => (double)this.GetValue(ValueProperty); set => this.SetValue(ValueProperty, value); } /// <summary> /// Gets or sets the percentage. /// </summary> public double Percentage { get => (double)this.GetValue(PercentageProperty); set => this.SetValue(PercentageProperty, value); } /// <summary> /// Gets or sets the item brush. /// </summary> public Brush ItemBrush { get => (Brush)this.GetValue(ItemBrushProperty); set => this.SetValue(ItemBrushProperty, value); } } }
27.362319
131
0.555614
[ "Apache-2.0" ]
mendonca-andre/Charts.WPF
Charts.WPF/ChartControls/PiePieceLabel.cs
3,778
C#
using ANM.Core.Domain.Abstractions.Events; using ANM.Example.Domain.Wallets; namespace ANM.Example.Domain.Stocks.Events { public class StockBougthDomainEvent : DomainEvent { public StockBougthDomainEvent(Wallet source, Stock entity) : base() { this.Wallet = source; this.Stock = entity; } public Wallet Wallet { get; } public Stock Stock { get; } public static StockBougthDomainEvent Create(Wallet source, Stock entity) { StockBougthDomainEvent domainEvent = new StockBougthDomainEvent(source, entity); return domainEvent; } } }
26.32
92
0.639818
[ "MIT" ]
alesimoes/hexagonal-clean-architecture
source/ANM.Example.Domain/Stocks/Events/StockBougthDomainEvent.cs
660
C#
using DarkUI.Config; using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace DarkUI.Controls { public class DarkCheckBox : CheckBox { #region Field Region private DarkControlState _controlState = DarkControlState.Normal; private bool _spacePressed; #endregion #region Property Region [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new Appearance Appearance { get { return base.Appearance; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new bool AutoEllipsis { get { return base.AutoEllipsis; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new Image BackgroundImage { get { return base.BackgroundImage; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new ImageLayout BackgroundImageLayout { get { return base.BackgroundImageLayout; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new bool FlatAppearance { get { return false; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new FlatStyle FlatStyle { get { return base.FlatStyle; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new Image Image { get { return base.Image; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new ContentAlignment ImageAlign { get { return base.ImageAlign; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new int ImageIndex { get { return base.ImageIndex; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new string ImageKey { get { return base.ImageKey; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new ImageList ImageList { get { return base.ImageList; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new ContentAlignment TextAlign { get { return base.TextAlign; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new TextImageRelation TextImageRelation { get { return base.TextImageRelation; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new bool ThreeState { get { return base.ThreeState; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new bool UseCompatibleTextRendering { get { return false; } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public new bool UseVisualStyleBackColor { get { return false; } } #endregion #region Constructor Region public DarkCheckBox() { SetStyle(ControlStyles.SupportsTransparentBackColor | ControlStyles.OptimizedDoubleBuffer | ControlStyles.ResizeRedraw | ControlStyles.UserPaint, true); } #endregion #region Method Region private void SetControlState(DarkControlState controlState) { if (_controlState != controlState) { _controlState = controlState; Invalidate(); } } #endregion #region Event Handler Region protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (_spacePressed) return; if (e.Button == MouseButtons.Left) { if (ClientRectangle.Contains(e.Location)) SetControlState(DarkControlState.Pressed); else SetControlState(DarkControlState.Hover); } else { SetControlState(DarkControlState.Hover); } } protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); if (!ClientRectangle.Contains(e.Location)) return; SetControlState(DarkControlState.Pressed); } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (_spacePressed) return; SetControlState(DarkControlState.Normal); } protected override void OnMouseLeave(EventArgs e) { base.OnMouseLeave(e); if (_spacePressed) return; SetControlState(DarkControlState.Normal); } protected override void OnMouseCaptureChanged(EventArgs e) { base.OnMouseCaptureChanged(e); if (_spacePressed) return; var location = Cursor.Position; if (!ClientRectangle.Contains(location)) SetControlState(DarkControlState.Normal); } protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); Invalidate(); } protected override void OnLostFocus(EventArgs e) { base.OnLostFocus(e); _spacePressed = false; var location = Cursor.Position; if (!ClientRectangle.Contains(location)) SetControlState(DarkControlState.Normal); else SetControlState(DarkControlState.Hover); } protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (e.KeyCode == Keys.Space) { _spacePressed = true; SetControlState(DarkControlState.Pressed); } } protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); if (e.KeyCode != Keys.Space) return; _spacePressed = false; var location = Cursor.Position; if (!ClientRectangle.Contains(location)) SetControlState(DarkControlState.Normal); else SetControlState(DarkControlState.Hover); } #endregion #region Paint Region protected override void OnPaint(PaintEventArgs e) { var g = e.Graphics; var rect = new Rectangle(0, 0, ClientSize.Width, ClientSize.Height); const int size = Consts.CheckBoxSize; var textColor = Colors.LightText; var borderColor = Colors.LightText; var fillColor = Colors.LightestBackground; Rectangle boxRect, checkBoxRect, labelRect; StringAlignment labelAlignment; switch (CheckAlign) { case ContentAlignment.MiddleRight: boxRect = new Rectangle(rect.Width - size - 2, rect.Height / 2 - size / 2, size, size); checkBoxRect = new Rectangle(rect.Width - size, rect.Height / 2 - (size - 4) / 2, size - 3, size - 3); labelRect = new Rectangle(0, 0, rect.Width - size - 5, rect.Height); labelAlignment = StringAlignment.Far; break; case ContentAlignment.MiddleLeft: default: boxRect = new Rectangle(0, rect.Height / 2 - size / 2, size, size); checkBoxRect = new Rectangle(2, rect.Height / 2 - (size - 4) / 2, size - 3, size - 3); labelRect = new Rectangle(size + 4, 0, rect.Width - size, rect.Height); labelAlignment = StringAlignment.Near; break; } if (Enabled) { if (Focused) { borderColor = Colors.BlueHighlight; fillColor = Colors.BlueSelection; } switch (_controlState) { case DarkControlState.Hover: borderColor = Colors.BlueHighlight; fillColor = Colors.BlueSelection; break; case DarkControlState.Pressed: borderColor = Colors.GreyHighlight; fillColor = Colors.GreySelection; break; } } else { textColor = Colors.DisabledText; borderColor = Colors.GreyHighlight; fillColor = Colors.GreySelection; } using (var b = new SolidBrush(Colors.GreyBackground)) { g.FillRectangle(b, rect); } using (var p = new Pen(borderColor)) { g.DrawRectangle(p, boxRect); } switch (CheckState) { case CheckState.Checked: Rectangle checkBoxRectCross = checkBoxRect; checkBoxRectCross.Inflate(new Size(-1, -1)); using (var p = new Pen(fillColor, 2) { StartCap = LineCap.Round, EndCap = LineCap.Round }) { g.SmoothingMode = SmoothingMode.HighQuality; g.DrawLines(p, new Point[] { new Point(checkBoxRectCross.Left - 1, checkBoxRectCross.Bottom - checkBoxRectCross.Height / 2 - 1), new Point(checkBoxRectCross.Left + checkBoxRectCross.Width / 2 - 1, checkBoxRectCross.Bottom - 1), new Point(checkBoxRectCross.Right - 1, checkBoxRectCross.Top) }); g.SmoothingMode = SmoothingMode.Default; } break; case CheckState.Indeterminate: using (var b = new SolidBrush(fillColor)) g.FillRectangle(b, checkBoxRect); break; } using (var b = new SolidBrush(textColor)) { var stringFormat = new StringFormat { LineAlignment = StringAlignment.Center, Alignment = labelAlignment }; g.DrawString(Text, Font, b, labelRect, stringFormat); } } #endregion } }
30.11658
131
0.539957
[ "MIT" ]
ohhsodead/DarkUI-master
DarkUI/Controls/DarkCheckBox.cs
11,627
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Shoot : MonoBehaviour { public GameObject bullet; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKey("space")) { Instantiate(bullet, transform.position, transform.rotation); } } }
18.782609
73
0.592593
[ "MIT" ]
AdamMinarik/SchoolWorkspace
UnityProjects/2nd lesson/Top Down Shooter/Assets/Shoot.cs
434
C#
namespace Azure.IoT.DeviceUpdate { public partial class DeploymentsClient { protected DeploymentsClient() { } public DeploymentsClient(string accountEndpoint, string instanceId, Azure.Core.TokenCredential credential) { } public DeploymentsClient(string accountEndpoint, string instanceId, Azure.Core.TokenCredential credential, Azure.IoT.DeviceUpdate.DeviceUpdateClientOptions options) { } public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Deployment> CancelDeployment(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Deployment>> CancelDeploymentAsync(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Deployment> CreateOrUpdateDeployment(string deploymentId, Azure.IoT.DeviceUpdate.Models.Deployment deployment, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Deployment>> CreateOrUpdateDeploymentAsync(string deploymentId, Azure.IoT.DeviceUpdate.Models.Deployment deployment, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response DeleteDeployment(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> DeleteDeploymentAsync(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.Deployment> GetAllDeployments(string filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.Deployment> GetAllDeploymentsAsync(string filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Deployment> GetDeployment(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Deployment>> GetDeploymentAsync(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.DeploymentDeviceState> GetDeploymentDevices(string deploymentId, string filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.DeploymentDeviceState> GetDeploymentDevicesAsync(string deploymentId, string filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.DeploymentStatus> GetDeploymentStatus(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.DeploymentStatus>> GetDeploymentStatusAsync(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Deployment> RetryDeployment(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Deployment>> RetryDeploymentAsync(string deploymentId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class DevicesClient { protected DevicesClient() { } public DevicesClient(string accountEndpoint, string instanceId, Azure.Core.TokenCredential credential) { } public DevicesClient(string accountEndpoint, string instanceId, Azure.Core.TokenCredential credential, Azure.IoT.DeviceUpdate.DeviceUpdateClientOptions options) { } public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Group> CreateOrUpdateGroup(string groupId, Azure.IoT.DeviceUpdate.Models.Group group, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Group>> CreateOrUpdateGroupAsync(string groupId, Azure.IoT.DeviceUpdate.Models.Group group, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response DeleteGroup(string groupId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> DeleteGroupAsync(string groupId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.DeviceClass> GetAllDeviceClasses(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.DeviceClass> GetAllDeviceClassesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.Device> GetAllDevices(string filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.Device> GetAllDevicesAsync(string filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.DeviceTag> GetAllDeviceTags(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.DeviceTag> GetAllDeviceTagsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.Group> GetAllGroups(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.Group> GetAllGroupsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Device> GetDevice(string deviceId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Device>> GetDeviceAsync(string deviceId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.DeviceClass> GetDeviceClass(string deviceClassId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.DeviceClass>> GetDeviceClassAsync(string deviceClassId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<string> GetDeviceClassDeviceIds(string deviceClassId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<string> GetDeviceClassDeviceIdsAsync(string deviceClassId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.UpdateId> GetDeviceClassInstallableUpdates(string deviceClassId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.UpdateId> GetDeviceClassInstallableUpdatesAsync(string deviceClassId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.DeviceTag> GetDeviceTag(string tagName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.DeviceTag>> GetDeviceTagAsync(string tagName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Group> GetGroup(string groupId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Group>> GetGroupAsync(string groupId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.UpdatableDevices> GetGroupBestUpdates(string groupId, string filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.UpdatableDevices> GetGroupBestUpdatesAsync(string groupId, string filter = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.UpdateCompliance> GetGroupUpdateCompliance(string groupId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.UpdateCompliance>> GetGroupUpdateComplianceAsync(string groupId, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.UpdateCompliance> GetUpdateCompliance(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.UpdateCompliance>> GetUpdateComplianceAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class DeviceUpdateClientOptions : Azure.Core.ClientOptions { public DeviceUpdateClientOptions(Azure.IoT.DeviceUpdate.DeviceUpdateClientOptions.ServiceVersion version = Azure.IoT.DeviceUpdate.DeviceUpdateClientOptions.ServiceVersion.V2020_09_01) { } public enum ServiceVersion { V2020_09_01 = 1, } } public partial class UpdatesClient { protected UpdatesClient() { } public UpdatesClient(string accountEndpoint, string instanceId, Azure.Core.TokenCredential credential) { } public UpdatesClient(string accountEndpoint, string instanceId, Azure.Core.TokenCredential credential, Azure.IoT.DeviceUpdate.DeviceUpdateClientOptions options) { } public virtual Azure.Response<string> DeleteUpdate(string provider, string name, string version, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<string>> DeleteUpdateAsync(string provider, string name, string version, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.File> GetFile(string provider, string name, string version, string fileId, Azure.IoT.DeviceUpdate.Models.AccessCondition accessCondition = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.File>> GetFileAsync(string provider, string name, string version, string fileId, Azure.IoT.DeviceUpdate.Models.AccessCondition accessCondition = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<string> GetFiles(string provider, string name, string version, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<string> GetFilesAsync(string provider, string name, string version, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<string> GetNames(string provider, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<string> GetNamesAsync(string provider, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Operation> GetOperation(string operationId, Azure.IoT.DeviceUpdate.Models.AccessCondition accessCondition = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Operation>> GetOperationAsync(string operationId, Azure.IoT.DeviceUpdate.Models.AccessCondition accessCondition = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.IoT.DeviceUpdate.Models.Operation> GetOperations(string filter = null, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.IoT.DeviceUpdate.Models.Operation> GetOperationsAsync(string filter = null, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<string> GetProviders(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<string> GetProvidersAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.IoT.DeviceUpdate.Models.Update> GetUpdate(string provider, string name, string version, Azure.IoT.DeviceUpdate.Models.AccessCondition accessCondition = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.IoT.DeviceUpdate.Models.Update>> GetUpdateAsync(string provider, string name, string version, Azure.IoT.DeviceUpdate.Models.AccessCondition accessCondition = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<string> GetVersions(string provider, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<string> GetVersionsAsync(string provider, string name, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<string> ImportUpdate(Azure.IoT.DeviceUpdate.Models.ImportUpdateInput updateToImport, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<string>> ImportUpdateAsync(Azure.IoT.DeviceUpdate.Models.ImportUpdateInput updateToImport, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } } namespace Azure.IoT.DeviceUpdate.Models { public partial class AccessCondition { public AccessCondition() { } public string IfNoneMatch { get { throw null; } set { } } } public partial class Compatibility { internal Compatibility() { } public string DeviceManufacturer { get { throw null; } } public string DeviceModel { get { throw null; } } } public partial class Deployment { public Deployment(string deploymentId, Azure.IoT.DeviceUpdate.Models.DeploymentType deploymentType, System.DateTimeOffset startDateTime, Azure.IoT.DeviceUpdate.Models.DeviceGroupType deviceGroupType, System.Collections.Generic.IEnumerable<string> deviceGroupDefinition, Azure.IoT.DeviceUpdate.Models.UpdateId updateId) { } public string DeploymentId { get { throw null; } set { } } public Azure.IoT.DeviceUpdate.Models.DeploymentType DeploymentType { get { throw null; } set { } } public string DeviceClassId { get { throw null; } set { } } public System.Collections.Generic.IList<string> DeviceGroupDefinition { get { throw null; } } public Azure.IoT.DeviceUpdate.Models.DeviceGroupType DeviceGroupType { get { throw null; } set { } } public bool? IsCanceled { get { throw null; } set { } } public bool? IsCompleted { get { throw null; } set { } } public bool? IsRetried { get { throw null; } set { } } public System.DateTimeOffset StartDateTime { get { throw null; } set { } } public Azure.IoT.DeviceUpdate.Models.UpdateId UpdateId { get { throw null; } set { } } } public partial class DeploymentDeviceState { internal DeploymentDeviceState() { } public string DeviceId { get { throw null; } } public Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState DeviceState { get { throw null; } } public bool MovedOnToNewDeployment { get { throw null; } } public int RetryCount { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct DeploymentState : System.IEquatable<Azure.IoT.DeviceUpdate.Models.DeploymentState> { private readonly object _dummy; private readonly int _dummyPrimitive; public DeploymentState(string value) { throw null; } public static Azure.IoT.DeviceUpdate.Models.DeploymentState Active { get { throw null; } } public static Azure.IoT.DeviceUpdate.Models.DeploymentState Canceled { get { throw null; } } public static Azure.IoT.DeviceUpdate.Models.DeploymentState Superseded { get { throw null; } } public bool Equals(Azure.IoT.DeviceUpdate.Models.DeploymentState other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.IoT.DeviceUpdate.Models.DeploymentState left, Azure.IoT.DeviceUpdate.Models.DeploymentState right) { throw null; } public static implicit operator Azure.IoT.DeviceUpdate.Models.DeploymentState (string value) { throw null; } public static bool operator !=(Azure.IoT.DeviceUpdate.Models.DeploymentState left, Azure.IoT.DeviceUpdate.Models.DeploymentState right) { throw null; } public override string ToString() { throw null; } } public partial class DeploymentStatus { internal DeploymentStatus() { } public Azure.IoT.DeviceUpdate.Models.DeploymentState DeploymentState { get { throw null; } } public int? DevicesCanceledCount { get { throw null; } } public int? DevicesCompletedFailedCount { get { throw null; } } public int? DevicesCompletedSucceededCount { get { throw null; } } public int? DevicesIncompatibleCount { get { throw null; } } public int? DevicesInProgressCount { get { throw null; } } public int? TotalDevices { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct DeploymentType : System.IEquatable<Azure.IoT.DeviceUpdate.Models.DeploymentType> { private readonly object _dummy; private readonly int _dummyPrimitive; public DeploymentType(string value) { throw null; } public static Azure.IoT.DeviceUpdate.Models.DeploymentType Complete { get { throw null; } } public static Azure.IoT.DeviceUpdate.Models.DeploymentType Download { get { throw null; } } public static Azure.IoT.DeviceUpdate.Models.DeploymentType Install { get { throw null; } } public bool Equals(Azure.IoT.DeviceUpdate.Models.DeploymentType other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.IoT.DeviceUpdate.Models.DeploymentType left, Azure.IoT.DeviceUpdate.Models.DeploymentType right) { throw null; } public static implicit operator Azure.IoT.DeviceUpdate.Models.DeploymentType (string value) { throw null; } public static bool operator !=(Azure.IoT.DeviceUpdate.Models.DeploymentType left, Azure.IoT.DeviceUpdate.Models.DeploymentType right) { throw null; } public override string ToString() { throw null; } } public partial class Device { internal Device() { } public Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState? DeploymentStatus { get { throw null; } } public string DeviceClassId { get { throw null; } } public string DeviceId { get { throw null; } } public string GroupId { get { throw null; } } public Azure.IoT.DeviceUpdate.Models.UpdateId InstalledUpdateId { get { throw null; } } public Azure.IoT.DeviceUpdate.Models.UpdateId LastAttemptedUpdateId { get { throw null; } } public string LastDeploymentId { get { throw null; } } public string Manufacturer { get { throw null; } } public string Model { get { throw null; } } public bool OnLatestUpdate { get { throw null; } } } public partial class DeviceClass { internal DeviceClass() { } public Azure.IoT.DeviceUpdate.Models.UpdateId BestCompatibleUpdateId { get { throw null; } } public string DeviceClassId { get { throw null; } } public string Manufacturer { get { throw null; } } public string Model { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct DeviceDeploymentState : System.IEquatable<Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState> { private readonly object _dummy; private readonly int _dummyPrimitive; public DeviceDeploymentState(string value) { throw null; } public static Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState Canceled { get { throw null; } } public static Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState Failed { get { throw null; } } public static Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState Incompatible { get { throw null; } } public static Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState InProgress { get { throw null; } } public static Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState Succeeded { get { throw null; } } public bool Equals(Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState left, Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState right) { throw null; } public static implicit operator Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState (string value) { throw null; } public static bool operator !=(Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState left, Azure.IoT.DeviceUpdate.Models.DeviceDeploymentState right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct DeviceGroupType : System.IEquatable<Azure.IoT.DeviceUpdate.Models.DeviceGroupType> { private readonly object _dummy; private readonly int _dummyPrimitive; public DeviceGroupType(string value) { throw null; } public static Azure.IoT.DeviceUpdate.Models.DeviceGroupType All { get { throw null; } } public static Azure.IoT.DeviceUpdate.Models.DeviceGroupType DeviceGroupDefinitions { get { throw null; } } public static Azure.IoT.DeviceUpdate.Models.DeviceGroupType Devices { get { throw null; } } public bool Equals(Azure.IoT.DeviceUpdate.Models.DeviceGroupType other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.IoT.DeviceUpdate.Models.DeviceGroupType left, Azure.IoT.DeviceUpdate.Models.DeviceGroupType right) { throw null; } public static implicit operator Azure.IoT.DeviceUpdate.Models.DeviceGroupType (string value) { throw null; } public static bool operator !=(Azure.IoT.DeviceUpdate.Models.DeviceGroupType left, Azure.IoT.DeviceUpdate.Models.DeviceGroupType right) { throw null; } public override string ToString() { throw null; } } public partial class DeviceTag { internal DeviceTag() { } public int DeviceCount { get { throw null; } } public string TagName { get { throw null; } } } public partial class Error { internal Error() { } public string Code { get { throw null; } } public System.Collections.Generic.IReadOnlyList<Azure.IoT.DeviceUpdate.Models.Error> Details { get { throw null; } } public Azure.IoT.DeviceUpdate.Models.InnerError Innererror { get { throw null; } } public string Message { get { throw null; } } public System.DateTimeOffset? OccurredDateTime { get { throw null; } } public string Target { get { throw null; } } } public partial class File { internal File() { } public string Etag { get { throw null; } } public string FileId { get { throw null; } } public string FileName { get { throw null; } } public System.Collections.Generic.IReadOnlyDictionary<string, string> Hashes { get { throw null; } } public string MimeType { get { throw null; } } public long SizeInBytes { get { throw null; } } } public partial class FileImportMetadata { public FileImportMetadata(string filename, string url) { } public string Filename { get { throw null; } } public string Url { get { throw null; } } } public partial class Group { public Group(string groupId, Azure.IoT.DeviceUpdate.Models.GroupType groupType, System.Collections.Generic.IEnumerable<string> tags, string createdDateTime) { } public string CreatedDateTime { get { throw null; } set { } } public int? DeviceCount { get { throw null; } set { } } public string GroupId { get { throw null; } set { } } public Azure.IoT.DeviceUpdate.Models.GroupType GroupType { get { throw null; } set { } } public System.Collections.Generic.IList<string> Tags { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct GroupType : System.IEquatable<Azure.IoT.DeviceUpdate.Models.GroupType> { private readonly object _dummy; private readonly int _dummyPrimitive; public GroupType(string value) { throw null; } public static Azure.IoT.DeviceUpdate.Models.GroupType IoTHubTag { get { throw null; } } public bool Equals(Azure.IoT.DeviceUpdate.Models.GroupType other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.IoT.DeviceUpdate.Models.GroupType left, Azure.IoT.DeviceUpdate.Models.GroupType right) { throw null; } public static implicit operator Azure.IoT.DeviceUpdate.Models.GroupType (string value) { throw null; } public static bool operator !=(Azure.IoT.DeviceUpdate.Models.GroupType left, Azure.IoT.DeviceUpdate.Models.GroupType right) { throw null; } public override string ToString() { throw null; } } public enum HashType { Sha256 = 1, } public sealed partial class ImportManifest { public ImportManifest(Azure.IoT.DeviceUpdate.Models.UpdateId updateId, string updateType, string installedCriteria, System.Collections.Generic.List<Azure.IoT.DeviceUpdate.Models.ImportManifestCompatibilityInfo> compatibility, System.DateTime createdDateTime, System.Version manifestVersion, System.Collections.Generic.List<Azure.IoT.DeviceUpdate.Models.ImportManifestFile> files) { } public System.Collections.Generic.List<Azure.IoT.DeviceUpdate.Models.ImportManifestCompatibilityInfo> Compatibility { get { throw null; } } public System.DateTime CreatedDateTime { get { throw null; } } public System.Collections.Generic.List<Azure.IoT.DeviceUpdate.Models.ImportManifestFile> Files { get { throw null; } } public string InstalledCriteria { get { throw null; } } public System.Version ManifestVersion { get { throw null; } } public Azure.IoT.DeviceUpdate.Models.UpdateId UpdateId { get { throw null; } } public string UpdateType { get { throw null; } } } public partial class ImportManifestCompatibilityInfo { public ImportManifestCompatibilityInfo(string deviceManufacturer, string deviceModel) { } public string DeviceManufacturer { get { throw null; } } public string DeviceModel { get { throw null; } } } public partial class ImportManifestFile { public ImportManifestFile(string fileName, long sizeInBytes, System.Collections.Generic.Dictionary<Azure.IoT.DeviceUpdate.Models.HashType, string> hashes) { } public string FileName { get { throw null; } set { } } public System.Collections.Generic.Dictionary<Azure.IoT.DeviceUpdate.Models.HashType, string> Hashes { get { throw null; } } public long SizeInBytes { get { throw null; } set { } } } public partial class ImportManifestMetadata { public ImportManifestMetadata(string url, long sizeInBytes, System.Collections.Generic.IDictionary<string, string> hashes) { } public System.Collections.Generic.IDictionary<string, string> Hashes { get { throw null; } } public long SizeInBytes { get { throw null; } } public string Url { get { throw null; } } } public partial class ImportUpdateInput { public ImportUpdateInput(Azure.IoT.DeviceUpdate.Models.ImportManifestMetadata importManifest, System.Collections.Generic.IEnumerable<Azure.IoT.DeviceUpdate.Models.FileImportMetadata> files) { } public System.Collections.Generic.IList<Azure.IoT.DeviceUpdate.Models.FileImportMetadata> Files { get { throw null; } } public Azure.IoT.DeviceUpdate.Models.ImportManifestMetadata ImportManifest { get { throw null; } } } public partial class InnerError { internal InnerError() { } public string Code { get { throw null; } } public string ErrorDetail { get { throw null; } } public Azure.IoT.DeviceUpdate.Models.InnerError InnerErrorValue { get { throw null; } } public string Message { get { throw null; } } } public partial class Operation { internal Operation() { } public System.DateTimeOffset CreatedDateTime { get { throw null; } } public Azure.IoT.DeviceUpdate.Models.Error Error { get { throw null; } } public string Etag { get { throw null; } } public System.DateTimeOffset LastActionDateTime { get { throw null; } } public string OperationId { get { throw null; } } public string ResourceLocation { get { throw null; } } public Azure.IoT.DeviceUpdate.Models.OperationStatus Status { get { throw null; } } public string TraceId { get { throw null; } } public Azure.IoT.DeviceUpdate.Models.UpdateId UpdateId { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct OperationStatus : System.IEquatable<Azure.IoT.DeviceUpdate.Models.OperationStatus> { private readonly object _dummy; private readonly int _dummyPrimitive; public OperationStatus(string value) { throw null; } public static Azure.IoT.DeviceUpdate.Models.OperationStatus Failed { get { throw null; } } public static Azure.IoT.DeviceUpdate.Models.OperationStatus NotStarted { get { throw null; } } public static Azure.IoT.DeviceUpdate.Models.OperationStatus Running { get { throw null; } } public static Azure.IoT.DeviceUpdate.Models.OperationStatus Succeeded { get { throw null; } } public static Azure.IoT.DeviceUpdate.Models.OperationStatus Undefined { get { throw null; } } public bool Equals(Azure.IoT.DeviceUpdate.Models.OperationStatus other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.IoT.DeviceUpdate.Models.OperationStatus left, Azure.IoT.DeviceUpdate.Models.OperationStatus right) { throw null; } public static implicit operator Azure.IoT.DeviceUpdate.Models.OperationStatus (string value) { throw null; } public static bool operator !=(Azure.IoT.DeviceUpdate.Models.OperationStatus left, Azure.IoT.DeviceUpdate.Models.OperationStatus right) { throw null; } public override string ToString() { throw null; } } public partial class UpdatableDevices { internal UpdatableDevices() { } public int DeviceCount { get { throw null; } } public Azure.IoT.DeviceUpdate.Models.UpdateId UpdateId { get { throw null; } } } public partial class Update { internal Update() { } public System.Collections.Generic.IReadOnlyList<Azure.IoT.DeviceUpdate.Models.Compatibility> Compatibility { get { throw null; } } public System.DateTimeOffset CreatedDateTime { get { throw null; } } public string Etag { get { throw null; } } public System.DateTimeOffset ImportedDateTime { get { throw null; } } public string InstalledCriteria { get { throw null; } } public string ManifestVersion { get { throw null; } } public Azure.IoT.DeviceUpdate.Models.UpdateId UpdateId { get { throw null; } } public string UpdateType { get { throw null; } } } public partial class UpdateCompliance { internal UpdateCompliance() { } public int NewUpdatesAvailableDeviceCount { get { throw null; } } public int OnLatestUpdateDeviceCount { get { throw null; } } public int TotalDeviceCount { get { throw null; } } public int UpdatesInProgressDeviceCount { get { throw null; } } } public partial class UpdateId { public UpdateId(string provider, string name, string version) { } public string Name { get { throw null; } set { } } public string Provider { get { throw null; } set { } } public string Version { get { throw null; } set { } } } }
93.52518
391
0.756359
[ "MIT" ]
AzureAppServiceCLI/azure-sdk-for-net
sdk/deviceupdate/Azure.Iot.DeviceUpdate/api/Azure.Iot.DeviceUpdate.netstandard2.0.cs
39,000
C#
/* * WebAPI * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: data * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = IO.Swagger.Client.SwaggerDateConverter; namespace IO.Swagger.Model { /// <summary> /// ProfileMailResponseItem /// </summary> [DataContract] public partial class ProfileMailResponseItem : IEquatable<ProfileMailResponseItem>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="ProfileMailResponseItem" /> class. /// </summary> /// <param name="responseProperty">Possible values: 1: Docnumber 2: JobId 3: ProfileSkipped 4: BufferId 5: ExistingDocnumber 6: ProtocolYear 7: InternalProtocolNumber 8: ProtocolNumber .</param> /// <param name="message">message.</param> public ProfileMailResponseItem(int? responseProperty = default(int?), string message = default(string)) { this.ResponseProperty = responseProperty; this.Message = message; } /// <summary> /// Possible values: 1: Docnumber 2: JobId 3: ProfileSkipped 4: BufferId 5: ExistingDocnumber 6: ProtocolYear 7: InternalProtocolNumber 8: ProtocolNumber /// </summary> /// <value>Possible values: 1: Docnumber 2: JobId 3: ProfileSkipped 4: BufferId 5: ExistingDocnumber 6: ProtocolYear 7: InternalProtocolNumber 8: ProtocolNumber </value> [DataMember(Name="responseProperty", EmitDefaultValue=false)] public int? ResponseProperty { get; set; } /// <summary> /// Gets or Sets Message /// </summary> [DataMember(Name="message", EmitDefaultValue=false)] public string Message { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ProfileMailResponseItem {\n"); sb.Append(" ResponseProperty: ").Append(ResponseProperty).Append("\n"); sb.Append(" Message: ").Append(Message).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as ProfileMailResponseItem); } /// <summary> /// Returns true if ProfileMailResponseItem instances are equal /// </summary> /// <param name="input">Instance of ProfileMailResponseItem to be compared</param> /// <returns>Boolean</returns> public bool Equals(ProfileMailResponseItem input) { if (input == null) return false; return ( this.ResponseProperty == input.ResponseProperty || (this.ResponseProperty != null && this.ResponseProperty.Equals(input.ResponseProperty)) ) && ( this.Message == input.Message || (this.Message != null && this.Message.Equals(input.Message)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.ResponseProperty != null) hashCode = hashCode * 59 + this.ResponseProperty.GetHashCode(); if (this.Message != null) hashCode = hashCode * 59 + this.Message.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
36.908451
210
0.594352
[ "Apache-2.0" ]
zanardini/ARXivarNext-WebApi
ARXivarNext-ConsumingWebApi/IO.Swagger/Model/ProfileMailResponseItem.cs
5,241
C#
using System; using System.Collections.Generic; using KoiVM.Runtime.VCalls; namespace KoiVM.Runtime.Data { internal static class VCallMap { static readonly Dictionary<byte, IVCall> vCalls; static VCallMap() { vCalls = new Dictionary<byte, IVCall>(); foreach (var type in typeof(VCallMap).Assembly.GetTypes()) { if (typeof(IVCall).IsAssignableFrom(type) && !type.IsAbstract) { var vCall = (IVCall)Activator.CreateInstance(type); vCalls[vCall.Code] = vCall; } } } public static IVCall Lookup(byte code) { return vCalls[code]; } } }
25.956522
69
0.671692
[ "CC0-1.0" ]
ElektroKill/KoiVM
KoiVM.Runtime/Data/VCallMap.cs
599
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.Qualitycheck.Transform; using Aliyun.Acs.Qualitycheck.Transform.V20190115; namespace Aliyun.Acs.Qualitycheck.Model.V20190115 { public class ListRulesRequest : RpcAcsRequest<ListRulesResponse> { public ListRulesRequest() : base("Qualitycheck", "2019-01-15", "ListRules", "Qualitycheck", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Aliyun.Acs.Qualitycheck.Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Aliyun.Acs.Qualitycheck.Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private string jsonStr; public string JsonStr { get { return jsonStr; } set { jsonStr = value; DictionaryUtil.Add(QueryParameters, "JsonStr", value); } } public override bool CheckShowJsonItemName() { return false; } public override ListRulesResponse GetResponse(UnmarshallerContext unmarshallerContext) { return ListRulesResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
33.101449
142
0.700963
[ "Apache-2.0" ]
awei1688/aliyun-openapi-net-sdk
aliyun-net-sdk-qualitycheck/Qualitycheck/Model/V20190115/ListRulesRequest.cs
2,284
C#
using Obi; using System.Collections; using System.Collections.Generic; using UnityEngine; using DG.Tweening; using TapticPlugin; public class ObiRopeManager : MonoBehaviour { //public ObiRope rope; public ObiSolver solver; public float Distance = .1f; public float Damper = 500f; public ObiRopeCursor[] cursors; public GameObject yarnBall, stick1, stick2; public ObiRope obiRope; void Start() { obiRope.OnRopeTorn += DestroyTeared_OnRopeTorn; } // Update is called once per frame void Update() { for (int i = 1; i < obiRope.activeParticleCount; ++i) { int solverIndex = obiRope.solverIndices[i]; int prevSolverIndex = obiRope.solverIndices[i - 1]; Vector3 connection = solver.velocities[solverIndex] - solver.velocities[prevSolverIndex]; var velocityTarget = connection + ((Vector3)solver.velocities[solverIndex] + Physics.gravity); var projectOnConnection = Vector3.Project(velocityTarget, connection); solver.velocities[solverIndex] = (velocityTarget - projectOnConnection) / (1 + Damper * Time.fixedDeltaTime); solver.velocities[solverIndex] = new Vector3(solver.velocities[solverIndex].x, Mathf.Clamp(solver.velocities[solverIndex].y, float.MinValue, -3), Mathf.Clamp(solver.velocities[solverIndex].z, float.MinValue, -2)); } //for (int i = 0; i < solver.positions.count; i++) //{ // if (solver.positions[i].magnitude != 0) // { // if (solver.positions[i].magnitude < magnitude) // { // magnitude = solver.positions[i].magnitude; // lastIndice = i; // } // } //} //puskuls[0].transform.localPosition = solver.positions[obiRopes[0].solverIndices[obiRopes[0].elements.Count - 1]]; } public float addingRopeLenght; public Color LastColor; public void AddNewRope(Color clr) { if (yarnBall.transform.localScale.z < 38) { yarnBall.transform.DOScale(yarnBall.transform.localScale + new Vector3(2, 2, 2), .3f); } for (int i = 0; i < obiRope.activeParticleCount; i++) { solver.colors[i] = Color.Lerp(clr, LastColor, (float)i / (float)obiRope.activeParticleCount); } yarnBall.GetComponent<MeshRenderer>().material.DOColor(clr, .3f); foreach (ObiRopeCursor item in cursors) { item.ChangeLength(item.GetComponent<ObiRope>().restLength + addingRopeLenght); item.GetComponent<ObiRope>().RebuildConstraintsFromElements(); item.UpdateCursor(); item.UpdateSource(); } LastColor = clr; } public IEnumerator RemoveRope(float ropeLength) { if (yarnBall.transform.localScale.x > 26) { yarnBall.transform.DOScale((yarnBall.transform.localScale - new Vector3(2, 2, 2)), .3f); } while (ropeLength > 0) { foreach (ObiRopeCursor item in cursors) { item.ChangeLength(GetComponent<ObiRope>().restLength - .03f); item.GetComponent<ObiRope>().RebuildConstraintsFromElements(); item.UpdateCursor(); item.UpdateSource(); } ropeLength -= .03f; if (obiRope.restLength <= 0) { if (!GameManager.Instance.isScalingRope) { GameManager.Instance.isGameOver = true; //LOSE StartCoroutine(GameManager.Instance.WaitAndGameLose()); Debug.Log(obiRope.restLength); GameManager.Instance.obiRopeManager.CloseYarnThings(); GameManager.Instance.playerControl.m_animator.SetTrigger("Lose"); } break; } yield return new WaitForSeconds(0); } } float distance = 50; int index; public bool isCutted; public void CutRope(int particleIndex) { Debug.Log("Cut Rope"); isCutted = true; ObiSolver.ParticleInActor pa = solver.particleToActor[particleIndex]; obiRope.Tear(obiRope.elements[pa.indexInActor]); obiRope.RebuildConstraintsFromElements(); foreach (ObiRopeCursor cr in cursors) { cr.cursorMu = (float)pa.indexInActor / (float)obiRope.activeParticleCount; cr.UpdateCursor(); } SoundManager.Instance.playSound(SoundManager.GameSounds.Cut); if (PlayerPrefs.GetInt("VIBRATION") == 1) TapticManager.Impact(ImpactFeedback.Medium); } private void DestroyTeared_OnRopeTorn(ObiRope rope, ObiRope.ObiRopeTornEventArgs tearInfo) { for (int i = rope.elements.Count - 1; i >= 0; --i) { var elm = rope.elements[i]; rope.DeactivateParticle(rope.solver.particleToActor[elm.particle2].indexInActor); rope.elements.RemoveAt(i); if (elm == tearInfo.element) break; } rope.RebuildConstraintsFromElements(); } //public GameObject[] puskuls; public void CloseYarnThings() { obiRope.GetComponent<MeshRenderer>().enabled = false; yarnBall.SetActive(false); //foreach (var item in puskuls) //{ // item.SetActive(false); //} stick1.SetActive(false); stick2.SetActive(false); } }
32.08046
225
0.591007
[ "MIT" ]
debruw/SewingRace
Assets/Scripts/ObiRopeManager.cs
5,584
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Resources; // 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("Vuforia")] [assembly: AssemblyProduct("")] [assembly: AssemblyDescription("")] [assembly: AssemblyCompany("Weekend game Studio")] [assembly: AssemblyCopyright("Copyright © Weekend Game Studio 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. Only Windows // assemblies support COM. [assembly: ComVisible(false)] // On Windows, the following GUID is for the ID of the typelib if this // project is exposed to COM. On other platforms, it unique identifies the // title storage container when deploying this assembly to the device. [assembly: Guid("536e2f19-76fd-4268-92a9-d10fccd1bb0b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: NeutralResourcesLanguageAttribute("en-US")]
38.540541
77
0.760168
[ "MIT" ]
starostin13/Samples
Graphics/Vuforia/LauncherIOS/Properties/AssemblyInfo.cs
1,427
C#
using System; using System.Linq; using System.Text.RegularExpressions; using HandlebarsDotNet; using WireMock.Util; using WireMock.Validation; namespace WireMock.Transformers { internal static class HandlebarsRegex { public static void Register(IHandlebars handlebarsContext) { handlebarsContext.RegisterHelper("Regex.Match", (writer, context, arguments) => { (string stringToProcess, string regexPattern, object defaultValue) = ParseArguments(arguments); Match match = Regex.Match(stringToProcess, regexPattern); if (match.Success) { writer.WriteSafeString(match.Value); } else if (defaultValue != null) { writer.WriteSafeString(defaultValue); } }); handlebarsContext.RegisterHelper("Regex.Match", (writer, options, context, arguments) => { (string stringToProcess, string regexPattern, object defaultValue) = ParseArguments(arguments); var regex = new Regex(regexPattern); var namedGroups = RegexUtils.GetNamedGroups(regex, stringToProcess); if (namedGroups.Any()) { options.Template(writer, namedGroups); } else if (defaultValue != null) { options.Template(writer, defaultValue); } }); } private static (string stringToProcess, string regexPattern, object defaultValue) ParseArguments(object[] arguments) { Check.Condition(arguments, args => args.Length == 2 || args.Length == 3, nameof(arguments)); string ParseAsString(object arg) { if (arg is string argAsString) { return argAsString; } throw new NotSupportedException($"The value '{arg}' with type '{arg?.GetType()}' cannot be used in Handlebars Regex."); } return (ParseAsString(arguments[0]), ParseAsString(arguments[1]), arguments.Length == 3 ? arguments[2] : null); } } }
35.46875
135
0.557269
[ "Apache-2.0" ]
APIWT/WireMock.Net
src/WireMock.Net/Transformers/HandleBarsRegex.cs
2,272
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using NBitcoin; using NBitcoin.DataEncoders; using Xels.Bitcoin.Base.Deployments; using Xels.Bitcoin.Connection; using Xels.Bitcoin.Consensus; using Xels.Bitcoin.Consensus.Rules; using Xels.Bitcoin.Features.Consensus.Rules.CommonRules; using Xels.Bitcoin.Features.Miner; using Xels.Bitcoin.Features.Miner.Interfaces; using Xels.Bitcoin.Features.Miner.Staking; using Xels.Bitcoin.Features.RPC; using Xels.Bitcoin.Features.Wallet.Controllers; using Xels.Bitcoin.Features.Wallet.Models; using Xels.Bitcoin.IntegrationTests.Common; using Xels.Bitcoin.IntegrationTests.Common.EnvironmentMockUpHelpers; using Xels.Bitcoin.Networks; using Xels.Bitcoin.Networks.Deployments; using Xels.Bitcoin.P2P.Peer; using Xels.Bitcoin.P2P.Protocol; using Xels.Bitcoin.P2P.Protocol.Behaviors; using Xels.Bitcoin.P2P.Protocol.Payloads; using Xels.Bitcoin.Tests.Common; using Xels.Bitcoin.Utilities.Extensions; using Xunit; namespace Xels.Bitcoin.IntegrationTests { /// <summary> /// Prevent network being matched by name and replaced with a different network /// in the <see cref="Configuration.NodeSettings" /> constructor. /// </summary> public class XlcOverrideRegTest : XlcRegTest { public XlcOverrideRegTest() : base() { this.Name = Guid.NewGuid().ToString(); } } // TODO: This is also used in the block store integration tests, perhaps move it into the common namespace /// <summary> /// Used for recording messages coming into a test node. Does not respond to them in any way. /// </summary> internal class TestBehavior : NetworkPeerBehavior { public readonly Dictionary<string, List<IncomingMessage>> receivedMessageTracker = new Dictionary<string, List<IncomingMessage>>(); protected override void AttachCore() { this.AttachedPeer.MessageReceived.Register(this.OnMessageReceivedAsync); } protected override void DetachCore() { this.AttachedPeer.MessageReceived.Unregister(this.OnMessageReceivedAsync); } private async Task OnMessageReceivedAsync(INetworkPeer peer, IncomingMessage message) { try { await this.ProcessMessageAsync(peer, message).ConfigureAwait(false); } catch (OperationCanceledException) { } } private async Task ProcessMessageAsync(INetworkPeer peer, IncomingMessage message) { if (!this.receivedMessageTracker.ContainsKey(message.Message.Payload.Command)) this.receivedMessageTracker[message.Message.Payload.Command] = new List<IncomingMessage>(); this.receivedMessageTracker[message.Message.Payload.Command].Add(message); } public override object Clone() { var res = new TestBehavior(); return res; } } public class SegWitTests { [Fact] public void TestSegwit_MinedOnCore_ActivatedOn_XelsNode() { // This test only verifies that the BIP9 machinery is operating correctly on the Xels PoW node. // Since newer versions of Bitcoin Core have segwit always activated from genesis, there is no need to // perform the reverse version of this test. Much more important are the P2P and mempool tests for // segwit transactions. using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode coreNode = builder.CreateBitcoinCoreNode(version: "0.15.1"); coreNode.Start(); CoreNode XelsNode = builder.CreateXelsPowNode(KnownNetworks.RegTest).Start(); RPCClient XelsNodeRpc = XelsNode.CreateRPCClient(); RPCClient coreRpc = coreNode.CreateRPCClient(); coreRpc.AddNode(XelsNode.Endpoint, false); XelsNodeRpc.AddNode(coreNode.Endpoint, false); // Core (in version 0.15.1) only mines segwit blocks above a certain height on regtest // See issue for more details https://github.com/Xelsproject/XelsBitcoinFullNode/issues/1028 BIP9DeploymentsParameters prevSegwitDeployment = KnownNetworks.RegTest.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit]; KnownNetworks.RegTest.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit] = new BIP9DeploymentsParameters("Test", 1, 0, DateTime.Now.AddDays(50).ToUnixTimestamp(), BIP9DeploymentsParameters.DefaultRegTestThreshold); try { // Generate 450 blocks, block 431 will be segwit activated. coreRpc.Generate(450); var cancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(2)).Token; TestBase.WaitLoop(() => XelsNode.CreateRPCClient().GetBestBlockHash() == coreNode.CreateRPCClient().GetBestBlockHash(), cancellationToken: cancellationToken); // Segwit activation on Bitcoin regtest. // - On regtest deployment state changes every 144 blocks, the threshold for activating a rule is 108 blocks. // Segwit deployment status should be: // - Defined up to block 142. // - Started at block 143 to block 286. // - LockedIn 287 (as segwit should already be signaled in blocks). // - Active at block 431. var consensusLoop = XelsNode.FullNode.NodeService<IConsensusRuleEngine>() as ConsensusRuleEngine; ThresholdState[] segwitDefinedState = consensusLoop.NodeDeployments.BIP9.GetStates(XelsNode.FullNode.ChainIndexer.GetHeader(142)); ThresholdState[] segwitStartedState = consensusLoop.NodeDeployments.BIP9.GetStates(XelsNode.FullNode.ChainIndexer.GetHeader(143)); ThresholdState[] segwitLockedInState = consensusLoop.NodeDeployments.BIP9.GetStates(XelsNode.FullNode.ChainIndexer.GetHeader(287)); ThresholdState[] segwitActiveState = consensusLoop.NodeDeployments.BIP9.GetStates(XelsNode.FullNode.ChainIndexer.GetHeader(431)); // Check that segwit got activated at block 431. Assert.Equal(ThresholdState.Defined, segwitDefinedState.GetValue((int)BitcoinBIP9Deployments.Segwit)); Assert.Equal(ThresholdState.Started, segwitStartedState.GetValue((int)BitcoinBIP9Deployments.Segwit)); Assert.Equal(ThresholdState.LockedIn, segwitLockedInState.GetValue((int)BitcoinBIP9Deployments.Segwit)); Assert.Equal(ThresholdState.Active, segwitActiveState.GetValue((int)BitcoinBIP9Deployments.Segwit)); } finally { KnownNetworks.RegTest.Consensus.BIP9Deployments[BitcoinBIP9Deployments.Segwit] = prevSegwitDeployment; } } } [Fact] public void CanCheckBlockWithWitness() { var network = KnownNetworks.RegTest; Block block = Block.Load(Encoders.Hex.DecodeData("000000202f6f6a130549473222411b5c6f54150d63b32aadf10e57f7d563cfc7010000001e28204471ef9ef11acd73543894a96a3044932b85e99889e731322a8ec28a9f9ae9fc56ffff011d0011b40202010000000001010000000000000000000000000000000000000000000000000000000000000000ffffffff2c028027266a24aa21a9ed09154465f26a2a4144739eba3e83b3e9ae6a1f69566eae7dc3747d48f1183779010effffffff0250b5062a0100000023210263ed47e995cbbf1bc560101e3b76c6bdb1b094a185450cea533781ce598ff2b6ac0000000000000000266a24aa21a9ed09154465f26a2a4144739eba3e83b3e9ae6a1f69566eae7dc3747d48f1183779012000000000000000000000000000000000000000000000000000000000000000000000000001000000000101cecd90cd38ac6858c47f2fe9f28145d6e18f9c5abc7ef1a41e2f19e6fe0362580100000000ffffffff0130b48d06000000001976a91405481b7f1d90c5a167a15b00e8af76eb6984ea5988ac0247304402206104c335e4adbb920184957f9f710b09de17d015329fde6807b9d321fd2142db02200b24ad996b4aa4ff103000348b5ad690abfd9fddae546af9e568394ed4a83113012103a65786c1a48d4167aca08cf6eb8eed081e13f45c02dc6000fd8f3bb16242579a00000000"), network.Consensus.ConsensusFactory); var consensusFlags = new DeploymentFlags { ScriptFlags = ScriptVerify.Witness | ScriptVerify.P2SH | ScriptVerify.Standard, LockTimeFlags = Transaction.LockTimeFlags.MedianTimePast, EnforceBIP34 = true }; var context = new RuleContext { Time = DateTimeOffset.UtcNow, ValidationContext = new ValidationContext { BlockToValidate = block }, Flags = consensusFlags, }; network.Consensus.Options = new ConsensusOptions(); new WitnessCommitmentsRule().ValidateWitnessCommitment(context, network).GetAwaiter().GetResult(); var rule = new CheckPowTransactionRule(); var options = network.Consensus.Options; foreach (Transaction tx in block.Transactions) rule.CheckTransaction(network, options, tx); } [Fact] public void CanCheckBlockWithWitnessInInput() { var network = new XlcRegTest(); var blockHex = "00000020e46299aa9ab7a76ce77c705ac50d6b031386246689cea9bde33fb851ca3c287726236faaa13be02ea891cdffbc229c9c39f9fdd957009ccf86d8c3311c377353eda4645fffff7f200500000001010000000001010000000000000000000000000000000000000000000000000000000000000000ffffffff025100ffffffff0200d2496b000000002321033ee9fd42c7ea8a3374710ea4e8af00d56015e1ed7c61a31eac29114e080f120fac0000000000000000266a24aa21a9ede2f61c3f71d1defd3fa999dfa36953755c690689799962b48bebd836974e8cf9012000000000000000000000000000000000000000000000000000000000000000000000000000"; Block block = Block.Load(Encoders.Hex.DecodeData(blockHex), network.Consensus.ConsensusFactory); var consensusFlags = new DeploymentFlags { ScriptFlags = ScriptVerify.Witness | ScriptVerify.P2SH | ScriptVerify.Standard, LockTimeFlags = Transaction.LockTimeFlags.MedianTimePast, EnforceBIP34 = true }; var context = new RuleContext { Time = DateTimeOffset.UtcNow, ValidationContext = new ValidationContext { BlockToValidate = block }, Flags = consensusFlags, }; network.Consensus.Options = new ConsensusOptions(); new WitnessCommitmentsRule().ValidateWitnessCommitment(context, network).GetAwaiter().GetResult(); var rule = new CheckPowTransactionRule(); var options = network.Consensus.Options; foreach (Transaction tx in block.Transactions) rule.CheckTransaction(network, options, tx); } [Fact] public void SegwitActivatedOnXlcNode() { using (NodeBuilder builder = NodeBuilder.Create(this)) { var network = new XlcOverrideRegTest(); // Set the date ranges such that segwit will 'Start' immediately after the initial confirmation window. network.Consensus.BIP9Deployments[XlcBIP9Deployments.Segwit] = new BIP9DeploymentsParameters("Test", 1, 0, DateTime.Now.AddDays(50).ToUnixTimestamp(), 8); // Set a small confirmation window to reduce time taken by this test. network.Consensus.MinerConfirmationWindow = 10; CoreNode XelsNode = builder.CreateXelsPosNode(network).WithWallet(); XelsNode.Start(); // Deployment activation: // - Deployment state changes every 'MinerConfirmationWindow' blocks. // - Remains in 'Defined' state until 'startedHeight'. // - Changes to 'Started' state at 'startedHeight'. // - Changes to 'LockedIn' state at 'lockedInHeight' (we are assuming that in this test every mined block will signal Segwit support) // - Changes to 'Active' state at 'activeHeight'. int startedHeight = network.Consensus.MinerConfirmationWindow - 1; int lockedInHeight = startedHeight + network.Consensus.MinerConfirmationWindow; int activeHeight = lockedInHeight + network.Consensus.MinerConfirmationWindow; // Generate enough blocks to cover all state changes. TestHelper.MineBlocks(XelsNode, activeHeight + 1); // Check that Segwit states got updated as expected. ThresholdConditionCache cache = (XelsNode.FullNode.NodeService<IConsensusRuleEngine>() as ConsensusRuleEngine).NodeDeployments.BIP9; Assert.Equal(ThresholdState.Defined, cache.GetState(XelsNode.FullNode.ChainIndexer.GetHeader(startedHeight - 1), XlcBIP9Deployments.Segwit)); Assert.Equal(ThresholdState.Started, cache.GetState(XelsNode.FullNode.ChainIndexer.GetHeader(startedHeight), XlcBIP9Deployments.Segwit)); Assert.Equal(ThresholdState.LockedIn, cache.GetState(XelsNode.FullNode.ChainIndexer.GetHeader(lockedInHeight), XlcBIP9Deployments.Segwit)); Assert.Equal(ThresholdState.Active, cache.GetState(XelsNode.FullNode.ChainIndexer.GetHeader(activeHeight), XlcBIP9Deployments.Segwit)); // Verify that the block created before activation does not have the 'Witness' script flag set. var rulesEngine = XelsNode.FullNode.NodeService<IConsensusRuleEngine>(); ChainedHeader prevHeader = XelsNode.FullNode.ChainIndexer.GetHeader(activeHeight - 1); DeploymentFlags flags1 = (rulesEngine as ConsensusRuleEngine).NodeDeployments.GetFlags(prevHeader); Assert.Equal(0, (int)(flags1.ScriptFlags & ScriptVerify.Witness)); // Verify that the block created after activation has the 'Witness' flag set. DeploymentFlags flags2 = (rulesEngine as ConsensusRuleEngine).NodeDeployments.GetFlags(XelsNode.FullNode.ChainIndexer.Tip); Assert.NotEqual(0, (int)(flags2.ScriptFlags & ScriptVerify.Witness)); } } [Fact] public void TestSegwit_AlwaysActivatedOn_XelsNode() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode coreNode = builder.CreateBitcoinCoreNode(version: "0.18.0", useNewConfigStyle: true); coreNode.Start(); CoreNode XelsNode = builder.CreateXelsPowNode(KnownNetworks.RegTest).Start(); RPCClient XelsNodeRpc = XelsNode.CreateRPCClient(); RPCClient coreRpc = coreNode.CreateRPCClient(); coreRpc.AddNode(XelsNode.Endpoint, false); XelsNodeRpc.AddNode(coreNode.Endpoint, false); coreRpc.Generate(1); var cancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token; TestBase.WaitLoop(() => XelsNode.CreateRPCClient().GetBestBlockHash() == coreNode.CreateRPCClient().GetBestBlockHash(), cancellationToken: cancellationToken); var consensusLoop = XelsNode.FullNode.NodeService<IConsensusRuleEngine>() as ConsensusRuleEngine; ThresholdState[] segwitActiveState = consensusLoop.NodeDeployments.BIP9.GetStates(XelsNode.FullNode.ChainIndexer.GetHeader(1)); // Check that segwit got activated at genesis. Assert.Equal(ThresholdState.Active, segwitActiveState.GetValue((int)BitcoinBIP9Deployments.Segwit)); } } [Fact] public void MineSegwitBlock() { using (NodeBuilder builder = NodeBuilder.Create(this)) { // Even though we are mining, we still want to use PoS consensus rules. CoreNode node = builder.CreateXelsPosNode(KnownNetworks.XlcRegTest).Start(); // Create a Segwit P2WPKH scriptPubKey. var script = new Key().PubKey.WitHash.ScriptPubKey; var miner = node.FullNode.NodeService<IPowMining>() as PowMining; List<uint256> res = miner.GenerateBlocks(new ReserveScript(script), 1, int.MaxValue); // Retrieve mined block. Block block = node.FullNode.ChainIndexer.GetHeader(res.First()).Block; // Confirm that the mined block is Segwit-ted. Script commitment = WitnessCommitmentsRule.GetWitnessCommitment(node.FullNode.Network, block); // We presume that the consensus rules are checking the actual validity of the commitment, we just ensure that it exists here. Assert.NotNull(commitment); } } [Fact] public void StakeSegwitBlock() { using (NodeBuilder builder = NodeBuilder.Create(this)) { // Even though we are mining, we still want to use PoS consensus rules. Network network = KnownNetworks.XlcRegTest; CoreNode node = builder.CreateXelsPosNode(network).WithWallet().Start(); // Need the premine to be past coinbase maturity so that we can stake with it. RPCClient rpc = node.CreateRPCClient(); int minStakeConfirmations = ((PosConsensusOptions)network.Consensus.Options).GetStakeMinConfirmations(0, network); rpc.Generate(minStakeConfirmations + 2); var cancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token; TestBase.WaitLoop(() => node.CreateRPCClient().GetBlockCount() >= (minStakeConfirmations + 2), cancellationToken: cancellationToken); // Now need to start staking. var staker = node.FullNode.NodeService<IPosMinting>() as XlcMinting; staker.Stake(new List<WalletSecret>() { new WalletSecret() { WalletName = node.WalletName, WalletPassword = node.WalletPassword } }); // Wait for the chain height to increase. TestBase.WaitLoop(() => node.CreateRPCClient().GetBlockCount() >= (minStakeConfirmations + 3), cancellationToken: cancellationToken); // Get the last staked block. Block block = node.FullNode.ChainIndexer.Tip.Block; // Confirm that the staked block is Segwit-ted. Script commitment = WitnessCommitmentsRule.GetWitnessCommitment(node.FullNode.Network, block); // We presume that the consensus rules are checking the actual validity of the commitment, we just ensure that it exists here. Assert.NotNull(commitment); } } [Fact] public void StakeSegwitBlock_UsingOnlySegwitUTXOs() { using (NodeBuilder builder = NodeBuilder.Create(this)) { // Even though we are mining, we still want to use PoS consensus rules. Network network = KnownNetworks.XlcRegTest; CoreNode node = builder.CreateXelsPosNode(network).WithWallet().Start(); var address = BitcoinWitPubKeyAddress.Create(node.FullNode.WalletManager().GetUnusedAddress().Bech32Address, network); // A P2WPKH scriptPubKey - so that funds get mined into the node's wallet as segwit UTXOs var script = address.ScriptPubKey; // Need the premine to be past coinbase maturity so that we can stake with it. var miner = node.FullNode.NodeService<IPowMining>() as PowMining; int minStakeConfirmations = ((PosConsensusOptions)network.Consensus.Options).GetStakeMinConfirmations(0, network); List<uint256> res = miner.GenerateBlocks(new ReserveScript(script), (ulong)minStakeConfirmations + 2, int.MaxValue); var cancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token; TestBase.WaitLoop(() => node.CreateRPCClient().GetBlockCount() >= (minStakeConfirmations + 2), cancellationToken: cancellationToken); TestBase.WaitLoop(() => node.FullNode.WalletManager().WalletTipHeight >= (minStakeConfirmations + 2), cancellationToken: cancellationToken); var scriptPubKeys = node.FullNode.WalletManager().GetAccounts(node.WalletName).SelectMany(a => a.GetCombinedAddresses()).SelectMany(b => b.Transactions).Select(c => c.ScriptPubKey); // The wallet must have correctly determined that the block rewards have been mined into addresses it is aware of. Assert.NotEmpty(scriptPubKeys); // Check that every UTXO in the wallet has a Segwit scriptPubKey. foreach (Script scriptPubKey in scriptPubKeys) Assert.True(scriptPubKey.IsScriptType(ScriptType.P2WPKH)); // Now need to start staking. var staker = node.FullNode.NodeService<IPosMinting>() as PosMinting; staker.Stake(new List<WalletSecret>() { new WalletSecret() { WalletName = node.WalletName, WalletPassword = node.WalletPassword } }); // Wait for the chain height to increase. TestBase.WaitLoop(() => node.CreateRPCClient().GetBlockCount() >= (minStakeConfirmations + 3), cancellationToken: cancellationToken); // Get the last staked block. Block block = node.FullNode.ChainIndexer.Tip.Block; // Confirm that the staked block is Segwit-ted. Script commitment = WitnessCommitmentsRule.GetWitnessCommitment(node.FullNode.Network, block); // We presume that the consensus rules are checking the actual validity of the commitment, we just ensure that it exists here. Assert.NotNull(commitment); } } [Fact] public void CheckSegwitP2PSerialisationForWitnessNode() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode node = builder.CreateXelsPosNode(KnownNetworks.XlcRegTest).Start(); CoreNode listener = builder.CreateXelsPosNode(KnownNetworks.XlcRegTest).Start(); IConnectionManager listenerConnMan = listener.FullNode.NodeService<IConnectionManager>(); listenerConnMan.Parameters.TemplateBehaviors.Add(new TestBehavior()); // The listener node will have default settings, i.e. it should ask for witness data in P2P messages. Assert.True(listenerConnMan.Parameters.Services.HasFlag(NetworkPeerServices.NODE_WITNESS)); TestHelper.Connect(listener, node); // Mine a Segwit block on the first node. var script = new Key().PubKey.WitHash.ScriptPubKey; var miner = node.FullNode.NodeService<IPowMining>() as PowMining; List<uint256> res = miner.GenerateBlocks(new ReserveScript(script), 1, int.MaxValue); Block block = node.FullNode.ChainIndexer.GetHeader(res.First()).Block; Script commitment = WitnessCommitmentsRule.GetWitnessCommitment(node.FullNode.Network, block); Assert.NotNull(commitment); var cancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token; TestBase.WaitLoop(() => listener.CreateRPCClient().GetBlockCount() >= 1, cancellationToken: cancellationToken); // We need to capture a message on the witness-enabled destination node and see that it contains a block serialised with witness data. INetworkPeer connectedPeer = listenerConnMan.ConnectedPeers.FindByEndpoint(node.Endpoint); TestBehavior testBehavior = connectedPeer.Behavior<TestBehavior>(); var blockMessages = testBehavior.receivedMessageTracker["block"]; var blockReceived = blockMessages.First(); var receivedBlock = blockReceived.Message.Payload as BlockPayload; var parsedBlock = receivedBlock.Obj; var nonWitnessBlock = parsedBlock.WithOptions(listener.FullNode.Network.Consensus.ConsensusFactory, TransactionOptions.None); Assert.True(parsedBlock.GetSerializedSize() > nonWitnessBlock.GetSerializedSize()); } } [Fact] public void CheckSegwitP2PSerialisationForNonWitnessNode() { using (NodeBuilder builder = NodeBuilder.Create(this)) { // We have to name the networks differently because the NBitcoin network registration won't allow two identical networks to coexist otherwise. var network = new XlcRegTest(); network.SetPrivatePropertyValue("Name", "XlcRegTestWithDeployments"); Assert.NotNull(network.Consensus.BIP9Deployments[2]); var networkNoBIP9 = new XlcRegTest(); networkNoBIP9.SetPrivatePropertyValue("Name", "XlcRegTestWithoutDeployments"); Assert.NotNull(networkNoBIP9.Consensus.BIP9Deployments[2]); // Remove BIP9 deployments (i.e. segwit). for (int i = 0; i < networkNoBIP9.Consensus.BIP9Deployments.Length; i++) networkNoBIP9.Consensus.BIP9Deployments[i] = null; // Ensure the workaround had the desired effect. Assert.Null(networkNoBIP9.Consensus.BIP9Deployments[2]); Assert.NotNull(network.Consensus.BIP9Deployments[2]); // Explicitly use new & separate instances of XelsRegTest because we modified the BIP9 deployments on one instance. CoreNode node = builder.CreateXelsPosNode(network).Start(); CoreNode listener = builder.CreateXelsPosNode(networkNoBIP9).Start(); // Sanity check. Assert.Null(listener.FullNode.Network.Consensus.BIP9Deployments[2]); Assert.NotNull(node.FullNode.Network.Consensus.BIP9Deployments[2]); // By disabling Segwit on the listener node we also prevent the WitnessCommitments rule from rejecting the mining node's blocks once we modify the listener's peer services. IConnectionManager listenerConnMan = listener.FullNode.NodeService<IConnectionManager>(); listenerConnMan.Parameters.TemplateBehaviors.Add(new TestBehavior()); // Override the listener node's default settings, so that it will not ask for witness data in P2P messages. listenerConnMan.Parameters.Services &= ~NetworkPeerServices.NODE_WITNESS; TestHelper.Connect(listener, node); // Mine a Segwit block on the first node. It should have commitment data as its settings have not been modified. var script = new Key().PubKey.WitHash.ScriptPubKey; var miner = node.FullNode.NodeService<IPowMining>() as PowMining; List<uint256> res = miner.GenerateBlocks(new ReserveScript(script), 1, int.MaxValue); Block block = node.FullNode.ChainIndexer.GetHeader(res.First()).Block; Script commitment = WitnessCommitmentsRule.GetWitnessCommitment(node.FullNode.Network, block); Assert.NotNull(commitment); // The listener should sync the mined block without validation failures. var cancellationToken = new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token; TestBase.WaitLoop(() => listener.CreateRPCClient().GetBlockCount() >= 1, cancellationToken: cancellationToken); // We need to capture a message on the non-witness-enabled destination node and see that it contains a block serialised without witness data. INetworkPeer connectedPeer = listenerConnMan.ConnectedPeers.FindByEndpoint(node.Endpoint); TestBehavior testBehavior = connectedPeer.Behavior<TestBehavior>(); var blockMessages = testBehavior.receivedMessageTracker["block"]; var blockReceived = blockMessages.First(); var receivedBlock = blockReceived.Message.Payload as BlockPayload; var parsedBlock = receivedBlock.Obj; // The block mined on the mining node (witness) should be bigger than the one received by the listener (no witness). Assert.True(block.GetSerializedSize() > parsedBlock.GetSerializedSize()); // Reserialise the received block without witness data (this should have no effect on its size). var nonWitnessBlock = parsedBlock.WithOptions(listener.FullNode.Network.Consensus.ConsensusFactory, TransactionOptions.None); // We received a block without witness data in the first place. Assert.True(parsedBlock.GetSerializedSize() == nonWitnessBlock.GetSerializedSize()); } } [Fact] public void SegwitWalletTransactionBuildingAndPropagationTest() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode node = builder.CreateXelsPosNode(KnownNetworks.XlcRegTest).WithWallet().Start(); CoreNode listener = builder.CreateXelsPosNode(KnownNetworks.XlcRegTest).WithWallet().Start(); IConnectionManager listenerConnMan = listener.FullNode.NodeService<IConnectionManager>(); listenerConnMan.Parameters.TemplateBehaviors.Add(new TestBehavior()); // The listener node will have default settings, i.e. it should ask for witness data in P2P messages. Assert.True(listenerConnMan.Parameters.Services.HasFlag(NetworkPeerServices.NODE_WITNESS)); TestHelper.Connect(listener, node); var mineAddress = node.FullNode.WalletManager().GetUnusedAddress(); var miner = node.FullNode.NodeService<IPowMining>() as PowMining; miner.GenerateBlocks(new ReserveScript(mineAddress.ScriptPubKey), (ulong)(node.FullNode.Network.Consensus.CoinbaseMaturity + 1), int.MaxValue); // Wait for listener to sync to the same block height so that it won't reject the coinbase spend as being premature. TestHelper.WaitForNodeToSync(node, listener); // Send a transaction from first node to itself so that it has a proper segwit input to spend. var destinationAddress = node.FullNode.WalletManager().GetUnusedAddress(); var witAddress = destinationAddress.Bech32Address; IActionResult transactionResult = node.FullNode.NodeController<WalletController>() .BuildTransaction(new BuildTransactionRequest { AccountName = "account 0", AllowUnconfirmed = true, Recipients = new List<RecipientModel> { new RecipientModel { DestinationAddress = witAddress, Amount = Money.Coins(1).ToString() } }, Password = node.WalletPassword, WalletName = node.WalletName, FeeAmount = Money.Coins(0.001m).ToString() }).GetAwaiter().GetResult(); var walletBuildTransactionModel = (WalletBuildTransactionModel)(transactionResult as JsonResult)?.Value; node.FullNode.NodeController<WalletController>().SendTransaction(new SendTransactionRequest(walletBuildTransactionModel.Hex)); Transaction witFunds = node.FullNode.Network.CreateTransaction(walletBuildTransactionModel.Hex); uint witIndex = witFunds.Outputs.AsIndexedOutputs().First(o => o.TxOut.ScriptPubKey.IsScriptType(ScriptType.P2WPKH)).N; TestBase.WaitLoop(() => listener.CreateRPCClient().GetBlockCount() >= 1, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); TestBase.WaitLoop(() => node.CreateRPCClient().GetRawMempool().Length > 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); TestBase.WaitLoop(() => listener.CreateRPCClient().GetRawMempool().Length > 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); INetworkPeer connectedPeer = listenerConnMan.ConnectedPeers.FindByEndpoint(node.Endpoint); TestBehavior testBehavior = connectedPeer.Behavior<TestBehavior>(); miner.GenerateBlocks(new ReserveScript(mineAddress.ScriptPubKey), 1, int.MaxValue); TestBase.WaitLoop(() => node.CreateRPCClient().GetRawMempool().Length == 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); TestBase.WaitLoop(() => listener.CreateRPCClient().GetRawMempool().Length == 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); // Make sure wallet is synced. TestBase.WaitLoop(() => node.CreateRPCClient().GetBlockCount() == node.FullNode.WalletManager().LastBlockHeight(), cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); // We need to capture a message on the witness-enabled destination node and see that it contains a transaction serialised with witness data. // However, the first transaction has no witness data since it was only being sent to a segwit scriptPubKey (i.e. no witness input data). // So clear all messages for now. testBehavior.receivedMessageTracker.Clear(); // Send a transaction that has a segwit input, to a segwit address. transactionResult = node.FullNode.NodeController<WalletController>() .BuildTransaction(new BuildTransactionRequest { AccountName = "account 0", AllowUnconfirmed = true, Outpoints = new List<OutpointRequest>() { new OutpointRequest() { Index = (int)witIndex, TransactionId = witFunds.GetHash().ToString() } }, Recipients = new List<RecipientModel> { new RecipientModel { DestinationAddress = witAddress, Amount = Money.Coins(0.5m).ToString() } }, Password = node.WalletPassword, WalletName = node.WalletName, FeeAmount = Money.Coins(0.001m).ToString() }).GetAwaiter().GetResult(); walletBuildTransactionModel = (WalletBuildTransactionModel)(transactionResult as JsonResult)?.Value; node.FullNode.NodeController<WalletController>().SendTransaction(new SendTransactionRequest(walletBuildTransactionModel.Hex)); TestBase.WaitLoop(() => node.CreateRPCClient().GetRawMempool().Length > 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); TestBase.WaitLoop(() => listener.CreateRPCClient().GetRawMempool().Length > 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); TestBase.WaitLoop(() => testBehavior.receivedMessageTracker.ContainsKey("tx"), cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); var txMessages = testBehavior.receivedMessageTracker["tx"]; var txMessage = txMessages.First(); var receivedTransaction = txMessage.Message.Payload as TxPayload; var parsedTransaction = receivedTransaction.Obj; var nonWitnessTransaction = parsedTransaction.WithOptions(TransactionOptions.None, listener.FullNode.Network.Consensus.ConsensusFactory); // The node that does not support being sent witness data will perceive the transaction to be smaller in size. Assert.True(parsedTransaction.GetSerializedSize() > nonWitnessTransaction.GetSerializedSize()); // However, as the witness data is not used in the determination of the txid the txid should be identical for both serialisations. Assert.Equal(parsedTransaction.GetHash(), nonWitnessTransaction.GetHash()); miner.GenerateBlocks(new ReserveScript(mineAddress.ScriptPubKey), 1, int.MaxValue); TestBase.WaitLoop(() => node.CreateRPCClient().GetRawMempool().Length == 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); TestBase.WaitLoop(() => listener.CreateRPCClient().GetRawMempool().Length == 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); // Basic sanity test to ensure that a segwit transaction can be retrieved normally via RPC. Transaction rpcTransaction = node.CreateRPCClient().GetTransaction(parsedTransaction.GetHash()); Assert.NotNull(rpcTransaction); Assert.True(rpcTransaction.GetSerializedSize() == parsedTransaction.GetSerializedSize()); } } [Fact] public void SegwitWalletTransactionBuildingTest_SpendP2WPKHAndNormalUTXOs() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode node = builder.CreateXelsPosNode(KnownNetworks.XlcRegTest).WithWallet().Start(); CoreNode listener = builder.CreateXelsPosNode(KnownNetworks.XlcRegTest).WithWallet().Start(); TestHelper.Connect(listener, node); var mineAddress = node.FullNode.WalletManager().GetUnusedAddress(); int maturity = (int)node.FullNode.Network.Consensus.CoinbaseMaturity; var miner = node.FullNode.NodeService<IPowMining>() as PowMining; miner.GenerateBlocks(new ReserveScript(mineAddress.ScriptPubKey), (ulong)(maturity + 2), int.MaxValue); // Send a transaction from first node to itself so that it has a proper segwit input to spend. var destinationAddress = node.FullNode.WalletManager().GetUnusedAddress(); var witAddress = destinationAddress.Bech32Address; var p2wpkhAmount = Money.Coins(1); IActionResult transactionResult = node.FullNode.NodeController<WalletController>() .BuildTransaction(new BuildTransactionRequest { AccountName = "account 0", AllowUnconfirmed = true, Recipients = new List<RecipientModel> { new RecipientModel { DestinationAddress = witAddress, Amount = p2wpkhAmount.ToString() } }, Password = node.WalletPassword, WalletName = node.WalletName, FeeAmount = Money.Coins(0.001m).ToString() }).GetAwaiter().GetResult(); var walletBuildTransactionModel = (WalletBuildTransactionModel)(transactionResult as JsonResult)?.Value; node.FullNode.NodeController<WalletController>().SendTransaction(new SendTransactionRequest(walletBuildTransactionModel.Hex)); Transaction witFunds = node.FullNode.Network.CreateTransaction(walletBuildTransactionModel.Hex); uint witIndex = witFunds.Outputs.AsIndexedOutputs().First(o => o.TxOut.ScriptPubKey.IsScriptType(ScriptType.P2WPKH)).N; TestBase.WaitLoop(() => listener.CreateRPCClient().GetBlockCount() >= (maturity + 2), cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); TestBase.WaitLoop(() => node.CreateRPCClient().GetRawMempool().Length > 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); TestBase.WaitLoop(() => listener.CreateRPCClient().GetRawMempool().Length > 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); miner.GenerateBlocks(new ReserveScript(mineAddress.ScriptPubKey), 1, int.MaxValue); TestBase.WaitLoop(() => node.CreateRPCClient().GetRawMempool().Length == 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); TestBase.WaitLoop(() => listener.CreateRPCClient().GetRawMempool().Length == 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); // Make sure wallet is synced. TestBase.WaitLoop(() => node.CreateRPCClient().GetBlockCount() == node.FullNode.WalletManager().LastBlockHeight(), cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); var spendable = node.FullNode.WalletManager().GetSpendableTransactionsInWallet(node.WalletName).Where(t => t.Address.Bech32Address != witAddress); // By sending more than the size of the P2WPKH UTXO, we guarantee that at least one non-P2WPKH UTXO gets included transactionResult = node.FullNode.NodeController<WalletController>() .BuildTransaction(new BuildTransactionRequest { AccountName = "account 0", AllowUnconfirmed = true, Outpoints = new List<OutpointRequest>() { new OutpointRequest() { Index = (int)witIndex, TransactionId = witFunds.GetHash().ToString() }, new OutpointRequest() { Index = spendable.First().Transaction.Index, TransactionId = spendable.First().Transaction.Id.ToString() } }, Recipients = new List<RecipientModel> { new RecipientModel { DestinationAddress = witAddress, Amount = (p2wpkhAmount + Money.Coins(0.5m)).ToString() } }, Password = node.WalletPassword, WalletName = node.WalletName, FeeAmount = Money.Coins(0.001m).ToString() }).GetAwaiter().GetResult(); walletBuildTransactionModel = (WalletBuildTransactionModel)(transactionResult as JsonResult)?.Value; node.FullNode.NodeController<WalletController>().SendTransaction(new SendTransactionRequest(walletBuildTransactionModel.Hex)); TestBase.WaitLoop(() => node.CreateRPCClient().GetRawMempool().Length > 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); TestBase.WaitLoop(() => listener.CreateRPCClient().GetRawMempool().Length > 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); miner.GenerateBlocks(new ReserveScript(mineAddress.ScriptPubKey), 1, int.MaxValue); TestBase.WaitLoop(() => node.CreateRPCClient().GetRawMempool().Length == 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); TestBase.WaitLoop(() => listener.CreateRPCClient().GetRawMempool().Length == 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); } } [Fact] public void SegwitWalletTransactionBuildingTest_SendToBech32AndNormalDestination() { using (NodeBuilder builder = NodeBuilder.Create(this)) { CoreNode node = builder.CreateXelsPosNode(KnownNetworks.XlcRegTest).WithWallet().Start(); CoreNode listener = builder.CreateXelsPosNode(KnownNetworks.XlcRegTest).WithWallet().Start(); TestHelper.Connect(listener, node); var mineAddress = node.FullNode.WalletManager().GetUnusedAddress(); int maturity = (int)node.FullNode.Network.Consensus.CoinbaseMaturity; var miner = node.FullNode.NodeService<IPowMining>() as PowMining; miner.GenerateBlocks(new ReserveScript(mineAddress.ScriptPubKey), (ulong)(maturity + 1), int.MaxValue); TestHelper.WaitForNodeToSync(node, listener); var destinationAddress = node.FullNode.WalletManager().GetUnusedAddress(); var witAddress = destinationAddress.Bech32Address; var nonWitAddress = destinationAddress.Address; IActionResult transactionResult = node.FullNode.NodeController<WalletController>() .BuildTransaction(new BuildTransactionRequest { AccountName = "account 0", AllowUnconfirmed = true, Recipients = new List<RecipientModel> { new RecipientModel { DestinationAddress = witAddress, Amount = Money.Coins(1).ToString() } }, Password = node.WalletPassword, WalletName = node.WalletName, FeeAmount = Money.Coins(0.001m).ToString() }).GetAwaiter().GetResult(); var walletBuildTransactionModel = (WalletBuildTransactionModel)(transactionResult as JsonResult)?.Value; node.FullNode.NodeController<WalletController>().SendTransaction(new SendTransactionRequest(walletBuildTransactionModel.Hex)); Transaction witFunds = node.FullNode.Network.CreateTransaction(walletBuildTransactionModel.Hex); uint witIndex = witFunds.Outputs.AsIndexedOutputs().First(o => o.TxOut.ScriptPubKey.IsScriptType(ScriptType.P2WPKH)).N; TestBase.WaitLoop(() => listener.CreateRPCClient().GetBlockCount() >= (maturity + 1), cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); TestBase.WaitLoop(() => node.CreateRPCClient().GetRawMempool().Length > 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); TestBase.WaitLoop(() => listener.CreateRPCClient().GetRawMempool().Length > 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); miner.GenerateBlocks(new ReserveScript(mineAddress.ScriptPubKey), 1, int.MaxValue); TestBase.WaitLoop(() => node.CreateRPCClient().GetRawMempool().Length == 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); TestBase.WaitLoop(() => listener.CreateRPCClient().GetRawMempool().Length == 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); // Make sure wallet is synced. TestBase.WaitLoop(() => node.CreateRPCClient().GetBlockCount() == node.FullNode.WalletManager().LastBlockHeight(), cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); // By sending more than the size of the P2WPKH UTXO, we guarantee that at least one non-P2WPKH UTXO gets included transactionResult = node.FullNode.NodeController<WalletController>() .BuildTransaction(new BuildTransactionRequest { AccountName = "account 0", AllowUnconfirmed = true, Outpoints = new List<OutpointRequest>() { new OutpointRequest() { Index = (int)witIndex, TransactionId = witFunds.GetHash().ToString() } }, Recipients = new List<RecipientModel> { new RecipientModel { DestinationAddress = witAddress, Amount = Money.Coins(0.4m).ToString() }, new RecipientModel { DestinationAddress = nonWitAddress, Amount = Money.Coins(0.4m).ToString() } }, Password = node.WalletPassword, WalletName = node.WalletName, FeeAmount = Money.Coins(0.001m).ToString() }).GetAwaiter().GetResult(); walletBuildTransactionModel = (WalletBuildTransactionModel)(transactionResult as JsonResult)?.Value; node.FullNode.NodeController<WalletController>().SendTransaction(new SendTransactionRequest(walletBuildTransactionModel.Hex)); TestBase.WaitLoop(() => node.CreateRPCClient().GetRawMempool().Length > 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); TestBase.WaitLoop(() => listener.CreateRPCClient().GetRawMempool().Length > 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); miner.GenerateBlocks(new ReserveScript(mineAddress.ScriptPubKey), 1, int.MaxValue); TestBase.WaitLoop(() => node.CreateRPCClient().GetRawMempool().Length == 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); TestBase.WaitLoop(() => listener.CreateRPCClient().GetRawMempool().Length == 0, cancellationToken: new CancellationTokenSource(TimeSpan.FromMinutes(1)).Token); } } } }
60.869458
1,096
0.661878
[ "MIT" ]
xels-io/SideChain-SmartContract
src/Xels.Bitcoin.IntegrationTests/SegWitTests.cs
49,428
C#
// ------------------------------------------------------------------------------ // <autogenerated> // This code was generated by a tool. // Mono Runtime Version: 4.0.30319.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </autogenerated> // ------------------------------------------------------------------------------ using System; using Hive5.Models; using LitJson; namespace Hive5.Models { public class AuthenticatePlatformAccountResponseBody : IResponseBody { public User User { get; set; } /// <summary> /// Load the specified json. /// </summary> /// <param name="json">Json.</param> public static IResponseBody Load(JsonData json) { if (json == null) return null; return new AuthenticatePlatformAccountResponseBody() { User = new User() { id = (string)json["user"]["id"], platform = (string)json["user"]["platform"], }, }; } } }
25.738095
81
0.482886
[ "MIT" ]
bytecodelab/hive5-sdk-unity
Assets/Hive5/Models/ResponseBody/AuthenticatePlatformAccountResponseBody.cs
1,081
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. #nullable enable #pragma warning disable SA1028 // ignore whitespace warnings for generated code using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Security.Cryptography; using Medikit.Security.Cryptography; using Medikit.Security.Cryptography.Asn1; namespace Medikit.Security.Cryptography.Pkcs.Asn1 { [StructLayout(LayoutKind.Sequential)] internal partial struct RecipientIdentifierAsn { internal IssuerAndSerialNumberAsn? IssuerAndSerialNumber; internal ReadOnlyMemory<byte>? SubjectKeyIdentifier; #if DEBUG static RecipientIdentifierAsn() { var usedTags = new Dictionary<Asn1Tag, string>(); Action<Asn1Tag, string> ensureUniqueTag = (tag, fieldName) => { if (usedTags.TryGetValue(tag, out string? existing)) { throw new InvalidOperationException($"Tag '{tag}' is in use by both '{existing}' and '{fieldName}'"); } usedTags.Add(tag, fieldName); }; ensureUniqueTag(Asn1Tag.Sequence, "IssuerAndSerialNumber"); ensureUniqueTag(new Asn1Tag(TagClass.ContextSpecific, 0), "SubjectKeyIdentifier"); } #endif internal void Encode(AsnWriter writer) { bool wroteValue = false; if (IssuerAndSerialNumber.HasValue) { if (wroteValue) throw new CryptographicException(); IssuerAndSerialNumber.Value.Encode(writer); wroteValue = true; } if (SubjectKeyIdentifier.HasValue) { if (wroteValue) throw new CryptographicException(); writer.WriteOctetString(new Asn1Tag(TagClass.ContextSpecific, 0), SubjectKeyIdentifier.Value.Span); wroteValue = true; } if (!wroteValue) { throw new CryptographicException(); } } internal static RecipientIdentifierAsn Decode(ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet) { AsnValueReader reader = new AsnValueReader(encoded.Span, ruleSet); Decode(ref reader, encoded, out RecipientIdentifierAsn decoded); reader.ThrowIfNotEmpty(); return decoded; } internal static void Decode(ref AsnValueReader reader, ReadOnlyMemory<byte> rebind, out RecipientIdentifierAsn decoded) { decoded = default; Asn1Tag tag = reader.PeekTag(); ReadOnlySpan<byte> rebindSpan = rebind.Span; int offset; ReadOnlySpan<byte> tmpSpan; if (tag.HasSameClassAndValue(Asn1Tag.Sequence)) { IssuerAndSerialNumberAsn tmpIssuerAndSerialNumber; IssuerAndSerialNumberAsn.Decode(ref reader, rebind, out tmpIssuerAndSerialNumber); decoded.IssuerAndSerialNumber = tmpIssuerAndSerialNumber; } else if (tag.HasSameClassAndValue(new Asn1Tag(TagClass.ContextSpecific, 0))) { if (reader.TryReadPrimitiveOctetStringBytes(new Asn1Tag(TagClass.ContextSpecific, 0), out tmpSpan)) { decoded.SubjectKeyIdentifier = rebindSpan.Overlaps(tmpSpan, out offset) ? rebind.Slice(offset, tmpSpan.Length) : tmpSpan.ToArray(); } else { decoded.SubjectKeyIdentifier = reader.ReadOctetString(new Asn1Tag(TagClass.ContextSpecific, 0)); } } else { throw new CryptographicException(); } } } }
35.309735
151
0.606516
[ "Apache-2.0" ]
ddonabedian/medikit
src/EHealth/Medikit.Security.Cryptography.Pkcs/System/Security/Cryptography/Pkcs/Asn1/RecipientIdentifierAsn.xml.cs
3,992
C#
#if UNITY_IOS using UnityEngine; using UnityEditor; using UnityEditor.Callbacks; using UnityEditor.iOS.Xcode; using System.Diagnostics; using System.IO; using Debug = UnityEngine.Debug; namespace Kakera.Unimgpicker { public class XcodeProjectConfigurator { [PostProcessBuild] static void OnPostprocessBuild(BuildTarget buildTarget, string buildPath) { if (buildTarget != BuildTarget.iOS) return; ConfigurePlist(buildPath, "Info.plist"); } static void ConfigurePlist(string buildPath, string plistPath) { var plist = new PlistDocument(); var path = Path.Combine(buildPath, plistPath); plist.ReadFromFile(path); var descriptionFilePath = Path.Combine(Application.dataPath, "Unimgpicker/Editor/NSPhotoLibraryUsageDescription.txt"); if (!File.Exists(descriptionFilePath)) { Debug.LogError(string.Format("[Unimgpicker]:File {0} is not found.", descriptionFilePath)); return; } var description = File.ReadAllText(descriptionFilePath); plist.root.SetString("NSPhotoLibraryUsageDescription", description); Debug.Log(string.Format("[Unimgpicker]:Set NSPhotoLibraryUsageDescription as \"{0}\"", description)); plist.WriteToFile(path); } } } #endif
30.191489
130
0.644116
[ "MIT" ]
ShreenathManikandaswamy/ARKIT-Photon
Assets/Unimgpicker/Editor/XcodeConfigurator.cs
1,421
C#
using QP_Comercio_Electronico.Models; using SQLite; using SQLiteNetExtensions.Attributes; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations.Schema; using System.Text; using XFFurniture.Models; namespace SwipeMenu.Models { public class OrdenModelo { [PrimaryKey] public int OrdId { get; set; } public string OrdNumero { get; set; } public int? OrdIdcliente { get; set; } public int? OrdIdtienda { get; set; } public string OrdDireccion { get; set; } public string OrdAltura { get; set; } public string OrdTelefono { get; set; } public double? OrdTotalcompra { get; set; } public DateTime? OrdFecha { get; set; } public double? OrdLatitud { get; set; } public double? OrdLongitud { get; set; } public DateTime? OrdFechaenvio { get; set; } public virtual ClienteModelo OrdIdclienteNavigation { get; set; } public ObservableCollection<Ordendetalle> Ordendetalles { get; set; } public virtual TiendaModelo OrdIdtiendaNavigation { get; set; } public int? OrdIdestado { get; set; } public string OrdDescripcion { get; set; } public int? OrdIdformapago { get; set; } public virtual Estadoorden OrdIdestadoNavigation { get; set; } public virtual Mediopago OrdIdformapagoNavigation { get; set; } } }
34.714286
77
0.672154
[ "MIT" ]
joseluishl123/Ordenes
XFFurniture/XFFurniture/Models/OrdenModelo.cs
1,460
C#
using System; using System.Xml.Serialization; namespace eidss.model.Avr.Chart { [Serializable] public class PieProperties : IParentSeries, IPieProperties { [XmlIgnore] public SeriesProperties ParentSeries { get; set; } public void CopyFrom(IPieProperties pie) { ShowArguments = pie.ShowArguments; Format = pie.Format; } public bool ShowArguments { get; set; } public int Format { get; set; } } }
23.5
63
0.591876
[ "BSD-2-Clause" ]
EIDSS/EIDSS-Legacy
EIDSS v6.1/eidss.model/AVR/Chart/PieProperties.cs
519
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Xamarin.Forms.Labs.Services.Serialization { /// <summary> /// Serializer extensions. /// </summary> public static class StringSerializerExtensions { /// <summary> /// Serializes to stream. /// </summary> /// <param name="obj">Object to serialize.</param> /// <param name="stream">Stream.</param> public static void SerializeToStream(this IStringSerializer serializer, object obj, Stream stream) { using (var streamWriter = new StreamWriter(stream)) { streamWriter.Write(serializer.Serialize(obj)); } } /// <summary> /// Deserializes from stream. /// </summary> /// <returns>The from stream.</returns> /// <param name="stream">Stream.</param> /// <typeparam name="T">The type of object to deserialize.</typeparam> public static T DeserializeFromStream<T>(this IStringSerializer serializer, Stream stream) { using (var streamReader = new StreamReader(stream)) { var text = streamReader.ReadToEnd(); return serializer.Deserialize<T>(text); } } /// <summary> /// Serializes to writer. /// </summary> /// <param name="obj">Object to serialize.</param> /// <param name="writer">Writer.</param> public static void SerializeToWriter(this IStringSerializer serializer, object obj, TextWriter writer) { writer.Write(serializer.Serialize(obj)); } /// <summary> /// Deserializes from reader. /// </summary> /// <returns>The serialized object from reader.</returns> /// <param name="reader">Reader to deserialize from.</param> public static T DeserializeFromReader<T>(this IStringSerializer serializer, TextReader reader) { return serializer.Deserialize<T>(reader.ReadToEnd()); } public static T DeserializeFromBytes<T>(this IStringSerializer serializer, byte[] data, Encoding encoding = null) { var encoder = encoding ?? Encoding.UTF8; var str = encoder.GetString(data, 0, data.Length); return serializer.Deserialize<T>(str); } public static byte[] SerializeToBytes(this IStringSerializer serializer, object obj, Encoding encoding = null) { var encoder = encoding ?? Encoding.UTF8; var str = serializer.Serialize(obj); return encoder.GetBytes(str); } } }
35.192308
121
0.5949
[ "Apache-2.0" ]
mrbrl/Xamarin-Forms-Labs
src/Xamarin.Forms.Labs/Xamarin.Forms.Labs/Services/Serialization/StringSerializerExtensions.cs
2,747
C#
using System; using System.Collections.Generic; using System.Text; namespace Orleans.Runtime.GrainDirectory { internal class AdaptiveGrainDirectoryCache<TValue> : IGrainDirectoryCache<TValue> { internal class GrainDirectoryCacheEntry { internal TValue Value { get; private set; } internal DateTime Created { get; set; } private DateTime LastRefreshed { get; set; } internal TimeSpan ExpirationTimer { get; private set; } internal int ETag { get; private set; } /// <summary> /// flag notifying whether this cache entry was accessed lately /// (more precisely, since the last refresh) /// </summary> internal int NumAccesses { get; set; } internal GrainDirectoryCacheEntry(TValue value, int etag, DateTime created, TimeSpan expirationTimer) { Value = value; ETag = etag; ExpirationTimer = expirationTimer; Created = created; LastRefreshed = DateTime.UtcNow; NumAccesses = 0; } internal bool IsExpired() { return DateTime.UtcNow >= LastRefreshed.Add(ExpirationTimer); } internal void Refresh(TimeSpan newExpirationTimer) { LastRefreshed = DateTime.UtcNow; ExpirationTimer = newExpirationTimer; } } private readonly LRU<GrainId, GrainDirectoryCacheEntry> cache; /// controls the time the new entry is considered "fresh" (unit: ms) private readonly TimeSpan initialExpirationTimer; /// controls the exponential growth factor (i.e., x2, x4) for the freshness timer (unit: none) private readonly double exponentialTimerGrowth; // controls the boundary on the expiration timer private readonly TimeSpan maxExpirationTimer; internal long NumAccesses; // number of cache item accesses (for stats) internal long NumHits; // number of cache access hits (for stats) internal long LastNumAccesses; internal long LastNumHits; public AdaptiveGrainDirectoryCache(TimeSpan initialExpirationTimer, TimeSpan maxExpirationTimer, double exponentialTimerGrowth, int maxCacheSize) { cache = new LRU<GrainId, GrainDirectoryCacheEntry>(maxCacheSize, TimeSpan.MaxValue, null); this.initialExpirationTimer = initialExpirationTimer; this.maxExpirationTimer = maxExpirationTimer; this.exponentialTimerGrowth = exponentialTimerGrowth; IntValueStatistic.FindOrCreate(StatisticNames.DIRECTORY_CACHE_SIZE, () => cache.Count); } public void AddOrUpdate(GrainId key, TValue value, int version) { var entry = new GrainDirectoryCacheEntry(value, version, DateTime.UtcNow, initialExpirationTimer); // Notice that LRU should know how to throw the oldest entry if the cache is full cache.Add(key, entry); } public bool Remove(GrainId key) { GrainDirectoryCacheEntry tmp; return cache.RemoveKey(key, out tmp); } public void Clear() { cache.Clear(); } public bool LookUp(GrainId key, out TValue result, out int version) { result = default(TValue); version = default(int); NumAccesses++; // for stats // Here we do not check whether the found entry is expired. // It will be done by the thread managing the cache. // This is to avoid situation where the entry was just expired, but the manager still have not run and have not refereshed it. GrainDirectoryCacheEntry tmp; if (!cache.TryGetValue(key, out tmp)) return false; NumHits++; // for stats tmp.NumAccesses++; result = tmp.Value; version = tmp.ETag; return true; } public IReadOnlyList<Tuple<GrainId, TValue, int>> KeyValues { get { var result = new List<Tuple<GrainId, TValue, int>>(); IEnumerator<KeyValuePair<GrainId, GrainDirectoryCacheEntry>> enumerator = GetStoredEntries(); while (enumerator.MoveNext()) { var current = enumerator.Current; result.Add(new Tuple<GrainId, TValue, int>(current.Key, current.Value.Value, current.Value.ETag)); } return result; } } public bool MarkAsFresh(GrainId key) { GrainDirectoryCacheEntry result; if (!cache.TryGetValue(key, out result)) return false; TimeSpan newExpirationTimer = StandardExtensions.Min(maxExpirationTimer, result.ExpirationTimer.Multiply(exponentialTimerGrowth)); result.Refresh(newExpirationTimer); return true; } internal GrainDirectoryCacheEntry Get(GrainId key) { return cache.Get(key); } internal IEnumerator<KeyValuePair<GrainId, GrainDirectoryCacheEntry>> GetStoredEntries() { return cache.GetEnumerator(); } public override string ToString() { var sb = new StringBuilder(); long curNumAccesses = NumAccesses - LastNumAccesses; LastNumAccesses = NumAccesses; long curNumHits = NumHits - LastNumHits; LastNumHits = NumHits; sb.Append("Adaptive cache statistics:").AppendLine(); sb.AppendFormat(" Cache size: {0} entries ({1} maximum)", cache.Count, cache.MaximumSize).AppendLine(); sb.AppendFormat(" Since last call:").AppendLine(); sb.AppendFormat(" Accesses: {0}", curNumAccesses); sb.AppendFormat(" Hits: {0}", curNumHits); if (curNumAccesses > 0) { sb.AppendFormat(" Hit Rate: {0:F1}%", (100.0 * curNumHits) / curNumAccesses).AppendLine(); } sb.AppendFormat(" Since start:").AppendLine(); sb.AppendFormat(" Accesses: {0}", LastNumAccesses); sb.AppendFormat(" Hits: {0}", LastNumHits); if (LastNumAccesses > 0) { sb.AppendFormat(" Hit Rate: {0:F1}%", (100.0 * LastNumHits) / LastNumAccesses).AppendLine(); } return sb.ToString(); } } }
37.273743
153
0.586181
[ "MIT" ]
1007lu/orleans
src/Orleans.Runtime/GrainDirectory/AdaptiveGrainDirectoryCache.cs
6,672
C#
using BasonManagement.Application.Interfaces.CacheRepositories; using AspNetCoreHero.Results; using AutoMapper; using MediatR; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace BasonManagement.Application.Features.Products.Queries.GetAllCached { public class GetAllProductsCachedQuery : IRequest<Result<List<GetAllProductsCachedResponse>>> { public GetAllProductsCachedQuery() { } } public class GetAllProductsCachedQueryHandler : IRequestHandler<GetAllProductsCachedQuery, Result<List<GetAllProductsCachedResponse>>> { private readonly IProductCacheRepository _productCache; private readonly IMapper _mapper; public GetAllProductsCachedQueryHandler(IProductCacheRepository productCache, IMapper mapper) { _productCache = productCache; _mapper = mapper; } public async Task<Result<List<GetAllProductsCachedResponse>>> Handle(GetAllProductsCachedQuery request, CancellationToken cancellationToken) { var productList = await _productCache.GetCachedListAsync(); var mappedProducts = _mapper.Map<List<GetAllProductsCachedResponse>>(productList); return Result<List<GetAllProductsCachedResponse>>.Success(mappedProducts); } } }
37.416667
148
0.744618
[ "MIT" ]
chougule-lalit/PrismCement
BasonManagement.Application/Features/Products/Queries/GetAllCached/GetAllProductsCachedQuery.cs
1,349
C#
namespace Cactus.TimmyAuth { public static class Const { public const string AuthenticationType = "TIMMY"; public const char ComplexTokenMarker = '!'; } }
20.444444
57
0.646739
[ "MIT" ]
CactusSoft/Cactus.DummyAuthentication
Cactus.TimmyAuth/Const.cs
186
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.DataFactory { public static class GetTrigger { /// <summary> /// Trigger resource type. /// API Version: 2018-06-01. /// </summary> public static Task<GetTriggerResult> InvokeAsync(GetTriggerArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetTriggerResult>("azure-nextgen:datafactory:getTrigger", args ?? new GetTriggerArgs(), options.WithVersion()); } public sealed class GetTriggerArgs : Pulumi.InvokeArgs { /// <summary> /// The factory name. /// </summary> [Input("factoryName", required: true)] public string FactoryName { get; set; } = null!; /// <summary> /// The resource group name. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// The trigger name. /// </summary> [Input("triggerName", required: true)] public string TriggerName { get; set; } = null!; public GetTriggerArgs() { } } [OutputType] public sealed class GetTriggerResult { /// <summary> /// Etag identifies change in the resource. /// </summary> public readonly string Etag; /// <summary> /// The resource identifier. /// </summary> public readonly string Id; /// <summary> /// The resource name. /// </summary> public readonly string Name; /// <summary> /// Properties of the trigger. /// </summary> public readonly object Properties; /// <summary> /// The resource type. /// </summary> public readonly string Type; [OutputConstructor] private GetTriggerResult( string etag, string id, string name, object properties, string type) { Etag = etag; Id = id; Name = name; Properties = properties; Type = type; } } }
26.806452
165
0.555957
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/DataFactory/GetTrigger.cs
2,493
C#
// <copyright file="AccountRepository.cs" company="SoluiNet"> // Copyright (c) SoluiNet. All rights reserved. // </copyright> namespace SoluiNet.DevTools.Management.Finances.Data.Repositories { using System.Collections.Generic; using System.Linq; using NHibernate; using NHibernate.Criterion; /// <summary> /// Provides a repository to handle categories. /// </summary> public class AccountRepository : BaseRepository<Account> { /// <summary> /// Add an account. /// </summary> /// <param name="account">The account.</param> public new void Add(Account account) { base.Add(account); } /// <summary> /// Get an account by ID. /// </summary> /// <param name="id">The ID.</param> /// <returns>The account that has the passed ID.</returns> public new Account Get(int id) { return base.Get(id); } /// <summary> /// Get all accounts. /// </summary> /// <returns>Returns a list of all accounts.</returns> public new ICollection<Account> GetAll() { return base.GetAll(); } /// <summary> /// Remove an account. /// </summary> /// <param name="account">The account.</param> public new void Remove(Account account) { base.Remove(account); } /// <summary> /// Update an account. /// </summary> /// <param name="account">The account.</param> public new void Update(Account account) { base.Update(account); } /// <summary> /// Find an account by IBAN. /// </summary> /// <param name="iban">The International Bank Account Number.</param> /// <returns>Returns the corresponding account.</returns> public Account FindByIban(string iban) { using (ISession session = NHibernateContext.GetCurrentSession()) { return session .CreateCriteria<Account>() .Add(Restrictions.Eq("IBAN", iban)) .UniqueResult<Account>(); } } /// <summary> /// Find an account by name. /// </summary> /// <param name="name">The name.</param> /// <returns>Returns the corresponding account.</returns> internal ICollection<Account> FindByName(string name) { using (ISession session = NHibernateContext.GetCurrentSession()) { return session .CreateCriteria<Account>() .Add(Restrictions.Eq("Name", name)) .List<Account>(); } } /// <summary> /// Find an account by name and IBAN. /// </summary> /// <param name="name">The name.</param> /// <param name="iban">The International Bank Account Number.</param> /// <returns>Returns the corresponding account.</returns> internal Account FindByNameAndIban(string name, string iban) { using (ISession session = NHibernateContext.GetCurrentSession()) { return session .CreateCriteria<Account>() .Add(Restrictions.Eq("Name", name)) .Add(Restrictions.Eq("IBAN", iban)) .UniqueResult<Account>(); } } } }
31.096491
77
0.517913
[ "MIT" ]
Kimiyou/SoluiNet.DevTools
SoluiNet.DevTools.Management.Finances/Data/Repositories/AccountRepository.cs
3,547
C#
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Analytics.Admin.V1Alpha.Snippets { // [START analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateDisplayVideo360AdvertiserLink_async] using Google.Analytics.Admin.V1Alpha; using System.Threading.Tasks; public sealed partial class GeneratedAnalyticsAdminServiceClientSnippets { /// <summary>Snippet for CreateDisplayVideo360AdvertiserLinkAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task CreateDisplayVideo360AdvertiserLinkRequestObjectAsync() { // Create client AnalyticsAdminServiceClient analyticsAdminServiceClient = await AnalyticsAdminServiceClient.CreateAsync(); // Initialize request argument(s) CreateDisplayVideo360AdvertiserLinkRequest request = new CreateDisplayVideo360AdvertiserLinkRequest { ParentAsPropertyName = PropertyName.FromProperty("[PROPERTY]"), DisplayVideo360AdvertiserLink = new DisplayVideo360AdvertiserLink(), }; // Make the request DisplayVideo360AdvertiserLink response = await analyticsAdminServiceClient.CreateDisplayVideo360AdvertiserLinkAsync(request); } } // [END analyticsadmin_v1alpha_generated_AnalyticsAdminService_CreateDisplayVideo360AdvertiserLink_async] }
46.195652
137
0.735529
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Analytics.Admin.V1Alpha/Google.Analytics.Admin.V1Alpha.GeneratedSnippets/AnalyticsAdminServiceClient.CreateDisplayVideo360AdvertiserLinkRequestObjectAsyncSnippet.g.cs
2,125
C#
namespace SignalR.Core.Model { public interface IModel // : INotifyPropertyChanged { } }
12.875
55
0.660194
[ "MIT" ]
Behzadkhosravifar/SignalR
SignalR/Core/SignalR.Core/Model/IModel.cs
105
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace Microsoft.ConsoleHelper.Threading { /// <summary>Provides a pump that supports running asynchronous methods on the current thread.</summary> public static class AsyncPump { /// <summary>Runs the specified asynchronous function.</summary> /// <param name="func">The asynchronous function to execute.</param> public static void Run(Func<Task> func) { if (func == null) throw new ArgumentNullException("func"); var prevCtx = SynchronizationContext.Current; try { // Establish the new context var syncCtx = new SingleThreadSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(syncCtx); // Invoke the function and alert the context to when it completes var t = func(); if (t == null) throw new InvalidOperationException("No task provided."); t.ContinueWith(delegate { syncCtx.Complete(); }, TaskScheduler.Default); // Pump continuations and propagate any exceptions syncCtx.RunOnCurrentThread(); t.GetAwaiter().GetResult(); } finally { SynchronizationContext.SetSynchronizationContext(prevCtx); } } /// <summary>Provides a SynchronizationContext that's single-threaded.</summary> private sealed class SingleThreadSynchronizationContext : SynchronizationContext { /// <summary>The queue of work items.</summary> private readonly BlockingCollection<KeyValuePair<SendOrPostCallback, object>> m_queue = new BlockingCollection<KeyValuePair<SendOrPostCallback, object>>(); /// <summary>The processing thread.</summary> private readonly Thread m_thread = Thread.CurrentThread; /// <summary>Dispatches an asynchronous message to the synchronization context.</summary> /// <param name="d">The System.Threading.SendOrPostCallback delegate to call.</param> /// <param name="state">The object passed to the delegate.</param> public override void Post(SendOrPostCallback d, object state) { if (d == null) throw new ArgumentNullException("d"); m_queue.Add(new KeyValuePair<SendOrPostCallback, object>(d, state)); } /// <summary>Not supported.</summary> public override void Send(SendOrPostCallback d, object state) { throw new NotSupportedException("Synchronously sending is not supported."); } /// <summary>Runs an loop to process all queued work items.</summary> public void RunOnCurrentThread() { foreach (var workItem in m_queue.GetConsumingEnumerable()) workItem.Key(workItem.Value); } /// <summary>Notifies the context that no more work will arrive.</summary> public void Complete() { m_queue.CompleteAdding(); } } } }
45.083333
108
0.623537
[ "MIT" ]
brentstineman/ServiceFabricPubSub
src/ServiceFabricPubSub/ClientApp/Microsoft.ConsoleHelper/AsyncPump.cs
3,248
C#
using System; using ByteBee.Framework.Converting; using ByteBee.Framework.Converting.Abstractions; using NUnit.Framework; namespace ByteBee.Framework.Tests.Converting.Standard.UriCastingTests { [TestFixture] public sealed partial class UriCastingTest { private ITypeConverter<Uri> _converter; [SetUp] public void Setup() { _converter = new StandardConverterFactory().Create<Uri>(); } [TearDown] public void TearDown() { } } }
22.041667
70
0.646503
[ "MIT" ]
ByteBee/ByteBee
tests/converting/Standard/UriCastingTests/UriCastingTest.cs
531
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Domain.Core.Classes { public interface IEvent { } public interface IApplyEvent<in T> where T : IEvent { void Apply(T @event); } public interface IEventPublisher { void Publish(IEvent @event); } }
16.434783
55
0.661376
[ "MIT" ]
Harunx9/AkkaCQRSExample
Domain/Core/Classes/Event.cs
380
C#
using System; using System.Collections.Generic; using AppStore.Infra.CrossCutting.Encryption.Extension; using AppStore.Domain.CreditCards; using System.Linq; namespace AppStore.Domain.Users { public class User : IUser { public User() { } public User(string email, string password, IUserRepository userRepository) { ValidateIfExists(email, userRepository); ValidatePassword(password); Email = email; SetPassword(password); } public int UserId { get; set; } public string Name { get; set; } public string SSN { get; set; } public Gender Gender { get; set; } public virtual Address Address { get; set; } public DateTime Birthdate { get; set; } public string Email { get; internal set; } public string Password { get; internal set; } public virtual ICollection<CreditCard> CreditCards { get; set; } = new List<CreditCard>(); public int AuthAttempt { get; private set; } public DateTime CreateDate { get; set; } = DateTime.Now; public DateTime? ModifyDate { get; set; } public virtual void ValidateAccess(string password) => PasswordMatch(password); internal void AddCreditCard(Guid instantBuyKey, CreditCardBrand brand, string lastDigits, int expMonth, int expYear) { var card = new CreditCard(this, instantBuyKey, brand, lastDigits, expMonth, expYear); this.CreditCards.Add(card); } private void PasswordMatch(string password) { const int attemptsLimit = 10; if (!Password.Equals(password.Encrypt())) { AuthAttempt++; var message = AuthAttempt > attemptsLimit ? "Password attempts exceeded. Access suspended." : "User not authorized."; throw new UnauthorizedException(message); } AuthAttempt = 0; } private void ValidateIfExists(string email, IUserRepository _userRepository) { if (_userRepository.Any(a => a.UserId != this.UserId && a.Email.Equals(email))) throw new InvalidOperationException("Email account is already registered."); } public CreditCard GetCreditCard(int? creditCardId) => CreditCards.FirstOrDefault(i => i.CreditCardId.Equals(creditCardId)); private void ValidatePassword(string password) { if (string.IsNullOrWhiteSpace(password)) throw new ArgumentException("Invalid password."); } private void SetPassword(string password) => this.Password = password.Encrypt(); } }
34.949367
98
0.612821
[ "MIT" ]
leocosta/AppStore
server/src/AppStore.Domain/Users/User.cs
2,763
C#
using System; using System.Collections.Generic; using System.Net.Http; using UniRx.Async; using UnityEngine; using Utf8Json; namespace GoogleSpreadSheetDownloaderForUnity { public class GoogleSpreadSheetLoaderForHttp : IAsyncCsvLoader { private readonly IGoogleSpreadSheetLoaderParam _param; public event Action PostLoad; public GoogleSpreadSheetLoaderForHttp(IGoogleSpreadSheetLoaderParam param) { _param = param; } public async UniTask<ICsvData> LoadAsync() { if(ParamValidate() is false) return null; var spreadSheetJson = await DownloadSpreadSheet(); if(spreadSheetJson is null) return null; var response = ParseSpreadSheetJson(spreadSheetJson); if (response is null) return null; var result = ParseResponseAsCsvData(response); PostLoad?.Invoke(); return result; } public async UniTask<string> LoadAsyncAsRawString() { if(ParamValidate() is false) return null; var spreadSheetJson = await DownloadSpreadSheet(); if(spreadSheetJson is null) return null; var response = ParseSpreadSheetJson(spreadSheetJson); if(response is null) return null; var result = ParseResponseAsRawCsvString(response); PostLoad?.Invoke(); return result; } /// <summary> /// GoogleSpreadSheet をHttp リクエストで取得する /// </summary> /// <returns> /// レスポンスのJson 文字列 /// </returns> private async UniTask<string> DownloadSpreadSheet() { const string requestUriBase = @"https://sheets.googleapis.com/v4/spreadsheets/"; string spreadSheetString; using (var client = new HttpClient()) { var range = _param.Range ?? string.Empty; var requestUri = $@"{requestUriBase}{_param.SpreadSheetId}/values/{_param.SpreadSheetName}{range}?key={_param.ApiKey}"; try { var response = await client.GetAsync(requestUri); spreadSheetString = await response.Content.ReadAsStringAsync(); } catch (Exception e) { Debug.LogError(e.Message); return null; } } return spreadSheetString; } private GoogleSpreadSheetResponse ParseSpreadSheetJson(string jsonString) { // TODO: async 版のデシリアライズを使う? var deserializeObj = JsonSerializer.Deserialize<GoogleSpreadSheetResponse>(jsonString); if (deserializeObj?.Values is null) { Debug.LogError("Json のデシリアライズに失敗"); return null; } return deserializeObj; } private ICsvData ParseResponseAsCsvData(GoogleSpreadSheetResponse response) { var csvData = new CsvData(); // NOTE: 先頭行・列はKey として取り扱う try { var header = response.Values[0]; header.RemoveAt(0); response.Values.RemoveAt(0); foreach(var row in response.Values) { var rowKey = row[0]; row.RemoveAt(0); var rowData = new Dictionary<string, string>(); csvData.Data.Add(rowKey, rowData); // データが不足しているので足りない分は空データをいれておく if (row.Count < header.Count) { while(row.Count != header.Count) row.Add(string.Empty); } for(var i = 0 ; i < header.Count ; i++) { var value = row[i]; rowData.Add(header[i], value); } } } catch (Exception e) { Debug.LogError($"{e}:{e.Message}"); } return csvData; } private string ParseResponseAsRawCsvString(GoogleSpreadSheetResponse response) { string rawCsvString = null; try { var header = response.Values[0]; foreach(var row in response.Values) { var validateRow = new List<string>(); // データが不足しているので足りない分は空データをいれておく if(row.Count < header.Count) { while(row.Count != header.Count) row.Add(string.Empty); } foreach(var column in row) { var validateColumn = column; // csv で複数行を扱うセルに関して、""で囲われた範囲が1セルになる。 // 更に、" が文字列として含まれている場合は"" とすることでエスケープされる。 if(column.Contains("\n")) { validateColumn = column.Replace("\"", "\"\""); validateColumn = $"\"{validateColumn}\""; } validateRow.Add(validateColumn); } var rowString = string.Join(",", validateRow) + "\n"; rawCsvString += rowString; } } catch (Exception e) { Debug.LogError($"{e}:{e.Message}"); } return rawCsvString; } private bool ParamValidate() { if (_param is null) { Console.WriteLine("パラメーターが未設定です。"); return false; } if (string.IsNullOrEmpty(_param.SpreadSheetName)) { Console.WriteLine("スプレッドシート名が未設定です。"); return false; } if(string.IsNullOrEmpty(_param.SpreadSheetId)) { Console.WriteLine("スプレッドシートID が未設定です。"); return false; } if(string.IsNullOrEmpty(_param.ApiKey)) { Console.WriteLine("API キーが未設定です。"); return false; } return true; } } }
30.142857
136
0.458383
[ "MIT" ]
R-Sudo/GoogleSpreadSheetDownloaderForUnity
UnityProject/Assets/GoogleSpreadSheetDownloaderForUnity/Scripts/GoogleSpreadSheetLoaderForHttp.cs
7,210
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cofoundry.Domain { public class PermissionCommandData { public string EntityDefinitionCode { get; set; } public string PermissionCode { get; set; } } }
19.3125
56
0.71521
[ "MIT" ]
BOBO41/cofoundry
src/Cofoundry.Domain/Domain/Roles/Commands/PermissionCommandData.cs
311
C#
using System; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Tokens; using OnionSquadTeamProject.Api.Services.Authentication; namespace OnionSquadTeamProject.Api.Authentication { public class JwtMiddleware { private readonly RequestDelegate _next; private readonly AppSettings _appSettings; public JwtMiddleware(RequestDelegate next, IOptions<AppSettings> appSettings) { _next = next; _appSettings = appSettings.Value; } public async Task Invoke(HttpContext context, IUserService userService) { var token = context.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last(); if (token != null) AttachUserToContext(context, userService, token); await _next(context); } private async Task AttachUserToContext(HttpContext context, IUserService userService, string token) { try { var tokenHandler = new JwtSecurityTokenHandler(); var key = Encoding.ASCII.GetBytes(_appSettings.Secret); tokenHandler.ValidateToken(token, new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false, // set clockskew to zero so tokens expire exactly at token expiration time (instead of 5 minutes later) ClockSkew = TimeSpan.Zero }, out SecurityToken validatedToken); JwtSecurityToken jwtToken = (JwtSecurityToken) validatedToken; int userId = int.Parse(jwtToken.Claims.First(x => x.Type == "id").Value); // attach user to context on successful jwt validation context.Items["User"] = await userService.GetUserById(userId); } catch { // do nothing if jwt validation fails // user is not attached to context so request won't have access to secure routes } } } }
33.174603
113
0.697608
[ "MIT" ]
AdamSzerszen/OnionSquadTeamProject
OnionSquadTeamProject.Api/Authentication/JwtMiddleware.cs
2,092
C#
#region netDxf library licensed under the MIT License // // netDxf library // Copyright (c) 2019-2021 Daniel Carvajal (haplokuon@gmail.com) // // 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. // #endregion using System; namespace netDxf.Tables { /// <summary> /// Base class for the three kinds of linetype segments simple, text, and shape. /// </summary> public abstract class LinetypeSegment : ICloneable { #region private fields private readonly LinetypeSegmentType type; private double length ; #endregion #region constructors /// <summary> /// Initializes a new instance of the <c>LinetypeSegment</c> class. /// </summary> /// <param name="type">Type of the linetype segment.</param> /// <param name="length">Dash or space length of the segment.</param> protected LinetypeSegment(LinetypeSegmentType type, double length) { this.type = type; this.length = length; } #endregion #region public properties /// <summary> /// Gets the linetype segment simple, text, or shape. /// </summary> public LinetypeSegmentType Type { get { return this.type; } } /// <summary> /// Gets or sets the dash, dot or space length. /// </summary> /// <remarks> /// A positive decimal number denotes a pen-down (dash) segment of that length. /// A negative decimal number denotes a pen-up (space) segment of that length. /// A dash length of 0 draws a dot. /// </remarks> public double Length { get { return this.length; } set { this.length = value; } } #endregion #region implements ICloneable /// <summary> /// Creates a new <c>LinetypeSegment</c> that is a copy of the current instance. /// </summary> /// <returns>A new <c>LinetypeSegment</c> that is a copy of this instance.</returns> public abstract object Clone(); #endregion } }
33.715789
92
0.633156
[ "MIT" ]
Atlant3D/netDxf
netDxf/Tables/LinetypeSegment.cs
3,203
C#
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // 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. #if FEATURE_DICTIONARYADAPTER_XML namespace Castle.Components.DictionaryAdapter.Xml { using System; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using System.Xml.Serialization; internal class XmlTypeSerializerCache : SingletonDispenser<Type, XmlTypeSerializer> { public static readonly XmlTypeSerializerCache Instance = new XmlTypeSerializerCache(); private XmlTypeSerializerCache() : base(CreateSerializer) { this[typeof(Object)] = XmlDynamicSerializer.Instance; this[typeof(String)] = XmlStringSerializer.Instance; this[typeof(Boolean)] = XmlSimpleSerializer.ForBoolean; this[typeof(Char)] = XmlSimpleSerializer.ForChar; this[typeof(SByte)] = XmlSimpleSerializer.ForSByte; this[typeof(Int16)] = XmlSimpleSerializer.ForInt16; this[typeof(Int32)] = XmlSimpleSerializer.ForInt32; this[typeof(Int64)] = XmlSimpleSerializer.ForInt64; this[typeof(Byte)] = XmlSimpleSerializer.ForByte; this[typeof(UInt16)] = XmlSimpleSerializer.ForUInt16; this[typeof(UInt32)] = XmlSimpleSerializer.ForUInt32; this[typeof(UInt64)] = XmlSimpleSerializer.ForUInt64; this[typeof(Single)] = XmlSimpleSerializer.ForSingle; this[typeof(Double)] = XmlSimpleSerializer.ForDouble; this[typeof(Decimal)] = XmlSimpleSerializer.ForDecimal; this[typeof(TimeSpan)] = XmlSimpleSerializer.ForTimeSpan; this[typeof(DateTime)] = XmlSimpleSerializer.ForDateTime; this[typeof(DateTimeOffset)] = XmlSimpleSerializer.ForDateTimeOffset; this[typeof(Guid)] = XmlSimpleSerializer.ForGuid; this[typeof(Byte[])] = XmlSimpleSerializer.ForByteArray; this[typeof(Uri)] = XmlSimpleSerializer.ForUri; } private static XmlTypeSerializer CreateSerializer(Type type) { if (type.GetTypeInfo().IsArray) return XmlArraySerializer.Instance; if (type.GetTypeInfo().IsGenericType) { var genericType = type.GetGenericTypeDefinition(); if (genericType == typeof(IList<>) || genericType == typeof(ICollection<>) || genericType == typeof(IEnumerable<>) || genericType == typeof(IBindingList<>)) return XmlListSerializer.Instance; #if DOTNET40 if (genericType == typeof(ISet<>)) return XmlSetSerializer.Instance; #endif if (// Dictionaries are not supported genericType == typeof(IDictionary<,>) || genericType == typeof(Dictionary<,>) || genericType == typeof(SortedDictionary<,>) || // Concrete list types are not supported genericType == typeof(List<>) || genericType == typeof(Stack<>) || genericType == typeof(Queue<>) || genericType == typeof(LinkedList<>) || genericType == typeof(SortedList<,>) || // Concrete set types are not supported genericType == typeof(HashSet<>) || #if DOTNET40 genericType == typeof(SortedSet<>) || #endif // CLR binding list is not supported; use Castle version genericType == typeof(BindingList<>)) throw Error.UnsupportedCollectionType(type); } if (type.GetTypeInfo().IsInterface) return XmlComponentSerializer.Instance; if (type.GetTypeInfo().IsEnum) return XmlEnumerationSerializer.Instance; if (type.IsCustomSerializable()) return XmlCustomSerializer.Instance; if (typeof(System.Xml.XmlNode).IsAssignableFrom(type)) return XmlXmlNodeSerializer.Instance; return new XmlDefaultSerializer(type); } } } #endif
39.847619
84
0.70435
[ "Apache-2.0" ]
CalosChen/Core
src/Castle.Core/Components.DictionaryAdapter/Xml/Internal/Serializers/XmlTypeSerializerCache.cs
4,186
C#
namespace Modularity { partial class ModuleControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft YaHei", 14.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label1.Location = new System.Drawing.Point(34, 41); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(67, 25); this.label1.TabIndex = 0; this.label1.Text = "label1"; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft YaHei", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); this.label2.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(128)))), ((int)(((byte)(0))))); this.label2.Location = new System.Drawing.Point(25, 75); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(83, 17); this.label2.TabIndex = 1; this.label2.Text = "click to load"; // // ModuleControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Name = "ModuleControl"; this.Size = new System.Drawing.Size(133, 110); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; } }
38.631579
166
0.559946
[ "MIT" ]
jackhuclan/bedrock
Quickstarts/Modularity/Modularity/ModuleControl.Designer.cs
2,938
C#
using System.Runtime.InteropServices; namespace System.Speech.Internal.SapiInterop { [StructLayout(LayoutKind.Sequential)] internal class SPSERIALIZEDPHRASEELEMENT { internal uint ulAudioTimeOffset; internal uint ulAudioSizeTime; internal uint ulAudioStreamOffset; internal uint ulAudioSizeBytes; internal uint ulRetainedStreamOffset; internal uint ulRetainedSizeBytes; internal uint pszDisplayTextOffset; internal uint pszLexicalFormOffset; internal uint pszPronunciationOffset; internal byte bDisplayAttributes; internal char RequiredConfidence; internal char ActualConfidence; internal byte Reserved; internal float SREngineConfidence; } }
18.621622
44
0.812772
[ "MIT" ]
aaasoft/Unoffical.System.Speech
System.Speech/System.Speech.Internal.SapiInterop/SPSERIALIZEDPHRASEELEMENT.cs
689
C#
using System.Collections.Generic; using Essensoft.Paylink.Alipay.Response; namespace Essensoft.Paylink.Alipay.Request { /// <summary> /// anttech.blockchain.defin.customer.login.confirm /// </summary> public class AnttechBlockchainDefinCustomerLoginConfirmRequest : IAlipayRequest<AnttechBlockchainDefinCustomerLoginConfirmResponse> { /// <summary> /// 登录接口 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "anttech.blockchain.defin.customer.login.confirm"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
22.951613
135
0.552706
[ "MIT" ]
fory77/paylink
src/Essensoft.Paylink.Alipay/Request/AnttechBlockchainDefinCustomerLoginConfirmRequest.cs
2,856
C#
using System; using System.IO; using GroupDocs.Conversion.Options.Convert; namespace GroupDocs.Conversion.Examples.CSharp.BasicUsage { /// <summary> /// This example demonstrates how to convert HTM file into TXT format. /// For more details about Hypertext Markup Language File (.htm) to Plain Text File Format (.txt) conversion please check this documentation article /// https://docs.groupdocs.com/conversion/net/convert-htm-to-txt /// </summary> internal static class ConvertHtmToTxt { public static void Run() { string outputFolder = Constants.GetOutputDirectoryPath(); string outputFile = Path.Combine(outputFolder, "htm-converted-to.txt"); // Load the source HTM file using (var converter = new GroupDocs.Conversion.Converter(Constants.SAMPLE_HTM)) { WordProcessingConvertOptions options = new WordProcessingConvertOptions { Format = GroupDocs.Conversion.FileTypes.WordProcessingFileType.Txt }; // Save converted TXT file converter.Convert(outputFile, options); } Console.WriteLine("\nConversion to txt completed successfully. \nCheck output in {0}", outputFolder); } } }
41.354839
159
0.665367
[ "MIT" ]
groupdocs-conversion/GroupDocs.Conversion-for-.NET
Examples/GroupDocs.Conversion.Examples.CSharp/BasicUsage/ConvertToWordProcessing/ConvertToTxt/ConvertHtmToTxt.cs
1,282
C#
using EasyModular.SqlSugar; using SqlSugar; using System; using System.Collections.Generic; using System.Text; namespace Demo.Admin.Domain { /// <summary> /// 用户最近选择 /// </summary> [SugarTable("Sys_User_Latest_Select", "用户最近选择")] public partial class UserLatestSelectEntity : SoftDeleteEntity<string> { /// <summary> /// 租户Id /// </summary> public string TenantId { get; set; } /// <summary> /// 用户Id /// </summary> public string UserId { get; set; } /// <summary> /// 关联用户ID /// </summary> public string RelationId { get; set; } /// <summary> /// 最近选择时间戳 /// </summary> public long Timestamp { get; set; } } }
20.342105
74
0.538163
[ "MIT" ]
doordie1991/EasyModular
simple/01_Admin/Demo.Admin.Domain/UserLatestSelect/Entity/UserLatestSelectEntity.cs
827
C#
using System; using System.Threading.Tasks; namespace RocketOptimize.Simulation { public class AscentOptimization { private static double ErrorFunction(double x, double scale = 1) { return (x * x / (scale * scale)); } public static double ComputeScore(AscentSimulationGoal goal, LookAheadState lookAheadState, State state, AscentSimulationControl guess) { const double distanceScaling = 10.0; double distanceFromApoapsisGoal = lookAheadState.Apoapsis / 1000.0 - goal.Apoapsis; double distanceFromPeriapsisGoal = lookAheadState.Periapsis / 1000.0 - goal.Periapsis; double distanceFromReachedAltitudeGoal = state.ReachedAltitude / 1000.0 - goal.Periapsis; double distanceFromAltitudeGoal = (state.Position.Length - Constants.EarthRadius) / 1000.0 - goal.Periapsis; double totalFuel = guess.Rocket.TotalFuelMass(); double fuelLeft = (totalFuel - state.ExpendedMass) / totalFuel; return ErrorFunction(distanceFromApoapsisGoal, distanceScaling) + ErrorFunction(distanceFromPeriapsisGoal, distanceScaling) + ErrorFunction(distanceFromReachedAltitudeGoal, distanceScaling) + ErrorFunction(distanceFromAltitudeGoal, distanceScaling) + fuelLeft*5; //+ ErrorFunction((guess.ThrustDuration1 + guess.ThrustDuration2) - guess.ThrustCutoff, 1); } private static void Print(AscentSimulationGoal goal, LookAheadState lookAheadState, State state, AscentSimulationControl guess, double bestScore) { Console.WriteLine("{0,1:F} {1,1:F}, {2,2:F}/{3,2:F}: g {4,1:F}, d {5,1:F}, mass left {6,2:F} kg - score {7,3:F}/{8,3:F}", (lookAheadState.Periapsis) / 1000.0, (lookAheadState.Apoapsis) / 1000.0, (state.Position.Length - Constants.EarthRadius) / 1000.0, state.ReachedAltitude / 1000.0, state.LossesToGravity, state.LossesToDrag, guess.Rocket.TotalFuelMass() - state.ExpendedMass, ComputeScore(goal, lookAheadState, state, guess), bestScore ); } public readonly double TimeStep; public readonly int MicroSteps; public readonly AscentSimulationGoal Goal; public readonly AscentSimulationControl InitialGuess; public AscentSimulationControl BestGuess; public double BestScore; public readonly State InitialState; public readonly double SurfaceVelocity; public AscentOptimization(double surfaceVelocity, AscentSimulationGoal goal, AscentSimulationControl initialGuess, State initialState, double timeStep, int microSteps, double bestScore = -1) { Goal = goal; InitialGuess = initialGuess; BestGuess = initialGuess; InitialState = initialState; TimeStep = timeStep; MicroSteps = microSteps; SurfaceVelocity = surfaceVelocity; LookAheadState lookAheadState; State state; BestScore = bestScore >= 0 ? bestScore : Tasklet(BestGuess, 0, 0.0, false, out BestGuess, out lookAheadState, out state); } private Random _random = new Random(); private double Tasklet(AscentSimulationControl currentBestGuess, double currentBestScore, double perturbationScale, bool print, out AscentSimulationControl control, out LookAheadState lookAheadState, out State state) { control = new AscentSimulationControl() { InitialVerticalTime = Math.Max(5, currentBestGuess.InitialVerticalTime + (perturbationScale * _random.NextDouble(1))), KickPitchTime = Math.Max(0, currentBestGuess.KickPitchTime + (perturbationScale * _random.NextDouble(4))), KickPitchAngle = currentBestGuess.KickPitchAngle, //Math.Max(0, currentBestGuess.KickPitchAngle + (perturbationScale * _random.NextDouble(1))), StagingAngle = Math.Max(0, Math.Min(90, currentBestGuess.StagingAngle + (perturbationScale * _random.NextDouble(2)))), MaxAcceleration = Math.Max(0, currentBestGuess.MaxAcceleration + (perturbationScale * _random.NextDouble(0.1))), Rocket = currentBestGuess.Rocket //Stage1Duration = currentBestGuess.Stage1Duration, // + (perturbationScale * _random.NextDouble(3)), //Stage2Duration = currentBestGuess.Stage2Duration, // + (perturbationScale * _random.NextDouble(3)), //Stage1InitialAcceleration = currentBestGuess.Stage1InitialAcceleration, //Stage1MaxAcceleration = currentBestGuess.Stage1MaxAcceleration, //Stage2InitialAcceleration = currentBestGuess.Stage2InitialAcceleration, //Stage2MaxAcceleration = currentBestGuess.Stage2MaxAcceleration //InitialTurnDuration = currentBestGuess.InitialTurnDuration + (perturbationScale * _random.NextDouble(0.2)), //MaxThrust1 = currentBestGuess.MaxThrust1, //MinThrust1 = currentBestGuess.MinThrust1, //MaxThrust2 = currentBestGuess.MaxThrust2, //MinThrust2 = currentBestGuess.MinThrust2, //ThrustCutoff = 1000, // Math.Max(0, currentBestGuess.ThrustCutoff + (perturbationScale * _random.NextDouble(5))), ////ThrustCurve = Math.Max(0, currentBestGuess.ThrustCurve + (perturbationScale * _random.NextDouble(5))), //ThrustDuration1 = Math.Max(0, currentBestGuess.ThrustDuration1 + (perturbationScale * _random.NextDouble(5))), //ThrustDuration2 = Math.Max(0, currentBestGuess.ThrustDuration2 + (perturbationScale * _random.NextDouble(5))), //TurnDelay = currentBestGuess.TurnDelay, //Math.Max(0, currentBestGuess.TurnDelay + (perturbationScale * _random.NextDouble(1))), //TurnDuration = Math.Max(0, currentBestGuess.TurnDuration + (perturbationScale * _random.NextDouble(1))), }; var simulation = new AscentSimulation(Goal, control, InitialState, SurfaceVelocity); double totalFuelMass = control.Rocket.TotalFuelMass(); while (!simulation.CurrentState.IsDone) { //Console.WriteLine("{0} {1}", simulation.CurrentState.ExpendedMass - totalFuelMass, simulation.CurrentState.Time); simulation.FastTick(TimeStep, MicroSteps); if (simulation.LookAheadState.Apoapsis / 1000.0 > (Goal.Apoapsis + 15) || simulation.LookAheadState.Periapsis / 1000.0 > (Goal.Periapsis + 15)) { //control.Stage2Duration = Math.Max(0, simulation.CurrentState.Time - control.Stage1Duration); break; } } if(print) { Print(Goal, simulation.LookAheadState, simulation.CurrentState, control, currentBestScore); } lookAheadState = simulation.LookAheadState; state = simulation.CurrentState; return ComputeScore(Goal, simulation.LookAheadState, state, control); } public double Run(double perturbationScale = 1.0) { var tasks = new Task<(double, AscentSimulationControl, LookAheadState, State)>[8]; for (int i = 0; i < tasks.Length; i++) { tasks[i] = new Task<(double, AscentSimulationControl, LookAheadState, State)>(() => { AscentSimulationControl newControl; LookAheadState lookAheadState; State state; double newScore = Tasklet(BestGuess, BestScore, perturbationScale, false, out newControl, out lookAheadState, out state); return (newScore, newControl, lookAheadState, state); }); tasks[i].Start(); } for (int i = 0; i < tasks.Length; i++) { tasks[i].Wait(); if (tasks[i].Result.Item1 < BestScore) { BestScore = tasks[i].Result.Item1; BestGuess = tasks[i].Result.Item2; Print(Goal, tasks[i].Result.Item3, tasks[i].Result.Item4, BestGuess, BestScore); Console.WriteLine(BestGuess); } } return BestScore; /* CurrentGuess.Score = CurrentScore; Print(); if (forceScore || CurrentGuess.Score < BestGuess.Score) { BestGuess = CurrentGuess; Console.WriteLine("New best!"); } Random random = new Random(); Reset(new AscentSimulationControl() { InitialTurnDuration = BestGuess.InitialTurnDuration + random.NextDouble(-0.1, 0.1), MaxThrust = BestGuess.MaxThrust, MinThrust = BestGuess.MinThrust, ThrustCurve = Math.Max(0, BestGuess.ThrustCurve + random.NextDouble(-0.1, 0.1)), ThrustDuration = Math.Max(0, BestGuess.ThrustDuration + random.NextDouble(-5, 5)), TurnDelay = Math.Max(0, BestGuess.TurnDelay + random.NextDouble(-1, 1)), TurnDuration = Math.Max(0, BestGuess.TurnDuration + random.NextDouble(-0.1, 0.1)), }); */ } } public static class RandomExtensions { public static double NextDouble( this Random random, double radius) { return random.NextDouble(-radius, radius); } public static double NextDouble( this Random random, double minValue, double maxValue) { return random.NextDouble() * (maxValue - minValue) + minValue; } } }
51.270408
198
0.611305
[ "MIT" ]
eweilow/rocket-optimize
RocketOptimize/Simulation/Optimize.cs
10,051
C#
using System.Linq; using FluentAssertions; using NUnit.Framework; using SkbKontur.TypeScript.ContractGenerator.CodeDom; using SkbKontur.TypeScript.ContractGenerator.Tests.Types; namespace SkbKontur.TypeScript.ContractGenerator.Tests { public class OptionsTests : TypeScriptTestBase { public OptionsTests(JavaScriptTypeChecker javaScriptTypeChecker) : base(javaScriptTypeChecker) { } [TestCase(EnumGenerationMode.FixedStringsAndDictionary, "enum-generation-fixed-strings")] [TestCase(EnumGenerationMode.TypeScriptEnum, "enum-generation-typescript-enum")] public void EnumGenerationModeTest(EnumGenerationMode enumGenerationMode, string expectedFileName) { var generatedCode = GenerateCode(new TypeScriptGenerationOptions {EnumGenerationMode = enumGenerationMode}, CustomTypeGenerator.Null, typeof(DefaultEnum)).Single().Replace("\r\n", "\n"); var expectedCode = GetExpectedCode($"Options.Expected/{expectedFileName}"); generatedCode.Should().Be(expectedCode); } [TestCase(true, "optional-properties-enabled")] [TestCase(false, "optional-properties-disabled")] public void OptionalPropertiesTest(bool optionalPropertiesEnabled, string expectedFileName) { var generatedCode = GenerateCode(new TypeScriptGenerationOptions {EnableOptionalProperties = optionalPropertiesEnabled}, CustomTypeGenerator.Null, typeof(SingleNullablePropertyType)).Single().Replace("\r\n", "\n"); var expectedCode = GetExpectedCode($"Options.Expected/{expectedFileName}"); generatedCode.Should().Be(expectedCode); } [TestCase(true, "explicit-nullability-enabled")] [TestCase(false, "explicit-nullability-disabled")] public void ExplicitNullabilityTest(bool explicitNullabilityEnabled, string expectedFileName) { var generatedCode = GenerateCode(new TypeScriptGenerationOptions {EnableExplicitNullability = explicitNullabilityEnabled}, CustomTypeGenerator.Null, typeof(ExplicitNullabilityRootType)).Single().Replace("\r\n", "\n"); var expectedCode = GetExpectedCode($"Options.Expected/{expectedFileName}"); generatedCode.Should().Be(expectedCode); } [TestCase(true, "global-nullable-enabled")] [TestCase(false, "global-nullable-disabled")] public void GlobalNullableTest(bool useGlobalNullable, string expectedFileName) { var generatedCode = GenerateCode(new TypeScriptGenerationOptions {UseGlobalNullable = useGlobalNullable}, CustomTypeGenerator.Null, typeof(GlobalNullableRootType)).Single().Replace("\r\n", "\n"); var expectedCode = GetExpectedCode($"Options.Expected/{expectedFileName}"); generatedCode.Should().Be(expectedCode); } } }
52.181818
229
0.721254
[ "MIT" ]
mr146/TypeScript.ContractGenerator
TypeScript.ContractGenerator.Tests/OptionsTests.cs
2,870
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Metadata; using Remotion.Linq; using Remotion.Linq.Clauses; using Remotion.Linq.Clauses.Expressions; namespace Microsoft.EntityFrameworkCore.Query.Internal { public partial class IncludeCompiler { private sealed class IncludeLoadTree : IncludeLoadTreeNodeBase { public IncludeLoadTree(QuerySourceReferenceExpression querySourceReferenceExpression) => QuerySourceReferenceExpression = querySourceReferenceExpression; public QuerySourceReferenceExpression QuerySourceReferenceExpression { get; } public void AddLoadPath(IReadOnlyList<INavigation> navigationPath) { AddLoadPath(this, navigationPath, index: 0); } public void Compile( QueryCompilationContext queryCompilationContext, QueryModel queryModel, bool trackingQuery, bool asyncQuery, ref int collectionIncludeId) { var querySourceReferenceExpression = QuerySourceReferenceExpression; if (querySourceReferenceExpression.ReferencedQuerySource is GroupJoinClause groupJoinClause) { if (queryModel.GetOutputExpression() is SubQueryExpression subQueryExpression && subQueryExpression.QueryModel.SelectClause.Selector is QuerySourceReferenceExpression qsre && (qsre.ReferencedQuerySource as MainFromClause)?.FromExpression == QuerySourceReferenceExpression) { querySourceReferenceExpression = qsre; queryModel = subQueryExpression.QueryModel; } else { // We expand GJs to 'from e in [g] select e' so we can rewrite the projector var joinClause = groupJoinClause.JoinClause; var mainFromClause = new MainFromClause(joinClause.ItemName, joinClause.ItemType, QuerySourceReferenceExpression); querySourceReferenceExpression = new QuerySourceReferenceExpression(mainFromClause); var subQueryModel = new QueryModel( mainFromClause, new SelectClause(querySourceReferenceExpression)); ApplyIncludeExpressionsToQueryModel( queryModel, QuerySourceReferenceExpression, new SubQueryExpression(subQueryModel)); queryModel = subQueryModel; } } Compile( queryCompilationContext, queryModel, trackingQuery, asyncQuery, ref collectionIncludeId, querySourceReferenceExpression); } } } }
41.615385
124
0.592113
[ "Apache-2.0" ]
Alecu100/EntityFrameworkCore
src/EFCore/Query/Internal/IncludeCompiler.IncludeLoadTree.cs
3,248
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the devicefarm-2015-06-23.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.DeviceFarm.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DeviceFarm.Model.Internal.MarshallTransformations { /// <summary> /// GetProject Request Marshaller /// </summary> public class GetProjectRequestMarshaller : IMarshaller<IRequest, GetProjectRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((GetProjectRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(GetProjectRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.DeviceFarm"); string target = "DeviceFarm_20150623.GetProject"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-06-23"; request.HttpMethod = "POST"; request.ResourcePath = "/"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetArn()) { context.Writer.WritePropertyName("arn"); context.Writer.Write(publicRequest.Arn); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static GetProjectRequestMarshaller _instance = new GetProjectRequestMarshaller(); internal static GetProjectRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetProjectRequestMarshaller Instance { get { return _instance; } } } }
34.572816
135
0.627633
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/DeviceFarm/Generated/Model/Internal/MarshallTransformations/GetProjectRequestMarshaller.cs
3,561
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AlibabaCloud.SDK.Vod20170321.Models { public class AttachAppPolicyToIdentityResponse : TeaModel { [NameInMap("RequestId")] [Validation(Required=true)] public string RequestId { get; set; } [NameInMap("NonExistPolicyNames")] [Validation(Required=true)] public List<string> NonExistPolicyNames { get; set; } [NameInMap("FailedPolicyNames")] [Validation(Required=true)] public List<string> FailedPolicyNames { get; set; } } }
24.111111
63
0.672811
[ "Apache-2.0" ]
alibabacloud-sdk-swift/alibabacloud-sdk
vod-20170321/csharp/core/Models/AttachAppPolicyToIdentityResponse.cs
651
C#
namespace SofiaToday.Web.Controllers { using System.Web.Mvc; using Common; using Data.Models; using Services.Data.Contracts; using ViewModels.Articles; public class CommentsController : BaseController { private readonly ICommentsService comments; public CommentsController(ICommentsService comments) { this.comments = comments; } [HttpGet] public ActionResult Comment() { return this.View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(int id, ArticlePageViewModel model) { if (!this.ModelState.IsValid) { return this.View(model); } var comment = new Comment { Content = model.CommentInputModel.Content, Email = model.CommentInputModel.Email, Author = model.CommentInputModel.Author, ArticleId = id }; this.comments.AddNewComment(comment); this.comments.SaveChanges(); this.TempData["Notification"] = GlobalConstants.CommentAddedSuccess; return this.Redirect(this.Request.UrlReferrer.ToString()); } } }
25.411765
80
0.573302
[ "MIT" ]
stoberov/SofiaToday
Source/Web/SofiaToday.Web/Controllers/CommentsController.cs
1,298
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; namespace yys_yuhun10_ { public class Client { public Point start_single_src = new Point(1800, 930); public Point ready_src = new Point(2130, 1060); public Point start_group_src = new Point(1944, 1123); public Point invite_src = new Point(1420, 810); public Point accept_src = new Point(270, 480); public Point size_src = new Point(2394, 1349); //src ready center position public Point check_point_src = new Point(2187, 1032); public Point check_size_src = new Point(200, 200); //780 public Point xuanshang_src = new Point(1700, 950); public Point start_single { get; set; } public Point ready { get; set; } public Point start_group { get; set; } public Point invite { get; set; } public Point accept { get; set; } public Point size { get; set; } public Point check_size { get; set; } public Point check_point { get; set; } public Point xuanshang { get; set; } public static int top_height = 30 * (int)DisplaySettings.Scaling; Point newPoint(Point std) { var x = (size.X / size_src.X) * std.X; var y = (size.Y / size_src.Y) * std.Y; Point p = new Point(x, y); return p; } public void Init(double width, double height) { size = new Point(width, height - 60); start_single = newPoint(start_single_src); ready = newPoint(ready_src); check_point = newPoint(check_point_src); start_group = newPoint(start_group_src); invite = newPoint(invite_src); accept = newPoint(accept_src); xuanshang = newPoint(xuanshang_src); var x =(size.Y / size_src.Y) * 200; check_size = new Point(x,x); } } public enum YYSMode { single=0, group_inviter=1, group_invitee=2, single_yyh=3, single_yl=4, single_ready=5 }; }
30.943662
74
0.583523
[ "MIT" ]
nzaocan/YYSHelper
yys_yuhun10_/Client.cs
2,199
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { public static void Main() { var lines = int.Parse(Console.ReadLine()); var persons = new List<Person>(); for (int i = 0; i < lines; i++) { var cmdArgs = Console.ReadLine().Split(); var person = new Person(cmdArgs[0], cmdArgs[1], int.Parse(cmdArgs[2])); persons.Add(person); } persons.OrderBy(p => p.FirstName) .ThenBy(p => p.Age) .ToList() .ForEach(p => Console.WriteLine(p.ToString())); } }
28.461538
87
0.495946
[ "MIT" ]
vlganev/CSharp-Fundamentals
CSharp OOP Basics/Lab Encapsulation/Persons/Program.cs
742
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Crystal3.Core { public enum Subplatform { None, /// <summary> /// Desktop and Holographic only (as of 6/16/2019) /// </summary> MixedReality, /// <summary> /// Desktop sku only /// </summary> TabletMode, /// <summary> /// Mobile sku only /// </summary> ContinuumForPhoneMode, } }
20.153846
58
0.551527
[ "MIT" ]
Amrykid/Crystal
src/Crystal3/Core/Subplatform.cs
526
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.IoTJobsDataPlane")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS IoT Jobs Data Plane. This release adds support for new the service called Iot Jobs. This client is built for the device SDK to use Iot Jobs Device specific APIs.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.5.0.34")]
47.34375
245
0.749835
[ "Apache-2.0" ]
altso/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/IoTJobsDataPlane/Properties/AssemblyInfo.cs
1,515
C#
using UnityEngine.Networking; #if ENABLE_PLAYFABSERVER_API namespace PlayFab { using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using MultiplayerAgent.Model; using UnityEngine; using MultiplayerAgent.Helpers; #pragma warning disable 414 public class PlayFabMultiplayerAgentAPI { // These two keys are only available after allocation (once readyForPlayers returns true) public const string SessionCookieKey = "sessionCookie"; public const string SessionIdKey = "sessionId"; public const string HeartbeatEndpointKey = "heartbeatEndpoint"; public const string ServerIdKey = "serverId"; public const string LogFolderKey = "logFolder"; public const string SharedContentFolderKey = "sharedContentFolder"; public const string CertificateFolderKey = "certificateFolder"; public const string TitleIdKey = "titleId"; public const string BuildIdKey = "buildId"; public const string RegionKey = "region"; public const string VmIdKey = "vmId"; public const string PublicIpV4AddressKey = "publicIpV4Address"; public const string FullyQualifiedDomainNameKey = "fullyQualifiedDomainName"; public delegate void OnAgentCommunicationErrorEvent(string error); public delegate void OnMaintenanceEvent(DateTime? NextScheduledMaintenanceUtc); public delegate void OnSessionConfigUpdate(SessionConfig sessionConfig); public delegate void OnServerActiveEvent(); public delegate void OnShutdownEventk(); private const string GsdkConfigFileEnvVarKey = "GSDK_CONFIG_FILE"; private static string _baseUrl = string.Empty; private static GSDKConfiguration _gsdkconfig; private static IDictionary<string, string> _configMap; private static SimpleJsonInstance _jsonInstance = new SimpleJsonInstance(); private static GameObject _agentView; public static SessionConfig SessionConfig = new SessionConfig(); public static HeartbeatRequest CurrentState = new HeartbeatRequest(); public static ErrorStates CurrentErrorState = ErrorStates.Ok; public static bool IsProcessing; public static bool IsDebugging = true; public static event OnShutdownEventk OnShutDownCallback; public static event OnMaintenanceEvent OnMaintenanceCallback; public static event OnAgentCommunicationErrorEvent OnAgentErrorCallback; public static event OnServerActiveEvent OnServerActiveCallback; public static event OnSessionConfigUpdate OnSessionConfigUpdateEvent; public static void Start() { string fileName = Environment.GetEnvironmentVariable(GsdkConfigFileEnvVarKey); if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName)) { _gsdkconfig = _jsonInstance.DeserializeObject<GSDKConfiguration>(File.ReadAllText(fileName)); } else { Debug.LogError(string.Format("Environment variable {0} not defined", GsdkConfigFileEnvVarKey)); Application.Quit(); } _baseUrl = string.Format("http://{0}/v1/sessionHosts/{1}/heartbeats", _gsdkconfig.HeartbeatEndpoint, _gsdkconfig.SessionHostId); CurrentState.CurrentGameState = GameState.Initializing; CurrentErrorState = ErrorStates.Ok; CurrentState.CurrentPlayers = new List<ConnectedPlayer>(); if (_configMap == null) { _configMap = CreateConfigMap(_gsdkconfig); } if (IsDebugging) { Debug.Log(_baseUrl); Debug.Log(_gsdkconfig.SessionHostId); Debug.Log(_gsdkconfig.LogFolder); } //Create an agent that can talk on the main-thread and pull on an interval. //This is a unity thing, need an object in the scene. if(_agentView == null) { _agentView = new GameObject("PlayFabAgentView"); _agentView.AddComponent<PlayFabMultiplayerAgentView>(); UnityEngine.Object.DontDestroyOnLoad(_agentView); } } private static IDictionary<string, string> CreateConfigMap(GSDKConfiguration localConfig) { var finalConfig = new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase); foreach (KeyValuePair<string, string> certEntry in localConfig.GameCertificates) { finalConfig[certEntry.Key] = certEntry.Value; } foreach (KeyValuePair<string, string> metadata in localConfig.BuildMetadata) { finalConfig[metadata.Key] = metadata.Value; } foreach (KeyValuePair<string, string> port in localConfig.GamePorts) { finalConfig[port.Key] = port.Value; } finalConfig[HeartbeatEndpointKey] = localConfig.HeartbeatEndpoint; finalConfig[ServerIdKey] = localConfig.SessionHostId; finalConfig[VmIdKey] = localConfig.VmId; finalConfig[LogFolderKey] = localConfig.LogFolder; finalConfig[SharedContentFolderKey] = localConfig.SharedContentFolder; finalConfig[CertificateFolderKey] = localConfig.CertificateFolder; finalConfig[TitleIdKey] = localConfig.TitleId; finalConfig[BuildIdKey] = localConfig.BuildId; finalConfig[RegionKey] = localConfig.Region; finalConfig[PublicIpV4AddressKey] = localConfig.PublicIpV4Address; finalConfig[FullyQualifiedDomainNameKey] = localConfig.FullyQualifiedDomainName; return finalConfig; } public static void ReadyForPlayers() { CurrentState.CurrentGameState = GameState.StandingBy; } public static GameServerConnectionInfo GetGameServerConnectionInfo() { return _gsdkconfig.GameServerConnectionInfo; } public static void UpdateConnectedPlayers(IList<ConnectedPlayer> currentlyConnectedPlayers) { CurrentState.CurrentPlayers = currentlyConnectedPlayers; } public static IDictionary<string, string> GetConfigSettings() { return new Dictionary<string, string>(_configMap, StringComparer.OrdinalIgnoreCase); } public static IList<string> GetInitialPlayers() { return new List<string>(SessionConfig.InitialPlayers); } public static IEnumerator SendHeartBeatRequest() { string payload = _jsonInstance.SerializeObject(CurrentState); if (string.IsNullOrEmpty(payload)) { yield break; } byte[] payloadBytes = Encoding.UTF8.GetBytes(payload); if (IsDebugging) { Debug.Log($"state: {CurrentState}, payload: {payload}"); } using (UnityWebRequest req = new UnityWebRequest(_baseUrl, UnityWebRequest.kHttpVerbPOST)) { req.SetRequestHeader("Accept","application/json"); req.SetRequestHeader("Content-Type","application/json"); req.downloadHandler = new DownloadHandlerBuffer(); req.uploadHandler = new UploadHandlerRaw(payloadBytes) {contentType = "application/json"}; yield return req.SendWebRequest(); if (req.isNetworkError || req.isHttpError) { Guid guid = Guid.NewGuid(); Debug.LogFormat("CurrentError: {0} - {1}", req.error, guid.ToString()); //Exponential backoff for 30 minutes for retries. switch (CurrentErrorState) { case ErrorStates.Ok: CurrentErrorState = ErrorStates.Retry30S; if (IsDebugging) { Debug.Log("Retrying heartbeat in 30s"); } break; case ErrorStates.Retry30S: CurrentErrorState = ErrorStates.Retry5M; if (IsDebugging) { Debug.Log("Retrying heartbeat in 5m"); } break; case ErrorStates.Retry5M: CurrentErrorState = ErrorStates.Retry10M; if (IsDebugging) { Debug.Log("Retrying heartbeat in 10m"); } break; case ErrorStates.Retry10M: CurrentErrorState = ErrorStates.Retry15M; if (IsDebugging) { Debug.Log("Retrying heartbeat in 15m"); } break; case ErrorStates.Retry15M: CurrentErrorState = ErrorStates.Cancelled; if (IsDebugging) { Debug.Log("Agent reconnection cannot be established - cancelling"); } break; } if (OnAgentErrorCallback != null) { OnAgentErrorCallback.Invoke(req.error); } IsProcessing = false; } else // success path { string json = Encoding.UTF8.GetString(req.downloadHandler.data); if (string.IsNullOrEmpty(json)) { yield break; } HeartbeatResponse hb = _jsonInstance.DeserializeObject<HeartbeatResponse>(json); if (hb != null) { ProcessAgentResponse(hb); } CurrentErrorState = ErrorStates.Ok; IsProcessing = false; } } } private static void ProcessAgentResponse(HeartbeatResponse heartBeat) { bool updateConfig = false; if (SessionConfig != heartBeat.SessionConfig) { updateConfig = true; } SessionConfig.CopyNonNullFields(heartBeat.SessionConfig); try { if(OnSessionConfigUpdateEvent != null) OnSessionConfigUpdateEvent.Invoke(SessionConfig); } catch(Exception e) { if(IsDebugging) { Debug.LogException(e); } } if (!string.IsNullOrEmpty(heartBeat.NextScheduledMaintenanceUtc)) { DateTime scheduledMaintDate; if (DateTime.TryParse( heartBeat.NextScheduledMaintenanceUtc, null, DateTimeStyles.RoundtripKind, out scheduledMaintDate)) { if (OnMaintenanceCallback != null) { OnMaintenanceCallback.Invoke(scheduledMaintDate); } } } switch (heartBeat.Operation) { case GameOperation.Continue: //No Action Required. break; case GameOperation.Active: //Transition Server State to Active. CurrentState.CurrentGameState = GameState.Active; _configMap.Add(SessionIdKey, heartBeat.SessionConfig.SessionId); _configMap.Add(SessionCookieKey, heartBeat.SessionConfig.SessionCookie); if (OnServerActiveCallback != null) { OnServerActiveCallback.Invoke(); } break; case GameOperation.Terminate: if (CurrentState.CurrentGameState == GameState.Terminated) { break; } //Transition Server to a Termination state. CurrentState.CurrentGameState = GameState.Terminating; if (OnShutDownCallback != null) { OnShutDownCallback.Invoke(); } break; default: Debug.LogWarning("Unknown operation received: " + heartBeat.Operation); break; } if (IsDebugging) { Debug.LogFormat("Operation: {0}, Maintenance:{1}, State: {2}", heartBeat.Operation, heartBeat.NextScheduledMaintenanceUtc, CurrentState.CurrentGameState); } } } } #endif
38.106742
140
0.549536
[ "Apache-2.0" ]
CaptainPineapple/gsdk
UnityGsdk/Assets/PlayFabSdk/MultiplayerAgent/PlayFabMultiplayerAgentAPI.cs
13,568
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class HandClapScript : MonoBehaviour { public void Clap() { Camera.main.GetComponent<cameraShake>().SmallShake(); } }
15.266667
61
0.707424
[ "MIT" ]
ojaypopedev/SwatTime
SwatTime/Assets/HandClapScript.cs
231
C#
using System.Collections.Generic; using Findit.API.Core; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Authorization; namespace Findit.API.Controllers { public class ValuesController : BaseController { [AllowAnonymous] // GET api/values [HttpGet] public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/values/5 [HttpGet("{id}")] public string Get(int id) { return "value"; } // POST api/values [HttpPost] public void Post([FromBody]string value) { } // PUT api/values/5 [HttpPut("{id}")] public void Put(int id, [FromBody]string value) { } // DELETE api/values/5 [HttpDelete("{id}")] public void Delete(int id) { } } }
16.795455
50
0.652233
[ "MIT" ]
robnvd/Findit.API
src/Findit.API/Controllers/ValuesController.cs
741
C#
using CarShop.Data.Models; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CarShop.Data { public class CarshopDbContext :DbContext { public DbSet<Car> Cars { get; set; } public DbSet<User> Users { get; set; } public DbSet<Issue> Issues { get; set; } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer("Server=.; Database=Carshop; Integrated Security=True"); } } } }
23.066667
100
0.653179
[ "MIT" ]
villdimova/SoftUni-WEB
ExamPreparation/CarShop/CarShop/Data/CarshopDbContext.cs
694
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. namespace Microsoft.Management.UI.Internal { /// <summary> /// The FilterRulePanelItemType enum is used to classify a <see cref="FilterRulePanelItem"/>'s /// hierarchical relationship within a <see cref="FilterRulePanel"/>. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.MSInternal", "CA903:InternalNamespaceShouldNotContainPublicTypes")] public enum FilterRulePanelItemType { /// <summary> /// A FilterRulePanelItemType of FirstHeader indicates that a FilterRulePanelItem /// is the first item in the FilterRulePanel. /// </summary> FirstHeader = 0, /// <summary> /// A FilterRulePanelItemType of Header indicates that a FilterRulePanelItem with /// some GroupId is the first item in the FilterRulePanel with that GroupId. /// </summary> Header = 1, /// <summary> /// A FilterRulePanelItemType of Item indicates that a FilterRulePanelItem with /// some GroupId is not the first item in the FilterRulePanel with that GroupId. /// </summary> Item = 2 } }
37.875
131
0.667492
[ "MIT" ]
10088/PowerShell
src/Microsoft.Management.UI.Internal/ManagementList/FilterProviders/FilterRulePanelItemType.cs
1,212
C#
namespace ChainOfResponsibilityPattern { /// <summary> /// The 'Handler' abstract class /// </summary> internal abstract class Approver { protected Approver Successor { get; set; } public void SetSuccessor(Approver successor) { Successor = successor; } public abstract void ProcessRequest(Purchase purchase); } }
21.777778
63
0.612245
[ "MIT" ]
PhilShishov/Design-Patterns
BehavioralPatterns/ChainOfResponsibilityPattern/Approver.cs
394
C#
namespace RippleDotNetCore.Rippled.Models.Requests.Ledger { public class LedgerRequestParams { public string LedgerHash { get; set; } public string LedgerIndex { get; set; } public bool Full { get; set; } public bool Accounts { get; set; } public bool Transactions { get; set; } public bool Expand { get; set; } public bool OwnerFunds { get; set; } public bool Binary { get; set; } } }
30.866667
58
0.606911
[ "MIT" ]
dxzcc/RippleDotNetCore
src/RippleDotNetCore.Rippled/Models/Requests/Ledger/LedgerRequestParams.cs
465
C#
using System; using System.Collections.Generic; using System.Text; namespace PartsTreeSystem { public class Asset { internal virtual Difference GetDifference(int instanceID) { return null; } internal virtual void SetDifference(int instanceID, Difference difference) { } } }
21.769231
80
0.780919
[ "Apache-2.0" ]
effekseer/PartsTreeSystem
PartsTreeSystem/Asset.cs
285
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 Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.dms_enterprise.Transform; using Aliyun.Acs.dms_enterprise.Transform.V20181101; using System.Collections.Generic; namespace Aliyun.Acs.dms_enterprise.Model.V20181101 { public class RegisterUserRequest : RpcAcsRequest<RegisterUserResponse> { public RegisterUserRequest() : base("dms_enterprise", "2018-11-01", "RegisterUser", "dmsenterprise", "openAPI") { } private string roleNames; private long? uid; private string userNick; private long? tid; public string RoleNames { get { return roleNames; } set { roleNames = value; DictionaryUtil.Add(QueryParameters, "RoleNames", value); } } public long? Uid { get { return uid; } set { uid = value; DictionaryUtil.Add(QueryParameters, "Uid", value.ToString()); } } public string UserNick { get { return userNick; } set { userNick = value; DictionaryUtil.Add(QueryParameters, "UserNick", value); } } public long? Tid { get { return tid; } set { tid = value; DictionaryUtil.Add(QueryParameters, "Tid", value.ToString()); } } public override RegisterUserResponse GetResponse(Core.Transform.UnmarshallerContext unmarshallerContext) { return RegisterUserResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
23.762376
112
0.667917
[ "Apache-2.0" ]
bitType/aliyun-openapi-net-sdk
aliyun-net-sdk-dms-enterprise/Dms_enterprise/Model/V20181101/RegisterUserRequest.cs
2,400
C#
using Newtonsoft.Json; using System.Web.Http; namespace Swagger_Test.Controllers { public class SymbolsController : ApiController { public Symbols Post(Symbols x) { return x; } } public class Symbols { [JsonProperty(PropertyName = "@id")] public int @id; [JsonProperty(PropertyName = "@name")] public string @name; [JsonIgnore] public string details; } }
19.416667
50
0.579399
[ "BSD-3-Clause" ]
heldersepu/Swagger-Net-Test
Swagger_Test/Controllers/SymbolsController.cs
468
C#
using System; using System.Linq; using Microsoft.CodeAnalysis; namespace Avalonia.PropertyGenerator.CSharp { internal sealed class StyledProperty : Property { private StyledProperty(IFieldSymbol field, string name, bool clrPropertyExists, Accessibility clrPropertyAccessibility) : base(field, name) { ClrPropertyExists = clrPropertyExists; ClrPropertyAccessibility = clrPropertyAccessibility; } public bool ClrPropertyExists { get; } public Accessibility ClrPropertyAccessibility { get; } public static new StyledProperty? TryCreate(Types types, IFieldSymbol field) { var name = GetPropertyName(field); if (name is null) { return null; } var clrPropertyExists = false; if (field.ContainingType is INamedTypeSymbol declaringType) { clrPropertyExists = declaringType.GetMembers().Any(x => String.Equals(x.Name, name, StringComparison.Ordinal)); } return new StyledProperty(field, name, clrPropertyExists, field.DeclaredAccessibility); } } }
30.95
128
0.617124
[ "MIT" ]
jp2masa/Avalonia.PropertyGenerator
src/Avalonia.PropertyGenerator.CSharp/StyledProperty.cs
1,238
C#
using HelperUtilities.IO; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp1 { class Program { static void Main(string[] args) { Logger _logger = new Logger(); _logger.AppendLog("test"); } } }
16.904762
42
0.605634
[ "MIT" ]
vibs2006/OWIN-WebAPI-Service
ConsoleApp1/Program.cs
357
C#
using System; using System.Drawing; using System.IO; using NUnit.Framework; namespace GraphicsCourse.Task2.UnitTests; public class Tests { private Drawer _drawer = null!; [SetUp] public void Setup() { _drawer = new Drawer(new Size(800, 800)); } [TestCase(1, 0, 1, 0)] [TestCase(1, 0, 1, 100)] [TestCase(1, 0, 1, 200)] [TestCase(1, 0, 1, 300)] [TestCase(1, 0, 1, 400)] [TestCase(1, 0, 1, 500)] [TestCase(1, 0, 1, 600)] [TestCase(1, 0, 1, 700)] [TestCase(1, 0, 1, 800)] public void MoveVertical(float a, float b, float c, float d) { Draw(a,b,c,d); } [TestCase(1, 0, 1, -800)] [TestCase(1, 0, 1, -700)] [TestCase(1, 0, 1, -600)] [TestCase(1, 0, 1, -500)] [TestCase(1, 0, 1, -400)] [TestCase(1, 0, 1, -300)] [TestCase(1, 0, 1, -200)] [TestCase(1, 0, 1, -100)] public void MoveVerticalNegative(float a, float b, float c, float d) { Draw(a,b,c,d); } [TestCase(1, 0, 1, 400)] [TestCase(1, 100, 1, 400)] [TestCase(1, 200, 1, 400)] [TestCase(1, 300, 1, 400)] [TestCase(1, 400, 1, 400)] [TestCase(1, 500, 1, 400)] [TestCase(1, 600, 1, 400)] [TestCase(1, 700, 1, 400)] [TestCase(1, 800, 1, 400)] public void MoveHorizontal(float a, float b, float c, float d) { Draw(a,b,c,d); } [TestCase(1, -800, 1, 400)] [TestCase(1, -700, 1, 400)] [TestCase(1, -600, 1, 400)] [TestCase(1, -500, 1, 400)] [TestCase(1, -400, 1, 400)] [TestCase(1, -300, 1, 400)] [TestCase(1, -200, 1, 400)] [TestCase(1, -100, 1, 400)] [TestCase(1, 0, 1, 400)] public void MoveHorizontalNegative(float a, float b, float c, float d) { Draw(a,b,c,d); } [TestCase(-0.01f, 799, 1, 400)] [TestCase(-0.01f, 700, 1, 400)] [TestCase(-0.01f, 600, 1, 400)] [TestCase(-0.01f, 500, 1, 400)] [TestCase(-0.01f, 400, 1, 400)] [TestCase(-0.01f, 300, 1, 400)] [TestCase(-0.01f, 200, 1, 400)] [TestCase(-0.01f, 100, 1, 400)] [TestCase(-0.01f, 0, 1, 400)] public void MoveHorizontalNegativeA(float a, float b, float c, float d) { Draw(a,b,c,d); } [TestCase(1, 0, 1, 0)] [TestCase(1, 100, 1, 100)] [TestCase(1, 200, 1, 200)] [TestCase(1, 300, 1, 300)] [TestCase(1, 400, 1, 400)] [TestCase(1, 500, 1, 500)] [TestCase(1, 600, 1, 600)] [TestCase(1, 700, 1, 700)] [TestCase(1, 800, 1, 800)] public void MoveDiagonal(float a, float b, float c, float d) { Draw(a,b,c,d); } [TestCase(-100, 400, 1, 400)] [TestCase(-10, 400, 1, 400)] [TestCase(-1, 400, 1, 400)] [TestCase(-0.1f, 400, 1, 400)] [TestCase(-0.01f, 400, 1, 400)] [TestCase(-0.001f, 400, 1, 400)] [TestCase(0.001f, 400, 1, 400)] [TestCase(0.01f, 400, 1, 400)] [TestCase(0.1f, 400, 1, 400)] [TestCase(1, 400, 1, 400)] [TestCase(10, 400, 1, 400)] [TestCase(100, 400, 1, 400)] public void ChangeA(float a, float b, float c, float d) { Draw(a, b, c, d, context => a + ".bmp"); } [TestCase(-100, 400, 1, 400)] [TestCase(-10, 400, 1, 400)] [TestCase(-1, 400, 1, 400)] [TestCase(-0.1f, 400, 1, 400)] [TestCase(-0.01f, 400, 1, 400)] [TestCase(-0.001f, 400, 1, 400)] [TestCase(0.001f, 400, 1, 400)] [TestCase(0.01f, 400, 1, 400)] [TestCase(0.1f, 400, 1, 400)] [TestCase(1, 400, 1, 400)] [TestCase(10, 400, 1, 400)] [TestCase(100, 400, 1, 400)] public void ChangeC(float c, float b, float a, float d) { Draw(a, b, c, d, context => c + ".bmp"); } private void Draw(float a, float b, float c, float d, Func<TestContext.TestAdapter, string> imageNameFactory) { var context = TestContext.CurrentContext.Test; var filename = imageNameFactory(context); var directory = Path.Join( "TestImages", (context.MethodName ?? throw new Exception())); if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } _drawer.Draw(Path.Join(directory, filename), new ParabolaParameters(a, b, c, d)); } private void Draw(float a, float b, float c, float d) { Draw(a, b, c, d, adapter => adapter.MethodName + string.Join("_", TestContext.CurrentContext.Test.Arguments) + ".bmp"); } }
28.603896
127
0.542565
[ "Apache-2.0" ]
gODeaLoAple/urfu-computer-grahpics
GraphicsCourse/GraphicsCourse.Task2.UnitTests/Tests.cs
4,405
C#
namespace Dio.Series { public class Serie : EntidadeBase { public Serie(Genero genero, string descricao, string titulo, int ano) { Genero = genero; Descricao = descricao; Titulo = titulo; Ano = ano; } public Serie(Guid id, Genero genero, string descricao, string titulo, int ano) { ID = id; Genero = genero; Descricao = descricao; Titulo = titulo; Ano = ano; } private Genero Genero { get; set; } private string Titulo { get; set; } private string Descricao { get; set; } private int Ano { get; set; } public override string ToString() { return $@"Gênero: {Genero}\n Titulo: {Titulo}\n Descrição: {Descricao}\n Ano de Início: {Ano}"; } public string retornaTitulo() { return Titulo; } public Genero retornaGenero() { return Genero; } public void remove() { Excluido_em = DateTime.Now; } } }
24.058824
87
0.461288
[ "CC0-1.0" ]
mckatoo/localiza-bootcamp-2
Cadastro_de_Series/Dio.Series/Classes/Serie.cs
1,231
C#
using NPOI.OpenXml4Net.Util; using System; using System.IO; using System.Xml; using System.Xml.Serialization; namespace NPOI.OpenXmlFormats.Spreadsheet { [Serializable] [XmlType(Namespace = "http://schemas.openxmlformats.org/spreadsheetml/2006/main")] public class CT_MergeCell { private string refField; [XmlAttribute] public string @ref { get { return refField; } set { refField = value; } } public static CT_MergeCell Parse(XmlNode node, XmlNamespaceManager namespaceManager) { if (node == null) { return null; } CT_MergeCell cT_MergeCell = new CT_MergeCell(); cT_MergeCell.@ref = XmlHelper.ReadString(node.Attributes["ref"]); return cT_MergeCell; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<{0}", nodeName)); XmlHelper.WriteAttribute(sw, "ref", @ref); sw.Write("/>"); } } }
19.255319
86
0.687293
[ "MIT" ]
iNeverSleeeeep/NPOI-For-Unity
NPOI.OpenXmlFormats.Spreadsheet/CT_MergeCell.cs
905
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; using Web001.Services; namespace Web001 { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.TryAddScoped<ICalculator, Calculator>(); services.AddControllersWithViews(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
26.363636
79
0.602759
[ "MIT" ]
axzxs2001/AspNetGitDemo
AspNetGitDemo/Web001/Startup.cs
1,450
C#
namespace CollectIt.Database.Abstractions.Account.Exceptions; public class UserAlreadySubscribedException : UserSubscriptionException { public UserAlreadySubscribedException(int userId, int subscriptionId) : base(userId, subscriptionId) { } }
29.222222
73
0.787072
[ "Apache-2.0" ]
Reb1azzze/collect-it
src/CollectIt.Database/CollectIt.Database.Abstractions/Account/Exceptions/UserAlreadySubscribedException.cs
263
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using resources.Data; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Http; using resources.Services; namespace resources { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(); services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); // Add framework services. services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton<ICurrentContextAdapter, CurrentContextAdapter>(); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseOAuthIntrospection(options => { options.Authority = new Uri("http://localhost:54540/"); options.Audiences.Add("aurelia-openiddict-resources"); options.ClientId = "aurelia-openiddict-resources"; options.ClientSecret = "846B62D0-DEF9-4215-A99D-86E6B8DAB342"; options.RequireHttpsMetadata = false; // Note: you can override the default name and role claims: // options.NameClaimType = "custom_name_claim"; // options.RoleClaimType = "custom_role_claim"; }); app.UseCors(builder => { builder.AllowAnyHeader(); builder.AllowAnyMethod(); builder.AllowAnyOrigin(); //builder.WithOrigins("http://localhost:49862"); //builder.WithMethods("GET"); //builder.WithHeaders("Authorization"); }); //app.UseJwtBearerAuthentication(new JwtBearerOptions() //{ // RequireHttpsMetadata = false, // AutomaticAuthenticate = true, // AutomaticChallenge = true, // Audience = "aurelia-openiddict-resources", // Authority = "http://localhost:54540/" //}); app.UseMvc(); } } }
36.461538
109
0.619952
[ "CC0-1.0" ]
SoftwareMasons/aurelia-openiddict
src/resources/Startup.cs
3,320
C#
namespace Auditio.Content; public class Class1 { }
10.4
27
0.769231
[ "MIT" ]
cwoodruff/auditio
auditio/Auditio.Content/Class1.cs
54
C#
//GENERATED: CS Code using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace UnrealEngine{ public partial class ALODActor:AActor { [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern new IntPtr StaticClass(); } }
24.583333
55
0.789831
[ "MIT" ]
RobertAcksel/UnrealCS
Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile/ALODActor.cs
295
C#
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Threading.Tasks; using Microsoft.AspNetCore.Server.IntegrationTesting; using Microsoft.AspNetCore.Testing; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging.Testing; using Xunit; using Xunit.Abstractions; namespace E2ETests { // These tests publish(on the machine where these tests on run) the MusicStore app to a local folder first // and then copy the published output to the target NanoServer and launch them. public class SmokeTestsOnNanoServerUsingStandaloneRuntime { private readonly SmokeTestsOnNanoServer _smokeTestsOnNanoServer; private readonly RemoteDeploymentConfig _remoteDeploymentConfig; public SmokeTestsOnNanoServerUsingStandaloneRuntime(ITestOutputHelper output) { _remoteDeploymentConfig = RemoteDeploymentConfigHelper.GetConfiguration(); _smokeTestsOnNanoServer = new SmokeTestsOnNanoServer(output, _remoteDeploymentConfig); } [ConditionalTheory, Trait("E2ETests", "NanoServer")] [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)] [SkipIfEnvironmentVariableNotEnabled("RUN_TESTS_ON_NANO")] [InlineData(ServerType.Kestrel, 5000, ApplicationType.Standalone)] [InlineData(ServerType.HttpSys, 5000, ApplicationType.Standalone)] [InlineData(ServerType.IIS, 8080, ApplicationType.Standalone)] public async Task Test(ServerType serverType, int portToListen, ApplicationType applicationType) { var applicationBaseUrl = $"http://{_remoteDeploymentConfig.ServerName}:{portToListen}/"; await _smokeTestsOnNanoServer.RunTestsAsync(serverType, applicationBaseUrl, applicationType); } } // Tests here test portable app scenario, so we copy the dotnet runtime onto the // target server's file share and after setting up a remote session to the server, we update the PATH environment // to have the path to this copied dotnet runtime folder in the share. // The dotnet runtime is copied only once for all the tests in this class. public class SmokeTestsOnNanoServerUsingSharedRuntime : IClassFixture<SmokeTestsOnNanoServerUsingSharedRuntime.DotnetRuntimeSetupTestFixture> { private readonly SmokeTestsOnNanoServer _smokeTestsOnNanoServer; private readonly RemoteDeploymentConfig _remoteDeploymentConfig; public SmokeTestsOnNanoServerUsingSharedRuntime( DotnetRuntimeSetupTestFixture dotnetRuntimeSetupTestFixture, ITestOutputHelper output) { _remoteDeploymentConfig = RemoteDeploymentConfigHelper.GetConfiguration(); _remoteDeploymentConfig.DotnetRuntimePathOnShare = dotnetRuntimeSetupTestFixture.DotnetRuntimePathOnShare; _smokeTestsOnNanoServer = new SmokeTestsOnNanoServer(output, _remoteDeploymentConfig); } [ConditionalTheory, Trait("E2Etests", "NanoServer")] [OSSkipCondition(OperatingSystems.Linux | OperatingSystems.MacOSX)] [SkipIfEnvironmentVariableNotEnabled("RUN_TESTS_ON_NANO")] [InlineData(ServerType.Kestrel, 5000, ApplicationType.Portable)] [InlineData(ServerType.HttpSys, 5000, ApplicationType.Portable)] [InlineData(ServerType.IIS, 8080, ApplicationType.Portable)] public async Task Test(ServerType serverType, int portToListen, ApplicationType applicationType) { var applicationBaseUrl = $"http://{_remoteDeploymentConfig.ServerName}:{portToListen}/"; await _smokeTestsOnNanoServer.RunTestsAsync(serverType, applicationBaseUrl, applicationType); } // Copies dotnet runtime to the target server's file share. public class DotnetRuntimeSetupTestFixture : IDisposable { private bool copiedDotnetRuntime; public DotnetRuntimeSetupTestFixture() { var runNanoServerTests = Environment.GetEnvironmentVariable("RUN_TESTS_ON_NANO"); if (string.IsNullOrWhiteSpace(runNanoServerTests) || string.IsNullOrEmpty(runNanoServerTests) || runNanoServerTests.ToLower() == "false") { return; } RemoteDeploymentConfig = RemoteDeploymentConfigHelper.GetConfiguration(); DotnetRuntimePathOnShare = Path.Combine(RemoteDeploymentConfig.FileSharePath, "dotnet_" + Guid.NewGuid()); // Prefer copying the zip file to fileshare and extracting on file share over copying the extracted // dotnet runtime folder from source to file share as the size could be significantly huge. if (!string.IsNullOrEmpty(RemoteDeploymentConfig.DotnetRuntimeZipFilePath)) { if (!File.Exists(RemoteDeploymentConfig.DotnetRuntimeZipFilePath)) { throw new InvalidOperationException( $"Expected dotnet runtime zip file at '{RemoteDeploymentConfig.DotnetRuntimeFolderPath}', but didn't find one."); } ZippedDotnetRuntimePathOnShare = Path.Combine( RemoteDeploymentConfig.FileSharePath, Path.GetFileName(RemoteDeploymentConfig.DotnetRuntimeZipFilePath)); if (!File.Exists(ZippedDotnetRuntimePathOnShare)) { File.Copy(RemoteDeploymentConfig.DotnetRuntimeZipFilePath, ZippedDotnetRuntimePathOnShare, overwrite: true); Console.WriteLine($"Copied the local dotnet zip folder '{RemoteDeploymentConfig.DotnetRuntimeZipFilePath}' " + $"to the file share path '{RemoteDeploymentConfig.FileSharePath}'"); } if (Directory.Exists(DotnetRuntimePathOnShare)) { Directory.Delete(DotnetRuntimePathOnShare, recursive: true); } ZipFile.ExtractToDirectory(ZippedDotnetRuntimePathOnShare, DotnetRuntimePathOnShare); copiedDotnetRuntime = true; Console.WriteLine($"Extracted dotnet runtime to folder '{DotnetRuntimePathOnShare}'"); } else if (!string.IsNullOrEmpty(RemoteDeploymentConfig.DotnetRuntimeFolderPath)) { if (!Directory.Exists(RemoteDeploymentConfig.DotnetRuntimeFolderPath)) { throw new InvalidOperationException( $"Expected dotnet runtime folder at '{RemoteDeploymentConfig.DotnetRuntimeFolderPath}', but didn't find one."); } Console.WriteLine($"Copying dotnet runtime folder from '{RemoteDeploymentConfig.DotnetRuntimeFolderPath}' to '{DotnetRuntimePathOnShare}'."); Console.WriteLine("This could take some time."); DirectoryCopy(RemoteDeploymentConfig.DotnetRuntimeFolderPath, DotnetRuntimePathOnShare, copySubDirs: true); copiedDotnetRuntime = true; } else { throw new InvalidOperationException("Dotnet runtime is required to be copied for testing portable apps scenario. " + $"Either supply '{nameof(RemoteDeploymentConfig.DotnetRuntimeFolderPath)}' containing the unzipped dotnet runtime content or " + $"supply the dotnet runtime zip file path via '{nameof(RemoteDeploymentConfig.DotnetRuntimeZipFilePath)}'."); } } public RemoteDeploymentConfig RemoteDeploymentConfig { get; } public string ZippedDotnetRuntimePathOnShare { get; } public string DotnetRuntimePathOnShare { get; } private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs) { var dir = new DirectoryInfo(sourceDirName); if (!dir.Exists) { throw new DirectoryNotFoundException( "Source directory does not exist or could not be found: " + sourceDirName); } var dirs = dir.GetDirectories(); if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } var files = dir.GetFiles(); foreach (var file in files) { var temppath = Path.Combine(destDirName, file.Name); file.CopyTo(temppath, false); } if (copySubDirs) { foreach (var subdir in dirs) { var temppath = Path.Combine(destDirName, subdir.Name); DirectoryCopy(subdir.FullName, temppath, copySubDirs); } } } public void Dispose() { if (!copiedDotnetRuntime) { return; } // In case the source is provided as a folder itself, then we wouldn't have the zip file to begin with. if (!string.IsNullOrEmpty(ZippedDotnetRuntimePathOnShare)) { try { Console.WriteLine($"Deleting the dotnet runtime zip file '{ZippedDotnetRuntimePathOnShare}'"); File.Delete(ZippedDotnetRuntimePathOnShare); } catch (Exception ex) { Console.WriteLine($"Failed to delete the dotnet runtime zip file '{ZippedDotnetRuntimePathOnShare}'. Exception: " + ex.ToString()); } } try { Console.WriteLine($"Deleting the dotnet runtime folder '{DotnetRuntimePathOnShare}'"); Directory.Delete(DotnetRuntimePathOnShare, recursive: true); } catch (Exception ex) { Console.WriteLine($"Failed to delete the dotnet runtime folder '{DotnetRuntimePathOnShare}'. Exception: " + ex.ToString()); } } } } class SmokeTestsOnNanoServer : LoggedTest { private readonly RemoteDeploymentConfig _remoteDeploymentConfig; public SmokeTestsOnNanoServer(ITestOutputHelper output, RemoteDeploymentConfig config) : base(output) { _remoteDeploymentConfig = config; } public async Task RunTestsAsync( ServerType serverType, string applicationBaseUrl, ApplicationType applicationType) { var testName = $"SmokeTestsOnNanoServer_{serverType}_{applicationType}"; using (StartLog(out var loggerFactory, testName)) { var logger = loggerFactory.CreateLogger(nameof(SmokeTestsOnNanoServerUsingStandaloneRuntime)); var deploymentParameters = new RemoteWindowsDeploymentParameters( Helpers.GetApplicationPath(), _remoteDeploymentConfig.DotnetRuntimePathOnShare, serverType, RuntimeFlavor.CoreClr, RuntimeArchitecture.x64, _remoteDeploymentConfig.FileSharePath, _remoteDeploymentConfig.ServerName, _remoteDeploymentConfig.AccountName, _remoteDeploymentConfig.AccountPassword) { TargetFramework = Tfm.NetCoreApp50, ApplicationBaseUriHint = applicationBaseUrl, ApplicationType = applicationType }; deploymentParameters.EnvironmentVariables.Add( new KeyValuePair<string, string>("ASPNETCORE_ENVIRONMENT", "SocialTesting")); using (var deployer = new RemoteWindowsDeployer(deploymentParameters, loggerFactory)) { var deploymentResult = await deployer.DeployAsync(); await SmokeTests.RunTestsAsync(deploymentResult, logger); } } } } static class RemoteDeploymentConfigHelper { private static RemoteDeploymentConfig _remoteDeploymentConfig; public static RemoteDeploymentConfig GetConfiguration() { if (_remoteDeploymentConfig == null) { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("remoteDeploymentConfig.json") .AddUserSecrets("MusicStore.E2ETests") .AddEnvironmentVariables() .Build(); _remoteDeploymentConfig = new RemoteDeploymentConfig(); configuration.GetSection("NanoServer").Bind(_remoteDeploymentConfig); } return _remoteDeploymentConfig; } } }
46.736111
161
0.612481
[ "Apache-2.0" ]
06b/AspNetCore
src/MusicStore/test/MusicStore.E2ETests/SmokeTestsOnNanoServer.cs
13,460
C#
using System.Web.Mvc; namespace AlloyDemoKit.Business.VisitorGroupUIStyling { public class OverrideVisitorGroupCssAttribute : OutputProcessorActionFilterAttribute { protected override string Process(string data) { return data .Replace("</head", "<link href=\"/Static/css/VisitorGroupUIOverrides.css\" rel=\"stylesheet\"></link></head"); } protected override bool ShouldProcess(ResultExecutedContext filterContext) { var result = filterContext.Result as ViewResultBase; var view = result?.View as WebFormView; return view != null && (view.ViewPath.Equals("/EPiServer/CMS/Views/VisitorGroups/Index.aspx") || view.ViewPath.Equals("/EPiServer/CMS/Views/VisitorGroups/Edit.aspx")); } } }
39.285714
163
0.654545
[ "Apache-2.0" ]
rholzner/AlloyDemoKit
src/AlloyDemoKit/Business/VisitorGroupUIStyling/OverrideVisitorGroupCss.cs
827
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/sapi.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("14056581-E16C-11D2-BB90-00C04F8EE6C0")] [NativeTypeName("struct ISpDataKey : IUnknown")] public unsafe partial struct ISpDataKey { public void** lpVtbl; [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject) { return ((delegate* stdcall<ISpDataKey*, Guid*, void**, int>)(lpVtbl[0]))((ISpDataKey*)Unsafe.AsPointer(ref this), riid, ppvObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* stdcall<ISpDataKey*, uint>)(lpVtbl[1]))((ISpDataKey*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* stdcall<ISpDataKey*, uint>)(lpVtbl[2]))((ISpDataKey*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetData([NativeTypeName("LPCWSTR")] ushort* pszValueName, [NativeTypeName("ULONG")] uint cbData, [NativeTypeName("const BYTE *")] byte* pData) { return ((delegate* stdcall<ISpDataKey*, ushort*, uint, byte*, int>)(lpVtbl[3]))((ISpDataKey*)Unsafe.AsPointer(ref this), pszValueName, cbData, pData); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int GetData([NativeTypeName("LPCWSTR")] ushort* pszValueName, [NativeTypeName("ULONG *")] uint* pcbData, [NativeTypeName("BYTE *")] byte* pData) { return ((delegate* stdcall<ISpDataKey*, ushort*, uint*, byte*, int>)(lpVtbl[4]))((ISpDataKey*)Unsafe.AsPointer(ref this), pszValueName, pcbData, pData); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetStringValue([NativeTypeName("LPCWSTR")] ushort* pszValueName, [NativeTypeName("LPCWSTR")] ushort* pszValue) { return ((delegate* stdcall<ISpDataKey*, ushort*, ushort*, int>)(lpVtbl[5]))((ISpDataKey*)Unsafe.AsPointer(ref this), pszValueName, pszValue); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int GetStringValue([NativeTypeName("LPCWSTR")] ushort* pszValueName, [NativeTypeName("LPWSTR *")] ushort** ppszValue) { return ((delegate* stdcall<ISpDataKey*, ushort*, ushort**, int>)(lpVtbl[6]))((ISpDataKey*)Unsafe.AsPointer(ref this), pszValueName, ppszValue); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int SetDWORD([NativeTypeName("LPCWSTR")] ushort* pszValueName, [NativeTypeName("DWORD")] uint dwValue) { return ((delegate* stdcall<ISpDataKey*, ushort*, uint, int>)(lpVtbl[7]))((ISpDataKey*)Unsafe.AsPointer(ref this), pszValueName, dwValue); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int GetDWORD([NativeTypeName("LPCWSTR")] ushort* pszValueName, [NativeTypeName("DWORD *")] uint* pdwValue) { return ((delegate* stdcall<ISpDataKey*, ushort*, uint*, int>)(lpVtbl[8]))((ISpDataKey*)Unsafe.AsPointer(ref this), pszValueName, pdwValue); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int OpenKey([NativeTypeName("LPCWSTR")] ushort* pszSubKeyName, [NativeTypeName("ISpDataKey **")] ISpDataKey** ppSubKey) { return ((delegate* stdcall<ISpDataKey*, ushort*, ISpDataKey**, int>)(lpVtbl[9]))((ISpDataKey*)Unsafe.AsPointer(ref this), pszSubKeyName, ppSubKey); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int CreateKey([NativeTypeName("LPCWSTR")] ushort* pszSubKey, [NativeTypeName("ISpDataKey **")] ISpDataKey** ppSubKey) { return ((delegate* stdcall<ISpDataKey*, ushort*, ISpDataKey**, int>)(lpVtbl[10]))((ISpDataKey*)Unsafe.AsPointer(ref this), pszSubKey, ppSubKey); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int DeleteKey([NativeTypeName("LPCWSTR")] ushort* pszSubKey) { return ((delegate* stdcall<ISpDataKey*, ushort*, int>)(lpVtbl[11]))((ISpDataKey*)Unsafe.AsPointer(ref this), pszSubKey); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int DeleteValue([NativeTypeName("LPCWSTR")] ushort* pszValueName) { return ((delegate* stdcall<ISpDataKey*, ushort*, int>)(lpVtbl[12]))((ISpDataKey*)Unsafe.AsPointer(ref this), pszValueName); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int EnumKeys([NativeTypeName("ULONG")] uint Index, [NativeTypeName("LPWSTR *")] ushort** ppszSubKeyName) { return ((delegate* stdcall<ISpDataKey*, uint, ushort**, int>)(lpVtbl[13]))((ISpDataKey*)Unsafe.AsPointer(ref this), Index, ppszSubKeyName); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int EnumValues([NativeTypeName("ULONG")] uint Index, [NativeTypeName("LPWSTR *")] ushort** ppszValueName) { return ((delegate* stdcall<ISpDataKey*, uint, ushort**, int>)(lpVtbl[14]))((ISpDataKey*)Unsafe.AsPointer(ref this), Index, ppszValueName); } } }
51
164
0.662713
[ "MIT" ]
Ethereal77/terrafx.interop.windows
sources/Interop/Windows/um/sapi/ISpDataKey.cs
6,326
C#
using APPRestaurante.UnitOfWork; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace APPRestaurante.Web.Areas.Admin.Controllers { public class ClienteController : BaseController { public ClienteController(IUnitOfWork unit) : base(unit) { } // GET: Admin/Cliente public ActionResult Index() { return View(); } } }
20.043478
63
0.646421
[ "MIT" ]
HugoRoca/app-restaurant
APPRestaurante/APPRestaurante.Web/Areas/Admin/Controllers/ClienteController.cs
463
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using StarkPlatform.CodeAnalysis.Stark.Syntax; using StarkPlatform.CodeAnalysis.PooledObjects; using Roslyn.Utilities; namespace StarkPlatform.CodeAnalysis.Stark.Symbols { internal sealed class LambdaSymbol : SourceMethodSymbol { private readonly Symbol _containingSymbol; private readonly MessageID _messageID; private readonly SyntaxNode _syntax; private readonly ImmutableArray<ParameterSymbol> _parameters; private RefKind _refKind; private TypeSymbolWithAnnotations _returnType; private readonly bool _isSynthesized; private readonly bool _isAsync; /// <summary> /// This symbol is used as the return type of a LambdaSymbol when we are interpreting /// lambda's body in order to infer its return type. /// </summary> internal static readonly TypeSymbol ReturnTypeIsBeingInferred = new UnsupportedMetadataTypeSymbol(); /// <summary> /// This symbol is used as the return type of a LambdaSymbol when we failed to infer its return type. /// </summary> internal static readonly TypeSymbol InferenceFailureReturnType = new UnsupportedMetadataTypeSymbol(); private static readonly TypeSymbolWithAnnotations UnknownReturnType = TypeSymbolWithAnnotations.Create(ErrorTypeSymbol.UnknownResultType); public LambdaSymbol( CSharpCompilation compilation, Symbol containingSymbol, UnboundLambda unboundLambda, ImmutableArray<TypeSymbolWithAnnotations> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, RefKind refKind, TypeSymbolWithAnnotations returnType, DiagnosticBag diagnostics) { _containingSymbol = containingSymbol; _messageID = unboundLambda.Data.MessageID; _syntax = unboundLambda.Syntax; _refKind = refKind; _returnType = returnType.IsNull ? TypeSymbolWithAnnotations.Create(ReturnTypeIsBeingInferred) : returnType; _isSynthesized = unboundLambda.WasCompilerGenerated; _isAsync = unboundLambda.IsAsync; // No point in making this lazy. We are always going to need these soon after creation of the symbol. _parameters = MakeParameters(compilation, unboundLambda, parameterTypes, parameterRefKinds, diagnostics); } public MessageID MessageID { get { return _messageID; } } public override MethodKind MethodKind { get { return MethodKind.AnonymousFunction; } } public override bool IsExtern { get { return false; } } public override bool IsSealed { get { return false; } } public override bool IsAbstract { get { return false; } } public override bool IsReadOnly => false; public override bool IsVirtual { get { return false; } } public override bool IsOverride { get { return false; } } public override bool IsStatic { get { return false; } } public override bool IsAsync { get { return _isAsync; } } internal sealed override ObsoleteAttributeData ObsoleteAttributeData { get { return null; } } internal sealed override bool IsMetadataNewSlot(bool ignoreInterfaceImplementationChanges = false) { return false; } internal sealed override bool IsMetadataVirtual(bool ignoreInterfaceImplementationChanges = false) { return false; } internal override bool IsMetadataFinal { get { return false; } } public override bool IsVararg { get { return false; } } internal override bool HasSpecialName { get { return false; } } internal override System.Reflection.MethodImplAttributes ImplementationAttributes { get { return default(System.Reflection.MethodImplAttributes); } } internal override bool RequiresSecurityObject { get { return false; } } public override DllImportData GetDllImportData() { return null; } internal override MarshalPseudoCustomAttributeData ReturnValueMarshallingInformation { get { return null; } } internal override ImmutableArray<string> GetAppliedConditionalSymbols() { return ImmutableArray<string>.Empty; } public override bool ReturnsVoid { get { return !this.ReturnType.IsNull && this.ReturnType.SpecialType == SpecialType.System_Void; } } public override RefKind RefKind { get { return _refKind; } } public override TypeSymbolWithAnnotations ReturnType { get { return _returnType; } } // In error recovery and type inference scenarios we do not know the return type // until after the body is bound, but the symbol is created before the body // is bound. Fill in the return type post hoc in these scenarios; the // IDE might inspect the symbol and want to know the return type. internal void SetInferredReturnType(RefKind refKind, TypeSymbolWithAnnotations inferredReturnType) { Debug.Assert(!inferredReturnType.IsNull); Debug.Assert((object)_returnType.TypeSymbol == ReturnTypeIsBeingInferred); _refKind = refKind; _returnType = inferredReturnType; } public override ImmutableArray<CustomModifier> RefCustomModifiers { get { return ImmutableArray<CustomModifier>.Empty; } } internal override bool IsExplicitInterfaceImplementation { get { return false; } } public override ImmutableArray<MethodSymbol> ExplicitInterfaceImplementations { get { return ImmutableArray<MethodSymbol>.Empty; } } public override Symbol AssociatedSymbol { get { return null; } } public override ImmutableArray<TypeSymbolWithAnnotations> TypeArguments { get { return ImmutableArray<TypeSymbolWithAnnotations>.Empty; } } public override ImmutableArray<TypeParameterSymbol> TypeParameters { get { return ImmutableArray<TypeParameterSymbol>.Empty; } } public override ImmutableArray<TypeSymbol> ThrowsList => ImmutableArray<TypeSymbol>.Empty; public override int Arity { get { return 0; } } public override ImmutableArray<ParameterSymbol> Parameters { get { return _parameters; } } internal override bool TryGetThisParameter(out ParameterSymbol thisParameter) { // Lambda symbols have no "this" parameter thisParameter = null; return true; } public override Accessibility DeclaredAccessibility { get { return Accessibility.Private; } } public override ImmutableArray<Location> Locations { get { return ImmutableArray.Create<Location>(_syntax.Location); } } /// <summary> /// Locations[0] on lambda symbols covers the entire syntax, which is inconvenient but remains for compatibility. /// For better diagnostics quality, use the DiagnosticLocation instead, which points to the "delegate" or the "=>". /// </summary> internal Location DiagnosticLocation { get { switch (_syntax.Kind()) { case SyntaxKind.AnonymousMethodExpression: return ((AnonymousMethodExpressionSyntax)_syntax).DelegateKeyword.GetLocation(); case SyntaxKind.SimpleLambdaExpression: case SyntaxKind.ParenthesizedLambdaExpression: return ((LambdaExpressionSyntax)_syntax).ArrowToken.GetLocation(); default: return Locations[0]; } } } public override ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray.Create<SyntaxReference>(_syntax.GetReference()); } } public override Symbol ContainingSymbol { get { return _containingSymbol; } } internal override StarkPlatform.Cci.CallingConvention CallingConvention { get { return StarkPlatform.Cci.CallingConvention.Default; } } public override bool IsExtensionMethod { get { return false; } } public override bool HidesBaseMethodsByName { get { return false; } } private ImmutableArray<ParameterSymbol> MakeParameters( CSharpCompilation compilation, UnboundLambda unboundLambda, ImmutableArray<TypeSymbolWithAnnotations> parameterTypes, ImmutableArray<RefKind> parameterRefKinds, DiagnosticBag diagnostics) { Debug.Assert(parameterTypes.Length == parameterRefKinds.Length); if (!unboundLambda.HasSignature || unboundLambda.ParameterCount == 0) { // The parameters may be omitted in source, but they are still present on the symbol. return parameterTypes.SelectAsArray((type, ordinal, arg) => SynthesizedParameterSymbol.Create( arg.owner, type, ordinal, arg.refKinds[ordinal], GeneratedNames.LambdaCopyParameterName(ordinal)), // Make sure nothing binds to this. (owner: this, refKinds: parameterRefKinds)); } var builder = ArrayBuilder<ParameterSymbol>.GetInstance(unboundLambda.ParameterCount); var hasExplicitlyTypedParameterList = unboundLambda.HasExplicitlyTypedParameterList; var numDelegateParameters = parameterTypes.Length; for (int p = 0; p < unboundLambda.ParameterCount; ++p) { // If there are no types given in the lambda then used the delegate type. // If the lambda is typed then the types probably match the delegate types; // if they do not, use the lambda types for binding. Either way, if we // can, then we use the lambda types. (Whatever you do, do not use the names // in the delegate parameters; they are not in scope!) TypeSymbolWithAnnotations type; RefKind refKind; if (hasExplicitlyTypedParameterList) { type = unboundLambda.ParameterType(p); refKind = unboundLambda.RefKind(p); } else if (p < numDelegateParameters) { type = parameterTypes[p]; refKind = parameterRefKinds[p]; } else { type = TypeSymbolWithAnnotations.Create(new ExtendedErrorTypeSymbol(compilation, name: string.Empty, arity: 0, errorInfo: null)); refKind = RefKind.None; } var name = unboundLambda.ParameterName(p); var location = unboundLambda.ParameterLocation(p); var locations = location == null ? ImmutableArray<Location>.Empty : ImmutableArray.Create<Location>(location); var parameter = new SourceSimpleParameterSymbol(this, type, p, refKind, name, locations); builder.Add(parameter); } var result = builder.ToImmutableAndFree(); return result; } public sealed override bool Equals(object symbol) { if ((object)this == symbol) return true; var lambda = symbol as LambdaSymbol; return (object)lambda != null && lambda._syntax == _syntax && lambda._refKind == _refKind && TypeSymbol.Equals(lambda.ReturnType.TypeSymbol, this.ReturnType.TypeSymbol, TypeCompareKind.ConsiderEverything2) && System.Linq.ImmutableArrayExtensions.SequenceEqual(lambda.ParameterTypes, this.ParameterTypes, (p1, p2) => p1.TypeSymbol.Equals(p2.TypeSymbol)) && Equals(lambda.ContainingSymbol, this.ContainingSymbol); } public override int GetHashCode() { return _syntax.GetHashCode(); } public override bool IsImplicitlyDeclared { get { return _isSynthesized; } } internal override bool GenerateDebugInfo { get { return true; } } public override ImmutableArray<TypeParameterConstraintClause> GetTypeParameterConstraintClauses(bool early) => ImmutableArray<TypeParameterConstraintClause>.Empty; internal override int CalculateLocalSyntaxOffset(int localPosition, SyntaxTree localTree) { throw ExceptionUtilities.Unreachable; } } }
35.53616
171
0.590807
[ "Apache-2.0" ]
stark-lang/stark-roslyn
src/Compilers/Stark/Portable/Symbols/Source/LambdaSymbol.cs
14,252
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using MLAgents; using System; [RequireComponent(typeof(Rigidbody))] [RequireComponent(typeof(CarVehicle))] public class AltAgentCar : AbstractAgentCarController { // A reference to the vehicle "driven" by the agent private AbstractVehicle car; // a reference to the dummy car private AbstractDummyCarController dummyCarController; /* * It was noted that the update and AgentAction were not synchronized * The agent action was running 3 - 4 times before an update excecutes * Because of that the agent was mimicking a "Slow" dummy car * Thus environment calls ensured that the dummy car and the agent are updating at the same rate */ [SerializeField] private BaseEnvironmentMaster environment; // the agent's rigidbody private Rigidbody agentRig; // the dummy car game object private GameObject dummyCar; // the maximum rotation distance between the dummy car and the agent [SerializeField] float maxRotDist; // the maximum position distance between the dummy car and the agent [SerializeField] float maxPosDist; [SerializeField] bool isTraining = true; private bool activeFitness; private bool initialized; public AltAgentCar() { } public override void InitializeAgent() { base.InitializeAgent(); } public override void AgentAction(float[] vectorAction) { if (dummyCar == null) return; //Debug.Log("Aget updae"); // increase velocities so that the agent can catch up to the dummy car float forwardAmount = vectorAction[0] * 1.1f; float steerAmount = vectorAction[1] * 1.1f; // apply input to the vehicle car.SetVehicleInput(steerAmount, forwardAmount); // culculate the distances in position and rotations float positionDifference = Vector3.Distance(dummyCar.transform.localPosition, transform.localPosition); float rotationDifference = Vector3.Angle(dummyCar.transform.right, transform.right); // give a small reward on each frame float distanceReward = 0; float rotationReward = 0; if (positionDifference <= 0.1) distanceReward = 1.0f; else distanceReward = 1 / (positionDifference * 10); if (rotationDifference <= 0.1) rotationReward = 1.0f; else rotationReward = 1 / (positionDifference * 10); fitness = (distanceReward * 0.5f + rotationReward * 0.5f) / 10; // check if the agent follows the dummy car //if ((positionDifference > 10 || rotationDifference > 20) && isTraining) if ((positionDifference > maxPosDist) && isTraining) { fitness = -10.0f; activeFitness = false; Done(); } SetReward(fitness); // Debug.Log("Fitenss " + fitness); // Debug.Log("Fitness " + fitness + " distanceReward: " + distanceReward + " rotationReward: " + rotationReward); } public override void CollectObservations(VectorSensor sensor) { if (agentRig == null) { sensor.AddObservation(Vector3.zero); sensor.AddObservation(0.0f); sensor.AddObservation(Vector3.zero); sensor.AddObservation(Vector3.zero); sensor.AddObservation(Vector3.zero); sensor.AddObservation(Vector3.zero); sensor.AddObservation(0.0f); sensor.AddObservation(Vector3.zero); sensor.AddObservation(0.0f); return; } // pass agent information sensor.AddObservation(transform.localPosition); sensor.AddObservation(transform.localEulerAngles.y); sensor.AddObservation(agentRig.velocity); // pass distance between agent and dummy car sensor.AddObservation(dummyCar.transform.localPosition - transform.localPosition); // pass rotation difference between agent and dummy car sensor.AddObservation(Vector3.Angle(dummyCar.transform.right, transform.right)); // pass dummy car information sensor.AddObservation(dummyCar.transform.localPosition); sensor.AddObservation(dummyCar.transform.localEulerAngles.y); // We definatelly need to add this (It wasn't added for the trained model) - possibly improve training times and rapid changes in the mean fitness // the mean fitness seems to be unstable sensor.AddObservation(dummyCarController.GetCurrentVelocity()); sensor.AddObservation(activeFitness); } public override void AgentReset() { if (dummyCar == null || dummyCarController == null) { //dummyCar = dummyCarController.GetVehicle().GetGameObject(); return; } // apply the dummy car state to the agent Vector3 posOffset = CreateRandomVector(-15, 15); posOffset.y = 0; transform.localPosition = dummyCar.transform.localPosition + posOffset; transform.localEulerAngles = dummyCar.transform.localEulerAngles + new Vector3(0.0f, UnityEngine.Random.Range(0, 90), 0.0f); Vector3 velocityOffset = CreateRandomVector(-20, 20); velocityOffset.y = 0; agentRig.velocity = dummyCarController.GetCurrentVelocity() + velocityOffset; } public Vector3 CreateRandomVector(float minMagnitude, float maxMagnitude) { float magnitude = UnityEngine.Random.Range(minMagnitude, maxMagnitude); Vector3 output = new Vector3(UnityEngine.Random.Range(-0.0f, 2.0f), 0, UnityEngine.Random.Range(0.0f, 2.0f)); output = output.normalized * magnitude; return output; } // Manual control public override float[] Heuristic() { float[] action = new float[2]; action[0] = Input.GetAxis("Vertical"); action[1] = Input.GetAxis("Horizontal"); return action; } public override void UpdateController() { throw new NotImplementedException(); } public override void InitController(AbstractVehicle vehicle) { // add car vehicle to this game object car = vehicle; // Set class attributes dummyCarController = environment.GetDummyCarController(); dummyCar = dummyCarController.GetVehicle().GetGameObject(); transform.localPosition = dummyCar.transform.position; transform.localEulerAngles = dummyCar.transform.localEulerAngles; agentRig = GetComponent<Rigidbody>(); // subscribe to the animation reset event environment.GetDummyCarController().ResetOccuredEvent += AgentReset; } public override void ResetVehicleController() { throw new NotImplementedException(); } }
32.889952
155
0.658859
[ "MIT" ]
FotisSpinos/Year-4-AI
AI Year 4 Project/Assets/Training/AltAgentCar.cs
6,876
C#
// // Copyright (c) .NET Foundation and Contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // using nanoFramework.TestFramework; using System; using System.Diagnostics; namespace NFUnitTestClasses { [TestClass] class UnitTestPropertiesTests { [TestMethod] public void Properties003_Test() { OutputHelper.WriteLine("Section 10.6"); OutputHelper.WriteLine("A property declaration may include set of"); OutputHelper.WriteLine("attributes, a new modifier, a valid combination"); OutputHelper.WriteLine("nof the four access modifiers, and a static modifier."); Assert.True(PropertiesTestClass003.testMethod()); } [TestMethod] public void Properties004_Test() { OutputHelper.WriteLine("Section 10.6"); OutputHelper.WriteLine("A property declaration may include set of"); OutputHelper.WriteLine("attributes, a new modifier, a valid combination"); OutputHelper.WriteLine("nof the four access modifiers, and a static modifier."); Assert.True(PropertiesTestClass004.testMethod()); } [TestMethod] public void Properties005_Test() { OutputHelper.WriteLine("Section 10.6"); OutputHelper.WriteLine("A property declaration may include set of"); OutputHelper.WriteLine("attributes, a new modifier, a valid combination"); OutputHelper.WriteLine("nof the four access modifiers, and a static modifier."); Assert.True(PropertiesTestClass005.testMethod()); } [TestMethod] public void Properties006_Test() { OutputHelper.WriteLine("Section 10.6"); OutputHelper.WriteLine("A property declaration may include set of"); OutputHelper.WriteLine("attributes, a new modifier, a valid combination"); OutputHelper.WriteLine("nof the four access modifiers, and a static modifier."); Assert.True(PropertiesTestClass006.testMethod()); } [TestMethod] public void Properties007_Test() { OutputHelper.WriteLine("Section 10.6"); OutputHelper.WriteLine("A property declaration may include set of"); OutputHelper.WriteLine("attributes, a new modifier, a valid combination"); OutputHelper.WriteLine("nof the four access modifiers, and a static modifier."); Assert.True(PropertiesTestClass007.testMethod()); } [TestMethod] public void Properties008_Test() { OutputHelper.WriteLine("Section 10.6"); OutputHelper.WriteLine("A property declaration may include set of"); OutputHelper.WriteLine("attributes, a new modifier, a valid combination"); OutputHelper.WriteLine("nof the four access modifiers, and a static modifier."); Assert.True(PropertiesTestClass008.testMethod()); } [TestMethod] public void Properties009_Test() { OutputHelper.WriteLine("Section 10.6"); OutputHelper.WriteLine("A property declaration may include set of"); OutputHelper.WriteLine("attributes, a new modifier, a valid combination"); OutputHelper.WriteLine("nof the four access modifiers, and a static modifier."); Assert.True(PropertiesTestClass009.testMethod()); } [TestMethod] public void Properties010_Test() { OutputHelper.WriteLine("Section 10.6"); OutputHelper.WriteLine("A property declaration may include set of"); OutputHelper.WriteLine("attributes, a new modifier, a valid combination"); OutputHelper.WriteLine("nof the four access modifiers, and a static modifier."); Assert.True(PropertiesTestClass010.testMethod()); } [TestMethod] public void Properties011_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("The type of a property declaration specifies"); OutputHelper.WriteLine("the type of the property introduced by the"); OutputHelper.WriteLine("declaration, and the member-name specifies"); OutputHelper.WriteLine("the name of the property. Unless the property"); OutputHelper.WriteLine("is an explicit interface member implementation,"); OutputHelper.WriteLine("the member name is simply an identifier. For an"); OutputHelper.WriteLine("explicit interface member implementation, the"); OutputHelper.WriteLine("member name consists of an interface-type followed"); OutputHelper.WriteLine("by a . and an identifier."); OutputHelper.WriteLine("This is currently an expected fail, but is resolved in 3.0 see Bug 16341 for details"); Assert.True(PropertiesTestClass011.testMethod()); } [TestMethod] public void Properties024_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("An instance property is associated with"); OutputHelper.WriteLine("a given instance of a class, and this instance"); OutputHelper.WriteLine("can be accessed as this in the accessors of"); OutputHelper.WriteLine("the property."); Assert.True(PropertiesTestClass024.testMethod()); } [TestMethod] public void Properties025_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("An instance property is associated with"); OutputHelper.WriteLine("a given instance of a class, and this instance"); OutputHelper.WriteLine("can be accessed as this in the accessors of"); OutputHelper.WriteLine("the property."); Assert.True(PropertiesTestClass025.testMethod()); } [TestMethod] public void Properties026_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("When a property is referenced in a member-access"); OutputHelper.WriteLine("of the form E.M, if M is a static property, E must"); OutputHelper.WriteLine("denote a type, and if M is an instance property,"); OutputHelper.WriteLine("E must denote an instance."); Assert.True(PropertiesTestClass026.testMethod()); } [TestMethod] public void Properties027_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("When a property is referenced in a member-access"); OutputHelper.WriteLine("of the form E.M, if M is a static property, E must"); OutputHelper.WriteLine("denote a type, and if M is an instance property,"); OutputHelper.WriteLine("E must denote an instance."); Assert.True(PropertiesTestClass027.testMethod()); } [TestMethod] public void Properties033_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("The accessor declarations consist of a "); OutputHelper.WriteLine("get-accessor-declaration, a set-accessor"); OutputHelper.WriteLine("declaration, or both."); Assert.True(PropertiesTestClass033.testMethod()); } [TestMethod] public void Properties034_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("The accessor declarations consist of a "); OutputHelper.WriteLine("get-accessor-declaration, a set-accessor"); OutputHelper.WriteLine("declaration, or both."); Assert.True(PropertiesTestClass034.testMethod()); } [TestMethod] public void Properties035_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("The accessor declarations consist of a "); OutputHelper.WriteLine("get-accessor-declaration, a set-accessor"); OutputHelper.WriteLine("declaration, or both."); Assert.True(PropertiesTestClass035.testMethod()); } [TestMethod] public void Properties036_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass036.testMethod()); } [TestMethod] public void Properties037_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass037.testMethod()); } [TestMethod] public void Properties038_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass038.testMethod()); } [TestMethod] public void Properties043_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass043.testMethod()); } [TestMethod] public void Properties046_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass046.testMethod()); } [TestMethod] public void Properties048_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass048.testMethod()); } [TestMethod] public void Properties050_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass050.testMethod()); } [TestMethod] public void Properties053_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass053.testMethod()); } [TestMethod] public void Properties054_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass054.testMethod()); } [TestMethod] public void Properties056_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass056.testMethod()); } [TestMethod] public void Properties058_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass058.testMethod()); } [TestMethod] public void Properties059_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass059.testMethod()); } [TestMethod] public void Properties060_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass060.testMethod()); } [TestMethod] public void Properties062_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass062.testMethod()); } [TestMethod] public void Properties068_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass068.testMethod()); } [TestMethod] public void Properties071_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass071.testMethod()); } [TestMethod] public void Properties072_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass072.testMethod()); } [TestMethod] public void Properties073_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass073.testMethod()); } [TestMethod] public void Properties074_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass074.testMethod()); } [TestMethod] public void Properties075_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass075.testMethod()); } [TestMethod] public void Properties078_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass078.testMethod()); } [TestMethod] public void Properties089_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass089.testMethod()); } [TestMethod] public void Properties090_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass090.testMethod()); } [TestMethod] public void Properties097_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass097.testMethod()); } [TestMethod] public void Properties109_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass109.testMethod()); } [TestMethod] public void Properties110_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass110.testMethod()); } [TestMethod] public void Properties121_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass121.testMethod()); } [TestMethod] public void Properties122_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass122.testMethod()); } [TestMethod] public void Properties123_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); OutputHelper.WriteLine("This test is an expected fail"); Assert.False(PropertiesTestClass123.testMethod()); } [TestMethod] public void Properties124_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); OutputHelper.WriteLine("This test is an expected fail"); Assert.False(PropertiesTestClass124.testMethod()); } [TestMethod] public void Properties125_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass125.testMethod()); } [TestMethod] public void Properties126_Test() { OutputHelper.WriteLine("Section 10.6 "); OutputHelper.WriteLine("Each accessor declaration consists of an"); OutputHelper.WriteLine("optional accessor-modifier, followed by the"); OutputHelper.WriteLine("keyword get or set, followed by an accessor"); Assert.True(PropertiesTestClass126.testMethod()); } //Compiled Test Cases class PropertiesTestClass003 { int intI = 0; int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass003 test = new PropertiesTestClass003(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass004_Base { public int MyProp { get { return 1; } } } class PropertiesTestClass004 : PropertiesTestClass004_Base { int intI = 0; new int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass004 test = new PropertiesTestClass004(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass005 { int intI = 0; public int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass005 test = new PropertiesTestClass005(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass006 { int intI = 0; protected int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass006 test = new PropertiesTestClass006(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass007 { int intI = 0; internal int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass007 test = new PropertiesTestClass007(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass008 { int intI = 0; private int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass008 test = new PropertiesTestClass008(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass009 { int intI = 0; protected internal int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass009 test = new PropertiesTestClass009(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass010 { static int intI = 0; static int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass010.MyProp = 2; if (PropertiesTestClass010.MyProp == 2) { return true; } else { return false; } } } interface PropertiesTestClass011_Interface { int MyProp { get; set; } } class PropertiesTestClass011 : PropertiesTestClass011_Interface { static int intI = 0; int PropertiesTestClass011_Interface.MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { try { PropertiesTestClass011 MC = new PropertiesTestClass011(); ((PropertiesTestClass011_Interface)MC).MyProp = 2; if (((PropertiesTestClass011_Interface)MC).MyProp == 2) { return true; } else { return false; } } catch { return false; } } } public class PropertiesTestClass024 { public int intI = 2; public int MyProp { get { return this.intI; } } public static bool testMethod() { PropertiesTestClass024 test = new PropertiesTestClass024(); if (test.MyProp == 2) { return true; } else { return false; } } } public class PropertiesTestClass025 { public int intI = 1; public int MyProp { set { this.intI = value; } } public static bool testMethod() { PropertiesTestClass025 test = new PropertiesTestClass025(); test.MyProp = 2; if (test.intI == 2) { return true; } else { return false; } } } public class PropertiesTestClass026 { public int intI = 1; public int MyProp { set { this.intI = value; } get { return intI; } } public int GetProp() { return MyProp; } public void SetProp(int intJ) { MyProp = intJ; } public static bool testMethod() { PropertiesTestClass026 test = new PropertiesTestClass026(); test.SetProp(3); if (test.GetProp() == 3) { return true; } else { return false; } } } public class PropertiesTestClass027 { public static int intI = 1; public static int MyProp { set { intI = value; } get { return intI; } } public static int GetProp() { return MyProp; } public static void SetProp(int intJ) { MyProp = intJ; } public static bool testMethod() { PropertiesTestClass027.SetProp(3); if (PropertiesTestClass027.GetProp() == 3) { return true; } else { return false; } } } public class PropertiesTestClass033 { public int MyProp { get { return 2; } } public static bool testMethod() { PropertiesTestClass033 test = new PropertiesTestClass033(); if (test.MyProp == 2) { return true; } else { return false; } } } public class PropertiesTestClass034 { public int intI = 0; public int MyProp { set { intI = value; } } public static bool testMethod() { PropertiesTestClass034 test = new PropertiesTestClass034(); test.MyProp = 2; if (test.intI == 2) { return true; } else { return false; } } } public class PropertiesTestClass035 { public int intI = 0; public int MyProp { set { intI = value; } get { return intI; } } public static bool testMethod() { PropertiesTestClass035 test = new PropertiesTestClass035(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } public class PropertiesTestClass036 { int intI = 0; public virtual int MyProp { set { intI = value; } get { return intI; } } public static bool testMethod() { PropertiesTestClass036 test = new PropertiesTestClass036(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } public class PropertiesTestClass037_Base { public virtual int MyProp { set { } get { return -1; } } } public class PropertiesTestClass037 : PropertiesTestClass037_Base { int intI = 0; public override int MyProp { set { intI = value; } get { return intI; } } public static bool testMethod() { PropertiesTestClass037_Base test = new PropertiesTestClass037(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } public abstract class PropertiesTestClass038_Base { public abstract int MyProp { set; get; } } public class PropertiesTestClass038 : PropertiesTestClass038_Base { int intI = 0; public override int MyProp { set { intI = value; } get { return intI; } } public static bool testMethod() { PropertiesTestClass038_Base test = new PropertiesTestClass038(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } public class PropertiesTestClass043 { public int TestInt = 1; public int MyProp { get { TestInt = 2; return -1; } set { } } public static bool testMethod() { PropertiesTestClass043 test = new PropertiesTestClass043(); test.MyProp = 2; if (test.TestInt == 1) { return true; } else { return false; } } } public class PropertiesTestClass046 { public int MyProp { get { short s = 3; return s; } } public static bool testMethod() { PropertiesTestClass046 test = new PropertiesTestClass046(); if (test.MyProp == 3) { return true; } else { return false; } } } public class PropertiesTestClass048_Sub { public int intI = 2; public static implicit operator int(PropertiesTestClass048_Sub t) { return t.intI; } } public class PropertiesTestClass048 { public int MyProp { get { PropertiesTestClass048_Sub test = new PropertiesTestClass048_Sub(); return test; } } public static bool testMethod() { PropertiesTestClass048 MC = new PropertiesTestClass048(); if (MC.MyProp == 2) { return true; } else { return false; } } } public class PropertiesTestClass050_Sub { public int intI = 2; public static implicit operator int(PropertiesTestClass050_Sub t) { return t.intI; } } public class PropertiesTestClass050 { public bool b = true; public int MyProp { get { if (b == true) { PropertiesTestClass050_Sub test = new PropertiesTestClass050_Sub(); return test; } else { return 3; } } } public static bool testMethod() { PropertiesTestClass050 MC = new PropertiesTestClass050(); PropertiesTestClass050 MC2 = new PropertiesTestClass050(); MC.b = true; MC2.b = false; if ((MC.MyProp == 2) && (MC2.MyProp == 3)) { return true; } else { return false; } } } public class PropertiesTestClass053 { public int MyProp { get { throw new System.Exception(); } } public static bool testMethod() { PropertiesTestClass053 test = new PropertiesTestClass053(); try { int intJ = test.MyProp; } catch (System.Exception e) { return true; } return false; } } public class PropertiesTestClass054 { public bool b = true; public int MyProp { get { if (b == true) { return 1; } else { throw new System.Exception(); } } } public static bool testMethod() { PropertiesTestClass054 MC = new PropertiesTestClass054(); PropertiesTestClass054 MC2 = new PropertiesTestClass054(); MC.b = true; MC2.b = false; if (MC.MyProp != 1) { return false; } try { int intJ = MC2.MyProp; } catch (System.Exception e) { return true; } return false; } } public class PropertiesTestClass056 { public int intI = 2; public int MyProp { set { } get { intI = 3; return 1; } } public static bool testMethod() { PropertiesTestClass056 test = new PropertiesTestClass056(); test.MyProp = 4; if (test.intI == 2) { return true; } else { return false; } } } public class PropertiesTestClass058 { public int intI = 2; public int MyProp { set { return; intI = 3; } } public static bool testMethod() { PropertiesTestClass058 test = new PropertiesTestClass058(); test.MyProp = 4; if (test.intI == 2) { return true; } else { return false; } } } public class PropertiesTestClass059 { public int intI = 2; public int MyProp { set { intI = value; return; } } public static bool testMethod() { PropertiesTestClass059 test = new PropertiesTestClass059(); test.MyProp = 4; if (test.intI == 4) { return true; } else { return false; } } } public class PropertiesTestClass060 { bool b = true; public int intI = 2; public int MyProp { set { if (b == true) { intI = value; return; } else { intI = value + 1; return; } } } public static bool testMethod() { PropertiesTestClass060 test = new PropertiesTestClass060(); PropertiesTestClass060 test2 = new PropertiesTestClass060(); test.b = true; test2.b = false; test.MyProp = 4; test2.MyProp = 4; if ((test.intI == 4) && (test2.intI == 5)) { return true; } else { return false; } } } public class PropertiesTestClass062 { int value; public int MyProp { set { this.value = 2; value = 3; } } public static bool testMethod() { PropertiesTestClass062 test = new PropertiesTestClass062(); test.MyProp = 1; if (test.value == 2) { return true; } else { return false; } } } public class PropertiesTestClass068_Base { public int intTest; public int MyProp { get { return intTest; } set { intTest = value; } } } public class PropertiesTestClass068 : PropertiesTestClass068_Base { new public int MyProp { get { return intTest + 1; } set { intTest = value + 1; } } public static bool testMethod() { PropertiesTestClass068 test = new PropertiesTestClass068(); test.MyProp = 2; if (test.MyProp == 4) { return true; } else { return false; } } } public class PropertiesTestClass071_Base { public int MyProp { get { return 1; } } } public class PropertiesTestClass071 : PropertiesTestClass071_Base { new public int MyProp { set { } } public static bool testMethod() { PropertiesTestClass071 test = new PropertiesTestClass071(); int intJ = ((PropertiesTestClass071_Base)test).MyProp; if (intJ == 1) { return true; } else { return false; } } } public class PropertiesTestClass072_Base { public int intI; public int MyProp { set { intI = value; } } } public class PropertiesTestClass072 : PropertiesTestClass072_Base { new public int MyProp { get { return 1; } } public static bool testMethod() { PropertiesTestClass072 test = new PropertiesTestClass072(); ((PropertiesTestClass072_Base)test).MyProp = 2; if (test.intI == 2) { return true; } else { return false; } } } public class PropertiesTestClass073_Base { public int MyProp { get { return 1; } } } public class PropertiesTestClass073 : PropertiesTestClass073_Base { new public int MyProp { get { return 2; } } public static bool testMethod() { PropertiesTestClass073 test = new PropertiesTestClass073(); int intJ = ((PropertiesTestClass073_Base)test).MyProp; if (intJ == 1) { return true; } else { return false; } } } public class PropertiesTestClass074_Base { public int intI; public int MyProp { set { intI = value; } } } public class PropertiesTestClass074 : PropertiesTestClass074_Base { new public int MyProp { set { intI = value + 1; } } public static bool testMethod() { PropertiesTestClass074 test = new PropertiesTestClass074(); ((PropertiesTestClass074_Base)test).MyProp = 2; if (test.intI == 2) { return true; } else { return false; } } } public class PropertiesTestClass075 { int intI = 0; public virtual int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass075 test = new PropertiesTestClass075(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } public abstract class PropertiesTestClass078_Sub { public int intI = 0; public abstract int MyProp { get; set; } } public class PropertiesTestClass078 : PropertiesTestClass078_Sub { public override int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass078_Sub test = new PropertiesTestClass078(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } public class PropertiesTestClass089_Base { public int intI; public virtual int MyProp { set { intI = value; } get { return intI; } } } public class PropertiesTestClass089 : PropertiesTestClass089_Base { public override int MyProp { get { return intI + 1; } } public static bool testMethod() { PropertiesTestClass089_Base test = new PropertiesTestClass089(); test.MyProp = 2; if (test.MyProp == 3) { return true; } else { return false; } } } public class PropertiesTestClass090_Base { public int intI; public virtual int MyProp { set { intI = value; } get { return intI; } } } public class PropertiesTestClass090 : PropertiesTestClass090_Base { public override int MyProp { set { intI = value - 1; } } public static bool testMethod() { PropertiesTestClass090_Base test = new PropertiesTestClass090(); test.MyProp = 2; if (test.MyProp == 1) { return true; } else { return false; } } } class PropertiesTestClass097 { int intI = 0; int MyProp { set { intI = value; } get { return intI; } } public static bool testMethod() { PropertiesTestClass097 test = new PropertiesTestClass097(); test.MyProp = 2; if (test.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass109_Base { public virtual int foo { get { return 1; } } } class PropertiesTestClass109_Derived : PropertiesTestClass109_Base { private int get_foo() { return 1; } } class PropertiesTestClass109 : PropertiesTestClass109_Derived { public override int foo { get { return 2; } } public static bool testMethod() { PropertiesTestClass109_Base MB = new PropertiesTestClass109(); if (MB.foo == 2) { return true; } else { return false; } } } class PropertiesTestClass110_Base { public int intI; public virtual int foo { set { intI = 1; } } } class PropertiesTestClass110_Derived : PropertiesTestClass110_Base { private void set_foo(int value) { intI = 2; } } class PropertiesTestClass110 : PropertiesTestClass110_Derived { public override int foo { set { intI = 3; } } public static bool testMethod() { PropertiesTestClass110_Base MB = new PropertiesTestClass110(); MB.foo = 3; if (MB.intI == 3) { return true; } else { return false; } } } class PropertiesTestClass121_Base { public virtual int MyProp { get { return 1; } } } class PropertiesTestClass121 : PropertiesTestClass121_Base { public override int MyProp { get { return 2; } } public static bool testMethod() { PropertiesTestClass121_Base MC = new PropertiesTestClass121(); if (MC.MyProp == 2) { return true; } else { return false; } } } class PropertiesTestClass122_Base { public int myInt; public virtual int MyProp { set { myInt = 1; } } } class PropertiesTestClass122 : PropertiesTestClass122_Base { public override int MyProp { set { myInt = 2; } } public static bool testMethod() { PropertiesTestClass122_Base MC = new PropertiesTestClass122(); MC.MyProp = 0; if (MC.myInt == 2) { return true; } else { return false; } } } class PropertiesTestClass123_Base { public virtual int MyProp { get { return 1; } } } class PropertiesTestClass123 : PropertiesTestClass123_Base { public new int MyProp { get { return 2; } } public static bool testMethod() { PropertiesTestClass123_Base MC = new PropertiesTestClass123(); if (MC.MyProp == 1) { return true; } else { return false; } } } class PropertiesTestClass124_Base { public int myInt; public virtual int MyProp { set { myInt = 1; } } } class PropertiesTestClass124 : PropertiesTestClass124_Base { public new int MyProp { set { myInt = 2; } } public static bool testMethod() { PropertiesTestClass124_Base MC = new PropertiesTestClass124(); MC.MyProp = 0; if (MC.myInt == 1) { return true; } else { return false; } } } class PropertiesTestClass125_Base { public int intI = 0; public virtual int MyProp { get { return -1; } set { intI = -1; } } } class PropertiesTestClass125 : PropertiesTestClass125_Base { public override int MyProp { get { return intI; } set { intI = value; } } public static bool testMethod() { PropertiesTestClass125_Base MC = new PropertiesTestClass125(); MC.MyProp = 4; if (MC.MyProp == 4) { return true; } else { return false; } } } class PropertiesTestClass126_Base { public int intI = 0; public virtual int MyProp { get { return intI; } set { intI = value; } } } class PropertiesTestClass126 : PropertiesTestClass126_Base { public new int MyProp { get { return -1; } set { intI = -1; } } public static bool testMethod() { PropertiesTestClass126_Base MC = new PropertiesTestClass126(); MC.MyProp = 4; if (MC.MyProp == -1) { return true; } else { return false; } } } } }
31.385554
124
0.441657
[ "MIT" ]
Eclo/lib-CoreLibrary
Tests/NFUnitTestClasses/UnitTestPropertiesTests.cs
61,706
C#
using System; using System.Threading.Tasks; namespace Maxisoft.Utils { public static class FuncExtensions { public static Task<T> ToTask<T>(this Func<T> func) { return Task.Run(func); } } }
18.384615
58
0.598326
[ "MIT" ]
sucrose0413/Maxisoft.Utils
Maxisoft.Utils/FuncExtensions.cs
241
C#
/* * * (c) Copyright Ascensio System Limited 2010-2021 * * 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.IO; namespace ASC.Data.Storage { public class ProgressStream : Stream { private readonly Stream stream; private long length = long.MaxValue; public ProgressStream(Stream stream) { if (stream == null) throw new ArgumentNullException("stream"); this.stream = stream; try { length = stream.Length; } catch (Exception) { } } public override bool CanRead { get { return stream.CanRead; } } public override bool CanSeek { get { return stream.CanSeek; } } public override bool CanWrite { get { return stream.CanWrite; } } public override long Length { get { return stream.Length; } } public override long Position { get { return stream.Position; } set { stream.Position = value; } } public event Action<ProgressStream, int> OnReadProgress; public void InvokeOnReadProgress(int progress) { var handler = OnReadProgress; if (handler != null) { handler(this, progress); } } public override void Flush() { stream.Flush(); } public override long Seek(long offset, SeekOrigin origin) { return stream.Seek(offset, origin); } public override void SetLength(long value) { stream.SetLength(value); length = value; } public override int Read(byte[] buffer, int offset, int count) { var readed = stream.Read(buffer, offset, count); OnReadProgress(this, (int)(stream.Position / (double)length * 100)); return readed; } public override void Write(byte[] buffer, int offset, int count) { stream.Write(buffer, offset, count); } } }
25.790476
80
0.562777
[ "ECL-2.0", "Apache-2.0", "MIT" ]
ONLYOFFICE/CommunityServer
common/ASC.Data.Storage/ProgressStream.cs
2,708
C#
using Orleans.Serialization.Buffers; using Orleans.Serialization.TypeSystem; using Orleans.Serialization.WireProtocol; using System; using System.Buffers; using System.Runtime.CompilerServices; namespace Orleans.Serialization.Codecs { /// <summary> /// Codec for operating with the wire format. /// </summary> public static class FieldHeaderCodec { /// <summary> /// Writes the field header. /// </summary> /// <typeparam name="TBufferWriter">The underlying buffer writer type.</typeparam> /// <param name="writer">The writer.</param> /// <param name="fieldId">The field identifier.</param> /// <param name="expectedType">The expected type.</param> /// <param name="actualType">The actual type.</param> /// <param name="wireType">The wire type.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteFieldHeader<TBufferWriter>( ref this Writer<TBufferWriter> writer, uint fieldId, Type expectedType, Type actualType, WireType wireType) where TBufferWriter : IBufferWriter<byte> { var hasExtendedFieldId = fieldId > Tag.MaxEmbeddedFieldIdDelta; var embeddedFieldId = hasExtendedFieldId ? Tag.FieldIdCompleteMask : (byte)fieldId; var tag = (byte)((byte)wireType | embeddedFieldId); if (actualType == expectedType) { writer.WriteByte((byte)(tag | (byte)SchemaType.Expected)); if (hasExtendedFieldId) { writer.WriteVarUInt32(fieldId); } } else if (writer.Session.WellKnownTypes.TryGetWellKnownTypeId(actualType, out var typeOrReferenceId)) { writer.WriteByte((byte)(tag | (byte)SchemaType.WellKnown)); if (hasExtendedFieldId) { writer.WriteVarUInt32(fieldId); } writer.WriteVarUInt32(typeOrReferenceId); } else if (writer.Session.ReferencedTypes.TryGetTypeReference(actualType, out typeOrReferenceId)) { writer.WriteByte((byte)(tag | (byte)SchemaType.Referenced)); if (hasExtendedFieldId) { writer.WriteVarUInt32(fieldId); } writer.WriteVarUInt32(typeOrReferenceId); } else { writer.WriteByte((byte)(tag | (byte)SchemaType.Encoded)); if (hasExtendedFieldId) { writer.WriteVarUInt32(fieldId); } writer.Session.TypeCodec.WriteEncodedType(ref writer, actualType); } } /// <summary> /// Writes an expected field header value. /// </summary> /// <typeparam name="TBufferWriter">The underlying buffer writer type.</typeparam> /// <param name="writer">The writer.</param> /// <param name="fieldId">The field identifier.</param> /// <param name="wireType">The wire type of the field.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteFieldHeaderExpected<TBufferWriter>(this ref Writer<TBufferWriter> writer, uint fieldId, WireType wireType) where TBufferWriter : IBufferWriter<byte> { if (fieldId < Tag.MaxEmbeddedFieldIdDelta) { WriteFieldHeaderExpectedEmbedded(ref writer, fieldId, wireType); } else { WriteFieldHeaderExpectedExtended(ref writer, fieldId, wireType); } } /// <summary> /// Writes an field header value with an expected type and an embedded field identifier. /// </summary> /// <typeparam name="TBufferWriter">The underlying buffer writer type.</typeparam> /// <param name="writer">The writer.</param> /// <param name="fieldId">The field identifier.</param> /// <param name="wireType">The wire type.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteFieldHeaderExpectedEmbedded<TBufferWriter>(this ref Writer<TBufferWriter> writer, uint fieldId, WireType wireType) where TBufferWriter : IBufferWriter<byte> => writer.WriteByte((byte)((byte)wireType | (byte)fieldId)); /// <summary> /// Writes a field header with an expected type and an extended field id. /// </summary> /// <typeparam name="TBufferWriter">The underlying buffer writer type.</typeparam> /// <param name="writer">The writer.</param> /// <param name="fieldId">The field identifier.</param> /// <param name="wireType">The wire type.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void WriteFieldHeaderExpectedExtended<TBufferWriter>(this ref Writer<TBufferWriter> writer, uint fieldId, WireType wireType) where TBufferWriter : IBufferWriter<byte> { writer.WriteByte((byte)((byte)wireType | Tag.FieldIdCompleteMask)); writer.WriteVarUInt32(fieldId); } /// <summary> /// Reads a field header. /// </summary> /// <typeparam name="TInput">The reader input type.</typeparam> /// <param name="reader">The reader.</param> /// <param name="field">The field header.</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static void ReadFieldHeader<TInput>(ref this Reader<TInput> reader, ref Field field) { var tag = reader.ReadByte(); if (tag != (byte)WireType.Extended && ((tag & Tag.FieldIdCompleteMask) == Tag.FieldIdCompleteMask || (tag & Tag.SchemaTypeMask) != (byte)SchemaType.Expected)) { field.Tag = tag; ReadExtendedFieldHeader(ref reader, ref field); } else { field.Tag = tag; field.FieldIdDeltaRaw = default; field.FieldTypeRaw = default; } } /// <summary> /// Reads a field header. /// </summary> /// <typeparam name="TInput">The reader input type.</typeparam> /// <param name="reader">The reader.</param> /// <returns>The field header.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Field ReadFieldHeader<TInput>(ref this Reader<TInput> reader) { Field field = default; var tag = reader.ReadByte(); if (tag != (byte)WireType.Extended && ((tag & Tag.FieldIdCompleteMask) == Tag.FieldIdCompleteMask || (tag & Tag.SchemaTypeMask) != (byte)SchemaType.Expected)) { field.Tag = tag; ReadExtendedFieldHeader(ref reader, ref field); } else { field.Tag = tag; field.FieldIdDeltaRaw = default; field.FieldTypeRaw = default; } return field; } /// <summary> /// Reads an extended field header. /// </summary> /// <typeparam name="TInput">The reader input type.</typeparam> /// <param name="reader">The reader.</param> /// <param name="field">The field.</param> [MethodImpl(MethodImplOptions.NoInlining)] internal static void ReadExtendedFieldHeader<TInput>(ref this Reader<TInput> reader, ref Field field) { // If all of the field id delta bits are set and the field isn't an extended wiretype field, read the extended field id delta var notExtended = (field.Tag & (byte)WireType.Extended) != (byte)WireType.Extended; if ((field.Tag & Tag.FieldIdCompleteMask) == Tag.FieldIdCompleteMask && notExtended) { field.FieldIdDeltaRaw = reader.ReadVarUInt32NoInlining(); } else { field.FieldIdDeltaRaw = 0; } // If schema type is valid, read the type. var schemaType = (SchemaType)(field.Tag & Tag.SchemaTypeMask); if (notExtended && schemaType != SchemaType.Expected) { field.FieldTypeRaw = reader.ReadType(schemaType); } else { field.FieldTypeRaw = default; } } [MethodImpl(MethodImplOptions.NoInlining)] private static Type ReadType<TInput>(this ref Reader<TInput> reader, SchemaType schemaType) { switch (schemaType) { case SchemaType.Expected: return null; case SchemaType.WellKnown: var typeId = reader.ReadVarUInt32(); return reader.Session.WellKnownTypes.GetWellKnownType(typeId); case SchemaType.Encoded: _ = reader.Session.TypeCodec.TryRead(ref reader, out Type encoded); return encoded; case SchemaType.Referenced: var reference = reader.ReadVarUInt32(); return reader.Session.ReferencedTypes.GetReferencedType(reference); default: return ExceptionHelper.ThrowArgumentOutOfRange<Type>(nameof(SchemaType)); } } [MethodImpl(MethodImplOptions.NoInlining)] private static (Type type, string typeName) ReadTypeForAnalysis<TInput>(this ref Reader<TInput> reader, SchemaType schemaType) { switch (schemaType) { case SchemaType.Expected: return (null, "Expected"); case SchemaType.WellKnown: { var typeId = reader.ReadVarUInt32(); if (reader.Session.WellKnownTypes.TryGetWellKnownType(typeId, out var type)) { return (type, $"WellKnown {typeId} ({(type is null ? "null" : RuntimeTypeNameFormatter.Format(type))})"); } else { return (null, $"WellKnown {typeId} (unknown)"); } } case SchemaType.Encoded: { var found = reader.Session.TypeCodec.TryReadForAnalysis(ref reader, out Type encoded, out var typeString); return (encoded, $"Encoded \"{typeString}\" ({(found ? RuntimeTypeNameFormatter.Format(encoded) : "not found")})"); } case SchemaType.Referenced: { var reference = reader.ReadVarUInt32(); var found = reader.Session.ReferencedTypes.TryGetReferencedType(reference, out var type); return (type, $"Referenced {reference} ({(found ? RuntimeTypeNameFormatter.Format(type) : "not found")})"); } default: throw new ArgumentOutOfRangeException(nameof(schemaType)); } } /// <summary> /// Reads a field header for diagnostic purposes. /// </summary> /// <typeparam name="TInput">The reader input type.</typeparam> /// <param name="reader">The reader.</param> /// <returns>The value which was read.</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static (Field Field, string Type) ReadFieldHeaderForAnalysis<TInput>(ref this Reader<TInput> reader) { Field field = default; string type = default; var tag = reader.ReadByte(); if (tag != (byte)WireType.Extended && ((tag & Tag.FieldIdCompleteMask) == Tag.FieldIdCompleteMask || (tag & Tag.SchemaTypeMask) != (byte)SchemaType.Expected)) { field.Tag = tag; ReadFieldHeaderForAnalysisSlow(ref reader, ref field, ref type); } else { field.Tag = tag; field.FieldIdDeltaRaw = default; field.FieldTypeRaw = default; type = "Expected"; } return (field, type); } [MethodImpl(MethodImplOptions.NoInlining)] private static void ReadFieldHeaderForAnalysisSlow<TInput>(ref this Reader<TInput> reader, ref Field field, ref string type) { var notExtended = (field.Tag & (byte)WireType.Extended) != (byte)WireType.Extended; if ((field.Tag & Tag.FieldIdCompleteMask) == Tag.FieldIdCompleteMask && notExtended) { field.FieldIdDeltaRaw = reader.ReadVarUInt32NoInlining(); } else { field.FieldIdDeltaRaw = 0; } // If schema type is valid, read the type. var schemaType = (SchemaType)(field.Tag & Tag.SchemaTypeMask); if (notExtended && schemaType != SchemaType.Expected) { (field.FieldTypeRaw, type) = reader.ReadTypeForAnalysis(schemaType); } else { field.FieldTypeRaw = default; } } } }
43.251592
170
0.55666
[ "MIT" ]
BearerPipelineTest/orleans
src/Orleans.Serialization/Codecs/FieldHeaderCodec.cs
13,581
C#
using System; using System.Collections.Generic; namespace Yarn.EventSourcing { public interface IAggregate { Guid Id { get; } int Version { get; } IEnumerable<object> GetUncommittedEvents(); void ClearUncommittedEvents(); } }
20.769231
51
0.651852
[ "MIT" ]
stepaside/Yarn
Yarn/EventSourcing/IAggregate.cs
270
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ResolveEventTrigger.cs" company="Sitecore A/S"> // Copyright (C) 2013 by Sitecore A/S // </copyright> // <summary> // Determines the event trigger. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace Sitecore.MediaFramework.Pipelines.Analytics { using Sitecore.Diagnostics; using Sitecore.MediaFramework.Analytics; using Sitecore.MediaFramework.Diagnostics; /// <summary> /// Determines the event trigger. /// </summary> public class ResolveEventTrigger : PlayerEventProcessorBase { /// <summary> /// Processes determining the event trigger. /// </summary> /// <param name="args"> /// The args. /// </param> public override void Process(PlayerEventArgs args) { Assert.ArgumentNotNull(args, "args"); Assert.ArgumentNotNull(args.Properties, "args.Parameters"); IEventTrigger trigger = MediaFrameworkContext.GetEventTrigger(args.Properties.Template); if (trigger != null) { args.Trigger = trigger; } else { LogHelper.Warn("Player event trigger couldn't be determine for the player.", this); args.AbortPipeline(); } } } }
34.844444
121
0.482143
[ "Apache-2.0" ]
BrightcoveOS/Sitecore-8.x-Media-Framework-2.x-Connector
src/Sitecore.MediaFramework/Pipelines/Analytics/ResolveEventTrigger.cs
1,570
C#
namespace EasyServices.Web.Areas.Administration.Controllers { using System.Threading.Tasks; using EasyServices.Services.Data; using EasyServices.Web.ViewModels.Administration.SubCategories; using Microsoft.AspNetCore.Mvc; public class SubCategoriesController : AdministrationController { private readonly ISubCategoriesService subCategoriesService; public SubCategoriesController(ISubCategoriesService subCategoriesService) { this.subCategoriesService = subCategoriesService; } [HttpPost] public async Task<IActionResult> Create(AddSubCategoryInputModel inputModel) { if (!this.ModelState.IsValid) { return this.Redirect($"/Administration/Categories/ById/{inputModel.CategoryId}"); } await this.subCategoriesService.AddSubCategory(inputModel); return this.Redirect($"/Administration/Categories/ById/{inputModel.CategoryId}"); } public async Task<IActionResult> Edit(EditSubCategoryModel editModel) { int categoryId = this.subCategoriesService.GetCategoryId(editModel.Id); if (!this.ModelState.IsValid) { return this.Redirect($"/Administration/Categories/ById/{categoryId}"); } await this.subCategoriesService.EditSubCategory(editModel); return this.Redirect($"/Administration/Categories/ById/{categoryId}"); } public async Task<IActionResult> Delete(int id) { int categoryId = this.subCategoriesService.GetCategoryId(id); await this.subCategoriesService.DeleteSubCategory(id); return this.Redirect($"/Administration/Categories/ById/{categoryId}"); } } }
33.090909
97
0.664286
[ "MIT" ]
djengo16/EasyServices
Web/EasyServices.Web/Areas/Administration/Controllers/SubCategoriesController.cs
1,822
C#
using System; using System.IO; namespace FingerSensorsApp.Helpers { public static class StreamExtensions { public static string ToBase64String(this Stream stream) { using (var memoryStream = new MemoryStream()) { stream.CopyTo(memoryStream); return Convert.ToBase64String(memoryStream.ToArray()); } } } }
22.833333
70
0.588808
[ "Apache-2.0" ]
srw2ho/FingerPrintSensor_SEN0188
FingerSensorsApp/Helpers/StreamExtensions.cs
413
C#
// <auto-generated /> using System; using AbpUserImport.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using Volo.Abp.EntityFrameworkCore; #nullable disable namespace AbpUserImport.Migrations { [DbContext(typeof(AbpUserImportDbContext))] [Migration("20211223102134_Initial")] partial class Initial { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("_Abp_DatabaseProvider", EfCoreDatabaseProvider.SqlServer) .HasAnnotation("ProductVersion", "6.0.0") .HasAnnotation("Relational:MaxIdentifierLength", 128); SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder, 1L, 1); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLog", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ApplicationName") .HasMaxLength(96) .HasColumnType("nvarchar(96)") .HasColumnName("ApplicationName"); b.Property<string>("BrowserInfo") .HasMaxLength(512) .HasColumnType("nvarchar(512)") .HasColumnName("BrowserInfo"); b.Property<string>("ClientId") .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("ClientId"); b.Property<string>("ClientIpAddress") .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("ClientIpAddress"); b.Property<string>("ClientName") .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("ClientName"); b.Property<string>("Comments") .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("Comments"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<string>("CorrelationId") .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("CorrelationId"); b.Property<string>("Exceptions") .HasColumnType("nvarchar(max)"); b.Property<int>("ExecutionDuration") .HasColumnType("int") .HasColumnName("ExecutionDuration"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<string>("HttpMethod") .HasMaxLength(16) .HasColumnType("nvarchar(16)") .HasColumnName("HttpMethod"); b.Property<int?>("HttpStatusCode") .HasColumnType("int") .HasColumnName("HttpStatusCode"); b.Property<Guid?>("ImpersonatorTenantId") .HasColumnType("uniqueidentifier") .HasColumnName("ImpersonatorTenantId"); b.Property<Guid?>("ImpersonatorUserId") .HasColumnType("uniqueidentifier") .HasColumnName("ImpersonatorUserId"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.Property<string>("TenantName") .HasColumnType("nvarchar(max)"); b.Property<string>("Url") .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("Url"); b.Property<Guid?>("UserId") .HasColumnType("uniqueidentifier") .HasColumnName("UserId"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("UserName"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId", "ExecutionTime"); b.ToTable("AbpAuditLogs", (string)null); }); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLogAction", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("AuditLogId") .HasColumnType("uniqueidentifier") .HasColumnName("AuditLogId"); b.Property<int>("ExecutionDuration") .HasColumnType("int") .HasColumnName("ExecutionDuration"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2") .HasColumnName("ExecutionTime"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<string>("MethodName") .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("MethodName"); b.Property<string>("Parameters") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)") .HasColumnName("Parameters"); b.Property<string>("ServiceName") .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("ServiceName"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("AuditLogId"); b.HasIndex("TenantId", "ServiceName", "MethodName", "ExecutionTime"); b.ToTable("AbpAuditLogActions", (string)null); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityChange", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("AuditLogId") .HasColumnType("uniqueidentifier") .HasColumnName("AuditLogId"); b.Property<DateTime>("ChangeTime") .HasColumnType("datetime2") .HasColumnName("ChangeTime"); b.Property<byte>("ChangeType") .HasColumnType("tinyint") .HasColumnName("ChangeType"); b.Property<string>("EntityId") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("EntityId"); b.Property<Guid?>("EntityTenantId") .HasColumnType("uniqueidentifier"); b.Property<string>("EntityTypeFullName") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("EntityTypeFullName"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("AuditLogId"); b.HasIndex("TenantId", "EntityTypeFullName", "EntityId"); b.ToTable("AbpEntityChanges", (string)null); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityPropertyChange", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("EntityChangeId") .HasColumnType("uniqueidentifier"); b.Property<string>("NewValue") .HasMaxLength(512) .HasColumnType("nvarchar(512)") .HasColumnName("NewValue"); b.Property<string>("OriginalValue") .HasMaxLength(512) .HasColumnType("nvarchar(512)") .HasColumnName("OriginalValue"); b.Property<string>("PropertyName") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("PropertyName"); b.Property<string>("PropertyTypeFullName") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("PropertyTypeFullName"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("EntityChangeId"); b.ToTable("AbpEntityPropertyChanges", (string)null); }); modelBuilder.Entity("Volo.Abp.BackgroundJobs.BackgroundJobRecord", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsAbandoned") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false); b.Property<string>("JobArgs") .IsRequired() .HasMaxLength(1048576) .HasColumnType("nvarchar(max)"); b.Property<string>("JobName") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<DateTime?>("LastTryTime") .HasColumnType("datetime2"); b.Property<DateTime>("NextTryTime") .HasColumnType("datetime2"); b.Property<byte>("Priority") .ValueGeneratedOnAdd() .HasColumnType("tinyint") .HasDefaultValue((byte)15); b.Property<short>("TryCount") .ValueGeneratedOnAdd() .HasColumnType("smallint") .HasDefaultValue((short)0); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs", (string)null); }); modelBuilder.Entity("Volo.Abp.FeatureManagement.FeatureValue", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ProviderName") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("Value") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.HasKey("Id"); b.HasIndex("Name", "ProviderName", "ProviderKey") .IsUnique() .HasFilter("[ProviderName] IS NOT NULL AND [ProviderKey] IS NOT NULL"); b.ToTable("AbpFeatureValues", (string)null); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityClaimType", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<string>("Description") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsStatic") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("Regex") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<string>("RegexDescription") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<bool>("Required") .HasColumnType("bit"); b.Property<int>("ValueType") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("AbpClaimTypes", (string)null); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityLinkUser", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("SourceTenantId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("SourceUserId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TargetTenantId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("TargetUserId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("SourceUserId", "SourceTenantId", "TargetUserId", "TargetTenantId") .IsUnique() .HasFilter("[SourceTenantId] IS NOT NULL AND [TargetTenantId] IS NOT NULL"); b.ToTable("AbpLinkUsers", (string)null); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRole", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDefault") .HasColumnType("bit") .HasColumnName("IsDefault"); b.Property<bool>("IsPublic") .HasColumnType("bit") .HasColumnName("IsPublic"); b.Property<bool>("IsStatic") .HasColumnType("bit") .HasColumnName("IsStatic"); b.Property<string>("Name") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("NormalizedName") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("NormalizedName"); b.ToTable("AbpRoles", (string)null); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("ClaimType") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("ClaimValue") .HasMaxLength(1024) .HasColumnType("nvarchar(1024)"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AbpRoleClaims", (string)null); }); modelBuilder.Entity("Volo.Abp.Identity.IdentitySecurityLog", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("Action") .HasMaxLength(96) .HasColumnType("nvarchar(96)"); b.Property<string>("ApplicationName") .HasMaxLength(96) .HasColumnType("nvarchar(96)"); b.Property<string>("BrowserInfo") .HasMaxLength(512) .HasColumnType("nvarchar(512)"); b.Property<string>("ClientId") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ClientIpAddress") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<string>("CorrelationId") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<string>("Identity") .HasMaxLength(96) .HasColumnType("nvarchar(96)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.Property<string>("TenantName") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<Guid?>("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("UserName") .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.HasKey("Id"); b.HasIndex("TenantId", "Action"); b.HasIndex("TenantId", "ApplicationName"); b.HasIndex("TenantId", "Identity"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpSecurityLogs", (string)null); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUser", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<int>("AccessFailedCount") .ValueGeneratedOnAdd() .HasColumnType("int") .HasDefaultValue(0) .HasColumnName("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("Email") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("Email"); b.Property<bool>("EmailConfirmed") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("EmailConfirmed"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<bool>("IsExternal") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsExternal"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<bool>("LockoutEnabled") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd") .HasColumnType("datetimeoffset"); b.Property<string>("Name") .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("Name"); b.Property<string>("NormalizedEmail") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("NormalizedEmail"); b.Property<string>("NormalizedUserName") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("NormalizedUserName"); b.Property<string>("PasswordHash") .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("PasswordHash"); b.Property<string>("PhoneNumber") .HasMaxLength(16) .HasColumnType("nvarchar(16)") .HasColumnName("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("SecurityStamp"); b.Property<string>("Surname") .HasMaxLength(64) .HasColumnType("nvarchar(64)") .HasColumnName("Surname"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.Property<bool>("TwoFactorEnabled") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("TwoFactorEnabled"); b.Property<string>("UserName") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)") .HasColumnName("UserName"); b.HasKey("Id"); b.HasIndex("Email"); b.HasIndex("NormalizedEmail"); b.HasIndex("NormalizedUserName"); b.HasIndex("UserName"); b.ToTable("AbpUsers", (string)null); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("ClaimType") .IsRequired() .HasMaxLength(256) .HasColumnType("nvarchar(256)"); b.Property<string>("ClaimValue") .HasMaxLength(1024) .HasColumnType("nvarchar(1024)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AbpUserClaims", (string)null); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("LoginProvider") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ProviderDisplayName") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .IsRequired() .HasMaxLength(196) .HasColumnType("nvarchar(196)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("UserId", "LoginProvider"); b.HasIndex("LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins", (string)null); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserOrganizationUnit", b => { b.Property<Guid>("OrganizationUnitId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("OrganizationUnitId", "UserId"); b.HasIndex("UserId", "OrganizationUnitId"); b.ToTable("AbpUserOrganizationUnits", (string)null); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId", "UserId"); b.ToTable("AbpUserRoles", (string)null); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b => { b.Property<Guid>("UserId") .HasColumnType("uniqueidentifier"); b.Property<string>("LoginProvider") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("Name") .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AbpUserTokens", (string)null); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnit", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("Code") .IsRequired() .HasMaxLength(95) .HasColumnType("nvarchar(95)") .HasColumnName("Code"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)") .HasColumnName("DisplayName"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<Guid?>("ParentId") .HasColumnType("uniqueidentifier"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("Code"); b.HasIndex("ParentId"); b.ToTable("AbpOrganizationUnits", (string)null); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnitRole", b => { b.Property<Guid>("OrganizationUnitId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("RoleId") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("OrganizationUnitId", "RoleId"); b.HasIndex("RoleId", "OrganizationUnitId"); b.ToTable("AbpOrganizationUnitRoles", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResource", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("AllowedAccessTokenSigningAlgorithms") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("Description") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<string>("DisplayName") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<bool>("Enabled") .HasColumnType("bit"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<bool>("ShowInDiscoveryDocument") .HasColumnType("bit"); b.HasKey("Id"); b.ToTable("IdentityServerApiResources", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceClaim", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("ApiResourceId", "Type"); b.ToTable("IdentityServerApiResourceClaims", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceProperty", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Key") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("Value") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.HasKey("ApiResourceId", "Key", "Value"); b.ToTable("IdentityServerApiResourceProperties", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceScope", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Scope") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("ApiResourceId", "Scope"); b.ToTable("IdentityServerApiResourceScopes", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceSecret", b => { b.Property<Guid>("ApiResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("Value") .HasMaxLength(4000) .HasColumnType("nvarchar(4000)"); b.Property<string>("Description") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.HasKey("ApiResourceId", "Type", "Value"); b.ToTable("IdentityServerApiResourceSecrets", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScope", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("Description") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<string>("DisplayName") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<bool>("Emphasize") .HasColumnType("bit"); b.Property<bool>("Enabled") .HasColumnType("bit"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<bool>("Required") .HasColumnType("bit"); b.Property<bool>("ShowInDiscoveryDocument") .HasColumnType("bit"); b.HasKey("Id"); b.ToTable("IdentityServerApiScopes", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScopeClaim", b => { b.Property<Guid>("ApiScopeId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("ApiScopeId", "Type"); b.ToTable("IdentityServerApiScopeClaims", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScopeProperty", b => { b.Property<Guid>("ApiScopeId") .HasColumnType("uniqueidentifier"); b.Property<string>("Key") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("Value") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.HasKey("ApiScopeId", "Key", "Value"); b.ToTable("IdentityServerApiScopeProperties", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.Client", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<int>("AbsoluteRefreshTokenLifetime") .HasColumnType("int"); b.Property<int>("AccessTokenLifetime") .HasColumnType("int"); b.Property<int>("AccessTokenType") .HasColumnType("int"); b.Property<bool>("AllowAccessTokensViaBrowser") .HasColumnType("bit"); b.Property<bool>("AllowOfflineAccess") .HasColumnType("bit"); b.Property<bool>("AllowPlainTextPkce") .HasColumnType("bit"); b.Property<bool>("AllowRememberConsent") .HasColumnType("bit"); b.Property<string>("AllowedIdentityTokenSigningAlgorithms") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<bool>("AlwaysIncludeUserClaimsInIdToken") .HasColumnType("bit"); b.Property<bool>("AlwaysSendClientClaims") .HasColumnType("bit"); b.Property<int>("AuthorizationCodeLifetime") .HasColumnType("int"); b.Property<bool>("BackChannelLogoutSessionRequired") .HasColumnType("bit"); b.Property<string>("BackChannelLogoutUri") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.Property<string>("ClientClaimsPrefix") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ClientId") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ClientName") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ClientUri") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<int?>("ConsentLifetime") .HasColumnType("int"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("Description") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<int>("DeviceCodeLifetime") .HasColumnType("int"); b.Property<bool>("EnableLocalLogin") .HasColumnType("bit"); b.Property<bool>("Enabled") .HasColumnType("bit"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("FrontChannelLogoutSessionRequired") .HasColumnType("bit"); b.Property<string>("FrontChannelLogoutUri") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.Property<int>("IdentityTokenLifetime") .HasColumnType("int"); b.Property<bool>("IncludeJwtId") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<string>("LogoUri") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.Property<string>("PairWiseSubjectSalt") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ProtocolType") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<int>("RefreshTokenExpiration") .HasColumnType("int"); b.Property<int>("RefreshTokenUsage") .HasColumnType("int"); b.Property<bool>("RequireClientSecret") .HasColumnType("bit"); b.Property<bool>("RequireConsent") .HasColumnType("bit"); b.Property<bool>("RequirePkce") .HasColumnType("bit"); b.Property<bool>("RequireRequestObject") .HasColumnType("bit"); b.Property<int>("SlidingRefreshTokenLifetime") .HasColumnType("int"); b.Property<bool>("UpdateAccessTokenClaimsOnRefresh") .HasColumnType("bit"); b.Property<string>("UserCodeType") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<int?>("UserSsoLifetime") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ClientId"); b.ToTable("IdentityServerClients", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientClaim", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("Value") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.HasKey("ClientId", "Type", "Value"); b.ToTable("IdentityServerClientClaims", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientCorsOrigin", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Origin") .HasMaxLength(150) .HasColumnType("nvarchar(150)"); b.HasKey("ClientId", "Origin"); b.ToTable("IdentityServerClientCorsOrigins", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientGrantType", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("GrantType") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.HasKey("ClientId", "GrantType"); b.ToTable("IdentityServerClientGrantTypes", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientIdPRestriction", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Provider") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("ClientId", "Provider"); b.ToTable("IdentityServerClientIdPRestrictions", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientPostLogoutRedirectUri", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("PostLogoutRedirectUri") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.HasKey("ClientId", "PostLogoutRedirectUri"); b.ToTable("IdentityServerClientPostLogoutRedirectUris", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientProperty", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Key") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("Value") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.HasKey("ClientId", "Key", "Value"); b.ToTable("IdentityServerClientProperties", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientRedirectUri", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("RedirectUri") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.HasKey("ClientId", "RedirectUri"); b.ToTable("IdentityServerClientRedirectUris", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientScope", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Scope") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("ClientId", "Scope"); b.ToTable("IdentityServerClientScopes", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientSecret", b => { b.Property<Guid>("ClientId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("Value") .HasMaxLength(4000) .HasColumnType("nvarchar(4000)"); b.Property<string>("Description") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.HasKey("ClientId", "Type", "Value"); b.ToTable("IdentityServerClientSecrets", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Devices.DeviceFlowCodes", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ClientId") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<string>("Data") .IsRequired() .HasMaxLength(50000) .HasColumnType("nvarchar(max)"); b.Property<string>("Description") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("DeviceCode") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<DateTime?>("Expiration") .IsRequired() .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<string>("SessionId") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<string>("SubjectId") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("UserCode") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("Id"); b.HasIndex("DeviceCode") .IsUnique(); b.HasIndex("Expiration"); b.HasIndex("UserCode"); b.ToTable("IdentityServerDeviceFlowCodes", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Grants.PersistedGrant", b => { b.Property<string>("Key") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ClientId") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime?>("ConsumedTime") .HasColumnType("datetime2"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("Data") .IsRequired() .HasMaxLength(50000) .HasColumnType("nvarchar(max)"); b.Property<string>("Description") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<DateTime?>("Expiration") .HasColumnType("datetime2"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("SessionId") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<string>("SubjectId") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<string>("Type") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.HasKey("Key"); b.HasIndex("Expiration"); b.HasIndex("SubjectId", "ClientId", "Type"); b.HasIndex("SubjectId", "SessionId", "Type"); b.ToTable("IdentityServerPersistedGrants", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("Description") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<string>("DisplayName") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<bool>("Emphasize") .HasColumnType("bit"); b.Property<bool>("Enabled") .HasColumnType("bit"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.Property<bool>("Required") .HasColumnType("bit"); b.Property<bool>("ShowInDiscoveryDocument") .HasColumnType("bit"); b.HasKey("Id"); b.ToTable("IdentityServerIdentityResources", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResourceClaim", b => { b.Property<Guid>("IdentityResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Type") .HasMaxLength(200) .HasColumnType("nvarchar(200)"); b.HasKey("IdentityResourceId", "Type"); b.ToTable("IdentityServerIdentityResourceClaims", (string)null); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResourceProperty", b => { b.Property<Guid>("IdentityResourceId") .HasColumnType("uniqueidentifier"); b.Property<string>("Key") .HasMaxLength(250) .HasColumnType("nvarchar(250)"); b.Property<string>("Value") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.HasKey("IdentityResourceId", "Key", "Value"); b.ToTable("IdentityServerIdentityResourceProperties", (string)null); }); modelBuilder.Entity("Volo.Abp.PermissionManagement.PermissionGrant", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ProviderName") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<Guid?>("TenantId") .HasColumnType("uniqueidentifier") .HasColumnName("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "Name", "ProviderName", "ProviderKey") .IsUnique() .HasFilter("[TenantId] IS NOT NULL"); b.ToTable("AbpPermissionGrants", (string)null); }); modelBuilder.Entity("Volo.Abp.SettingManagement.Setting", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128) .HasColumnType("nvarchar(128)"); b.Property<string>("ProviderKey") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("ProviderName") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("Value") .IsRequired() .HasMaxLength(2048) .HasColumnType("nvarchar(2048)"); b.HasKey("Id"); b.HasIndex("Name", "ProviderName", "ProviderKey") .IsUnique() .HasFilter("[ProviderName] IS NOT NULL AND [ProviderKey] IS NOT NULL"); b.ToTable("AbpSettings", (string)null); }); modelBuilder.Entity("Volo.Abp.TenantManagement.Tenant", b => { b.Property<Guid>("Id") .HasColumnType("uniqueidentifier"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(40) .HasColumnType("nvarchar(40)") .HasColumnName("ConcurrencyStamp"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2") .HasColumnName("CreationTime"); b.Property<Guid?>("CreatorId") .HasColumnType("uniqueidentifier") .HasColumnName("CreatorId"); b.Property<Guid?>("DeleterId") .HasColumnType("uniqueidentifier") .HasColumnName("DeleterId"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2") .HasColumnName("DeletionTime"); b.Property<string>("ExtraProperties") .HasColumnType("nvarchar(max)") .HasColumnName("ExtraProperties"); b.Property<bool>("IsDeleted") .ValueGeneratedOnAdd() .HasColumnType("bit") .HasDefaultValue(false) .HasColumnName("IsDeleted"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2") .HasColumnName("LastModificationTime"); b.Property<Guid?>("LastModifierId") .HasColumnType("uniqueidentifier") .HasColumnName("LastModifierId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.HasKey("Id"); b.HasIndex("Name"); b.ToTable("AbpTenants", (string)null); }); modelBuilder.Entity("Volo.Abp.TenantManagement.TenantConnectionString", b => { b.Property<Guid>("TenantId") .HasColumnType("uniqueidentifier"); b.Property<string>("Name") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<string>("Value") .IsRequired() .HasMaxLength(1024) .HasColumnType("nvarchar(1024)"); b.HasKey("TenantId", "Name"); b.ToTable("AbpTenantConnectionStrings", (string)null); }); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLogAction", b => { b.HasOne("Volo.Abp.AuditLogging.AuditLog", null) .WithMany("Actions") .HasForeignKey("AuditLogId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityChange", b => { b.HasOne("Volo.Abp.AuditLogging.AuditLog", null) .WithMany("EntityChanges") .HasForeignKey("AuditLogId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityPropertyChange", b => { b.HasOne("Volo.Abp.AuditLogging.EntityChange", null) .WithMany("PropertyChanges") .HasForeignKey("EntityChangeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRoleClaim", b => { b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserClaim", b => { b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserLogin", b => { b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserOrganizationUnit", b => { b.HasOne("Volo.Abp.Identity.OrganizationUnit", null) .WithMany() .HasForeignKey("OrganizationUnitId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("OrganizationUnits") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserRole", b => { b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUserToken", b => { b.HasOne("Volo.Abp.Identity.IdentityUser", null) .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnit", b => { b.HasOne("Volo.Abp.Identity.OrganizationUnit", null) .WithMany() .HasForeignKey("ParentId"); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnitRole", b => { b.HasOne("Volo.Abp.Identity.OrganizationUnit", null) .WithMany("Roles") .HasForeignKey("OrganizationUnitId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Volo.Abp.Identity.IdentityRole", null) .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceClaim", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("UserClaims") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceProperty", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("Properties") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceScope", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("Scopes") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResourceSecret", b => { b.HasOne("Volo.Abp.IdentityServer.ApiResources.ApiResource", null) .WithMany("Secrets") .HasForeignKey("ApiResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScopeClaim", b => { b.HasOne("Volo.Abp.IdentityServer.ApiScopes.ApiScope", null) .WithMany("UserClaims") .HasForeignKey("ApiScopeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScopeProperty", b => { b.HasOne("Volo.Abp.IdentityServer.ApiScopes.ApiScope", null) .WithMany("Properties") .HasForeignKey("ApiScopeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientClaim", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("Claims") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientCorsOrigin", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("AllowedCorsOrigins") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientGrantType", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("AllowedGrantTypes") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientIdPRestriction", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("IdentityProviderRestrictions") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientPostLogoutRedirectUri", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("PostLogoutRedirectUris") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientProperty", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("Properties") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientRedirectUri", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("RedirectUris") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientScope", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("AllowedScopes") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.ClientSecret", b => { b.HasOne("Volo.Abp.IdentityServer.Clients.Client", null) .WithMany("ClientSecrets") .HasForeignKey("ClientId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResourceClaim", b => { b.HasOne("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", null) .WithMany("UserClaims") .HasForeignKey("IdentityResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResourceProperty", b => { b.HasOne("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", null) .WithMany("Properties") .HasForeignKey("IdentityResourceId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.TenantManagement.TenantConnectionString", b => { b.HasOne("Volo.Abp.TenantManagement.Tenant", null) .WithMany("ConnectionStrings") .HasForeignKey("TenantId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Volo.Abp.AuditLogging.AuditLog", b => { b.Navigation("Actions"); b.Navigation("EntityChanges"); }); modelBuilder.Entity("Volo.Abp.AuditLogging.EntityChange", b => { b.Navigation("PropertyChanges"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityRole", b => { b.Navigation("Claims"); }); modelBuilder.Entity("Volo.Abp.Identity.IdentityUser", b => { b.Navigation("Claims"); b.Navigation("Logins"); b.Navigation("OrganizationUnits"); b.Navigation("Roles"); b.Navigation("Tokens"); }); modelBuilder.Entity("Volo.Abp.Identity.OrganizationUnit", b => { b.Navigation("Roles"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiResources.ApiResource", b => { b.Navigation("Properties"); b.Navigation("Scopes"); b.Navigation("Secrets"); b.Navigation("UserClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.ApiScopes.ApiScope", b => { b.Navigation("Properties"); b.Navigation("UserClaims"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.Clients.Client", b => { b.Navigation("AllowedCorsOrigins"); b.Navigation("AllowedGrantTypes"); b.Navigation("AllowedScopes"); b.Navigation("Claims"); b.Navigation("ClientSecrets"); b.Navigation("IdentityProviderRestrictions"); b.Navigation("PostLogoutRedirectUris"); b.Navigation("Properties"); b.Navigation("RedirectUris"); }); modelBuilder.Entity("Volo.Abp.IdentityServer.IdentityResources.IdentityResource", b => { b.Navigation("Properties"); b.Navigation("UserClaims"); }); modelBuilder.Entity("Volo.Abp.TenantManagement.Tenant", b => { b.Navigation("ConnectionStrings"); }); #pragma warning restore 612, 618 } } }
38.787105
106
0.446021
[ "MIT" ]
bartvanhoey/AbpUserImport
src/AbpUserImport.EntityFrameworkCore/Migrations/20211223102134_Initial.Designer.cs
89,639
C#
/******************************************************************************* * Copyright 2012-2019 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.ElasticTranscoder; using Amazon.ElasticTranscoder.Model; namespace Amazon.PowerShell.Cmdlets.ETS { /// <summary> /// The ReadJob operation returns detailed information about a job. /// </summary> [Cmdlet("Read", "ETSJob", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("Amazon.ElasticTranscoder.Model.Job")] [AWSCmdlet("Calls the Amazon Elastic Transcoder ReadJob API operation.", Operation = new[] {"ReadJob"}, SelectReturnType = typeof(Amazon.ElasticTranscoder.Model.ReadJobResponse))] [AWSCmdletOutput("Amazon.ElasticTranscoder.Model.Job or Amazon.ElasticTranscoder.Model.ReadJobResponse", "This cmdlet returns an Amazon.ElasticTranscoder.Model.Job object.", "The service call response (type Amazon.ElasticTranscoder.Model.ReadJobResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class ReadETSJobCmdlet : AmazonElasticTranscoderClientCmdlet, IExecutor { #region Parameter Id /// <summary> /// <para> /// <para>The identifier of the job for which you want to get detailed information.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String Id { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'Job'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.ElasticTranscoder.Model.ReadJobResponse). /// Specifying the name of a property of type Amazon.ElasticTranscoder.Model.ReadJobResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "Job"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the Id parameter. /// The -PassThru parameter is deprecated, use -Select '^Id' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^Id' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.Id), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Read-ETSJob (ReadJob)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.ElasticTranscoder.Model.ReadJobResponse, ReadETSJobCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.Id; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.Id = this.Id; #if MODULAR if (this.Id == null && ParameterWasBound(nameof(this.Id))) { WriteWarning("You are passing $null as a value for parameter Id which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.ElasticTranscoder.Model.ReadJobRequest(); if (cmdletContext.Id != null) { request.Id = cmdletContext.Id; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.ElasticTranscoder.Model.ReadJobResponse CallAWSServiceOperation(IAmazonElasticTranscoder client, Amazon.ElasticTranscoder.Model.ReadJobRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Elastic Transcoder", "ReadJob"); try { #if DESKTOP return client.ReadJob(request); #elif CORECLR return client.ReadJobAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String Id { get; set; } public System.Func<Amazon.ElasticTranscoder.Model.ReadJobResponse, ReadETSJobCmdlet, object> Select { get; set; } = (response, cmdlet) => response.Job; } } }
44.398148
273
0.607716
[ "Apache-2.0" ]
5u5hma/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/ElasticTranscoder/Basic/Read-ETSJob-Cmdlet.cs
9,590
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Windows; using System.Windows.Controls; using System.Windows.Navigation; using Microsoft.Phone.Controls; using Microsoft.Phone.Shell; using Phone.Classes; using System.Windows.Media.Imaging; using System.Windows.Media; using Phone.Classes.Models; using Phone.Resources; using Phone.Controls; namespace Phone { public partial class JogoPage : PhoneApplicationPage { private bool DEBUG = true; #region Events public event StringEventHandler AskGameStart; public event EmptyEventHandler AskToInitializeData; public event IntEventHandler ClickedCard; public event StringEventHandler SaveGame; public event StringEventHandler AskToLoadSavedData; #endregion private GameModel model = null; public GameModel Model { set { model = value; model.AnswerInitializeData += model_AnswerInitializeData; model.VazaChanged += model_VazaChanged; model.CardsSet += model_CardsSet; model.EnableActivePlayer += model_EnableActivePlayer; model.ChangeGamePoints += model_ChangeGamePoints; model.ChangePoints += model_ChangePoints; // respostas // eventos } } void model_ChangePoints(int a, int b) { if (a == 0) { TextBlock block = this.controlFindBlock("partidaEquipaA", GridPontuacao.Children); block.Text = b.ToString(); } else { TextBlock block = this.controlFindBlock("partidaEquipaB", GridPontuacao.Children); block.Text = b.ToString(); } } void model_ChangeGamePoints(int a, int b) { if (a == 0) { TextBlock block = this.controlFindBlock("jogoEquipaA", GridPontuacao.Children); block.Text = b.ToString(); } else { TextBlock block = this.controlFindBlock("jogoEquipaB", GridPontuacao.Children); block.Text = b.ToString(); } } public JogoPage() { InitializeComponent(); App.controller.MainView = this; this.Model = App.controller.Model; this.handUsuario.DoubleClick += handUsuario_DoubleClick; #region Application Bar Menu ApplicationBar = new ApplicationBar(); ApplicationBar.Mode = ApplicationBarMode.Default; ApplicationBar.Opacity = 1.0; ApplicationBar.IsVisible = false; ApplicationBar.IsMenuEnabled = false; ApplicationBarIconButton buttonPontuacao = new ApplicationBarIconButton(); buttonPontuacao.IconUri = new Uri("/icons_dark/appbar.upload.rest.png", UriKind.Relative); buttonPontuacao.Click += buttonPontuacao_Click; buttonPontuacao.Text = "Pontuation"; ApplicationBarIconButton buttonHistorico = new ApplicationBarIconButton(); buttonHistorico.IconUri = new Uri("/icons_dark/appbar.edit.rest.png", UriKind.Relative); buttonHistorico.Click += buttonHistorico_Click; buttonHistorico.Text = "History"; ApplicationBarIconButton buttonExit = new ApplicationBarIconButton(); buttonExit.IconUri = new Uri("/icons_dark/appbar.stop.rest.png", UriKind.Relative); buttonExit.Click += buttonExit_Click; buttonExit.Text = "Exit"; ApplicationBar.Buttons.Add(buttonPontuacao); ApplicationBar.Buttons.Add(buttonHistorico); ApplicationBar.Buttons.Add(buttonExit); #endregion GridAvatars.Visibility = Visibility.Collapsed; GridGame.Visibility = Visibility.Collapsed; GridClose.Visibility = Visibility.Collapsed; GridPontuacao.Visibility = Visibility.Collapsed; GridGame.Visibility = Visibility.Collapsed; GridFill.Visibility = Visibility.Visible; } void buttonHistorico_Click(object sender, EventArgs e) { (App.Current as App).currentPartida = this.model.partidas[this.model.curPartida]; NavigationService.Navigate(new Uri("/HistoryPage.xaml", UriKind.Relative)); } void model_VazaChanged() { if (model.partidas[model.curPartida].vazas[model.partidas[model.curPartida].vazas.Count - 1].getNumeroJogadas() == 0) { foreach (UIElement ctrl in GridGame.Children) { if (ctrl.GetType() == typeof(Image)) { Image pic = ((Image)ctrl); if (pic.Name.Contains("picJogada")) { pic.Source = null; } } } } else { foreach (Jogada jogada in model.partidas[model.curPartida].vazas[model.partidas[model.curPartida].vazas.Count - 1].jogadas) { int id = jogada.jogador.ID; Image pic = controlFind("picJogada" + id); //Image pic = this.panelVaza.Controls.Find("picJogada" + id, true)[0] as PictureBox; pic.Source = new BitmapImage(new Uri("/Resources/Cards/" + jogada.carta.naipe.ToString() + "/" + jogada.carta.identificador + ".png", UriKind.RelativeOrAbsolute)); } } } void model_CardsSet() { // trunfo this.picTrunfo.Source = new BitmapImage(new Uri("/Resources/Cards/" + model.partidas[model.curPartida].trunfo.naipe.ToString() + "/" + model.partidas[model.curPartida].trunfo.identificador + ".png", UriKind.RelativeOrAbsolute)); for (int i = 0; i < 4; i++) { TextBlock playername = this.controlFindBlock("lblPlayerName" + i, GridGame.Children); playername.Text = model.equipas[i / 2].jogadores[i % 2].Nome; } } void model_EnableActivePlayer() { int id = model.ActivePlayer.ID; for (int i = 0; i < 4; i++) { TextBlock playername = controlFindBlock("lblPlayerName" + i, GridGame.Children); playername.Foreground = id == i ? new SolidColorBrush(Colors.Red) : new SolidColorBrush(Colors.White); } this.handUsuario.IsEnabled = model.ActivePlayer is HumanPlayer; } Image controlFind(string key) { foreach (UIElement ctrl in GridGame.Children) { if (ctrl.GetType() == typeof(Image)) { Image pic = ((Image)ctrl); if (pic.Name == key) { return pic; } } } return null; } TextBlock controlFindBlock(string key, UIElementCollection collection) { foreach (UIElement ctrl in collection) { if (ctrl.GetType() == typeof(TextBlock)) { TextBlock pic = ((TextBlock)ctrl); if (pic.Name == key) { return pic; } } } return null; } void model_AnswerInitializeData() { for (int i = 0; i < 4; i++) { IPlayer player = model.partidas[model.curPartida].Equipas[i % 2].jogadores[i / 2]; player.RefreshHand += player_RefreshHand; } } void player_RefreshHand(IPlayer player) { switch (player.ID) { // jogador case 0: DrawHands(this.handUsuario, player); break; // parceiro case 1: DrawHands(this.handParceiro, player, true); break; // bot direita case 2: DrawHands(this.handBotDireita, player, true); break; // bot esquerda case 3: DrawHands(this.handBotEsquerda, player, true); break; default: break; } } private void DrawHands(UserControl hand, IPlayer player, bool backside = false) { string pathTest; for (int i = 0; i < 10; i++) { if (!backside || DEBUG) { if (player.Mao[i] != null) { pathTest = "/Resources/Cards/" + player.Mao[i].naipe.ToString() + "/" + player.Mao[i].identificador + ".png"; } else pathTest = ""; } else if (player.Mao[i] != null) pathTest = "/Resources/Cards/backside.png"; else pathTest = ""; if (hand is HandHorizontal) { ((HandHorizontal)hand).ChangeHandCard(i, pathTest); } else if (hand is HandUpRight) { ((HandUpRight)hand).ChangeHandCard(i, pathTest); } } } void handUsuario_DoubleClick(object o) { Image p = o as Image; int pos = Convert.ToInt32(p.Name.Substring(4)); if (ClickedCard != null) { ClickedCard(pos); } } //private void DrawAvatars() //{ // BitmapImage src = new BitmapImage(new Uri("/Resources/Avatars/0.png", UriKind.RelativeOrAbsolute)); // avatarUsuario.Source = src; // BitmapImage src1 = new BitmapImage(new Uri("/Resources/Avatars/1.png", UriKind.RelativeOrAbsolute)); // avatarBotEsquerda.Source = src1; // BitmapImage src2 = new BitmapImage(new Uri("/Resources/Avatars/2.png", UriKind.RelativeOrAbsolute)); // avatarParceiro.Source = src2; // BitmapImage src3 = new BitmapImage(new Uri("/Resources/Avatars/3.png", UriKind.RelativeOrAbsolute)); // avatarBotDireita.Source = src3; // //pic.Image = ImageUtilities.ResizeImage(src, newWidth, newHeight); // //pic.Image = ImageUtilities.ChangeOpacity(pic.Image, 0.5f); //} private void close() { if (!canClose && this.GridGame.Visibility == Visibility.Visible) { // para não haver sobreposição de grids this.GridPontuacao.Visibility = Visibility.Collapsed; this.ApplicationBar.IsMenuEnabled = false; //this.GridGame.Visibility = Visibility.Collapsed; this.GridClose.Visibility = Visibility.Visible; } } void buttonPontuacao_Click(object sender, EventArgs e) { switch (GridPontuacao.Visibility) { case Visibility.Collapsed: GridPontuacao.Visibility = Visibility.Visible; break; case Visibility.Visible: GridPontuacao.Visibility = Visibility.Collapsed; break; } } private bool goback; void buttonExit_Click(object sender, EventArgs e) { goback = !canClose; close(); } private bool canClose = false; private void PhoneApplicationPage_BackKeyPress_1(object sender, System.ComponentModel.CancelEventArgs e) { e.Cancel = !canClose; // model. close(); } private void btnYes_Click(object sender, RoutedEventArgs e) { canClose = true; goback = true; this.GridClose.Visibility = Visibility.Collapsed; if (SaveGame != null) { SaveGame("savedData.xml"); //MyFolder\\ } NavigationService.GoBack(); // codigo para gravar } private void btnNo_Click(object sender, RoutedEventArgs e) { canClose = true; goback = true; this.GridClose.Visibility = Visibility.Collapsed; NavigationService.GoBack(); // aqui nao grava } private void btnCancel_Click(object sender, RoutedEventArgs e) { canClose = false; goback = false; this.GridClose.Visibility = Visibility.Collapsed; this.ApplicationBar.IsMenuEnabled = true; } private void txtName_TextChanged(object sender, TextChangedEventArgs e) { if (txtName.Text.Trim() != "") { btnConfirm.IsEnabled = true; } else btnConfirm.IsEnabled = false; } private void btnConfirm_Click(object sender, RoutedEventArgs e) { if (AskGameStart != null) { AskGameStart(txtName.Text); GridFill.Visibility = Visibility.Collapsed; GridGame.Visibility = Visibility.Visible; GridAvatars.Visibility = Visibility.Visible; ApplicationBar.IsVisible = true; ApplicationBar.IsMenuEnabled = true; } } private void PhoneApplicationPage_Loaded_1(object sender, RoutedEventArgs e) { if (AskToInitializeData != null && (App.Current as App).load == "false") { AskToInitializeData(); } else if (AskToLoadSavedData != null && (App.Current as App).load == "true") { AskToLoadSavedData("saveData.xml"); //MyFolder } } public void GoBack() { NavigationService.GoBack(); } } }
33.580645
241
0.518732
[ "MIT" ]
Apidcloud/ProjectoSueca
Windows Phone 7.1 - updated/Phone - actualizado/Phone/JogoPage.xaml.cs
14,579
C#
namespace BrightChain.Engine.Enumerations { /// <summary> /// List of the pre-specified block sizes this node supports /// The BlockSizeMap class contains the map to the actual sizes. /// </summary> public enum BlockSize { /// <summary> /// Invalid/indeterminate/unknown block size /// </summary> Unknown, /// <summary> /// Message size, such as a small data blob, currently 512b /// </summary> Message, /// <summary> /// Tiny size, such as smaller messages and configs, currently 1K /// </summary> Tiny, /// <summary> /// Small size, such as small data files up to a mb or so depending on desired block count, currently 4K /// </summary> Small, /// <summary> /// Medium size, such as medium data files up to 5-100mb, currently 1M /// </summary> Medium, /// <summary> /// Large size, such as large data files over 4M up to many terabytes. /// </summary> Large } }
31.057143
113
0.551058
[ "Apache-2.0" ]
MaxMood96/BrightChain
src/BrightChain.Engine/Enumerations/BlockSize.cs
1,089
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ViewLocator.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Catel.MVVM { using System; using System.Collections.Generic; using Catel.Services; using Reflection; /// <summary> /// Resolver that will resolve view types based on the view model type. For example, if a view model with the type /// name <c>MyAssembly.ViewModels.PersonViewModel</c> is inserted, this could result in the view type /// <c>MyAssembly.Views.PersonView</c>. /// </summary> public class ViewLocator : LocatorBase, IViewLocator { /// <summary> /// Registers the specified view in the local cache. This cache will also be used by the /// <see cref="ResolveView"/> method. /// </summary> /// <param name="viewModelType">Type of the view model.</param> /// <param name="viewType">Type of the view.</param> /// <exception cref="ArgumentNullException">The <paramref name="viewModelType"/> is <c>null</c>.</exception> /// <exception cref="ArgumentNullException">The <paramref name="viewType"/> is <c>null</c>.</exception> public void Register(Type viewModelType, Type viewType) { Argument.IsNotNull("viewModelType", viewModelType); Argument.IsNotNull("viewType", viewType); var viewModelTypeName = TypeHelper.GetTypeNameWithAssembly(viewModelType.AssemblyQualifiedName); var viewTypeName = TypeHelper.GetTypeNameWithAssembly(viewType.AssemblyQualifiedName); Register(viewModelTypeName, viewTypeName); } /// <summary> /// Resolves a view type by the view model and the registered <see cref="ILocator.NamingConventions"/>. /// </summary> /// <param name="viewModelType">Type of the view model to resolve the view for.</param> /// <returns>The resolved view or <c>null</c> if the view could not be resolved.</returns> /// <exception cref="ArgumentNullException">The <paramref name="viewModelType"/> is <c>null</c>.</exception> public virtual Type ResolveView(Type viewModelType) { Argument.IsNotNull("viewModelType", viewModelType); var viewModelTypeName = TypeHelper.GetTypeNameWithAssembly(viewModelType.AssemblyQualifiedName); string resolvedType = Resolve(viewModelTypeName); return GetTypeFromString(resolvedType); } /// <summary> /// Resolves a single naming convention. /// <para/> /// This method is abstract because each locator should or could use its own naming convention to resolve /// the type. The <see cref="LocatorBase.Resolve"/> method has prepared all the values such as the assembly name and the /// only thing this method has to do is to actually resolve a string value based on the specified naming convention. /// </summary> /// <param name="assembly">The assembly name.</param> /// <param name="typeToResolveName">The full type name of the type to resolve.</param> /// <param name="namingConvention">The naming convention to use for resolving.</param> /// <returns>The resolved naming convention.</returns> protected override string ResolveNamingConvention(string assembly, string typeToResolveName, string namingConvention) { return NamingConvention.ResolveViewByViewModelName(assembly, typeToResolveName, namingConvention); } /// <summary> /// Gets the default naming conventions. /// </summary> /// <returns>An enumerable of default naming conventions.</returns> protected override IEnumerable<string> GetDefaultNamingConventions() { var namingConventions = new List<string>(); namingConventions.Add(string.Format("[UP].Views.{0}", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("[UP].Views.{0}View", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("[UP].Views.{0}Control", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("[UP].Views.{0}Window", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("[UP].Views.{0}Page", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("[UP].Views.{0}Activity", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("[UP].Views.{0}Fragment", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("[UP].Controls.{0}", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("[UP].Controls.{0}Control", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("[UP].Pages.{0}", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("[UP].Pages.{0}Page", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("[UP].Windows.{0}", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("[UP].Windows.{0}Window", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("[UP].Activities.{0}", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("[UP].Activities.{0}Activity", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("[UP].Fragments.{0}", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("[UP].Fragments.{0}Fragment", NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Views.{1}", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Views.{1}View", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Views.{1}Control", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Views.{1}Page", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Views.{1}Window", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Views.{1}Activity", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Views.{1}Fragment", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Controls.{1}", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Controls.{1}Control", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Pages.{1}", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Pages.{1}Page", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Windows.{1}", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Windows.{1}Window", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Activities.{1}", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Activities.{1}Activity", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Fragments.{1}", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.Fragments.{1}Fragment", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.UI.Views.{1}", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.UI.Views.{1}View", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.UI.Views.{1}Control", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.UI.Views.{1}Page", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.UI.Views.{1}Window", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.UI.Views.{1}Activity", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.UI.Views.{1}Fragment", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.UI.Controls.{1}", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.UI.Controls.{1}Control", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.UI.Pages.{1}", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.UI.Pages.{1}Page", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.UI.Windows.{1}", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.UI.Windows.{1}Window", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.UI.Activities.{1}", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.UI.Activities.{1}Activity", NamingConvention.Assembly, NamingConvention.ViewModelName)); namingConventions.Add(string.Format("{0}.UI.Activities.{1}Fragment", NamingConvention.Assembly, NamingConvention.ViewModelName)); return namingConventions; } } }
74.185714
141
0.68756
[ "MIT" ]
crazeydave/Catel
src/Catel.MVVM/Catel.MVVM.Shared/MVVM/Locators/ViewLocator.cs
10,388
C#
using System.Collections.Generic; using System.Linq; using GingerbreadAI.NLP.Word2Vec.AnalysisFunctions; using GingerbreadAI.NLP.Word2Vec.Embeddings; using Xunit; namespace GingerbreadAI.NLP.Word2Vec.Test.AnalysisFunctions; public class KMeansShould { [Theory] [MemberData(nameof(GetPutXElementsInXClustersData))] public void PutXElementsInXClusters(int x) { var embeddings = new List<WordEmbedding>(); for (var i = 0; i < x; i++) { var embedding = new double[x]; embedding[i] = 1d; embeddings.Add(new WordEmbedding(i.ToString(), embedding)); } var kMeans = new KMeans(embeddings); kMeans.CalculateLabelClusterMap(numberOfClusters: x); Assert.Equal(x, kMeans.LabelClusterMap.Keys.Distinct().Count()); } [Theory] [MemberData(nameof(GetCorrectlyAssignClustersData))] public void CorrectlyAssignClusters(List<IEmbedding> embeddings, int numberOfClusters, List<List<string>> desiredClusters) { var kMeans = new KMeans(embeddings); kMeans.CalculateLabelClusterMap(numberOfClusters: numberOfClusters); var clusters = kMeans.LabelClusterMap.GroupBy(lcm => lcm.Value); foreach (var cluster in clusters) { var elements = cluster.ToArray(); var desiredCluster = desiredClusters.First(dc => dc.Contains(elements[0].Key)); // assert desired and actual cluster contain the same elements Assert.Equal(desiredCluster.Count, elements.Length); foreach (var element in elements) { Assert.Contains(desiredCluster, x => x == element.Key); } } } public static IEnumerable<object[]> GetPutXElementsInXClustersData() { yield return new object[] { 1 }; yield return new object[] { 2 }; yield return new object[] { 5 }; yield return new object[] { 10 }; } public static IEnumerable<object[]> GetCorrectlyAssignClustersData() { yield return new object[] { new List<IEmbedding> { new WordEmbedding("a", new [] {1d, 1d, 1d} ), new WordEmbedding("b", new [] {2d, 2d, 2d} ), new WordEmbedding("c", new [] {3d, 3d, 3d} ) }, 3, new List<List<string>> { new List<string> { "a" }, new List<string> { "b" }, new List<string> { "c" } } }; yield return new object[] { new List<IEmbedding> { new WordEmbedding("a", new [] {1d, 1d, 1d} ), new WordEmbedding("b", new [] {2d, 2d, 2d} ), new WordEmbedding("c", new [] {3d, 3d, 3d} ) }, 1, new List<List<string>> { new List<string> { "a", "b", "c" } } }; yield return new object[] { new List<IEmbedding> { new WordEmbedding("a", new [] {-1d, -1d, -1d} ), new WordEmbedding("b", new [] {2d, 2d, 2d} ), new WordEmbedding("c", new [] {3d, 3d, 3d} ) }, 2, new List<List<string>> { new List<string> { "a" }, new List<string> { "b", "c" } } }; } }
34.427083
126
0.54947
[ "MIT" ]
benchiverton/GingerbreadAI
src/NLP/GingerbreadAI.NLP.Word2Vec.Test/AnalysisFunctions/KMeansShould.cs
3,305
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. using Mosa.Compiler.Framework; using Mosa.Compiler.MosaTypeSystem; using System; using System.Collections.Generic; using System.Text; namespace Mosa.Compiler.Trace { /// <summary> /// Logs all instructions. /// </summary> public static class InstructionLogger { public static void Run(BaseMethodCompiler methodCompiler, IPipelineStage stage) { Run( methodCompiler.Trace, methodCompiler.FormatStageName(stage), methodCompiler.Method, methodCompiler.BasicBlocks ); } public static void Run(CompilerTrace compilerTrace, string stage, MosaMethod method, BasicBlocks basicBlocks) { if (compilerTrace == null) return; if (!compilerTrace.TraceFilter.IsMatch(method, stage)) return; var traceLog = new TraceLog(TraceType.InstructionList, method, stage, true); traceLog.Log(String.Format("IR representation of method {0} after stage {1}:", method.FullName, stage)); traceLog.Log(); if (basicBlocks.Count > 0) { foreach (var block in basicBlocks) { traceLog.Log(String.Format("Block #{0} - Label L_{1:X4}", block.Sequence, block.Label) + (basicBlocks.IsHeaderBlock(block) ? " [Header]" : string.Empty)); traceLog.Log(" Prev: " + ListBlocks(block.PreviousBlocks)); LogInstructions(traceLog, block.First); traceLog.Log(" Next: " + ListBlocks(block.NextBlocks)); traceLog.Log(); } } else { traceLog.Log("No instructions."); } compilerTrace.NewTraceLog(traceLog); } private static string ListBlocks(IList<BasicBlock> blocks) { var text = new StringBuilder(); foreach (var next in blocks) { if (text.Length != 0) text.Append(", "); text.AppendFormat(next.ToString()); } return text.ToString(); } /// <summary> /// Logs the instructions in the given enumerable to the trace. /// </summary> /// <param name="traceLog">The trace log.</param> /// <param name="node">The context.</param> private static void LogInstructions(TraceLog traceLog, InstructionNode node) { for (; !node.IsBlockEndInstruction; node = node.Next) { if (node.IsEmpty) continue; traceLog.Log(node.ToString()); if (node.IsBlockEndInstruction) return; } } } }
23.571429
111
0.675758
[ "BSD-3-Clause" ]
Kintaro/MOSA-Project
Source/Mosa.Compiler.Framework/InstructionLogger.cs
2,310
C#
//------------------------------------------------------------------------------ // <auto-generated> // Этот код создан программой. // Исполняемая версия:4.0.30319.42000 // // Изменения в этом файле могут привести к неправильной работе и будут потеряны в случае // повторной генерации кода. // </auto-generated> //------------------------------------------------------------------------------ namespace AKITE.Contingent.Client.Properties { using System; /// <summary> /// Класс ресурса со строгой типизацией для поиска локализованных строк и т.д. /// </summary> // Этот класс создан автоматически классом StronglyTypedResourceBuilder // с помощью такого средства, как ResGen или Visual Studio. // Чтобы добавить или удалить член, измените файл .ResX и снова запустите ResGen // с параметром /str или перестройте свой проект VS. [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> /// Возвращает кэшированный экземпляр ResourceManager, использованный этим классом. /// </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("AKITE.Contingent.Client.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Перезаписывает свойство CurrentUICulture текущего потока для всех /// обращений к ресурсу с помощью этого класса ресурса со строгой типизацией. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
45.046875
189
0.627818
[ "BSD-3-Clause" ]
TrueMemer/AKITE.Contingent
Client/Properties/Resources.Designer.cs
3,394
C#
using System; namespace ToDo_List.Utils { public class MenuUtils { public static void MenuDeslogado() { Console.WriteLine("--------------------------------------------"); Console.WriteLine("---------- TT Trello Terminal ------------"); Console.WriteLine("------------- Conta ---------------"); Console.WriteLine("--------------------------------------------"); Console.WriteLine(" (1) Cadastrar Usuário "); Console.WriteLine(" (2) Efetuar Login "); Console.WriteLine(" (3) Listar Usuários "); Console.WriteLine("--------------------------------------------"); Console.WriteLine(" (0) Sair "); Console.WriteLine("--------------------------------------------"); Console.WriteLine(" Escolha uma opção "); } public static void MenuLogado() { Console.WriteLine("--------------------------------------------"); Console.WriteLine($"---------- Bem Vindo de Volta ------------"); Console.WriteLine("------------- Conta ---------------"); Console.WriteLine("--------------------------------------------"); Console.WriteLine(" (1) Cadastrar Tarefas "); Console.WriteLine(" (2) Excluir Tarefas "); Console.WriteLine(" (3) Listar Tarefas "); Console.WriteLine(" (4) Mover Tarefas "); Console.WriteLine("--------------------------------------------"); Console.WriteLine(" (0) Sair da Conta "); Console.WriteLine("--------------------------------------------"); Console.WriteLine(" Escolha uma opção "); } } }
53.263158
78
0.330534
[ "MIT" ]
Gcarvalhu/ProgramacaoOrientadaAoObjeto
ToDo_List/Utils/MenuUtils.cs
2,030
C#
namespace OnlineStore.Models.Enums { public enum SortingOptions { Alphabetical_Ascending, Alphabetical_Descending, Price_LowToHigh, Price_HighToLow } }
19.5
34
0.666667
[ "MIT" ]
JV-Amorim/OnlineStore-ASP.NET-Core
Models/Enums/SortingOptions.cs
195
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Net.Http.Headers; namespace JHCW.Areas.HelpPage { /// <summary> /// This is used to identify the place where the sample should be applied. /// </summary> public class HelpPageSampleKey { /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type. /// </summary> /// <param name="mediaType">The media type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } ActionName = String.Empty; ControllerName = String.Empty; MediaType = mediaType; ParameterNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type and CLR type. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="type">The CLR type.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, Type type) : this(mediaType) { if (type == null) { throw new ArgumentNullException("type"); } ParameterType = type; } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (controllerName == null) { throw new ArgumentNullException("controllerName"); } if (actionName == null) { throw new ArgumentNullException("actionName"); } if (parameterNames == null) { throw new ArgumentNullException("parameterNames"); } ControllerName = controllerName; ActionName = actionName; ParameterNames = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); SampleDirection = sampleDirection; } /// <summary> /// Creates a new <see cref="HelpPageSampleKey"/> based on media type, <see cref="SampleDirection"/>, controller name, action name and parameter names. /// </summary> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The <see cref="SampleDirection"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public HelpPageSampleKey(MediaTypeHeaderValue mediaType, SampleDirection sampleDirection, string controllerName, string actionName, IEnumerable<string> parameterNames) : this(sampleDirection, controllerName, actionName, parameterNames) { if (mediaType == null) { throw new ArgumentNullException("mediaType"); } MediaType = mediaType; } /// <summary> /// Gets the name of the controller. /// </summary> /// <value> /// The name of the controller. /// </value> public string ControllerName { get; private set; } /// <summary> /// Gets the name of the action. /// </summary> /// <value> /// The name of the action. /// </value> public string ActionName { get; private set; } /// <summary> /// Gets the media type. /// </summary> /// <value> /// The media type. /// </value> public MediaTypeHeaderValue MediaType { get; private set; } /// <summary> /// Gets the parameter names. /// </summary> public HashSet<string> ParameterNames { get; private set; } public Type ParameterType { get; private set; } /// <summary> /// Gets the <see cref="SampleDirection"/>. /// </summary> public SampleDirection? SampleDirection { get; private set; } public override bool Equals(object obj) { HelpPageSampleKey otherKey = obj as HelpPageSampleKey; if (otherKey == null) { return false; } return String.Equals(ControllerName, otherKey.ControllerName, StringComparison.OrdinalIgnoreCase) && String.Equals(ActionName, otherKey.ActionName, StringComparison.OrdinalIgnoreCase) && (MediaType == otherKey.MediaType || (MediaType != null && MediaType.Equals(otherKey.MediaType))) && ParameterType == otherKey.ParameterType && SampleDirection == otherKey.SampleDirection && ParameterNames.SetEquals(otherKey.ParameterNames); } public override int GetHashCode() { int hashCode = ControllerName.ToUpperInvariant().GetHashCode() ^ ActionName.ToUpperInvariant().GetHashCode(); if (MediaType != null) { hashCode ^= MediaType.GetHashCode(); } if (SampleDirection != null) { hashCode ^= SampleDirection.GetHashCode(); } if (ParameterType != null) { hashCode ^= ParameterType.GetHashCode(); } foreach (string parameterName in ParameterNames) { hashCode ^= parameterName.ToUpperInvariant().GetHashCode(); } return hashCode; } } }
38.381503
176
0.554518
[ "MIT" ]
booko365dev/BookExamples
JHCW/Areas/HelpPage/SampleGeneration/HelpPageSampleKey.cs
6,640
C#
using System; namespace BeatServerBrowser.Core.Interfaces { public interface ILoadingService { bool IsLoading { get; set; } void Load(Action action); } }
16.727273
43
0.652174
[ "MIT" ]
denpadokei/BeatServerBrowser
BeatServerBrowser.Core/Interfaces/ILoadingService.cs
186
C#