content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
namespace Socializer.Web.ViewModels.Chat { using System; using Socializer.Data.Models; using Socializer.Services.Mapping; using Socializer.Web.ViewModels.Users; public class ChatMessageViewModel : IMapFrom<ChatMessage> { public string Content { get; set; } public ShortUserViewModel Sender { get; set; } public DateTime CreatedOn { get; set; } } }
22.5
61
0.679012
[ "MIT" ]
Dreed657/Socializer
Web/Socializer.Web.ViewModels/Chat/ChatMessageViewModel.cs
407
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Microsoft.AspNetCore.Components.WebAssembly.Hosting; /// <summary> /// Static class that adds extension methods to <see cref="IWebAssemblyHostEnvironment"/>. /// </summary> public static class WebAssemblyHostEnvironmentExtensions { /// <summary> /// Checks if the current hosting environment name is <c>Development</c>. /// </summary> /// <param name="hostingEnvironment">An instance of <see cref="IWebAssemblyHostEnvironment"/>.</param> /// <returns>True if the environment name is <c>Development</c>, otherwise false.</returns> public static bool IsDevelopment(this IWebAssemblyHostEnvironment hostingEnvironment) { if (hostingEnvironment == null) { throw new ArgumentNullException(nameof(hostingEnvironment)); } return hostingEnvironment.IsEnvironment("Development"); } /// <summary> /// Checks if the current hosting environment name is <c>Staging</c>. /// </summary> /// <param name="hostingEnvironment">An instance of <see cref="IWebAssemblyHostEnvironment"/>.</param> /// <returns>True if the environment name is <c>Staging</c>, otherwise false.</returns> public static bool IsStaging(this IWebAssemblyHostEnvironment hostingEnvironment) { if (hostingEnvironment == null) { throw new ArgumentNullException(nameof(hostingEnvironment)); } return hostingEnvironment.IsEnvironment("Staging"); } /// <summary> /// Checks if the current hosting environment name is <c>Production</c>. /// </summary> /// <param name="hostingEnvironment">An instance of <see cref="IWebAssemblyHostEnvironment"/>.</param> /// <returns>True if the environment name is <c>Production</c>, otherwise false.</returns> public static bool IsProduction(this IWebAssemblyHostEnvironment hostingEnvironment) { if (hostingEnvironment == null) { throw new ArgumentNullException(nameof(hostingEnvironment)); } return hostingEnvironment.IsEnvironment("Production"); } /// <summary> /// Compares the current hosting environment name against the specified value. /// </summary> /// <param name="hostingEnvironment">An instance of <see cref="IWebAssemblyHostEnvironment"/>.</param> /// <param name="environmentName">Environment name to validate against.</param> /// <returns>True if the specified name is the same as the current environment, otherwise false.</returns> public static bool IsEnvironment( this IWebAssemblyHostEnvironment hostingEnvironment, string environmentName) { if (hostingEnvironment == null) { throw new ArgumentNullException(nameof(hostingEnvironment)); } return string.Equals( hostingEnvironment.Environment, environmentName, StringComparison.OrdinalIgnoreCase); } }
39.883117
110
0.683816
[ "MIT" ]
3ejki/aspnetcore
src/Components/WebAssembly/WebAssembly/src/Hosting/WebAssemblyHostEnvironmentExtensions.cs
3,071
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; namespace System.Text.Json.Serialization.Converters { /// <summary> /// Default base class implementation of <cref>JsonObjectConverter{T}</cref>. /// </summary> internal sealed class JsonObjectDefaultConverter<T> : JsonObjectConverter<T> { internal override bool OnTryRead(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options, ref ReadStack state, out T value) { bool shouldReadPreservedReferences = options.ReferenceHandling.ShouldReadPreservedReferences(); object obj; if (!state.SupportContinuation && !shouldReadPreservedReferences) { // Fast path that avoids maintaining state variables and dealing with preserved references. if (reader.TokenType != JsonTokenType.StartObject) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } if (state.Current.JsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_DeserializeNoParameterlessConstructor(state.Current.JsonClassInfo.Type); } obj = state.Current.JsonClassInfo.CreateObject!()!; // Process all properties. while (true) { // Read the property name or EndObject. reader.ReadWithVerify(); JsonTokenType tokenType = reader.TokenType; if (tokenType == JsonTokenType.EndObject) { break; } if (tokenType != JsonTokenType.PropertyName) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } JsonPropertyInfo jsonPropertyInfo = JsonSerializer.LookupProperty( obj, ref reader, options, ref state, out bool useExtensionProperty); // Skip the property if not found. if (!jsonPropertyInfo.ShouldDeserialize) { reader.Skip(); state.Current.EndProperty(); continue; } // Set the property value. reader.ReadWithVerify(); if (!useExtensionProperty) { jsonPropertyInfo.ReadJsonAndSetMember(obj, ref state, ref reader); } else { jsonPropertyInfo.ReadJsonAndAddExtensionProperty(obj, ref state, ref reader); } // Ensure any exception thrown in the next read does not have a property in its JsonPath. state.Current.EndProperty(); } } else { // Slower path that supports continuation and preserved references. if (state.Current.ObjectState == StackFrameObjectState.None) { if (reader.TokenType != JsonTokenType.StartObject) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } state.Current.ObjectState = StackFrameObjectState.StartToken; } // Handle the metadata properties. if (state.Current.ObjectState < StackFrameObjectState.MetadataPropertyValue) { if (shouldReadPreservedReferences) { if (JsonSerializer.ResolveMetadata(this, ref reader, ref state)) { if (state.Current.ObjectState == StackFrameObjectState.MetadataRefPropertyEndObject) { value = (T)state.Current.ReturnValue!; return true; } } else { value = default!; return false; } } state.Current.ObjectState = StackFrameObjectState.MetadataPropertyValue; } if (state.Current.ObjectState < StackFrameObjectState.CreatedObject) { if (state.Current.JsonClassInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_DeserializeNoParameterlessConstructor(state.Current.JsonClassInfo.Type); } obj = state.Current.JsonClassInfo.CreateObject!()!; if (state.Current.MetadataId != null) { if (!state.ReferenceResolver.AddReferenceOnDeserialize(state.Current.MetadataId, obj)) { ThrowHelper.ThrowJsonException_MetadataDuplicateIdFound(state.Current.MetadataId, ref state); } } state.Current.ReturnValue = obj; state.Current.ObjectState = StackFrameObjectState.CreatedObject; } else { obj = state.Current.ReturnValue!; Debug.Assert(obj != null); } // Process all properties. while (true) { // Determine the property. if (state.Current.PropertyState == StackFramePropertyState.None) { state.Current.PropertyState = StackFramePropertyState.ReadName; if (!reader.Read()) { // The read-ahead functionality will do the Read(). state.Current.ReturnValue = obj; value = default!; return false; } } JsonPropertyInfo jsonPropertyInfo; if (state.Current.PropertyState < StackFramePropertyState.Name) { state.Current.PropertyState = StackFramePropertyState.Name; JsonTokenType tokenType = reader.TokenType; if (tokenType == JsonTokenType.EndObject) { // We are done reading properties. break; } else if (tokenType != JsonTokenType.PropertyName) { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(TypeToConvert); } jsonPropertyInfo = JsonSerializer.LookupProperty( obj, ref reader, options, ref state, out bool useExtensionProperty); state.Current.UseExtensionProperty = useExtensionProperty; } else { Debug.Assert(state.Current.JsonPropertyInfo != null); jsonPropertyInfo = state.Current.JsonPropertyInfo!; } if (state.Current.PropertyState < StackFramePropertyState.ReadValue) { if (!jsonPropertyInfo.ShouldDeserialize) { if (!reader.TrySkip()) { state.Current.ReturnValue = obj; value = default!; return false; } state.Current.EndProperty(); continue; } // Returning false below will cause the read-ahead functionality to finish the read. state.Current.PropertyState = StackFramePropertyState.ReadValue; if (!state.Current.UseExtensionProperty) { if (!SingleValueReadWithReadAhead(jsonPropertyInfo.ConverterBase.ClassType, ref reader, ref state)) { state.Current.ReturnValue = obj; value = default!; return false; } } else { // The actual converter is JsonElement, so force a read-ahead. if (!SingleValueReadWithReadAhead(ClassType.Value, ref reader, ref state)) { state.Current.ReturnValue = obj; value = default!; return false; } } } if (state.Current.PropertyState < StackFramePropertyState.TryRead) { // Obtain the CLR value from the JSON and set the member. if (!state.Current.UseExtensionProperty) { if (!jsonPropertyInfo.ReadJsonAndSetMember(obj, ref state, ref reader)) { state.Current.ReturnValue = obj; value = default!; return false; } } else { if (!jsonPropertyInfo.ReadJsonAndAddExtensionProperty(obj, ref state, ref reader)) { // No need to set 'value' here since JsonElement must be read in full. state.Current.ReturnValue = obj; value = default!; return false; } } state.Current.EndProperty(); } } } // Check if we are trying to build the sorted cache. if (state.Current.PropertyRefCache != null) { state.Current.JsonClassInfo.UpdateSortedPropertyCache(ref state.Current); } value = (T)obj; return true; } internal override bool OnTryWrite(Utf8JsonWriter writer, T value, JsonSerializerOptions options, ref WriteStack state) { // Minimize boxing for structs by only boxing once here object? objectValue = value; if (!state.SupportContinuation) { if (objectValue == null) { writer.WriteNullValue(); return true; } writer.WriteStartObject(); if (options.ReferenceHandling.ShouldWritePreservedReferences()) { if (JsonSerializer.WriteReferenceForObject(this, objectValue, ref state, writer) == MetadataPropertyName.Ref) { return true; } } JsonPropertyInfo? dataExtensionProperty = state.Current.JsonClassInfo.DataExtensionProperty; int propertyCount = 0; JsonPropertyInfo[]? propertyCacheArray = state.Current.JsonClassInfo.PropertyCacheArray; if (propertyCacheArray != null) { propertyCount = propertyCacheArray.Length; } for (int i = 0; i < propertyCount; i++) { JsonPropertyInfo jsonPropertyInfo = propertyCacheArray![i]; // Remember the current property for JsonPath support if an exception is thrown. state.Current.DeclaredJsonPropertyInfo = jsonPropertyInfo; if (jsonPropertyInfo.ShouldSerialize) { if (jsonPropertyInfo == dataExtensionProperty) { if (!jsonPropertyInfo.GetMemberAndWriteJsonExtensionData(objectValue, ref state, writer)) { return false; } } else { if (!jsonPropertyInfo.GetMemberAndWriteJson(objectValue, ref state, writer)) { Debug.Assert(jsonPropertyInfo.ConverterBase.ClassType != ClassType.Value); return false; } } } state.Current.EndProperty(); } writer.WriteEndObject(); return true; } else { if (!state.Current.ProcessedStartToken) { if (objectValue == null) { writer.WriteNullValue(); return true; } writer.WriteStartObject(); if (options.ReferenceHandling.ShouldWritePreservedReferences()) { if (JsonSerializer.WriteReferenceForObject(this, objectValue, ref state, writer) == MetadataPropertyName.Ref) { return true; } } state.Current.ProcessedStartToken = true; } JsonPropertyInfo? dataExtensionProperty = state.Current.JsonClassInfo.DataExtensionProperty; int propertyCount = 0; JsonPropertyInfo[]? propertyCacheArray = state.Current.JsonClassInfo.PropertyCacheArray; if (propertyCacheArray != null) { propertyCount = propertyCacheArray.Length; } while (propertyCount > state.Current.EnumeratorIndex) { JsonPropertyInfo jsonPropertyInfo = propertyCacheArray![state.Current.EnumeratorIndex]; state.Current.DeclaredJsonPropertyInfo = jsonPropertyInfo; if (jsonPropertyInfo.ShouldSerialize) { if (jsonPropertyInfo == dataExtensionProperty) { if (!jsonPropertyInfo.GetMemberAndWriteJsonExtensionData(objectValue!, ref state, writer)) { return false; } } else { if (!jsonPropertyInfo.GetMemberAndWriteJson(objectValue!, ref state, writer)) { Debug.Assert(jsonPropertyInfo.ConverterBase.ClassType != ClassType.Value); return false; } } } state.Current.EndProperty(); state.Current.EnumeratorIndex++; if (ShouldFlush(writer, ref state)) { return false; } } if (!state.Current.ProcessedEndToken) { state.Current.ProcessedEndToken = true; writer.WriteEndObject(); } return true; } } } }
40.614078
152
0.447499
[ "MIT" ]
hassoon1986/runtime
src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/JsonObjectDefaultConverter.cs
16,735
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本:4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将会丢失。 // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("aspnetcoredocker")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("aspnetcoredocker")] [assembly: System.Reflection.AssemblyTitleAttribute("aspnetcoredocker")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // 由 MSBuild WriteCodeFragment 类生成。
37.166667
80
0.636771
[ "MIT" ]
MonkSoul/jenkins_asp_net_core_docker
src/aspnetcoredocker/obj/Debug/netcoreapp2.2/aspnetcoredocker.AssemblyInfo.cs
1,008
C#
using Microsoft.Xna.Framework; using ColorHelper = Microsoft.Xna.Framework.Color; using System.Runtime.Serialization; namespace SadConsole.Themes { /// <summary> /// The library of themes. Holds the themes of all controls. /// </summary> [DataContract] public class Library { /// <summary> /// If a control does not specify its own theme, the theme from this property will be used. /// </summary> public static Library Default { get; set; } /// <summary> /// Theme for the <see cref="SadConsole.Controls.Button"/> control. /// </summary> [DataMember] public ButtonTheme ButtonTheme; /// <summary> /// Theme for the <see cref="SadConsole.Controls.SelectionButton"/> control. /// </summary> [DataMember] public ButtonTheme SelectionButtonTheme; /// <summary> /// Theme for the <see cref="SadConsole.Consoles.Window"/> control. /// </summary> [DataMember] public WindowTheme WindowTheme; /// <summary> /// Theme for the <see cref="SadConsole.Controls.ScrollBar"/> control. /// </summary> [DataMember] public ScrollBarTheme ScrollBarTheme; /// <summary> /// Theme for the <see cref="SadConsole.Controls.RadioButton"/> control. /// </summary> [DataMember] public RadioButtonTheme RadioButtonTheme; /// <summary> /// Theme for the <see cref="SadConsole.Controls.ListBox"/> control. /// </summary> [DataMember] public ListBoxTheme ListBoxTheme; /// <summary> /// Theme for the <see cref="SadConsole.Controls.CheckBox"/> control. /// </summary> [DataMember] public CheckBoxTheme CheckBoxTheme; /// <summary> /// Theme for the <see cref="SadConsole.Controls.InputBox"/> control. /// </summary> [DataMember] public InputBoxTheme InputBoxTheme; /// <summary> /// Theme for <see cref="Consoles.ControlsConsole"/>. /// </summary> [DataMember] public ControlsConsoleTheme ControlsConsoleTheme; static Library() { if (Default == null) Default = new Library(); } /// <summary> /// Creates a new instance of the theme library with default themes. /// </summary> public Library() { ButtonTheme = new ButtonTheme(); ButtonTheme.Normal = new Cell(ColorAnsi.WhiteBright, ColorAnsi.White); ButtonTheme.Focused = new Cell(ColorAnsi.Blue, ColorAnsi.White); ButtonTheme.MouseOver = new Cell(ColorAnsi.White, ColorAnsi.WhiteBright); ButtonTheme.MouseClicking = new Cell(ColorAnsi.WhiteBright, ColorAnsi.White); ButtonTheme.Disabled = new Cell(ColorAnsi.WhiteBright, ColorAnsi.White); SelectionButtonTheme = (ButtonTheme)ButtonTheme.Clone(); ScrollBarTheme = new ScrollBarTheme(); ScrollBarTheme.Bar = new ThemePartBase(); ScrollBarTheme.Bar.Normal = new Cell(ColorHelper.LightGray, ColorHelper.Black); ScrollBarTheme.Bar.Focused = new Cell(ColorHelper.LightGray, ColorHelper.Black); ScrollBarTheme.Bar.Disabled = new Cell(ColorHelper.Gray, ColorHelper.Black); ScrollBarTheme.Bar.MouseOver = new Cell(ColorHelper.LightGray, ColorHelper.Black); ScrollBarTheme.Ends = new ThemePartBase(); ScrollBarTheme.Ends.Normal = new Cell(ColorHelper.White, ColorHelper.Black); ScrollBarTheme.Ends.Focused = new Cell(ColorHelper.LightGray, ColorHelper.Black); ScrollBarTheme.Ends.Disabled = new Cell(ColorHelper.Gray, ColorHelper.Black); ScrollBarTheme.Ends.MouseOver = new Cell(ColorHelper.White, ColorHelper.Black); ScrollBarTheme.Slider = new ThemePartBase(); ScrollBarTheme.Slider.Normal = new Cell(ColorHelper.White, ColorHelper.Black); ScrollBarTheme.Slider.Focused = new Cell(ColorHelper.LightGray, ColorHelper.Black); ScrollBarTheme.Slider.Disabled = new Cell(ColorHelper.Gray, ColorHelper.Black); ScrollBarTheme.Slider.MouseOver = new Cell(ColorHelper.White, ColorHelper.Black); WindowTheme = new WindowTheme(); WindowTheme.TitleStyle = new Cell(ColorAnsi.Black, ColorAnsi.WhiteBright); WindowTheme.BorderStyle = new Cell(ColorAnsi.WhiteBright, ColorAnsi.Black); WindowTheme.FillStyle = new Cell(ColorAnsi.WhiteBright, ColorAnsi.Black); ControlsConsoleTheme = new ControlsConsoleTheme(); ControlsConsoleTheme.FillStyle = new Cell(ColorAnsi.WhiteBright, ColorAnsi.Black); CheckBoxTheme = new CheckBoxTheme(); CheckBoxTheme.CheckedIcon = 251; CheckBoxTheme.UncheckedIcon = 0; CheckBoxTheme.Button = new ThemePartSelected(); CheckBoxTheme.Button.Normal = new Cell(ColorAnsi.WhiteBright, ColorHelper.Transparent); CheckBoxTheme.Button.Focused = new Cell(ColorAnsi.Blue, ColorHelper.Transparent); CheckBoxTheme.Button.MouseOver = new Cell(ColorAnsi.White, ColorAnsi.WhiteBright); CheckBoxTheme.Button.MouseClicking = new Cell(ColorAnsi.WhiteBright, ColorHelper.Transparent); CheckBoxTheme.Button.Disabled = new Cell(ColorAnsi.Black, ColorHelper.Transparent); CheckBoxTheme.Button.Selected = new Cell(ColorAnsi.YellowBright, ColorHelper.Transparent); CheckBoxTheme.Normal = new Cell(ColorAnsi.WhiteBright, ColorHelper.Transparent); CheckBoxTheme.Focused = new Cell(ColorAnsi.Blue, ColorHelper.Transparent); CheckBoxTheme.MouseOver = new Cell(ColorAnsi.White, ColorAnsi.WhiteBright); CheckBoxTheme.MouseClicking = new Cell(ColorAnsi.WhiteBright, ColorHelper.Transparent); CheckBoxTheme.Disabled = new Cell(ColorAnsi.Black, ColorHelper.Transparent); CheckBoxTheme.Selected = new Cell(ColorAnsi.YellowBright, ColorHelper.Transparent); RadioButtonTheme = new RadioButtonTheme(); RadioButtonTheme.CheckedIcon = 7; RadioButtonTheme.UncheckedIcon = 0; RadioButtonTheme.Button = new ThemePartSelected(); RadioButtonTheme.Button.Normal = new Cell(ColorAnsi.WhiteBright, ColorHelper.Transparent); RadioButtonTheme.Button.Focused = new Cell(ColorAnsi.Blue, ColorHelper.Transparent); RadioButtonTheme.Button.MouseOver = new Cell(ColorAnsi.White, ColorAnsi.WhiteBright); RadioButtonTheme.Button.MouseClicking = new Cell(ColorAnsi.WhiteBright, ColorHelper.Transparent); RadioButtonTheme.Button.Disabled = new Cell(ColorAnsi.Black, ColorHelper.Transparent); RadioButtonTheme.Button.Selected = new Cell(ColorAnsi.YellowBright, ColorHelper.Transparent); RadioButtonTheme.Normal = new Cell(ColorAnsi.WhiteBright, ColorHelper.Transparent); RadioButtonTheme.Focused = new Cell(ColorAnsi.Blue, ColorHelper.Transparent); RadioButtonTheme.MouseOver = new Cell(ColorAnsi.White, ColorAnsi.WhiteBright); RadioButtonTheme.MouseClicking = new Cell(ColorAnsi.WhiteBright, ColorHelper.Transparent); RadioButtonTheme.Disabled = new Cell(ColorAnsi.Black, ColorHelper.Transparent); RadioButtonTheme.Selected = new Cell(ColorAnsi.YellowBright, ColorHelper.Transparent); ListBoxTheme = new ListBoxTheme(); ListBoxTheme.Border = new Cell(ColorHelper.LightGray, ColorHelper.Black); ListBoxTheme.Item = new ThemePartSelected(); ListBoxTheme.Item.Normal = new Cell(ColorHelper.White, ColorHelper.Transparent); ListBoxTheme.Item.Focused = new Cell(ColorHelper.White, ColorHelper.Transparent); ListBoxTheme.Item.MouseClicking = new Cell(ColorHelper.White, ColorHelper.Transparent); ListBoxTheme.Item.Disabled = new Cell(ColorHelper.White, ColorHelper.Transparent); ListBoxTheme.Item.MouseOver = new Cell(ColorHelper.LightGray, ColorHelper.Gray); ListBoxTheme.Item.Selected = new Cell(ColorHelper.Yellow, ColorHelper.Gray); ListBoxTheme.ScrollBarTheme = (ScrollBarTheme)ScrollBarTheme.Clone(); ListBoxTheme.Normal = new Cell(ColorAnsi.WhiteBright, ColorHelper.Transparent); ListBoxTheme.Focused = new Cell(ColorAnsi.Blue, ColorHelper.Transparent); ListBoxTheme.MouseOver = new Cell(ColorAnsi.White, ColorAnsi.WhiteBright); ListBoxTheme.Disabled = new Cell(ColorAnsi.Black, ColorHelper.Transparent); InputBoxTheme = new InputBoxTheme(); InputBoxTheme.Normal = new Cell(ColorHelper.Blue, ColorHelper.DimGray); InputBoxTheme.Focused = new Cell(ColorHelper.DarkBlue, ColorHelper.DarkGray); InputBoxTheme.MouseOver = new Cell(ColorHelper.DarkBlue, ColorHelper.DarkGray); InputBoxTheme.Disabled = new Cell(ColorHelper.Black, ColorAnsi.White); InputBoxTheme.CarrotEffect = new Effects.BlinkGlyph() { GlyphIndex = 95, BlinkSpeed = 0.4f }; } } }
51.535912
109
0.666166
[ "MIT" ]
HooniusDev/SadConsole
src/SadConsole.Shared/Themes/Library.cs
9,330
C#
// Copyright (c) Lex Li. All rights reserved. // // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Web.Management.Server { public enum ConfigurationPathType { Server = 0, Site = 1, Application = 2, Folder = 3, File = 4 } }
23.266667
101
0.621777
[ "MIT" ]
68681395/JexusManager
Microsoft.Web.Management/Server/ConfigurationPathType.cs
351
C#
using UnityEngine; using SanAndreasUnity.Importing.Animation; namespace SanAndreasUnity.Behaviours.Weapons { public class Spas12 : Weapon { public override AnimId AimAnim { get { return new AnimId (AnimGroup.Buddy, AnimIndex.buddy_fire); } } } }
13.5
62
0.725926
[ "MIT" ]
Almahmudrony/SanAndreasUnity
Assets/Scripts/Behaviours/Weapons/Spas12.cs
272
C#
// <auto-generated /> using System; using DA.ProjectManagement.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace DA.ProjectManagement.Migrations { [DbContext(typeof(ProjectManagementDbContext))] [Migration("20200806103525_Add_Student_Table_Teacher_Table")] partial class Add_Student_Table_Teacher_Table { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.5") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Abp.Application.Editions.Edition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.HasKey("Id"); b.ToTable("AbpEditions"); }); modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.HasKey("Id"); b.ToTable("AbpFeatures"); b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting"); }); modelBuilder.Entity("Abp.Auditing.AuditLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("CustomData") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<string>("Exception") .HasColumnType("nvarchar(2000)") .HasMaxLength(2000); b.Property<int>("ExecutionDuration") .HasColumnType("int"); b.Property<DateTime>("ExecutionTime") .HasColumnType("datetime2"); b.Property<int?>("ImpersonatorTenantId") .HasColumnType("int"); b.Property<long?>("ImpersonatorUserId") .HasColumnType("bigint"); b.Property<string>("MethodName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("Parameters") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<string>("ReturnValue") .HasColumnType("nvarchar(max)"); b.Property<string>("ServiceName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionDuration"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Abp.Authorization.PermissionSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Discriminator") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<bool>("IsGranted") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpPermissions"); b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<long?>("UserLinkId") .HasColumnType("bigint"); b.Property<string>("UserName") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("EmailAddress"); b.HasIndex("UserName"); b.HasIndex("TenantId", "EmailAddress"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "UserName"); b.ToTable("AbpUserAccounts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("ClaimValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("LoginProvider") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<byte>("Result") .HasColumnType("tinyint"); b.Property<string>("TenancyName") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("UserNameOrEmailAddress") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("UserId", "TenantId"); b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result"); b.ToTable("AbpUserLoginAttempts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<long>("OrganizationUnitId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "RoleId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime?>("ExpireDate") .HasColumnType("datetime2"); b.Property<string>("LoginProvider") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Name") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<bool>("IsAbandoned") .HasColumnType("bit"); b.Property<string>("JobArgs") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("JobType") .IsRequired() .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<DateTime?>("LastTryTime") .HasColumnType("datetime2"); b.Property<DateTime>("NextTryTime") .HasColumnType("datetime2"); b.Property<byte>("Priority") .HasColumnType("tinyint"); b.Property<short>("TryCount") .HasColumnType("smallint"); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.Property<string>("Value") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "Name", "UserId") .IsUnique(); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Abp.DynamicEntityParameters.DynamicParameter", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("InputType") .HasColumnType("nvarchar(max)"); b.Property<string>("ParameterName") .HasColumnType("nvarchar(450)"); b.Property<string>("Permission") .HasColumnType("nvarchar(max)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ParameterName", "TenantId") .IsUnique() .HasFilter("[ParameterName] IS NOT NULL AND [TenantId] IS NOT NULL"); b.ToTable("AbpDynamicParameters"); }); modelBuilder.Entity("Abp.DynamicEntityParameters.DynamicParameterValue", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("DynamicParameterId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("DynamicParameterId"); b.ToTable("AbpDynamicParameterValues"); }); modelBuilder.Entity("Abp.DynamicEntityParameters.EntityDynamicParameter", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("DynamicParameterId") .HasColumnType("int"); b.Property<string>("EntityFullName") .HasColumnType("nvarchar(450)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("DynamicParameterId"); b.HasIndex("EntityFullName", "DynamicParameterId", "TenantId") .IsUnique() .HasFilter("[EntityFullName] IS NOT NULL AND [TenantId] IS NOT NULL"); b.ToTable("AbpEntityDynamicParameters"); }); modelBuilder.Entity("Abp.DynamicEntityParameters.EntityDynamicParameterValue", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("EntityDynamicParameterId") .HasColumnType("int"); b.Property<string>("EntityId") .HasColumnType("nvarchar(max)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("EntityDynamicParameterId"); b.ToTable("AbpEntityDynamicParameterValues"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("ChangeTime") .HasColumnType("datetime2"); b.Property<byte>("ChangeType") .HasColumnType("tinyint"); b.Property<long>("EntityChangeSetId") .HasColumnType("bigint"); b.Property<string>("EntityId") .HasColumnType("nvarchar(48)") .HasMaxLength(48); b.Property<string>("EntityTypeFullName") .HasColumnType("nvarchar(192)") .HasMaxLength(192); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("EntityChangeSetId"); b.HasIndex("EntityTypeFullName", "EntityId"); b.ToTable("AbpEntityChanges"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChangeSet", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ClientName") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("ExtensionData") .HasColumnType("nvarchar(max)"); b.Property<int?>("ImpersonatorTenantId") .HasColumnType("int"); b.Property<long?>("ImpersonatorUserId") .HasColumnType("bigint"); b.Property<string>("Reason") .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long?>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("TenantId", "CreationTime"); b.HasIndex("TenantId", "Reason"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpEntityChangeSets"); }); modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<long>("EntityChangeId") .HasColumnType("bigint"); b.Property<string>("NewValue") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("OriginalValue") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("PropertyName") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("PropertyTypeFullName") .HasColumnType("nvarchar(192)") .HasMaxLength(192); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("EntityChangeId"); b.ToTable("AbpEntityPropertyChanges"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("Icon") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsDisabled") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpLanguages"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Key") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("LanguageName") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Source") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("Value") .IsRequired() .HasColumnType("nvarchar(max)") .HasMaxLength(67108864); b.HasKey("Id"); b.HasIndex("TenantId", "Source", "LanguageName", "Key"); b.ToTable("AbpLanguageTexts"); }); modelBuilder.Entity("Abp.Notifications.NotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("ExcludedUserIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.Property<string>("NotificationName") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<string>("TenantIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.Property<string>("UserIds") .HasColumnType("nvarchar(max)") .HasMaxLength(131072); b.HasKey("Id"); b.ToTable("AbpNotifications"); }); modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("NotificationName") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId"); b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId"); b.ToTable("AbpNotificationSubscriptions"); }); modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Data") .HasColumnType("nvarchar(max)") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityId") .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasColumnType("nvarchar(512)") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasColumnType("nvarchar(250)") .HasMaxLength(250); b.Property<string>("NotificationName") .IsRequired() .HasColumnType("nvarchar(96)") .HasMaxLength(96); b.Property<byte>("Severity") .HasColumnType("tinyint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AbpTenantNotifications"); }); modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<int>("State") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<Guid>("TenantNotificationId") .HasColumnType("uniqueidentifier"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasKey("Id"); b.HasIndex("UserId", "State", "CreationTime"); b.ToTable("AbpUserNotifications"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Code") .IsRequired() .HasColumnType("nvarchar(95)") .HasMaxLength(95); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<long?>("ParentId") .HasColumnType("bigint"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ParentId"); b.HasIndex("TenantId", "Code"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnitRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<long>("OrganizationUnitId") .HasColumnType("bigint"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "RoleId"); b.ToTable("AbpOrganizationUnitRoles"); }); modelBuilder.Entity("Abp.Webhooks.WebhookEvent", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<string>("Data") .HasColumnType("nvarchar(max)"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("WebhookName") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("AbpWebhookEvents"); }); modelBuilder.Entity("Abp.Webhooks.WebhookSendAttempt", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<string>("Response") .HasColumnType("nvarchar(max)"); b.Property<int?>("ResponseStatusCode") .HasColumnType("int"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<Guid>("WebhookEventId") .HasColumnType("uniqueidentifier"); b.Property<Guid>("WebhookSubscriptionId") .HasColumnType("uniqueidentifier"); b.HasKey("Id"); b.HasIndex("WebhookEventId"); b.ToTable("AbpWebhookSendAttempts"); }); modelBuilder.Entity("Abp.Webhooks.WebhookSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Headers") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<string>("Secret") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("WebhookUri") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Webhooks") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("AbpWebhookSubscriptions"); }); modelBuilder.Entity("DA.ProjectManagement.Authorization.Roles.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Description") .HasColumnType("nvarchar(max)") .HasMaxLength(5000); b.Property<string>("DisplayName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<bool>("IsDefault") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsStatic") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("NormalizedName") .IsRequired() .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<int?>("TenantId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("DA.ProjectManagement.Authorization.Users.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnType("bigint") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("AccessFailedCount") .HasColumnType("int"); b.Property<string>("AuthenticationSource") .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("EmailAddress") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("EmailConfirmationCode") .HasColumnType("nvarchar(328)") .HasMaxLength(328); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsEmailConfirmed") .HasColumnType("bit"); b.Property<bool>("IsLockoutEnabled") .HasColumnType("bit"); b.Property<bool>("IsPhoneNumberConfirmed") .HasColumnType("bit"); b.Property<bool>("IsTwoFactorEnabled") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<DateTime?>("LockoutEndDateUtc") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<string>("NormalizedEmailAddress") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.Property<string>("Password") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("PasswordResetCode") .HasColumnType("nvarchar(328)") .HasMaxLength(328); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(32)") .HasMaxLength(32); b.Property<string>("SecurityStamp") .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("Surname") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.Property<int?>("TenantId") .HasColumnType("int"); b.Property<string>("UserName") .IsRequired() .HasColumnType("nvarchar(256)") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedEmailAddress"); b.HasIndex("TenantId", "NormalizedUserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("DA.ProjectManagement.MultiTenancy.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ConnectionString") .HasColumnType("nvarchar(1024)") .HasMaxLength(1024); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<int?>("EditionId") .HasColumnType("int"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .IsRequired() .HasColumnType("nvarchar(128)") .HasMaxLength(128); b.Property<string>("TenancyName") .IsRequired() .HasColumnType("nvarchar(64)") .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("EditionId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenancyName"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("DA.ProjectManagement.Students.Student", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Address") .HasColumnType("nvarchar(max)"); b.Property<DateTime?>("Birthday") .HasColumnType("datetime2"); b.Property<string>("Branch") .HasColumnType("nvarchar(max)"); b.Property<string>("CourseYear") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Email") .HasColumnType("nvarchar(max)"); b.Property<string>("Faculty") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<string>("StundentCode") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Students"); }); modelBuilder.Entity("DA.ProjectManagement.Teachers.Teacher", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Address") .HasColumnType("nvarchar(max)"); b.Property<DateTime?>("Birthday") .HasColumnType("datetime2"); b.Property<DateTime>("CreationTime") .HasColumnType("datetime2"); b.Property<long?>("CreatorUserId") .HasColumnType("bigint"); b.Property<string>("Degree") .HasColumnType("nvarchar(max)"); b.Property<long?>("DeleterUserId") .HasColumnType("bigint"); b.Property<DateTime?>("DeletionTime") .HasColumnType("datetime2"); b.Property<string>("Email") .HasColumnType("nvarchar(max)"); b.Property<string>("Faculty") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime?>("LastModificationTime") .HasColumnType("datetime2"); b.Property<long?>("LastModifierUserId") .HasColumnType("bigint"); b.Property<string>("Name") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasColumnType("nvarchar(max)"); b.Property<string>("Position") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Teachers"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("EditionId") .HasColumnType("int"); b.HasIndex("EditionId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("EditionFeatureSetting"); }); modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("TenantFeatureSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<int>("RoleId") .HasColumnType("int"); b.HasIndex("RoleId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("RolePermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<long>("UserId") .HasColumnType("bigint"); b.HasIndex("UserId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("UserPermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.HasOne("DA.ProjectManagement.Authorization.Roles.Role", null) .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.HasOne("DA.ProjectManagement.Authorization.Users.User", null) .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.HasOne("DA.ProjectManagement.Authorization.Users.User", null) .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.HasOne("DA.ProjectManagement.Authorization.Users.User", null) .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.HasOne("DA.ProjectManagement.Authorization.Users.User", null) .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.HasOne("DA.ProjectManagement.Authorization.Users.User", null) .WithMany("Settings") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.DynamicEntityParameters.DynamicParameterValue", b => { b.HasOne("Abp.DynamicEntityParameters.DynamicParameter", "DynamicParameter") .WithMany("DynamicParameterValues") .HasForeignKey("DynamicParameterId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.DynamicEntityParameters.EntityDynamicParameter", b => { b.HasOne("Abp.DynamicEntityParameters.DynamicParameter", "DynamicParameter") .WithMany() .HasForeignKey("DynamicParameterId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.DynamicEntityParameters.EntityDynamicParameterValue", b => { b.HasOne("Abp.DynamicEntityParameters.EntityDynamicParameter", "EntityDynamicParameter") .WithMany() .HasForeignKey("EntityDynamicParameterId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.HasOne("Abp.EntityHistory.EntityChangeSet", null) .WithMany("EntityChanges") .HasForeignKey("EntityChangeSetId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b => { b.HasOne("Abp.EntityHistory.EntityChange", null) .WithMany("PropertyChanges") .HasForeignKey("EntityChangeId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.HasOne("Abp.Organizations.OrganizationUnit", "Parent") .WithMany("Children") .HasForeignKey("ParentId"); }); modelBuilder.Entity("Abp.Webhooks.WebhookSendAttempt", b => { b.HasOne("Abp.Webhooks.WebhookEvent", "WebhookEvent") .WithMany() .HasForeignKey("WebhookEventId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("DA.ProjectManagement.Authorization.Roles.Role", b => { b.HasOne("DA.ProjectManagement.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("DA.ProjectManagement.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("DA.ProjectManagement.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("DA.ProjectManagement.Authorization.Users.User", b => { b.HasOne("DA.ProjectManagement.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("DA.ProjectManagement.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("DA.ProjectManagement.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("DA.ProjectManagement.MultiTenancy.Tenant", b => { b.HasOne("DA.ProjectManagement.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("DA.ProjectManagement.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId"); b.HasOne("DA.ProjectManagement.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasOne("DA.ProjectManagement.Authorization.Roles.Role", null) .WithMany("Permissions") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasOne("DA.ProjectManagement.Authorization.Users.User", null) .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
37.101031
125
0.447524
[ "MIT" ]
anthonynguyen92/DoAn
aspnet-core/src/DA.ProjectManagement.EntityFrameworkCore/Migrations/20200806103525_Add_Student_Table_Teacher_Table.Designer.cs
71,978
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; using java = biz.ritter.javapi; using javax = biz.ritter.javapix; namespace biz.ritter.javapi.util { /** * {@code TimeZone} represents a time zone offset, taking into account * daylight savings. * <p/> * Typically, you get a {@code TimeZone} using {@code getDefault} * which creates a {@code TimeZone} based on the time zone where the * program is running. For example, for a program running in Japan, * {@code getDefault} creates a {@code TimeZone} object based on * Japanese Standard Time. * <p/> * You can also get a {@code TimeZone} using {@code getTimeZone} * along with a time zone ID. For instance, the time zone ID for the U.S. * Pacific Time zone is "America/Los_Angeles". So, you can get a U.S. Pacific * Time {@code TimeZone} object with the following: <blockquote> * * <pre> * TimeZone tz = TimeZone.getTimeZone(&quot;America/Los_Angeles&quot;); * </pre> * * </blockquote> You can use the {@code getAvailableIDs} method to iterate * through all the supported time zone IDs. You can then choose a supported ID * to get a {@code TimeZone}. If the time zone you want is not * represented by one of the supported IDs, then you can create a custom time * zone ID with the following syntax: <blockquote> * * <pre> * GMT[+|-]hh[[:]mm] * </pre> * * </blockquote> For example, you might specify GMT+14:00 as a custom time zone * ID. The {@code TimeZone} that is returned when you specify a custom * time zone ID does not include daylight savings time. * <p/> * For compatibility with JDK 1.1.x, some other three-letter time zone IDs (such * as "PST", "CTT", "AST") are also supported. However, <strong>their use is * deprecated</strong> because the same abbreviation is often used for multiple * time zones (for example, "CST" could be U.S. "Central Standard Time" and * "China Standard Time"), and the Java platform can then only recognize one of * them. * <p/> * Please note the type returned by factory methods, i.e. {@code getDefault()} * and {@code getTimeZone(String)}, is implementation dependent, so it may * introduce serialization incompatibility issues between different * implementations. * * @see GregorianCalendar * @see SimpleTimeZone */ [Serializable] public abstract class TimeZone : java.io.Serializable, java.lang.Cloneable { private const long serialVersionUID = 3581463369166924961L; /** * The SHORT display name style. */ public const int SHORT = 0; /** * The LONG display name style. */ public const int LONG = 1; private static HashMap<String, TimeZone> AvailableZones; private static TimeZone Default; static TimeZone GMT = new SimpleTimeZone(0, "GMT"); // Greenwich Mean Time private String ID; private static void initializeAvailable() { TimeZone[] zones = TimeZones.getTimeZones(); AvailableZones = new HashMap<String, TimeZone>( (zones.Length + 1) * 4 / 3); AvailableZones.put(GMT.getID(), GMT); for (int i = 0; i < zones.Length; i++) { AvailableZones.put(zones[i].getID(), zones[i]); } } /** * Constructs a new instance of this class. */ public TimeZone() { } /** * Returns a new {@code TimeZone} with the same ID, {@code rawOffset} and daylight savings * time rules as this {@code TimeZone}. * * @return a shallow copy of this {@code TimeZone}. * @see java.lang.Cloneable */ public virtual Object clone() { try { TimeZone zone = (TimeZone)base.MemberwiseClone(); return zone; } catch (java.lang.CloneNotSupportedException) { return null; } } /** * Gets the ID of this {@code TimeZone}. * * @return the time zone ID string. */ public String getID() { return ID; } /** * Gets the daylight savings offset in milliseconds for this {@code TimeZone}. * <p/> * This implementation returns 3600000 (1 hour), or 0 if the time zone does * not observe daylight savings. * <p/> * Subclasses may override to return daylight savings values other than 1 * hour. * <p/> * * @return the daylight savings offset in milliseconds if this {@code TimeZone} * observes daylight savings, zero otherwise. */ public virtual int getDSTSavings() { if (useDaylightTime()) { return 3600000; } return 0; } /** * Gets the offset from GMT of this {@code TimeZone} for the specified date. The * offset includes daylight savings time if the specified date is within the * daylight savings time period. * * @param time * the date in milliseconds since January 1, 1970 00:00:00 GMT * @return the offset from GMT in milliseconds. */ public int getOffset(long time) { if (inDaylightTime(new Date(time))) { return getRawOffset() + getDSTSavings(); } return getRawOffset(); } /** * Gets the offset from GMT of this {@code TimeZone} for the specified date and * time. The offset includes daylight savings time if the specified date and * time are within the daylight savings time period. * * @param era * the {@code GregorianCalendar} era, either {@code GregorianCalendar.BC} or * {@code GregorianCalendar.AD}. * @param year * the year. * @param month * the {@code Calendar} month. * @param day * the day of the month. * @param dayOfWeek * the {@code Calendar} day of the week. * @param time * the time of day in milliseconds. * @return the offset from GMT in milliseconds. */ abstract public int getOffset(int era, int year, int month, int day, int dayOfWeek, int time); /** * Gets the offset for standard time from GMT for this {@code TimeZone}. * * @return the offset from GMT in milliseconds. */ abstract public int getRawOffset(); private static String formatTimeZoneName(String name, int offset) { java.lang.StringBuilder buf = new java.lang.StringBuilder(); int index = offset, length = name.length(); buf.append(name.substring(0, offset)); while (index < length) { if (java.lang.Character.digit(name.charAt(index), 10) != -1) { buf.append(name.charAt(index)); if ((length - (index + 1)) == 2) { buf.append(':'); } } else if (name.charAt(index) == ':') { buf.append(':'); } index++; } if (buf.toString().indexOf(":") == -1) { buf.append(':'); buf.append("00"); } if (buf.toString().indexOf(":") == 5) { buf.insert(4, '0'); } return buf.toString(); } /** * Returns whether the specified {@code TimeZone} has the same raw offset as this * {@code TimeZone}. * * @param zone * a {@code TimeZone}. * @return {@code true} when the {@code TimeZone} have the same raw offset, {@code false} * otherwise. */ public virtual bool hasSameRules(TimeZone zone) { if (zone == null) { return false; } return getRawOffset() == zone.getRawOffset(); } /** * Returns whether the specified {@code Date} is in the daylight savings time period for * this {@code TimeZone}. * * @param time * a {@code Date}. * @return {@code true} when the {@code Date} is in the daylight savings time period, {@code false} * otherwise. */ abstract public bool inDaylightTime(Date time); private static int parseNumber(String s, int offset, int[] position) { int index = offset, length = s.length(), digit, result = 0; while (index < length && (digit = java.lang.Character.digit(s.charAt(index), 10)) != -1) { index++; result = result * 10 + digit; } position[0] = index == offset ? -1 : index; return result; } /** * Sets the ID of this {@code TimeZone}. * * @param name * a string which is the time zone ID. */ public void setID(String name) { if (name == null) { throw new java.lang.NullPointerException(); } ID = name; } /** * Sets the offset for standard time from GMT for this {@code TimeZone}. * * @param offset * the offset from GMT in milliseconds. */ abstract public void setRawOffset(int offset); /** * Returns whether this {@code TimeZone} has a daylight savings time period. * * @return {@code true} if this {@code TimeZone} has a daylight savings time period, {@code false} * otherwise. */ abstract public bool useDaylightTime(); } }
34.398773
107
0.537542
[ "ECL-2.0", "Apache-2.0" ]
bastie/NetSpider
NetVampiro/java/util/TimeZone.cs
11,214
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using CM = Models.Common; using Utilities; using CTIServices; using Data; using EntityContext = Data.CTIEntities; using Factories; namespace CTI.Directory.Areas.Admin.Controllers { public class SiteController : CTI.Directory.Controllers.BaseController { // GET: Admin/Site public ActionResult Index() { return View(); } [Authorize( Roles = "Administrator, Site Staff" )] public ActionResult RefreshOrganizationCache() { if ( !User.Identity.IsAuthenticated || ( User.Identity.Name != "mparsons" && User.Identity.Name != "cwd-mparsons@ad.siu.edu" && User.Identity.Name != "cwd-mparsons@ad.siu.edu" && User.Identity.Name != "nathan.argo@siuccwd.com" ) ) { SetSystemMessage( "Unauthorized Action", "You are not authorized to import users." ); return RedirectToAction( "Index", "Message" ); } using ( var context = new EntityContext() ) { var result = context.Cache_Organization_ActorRoles_Populate(0); //now what } return RedirectToAction( "Index", "Message", new { area = "" } ); } // Import users [Authorize( Roles = "Administrator, Site Staff" )] public ActionResult ImportMicrosoft( int maxRecords = 100 ) { if ( !User.Identity.IsAuthenticated || ( User.Identity.Name != "mparsons" && User.Identity.Name != "cwd-mparsons@ad.siu.edu" && User.Identity.Name != "nathan.argo@siuccwd.com" ) ) { // SetSystemMessage( "Unauthorized Action", "You are not authorized to request this import of Microsoft certifications." ); return RedirectToAction( "Index", "Message" ); } string report = ""; List<string> summary = new List<string>(); SiteServices mgr = new SiteServices(); mgr.ImportMicrosoftCredentials( ref summary, maxRecords ); foreach (string s in summary) { report += s + "<br/>"; } LoggingHelper.DoTrace( 1, "Microsoft Import report: \r\n" + report ); SetSystemMessage( "Microsoft Import", report ); return RedirectToAction( "Index", "Message", new { area = "" } ); } // fix addresses missing lat/lng, and normalize [Authorize( Roles = "Administrator, Site Staff" )] public ActionResult NormalizeAddresses( int maxRecords = 100 ) { if ( !User.Identity.IsAuthenticated || ( User.Identity.Name != "mparsons" && User.Identity.Name != "cwd-mparsons@ad.siu.edu" && User.Identity.Name != "nathan.argo@siuccwd.com" ) ) { SetSystemMessage( "Unauthorized Action", "You are not authorized to invoke NormalizeAddresses." ); return RedirectToAction( "Index", "Message" ); } string report = ""; string messages = ""; List<CM.Address> list = new AddressProfileManager().ResolveMissingGeodata( ref messages, maxRecords: maxRecords ); if ( !string.IsNullOrWhiteSpace( messages ) ) report = "<p>Normalize Addresses: <br/>" + messages + "</p>" ; foreach ( var address in list ) { string msg = string.Format( " - Unable to resolve address: Id: {0}, address1: {1}, city: {2}, region: {3}, postalCode: {4}, country: {5} ", address.Id, address.Address1, address.City, address.AddressRegion, address.PostalCode, address.Country ); LoggingHelper.DoTrace(2, msg ); report += System.Environment.NewLine + msg; } SetSystemMessage( "Normalize Addresses", report ); return RedirectToAction( "Index", "Message", new { area = "" } ); } } }
33.252174
261
0.615063
[ "Apache-2.0" ]
CredentialEngine/CredentialFinderEditor
Directory/Areas/Admin/Controllers/SiteController.cs
3,826
C#
using System; namespace Shamisen.Codecs.Native.Flac.LibFLAC { public enum FLAC__StreamEncoderSeekStatus { FLAC__STREAM_ENCODER_SEEK_STATUS_OK, FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR, FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED, } }
22.5
53
0.766667
[ "Apache-2.0" ]
MineCake147E/MonoAudio
Codecs/Shamisen.Codecs.Native.FLAC/LibFLAC/FLAC__StreamEncoderSeekStatus.cs
270
C#
using System; namespace TechTalk.SpecFlow.Assist.ValueRetrievers { public class NullableBoolValueRetriever : NullableValueRetriever<bool?> { private readonly Func<string, bool> boolValueRetriever; public NullableBoolValueRetriever() : this(v => new BoolValueRetriever().GetValue(v)) { } public NullableBoolValueRetriever(Func<string, bool> boolValueRetriever = null) { if (boolValueRetriever != null) this.boolValueRetriever = boolValueRetriever; } protected override bool? GetNonEmptyValue(string value) { return boolValueRetriever(value); } } }
28.76
88
0.616134
[ "Apache-2.0", "MIT" ]
Artur-Laskowski/SpecFlow
TechTalk.SpecFlow/Assist/ValueRetrievers/NullableBoolValueRetriever.cs
721
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Bastis.Common { public class Enums { public enum MenuOptions { Administration = 1, Configuration = 2, Agencies = 3, Properties = 4, Agents = 5, Photos = 6, States = 7, Cities = 8, Permissions = 9, Menus = 1, ApplicationRoles = 11, ApplicationUsers = 12, } } }
20.615385
34
0.481343
[ "MIT" ]
JuanCarlosReyesGuerrero/BastisProjects-AdminLte
Bastis.Web/Common/Enums.cs
538
C#
using System.Security.Claims; namespace WorkflowMaxOAuth2Sample.Extensions { public static class ClaimsPrincipalExtensions { public static string XeroUserId(this ClaimsPrincipal claims) { return claims.FindFirstValue("xero_userid"); } } }
22.230769
68
0.688581
[ "MIT" ]
Olyshka/workflowmax-dotnetcore-oauth2-sample
WorkflowMaxOAuth2Sample/Extensions/ClaimsPrincipalExtensions.cs
291
C#
using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Driver; using MongoDB.Labs.Search; namespace Mongo.LuceneQuery { public sealed class LuceneSearchDefinition<TDocument> : SearchDefinition<TDocument> { private readonly FieldDefinition<TDocument> defaultPath; private readonly LuceneQueryVisitor visitor; private readonly string query; public LuceneSearchDefinition(FieldDefinition<TDocument> defaultPath, string query, Func<string, string>? fieldConverter = null) { this.defaultPath = defaultPath; if (fieldConverter != null) { visitor = LuceneQueryVisitor.Default; } else { visitor = new LuceneQueryVisitor(fieldConverter); } this.query = query; } public override BsonDocument Render(IBsonSerializer<TDocument> documentSerializer, IBsonSerializerRegistry serializerRegistry) { var renderedField = defaultPath.Render(documentSerializer, serializerRegistry); var renderedQuery = LuceneQueryParser.Parse(query, renderedField.FieldName); var rendered = visitor.Visit(renderedQuery); return rendered; } } }
31.414634
136
0.65528
[ "MIT" ]
SebastianStehle/MongoSearchTest
Mongo.LuceneQuery/LuceneSearchDefinition.cs
1,290
C#
//********************************* bs::framework - Copyright 2018-2019 Marko Pintera ************************************// //*********** Licensed under the MIT license. See LICENSE.md for full terms. This notice is not to be removed. ***********// using System; using System.Runtime.CompilerServices; namespace bs { /** @addtogroup GUI * @{ */ public partial class LocString { /// <summary> /// Converts a normal string into a localized string by using the normal string as the identifier. /// </summary> /// <param name="identifier">Localized string identifier.</param> /// <returns>Localized string with the provided identifier, from the default string table.</returns> public static implicit operator LocString(string identifier) { return new LocString(identifier); } /// <summary> /// Retrieves localized text for the active language from the localized string. /// </summary> /// <param name="text">Localized string to retrieve the text from.</param> /// <returns>Translated text for the currently active language.</returns> public static explicit operator string(LocString text) { return Internal_getValue(text.mCachedPtr); } } /** @} */ }
36.081081
125
0.588764
[ "MIT" ]
Alan-love/bsf
Source/Scripting/bsfSharp/GUI/LocString.cs
1,337
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.ComponentModel; namespace Azure.Analytics.Synapse.Artifacts.Models { /// <summary> The deployment type of the Dynamics instance. &apos;Online&apos; for Dynamics Online and &apos;OnPremisesWithIfd&apos; for Dynamics on-premises with Ifd. Type: string (or Expression with resultType string). </summary> public readonly partial struct DynamicsDeploymentType : IEquatable<DynamicsDeploymentType> { private readonly string _value; /// <summary> Determines if two <see cref="DynamicsDeploymentType"/> values are the same. </summary> public DynamicsDeploymentType(string value) { _value = value ?? throw new ArgumentNullException(nameof(value)); } private const string OnlineValue = "Online"; private const string OnPremisesWithIfdValue = "OnPremisesWithIfd"; /// <summary> Online. </summary> public static DynamicsDeploymentType Online { get; } = new DynamicsDeploymentType(OnlineValue); /// <summary> OnPremisesWithIfd. </summary> public static DynamicsDeploymentType OnPremisesWithIfd { get; } = new DynamicsDeploymentType(OnPremisesWithIfdValue); /// <summary> Determines if two <see cref="DynamicsDeploymentType"/> values are the same. </summary> public static bool operator ==(DynamicsDeploymentType left, DynamicsDeploymentType right) => left.Equals(right); /// <summary> Determines if two <see cref="DynamicsDeploymentType"/> values are not the same. </summary> public static bool operator !=(DynamicsDeploymentType left, DynamicsDeploymentType right) => !left.Equals(right); /// <summary> Converts a string to a <see cref="DynamicsDeploymentType"/>. </summary> public static implicit operator DynamicsDeploymentType(string value) => new DynamicsDeploymentType(value); /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override bool Equals(object obj) => obj is DynamicsDeploymentType other && Equals(other); /// <inheritdoc /> public bool Equals(DynamicsDeploymentType other) => string.Equals(_value, other._value, StringComparison.InvariantCultureIgnoreCase); /// <inheritdoc /> [EditorBrowsable(EditorBrowsableState.Never)] public override int GetHashCode() => _value?.GetHashCode() ?? 0; /// <inheritdoc /> public override string ToString() => _value; } }
50.941176
235
0.706313
[ "MIT" ]
AzureDataBox/azure-sdk-for-net
sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/DynamicsDeploymentType.cs
2,598
C#
using System; namespace Ganss.Excel { /// <summary> /// Attribute which specifies that the formula result instead of the formula should be mapped. /// This applies only to string properties, as for all other types the result will be mapped. /// </summary> /// <seealso cref="System.Attribute" /> [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)] public sealed class FormulaResultAttribute : Attribute { } }
32
98
0.697917
[ "MIT" ]
BeyondMySouls/ExcelMapper
ExcelMapper/Attributes/FormulaResultAttribute.cs
482
C#
/* ======================================================================= Copyright 2017 Technische Universitaet Darmstadt, Fachgebiet fuer Stroemungsdynamik (chair of fluid dynamics) 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 BoSSS.Foundation; using BoSSS.Foundation.Grid; using BoSSS.Foundation.Quadrature; using BoSSS.Foundation.XDG; using BoSSS.Platform; using System; using ilPSP; using BoSSS.Foundation.Grid.Classic; namespace CutCellQuadrature { class ScalarFieldQuadrature : CellQuadrature { public double Result; private DGField field; public ScalarFieldQuadrature(IGridData gridData, DGField field, CellQuadratureScheme quadInstr, int quadOrder) : base(new int[] { 1 }, gridData, quadInstr.Compile(gridData, quadOrder)) { this.field = field; } protected override void Evaluate(int i0, int Length, QuadRule qr, MultidimensionalArray EvalResult) { if (field is XDGField) { SpeciesId speciesB = new SpeciesId() { cntnt = 11112 }; MultidimensionalArray result = EvalResult.ExtractSubArrayShallow(-1, -1, 0); ((XDGField)field).GetSpeciesShadowField(speciesB).Evaluate(i0, Length, qr.Nodes, result, 0, 0.0); } else { field.Evaluate(i0, Length, qr.Nodes, EvalResult.ExtractSubArrayShallow(-1, -1, 0)); } } protected override void SaveIntegrationResults(int i0, int Length, MultidimensionalArray ResultsOfIntegration) { for (int i = 0; i < Length; i++) { Result += ResultsOfIntegration[i, 0]; } } } }
37.366667
121
0.637377
[ "Apache-2.0" ]
FDYdarmstadt/BoSSS
src/L4-application/CutCellQuadrature/ScalarFieldQuadrature.cs
2,185
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace VariableInHexadecimalFormat { class Program { static void Main(string[] args) { string hexValue = Console.ReadLine(); int decValue = Convert.ToInt32(hexValue, 16); Console.WriteLine(decValue); } } }
20
57
0.6375
[ "MIT" ]
valkin88/Technologies-Fundamentals
Programming Fundamentals/Program Fundamentals - Data Types and Variables - Exercises/VariableInHexadecimalFormat/VariableInHexadecimalFormat/Program.cs
402
C#
using System; using System.Collections; using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation; using System.Net.Http; using System.Net.Http.Headers; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Graph.PowerShell.Authentication.Extensions; using Microsoft.Graph.PowerShell.Authentication.Helpers; using Microsoft.Graph.PowerShell.Authentication.Interfaces; using Microsoft.Graph.PowerShell.Authentication.Models; using Microsoft.Graph.PowerShell.Authentication.Properties; using Microsoft.PowerShell.Commands; using Newtonsoft.Json; using static Microsoft.Graph.PowerShell.Authentication.Helpers.AsyncHelpers; using DriveNotFoundException = System.Management.Automation.DriveNotFoundException; namespace Microsoft.Graph.PowerShell.Authentication.Cmdlets { [Cmdlet(VerbsLifecycle.Invoke, "MgGraphRequest", DefaultParameterSetName = Constants.UserParameterSet)] [Alias("Invoke-GraphRequest")] public class InvokeMgGraphRequest : PSCmdlet { private readonly CancellationTokenSource _cancellationTokenSource = new CancellationTokenSource(); private RequestUserAgent _graphRequestUserAgent; private IGraphEnvironment _originalEnvironment; private string _originalFilePath; public InvokeMgGraphRequest() { Authentication = GraphRequestAuthenticationType.Default; } /// <summary> /// Http Method /// </summary> [Parameter(ParameterSetName = Constants.UserParameterSet, Position = 1, HelpMessage = "Http Method")] public GraphRequestMethod Method { get; set; } = GraphRequestMethod.GET; /// <summary> /// Uri to call using the Graph HttpClient can be segments such as /beta/me /// or fully qualified url such as https://graph.microsoft.com/beta/me /// </summary> [Parameter(ParameterSetName = Constants.UserParameterSet, Position = 2, Mandatory = true, HelpMessage = "Uri to call can be segments such as /beta/me or fully qualified https://graph.microsoft.com/beta/me")] public Uri Uri { get; set; } /// <summary> /// Optional Http Body /// </summary> [Parameter(ParameterSetName = Constants.UserParameterSet, Position = 3, HelpMessage = "Request Body. Required when Method is Post or Patch", ValueFromPipeline = true)] public object Body { get; set; } /// <summary> /// Optional Custom Headers /// </summary> [Parameter(Mandatory = false, ParameterSetName = Constants.UserParameterSet, Position = 4, HelpMessage = "Optional Custom Headers")] public IDictionary Headers { get; set; } /// <summary> /// Relative or absolute path where the response body will be saved. /// Not allowed when InferOutputFileName is specified. /// </summary> [Parameter(Mandatory = false, ParameterSetName = Constants.UserParameterSet, Position = 5, HelpMessage = "Output file where the response body will be saved")] public string OutputFilePath { get; set; } /// <summary> /// Infer Download FileName from ContentDisposition Header. /// Not allowed when OutputFilePath is specified. /// </summary> [Parameter(Mandatory = false, ParameterSetName = Constants.UserParameterSet, Position = 6, HelpMessage = "Infer output filename")] public SwitchParameter InferOutputFileName { get; set; } /// <summary> /// Gets or sets the InputFilePath property to send in the request /// </summary> [Parameter(Mandatory = false, ParameterSetName = Constants.UserParameterSet, Position = 7, HelpMessage = "Input file to send in the request")] public virtual string InputFilePath { get; set; } /// <summary> /// Indicates that the cmdlet returns the results, in addition to writing them to a file. /// only valid when the OutFile parameter is also used. /// </summary> [Parameter(Mandatory = false, ParameterSetName = Constants.UserParameterSet, Position = 8, HelpMessage = "Indicates that the cmdlet returns the results, in addition to writing them to a file. Only valid when the OutFile parameter is also used. ")] public SwitchParameter PassThru { get; set; } /// <summary> /// OAuth or Bearer Token to use instead of already acquired token /// </summary> [Parameter(Mandatory = false, ParameterSetName = Constants.UserParameterSet, Position = 9, HelpMessage = "OAuth or Bearer Token to use instead of already acquired token")] public SecureString Token { get; set; } /// <summary> /// Add headers to Request Header collection without validation /// </summary> [Parameter(Mandatory = false, ParameterSetName = Constants.UserParameterSet, Position = 10, HelpMessage = "Add headers to Request Header collection without validation")] public SwitchParameter SkipHeaderValidation { get; set; } /// <summary> /// Custom Content Type /// </summary> [Parameter(Mandatory = false, ParameterSetName = Constants.UserParameterSet, Position = 11, HelpMessage = "Custom Content Type")] public virtual string ContentType { get; set; } /// <summary> /// Graph Authentication Type /// </summary> [Parameter(Mandatory = false, ParameterSetName = Constants.UserParameterSet, Position = 12, HelpMessage = "Graph Authentication Type")] public GraphRequestAuthenticationType Authentication { get; set; } /// <summary> /// Specifies a web request session. Enter the variable name, including the dollar sign ($). /// You can't use the SessionVariable and WebSession parameters in the same command. /// </summary> [Parameter(Mandatory = false, ParameterSetName = Constants.UserParameterSet, Position = 13, HelpMessage = "Specifies a web request session. Enter the variable name, including the dollar sign ($)." + "You can't use the SessionVariable and GraphRequestSession parameters in the same command.")] [Alias("SV")] public string SessionVariable { get; set; } /// <summary> /// Response Headers Variable /// </summary> [Parameter(Mandatory = false, ParameterSetName = Constants.UserParameterSet, Position = 14, HelpMessage = "Response Headers Variable")] [Alias("RHV")] public string ResponseHeadersVariable { get; set; } /// <summary> /// Response Status Code Variable /// </summary> [Parameter(Position = 15, ParameterSetName = Constants.UserParameterSet, Mandatory = false, HelpMessage = "Response Status Code Variable")] public string StatusCodeVariable { get; set; } /// <summary> /// Gets or sets whether to skip checking HTTP status for error codes. /// </summary> [Parameter(Position = 16, ParameterSetName = Constants.UserParameterSet, Mandatory = false, HelpMessage = "Skip Checking Http Errors")] public virtual SwitchParameter SkipHttpErrorCheck { get; set; } /// <summary> /// Gets or sets the Session property. /// </summary> [Parameter(Mandatory = false, Position = 17, ParameterSetName = Constants.UserParameterSet, HelpMessage = "Custom Graph Request Session")] public GraphRequestSession GraphRequestSession { get; set; } /// <summary> /// Custom User Specified User Agent /// </summary> [Parameter(Mandatory = false, Position = 18, ParameterSetName = Constants.UserParameterSet, HelpMessage = "Custom User Specified User Agent")] public string UserAgent { get; set; } /// <summary> /// OutputType to return to the caller, Defaults to HashTable /// </summary> [Parameter(Mandatory = false, Position = 19, ParameterSetName = Constants.UserParameterSet, HelpMessage = "Output Type to return to the caller")] public OutputType OutputType { get; set; } = OutputType.HashTable; /// <summary> /// Wait for .NET debugger to attach /// </summary> [Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] public SwitchParameter Break { get; set; } internal string QualifiedOutFile => QualifyFilePath(OutputFilePath); internal bool ShouldSaveToOutFile => !string.IsNullOrEmpty(OutputFilePath); /// <summary> /// Only write to pipeline if outfile is not specified, inference is not specified but PassThru is set. /// </summary> internal bool ShouldWriteToPipeline => !ShouldSaveToOutFile && !InferOutputFileName || PassThru; internal bool ShouldCheckHttpStatus => !SkipHttpErrorCheck; /// <summary> /// Only Set Default Content Type (application/json) for POST, PUT and PATCH requests, where its not specified via `-ContentType`. /// </summary> private bool ShouldSetDefaultContentType => Method == GraphRequestMethod.POST || Method == GraphRequestMethod.PUT || Method == GraphRequestMethod.PATCH; private static async Task<ErrorRecord> GenerateHttpErrorRecordAsync( HttpMessageFormatter httpResponseMessageFormatter, HttpRequestMessage httpRequestMessage) { using (NoSynchronizationContext) { // Load into buffer to avoid stream already consumed issues. await httpResponseMessageFormatter.LoadIntoBufferAsync(); var currentResponse = httpResponseMessageFormatter.HttpResponseMessage; var errorMessage = Resources.ResponseStatusCodeFailure.FormatCurrentCulture(currentResponse.StatusCode, currentResponse.ReasonPhrase); var httpException = new HttpResponseException(errorMessage, currentResponse); var errorRecord = new ErrorRecord(httpException, ErrorConstants.Codes.InvokeGraphHttpResponseException, ErrorCategory.InvalidOperation, httpRequestMessage); var detailMsg = await httpResponseMessageFormatter.ReadAsStringAsync(); if (!string.IsNullOrEmpty(detailMsg)) { errorRecord.ErrorDetails = new ErrorDetails(detailMsg); } return errorRecord; } } /// <summary> /// When -Verbose is specified, print out response status /// </summary> /// <param name="requestMessageFormatter"></param> private async Task ReportRequestStatusAsync(HttpMessageFormatter requestMessageFormatter) { using (NoSynchronizationContext) { await requestMessageFormatter.LoadIntoBufferAsync(); var requestMessage = requestMessageFormatter.HttpRequestMessage; var requestContentLength = requestMessage.Content?.Headers.ContentLength.Value ?? 0; var reqVerboseMsg = Resources.InvokeGraphRequestVerboseMessage.FormatCurrentCulture( requestMessage.Method, requestMessage.RequestUri, requestContentLength); // If Verbose is specified, will print out Uri and Content Length WriteVerbose(reqVerboseMsg); var requestString = await requestMessageFormatter.ReadAsStringAsync(); // If Debug is Specified, will print out the Http Request as a string WriteDebug(requestString); } } /// <summary> /// When -Verbose is specified, print out response status /// </summary> /// <param name="responseMessageFormatter"></param> private async Task ReportResponseStatusASync(HttpMessageFormatter responseMessageFormatter) { using (NoSynchronizationContext) { await responseMessageFormatter.LoadIntoBufferAsync(); var contentType = responseMessageFormatter.HttpResponseMessage.GetContentType(); var respVerboseMsg = Resources.InvokeGraphResponseVerboseMessage.FormatCurrentCulture( responseMessageFormatter.HttpResponseMessage.Content.Headers.ContentLength, contentType); // If Verbose is specified, will print out Uri and Content Length WriteVerbose(respVerboseMsg); var responseString = await responseMessageFormatter.ReadAsStringAsync(); // If Debug is Specified, will print out the Http Response as a string WriteDebug(responseString); } } /// <summary> /// Compose a request, setting Uri and Headers. /// </summary> /// <param name="httpClient"></param> /// <param name="uri"></param> /// <returns></returns> private HttpRequestMessage GetRequest(HttpClient httpClient, Uri uri) { var requestUri = PrepareUri(httpClient, uri); var httpMethod = GetHttpMethod(Method); // create the base WebRequest object var request = new HttpRequestMessage(httpMethod, requestUri); // pull in session data if (GraphRequestSession.Headers.Count > 0) { GraphRequestSession.ContentHeaders.Clear(); foreach (var entry in GraphRequestSession.Headers) { if (HttpKnownHeaderNames.ContentHeaders.Contains(entry.Key)) { GraphRequestSession.ContentHeaders.Add(entry.Key, entry.Value); } else { if (SkipHeaderValidation) { request.Headers.TryAddWithoutValidation(entry.Key, entry.Value); } else { request.Headers.Add(entry.Key, entry.Value); } } } } // Set 'Transfer-Encoding: chunked' if 'Transfer-Encoding' is specified if (GraphRequestSession.Headers.ContainsKey(HttpKnownHeaderNames.TransferEncoding)) { request.Headers.TransferEncodingChunked = true; } // Set 'User-Agent' if WebSession.Headers doesn't already contain it if (GraphRequestSession.Headers.TryGetValue(HttpKnownHeaderNames.UserAgent, out var userAgent)) { GraphRequestSession.UserAgent = userAgent; } else { if (SkipHeaderValidation) { request.Headers.TryAddWithoutValidation(HttpKnownHeaderNames.UserAgent, GraphRequestSession.UserAgent); } else { request.Headers.Add(HttpKnownHeaderNames.UserAgent, GraphRequestSession.UserAgent); } } return request; } /// <summary> /// Compose Request Uri /// </summary> /// <param name="httpClient"></param> /// <param name="uri"></param> /// <returns></returns> private Uri PrepareUri(HttpClient httpClient, Uri uri) { UriBuilder uriBuilder; // For AbsoluteUri such as /beta/groups?$count=true, Get the scheme and host from httpClient // Then use them to compose a new Url with the URL fragment. if (!uri.IsAbsoluteUri) { uriBuilder = new UriBuilder { Scheme = httpClient.BaseAddress.Scheme, Host = httpClient.BaseAddress.Host }; uri = new Uri(uriBuilder.Uri, uri); } uriBuilder = new UriBuilder(uri); // before creating the web request, // preprocess Body if content is a dictionary and method is GET (set as query) if (Method == GraphRequestMethod.GET && LanguagePrimitives.TryConvertTo(Body, out IDictionary bodyAsDictionary)) { var bodyQueryParameters = bodyAsDictionary?.FormatDictionary(); if (uriBuilder.Query != null && uriBuilder.Query.Length > 1 && !string.IsNullOrWhiteSpace(bodyQueryParameters)) { uriBuilder.Query = uriBuilder.Query.Substring(1) + "&" + bodyQueryParameters; } else if (!string.IsNullOrWhiteSpace(bodyQueryParameters)) { uriBuilder.Query = bodyQueryParameters; } // set body to null to prevent later FillRequestStream Body = null; } return uriBuilder.Uri; } private void ThrowIfError(ErrorRecord error) { if (error != null) { ThrowTerminatingError(error); } } /// <summary> /// Process Http Response /// </summary> /// <param name="response"></param> internal async Task ProcessResponseAsync(HttpResponseMessage response) { if (response == null) throw new ArgumentNullException(nameof(response)); if (ShouldWriteToPipeline) { var returnType = response.CheckReturnType(); if (returnType == RestReturnType.Json) { var responseString = await response.Content.ReadAsStringAsync(); ErrorRecord error; switch (OutputType) { case OutputType.HashTable: var hashTable = responseString.ConvertFromJson(true, null, out error); ThrowIfError(error); WriteObject(hashTable); break; case OutputType.PSObject: var psObject = responseString.ConvertFromJson(false, null, out error); ThrowIfError(error); WriteObject(psObject, true); break; case OutputType.HttpResponseMessage: WriteObject(response); break; case OutputType.Json: WriteObject(responseString); break; default: throw new ArgumentOutOfRangeException(); } } else if (returnType == RestReturnType.Image) { var errorRecord = GetValidationError(Resources.NonJsonResponseWithoutOutputFilePath, ErrorConstants.Codes.InvokeGraphContentTypeException, returnType); ThrowIfError(errorRecord); } else if (returnType == RestReturnType.OctetStream) { var errorRecord = GetValidationError(Resources.NonJsonResponseWithoutInfer, ErrorConstants.Codes.InvokeGraphContentTypeException, returnType, response.Content.Headers.ContentDisposition); ThrowIfError(errorRecord); } } if (ShouldSaveToOutFile) { response.GetResponseStream().SaveStreamToFile(QualifiedOutFile, this, _cancellationTokenSource.Token); } if (InferOutputFileName.IsPresent) { if (response.Content.Headers.ContentDisposition != null) { if (!string.IsNullOrWhiteSpace(response.Content.Headers.ContentDisposition.FileName)) { var fileName = response.Content.Headers.ContentDisposition.FileNameStar ?? response.Content.Headers.ContentDisposition.FileName; if (!string.IsNullOrWhiteSpace(fileName)) { var sanitizedFileName = SanitizeFileName(fileName); var fullFileName = QualifyFilePath(sanitizedFileName); WriteVerbose( Resources.InferredFileNameVerboseMessage.FormatCurrentCulture(fileName, fullFileName)); response.GetResponseStream().SaveStreamToFile(fullFileName, this, _cancellationTokenSource.Token); } else { var errorRecord = GetValidationError(Resources.InferredFileNameIncorrect, ErrorConstants.Codes.InvokeGraphRequestCouldNotInferFileName, fileName); WriteError(errorRecord); } } } else { var errorRecord = GetValidationError(Resources.InferredFileNameErrorMessage, ErrorConstants.Codes.InvokeGraphRequestCouldNotInferFileName); WriteError(errorRecord); } } if (!string.IsNullOrEmpty(StatusCodeVariable)) { var vi = SessionState.PSVariable; vi.Set(StatusCodeVariable, (int)response.StatusCode); } if (!string.IsNullOrEmpty(ResponseHeadersVariable)) { var vi = SessionState.PSVariable; vi.Set(ResponseHeadersVariable, response.GetHttpResponseHeaders()); } } /// <summary> /// When Inferring file names from Content disposition, ensure that /// only valid path characters are in the file name /// </summary> /// <param name="fileName"></param> /// <returns></returns> private static string SanitizeFileName(string fileName) { var illegalCharacters = Path.GetInvalidFileNameChars().Concat(Path.GetInvalidPathChars()).ToArray(); return string.Concat(fileName.Split(illegalCharacters)); } /// <summary> /// Gets a Custom AuthProvider or configured default provided depending on Auth Scheme specified. /// </summary> /// <returns></returns> private IAuthenticationProvider GetAuthProvider() { if (Authentication == GraphRequestAuthenticationType.UserProvidedToken) { return new InvokeGraphRequestAuthProvider(GraphRequestSession); } // Ensure that AuthContext is present in DefaultAuth mode, otherwise demand for Connect-Graph to be called. if (Authentication == GraphRequestAuthenticationType.Default && GraphSession.Instance.AuthContext != null) { return AuthenticationHelpers.GetAuthProvider(GraphSession.Instance.AuthContext); } var error = new ArgumentNullException( Resources.MissingAuthenticationContext.FormatCurrentCulture(nameof(GraphSession.Instance.AuthContext)), nameof(GraphSession.Instance.AuthContext)); throw error; } /// <summary> /// Gets a Graph HttpClient with a custom or default auth provider. /// </summary> /// <returns></returns> private HttpClient GetHttpClient() { var provider = GetAuthProvider(); var client = HttpHelpers.GetGraphHttpClient(provider, GraphSession.Instance.AuthContext.ClientTimeout); return client; } /// <summary> /// Executes the HTTP Request and returns a response /// </summary> /// <param name="client"></param> /// <param name="request"></param> /// <returns></returns> private async Task<HttpResponseMessage> GetResponseAsync(HttpClient client, HttpRequestMessage request) { using (NoSynchronizationContext) { if (client == null) { throw new ArgumentNullException(nameof(client)); } if (request == null) { throw new ArgumentNullException(nameof(request)); } var cancellationToken = _cancellationTokenSource.Token; var response = await client.SendAsync(request, cancellationToken); return response; } } /// <summary> /// Set the request content. /// Convert Dictionaries to Json /// Passing a dictionary to the body object should be translated to Json. /// Almost everything on Microsoft Graph works converts dictionaries and arrays to JSON. /// </summary> /// <param name="request"></param> /// <param name="content"></param> /// <returns></returns> private long SetRequestContent(HttpRequestMessage request, IDictionary content) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (content == null) { throw new ArgumentNullException(nameof(content)); } // Covert all dictionaries to Json var body = JsonConvert.SerializeObject(content); return SetRequestContent(request, body); } /// <summary> /// Set the request content /// </summary> /// <param name="request"></param> /// <param name="content"></param> /// <returns></returns> private long SetRequestContent(HttpRequestMessage request, string content) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (content == null) { return 0; } Encoding encoding = null; // When contentType is set, coerce to correct encoding. if (!string.IsNullOrWhiteSpace(ContentType)) { // If Content-Type contains the encoding format (as CharSet), use this encoding format // to encode the Body of the GraphRequest sent to the server. Default Encoding format // would be used if Charset is not supplied in the Content-Type property. try { var mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(ContentType); if (!string.IsNullOrEmpty(mediaTypeHeaderValue.CharSet)) { encoding = Encoding.GetEncoding(mediaTypeHeaderValue.CharSet); } } catch (FormatException ex) { if (!SkipHeaderValidation) { var outerEx = new ValidationMetadataException(Resources.ContentTypeExceptionErrorMessage, ex); var er = new ErrorRecord(outerEx, ErrorConstants.Codes.InvokeGraphContentTypeException, ErrorCategory.InvalidArgument, ContentType); ThrowTerminatingError(er); } } catch (ArgumentException ex) { if (!SkipHeaderValidation) { var outerEx = new ValidationMetadataException(Resources.ContentTypeExceptionErrorMessage, ex); var er = new ErrorRecord(outerEx, ErrorConstants.Codes.InvokeGraphContentTypeException, ErrorCategory.InvalidArgument, ContentType); ThrowTerminatingError(er); } } } var bytes = content.EncodeToBytes(encoding); var byteArrayContent = new ByteArrayContent(bytes); request.Content = byteArrayContent; return byteArrayContent.Headers.ContentLength.Value; } /// <summary> /// Hydrate the request with the requisite data. /// for Body handle Dictionaries, Streams and Byte Arrays, coerce /// into a string if none of the above types. /// </summary> /// <param name="request"></param> private void FillRequestStream(HttpRequestMessage request) { if (request == null) throw new ArgumentNullException(nameof(request)); if (ContentType != null) { GraphRequestSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = ContentType; } else if (ShouldSetDefaultContentType) { GraphRequestSession.ContentHeaders.TryGetValue(HttpKnownHeaderNames.ContentType, out var contentType); if (string.IsNullOrWhiteSpace(contentType)) { // Assume application/json if not set by user GraphRequestSession.ContentHeaders[HttpKnownHeaderNames.ContentType] = CoreConstants.MimeTypeNames.Application.Json; } } // coerce body into a usable form if (Body != null) { var content = Body; // make sure we're using the base object of the body, not the PSObject wrapper if (Body is PSObject psBody) { content = psBody.BaseObject; } // Passing a dictionary to the body object should be translated to Json. // Almost everything on Microsoft Graph works converts dictionaries and arrays to JSON. if (content is IDictionary dictionary && request.Method != HttpMethod.Get) { SetRequestContent(request, dictionary); } else if (content is Stream stream) { SetRequestContent(request, stream); } else if (content is byte[] bytes) { SetRequestContent(request, bytes); } else { // Assume its a string SetRequestContent(request, (string)LanguagePrimitives.ConvertTo(content, typeof(string), CultureInfo.InvariantCulture)); } } else if (InputFilePath != null) // copy InputFilePath data { try { // open the input file SetRequestContent(request, new FileStream(InputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)); } catch (UnauthorizedAccessException) { var msg = Resources.AccessDenied.FormatCurrentCulture(_originalFilePath); throw new UnauthorizedAccessException(msg); } } // Add the content headers // Only Set Content Headers when its not a GET Request if (request.Content == null && Method != GraphRequestMethod.GET) { request.Content = new StringContent(string.Empty); request.Content.Headers.Clear(); } foreach (var entry in GraphRequestSession.ContentHeaders.Where(header => !string.IsNullOrWhiteSpace(header.Value))) { if (SkipHeaderValidation) { request.Content?.Headers.TryAddWithoutValidation(entry.Key, entry.Value); } else { try { request.Content?.Headers.Add(entry.Key, entry.Value); } catch (FormatException ex) { var outerEx = new ValidationMetadataException(Resources.ContentTypeExceptionErrorMessage, ex); var er = new ErrorRecord(outerEx, ErrorConstants.Codes.InvokeGraphContentTypeException, ErrorCategory.InvalidArgument, ContentType); ThrowTerminatingError(er); } } } } /// <summary> /// Sets the body of the to be a byte array /// </summary> /// <param name="request"></param> /// <param name="content"></param> /// <returns></returns> private static long SetRequestContent(HttpRequestMessage request, byte[] content) { if (request == null) throw new ArgumentNullException(nameof(request)); if (content == null) return 0; var byteArrayContent = new ByteArrayContent(content); request.Content = byteArrayContent; return byteArrayContent.Headers.ContentLength.Value; } /// <summary> /// Sets the body of the request to be a Stream /// </summary> /// <param name="request"></param> /// <param name="contentStream"></param> /// <returns></returns> private static long SetRequestContent(HttpRequestMessage request, Stream contentStream) { if (request == null) throw new ArgumentNullException(nameof(request)); if (contentStream == null) throw new ArgumentNullException(nameof(contentStream)); var streamContent = new StreamContent(contentStream); request.Content = streamContent; return streamContent.Headers.ContentLength.Value; } /// <summary> /// Maps from HttpVerb to System.Net.Http.HttpMethod /// </summary> /// <returns>System.Net.Http.HttpMethod</returns> private static HttpMethod GetHttpMethod(GraphRequestMethod graphRequestMethod) { return new HttpMethod(graphRequestMethod.ToString().ToUpperInvariant()); } /// <summary> /// Prepare GraphRequestSession to be used downstream. /// </summary> internal virtual void PrepareSession() { // Swap current GraphSession environment with a temporary environment for this request. // This only occurs when a customer has provided an absolute url and an access token. if (MyInvocation.BoundParameters.ContainsKey(nameof(Uri)) && MyInvocation.BoundParameters.ContainsKey(nameof(Token)) && Uri.IsAbsoluteUri) { _originalEnvironment = GraphSession.Instance.Environment; GraphSession.Instance.Environment = new GraphEnvironment { Name = "MSGraphInvokeGraphRequest", GraphEndpoint = Uri.GetBaseUrl() // No need to set AAD endpoint since a token is provided. }; } // Create a new GraphRequestSession object to work with if one is not supplied GraphRequestSession = GraphRequestSession ?? new GraphRequestSession(); if (SessionVariable != null) { // save the session back to the PS environment if requested var vi = SessionState.PSVariable; vi.Set(SessionVariable, GraphRequestSession); } if (Authentication == GraphRequestAuthenticationType.UserProvidedToken && Token != null) { GraphRequestSession.Token = Token; GraphRequestSession.AuthenticationType = Authentication; } // // Handle Custom User Agents // GraphRequestSession.UserAgent = UserAgent ?? _graphRequestUserAgent.UserAgent; // Store the other supplied headers if (Headers != null) { foreach (string key in Headers.Keys) { var value = Headers[key]; // null is not valid value for header. // We silently ignore header if value is null. if (!(value is null)) { // add the header value (or overwrite it if already present) GraphRequestSession.Headers[key] = value.ToString(); } } } } /// <summary> /// Validate the Request Uri must have the same Host as GraphHttpClient BaseAddress. /// </summary> private void ValidateRequestUri() { if (Uri == null) { var error = GetValidationError( Resources.InvokeGraphRequestMissingUriErrorMessage, ErrorConstants.Codes.InvokeGraphRequestInvalidHost, nameof(Uri)); ThrowTerminatingError(error); } if (string.IsNullOrWhiteSpace(Uri.ToString())) { var error = GetValidationError( Resources.InvokeGraphRequestInvalidUriErrorMessage, ErrorConstants.Codes.InvokeGraphRequestInvalidHost, nameof(Uri)); ThrowTerminatingError(error); } } /// <summary> /// Validate Passed In Parameters /// </summary> private void ValidateParameters() { if (GraphRequestSession != null && SessionVariable != null) { var error = GetValidationError( Resources.GraphRequestSessionConflict, ErrorConstants.Codes.InvokeGraphRequestSessionConflictException); ThrowTerminatingError(error); } if (PassThru && OutputFilePath == null) { var error = GetValidationError( Resources.PassThruWithOutputFilePathMissing, ErrorConstants.Codes.InvokeGraphRequestOutFileMissingException, nameof(PassThru), nameof(OutputFilePath)); ThrowTerminatingError(error); } if (Authentication == GraphRequestAuthenticationType.Default && Token != null) { var error = GetValidationError( Resources.AuthenticationTokenConflict, ErrorConstants.Codes.InvokeGraphRequestAuthenticationTokenConflictException, Authentication, nameof(Token)); ThrowTerminatingError(error); } if (Authentication == GraphRequestAuthenticationType.Default && GraphSession.Instance.AuthContext == null) { var error = GetValidationError( Resources.NotConnectedToGraphException, ErrorConstants.Codes.InvokeGraphRequestAuthenticationTokenConflictException, Authentication, nameof(Token)); ThrowTerminatingError(error); } // Token shouldn't be null when UserProvidedToken is specified if (Authentication == GraphRequestAuthenticationType.UserProvidedToken && Token == null) { var error = GetValidationError( Resources.AuthenticationCredentialNotSupplied, ErrorConstants.Codes.InvokeGraphRequestAuthenticationTokenConflictException, Authentication, nameof(Token)); ThrowTerminatingError(error); } // Only Body or InputFilePath can be specified at a time if (Body != null && !string.IsNullOrWhiteSpace(InputFilePath)) { var error = GetValidationError( Resources.BodyConflict, ErrorConstants.Codes.InvokeGraphRequestBodyConflictException, nameof(Body), nameof(InputFilePath)); ThrowTerminatingError(error); } if (InferOutputFileName.IsPresent && !string.IsNullOrWhiteSpace(OutputFilePath)) { var error = GetValidationError( Resources.InferFileNameOutFilePathConflict, ErrorConstants.Codes.InvokeGraphRequestBodyConflictException, nameof(InferOutputFileName), nameof(OutputFilePath)); ThrowTerminatingError(error); } // Ensure InputFilePath is an Existing Item if (InputFilePath != null) { ErrorRecord errorRecord = null; try { var providerPaths = GetResolvedProviderPathFromPSPath(InputFilePath, out var provider); if (!provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase)) { errorRecord = GetValidationError( Resources.NotFileSystemPath, ErrorConstants.Codes.InvokeGraphRequestFileNotFilesystemPathException, InputFilePath); } else { if (providerPaths.Count > 1) { errorRecord = GetValidationError( Resources.MultiplePathsResolved, ErrorConstants.Codes.InvokeGraphRequestInputFileMultiplePathsResolvedException, InputFilePath); } else if (providerPaths.Count == 0) { errorRecord = GetValidationError( Resources.NoPathResolved, ErrorConstants.Codes.InvokeGraphRequestInputFileNoPathResolvedException, InputFilePath); } else { if (Directory.Exists(providerPaths[0])) { errorRecord = GetValidationError( Resources.DirectoryPathSpecified, ErrorConstants.Codes.InvokeGraphRequestInputFileNotFilePathException, InputFilePath); } _originalFilePath = InputFilePath; InputFilePath = providerPaths[0]; } } } catch (ItemNotFoundException pathNotFound) { errorRecord = new ErrorRecord(pathNotFound.ErrorRecord, pathNotFound); } catch (ProviderNotFoundException providerNotFound) { errorRecord = new ErrorRecord(providerNotFound.ErrorRecord, providerNotFound); } catch (DriveNotFoundException driveNotFound) { errorRecord = new ErrorRecord(driveNotFound.ErrorRecord, driveNotFound); } if (errorRecord != null) ThrowTerminatingError(errorRecord); } } /// <summary> /// Composes a validation error /// </summary> /// <param name="msg"></param> /// <param name="errorId"></param> /// <returns></returns> private ErrorRecord GetValidationError(string msg, string errorId) { var ex = new ValidationMetadataException(msg); var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); return error; } /// <summary> /// Composes a validation error /// </summary> /// <param name="msg"></param> /// <param name="errorId"></param> /// <param name="args"></param> /// <returns></returns> private ErrorRecord GetValidationError(string msg, string errorId, params object[] args) { msg = msg.FormatCurrentCulture(args); var ex = new ValidationMetadataException(msg); var error = new ErrorRecord(ex, errorId, ErrorCategory.InvalidArgument, this); return error; } /// <summary> /// Generate a fully qualified file path /// </summary> /// <param name="path"></param> /// <returns></returns> private string QualifyFilePath(string path) { var resolvedFilePath = PathUtils.ResolveFilePath(path, this, true); return resolvedFilePath; } /// <summary> /// Resets GraphSession environment back to its original state. /// </summary> private void ResetGraphSessionEnvironment() { GraphSession.Instance.Environment = _originalEnvironment; } #region CmdLet LifeCycle protected override void BeginProcessing() { if (Break) { this.Break(); } _graphRequestUserAgent = new RequestUserAgent(this.Host.Version, this.MyInvocation); ValidateParameters(); base.BeginProcessing(); } private async Task ProcessRecordAsync() { using (NoSynchronizationContext) { try { PrepareSession(); using (var client = GetHttpClient()) { ValidateRequestUri(); using (var httpRequestMessage = GetRequest(client, Uri)) { var httpRequestMessageFormatter = new HttpMessageFormatter(httpRequestMessage); FillRequestStream(httpRequestMessage); try { await ReportRequestStatusAsync(httpRequestMessageFormatter); var httpResponseMessage = await GetResponseAsync(client, httpRequestMessage); var httpResponseMessageFormatter = new HttpMessageFormatter(httpResponseMessage); await ReportResponseStatusASync(httpResponseMessageFormatter); var isSuccess = httpResponseMessage.IsSuccessStatusCode; if (ShouldCheckHttpStatus && !isSuccess) { var httpErrorRecord = await GenerateHttpErrorRecordAsync(httpResponseMessageFormatter, httpRequestMessage); ThrowTerminatingError(httpErrorRecord); } await ProcessResponseAsync(httpResponseMessage); } catch (HttpRequestException ex) { var er = new ErrorRecord(ex, ErrorConstants.Codes.InvokeGraphHttpResponseException, ErrorCategory.InvalidOperation, httpRequestMessage); if (ex.InnerException != null) { er.ErrorDetails = new ErrorDetails(ex.InnerException.Message); } ThrowTerminatingError(er); } } } } catch (HttpRequestException httpRequestException) { var errorRecord = new ErrorRecord(httpRequestException, ErrorCategory.ConnectionError.ToString(), ErrorCategory.InvalidResult, null); ThrowTerminatingError(errorRecord); } catch (Exception exception) { var errorRecord = new ErrorRecord(exception, ErrorCategory.NotSpecified.ToString(), ErrorCategory.InvalidOperation, null); ThrowTerminatingError(errorRecord); } } } protected override void ProcessRecord() { base.ProcessRecord(); try { using (var asyncCommandRuntime = new CustomAsyncCommandRuntime(this, _cancellationTokenSource.Token)) { asyncCommandRuntime.Wait(ProcessRecordAsync(), _cancellationTokenSource.Token); } } catch (AggregateException aggregateException) { // unroll the inner exceptions to get the root cause foreach (var innerException in aggregateException.Flatten().InnerExceptions) { var errorRecords = innerException.Data; if (errorRecords.Count > 1) { foreach (DictionaryEntry dictionaryEntry in errorRecords) { WriteError((ErrorRecord)dictionaryEntry.Value); } } else { WriteError(new ErrorRecord(innerException, string.Empty, ErrorCategory.NotSpecified, null)); } } } catch (Exception exception) when (exception as PipelineStoppedException == null || (exception as PipelineStoppedException).InnerException != null) { // Write exception out to error channel. WriteError(new ErrorRecord(exception, string.Empty, ErrorCategory.NotSpecified, null)); } } protected override void EndProcessing() { ResetGraphSessionEnvironment(); base.EndProcessing(); } protected override void StopProcessing() { ResetGraphSessionEnvironment(); _cancellationTokenSource.Cancel(); base.StopProcessing(); } #endregion } }
42.447347
160
0.547367
[ "MIT" ]
JeffBley/msgraph-sdk-powershell
src/Authentication/Authentication/Cmdlets/InvokeMgGraphRequest.cs
51,998
C#
using System; using System.Collections.Generic; using System.Text; namespace Crass.Plugin.ARCGameEngine { public struct IndexEntryHeaderBIN { public UInt32 EntriesCount; } }
16.333333
37
0.729592
[ "BSD-3-Clause" ]
MaiReo/crass-csharp
src/cui/Crass.Plugin.ARCGameEngine/Index/IndexEntryHeaderBIN.cs
198
C#
namespace MechanicGrip.Suits { public class StandardSuit { public static string ClubsName = "Clubs"; public static string SpadesName = "Spades"; public static string HeartsName = "Hearts"; public static string DiamondsName = "Diamonds"; public static char HeartsSymbol = '\u2665'; public static char DiamondsSymbol = '\u2666'; public static char SpadesSymbol = '\u2660'; public static char ClubsSymbol = '\u2663'; public static ISuit Clubs = new Suit(ClubsName, ClubsSymbol); public static ISuit Spades = new Suit(SpadesName, SpadesSymbol); public static ISuit Hearts = new Suit(HeartsName, HeartsSymbol); public static ISuit Diamonds = new Suit(DiamondsName, DiamondsSymbol); } }
37.714286
78
0.670455
[ "MIT" ]
kgiszewski/MechanicGrip
src/MechanicGrip/Suits/StandardSuit.cs
794
C#
using FastReport.Utils; namespace FastReport.Table { partial class TableBase { #region Private Methods /// <summary> /// Does nothing /// </summary> /// <param name="e"></param> partial void DrawDesign(FRPaintEventArgs e); /// <summary> /// Does nothing /// </summary> /// <param name="e"></param> partial void DrawDesign_Borders(FRPaintEventArgs e); /// <summary> /// Does nothing /// </summary> /// <param name="e"></param> partial void DrawDesign_BordersRtl(FRPaintEventArgs e); /// <summary> /// Does nothing /// </summary> /// <param name="e"></param> partial void DrawDesign_SelectedCells(FRPaintEventArgs e); /// <summary> /// Does nothing /// </summary> /// <param name="e"></param> partial void DrawDesign_SelectedCellsRtl(FRPaintEventArgs e); #endregion Private Methods } }
24.853659
69
0.537782
[ "MIT" ]
EasyLOB/FastReport
FastReport.OpenSource/Table/TableBase.Core.cs
1,021
C#
namespace Sdl.Web.Tridion.Templates.R2.Data { /// <summary> /// Represents the settings for <see cref="DataModelBuilder"/> /// </summary> public class DataModelBuilderSettings { /// <summary> /// Gets or sets the depth that Component/Keyword links should be expanded (on CM-side) /// </summary> public int ExpandLinkDepth { get; set; } /// <summary> /// Gets or sets whether XPM metadata should be generated or not. /// </summary> public bool GenerateXpmMetadata { get; set; } /// <summary> /// Gets or sets the Locale which is output as <c>og:locale</c> PageModel Meta. /// </summary> public string Locale { get; set; } } }
29.96
95
0.58478
[ "Apache-2.0" ]
kunalshetye/dxa-content-management
Sdl.Web.Tridion.Templates.R2/Data/DataModelBuilderSettings.cs
751
C#
using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; namespace WebApplication.Data.Migrations { public partial class CreateIdentitySchema : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "AspNetRoles", columns: table => new { Id = table.Column<string>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Name = table.Column<string>(nullable: true), NormalizedName = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetRoles", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetUserTokens", columns: table => new { UserId = table.Column<string>(nullable: false), LoginProvider = table.Column<string>(nullable: false), Name = table.Column<string>(nullable: false), Value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUserTokens", x => new { x.UserId, x.LoginProvider, x.Name }); }); migrationBuilder.CreateTable( name: "AspNetUsers", columns: table => new { Id = table.Column<string>(nullable: false), AccessFailedCount = table.Column<int>(nullable: false), ConcurrencyStamp = table.Column<string>(nullable: true), Email = table.Column<string>(nullable: true), EmailConfirmed = table.Column<bool>(nullable: false), LockoutEnabled = table.Column<bool>(nullable: false), LockoutEnd = table.Column<DateTimeOffset>(nullable: true), NormalizedEmail = table.Column<string>(nullable: true), NormalizedUserName = table.Column<string>(nullable: true), PasswordHash = table.Column<string>(nullable: true), PhoneNumber = table.Column<string>(nullable: true), PhoneNumberConfirmed = table.Column<bool>(nullable: false), SecurityStamp = table.Column<string>(nullable: true), TwoFactorEnabled = table.Column<bool>(nullable: false), UserName = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AspNetUsers", x => x.Id); }); migrationBuilder.CreateTable( name: "AspNetRoleClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Autoincrement", true), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetRoleClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetRoleClaims_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserClaims", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Autoincrement", true), ClaimType = table.Column<string>(nullable: true), ClaimValue = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserClaims", x => x.Id); table.ForeignKey( name: "FK_AspNetUserClaims_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserLogins", columns: table => new { LoginProvider = table.Column<string>(nullable: false), ProviderKey = table.Column<string>(nullable: false), ProviderDisplayName = table.Column<string>(nullable: true), UserId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserLogins", x => new { x.LoginProvider, x.ProviderKey }); table.ForeignKey( name: "FK_AspNetUserLogins_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AspNetUserRoles", columns: table => new { UserId = table.Column<string>(nullable: false), RoleId = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AspNetUserRoles", x => new { x.UserId, x.RoleId }); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetRoles_RoleId", column: x => x.RoleId, principalTable: "AspNetRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_AspNetUserRoles_AspNetUsers_UserId", column: x => x.UserId, principalTable: "AspNetUsers", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "RoleNameIndex", table: "AspNetRoles", column: "NormalizedName"); migrationBuilder.CreateIndex( name: "IX_AspNetRoleClaims_RoleId", table: "AspNetRoleClaims", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserClaims_UserId", table: "AspNetUserClaims", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserLogins_UserId", table: "AspNetUserLogins", column: "UserId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_RoleId", table: "AspNetUserRoles", column: "RoleId"); migrationBuilder.CreateIndex( name: "IX_AspNetUserRoles_UserId", table: "AspNetUserRoles", column: "UserId"); migrationBuilder.CreateIndex( name: "EmailIndex", table: "AspNetUsers", column: "NormalizedEmail"); migrationBuilder.CreateIndex( name: "UserNameIndex", table: "AspNetUsers", column: "NormalizedUserName"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AspNetRoleClaims"); migrationBuilder.DropTable( name: "AspNetUserClaims"); migrationBuilder.DropTable( name: "AspNetUserLogins"); migrationBuilder.DropTable( name: "AspNetUserRoles"); migrationBuilder.DropTable( name: "AspNetUserTokens"); migrationBuilder.DropTable( name: "AspNetRoles"); migrationBuilder.DropTable( name: "AspNetUsers"); } } }
42.199074
109
0.478003
[ "MIT" ]
AGiorgetti/AngularConf2016
WebService/Data/Migrations/00000000000000_CreateIdentitySchema.cs
9,115
C#
#region using System.Collections.Generic; using System.Globalization; using System.Text.RegularExpressions; using static HearthDb.Enums.CardSet; #endregion namespace HearthDb.CardIdGenerator { internal class Helper { internal static readonly Dictionary<string, string> SpecialPrefixes = new Dictionary<string, string> { {"NAX1h_01", "Heroic"}, {"NAX1h_03", "Heroic"}, {"NAX1h_04", "Heroic"}, {"BRMA09_2t", "BRS"}, {"BRMA09_2Ht", "BRS"}, {"BRMA13_3", "BWL"}, {"BRMA13_3H", "BWL"}, {"BRMA17_2", "HiddenLab"}, {"BRMA17_2H", "HiddenLab"}, {"LOEA01_01", "Temple"}, {"LOEA02_01", "Temple"}, {"LOEA02_01h", "Temple"}, {"LOEA04_27", "Uldaman"}, {"LOEA05_01", "Uldaman"}, {"LOEA08_01", "TRC"}, {"LOEA08_01h", "TRC"}, {"LOEA09_1", "TRC"}, {"LOEA09_1H", "TRC"}, {"LOEA10_1", "Hall"}, {"LOEA10_1H", "Hall"}, {"LOEA12_1", "Hall"}, {"LOEA12_1H", "Hall"}, {"LOEA13_1", "Hall"}, {"LOEA13_1H", "Hall"}, {"LOEA14_1", "LOEA14"}, {"LOEA14_1H", "LOEA14"}, {"LOEA15_1", "LOEA15"}, {"LOEA15_1H", "LOEA15"}, {"LOEA16_1", "LOEA16"}, {"LOEA16_17", "LOEA16"}, {"LOEA16_18", "LOEA16"}, {"LOEA16_18H", "LOEA16"}, {"LOEA16_19", "LOEA16"}, {"LOEA16_19H", "LOEA16"}, {"LOEA16_1H", "LOEA16"}, {"LOEA16_21", "LOEA16"}, {"LOEA16_21H", "LOEA16"}, {"LOEA16_22", "LOEA16"}, {"LOEA16_22H", "LOEA16"}, {"LOEA16_23", "LOEA16"}, {"LOEA16_23H", "LOEA16"}, {"LOEA16_24", "LOEA16"}, {"LOEA16_24H", "LOEA16"}, {"LOEA16_25", "LOEA16"}, {"LOEA16_25H", "LOEA16"}, {"LOEA16_26", "LOEA16"}, {"LOEA16_26H", "LOEA16"}, {"LOEA16_27", "LOEA16"}, {"LOEA16_27H", "LOEA16"} }; internal static string GetSetName(CardSet set) { switch(set) { case CardSet.CORE: return "Basic"; case CardSet.EXPERT1: return "Classic"; case CardSet.PROMO: return "Promotion"; case CardSet.FP1: return "CurseOfNaxxramas"; case CardSet.PE1: return "GoblinsVsGnomes"; case CardSet.BRM: return "BlackrockMountain"; case CardSet.TGT: return "TheGrandTournament"; case CardSet.LOE: return "LeagueOfExplorers"; default: return CultureInfo.InvariantCulture.TextInfo.ToTitleCase(set.ToString().ToLower()); } } public static string GetSetAbbreviation(Enums.CardSet set) { switch(set) { case FP1: return "NAXX"; case PE1: return "GVG"; case EXPERT1: return "Classic"; case MISSIONS: return "Missions"; case CORE: return "Basic"; case INVALID: return "Invalid"; case TEST_TEMPORARY: return "Test"; case DEMO: return "Demo"; case NONE: return "None"; case CHEAT: return "Cheat"; case BLANK: return "Blank"; case DEBUG_SP: return "Debug"; case PROMO: return "Promo"; case CREDITS: return "Credits"; case HERO_SKINS: return "HeroSkins"; case TB: return "TavernBrawl"; case SLUSH: return "Slush"; default: return set.ToString(); } } public static string GetBaseId(string id) { if(string.IsNullOrEmpty(id)) return id; if(id.StartsWith("LOE_019t")) return "LOE_079"; var match = Regex.Match(id, @"(?<base>(.*_\d+[hH]?)).*"); return match.Success ? match.Groups["base"].Value : id; } } }
23.103448
102
0.594925
[ "MIT" ]
Phoenixy/Hearthstone
HearthDb.CardIdGenerator/Helper.cs
3,350
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ namespace Microsoft.ServiceFabric.Powershell.Http { using System; using System.Collections.Generic; using System.Management.Automation; using Microsoft.ServiceFabric.Common; /// <summary> /// Deletes the backup policy. /// </summary> [Cmdlet(VerbsCommon.Remove, "SFBackupPolicy")] public partial class RemoveBackupPolicyCmdlet : CommonCmdletBase { /// <summary> /// Gets or sets BackupPolicyName. The name of the backup policy. /// </summary> [Parameter(Mandatory = true, ValueFromPipelineByPropertyName = true, Position = 0)] public string BackupPolicyName { get; set; } /// <summary> /// Gets or sets ServerTimeout. The server timeout for performing the operation in seconds. This timeout specifies the /// time duration that the client is willing to wait for the requested operation to complete. The default value for /// this parameter is 60 seconds. /// </summary> [Parameter(Mandatory = false, Position = 1)] public long? ServerTimeout { get; set; } /// <summary> /// Gets or sets the force flag. If provided, then the destructive action will be performed without asking for /// confirmation prompt. /// </summary> [Parameter(Mandatory = false, Position = 2)] public SwitchParameter Force { get; set; } /// <inheritdoc/> protected override void ProcessRecordInternal() { if (((this.Force != null) && this.Force) || this.ShouldContinue(string.Empty, string.Empty)) { this.ServiceFabricClient.BackupRestore.DeleteBackupPolicyAsync( backupPolicyName: this.BackupPolicyName, serverTimeout: this.ServerTimeout, cancellationToken: this.CancellationToken).GetAwaiter().GetResult(); Console.WriteLine("Success!"); } } } }
41.127273
126
0.600354
[ "MIT" ]
Bhaskers-Blu-Org2/service-fabric-client-dotnet
src/Microsoft.ServiceFabric.Powershell.Http/Generated/RemoveBackupPolicyCmdlet.cs
2,262
C#
using System.Reflection; using System.Runtime.InteropServices; using System.Windows; // 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("EmployeeManager")] [assembly: AssemblyDescription("The Contoso Employee Manager")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Contoso Ltd.")] [assembly: AssemblyProduct("EmployeeManager")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. UpdateAsync the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.714286
96
0.753147
[ "MIT" ]
PacktPublishing/Modernizing-Your-Windows-Applications-with-the-Windows-Apps-SDK-and-WinUI
Chapter07/WPF/EmployeeManager/Properties/AssemblyInfo.cs
2,227
C#
using SporeMods.Core; using SporeMods.Core.Injection; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Windows; namespace SporeMods.CommonUI.Localization { public class LanguageManager : NotifyPropertyChangedBase { public static LanguageManager Instance { get; private set; } static LanguageManager() { Instance = new LanguageManager(); Instance.FinishInit(); } static Language _canadianEnglish = null; public static Language CanadianEnglish { get => _canadianEnglish; private set => _canadianEnglish = value; } const string CANADIAN_ENG_ID = "en-ca"; const string CANADIAN_ENG_RES_NAME = Language.LANG_RESOURCE_START + CANADIAN_ENG_ID + ".txt"; List<string> _resNames; List<string> _availableLanguageCodes = new List<string>() { CANADIAN_ENG_ID }; private LanguageManager() { var allResNames = Assembly.GetExecutingAssembly().GetManifestResourceNames(); _resNames = allResNames.Where(x => x.StartsWith(Language.LANG_RESOURCE_START)).ToList(); //string canadianEngRes = Language.LANG_RESOURCE_START + $"{CANADIAN_ENGLISH}.txt"; _resNames.Remove(CANADIAN_ENG_RES_NAME); CanadianEnglish = new Language(CANADIAN_ENG_RES_NAME); Languages.Add(CanadianEnglish); foreach (string resName in _resNames) { var lang = new Language(resName); Languages.Add(lang); _availableLanguageCodes.Add(lang.LanguageCode); } //_resNames.Add(CANADIAN_ENGLISH_RES); if (Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName).Equals(CrossProcess.MGR_EXE, StringComparison.OrdinalIgnoreCase)) { string hotReloadFolderPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "SMM"); string hotReloadPath = Path.Combine(hotReloadFolderPath, "te-st.txt"); if (File.Exists(hotReloadPath)) { Language hotReload = new Language(hotReloadPath); Languages.Add(hotReload); CurrentLanguage = hotReload; FileSystemWatcher hotReloadWatcher = new FileSystemWatcher(hotReloadFolderPath, "*.txt"); hotReloadWatcher.Changed += (s, e) => Application.Current.Dispatcher.Invoke(() => { if (e.FullPath.Equals(hotReloadPath, StringComparison.OrdinalIgnoreCase)) { Languages.Remove(hotReload); if (File.Exists(hotReloadPath)) { hotReload = new Language(hotReloadPath); Languages.Add(hotReload); CurrentLanguage = hotReload; } } }); hotReloadWatcher.EnableRaisingEvents = true; } else { string ident = GetRoundedSystemLanguageIdentifier(); var lang = Languages.FirstOrDefault(x => x.LanguageCode.Equals(ident, StringComparison.OrdinalIgnoreCase)); if (lang == default(Language)) lang = CanadianEnglish; CurrentLanguage = lang; } } _writeCurrentLanguage = true; /*if (Process.GetCurrentProcess().MainModule.FileName.Contains("servant", StringComparison.OrdinalIgnoreCase)) { MessageBox.Show(Settings.CurrentLanguageCode); }*/ //string currentCode = Settings.CurrentLanguageCode; SporeLauncher.GetLocalizedString = GetLocalizedText; Core.Mods.XmlModIdentityV1.GetLocalizedString = GetLocalizedText; } void FinishInit() { } static readonly string[] LANGUAGE_ROUNDING_ALLOWED_GROUPS = { "en", "es", "ca" }; string GetRoundedSystemLanguageIdentifier() { string langCode = CultureInfo.CurrentUICulture.Name.ToLowerInvariant(); var target = _availableLanguageCodes.FirstOrDefault(x => x.Equals(langCode, StringComparison.OrdinalIgnoreCase)); if (target != default(string)) { string langGroup = langCode.Split('-')[0]; if (LANGUAGE_ROUNDING_ALLOWED_GROUPS.Any(x => x.Equals(langGroup, StringComparison.OrdinalIgnoreCase))) { langCode = _availableLanguageCodes.FirstOrDefault(x => x.Split('-')[0].Equals(langCode, StringComparison.OrdinalIgnoreCase)); } } if (target == default(string)) target = CANADIAN_ENG_ID; return target; } /*string _osLangIdentifier = null; string zGetCurrentLanguageIdentifier() { if (_osLangIdentifier == null) { string langCode = CultureInfo.CurrentUICulture.Name.ToLowerInvariant(); if (!Languages.Any(x => x.LanguageCode.Equals(langCode, StringComparison.OrdinalIgnoreCase))) { string langGroup = langCode.Split('-')[0]; langCode = null; if (LANGUAGE_ROUNDING_ALLOWED_GROUPS.Any(x => x.Equals(langGroup, StringComparison.OrdinalIgnoreCase))) { // Try to get one from the same group. If user has en-us, try to set en-ca, etc langCode = Languages.FirstOrDefault(x => x.LanguageCode.Split('-')[0].Equals(langGroup, StringComparison.OrdinalIgnoreCase)).LanguageCode; } } if (langCode.IsNullOrEmptyOrWhiteSpace()) langCode = "en-ca"; _osLangIdentifier = langCode; } string ret = Settings.GetElementValue(_currentLanguageCode, _osLangIdentifier); return Languages.Any(x => x.LanguageCode.Equals(ret, StringComparison.OrdinalIgnoreCase)) ? ret : "en-ca"; }*/ /*bool zTryGetPreferredLanguageForOS(out Language language) { Language lang = null; string langCode = CultureInfo.CurrentUICulture.Name.ToLowerInvariant(); if (!Languages.Any(x => { if (x.LanguageCode.Equals(langCode, StringComparison.OrdinalIgnoreCase)) { lang = x; return true; } return false; })) { string langGroup = langCode.Split('-')[0]; if (LANGUAGE_ROUNDING_ALLOWED_GROUPS.Any(x => x.Equals(langGroup, StringComparison.OrdinalIgnoreCase))) { // Try to get one from the same group. If user has en-us, try to set en-ca, etc Languages.FirstOrDefault((x) => { string code = x.LanguageCode; if (code.Split('-')[0].Equals(langGroup, StringComparison.OrdinalIgnoreCase)) { lang = x; return true; } return false; }); } } if (langCode == null) langCode = "en-ca"; language = lang; return language != null; }*/ ObservableCollection<Language> _languages = new ObservableCollection<Language>(); public ObservableCollection<Language> Languages { get => _languages; set { _languages = value; NotifyPropertyChanged(); } } static readonly string _currentLanguageCode = "CurrentLanguageCode"; Language _currentLanguage = null; bool _writeCurrentLanguage = false; public Language CurrentLanguage { get => _currentLanguage; set { _currentLanguage = value; if ((value != null) && (!value.IsExternalLanguage) && _writeCurrentLanguage) Settings.SetElementValue(_currentLanguageCode, value.LanguageCode); TryRefreshWpfResources(); NotifyPropertyChanged(); } } ResourceDictionary _prevLangDictionary = null; public void TryRefreshWpfResources() { var currentApp = Application.Current; if (currentApp != null) { var langContents = CurrentLanguage.Dictionary; if (currentApp.Resources.MergedDictionaries.Contains(_prevLangDictionary)) { int prevIndex = currentApp.Resources.MergedDictionaries.IndexOf(_prevLangDictionary); currentApp.Resources.MergedDictionaries.RemoveAt(prevIndex); //currentApp.Resources.MergedDictionaries.Insert(prevIndex, langContents); } //else currentApp.Resources.MergedDictionaries.Add(langContents); _prevLangDictionary = langContents; } } public string GetLocalizedText(string key) { //string key = strKey.ToString().Replace('-', '!'); /*if (Application.Current != null) { var res = Application.Current.TryFindResource(key); if (res != null) value = res.ToString(); } else */ if (CurrentLanguage == null) return "(NO LANGUAGE SELECTED) (NOT LOCALIZED)"; var dict = _currentLanguage.Dictionary; if (dict.Contains(key)) { object res = dict[key]; if ((res == null) && (dict.MergedDictionaries.Count > 0)) res = dict.MergedDictionaries[0][key]; if (res != null) return res.ToString(); } return $"{key} (NOT LOCALIZED)"; } } }
36.97619
163
0.533622
[ "MIT" ]
plencka/Spore-Mod-Manager
SporeMods.CommonUI/Localization/LanguageManager.cs
10,873
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.AzureStack.Management.Storage.Admin { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// StorageAccountsOperations operations. /// </summary> internal partial class StorageAccountsOperations : IServiceOperations<StorageAdminClient>, IStorageAccountsOperations { /// <summary> /// Initializes a new instance of the StorageAccountsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal StorageAccountsOperations(StorageAdminClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the StorageAdminClient /// </summary> public StorageAdminClient Client { get; private set; } /// <summary> /// Returns a list of storage accounts. /// </summary> /// <param name='location'> /// Resource location. /// </param> /// <param name='filter'> /// Filter string /// </param> /// <param name='summary'> /// Switch for whether summary or detailed information is returned. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<StorageAccount>>> ListWithHttpMessagesAsync(string location, string filter = default(string), bool? summary = default(bool?), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("filter", filter); tracingParameters.Add("summary", summary); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Storage.Admin/locations/{location}/storageaccounts").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter))); } if (summary != null) { _queryParameters.Add(string.Format("summary={0}", System.Uri.EscapeDataString(Rest.Serialization.SafeJsonConvert.SerializeObject(summary, Client.SerializationSettings).Trim('"')))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // add Prefer: odata.maxpagesize=1000 for paging if (_httpRequest.Headers.Contains("Prefer")) { _httpRequest.Headers.Remove("Prefer"); } _httpRequest.Headers.TryAddWithoutValidation("Prefer", "odata.maxpagesize=1000"); // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<StorageAccount>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<StorageAccount>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Returns the requested storage account. /// </summary> /// <param name='location'> /// Resource location. /// </param> /// <param name='accountId'> /// Internal storage account ID, which is not visible to tenant. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<StorageAccount>> GetWithHttpMessagesAsync(string location, string accountId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (accountId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("accountId", accountId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Storage.Admin/locations/{location}/storageaccounts/{accountId}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{accountId}", System.Uri.EscapeDataString(accountId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<StorageAccount>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<StorageAccount>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Undelete a deleted storage account with new account name if the a new name /// is provided. /// </summary> /// <param name='location'> /// Resource location. /// </param> /// <param name='accountId'> /// Internal storage account ID, which is not visible to tenant. /// </param> /// <param name='newAccountName'> /// New storage account name when doing undelete storage account operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<UndeleteStorageAccount>> UndeleteWithHttpMessagesAsync(string location, string accountId, string newAccountName = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse<UndeleteStorageAccount> _response = await BeginUndeleteWithHttpMessagesAsync(location, accountId, newAccountName, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Start reclaim storage capacity on deleted storage objects. /// </summary> /// <param name='location'> /// Resource location. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse> ReclaimStorageCapacityWithHttpMessagesAsync(string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send request AzureOperationResponse _response = await BeginReclaimStorageCapacityWithHttpMessagesAsync(location, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPostOrDeleteOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Undelete a deleted storage account with new account name if the a new name /// is provided. /// </summary> /// <param name='location'> /// Resource location. /// </param> /// <param name='accountId'> /// Internal storage account ID, which is not visible to tenant. /// </param> /// <param name='newAccountName'> /// New storage account name when doing undelete storage account operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<UndeleteStorageAccount>> BeginUndeleteWithHttpMessagesAsync(string location, string accountId, string newAccountName = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (accountId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountId"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("accountId", accountId); tracingParameters.Add("newAccountName", newAccountName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginUndelete", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Storage.Admin/locations/{location}/storageaccounts/{accountId}/undelete").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); _url = _url.Replace("{accountId}", System.Uri.EscapeDataString(accountId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (newAccountName != null) { _queryParameters.Add(string.Format("newAccountName={0}", System.Uri.EscapeDataString(newAccountName))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<UndeleteStorageAccount>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<UndeleteStorageAccount>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Start reclaim storage capacity on deleted storage objects. /// </summary> /// <param name='location'> /// Resource location. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> BeginReclaimStorageCapacityWithHttpMessagesAsync(string location, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (location == null) { throw new ValidationException(ValidationRules.CannotBeNull, "location"); } if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("location", location); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginReclaimStorageCapacity", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/providers/Microsoft.Storage.Admin/locations/{location}/reclaimStorageCapacity").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{location}", System.Uri.EscapeDataString(location)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 202) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Returns a list of storage accounts. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<StorageAccount>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing var _baseUrl = Client.BaseUri.AbsoluteUri; bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), _url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // add Prefer: odata.maxpagesize=1000 for paging if (_httpRequest.Headers.Contains("Prefer")) { _httpRequest.Headers.Remove("Prefer"); } _httpRequest.Headers.TryAddWithoutValidation("Prefer", "odata.maxpagesize=1000"); // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorResponse _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<StorageAccount>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<StorageAccount>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
45.752178
305
0.56648
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/azurestack/Microsoft.AzureStack.Management.Storage.Admin/src/Generated/StorageAccountsOperations.cs
47,262
C#
/* * Copyright 2019-2021 Robbyxp1 @ github.com * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this * file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under * the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF * ANY KIND, either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ using System; using OpenTK.Graphics.OpenGL4; namespace GLOFC.GL4 { ///<summary> A render buffer can be used as a target for GLFrameBuffer instead of a texture</summary> [System.Diagnostics.DebuggerDisplay("Id {Id} {Width} {Height} {Samples}")] public class GLRenderBuffer : IDisposable { /// <summary>GL ID</summary> public int Id { get; private set; } = -1; /// <summary> Width of buffer in pixels</summary> public int Width { get; protected set; } = 0; // Set when colour texture attaches /// <summary> Height of buffer in pixels </summary> public int Height { get; protected set; } = 1; /// <summary> Sample depth for multisample buffers</summary> public int Samples { get; protected set; } = 0; /// <summary> Construct a buffer </summary> public GLRenderBuffer() { Id = GL.GenRenderbuffer(); GLStatics.RegisterAllocation(typeof(GLRenderBuffer)); } /// <summary> Allocate a non multisampled buffer of width and height, and bind to target Renderbuffer </summary> public void Allocate(RenderbufferStorage storage, int width, int height) { Width = width; Height = height; GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, Id); GL.NamedRenderbufferStorage(Id, storage, Width, Height); System.Diagnostics.Debug.Assert(GLOFC.GLStatics.CheckGL(out string glasserterr), glasserterr); } /// <summary> Allocate a multisample buffer of width, height, and samples depth, and bind to target Renderbuffer </summary> public void AllocateMultisample(RenderbufferStorage storage, int width, int height, int samples) { Width = width; Height = height; Samples = samples; GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, Id); GL.NamedRenderbufferStorageMultisample(Id,Samples, storage, Width, Height); System.Diagnostics.Debug.Assert(GLOFC.GLStatics.CheckGL(out string glasserterr), glasserterr); } /// <summary> Unbind the buffer from the render buffer target </summary> public static void UnBind() { GL.BindRenderbuffer(RenderbufferTarget.Renderbuffer, 0); } /// <summary> From the any type of ImageTarget into this</summary> public void CopyFrom(int srcid, ImageTarget srctype, int srcmiplevel, int sx, int sy, int sz, int dx, int dy, int width, int height) { GL.CopyImageSubData(srcid, srctype, srcmiplevel, sx, sy, sz, Id, ImageTarget.Renderbuffer, 0, dx, dy, 0, width, height, 1); System.Diagnostics.Debug.Assert(GLOFC.GLStatics.CheckGL(out string glasserterr), glasserterr); } /// <summary> Dispose of the buffer </summary> public void Dispose() // you can double dispose. { if (Id != -1) { GL.DeleteRenderbuffer(Id); GLStatics.RegisterDeallocation(typeof(GLRenderBuffer)); Id = -1; } else System.Diagnostics.Trace.WriteLine($"OFC Warning - double disposing of ${this.GetType().FullName}"); } } }
44.955056
147
0.623344
[ "Apache-2.0" ]
OpenTK-Foundation-Classes/OFC
OFC/GL4/BasicTypes/GLRenderBuffer.cs
3,915
C#
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AntChain.SDK.BOT.Models { // 设备类型 public class Device : TeaModel { // 设备实体唯一Id [NameInMap("device_id")] [Validation(Required=true)] public string DeviceId { get; set; } // 数据模型Id [NameInMap("device_data_model_id")] [Validation(Required=true)] public string DeviceDataModelId { get; set; } // 场景码 [NameInMap("scene")] [Validation(Required=true)] public string Scene { get; set; } // imei号 [NameInMap("device_imei")] [Validation(Required=true)] public string DeviceImei { get; set; } // 设备名称 [NameInMap("device_name")] [Validation(Required=false)] public string DeviceName { get; set; } // 设备厂商名称 [NameInMap("corp_name")] [Validation(Required=false)] public string CorpName { get; set; } // 设备ICCID // // [NameInMap("device_iccid")] [Validation(Required=false)] public string DeviceIccid { get; set; } // 设备扩展信息 [NameInMap("extra_info")] [Validation(Required=false)] public string ExtraInfo { get; set; } // 设备链上Id [NameInMap("chain_device_id")] [Validation(Required=true)] public string ChainDeviceId { get; set; } // 上链哈希 [NameInMap("tx_hash")] [Validation(Required=true)] public string TxHash { get; set; } // 上链时间 [NameInMap("tx_time")] [Validation(Required=true)] public long? TxTime { get; set; } // 设备类型编码,必填,对应资管平台中的设备类型 // // 枚举值: // // 车辆 1000 // 车辆 四轮车 1001 // 车辆 四轮车 纯电四轮车 1002 // 车辆 四轮车 混动四轮车 1003 // 车辆 四轮车 燃油四轮车 1004 // 车辆 两轮车 1011 // 车辆 两轮车 两轮单车 1012 // 车辆 两轮车 两轮助力车 1013 // // 换电柜 2000 // 换电柜 二轮车换电柜 2001 // // 电池 3000 // 电池 磷酸铁电池 3001 // 电池 三元锂电池 3002 // // 回收设备 4000 // // 垃圾分类回收 4001 // // 洗车机 5000 [NameInMap("device_type_code")] [Validation(Required=true)] public long? DeviceTypeCode { get; set; } // 单价 [NameInMap("initial_price")] [Validation(Required=true)] public long? InitialPrice { get; set; } // 投放时间 [NameInMap("release_time")] [Validation(Required=true, Pattern="\\d{4}[-]\\d{1,2}[-]\\d{1,2}[T]\\d{2}:\\d{2}:\\d{2}([Z]|([\\.]\\d{1,9})?[\\+]\\d{2}[\\:]?\\d{2})")] public string ReleaseTime { get; set; } // 出厂时间 [NameInMap("factory_time")] [Validation(Required=true, Pattern="\\d{4}[-]\\d{1,2}[-]\\d{1,2}[T]\\d{2}:\\d{2}:\\d{2}([Z]|([\\.]\\d{1,9})?[\\+]\\d{2}[\\:]?\\d{2})")] public string FactoryTime { get; set; } // 设备状态,取值范围:NORMAL、OFFLINE、UNREGISTER [NameInMap("device_status")] [Validation(Required=false)] public string DeviceStatus { get; set; } } }
26.278689
143
0.509981
[ "MIT" ]
alipay/antchain-openapi-prod-sdk
bot/csharp/core/Models/Device.cs
3,602
C#
using System.Windows.Forms; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Windows; using System.Windows.Controls; using System.ComponentModel; using DevExpress.Mvvm.UI.Interactivity; using DevExpress.Mvvm.UI.Native; namespace DevExpress.Mvvm.UI.Native { public interface ISaveFileDialog : IFileDialog { bool CreatePrompt { get; set; } bool OverwritePrompt { get; set; } } } namespace DevExpress.Mvvm.UI { [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)] [TargetType(typeof(System.Windows.Controls.UserControl)), TargetType(typeof(Window))] public class SaveFileDialogService : FileDialogServiceBase, ISaveFileDialogService { protected class SaveFileDialogAdapter : FileDialogAdapter<SaveFileDialog>, ISaveFileDialog { public SaveFileDialogAdapter(SaveFileDialog fileDialog) : base(fileDialog) { } bool ISaveFileDialog.CreatePrompt { get { return fileDialog.CreatePrompt; } set { fileDialog.CreatePrompt = value; } } bool ISaveFileDialog.OverwritePrompt { get { return fileDialog.OverwritePrompt; } set { fileDialog.OverwritePrompt = value; } } } public static readonly DependencyProperty CreatePromptProperty = DependencyProperty.Register("CreatePrompt", typeof(bool), typeof(SaveFileDialogService), new PropertyMetadata(false)); public static readonly DependencyProperty OverwritePromptProperty = DependencyProperty.Register("OverwritePrompt", typeof(bool), typeof(SaveFileDialogService), new PropertyMetadata(true)); public static readonly DependencyProperty DefaultExtProperty = DependencyProperty.Register("DefaultExt", typeof(string), typeof(SaveFileDialogService), new PropertyMetadata(string.Empty)); public static readonly DependencyProperty FilterProperty = DependencyProperty.Register("Filter", typeof(string), typeof(SaveFileDialogService), new PropertyMetadata(string.Empty)); public static readonly DependencyProperty FilterIndexProperty = DependencyProperty.Register("FilterIndex", typeof(int), typeof(SaveFileDialogService), new PropertyMetadata(1)); public bool CreatePrompt { get { return (bool)GetValue(CreatePromptProperty); } set { SetValue(CreatePromptProperty, value); } } public bool OverwritePrompt { get { return (bool)GetValue(OverwritePromptProperty); } set { SetValue(OverwritePromptProperty, value); } } public string DefaultExt { get { return (string)GetValue(DefaultExtProperty); } set { SetValue(DefaultExtProperty, value); } } public string Filter { get { return (string)GetValue(FilterProperty); } set { SetValue(FilterProperty, value); } } public int FilterIndex { get { return (int)GetValue(FilterIndexProperty); } set { SetValue(FilterIndexProperty, value); } } ISaveFileDialog SaveFileDialog { get { return (ISaveFileDialog)GetFileDialog(); } } public SaveFileDialogService() { CheckFileExists = false; } protected override IFileDialog CreateFileDialogAdapter() { return new SaveFileDialogAdapter(new SaveFileDialog()); } protected override void InitFileDialog() { SaveFileDialog.CreatePrompt = CreatePrompt; SaveFileDialog.OverwritePrompt = OverwritePrompt; SaveFileDialog.FileName = DefaultFileName; SaveFileDialog.DefaultExt = DefaultExt; SaveFileDialog.Filter = Filter; SaveFileDialog.FilterIndex = FilterIndex; } protected override List<object> GetFileInfos() { List<object> res = new List<object>(); foreach(string fileName in SaveFileDialog.FileNames) res.Add(FileInfoWrapper.Create(fileName)); return res; } IFileInfo ISaveFileDialogService.File { get { return (IFileInfo)GetFiles().FirstOrDefault(); } } bool ISaveFileDialogService.ShowDialog(Action<CancelEventArgs> fileOK, string directoryName, string fileName) { if(directoryName != null) InitialDirectory = directoryName; if(fileName != null) DefaultFileName = fileName; var res = Show(fileOK); FilterIndex = SaveFileDialog.FilterIndex; return res; } } }
46.888889
137
0.668246
[ "MIT" ]
QuinnBryant/DevExpress.Mvvm.Free
DevExpress.Mvvm.UI/Services/SaveFileDialogService.cs
4,642
C#
namespace formulate.app.Forms.Fields.ExtendedRadioButtonList { /// <summary> /// An individual item used by <see cref="ExtendedRadioButtonListField"/>. /// </summary> public class ExtendedRadioButtonListItem { /// <summary> /// Gets or sets a value indicating whether this item is selected. /// </summary> public bool Selected { get; set; } /// <summary> /// Gets or sets the primary. /// </summary> public string Primary { get; set; } /// <summary> /// Gets or sets the secondary. /// </summary> public string Secondary { get; set; } } }
27.916667
78
0.559701
[ "MIT" ]
rhythmagency/formulate
src/formulate.app/Forms/Fields/ExtendedRadioButtonList/ExtendedRadioButtonListItem.cs
672
C#
using System; using System.Collections.Generic; using System.Linq; class M { static int[] Read() => Console.ReadLine().Split().Select(int.Parse).ToArray(); static void Main() { var h = Read(); int d = h[0], l = h[1], n = h[2]; var c = Read(); var people = new int[n].Select(_ => Read()).ToArray(); var dishDays = new List<int>[100001]; for (int i = 0; i < d; i++) { var ds = dishDays[c[i]]; if (ds == null) dishDays[c[i]] = ds = new List<int>(); ds.Add(i + 1); } for (int i = 0; i <= 100000; i++) { var ds = dishDays[i]; if (ds == null) continue; ds.AddRange(ds.Select(x => x + d).ToArray()); } // 何回目に好みの料理を食べられるか。 var dishCounts = new List<int>[100001]; for (int i = 0; i <= 100000; i++) { var ds = dishDays[i]; if (ds == null) continue; var dsc = ds.Count / 2; dishCounts[i] = new List<int> { (ds[dsc] - ds[dsc - 1] + l - 1) / l }; for (int j = 1; j < ds.Count; j++) dishCounts[i].Add(dishCounts[i].Last() + (ds[j] - ds[j - 1] + l - 1) / l); } int GetCount(int[] p) { int k = p[0], f = p[1], t = p[2], r = 0; var days = dishDays[k]; // 好みの料理が提供されない場合。 if (days == null) return r; var likes = days.Count / 2; var periodCount = dishCounts[k].Last() / 2; // 初めて好みの料理を食べる日まで移動します。 var i = days.BinarySearch(f); if (i < 0) { t -= (days[i = ~i] - f + l - 1) / l; i %= likes; } if (t <= 0) return r; // D 日周期を繰り返します。 r += t / periodCount * likes; t %= periodCount; if (t <= 0) return r; // 最後の周回。 t--; r++; if (t <= 0) return r; var j = dishCounts[k].BinarySearch(dishCounts[k][i] + t); if (j < 0) j = ~j - 1; return r + j - i; } Console.WriteLine(string.Join("\n", people.Select(GetCount))); } }
23.831169
80
0.501907
[ "MIT" ]
sakapon/AtCoder-Contests
CSharp/PAST/PAST202004/M.cs
1,977
C#
// Simple Scroll-Snap // Version: 1.2.0 // Author: Daniel Lochner using System; using UnityEngine; using UnityEngine.UI; namespace DanielLochner.Assets.SimpleScrollSnap { public class DynamicContentController : MonoBehaviour { #region Fields [SerializeField] protected GameObject panel, toggle, addInput, removeInput; private float toggleWidth; private SimpleScrollSnap sss; #endregion #region Methods private void Awake() { sss = GetComponent<SimpleScrollSnap>(); toggleWidth = toggle.GetComponent<RectTransform>().sizeDelta.x * (Screen.width / 2048f); ; } public void AddToFront() { Add(0); } public void AddToBack() { Add(sss.NumberOfPanels); } public void AddAtIndex() { int index = Convert.ToInt32(addInput.GetComponent<InputField>().text); Add(index); } private void Add(int index) { //Pagination Instantiate(toggle, sss.pagination.transform.position + new Vector3(toggleWidth * (sss.NumberOfPanels + 1), 0, 0), Quaternion.identity, sss.pagination.transform); sss.pagination.transform.position -= new Vector3(toggleWidth / 2f, 0, 0); //Panel panel.GetComponent<Image>().color = new Color(UnityEngine.Random.Range(0, 255) / 255f, UnityEngine.Random.Range(0, 255) / 255f, UnityEngine.Random.Range(0, 255) / 255f); sss.Add(panel, index); } public void RemoveFromFront() { Remove(0); } public void RemoveFromBack() { if (sss.NumberOfPanels > 0) { Remove(sss.NumberOfPanels - 1); } else { Remove(0); } } public void RemoveAtIndex() { int index = Convert.ToInt32(removeInput.GetComponent<InputField>().text); Remove(index); } private void Remove(int index) { if (sss.NumberOfPanels > 0) { //Pagination DestroyImmediate(sss.pagination.transform.GetChild(sss.NumberOfPanels - 1).gameObject); sss.pagination.transform.position += new Vector3(toggleWidth / 2f, 0, 0); //Panel sss.Remove(index); } } #endregion } }
29.186047
181
0.544622
[ "Unlicense" ]
23SAMY23/Drift-Into-Space
Drift Into Space/Assets/Simple Scroll-Snap/Examples/Example 5 (Dynamic Content)/Scripts/DynamicContentController.cs
2,512
C#
using System; using System.ComponentModel; namespace MsSystem.Web.Areas.WF.ViewModel { public class FormPageDto { public Guid FormId { get; set; } public string FormName { get; set; } /// <summary> /// 流程名称 /// </summary> public string FlowName { get; set; } public int FormType { get; set; } public long CreateTime { get; set; } } public class FormDetailDto { public Guid FormId { get; set; } public string FormName { get; set; } public int FormType { get; set; } public string Content { get; set; } public string FormUrl { get; set; } public string CreateUserId { get; set; } } }
25.75
48
0.568655
[ "MIT" ]
SpoonySeedLSP/BPM-ServiceAndWebApps
src/Web/MVC/Controllers/MsSystem.Web.Areas.WF/ViewModel/FormDto.cs
731
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Security.Claims; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; namespace Microsoft.AspNetCore.Identity.EntityFrameworkCore; /// <summary> /// Creates a new instance of a persistence store for roles. /// </summary> /// <typeparam name="TRole">The type of the class representing a role</typeparam> public class RoleStore<TRole> : RoleStore<TRole, DbContext, string> where TRole : IdentityRole<string> { /// <summary> /// Constructs a new instance of <see cref="RoleStore{TRole}"/>. /// </summary> /// <param name="context">The <see cref="DbContext"/>.</param> /// <param name="describer">The <see cref="IdentityErrorDescriber"/>.</param> public RoleStore(DbContext context, IdentityErrorDescriber describer = null) : base(context, describer) { } } /// <summary> /// Creates a new instance of a persistence store for roles. /// </summary> /// <typeparam name="TRole">The type of the class representing a role.</typeparam> /// <typeparam name="TContext">The type of the data context class used to access the store.</typeparam> public class RoleStore<TRole, TContext> : RoleStore<TRole, TContext, string> where TRole : IdentityRole<string> where TContext : DbContext { /// <summary> /// Constructs a new instance of <see cref="RoleStore{TRole, TContext}"/>. /// </summary> /// <param name="context">The <see cref="DbContext"/>.</param> /// <param name="describer">The <see cref="IdentityErrorDescriber"/>.</param> public RoleStore(TContext context, IdentityErrorDescriber describer = null) : base(context, describer) { } } /// <summary> /// Creates a new instance of a persistence store for roles. /// </summary> /// <typeparam name="TRole">The type of the class representing a role.</typeparam> /// <typeparam name="TContext">The type of the data context class used to access the store.</typeparam> /// <typeparam name="TKey">The type of the primary key for a role.</typeparam> public class RoleStore<TRole, TContext, TKey> : RoleStore<TRole, TContext, TKey, IdentityUserRole<TKey>, IdentityRoleClaim<TKey>>, IQueryableRoleStore<TRole>, IRoleClaimStore<TRole> where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> where TContext : DbContext { /// <summary> /// Constructs a new instance of <see cref="RoleStore{TRole, TContext, TKey}"/>. /// </summary> /// <param name="context">The <see cref="DbContext"/>.</param> /// <param name="describer">The <see cref="IdentityErrorDescriber"/>.</param> public RoleStore(TContext context, IdentityErrorDescriber describer = null) : base(context, describer) { } } /// <summary> /// Creates a new instance of a persistence store for roles. /// </summary> /// <typeparam name="TRole">The type of the class representing a role.</typeparam> /// <typeparam name="TContext">The type of the data context class used to access the store.</typeparam> /// <typeparam name="TKey">The type of the primary key for a role.</typeparam> /// <typeparam name="TUserRole">The type of the class representing a user role.</typeparam> /// <typeparam name="TRoleClaim">The type of the class representing a role claim.</typeparam> public class RoleStore<TRole, TContext, TKey, TUserRole, TRoleClaim> : IQueryableRoleStore<TRole>, IRoleClaimStore<TRole> where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> where TContext : DbContext where TUserRole : IdentityUserRole<TKey>, new() where TRoleClaim : IdentityRoleClaim<TKey>, new() { /// <summary> /// Constructs a new instance of <see cref="RoleStore{TRole, TContext, TKey, TUserRole, TRoleClaim}"/>. /// </summary> /// <param name="context">The <see cref="DbContext"/>.</param> /// <param name="describer">The <see cref="IdentityErrorDescriber"/>.</param> public RoleStore(TContext context, IdentityErrorDescriber describer = null) { if (context == null) { throw new ArgumentNullException(nameof(context)); } Context = context; ErrorDescriber = describer ?? new IdentityErrorDescriber(); } private bool _disposed; /// <summary> /// Gets the database context for this store. /// </summary> public virtual TContext Context { get; private set; } /// <summary> /// Gets or sets the <see cref="IdentityErrorDescriber"/> for any error that occurred with the current operation. /// </summary> public IdentityErrorDescriber ErrorDescriber { get; set; } /// <summary> /// Gets or sets a flag indicating if changes should be persisted after CreateAsync, UpdateAsync and DeleteAsync are called. /// </summary> /// <value> /// True if changes should be automatically persisted, otherwise false. /// </value> public bool AutoSaveChanges { get; set; } = true; /// <summary>Saves the current store.</summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> protected virtual async Task SaveChanges(CancellationToken cancellationToken) { if (AutoSaveChanges) { await Context.SaveChangesAsync(cancellationToken); } } /// <summary> /// Creates a new role in a store as an asynchronous operation. /// </summary> /// <param name="role">The role to create in the store.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous query.</returns> public virtual async Task<IdentityResult> CreateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } Context.Add(role); await SaveChanges(cancellationToken); return IdentityResult.Success; } /// <summary> /// Updates a role in a store as an asynchronous operation. /// </summary> /// <param name="role">The role to update in the store.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous query.</returns> public virtual async Task<IdentityResult> UpdateAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } Context.Attach(role); role.ConcurrencyStamp = Guid.NewGuid().ToString(); Context.Update(role); try { await SaveChanges(cancellationToken); } catch (DbUpdateConcurrencyException) { return IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure()); } return IdentityResult.Success; } /// <summary> /// Deletes a role from the store as an asynchronous operation. /// </summary> /// <param name="role">The role to delete from the store.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that represents the <see cref="IdentityResult"/> of the asynchronous query.</returns> public virtual async Task<IdentityResult> DeleteAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } Context.Remove(role); try { await SaveChanges(cancellationToken); } catch (DbUpdateConcurrencyException) { return IdentityResult.Failed(ErrorDescriber.ConcurrencyFailure()); } return IdentityResult.Success; } /// <summary> /// Gets the ID for a role from the store as an asynchronous operation. /// </summary> /// <param name="role">The role whose ID should be returned.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the ID of the role.</returns> public virtual Task<string> GetRoleIdAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } return Task.FromResult(ConvertIdToString(role.Id)); } /// <summary> /// Gets the name of a role from the store as an asynchronous operation. /// </summary> /// <param name="role">The role whose name should be returned.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the name of the role.</returns> public virtual Task<string> GetRoleNameAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } return Task.FromResult(role.Name); } /// <summary> /// Sets the name of a role in the store as an asynchronous operation. /// </summary> /// <param name="role">The role whose name should be set.</param> /// <param name="roleName">The name of the role.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task SetRoleNameAsync(TRole role, string roleName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } role.Name = roleName; return Task.CompletedTask; } /// <summary> /// Converts the provided <paramref name="id"/> to a strongly typed key object. /// </summary> /// <param name="id">The id to convert.</param> /// <returns>An instance of <typeparamref name="TKey"/> representing the provided <paramref name="id"/>.</returns> public virtual TKey ConvertIdFromString(string id) { if (id == null) { return default(TKey); } return (TKey)TypeDescriptor.GetConverter(typeof(TKey)).ConvertFromInvariantString(id); } /// <summary> /// Converts the provided <paramref name="id"/> to its string representation. /// </summary> /// <param name="id">The id to convert.</param> /// <returns>An <see cref="string"/> representation of the provided <paramref name="id"/>.</returns> public virtual string ConvertIdToString(TKey id) { if (id.Equals(default(TKey))) { return null; } return id.ToString(); } /// <summary> /// Finds the role who has the specified ID as an asynchronous operation. /// </summary> /// <param name="id">The role ID to look for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that result of the look up.</returns> public virtual Task<TRole> FindByIdAsync(string id, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); var roleId = ConvertIdFromString(id); return Roles.FirstOrDefaultAsync(u => u.Id.Equals(roleId), cancellationToken); } /// <summary> /// Finds the role who has the specified normalized name as an asynchronous operation. /// </summary> /// <param name="normalizedName">The normalized role name to look for.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that result of the look up.</returns> public virtual Task<TRole> FindByNameAsync(string normalizedName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); return Roles.FirstOrDefaultAsync(r => r.NormalizedName == normalizedName, cancellationToken); } /// <summary> /// Get a role's normalized name as an asynchronous operation. /// </summary> /// <param name="role">The role whose normalized name should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the name of the role.</returns> public virtual Task<string> GetNormalizedRoleNameAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } return Task.FromResult(role.NormalizedName); } /// <summary> /// Set a role's normalized name as an asynchronous operation. /// </summary> /// <param name="role">The role whose normalized name should be set.</param> /// <param name="normalizedName">The normalized name to set</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task SetNormalizedRoleNameAsync(TRole role, string normalizedName, CancellationToken cancellationToken = default(CancellationToken)) { cancellationToken.ThrowIfCancellationRequested(); ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } role.NormalizedName = normalizedName; return Task.CompletedTask; } /// <summary> /// Throws if this class has been disposed. /// </summary> protected void ThrowIfDisposed() { if (_disposed) { throw new ObjectDisposedException(GetType().Name); } } /// <summary> /// Dispose the stores /// </summary> public void Dispose() => _disposed = true; /// <summary> /// Get the claims associated with the specified <paramref name="role"/> as an asynchronous operation. /// </summary> /// <param name="role">The role whose claims should be retrieved.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>A <see cref="Task{TResult}"/> that contains the claims granted to a role.</returns> public virtual async Task<IList<Claim>> GetClaimsAsync(TRole role, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } return await RoleClaims.Where(rc => rc.RoleId.Equals(role.Id)).Select(c => new Claim(c.ClaimType, c.ClaimValue)).ToListAsync(cancellationToken); } /// <summary> /// Adds the <paramref name="claim"/> given to the specified <paramref name="role"/>. /// </summary> /// <param name="role">The role to add the claim to.</param> /// <param name="claim">The claim to add to the role.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual Task AddClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } if (claim == null) { throw new ArgumentNullException(nameof(claim)); } RoleClaims.Add(CreateRoleClaim(role, claim)); return Task.FromResult(false); } /// <summary> /// Removes the <paramref name="claim"/> given from the specified <paramref name="role"/>. /// </summary> /// <param name="role">The role to remove the claim from.</param> /// <param name="claim">The claim to remove from the role.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> used to propagate notifications that the operation should be canceled.</param> /// <returns>The <see cref="Task"/> that represents the asynchronous operation.</returns> public virtual async Task RemoveClaimAsync(TRole role, Claim claim, CancellationToken cancellationToken = default(CancellationToken)) { ThrowIfDisposed(); if (role == null) { throw new ArgumentNullException(nameof(role)); } if (claim == null) { throw new ArgumentNullException(nameof(claim)); } var claims = await RoleClaims.Where(rc => rc.RoleId.Equals(role.Id) && rc.ClaimValue == claim.Value && rc.ClaimType == claim.Type).ToListAsync(cancellationToken); foreach (var c in claims) { RoleClaims.Remove(c); } } /// <summary> /// A navigation property for the roles the store contains. /// </summary> public virtual IQueryable<TRole> Roles => Context.Set<TRole>(); private DbSet<TRoleClaim> RoleClaims { get { return Context.Set<TRoleClaim>(); } } /// <summary> /// Creates an entity representing a role claim. /// </summary> /// <param name="role">The associated role.</param> /// <param name="claim">The associated claim.</param> /// <returns>The role claim entity.</returns> protected virtual TRoleClaim CreateRoleClaim(TRole role, Claim claim) => new TRoleClaim { RoleId = role.Id, ClaimType = claim.Type, ClaimValue = claim.Value }; }
44.289238
170
0.667747
[ "MIT" ]
AndrewTriesToCode/aspnetcore
src/Identity/EntityFrameworkCore/src/RoleStore.cs
19,753
C#
using System.Web; using System.Web.Mvc; namespace PushServe.Api { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
20.384615
80
0.656604
[ "MIT" ]
bczang2/PushServe
PushServe.Api/App_Start/FilterConfig.cs
267
C#
namespace GreatQuotes { public interface ITextToSpeech { void Speak(string text); } }
13.375
34
0.626168
[ "MIT" ]
BicycleMark/XAM-250
Exercise 2/Completed/GreatQuotes.Data/ITextToSpeech.cs
109
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.Immutable; using System.Composition; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.DocumentationComments; using Microsoft.CodeAnalysis.LanguageServices; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.SignatureHelp; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.CSharp.SignatureHelp { [ExportSignatureHelpProvider("InvocationExpressionSignatureHelpProvider", LanguageNames.CSharp), Shared] internal partial class InvocationExpressionSignatureHelpProvider : AbstractCSharpSignatureHelpProvider { public override bool IsTriggerCharacter(char ch) { return ch == '(' || ch == ','; } public override bool IsRetriggerCharacter(char ch) { return ch == ')'; } private bool TryGetInvocationExpression(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, SignatureHelpTriggerReason triggerReason, CancellationToken cancellationToken, out InvocationExpressionSyntax expression) { if (!CommonSignatureHelpUtilities.TryGetSyntax(root, position, syntaxFacts, triggerReason, IsTriggerToken, IsArgumentListToken, cancellationToken, out expression)) { return false; } return expression.ArgumentList != null; } private bool IsTriggerToken(SyntaxToken token) { return SignatureHelpUtilities.IsTriggerParenOrComma<InvocationExpressionSyntax>(token, IsTriggerCharacter); } private static bool IsArgumentListToken(InvocationExpressionSyntax expression, SyntaxToken token) { return expression.ArgumentList.Span.Contains(token.SpanStart) && token != expression.ArgumentList.CloseParenToken; } protected override async Task<SignatureHelpItems> GetItemsWorkerAsync(Document document, int position, SignatureHelpTriggerInfo triggerInfo, CancellationToken cancellationToken) { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); if (!TryGetInvocationExpression(root, position, document.GetLanguageService<ISyntaxFactsService>(), triggerInfo.TriggerReason, cancellationToken, out var invocationExpression)) { return null; } var semanticModel = await document.GetSemanticModelForNodeAsync(invocationExpression, cancellationToken).ConfigureAwait(false); var within = semanticModel.GetEnclosingNamedTypeOrAssembly(position, cancellationToken); if (within == null) { return null; } // get the regular signature help items var symbolDisplayService = document.Project.LanguageServices.GetService<ISymbolDisplayService>(); var methodGroup = semanticModel.GetMemberGroup(invocationExpression.Expression, cancellationToken) .OfType<IMethodSymbol>() .ToImmutableArray() .FilterToVisibleAndBrowsableSymbols(document.ShouldHideAdvancedMembers(), semanticModel.Compilation); // try to bind to the actual method var symbolInfo = semanticModel.GetSymbolInfo(invocationExpression, cancellationToken); // if the symbol could be bound, replace that item in the symbol list if (symbolInfo.Symbol is IMethodSymbol matchedMethodSymbol && matchedMethodSymbol.IsGenericMethod) { methodGroup = methodGroup.SelectAsArray(m => matchedMethodSymbol.OriginalDefinition == m ? matchedMethodSymbol : m); } methodGroup = methodGroup.Sort( symbolDisplayService, semanticModel, invocationExpression.SpanStart); var expressionType = semanticModel.GetTypeInfo(invocationExpression.Expression, cancellationToken).Type as INamedTypeSymbol; var anonymousTypeDisplayService = document.Project.LanguageServices.GetService<IAnonymousTypeDisplayService>(); var documentationCommentFormattingService = document.Project.LanguageServices.GetService<IDocumentationCommentFormattingService>(); var textSpan = SignatureHelpUtilities.GetSignatureHelpSpan(invocationExpression.ArgumentList); var syntaxFacts = document.GetLanguageService<ISyntaxFactsService>(); if (methodGroup.Any()) { return CreateSignatureHelpItems( GetMethodGroupItems(invocationExpression, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, within, methodGroup, cancellationToken), textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken)); } else if (expressionType != null && expressionType.TypeKind == TypeKind.Delegate) { return CreateSignatureHelpItems( GetDelegateInvokeItems(invocationExpression, semanticModel, symbolDisplayService, anonymousTypeDisplayService, documentationCommentFormattingService, within, expressionType, cancellationToken), textSpan, GetCurrentArgumentState(root, position, syntaxFacts, textSpan, cancellationToken)); } else { return null; } } public override SignatureHelpState GetCurrentArgumentState(SyntaxNode root, int position, ISyntaxFactsService syntaxFacts, TextSpan currentSpan, CancellationToken cancellationToken) { if (TryGetInvocationExpression( root, position, syntaxFacts, SignatureHelpTriggerReason.InvokeSignatureHelpCommand, cancellationToken, out var expression) && currentSpan.Start == SignatureHelpUtilities.GetSignatureHelpSpan(expression.ArgumentList).Start) { return SignatureHelpUtilities.GetSignatureHelpState(expression.ArgumentList, position); } return null; } } }
50.44697
233
0.690344
[ "Apache-2.0" ]
DaiMichael/roslyn
src/Features/CSharp/Portable/SignatureHelp/InvocationExpressionSignatureHelpProvider.cs
6,661
C#
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Lightup { using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; internal readonly partial struct ForEachVariableStatementSyntaxWrapper : ISyntaxWrapper<StatementSyntax> { internal const string WrappedTypeName = "Microsoft.CodeAnalysis.CSharp.Syntax.ForEachVariableStatementSyntax"; private static readonly Type WrappedType; private static readonly Func<StatementSyntax, ExpressionSyntax> VariableAccessor; private static readonly Func<StatementSyntax, SyntaxList<AttributeListSyntax>, StatementSyntax> WithAttributeListsAccessor; private static readonly Func<StatementSyntax, SyntaxToken, StatementSyntax> WithAwaitKeywordAccessor; private static readonly Func<StatementSyntax, SyntaxToken, StatementSyntax> WithForEachKeywordAccessor; private static readonly Func<StatementSyntax, SyntaxToken, StatementSyntax> WithOpenParenTokenAccessor; private static readonly Func<StatementSyntax, ExpressionSyntax, StatementSyntax> WithVariableAccessor; private static readonly Func<StatementSyntax, SyntaxToken, StatementSyntax> WithInKeywordAccessor; private static readonly Func<StatementSyntax, ExpressionSyntax, StatementSyntax> WithExpressionAccessor; private static readonly Func<StatementSyntax, SyntaxToken, StatementSyntax> WithCloseParenTokenAccessor; private static readonly Func<StatementSyntax, StatementSyntax, StatementSyntax> WithStatementAccessor; private readonly StatementSyntax node; static ForEachVariableStatementSyntaxWrapper() { WrappedType = SyntaxWrapperHelper.GetWrappedType(typeof(ForEachVariableStatementSyntaxWrapper)); VariableAccessor = LightupHelpers.CreateSyntaxPropertyAccessor<StatementSyntax, ExpressionSyntax>(WrappedType, nameof(Variable)); WithAttributeListsAccessor = LightupHelpers.CreateSyntaxWithPropertyAccessor<StatementSyntax, SyntaxList<AttributeListSyntax>>(WrappedType, nameof(AttributeLists)); WithAwaitKeywordAccessor = LightupHelpers.CreateSyntaxWithPropertyAccessor<StatementSyntax, SyntaxToken>(WrappedType, nameof(AwaitKeyword)); WithForEachKeywordAccessor = LightupHelpers.CreateSyntaxWithPropertyAccessor<StatementSyntax, SyntaxToken>(WrappedType, nameof(ForEachKeyword)); WithOpenParenTokenAccessor = LightupHelpers.CreateSyntaxWithPropertyAccessor<StatementSyntax, SyntaxToken>(WrappedType, nameof(OpenParenToken)); WithVariableAccessor = LightupHelpers.CreateSyntaxWithPropertyAccessor<StatementSyntax, ExpressionSyntax>(WrappedType, nameof(Variable)); WithInKeywordAccessor = LightupHelpers.CreateSyntaxWithPropertyAccessor<StatementSyntax, SyntaxToken>(WrappedType, nameof(InKeyword)); WithExpressionAccessor = LightupHelpers.CreateSyntaxWithPropertyAccessor<StatementSyntax, ExpressionSyntax>(WrappedType, nameof(Expression)); WithCloseParenTokenAccessor = LightupHelpers.CreateSyntaxWithPropertyAccessor<StatementSyntax, SyntaxToken>(WrappedType, nameof(CloseParenToken)); WithStatementAccessor = LightupHelpers.CreateSyntaxWithPropertyAccessor<StatementSyntax, StatementSyntax>(WrappedType, nameof(Statement)); } private ForEachVariableStatementSyntaxWrapper(StatementSyntax node) { this.node = node; } public StatementSyntax SyntaxNode => this.node; public SyntaxList<AttributeListSyntax> AttributeLists { get { return this.SyntaxNode.AttributeLists(); } } public SyntaxToken AwaitKeyword { get { return ((CommonForEachStatementSyntaxWrapper)this).AwaitKeyword; } } public SyntaxToken ForEachKeyword { get { return ((CommonForEachStatementSyntaxWrapper)this).ForEachKeyword; } } public SyntaxToken OpenParenToken { get { return ((CommonForEachStatementSyntaxWrapper)this).OpenParenToken; } } public ExpressionSyntax Variable { get { return VariableAccessor(this.SyntaxNode); } } public SyntaxToken InKeyword { get { return ((CommonForEachStatementSyntaxWrapper)this).InKeyword; } } public ExpressionSyntax Expression { get { return ((CommonForEachStatementSyntaxWrapper)this).Expression; } } public SyntaxToken CloseParenToken { get { return ((CommonForEachStatementSyntaxWrapper)this).CloseParenToken; } } public StatementSyntax Statement { get { return ((CommonForEachStatementSyntaxWrapper)this).Statement; } } public static explicit operator ForEachVariableStatementSyntaxWrapper(CommonForEachStatementSyntaxWrapper node) { return (ForEachVariableStatementSyntaxWrapper)node.SyntaxNode; } public static explicit operator ForEachVariableStatementSyntaxWrapper(SyntaxNode node) { if (node == null) { return default; } if (!IsInstance(node)) { throw new InvalidCastException($"Cannot cast '{node.GetType().FullName}' to '{WrappedTypeName}'"); } return new ForEachVariableStatementSyntaxWrapper((StatementSyntax)node); } public static implicit operator CommonForEachStatementSyntaxWrapper(ForEachVariableStatementSyntaxWrapper wrapper) { return CommonForEachStatementSyntaxWrapper.FromUpcast(wrapper.node); } public static implicit operator StatementSyntax(ForEachVariableStatementSyntaxWrapper wrapper) { return wrapper.node; } public static bool IsInstance(SyntaxNode node) { return node != null && LightupHelpers.CanWrapNode(node, WrappedType); } public ForEachVariableStatementSyntaxWrapper WithAttributeLists(SyntaxList<AttributeListSyntax> attributeLists) { return new ForEachVariableStatementSyntaxWrapper(WithAttributeListsAccessor(this.SyntaxNode, attributeLists)); } public ForEachVariableStatementSyntaxWrapper WithAwaitKeyword(SyntaxToken awaitKeyword) { return new ForEachVariableStatementSyntaxWrapper(WithAwaitKeywordAccessor(this.SyntaxNode, awaitKeyword)); } public ForEachVariableStatementSyntaxWrapper WithForEachKeyword(SyntaxToken forEachKeyword) { return new ForEachVariableStatementSyntaxWrapper(WithForEachKeywordAccessor(this.SyntaxNode, forEachKeyword)); } public ForEachVariableStatementSyntaxWrapper WithOpenParenToken(SyntaxToken openParenToken) { return new ForEachVariableStatementSyntaxWrapper(WithOpenParenTokenAccessor(this.SyntaxNode, openParenToken)); } public ForEachVariableStatementSyntaxWrapper WithVariable(ExpressionSyntax variable) { return new ForEachVariableStatementSyntaxWrapper(WithVariableAccessor(this.SyntaxNode, variable)); } public ForEachVariableStatementSyntaxWrapper WithInKeyword(SyntaxToken inKeyword) { return new ForEachVariableStatementSyntaxWrapper(WithInKeywordAccessor(this.SyntaxNode, inKeyword)); } public ForEachVariableStatementSyntaxWrapper WithExpression(ExpressionSyntax expression) { return new ForEachVariableStatementSyntaxWrapper(WithExpressionAccessor(this.SyntaxNode, expression)); } public ForEachVariableStatementSyntaxWrapper WithCloseParenToken(SyntaxToken closeParenToken) { return new ForEachVariableStatementSyntaxWrapper(WithCloseParenTokenAccessor(this.SyntaxNode, closeParenToken)); } public ForEachVariableStatementSyntaxWrapper WithStatement(StatementSyntax statement) { return new ForEachVariableStatementSyntaxWrapper(WithStatementAccessor(this.SyntaxNode, statement)); } } }
42.84878
176
0.702641
[ "MIT" ]
AraHaan/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers/Lightup/.generated/StyleCop.Analyzers.CodeGeneration/StyleCop.Analyzers.CodeGeneration.SyntaxLightupGenerator/ForEachVariableStatementSyntaxWrapper.g.cs
8,786
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Text; namespace CodeWars { /// <see cref="https://www.codewars.com/kata/54b724efac3d5402db00065e"/> [TestClass] public class DecodeTheMorseCode { [TestMethod] public void Test() { Assert.AreEqual("HEY JUDE", ".... . -.-- .--- ..- -.. ."); } public string Decode(string morseCode) { var result = new StringBuilder(); var words = morseCode.Split(" "); foreach (var word in words) { var characters = word.Split(' '); foreach (var character in characters) { var convertedCharacter = MorseCode.Get(character); result.Append(convertedCharacter); } result.Append(" "); } return result.ToString().Trim(); } public class MorseCode { public static string Get(string character) { return character; } } } }
24.255319
76
0.480702
[ "MIT" ]
Hyolog/CodeWars
CodeWars/CodeWars/DecodeTheMorseCode.cs
1,140
C#
//using System; //using System.Collections.Generic; //using System.Text; //namespace Discord.Addons.MpGame.Remotes //{ // /// <summary> // /// // /// </summary> // /// <typeparam name="TGame"> // /// The type of game that is managed. // /// </typeparam> // /// <typeparam name="TPlayer"> // /// The type of the <see cref="Player"/> object. // /// </typeparam> // internal sealed class RemoteMpGameClient<TGame, TPlayer> : RemoteMpGameService.RemoteMpGameServiceClient // where TGame : GameBase<TPlayer> // where TPlayer : Player // { // } //}
26.304348
110
0.583471
[ "MIT" ]
Joe4evr/Discord.Addons
src/Discord.Addons.MpGame.ShardedBridge/Remotes/RemoteMpGameClient.cs
607
C#
// <copyright file="BDDLoggingTimeEventHandlers.cs" company="Automate The Planet Ltd."> // Copyright 2021 Automate The Planet Ltd. // 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. // </copyright> // <author>Anton Angelov</author> // <site>https://bellatrix.solutions/</site> using Bellatrix.Desktop.EventHandlers; using Bellatrix.Desktop.Events; namespace Bellatrix.Desktop.BddLogging { public class BDDLoggingTimeEventHandlers : TimeEventHandlers { protected override void SettingTimeEventHandler(object sender, ElementActionEventArgs arg) => Logger.LogInformation($"Set '{arg.ActionValue}' into {arg.Element.ElementName} on {arg.Element.PageName}"); } }
48.791667
209
0.765158
[ "Apache-2.0" ]
alexandrejulien/BELLATRIX
src/Bellatrix.Desktop/eventhandlers/BddLogging/BDDLoggingTimeEventHandlers.cs
1,173
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("NSC_TournamentGen.Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NSC_TournamentGen.Core")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("CE128572-05F0-4FDC-B08C-0E670FA69F9B")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.342857
84
0.744372
[ "MIT" ]
Eperty123/NSC-TournamentGen
NSC-TournamentGen.Core/Properties/AssemblyInfo.cs
1,380
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; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.rtc.Model.V20180111; namespace Aliyun.Acs.rtc.Transform.V20180111 { public class DescribeRtcScaleDetailResponseUnmarshaller { public static DescribeRtcScaleDetailResponse Unmarshall(UnmarshallerContext _ctx) { DescribeRtcScaleDetailResponse describeRtcScaleDetailResponse = new DescribeRtcScaleDetailResponse(); describeRtcScaleDetailResponse.HttpResponse = _ctx.HttpResponse; describeRtcScaleDetailResponse.RequestId = _ctx.StringValue("DescribeRtcScaleDetail.RequestId"); List<DescribeRtcScaleDetailResponse.DescribeRtcScaleDetail_ScaleItem> describeRtcScaleDetailResponse_scale = new List<DescribeRtcScaleDetailResponse.DescribeRtcScaleDetail_ScaleItem>(); for (int i = 0; i < _ctx.Length("DescribeRtcScaleDetail.Scale.Length"); i++) { DescribeRtcScaleDetailResponse.DescribeRtcScaleDetail_ScaleItem scaleItem = new DescribeRtcScaleDetailResponse.DescribeRtcScaleDetail_ScaleItem(); scaleItem.TS = _ctx.StringValue("DescribeRtcScaleDetail.Scale["+ i +"].TS"); scaleItem.CC = _ctx.LongValue("DescribeRtcScaleDetail.Scale["+ i +"].CC"); scaleItem.UC = _ctx.LongValue("DescribeRtcScaleDetail.Scale["+ i +"].UC"); describeRtcScaleDetailResponse_scale.Add(scaleItem); } describeRtcScaleDetailResponse.Scale = describeRtcScaleDetailResponse_scale; return describeRtcScaleDetailResponse; } } }
45.235294
189
0.774599
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-rtc/Rtc/Transform/V20180111/DescribeRtcScaleDetailResponseUnmarshaller.cs
2,307
C#
using Xunit; using Exercism.Tests; public class RemoteControlCarTests { [Fact] public void New_remote_control_car_has_not_driven_any_distance() { int speed = 10; int batteryDrain = 2; var car = new RemoteControlCar(speed, batteryDrain); Assert.Equal(0, car.DistanceDriven()); } [Fact(Skip = "Remove this Skip property to run this test")] public void Drive_increases_distance_driven_with_speed() { int speed = 5; int batteryDrain = 1; var car = new RemoteControlCar(speed, batteryDrain); car.Drive(); Assert.Equal(5, car.DistanceDriven()); } [Fact(Skip = "Remove this Skip property to run this test")] public void Drive_does_not_increase_distance_driven_when_battery_drained() { int speed = 9; int batteryDrain = 50; var car = new RemoteControlCar(speed, batteryDrain); // Drain the battery car.Drive(); car.Drive(); // One extra drive attempt (should not succeed) car.Drive(); Assert.Equal(18, car.DistanceDriven()); } [Fact(Skip = "Remove this Skip property to run this test")] public void New_remote_control_car_battery_is_not_drained() { int speed = 15; int batteryDrain = 3; var car = new RemoteControlCar(speed, batteryDrain); Assert.False(car.BatteryDrained()); } [Fact(Skip = "Remove this Skip property to run this test")] public void Drive_to_almost_drain_battery() { int speed = 2; int batteryDrain = 1; var car = new RemoteControlCar(speed, batteryDrain); // Almost drain the battery for (var i = 0; i < 99; i++) { car.Drive(); } Assert.False(car.BatteryDrained()); } [Fact(Skip = "Remove this Skip property to run this test")] public void Drive_until_battery_is_drained() { int speed = 2; int batteryDrain = 1; var car = new RemoteControlCar(speed, batteryDrain); // Drain the battery for (var i = 0; i < 100; i++) { car.Drive(); } Assert.True(car.BatteryDrained()); } [Fact(Skip = "Remove this Skip property to run this test")] public void Nitro_car_has_not_driven_any_distance() { var car = RemoteControlCar.Nitro(); Assert.Equal(0, car.DistanceDriven()); } [Fact(Skip = "Remove this Skip property to run this test")] public void Nitro_car_has_battery_not_drained() { var car = RemoteControlCar.Nitro(); Assert.False(car.BatteryDrained()); } [Fact(Skip = "Remove this Skip property to run this test")] public void Nitro_car_has_correct_speed() { var car = RemoteControlCar.Nitro(); car.Drive(); Assert.Equal(50, car.DistanceDriven()); } [Fact(Skip = "Remove this Skip property to run this test")] public void Nitro_car_has_correct_battery_drain() { var car = RemoteControlCar.Nitro(); // The battery is almost drained for (var i = 0; i < 24; i++) { car.Drive(); } Assert.False(car.BatteryDrained()); // Drain the battery car.Drive(); Assert.True(car.BatteryDrained()); } } public class RaceTrackTests { [Fact(Skip = "Remove this Skip property to run this test")] public void Car_can_finish_with_car_that_can_easily_finish() { int speed = 10; int batteryDrain = 2; var car = new RemoteControlCar(speed, batteryDrain); int distance = 100; var race = new RaceTrack(distance); Assert.True(race.CarCanFinish(car)); } [Fact(Skip = "Remove this Skip property to run this test")] public void Car_can_finish_with_car_that_can_just_finish() { int speed = 2; int batteryDrain = 10; var car = new RemoteControlCar(speed, batteryDrain); int distance = 20; var race = new RaceTrack(distance); Assert.True(race.CarCanFinish(car)); } [Fact(Skip = "Remove this Skip property to run this test")] public void Car_can_finish_with_car_that_just_cannot_finish() { int speed = 3; int batteryDrain = 20; var car = new RemoteControlCar(speed, batteryDrain); int distance = 16; var race = new RaceTrack(distance); Assert.False(race.CarCanFinish(car)); } [Fact(Skip = "Remove this Skip property to run this test")] public void Car_can_finish_with_car_that_cannot_finish() { int speed = 1; int batteryDrain = 20; var car = new RemoteControlCar(speed, batteryDrain); int distance = 678; var race = new RaceTrack(distance); Assert.False(race.CarCanFinish(car)); } }
26.612022
78
0.609651
[ "MIT" ]
18-F-cali/csharp
exercises/concept/need-for-speed/NeedForSpeedTests.cs
4,870
C#
namespace Agebull.Common.Logging { /// <summary> /// 日志类型 /// </summary> public enum LogLevel { /// <summary> /// 无 /// </summary> None, /// <summary> /// 调试信息 /// </summary> Debug, /// <summary> /// 跟踪信息 /// </summary> Trace, /// <summary> /// 警告 /// </summary> Warning, /// <summary> /// 系统 /// </summary> System, /// <summary> /// 错误 /// </summary> Error } /// <summary> /// 日志枚举辅助 /// </summary> public static class LogEnumHelper { /// <summary> /// 日志类型到级别 /// </summary> /// <param name="type"></param> public static LogLevel Level(this LogType type) { switch (type) { case LogType.Debug: case LogType.Monitor: case LogType.DataBase: return LogLevel.Debug; case LogType.Login: case LogType.NetWork: case LogType.Message: case LogType.Request: case LogType.Trace: return LogLevel.Trace; case LogType.Warning: return LogLevel.Warning; case LogType.Error: case LogType.Exception: return LogLevel.Error; case LogType.System: case LogType.Plan: return LogLevel.System; } return LogLevel.None; } /// <summary> /// 日志类型到文本 /// </summary> /// <param name="type"> </param> /// <param name="def"> </param> /// <returns> </returns> public static string TypeToString(LogType type, string def = null) { switch (type) { default: return def ?? "None"; case LogType.Plan: return "Plan"; case LogType.Debug: return "Debug"; case LogType.Trace: return "Trace"; case LogType.Message: return "Message"; case LogType.Warning: return "Warning"; case LogType.Error: return "Error"; case LogType.Exception: return "Exception"; case LogType.System: return "System"; case LogType.Login: return "Login"; case LogType.Request: return "Request"; case LogType.DataBase: return "DataBase"; case LogType.NetWork: return "NetWork"; } } } }
26.455357
74
0.399595
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
agebullhu/EntityModel
src/LogRecorder/Logging/LogLevel.cs
3,043
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace StoreAPI.Service.Migrations { public partial class addname : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "Name", table: "Deck", type: "nvarchar(max)", nullable: true); migrationBuilder.UpdateData( table: "Card", keyColumn: "EntityId", keyValue: 1, columns: new[] { "Answer", "Question" }, values: new object[] { "1", "1x1" }); migrationBuilder.UpdateData( table: "Deck", keyColumn: "EntityId", keyValue: 1, column: "Name", value: "Math"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Name", table: "Deck"); migrationBuilder.UpdateData( table: "Card", keyColumn: "EntityId", keyValue: 1, columns: new[] { "Answer", "Question" }, values: new object[] { "George Washington", "Who was the first president?" }); } } }
30.355556
94
0.486091
[ "MIT" ]
CardCram/project.p2
aspnet_api_store/StoreAPI.Service/Migrations/20210202235501_addname.cs
1,368
C#
// ************************************************************************ // // * Copyright 2017 OSIsoft, 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 // * // * <http://www.apache.org/licenses/LICENSE-2.0> // * // * Unless required by applicable law or agreed to in writing, software // * distributed under the License is distributed on an "AS IS" BASIS, // * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // * See the License for the specific language governing permissions and // * limitations under the License. // ************************************************************************ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using OSIsoft.PIDevClub.PIWebApiClient.Client; using System.Runtime.InteropServices; namespace OSIsoft.PIDevClub.PIWebApiClient.Model { /// <summary> /// PIItemEventFrame /// </summary> [DataContract] public class PIItemEventFrame { public PIItemEventFrame(string Identifier = null, string IdentifierType = null, PIEventFrame Object = null, PIErrors Exception = null) { this.Identifier = Identifier; this.IdentifierType = IdentifierType; this.Object = Object; this.Exception = Exception; } /// <summary> /// Gets or Sets PIItemEventFrame /// </summary> [DataMember(Name = "Identifier", EmitDefaultValue = false)] public string Identifier { get; set; } /// <summary> /// Gets or Sets PIItemEventFrame /// </summary> [DataMember(Name = "IdentifierType", EmitDefaultValue = false)] public string IdentifierType { get; set; } /// <summary> /// Gets or Sets PIItemEventFrame /// </summary> [DataMember(Name = "Object", EmitDefaultValue = false)] public PIEventFrame Object { get; set; } /// <summary> /// Gets or Sets PIItemEventFrame /// </summary> [DataMember(Name = "Exception", EmitDefaultValue = false)] public PIErrors Exception { get; set; } } }
30.684211
136
0.676244
[ "Apache-2.0" ]
raouldke/PI-Web-API-Client-DotNet
src/OSIsoft.PIDevClub.PIWebApiClient/OSIsoft.PIDevClub.PIWebApiClient/Model/PIItemEventFrame.cs
2,332
C#
using System; using UnityEngine; public class Pause : MonoBehaviour { [SerializeField] private Canvas _pauseMenu; [SerializeField] private CursorManager _cursorManager; [SerializeField] private bool _isPaused; private bool _hasReleased; private void Update() { if (Math.Abs(Input.GetAxisRaw("Cancel")) >= 0.9 && _hasReleased) { _hasReleased = false; TogglePause(); } else if (Math.Abs(Input.GetAxisRaw("Cancel")) <= 0.1) { _hasReleased = true; } } private void TogglePause() { _isPaused = !_isPaused; Time.timeScale = _isPaused ? 0 : 1; _pauseMenu.enabled = _isPaused; _cursorManager.enabled = !_isPaused; } }
23.484848
72
0.592258
[ "Unlicense" ]
doovagames/A-Way-Home-Final-Game
A Way Home/Assets/Scripts/Player/Pause.cs
777
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace VoltageSampling.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("VoltageSampling.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; } } } }
38.708333
181
0.604234
[ "MIT" ]
manuelbl/WirekiteWin
Examples/VoltageSampling/VoltageSampling/Properties/Resources.Designer.cs
2,789
C#
namespace NEventStore.Client { using System; using System.Threading; using System.Threading.Tasks; internal static class TaskHelpers { internal static Task Delay(double milliseconds, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<bool>(); TimerCallback callback = (state) => tcs.TrySetResult(true); var timer = new System.Threading.Timer(callback, null, 0, Convert.ToInt32(milliseconds)); CancellationTokenRegistration cancellationTokenRegistration = cancellationToken.Register(() => { timer.Dispose(); tcs.TrySetCanceled(); }); return tcs.Task.ContinueWith(_ => { cancellationTokenRegistration.Dispose(); timer.Dispose(); }, TaskContinuationOptions.ExecuteSynchronously); } public static void WhenCompleted<T>(this Task<T> task, Action<Task<T>> onComplete, Action<Task<T>> onFaulted, bool execSync = false) { if (task.IsCompleted) { if (task.IsFaulted) { onFaulted.Invoke(task); return; } onComplete.Invoke(task); return; } task.ContinueWith( onComplete, execSync ? TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion : TaskContinuationOptions.OnlyOnRanToCompletion); task.ContinueWith( onFaulted, execSync ? TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted : TaskContinuationOptions.OnlyOnFaulted); } public static void WhenCompleted(this Task task, Action<Task> onComplete, Action<Task> onFaulted, bool execSync = false) { if (task.IsCompleted) { if (task.IsFaulted) { onFaulted.Invoke(task); return; } onComplete.Invoke(task); return; } task.ContinueWith( onComplete, execSync ? TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnRanToCompletion : TaskContinuationOptions.OnlyOnRanToCompletion); task.ContinueWith( onFaulted, execSync ? TaskContinuationOptions.ExecuteSynchronously | TaskContinuationOptions.OnlyOnFaulted : TaskContinuationOptions.OnlyOnFaulted); } } }
35.6875
140
0.544308
[ "MIT" ]
dementeddevil/NEventStore
src/NEventStore/Client/TaskHelpers.cs
2,857
C#
using System; using System.Reflection; namespace MacroFramework.Commands { /// <summary> /// <see cref="Attribute"/> for easily creating a <see cref="TimerActivator"/> /// </summary> public class TimerActivatorAttribute : ActivatorAttribute { private int delay; private TimeUnit unit; private bool callAtStart; /// <summary> /// Creates a new <see cref="TimerActivator"/> instance at the start of the application from this method. /// </summary> /// <param name="delay">Minimum delay between last execution and new execution start/param> /// <param name="callAtStart">If true the command is called on the first update loop</param> /// <param name="unit">The unit of time used</param> public TimerActivatorAttribute(int delay, TimeUnit unit = TimeUnit.Seconds, bool callAtStart = false) { this.delay = delay; this.unit = unit; this.callAtStart = callAtStart; } public override IActivator GetCommandActivator(Command c, MethodInfo m) { return new TimerActivator(delay, unit, callAtStart, () => m.Invoke(c, null)); } } }
38.548387
113
0.637657
[ "MIT" ]
porrasm/macro-framework
MacroFrameworkLibrary/Commands/Attributes/TimerActivatorAttribute.cs
1,197
C#
#if WITH_GAME #if PLATFORM_32BITS using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace UnrealEngine { public partial class UMaterialExpressionTransformPosition { static readonly int Input__Offset; public FExpressionInput Input { get{ CheckIsValid();return (FExpressionInput)Marshal.PtrToStructure(_this.Get()+Input__Offset, typeof(FExpressionInput));} } static readonly int TransformSourceType__Offset; public EMaterialPositionTransformSource TransformSourceType { get{ CheckIsValid();return (EMaterialPositionTransformSource)Marshal.PtrToStructure(_this.Get()+TransformSourceType__Offset, typeof(EMaterialPositionTransformSource));} set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+TransformSourceType__Offset, false);} } static readonly int TransformType__Offset; public EMaterialPositionTransformSource TransformType { get{ CheckIsValid();return (EMaterialPositionTransformSource)Marshal.PtrToStructure(_this.Get()+TransformType__Offset, typeof(EMaterialPositionTransformSource));} set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+TransformType__Offset, false);} } static UMaterialExpressionTransformPosition() { IntPtr NativeClassPtr=GetNativeClassFromName("MaterialExpressionTransformPosition"); Input__Offset=GetPropertyOffset(NativeClassPtr,"Input"); TransformSourceType__Offset=GetPropertyOffset(NativeClassPtr,"TransformSourceType"); TransformType__Offset=GetPropertyOffset(NativeClassPtr,"TransformType"); } } } #endif #endif
34.042553
171
0.808125
[ "MIT" ]
RobertAcksel/UnrealCS
Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile_Game_32bits/UMaterialExpressionTransformPosition_FixSize.cs
1,600
C#
using System.Net; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Oqtane.Extensions; namespace Oqtane.Pages { [AllowAnonymous] [IgnoreAntiforgeryToken] public class ExternalModel : PageModel { public IActionResult OnGetAsync(string returnurl) { returnurl = (returnurl == null) ? "/" : returnurl; returnurl = (!returnurl.StartsWith("/")) ? "/" + returnurl : returnurl; var providertype = HttpContext.GetSiteSettings().GetValue("ExternalLogin:ProviderType", ""); if (providertype != "") { return new ChallengeResult(providertype, new AuthenticationProperties { RedirectUri = returnurl + (returnurl.Contains("?") ? "&" : "?") + "reload=post" }); } else { HttpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden; return new EmptyResult(); } } public IActionResult OnPostAsync(string returnurl) { if (returnurl == null) { returnurl = ""; } if (!returnurl.StartsWith("/")) { returnurl = "/" + returnurl; } // remove reload parameter returnurl = returnurl.ReplaceMultiple(new string[] { "?reload=post", "&reload=post" }, ""); return LocalRedirect(Url.Content("~" + returnurl)); } } }
32.163265
175
0.564721
[ "MIT" ]
dkoeder/oqtane.framework
Oqtane.Server/Pages/External.cshtml.cs
1,576
C#
using System.Threading.Tasks; using System; using System.Collections.Generic; using System.Threading; using Narochno.Jenkins.Entities; using Narochno.Jenkins.Entities.Builds; using Narochno.Jenkins.Entities.Jobs; using Narochno.Jenkins.Entities.Views; using Narochno.Jenkins.Entities.Users; namespace Narochno.Jenkins { public interface IJenkinsClient : IDisposable { Task<BuildInfo> GetBuild(string job, string build, CancellationToken ctx = default(CancellationToken)); Task<string> GetBuildConsole(string job, string build, CancellationToken ctx = default(CancellationToken)); Task<JobInfo> GetJob(string job, CancellationToken ctx = default(CancellationToken)); Task<UserInfo> GetUser(string user, CancellationToken ctx = default(CancellationToken)); Task<ViewInfo> GetView(string view, CancellationToken ctx = default(CancellationToken)); Task<Master> GetMaster(CancellationToken ctx = default(CancellationToken)); Task BuildProject(string job, CancellationToken ctx = default(CancellationToken)); Task BuildProjectWithParameters(string job, IDictionary<string, string> parameters, CancellationToken ctx = default(CancellationToken)); Task CopyJob(string fromJobName, string newJobName, CancellationToken ctx = default(CancellationToken)); Task CopyJob(string fromJobName, string newJobName, string path, CancellationToken ctx = default(CancellationToken)); Task<string> DownloadJobConfig(string job, CancellationToken ctx = default(CancellationToken)); Task UploadJobConfig(string job, string xml, CancellationToken ctx = default(CancellationToken)); Task EnableJob(string job, CancellationToken ctx = default(CancellationToken)); Task DisableJob(string job, CancellationToken ctx = default(CancellationToken)); Task DeleteJob(string job, CancellationToken ctx = default(CancellationToken)); Task<bool> ExistsJob(string job, CancellationToken ctx = default(CancellationToken)); Task CreateJob(string job, string xml, CancellationToken ctx = default(CancellationToken)); Task CreateJob(string job, string xml, string path, CancellationToken ctx = default(CancellationToken)); Task CreateFolder(string folder, CancellationToken ctx = default(CancellationToken)); Task CreateFolder(string folder, string path, CancellationToken ctx = default(CancellationToken)); Task DeleteFolder(string folder, CancellationToken ctx = default(CancellationToken)); Task QuietDown(string reason = "", CancellationToken ctx = default(CancellationToken)); Task CancelQuietDown(CancellationToken ctx = default(CancellationToken)); Task Restart(CancellationToken ctx = default(CancellationToken)); Task SafeRestart(CancellationToken ctx = default(CancellationToken)); } }
70.902439
145
0.755074
[ "MIT" ]
db2222/Narochno.Jenkins
src/Narochno.Jenkins/IJenkinsClient.cs
2,909
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LiteDB; using IFCLite.Data; namespace IFCLite.Access { public class IFCDelete { private IFCDatabase Database { get; set; } public IFCDelete(IFCDatabase Database) { this.Database = Database; } /// <summary> /// 透過P21Id刪除物件。 /// </summary> /// <param name="p21Id"></param> public void ByP21Id(string p21Id) { BsonDocument obj = Database.IFCModel.FindOne(x => x["P21Id"] == p21Id); if (obj == null) //屬於被取代的資料, 可直接刪除Replace資料即可 { Database.ReplaceTable.DeleteMany(x => x.KeyElement == p21Id); return; } List<IFCReplaceRecord> record = Database.ReplaceTable.Find(x => x.ValueElement == p21Id).ToList(); //取得取代資料 if(record.Count() != 0) //有取代別人, 需額外處理 { string newReplaceId = record.First().KeyElement; record.Remove(record[0]); //刪除第一筆資料 foreach (IFCReplaceRecord data in record) { data.ValueElement = newReplaceId; Database.ReplaceTable.Update(data); //更新ReplaceTable } obj["P21Id"] = newReplaceId; //更新P21Id Database.IFCModel.Insert(obj); //新增至資料庫 } Database.IFCModel.Delete(obj["_id"]); //刪除該物件 } /// <summary> /// 透過IFC物件刪除單一物件。 /// </summary> /// <param name="ifcObject"></param> public void ByObject(IFCObject ifcObject) { ByP21Id(ifcObject.P21Id); } /// <summary> /// 透過IFC物件陣列刪除多個IFC物件。 /// </summary> /// <param name="ifcObjects"></param> public void ByObject(List<IFCObject> ifcObjects) { foreach (IFCObject obj in ifcObjects) ByP21Id(obj.P21Id); } } }
32.95082
119
0.535323
[ "MIT" ]
J-YingHuang/IFCLite
src/Access/IFCDelete.cs
2,184
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections.Generic; using System.Linq; using Microsoft.Bot.Builder.Dialogs.Choices; using Microsoft.Bot.Connector; using Microsoft.Bot.Schema; using Xunit; namespace Microsoft.Bot.Builder.Dialogs.Tests { [Trait("TestCategory", "Prompts")] [Trait("TestCategory", "Choice Tests")] public class ChoiceFactoryTests { private static List<Choice> colorChoices = new List<Choice> { new Choice("red"), new Choice("green"), new Choice("blue") }; private static List<Choice> extraChoices = new List<Choice> { new Choice("red"), new Choice("green"), new Choice("blue"), new Choice("alpha") }; private static List<Choice> choicesWithActions = new List<Choice> { new Choice("ImBack") { Action = new CardAction(ActionTypes.ImBack, "ImBack Action", value: "ImBack Value") }, new Choice("MessageBack") { Action = new CardAction(ActionTypes.MessageBack, "MessageBack Action", value: "MessageBack Value") }, new Choice("PostBack") { Action = new CardAction(ActionTypes.PostBack, "PostBack Action", value: "PostBack Value") }, }; [Fact] public void ShouldRenderChoicesInline() { var activity = ChoiceFactory.Inline(colorChoices, "select from:"); Assert.Equal("select from: (1) red, (2) green, or (3) blue", activity.Text); } [Fact] public void ShouldRenderChoicesAsAList() { var activity = ChoiceFactory.List(colorChoices, "select from:"); Assert.Equal("select from:\n\n 1. red\n 2. green\n 3. blue", activity.Text); } [Fact] public void ShouldRenderUnincludedNumbersChoicesAsAList() { var activity = ChoiceFactory.List(colorChoices, "select from:", options: new ChoiceFactoryOptions { IncludeNumbers = false }); Assert.Equal("select from:\n\n - red\n - green\n - blue", activity.Text); } [Fact] public void ShouldRenderChoicesAsSuggestedActions() { var activity = ChoiceFactory.SuggestedAction(colorChoices, "select from:"); Assert.Equal("select from:", activity.Text); Assert.NotNull(activity.SuggestedActions); Assert.Equal(3, activity.SuggestedActions.Actions.Count); Assert.Equal(ActionTypes.ImBack, activity.SuggestedActions.Actions[0].Type); Assert.Equal("red", activity.SuggestedActions.Actions[0].Value); Assert.Equal("red", activity.SuggestedActions.Actions[0].Title); Assert.Equal(ActionTypes.ImBack, activity.SuggestedActions.Actions[1].Type); Assert.Equal("green", activity.SuggestedActions.Actions[1].Value); Assert.Equal("green", activity.SuggestedActions.Actions[1].Title); Assert.Equal(ActionTypes.ImBack, activity.SuggestedActions.Actions[2].Type); Assert.Equal("blue", activity.SuggestedActions.Actions[2].Value); Assert.Equal("blue", activity.SuggestedActions.Actions[2].Title); } [Fact] public void ShouldRenderChoicesAsHeroCard() { var activity = ChoiceFactory.HeroCard(colorChoices, "select from:"); Assert.NotNull(activity.Attachments); var heroCard = (HeroCard)activity.Attachments.First().Content; Assert.Equal(3, heroCard.Buttons.Count); Assert.Equal(ActionTypes.ImBack, heroCard.Buttons[0].Type); Assert.Equal("red", heroCard.Buttons[0].Value); Assert.Equal("red", heroCard.Buttons[0].Title); Assert.Equal(ActionTypes.ImBack, heroCard.Buttons[1].Type); Assert.Equal("green", heroCard.Buttons[1].Value); Assert.Equal("green", heroCard.Buttons[1].Title); Assert.Equal(ActionTypes.ImBack, heroCard.Buttons[2].Type); Assert.Equal("blue", heroCard.Buttons[2].Value); Assert.Equal("blue", heroCard.Buttons[2].Title); } [Fact] public void ShouldAutomaticallyChooseRenderStyleBasedOnChannelType() { var activity = ChoiceFactory.ForChannel(Channels.Emulator, colorChoices, "select from:"); Assert.Equal("select from:", activity.Text); Assert.NotNull(activity.SuggestedActions); Assert.Equal(3, activity.SuggestedActions.Actions.Count); Assert.Equal(ActionTypes.ImBack, activity.SuggestedActions.Actions[0].Type); Assert.Equal("red", activity.SuggestedActions.Actions[0].Value); Assert.Equal("red", activity.SuggestedActions.Actions[0].Title); Assert.Equal(ActionTypes.ImBack, activity.SuggestedActions.Actions[1].Type); Assert.Equal("green", activity.SuggestedActions.Actions[1].Value); Assert.Equal("green", activity.SuggestedActions.Actions[1].Title); Assert.Equal(ActionTypes.ImBack, activity.SuggestedActions.Actions[2].Type); Assert.Equal("blue", activity.SuggestedActions.Actions[2].Value); Assert.Equal("blue", activity.SuggestedActions.Actions[2].Title); } [Fact] public void ShouldChooseCorrectStylesForCortana() { var activity = ChoiceFactory.ForChannel(Channels.Cortana, colorChoices, "select from:"); Assert.NotNull(activity.Attachments); var heroCard = (HeroCard)activity.Attachments.First().Content; Assert.Equal(3, heroCard.Buttons.Count); Assert.Equal(ActionTypes.ImBack, heroCard.Buttons[0].Type); Assert.Equal("red", heroCard.Buttons[0].Value); Assert.Equal("red", heroCard.Buttons[0].Title); Assert.Equal(ActionTypes.ImBack, heroCard.Buttons[1].Type); Assert.Equal("green", heroCard.Buttons[1].Value); Assert.Equal("green", heroCard.Buttons[1].Title); Assert.Equal(ActionTypes.ImBack, heroCard.Buttons[2].Type); Assert.Equal("blue", heroCard.Buttons[2].Value); Assert.Equal("blue", heroCard.Buttons[2].Title); } [Fact] public void ShouldChooseCorrectStylesForTeams() { var activity = ChoiceFactory.ForChannel(Channels.Msteams, colorChoices, "select from:"); Assert.NotNull(activity.Attachments); var heroCard = (HeroCard)activity.Attachments.First().Content; Assert.Equal(3, heroCard.Buttons.Count); Assert.Equal(ActionTypes.ImBack, heroCard.Buttons[0].Type); Assert.Equal("red", heroCard.Buttons[0].Value); Assert.Equal("red", heroCard.Buttons[0].Title); Assert.Equal(ActionTypes.ImBack, heroCard.Buttons[1].Type); Assert.Equal("green", heroCard.Buttons[1].Value); Assert.Equal("green", heroCard.Buttons[1].Title); Assert.Equal(ActionTypes.ImBack, heroCard.Buttons[2].Type); Assert.Equal("blue", heroCard.Buttons[2].Value); Assert.Equal("blue", heroCard.Buttons[2].Title); } [Fact] public void ShouldIncludeChoiceActionsInSuggestedActions() { var activity = ChoiceFactory.SuggestedAction(choicesWithActions, "select from:"); Assert.Equal("select from:", activity.Text); Assert.NotNull(activity.SuggestedActions); Assert.Equal(3, activity.SuggestedActions.Actions.Count); Assert.Equal(ActionTypes.ImBack, activity.SuggestedActions.Actions[0].Type); Assert.Equal("ImBack Value", activity.SuggestedActions.Actions[0].Value); Assert.Equal("ImBack Action", activity.SuggestedActions.Actions[0].Title); Assert.Equal(ActionTypes.MessageBack, activity.SuggestedActions.Actions[1].Type); Assert.Equal("MessageBack Value", activity.SuggestedActions.Actions[1].Value); Assert.Equal("MessageBack Action", activity.SuggestedActions.Actions[1].Title); Assert.Equal(ActionTypes.PostBack, activity.SuggestedActions.Actions[2].Type); Assert.Equal("PostBack Value", activity.SuggestedActions.Actions[2].Value); Assert.Equal("PostBack Action", activity.SuggestedActions.Actions[2].Title); } [Fact] public void ShouldIncludeChoiceActionsInHeroCards() { var activity = ChoiceFactory.HeroCard(choicesWithActions, "select from:"); Assert.NotNull(activity.Attachments); var heroCard = (HeroCard)activity.Attachments.First().Content; Assert.Equal(3, heroCard.Buttons.Count); Assert.Equal(ActionTypes.ImBack, heroCard.Buttons[0].Type); Assert.Equal("ImBack Value", heroCard.Buttons[0].Value); Assert.Equal("ImBack Action", heroCard.Buttons[0].Title); Assert.Equal(ActionTypes.MessageBack, heroCard.Buttons[1].Type); Assert.Equal("MessageBack Value", heroCard.Buttons[1].Value); Assert.Equal("MessageBack Action", heroCard.Buttons[1].Title); Assert.Equal(ActionTypes.PostBack, heroCard.Buttons[2].Type); Assert.Equal("PostBack Value", heroCard.Buttons[2].Value); Assert.Equal("PostBack Action", heroCard.Buttons[2].Title); } } }
50.263441
152
0.646807
[ "MIT" ]
Alpharceus/botbuilder-dotnet
tests/Microsoft.Bot.Builder.Dialogs.Tests/ChoiceFactoryTests.cs
9,351
C#
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace DailyTimeScheduler.Model { public class TimeBlock { /// <summary> /// PK Unique TimeBlock Number in DB /// </summary> [Key] public int No { get; set; } /// <summary> /// Intial schedule time. /// DateTime.Ticks value for 100 nano second from 12:00:00 midnight, January 1, 0001 /// </summary> [Required] public long IntialUTCTime { get; set; } /// <summary> /// End DateTime of repeating if 0 time block not repeating. /// DateTime.Ticks value for 100 nano second from 12:00:00 midnight, January 1, 0001 /// </summary> [Required] public long EndUTCTime { get; set; } /// <summary> /// Size of this time block; Range of this time block /// DateTime.Ticks value For 100 nano second from 12:00:00 midnight, January 1, 0001 /// </summary> [Required] public long BlockSize { get; set; } /// <summary> /// Repeat period Of this Time block, 0 if this schedule is not repeating /// DateTime.Ticks value For 100 nano second from 12:00:00 midnight, January 1, 0001 /// </summary> [Required] public long RepeatPeriod { get; set; } /// <summary> /// Is timeblock is on allday colum /// </summary> [Required] public bool IsAllDay { get; set; } /// <summary> /// Schedule Number foregin /// </summary> [Required] public int ScheduleNo { get; set; } [ForeignKey("ScheduleNo")] public virtual Schedule Schedule { get; set; } } }
29.85
93
0.567281
[ "MIT" ]
GoodSSenDev/DailyTimeScheduler
DailyTimeScheduler.Model/TimeBlock.cs
1,793
C#
//------------------------------------------------------------------------------ // 此代码版权(除特别声明或在RRQMCore.XREF命名空间的代码)归作者本人若汝棋茗所有 // 源代码使用协议遵循本仓库的开源协议及附加协议,若本仓库没有设置,则按MIT开源协议授权 // CSDN博客:https://blog.csdn.net/qq_40374647 // 哔哩哔哩视频:https://space.bilibili.com/94253567 // Gitee源代码仓库:https://gitee.com/RRQM_Home // Github源代码仓库:https://github.com/RRQM // 交流QQ群:234762506 // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ #region License // Copyright (c) 2007 James Newton-King // // 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 License using System; using System.Collections.Generic; using RRQMCore.XREF.Newtonsoft.Json.Linq; using RRQMCore.XREF.Newtonsoft.Json.Serialization; using RRQMCore.XREF.Newtonsoft.Json.Utilities; #if !HAVE_LINQ using RRQMCore.XREF.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace RRQMCore.XREF.Newtonsoft.Json.Schema { [Obsolete("JSON Schema validation has been moved to its own package. See http://www.newtonsoft.com/jsonschema for more details.")] internal class JsonSchemaWriter { private readonly JsonWriter _writer; private readonly JsonSchemaResolver _resolver; public JsonSchemaWriter(JsonWriter writer, JsonSchemaResolver resolver) { ValidationUtils.ArgumentNotNull(writer, nameof(writer)); _writer = writer; _resolver = resolver; } private void ReferenceOrWriteSchema(JsonSchema schema) { if (schema.Id != null && _resolver.GetSchema(schema.Id) != null) { _writer.WriteStartObject(); _writer.WritePropertyName(JsonTypeReflector.RefPropertyName); _writer.WriteValue(schema.Id); _writer.WriteEndObject(); } else { WriteSchema(schema); } } public void WriteSchema(JsonSchema schema) { ValidationUtils.ArgumentNotNull(schema, nameof(schema)); if (!_resolver.LoadedSchemas.Contains(schema)) { _resolver.LoadedSchemas.Add(schema); } _writer.WriteStartObject(); WritePropertyIfNotNull(_writer, JsonSchemaConstants.IdPropertyName, schema.Id); WritePropertyIfNotNull(_writer, JsonSchemaConstants.TitlePropertyName, schema.Title); WritePropertyIfNotNull(_writer, JsonSchemaConstants.DescriptionPropertyName, schema.Description); WritePropertyIfNotNull(_writer, JsonSchemaConstants.RequiredPropertyName, schema.Required); WritePropertyIfNotNull(_writer, JsonSchemaConstants.ReadOnlyPropertyName, schema.ReadOnly); WritePropertyIfNotNull(_writer, JsonSchemaConstants.HiddenPropertyName, schema.Hidden); WritePropertyIfNotNull(_writer, JsonSchemaConstants.TransientPropertyName, schema.Transient); if (schema.Type != null) { WriteType(JsonSchemaConstants.TypePropertyName, _writer, schema.Type.GetValueOrDefault()); } if (!schema.AllowAdditionalProperties) { _writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName); _writer.WriteValue(schema.AllowAdditionalProperties); } else { if (schema.AdditionalProperties != null) { _writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName); ReferenceOrWriteSchema(schema.AdditionalProperties); } } if (!schema.AllowAdditionalItems) { _writer.WritePropertyName(JsonSchemaConstants.AdditionalItemsPropertyName); _writer.WriteValue(schema.AllowAdditionalItems); } else { if (schema.AdditionalItems != null) { _writer.WritePropertyName(JsonSchemaConstants.AdditionalItemsPropertyName); ReferenceOrWriteSchema(schema.AdditionalItems); } } WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.PropertiesPropertyName, schema.Properties); WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.PatternPropertiesPropertyName, schema.PatternProperties); WriteItems(schema); WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumPropertyName, schema.Minimum); WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumPropertyName, schema.Maximum); WritePropertyIfNotNull(_writer, JsonSchemaConstants.ExclusiveMinimumPropertyName, schema.ExclusiveMinimum); WritePropertyIfNotNull(_writer, JsonSchemaConstants.ExclusiveMaximumPropertyName, schema.ExclusiveMaximum); WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumLengthPropertyName, schema.MinimumLength); WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumLengthPropertyName, schema.MaximumLength); WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumItemsPropertyName, schema.MinimumItems); WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumItemsPropertyName, schema.MaximumItems); WritePropertyIfNotNull(_writer, JsonSchemaConstants.DivisibleByPropertyName, schema.DivisibleBy); WritePropertyIfNotNull(_writer, JsonSchemaConstants.FormatPropertyName, schema.Format); WritePropertyIfNotNull(_writer, JsonSchemaConstants.PatternPropertyName, schema.Pattern); if (schema.Enum != null) { _writer.WritePropertyName(JsonSchemaConstants.EnumPropertyName); _writer.WriteStartArray(); foreach (JToken token in schema.Enum) { token.WriteTo(_writer); } _writer.WriteEndArray(); } if (schema.Default != null) { _writer.WritePropertyName(JsonSchemaConstants.DefaultPropertyName); schema.Default.WriteTo(_writer); } if (schema.Disallow != null) { WriteType(JsonSchemaConstants.DisallowPropertyName, _writer, schema.Disallow.GetValueOrDefault()); } if (schema.Extends != null && schema.Extends.Count > 0) { _writer.WritePropertyName(JsonSchemaConstants.ExtendsPropertyName); if (schema.Extends.Count == 1) { ReferenceOrWriteSchema(schema.Extends[0]); } else { _writer.WriteStartArray(); foreach (JsonSchema jsonSchema in schema.Extends) { ReferenceOrWriteSchema(jsonSchema); } _writer.WriteEndArray(); } } _writer.WriteEndObject(); } private void WriteSchemaDictionaryIfNotNull(JsonWriter writer, string propertyName, IDictionary<string, JsonSchema> properties) { if (properties != null) { writer.WritePropertyName(propertyName); writer.WriteStartObject(); foreach (KeyValuePair<string, JsonSchema> property in properties) { writer.WritePropertyName(property.Key); ReferenceOrWriteSchema(property.Value); } writer.WriteEndObject(); } } private void WriteItems(JsonSchema schema) { if (schema.Items == null && !schema.PositionalItemsValidation) { return; } _writer.WritePropertyName(JsonSchemaConstants.ItemsPropertyName); if (!schema.PositionalItemsValidation) { if (schema.Items != null && schema.Items.Count > 0) { ReferenceOrWriteSchema(schema.Items[0]); } else { _writer.WriteStartObject(); _writer.WriteEndObject(); } return; } _writer.WriteStartArray(); if (schema.Items != null) { foreach (JsonSchema itemSchema in schema.Items) { ReferenceOrWriteSchema(itemSchema); } } _writer.WriteEndArray(); } private void WriteType(string propertyName, JsonWriter writer, JsonSchemaType type) { if (Enum.IsDefined(typeof(JsonSchemaType), type)) { writer.WritePropertyName(propertyName); writer.WriteValue(JsonSchemaBuilder.MapType(type)); } else { IEnumerator<JsonSchemaType> en = EnumUtils.GetFlagsValues(type).Where(v => v != JsonSchemaType.None).GetEnumerator(); if (en.MoveNext()) { writer.WritePropertyName(propertyName); JsonSchemaType first = en.Current; if (en.MoveNext()) { writer.WriteStartArray(); writer.WriteValue(JsonSchemaBuilder.MapType(first)); do { writer.WriteValue(JsonSchemaBuilder.MapType(en.Current)); } while (en.MoveNext()); writer.WriteEndArray(); } else { writer.WriteValue(JsonSchemaBuilder.MapType(first)); } } } } private void WritePropertyIfNotNull(JsonWriter writer, string propertyName, object value) { if (value != null) { writer.WritePropertyName(propertyName); writer.WriteValue(value); } } } }
41.722628
135
0.591935
[ "Apache-2.0" ]
RRQM/RRQMCore
RRQMCore/XREF/Newtonsoft.Json/Schema/JsonSchemaWriter.cs
11,646
C#
namespace KalosfideAPI.Sécurité { public class ConnectionVue { public string UserName { get; set; } public string Password { get; set; } public bool Persistant { get; set; } } }
21.5
44
0.609302
[ "MIT" ]
kalosfide/KalosfideAPI
KalosfideAPI/Utilisateurs/ConnectionVue.cs
219
C#
/* * Copyright 2019 GridGain Systems, Inc. and Contributors. * * Licensed under the GridGain Community Edition License (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.gridgain.com/products/software/community-edition/gridgain-community-edition-license * * 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. */ #pragma warning disable 1587 // invalid XML comment /// <summary> /// Persistent Store APIs. /// </summary> namespace Apache.Ignite.Core.PersistentStore { // No-op. }
33.076923
102
0.74186
[ "CC0-1.0" ]
Diffblue-benchmarks/Gridgain-gridgain
modules/platforms/dotnet/Apache.Ignite.Core/PersistentStore/Package-Info.cs
862
C#
#region License // // Author: Joe McLain <nmp.developer@outlook.com> // Copyright (c) 2015, Joe McLain and Digital Writing // // Licensed under Eclipse Public License, Version 1.0 (EPL-1.0) // See the file LICENSE.txt for details. // #endregion #region Generated // // This file was generated by a tool on 9/10/2015 9:54:54 AM an should not be // modified unless removed from the "Others" directory and added to // a different collection of Tags // // Any modifications will be lost the next time the file is generated. // #endregion using System; using System.Collections.Generic; using System.Linq; namespace SharpHtml { ///////////////////////////////////////////////////////////////////////////// public class Dialog : Tag { protected override string _TagName => "dialog"; ///////////////////////////////////////////////////////////////////////////// public Dialog() { } } }
24.405405
79
0.589147
[ "EPL-1.0" ]
gitsharper/SharpHtml
SharpHtml/src/Tags/Others/Dialog.cs
903
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org) // Copyright (c) 2018-2021 Stride and its contributors (https://stride3d.net) // Copyright (c) 2011-2018 Silicon Studio Corp. (https://www.siliconstudio.co.jp) // See the LICENSE.md file in the project root for full license information. using System; using System.Threading.Tasks; using Stride.Core.Assets.Editor.Services; using Stride.Core.Assets.Quantum; using Stride.Core.Assets.Yaml; using Stride.Core; using Stride.Core.Reflection; using Stride.Core.Quantum; namespace Stride.Core.Assets.Editor.ViewModel.CopyPasteProcessors { public abstract class PasteProcessorBase : IPasteProcessor { /// <inheritdoc /> public abstract bool Accept(Type targetRootType, Type targetMemberType, Type pastedDataType); /// <inheritdoc /> public abstract bool ProcessDeserializedData(AssetPropertyGraphContainer graphContainer, object targetRootObject, Type targetMemberType, ref object data, bool isRootDataObjectReference, AssetId? sourceId, YamlAssetMetadata<OverrideType> overrides, YamlAssetPath basePath); /// <inheritdoc /> public virtual Task Paste(IPasteItem pasteResultItem, AssetPropertyGraph propertyGraph, ref NodeAccessor nodeAccessor, ref PropertyContainer propertyContainer) { // default implementation does nothing return Task.CompletedTask; } } }
42.264706
280
0.754349
[ "MIT" ]
Ethereal77/stride
sources/editor/Stride.Core.Assets.Editor/ViewModel/CopyPasteProcessors/PasteProcessorBase.cs
1,437
C#
// (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Public License (Ms-PL). // Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details. // All other rights reserved. using System; using System.Collections.Generic; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace Microsoft.Phone.Controls { /// <summary> /// The GestureListener class raises events similar to those provided by the XNA TouchPanel, but it is designed for /// XAML's event-driven model, rather than XNA's loop/polling model, and it also takes care of the hit testing /// and event routing. /// </summary> [System.Obsolete("GestureListener is obsolete beginning in Windows Phone 8, as the built-in manipulation and gesture events on UIElement now have functional parity with it.")] public partial class GestureListener { private enum GestureState { None, Hold, Undetermined, Drag, Pinch, } private static bool _isInitialized = false; private static Point _gestureOrigin; private static bool _gestureChanged = false; private static List<UIElement> _elements; private static GestureState _state = GestureState.None; private static ManipulationDeltaEventArgs _previousDelta = null; internal static void Initialize(DependencyObject o) { var gestureSensitiveElement = o as FrameworkElement; if (!_isInitialized && gestureSensitiveElement != null) { // We need to add event handlers to the application root visual, but it may not // be available yet. If that's the case, defer initialization until the visual // tree is loaded. if (Application.Current.RootVisual == null) { gestureSensitiveElement.Loaded += OnGestureSensitiveElementLoaded; } else { Initialize(); } } } private static void OnGestureSensitiveElementLoaded(object sender, RoutedEventArgs e) { Initialize(); (sender as FrameworkElement).Loaded -= OnGestureSensitiveElementLoaded; } private static void Initialize() { var root = Application.Current.RootVisual; System.Diagnostics.Debug.Assert(root != null); root.AddHandler(UIElement.TapEvent, new EventHandler<System.Windows.Input.GestureEventArgs>(OnTap), true); root.AddHandler(UIElement.DoubleTapEvent, new EventHandler<System.Windows.Input.GestureEventArgs>(OnDoubleTap), true); root.AddHandler(UIElement.HoldEvent, new EventHandler<System.Windows.Input.GestureEventArgs>(OnHold), true); root.AddHandler(UIElement.ManipulationStartedEvent, new EventHandler<System.Windows.Input.ManipulationStartedEventArgs>(OnManipulationStarted), true); root.AddHandler(UIElement.ManipulationDeltaEvent, new EventHandler<System.Windows.Input.ManipulationDeltaEventArgs>(OnManipulationDelta), true); root.AddHandler(UIElement.ManipulationCompletedEvent, new EventHandler<System.Windows.Input.ManipulationCompletedEventArgs>(OnManipulationCompleted), true); _isInitialized = true; } private static void OnTap(object sender, System.Windows.Input.GestureEventArgs e) { var touchPoint = e.GetPosition(Application.Current.RootVisual); touchPoint = GetInverseTransform(true).Transform(touchPoint); RaiseGestureEvent((handler) => handler.Tap, () => new Microsoft.Phone.Controls.GestureEventArgs(_gestureOrigin, touchPoint), false); OnGestureComplete(touchPoint, touchPoint); } private static void OnDoubleTap(object sender, System.Windows.Input.GestureEventArgs e) { var touchPoint = e.GetPosition(Application.Current.RootVisual); touchPoint = GetInverseTransform(true).Transform(touchPoint); RaiseGestureEvent((handler) => handler.DoubleTap, () => new Microsoft.Phone.Controls.GestureEventArgs(_gestureOrigin, touchPoint), false); OnGestureComplete(touchPoint, touchPoint); } private static void OnHold(object sender, System.Windows.Input.GestureEventArgs e) { _state = GestureState.Hold; var touchPoint = e.GetPosition(Application.Current.RootVisual); touchPoint = GetInverseTransform(true).Transform(touchPoint); RaiseGestureEvent((handler) => handler.Hold, () => new Microsoft.Phone.Controls.GestureEventArgs(_gestureOrigin, touchPoint), false); } private static void OnManipulationStarted(object sender, ManipulationStartedEventArgs e) { OnGestureBegin(GetInverseTransform(true, e.ManipulationContainer).Transform(e.ManipulationOrigin)); } private static void OnManipulationDelta(object sender, ManipulationDeltaEventArgs e) { var oldState = _state; var wasGestureChanged = _gestureChanged; _state = e.PinchManipulation == null ? GestureState.Drag : GestureState.Pinch; var transformToRoot = GetInverseTransform(true, e.ManipulationContainer); if (_state == GestureState.Drag) { var deltaTransform = GetInverseTransform(false, e.ManipulationContainer); var totalTranslation = deltaTransform.Transform(e.CumulativeManipulation.Translation); var deltaTranslation = deltaTransform.Transform(e.DeltaManipulation.Translation); Orientation orientation = GetOrientation(totalTranslation.X, totalTranslation.Y); if (wasGestureChanged) { OnGestureBegin(transformToRoot.Transform(e.ManipulationOrigin)); // Fire the deferred DragStarted RaiseGestureEvent( (handler) => handler.DragStarted, () => new Microsoft.Phone.Controls.DragStartedGestureEventArgs(_gestureOrigin, orientation), true); } if (oldState == GestureState.Drag) { // Continue the drag var currentPoint = new Point(_gestureOrigin.X + totalTranslation.X, _gestureOrigin.Y + totalTranslation.Y); RaiseGestureEvent( (handler) => handler.DragDelta, () => new Microsoft.Phone.Controls.DragDeltaGestureEventArgs(_gestureOrigin, currentPoint, deltaTranslation, orientation), false); } else { if (oldState == GestureState.Pinch) { // End the pinch OnPinchCompleted(_previousDelta); // Transitioning from a pinch to a drag. _gestureChanged = true; // Note that we are deferring the DragStarted event until the next // ManipulationDelta is received. // We want to fire a DragStarted event now, but the ManipulationOrigin // for the first ManipulationDelta after a pinch is completed always corresponds // to the primary touch point from the previous pinch, even if it was the // secondary touch point that remains on the screen. // Since the pinch is now completed, but we haven't been able to determine // the drag origin, we'll go back to the Undetermined state. _state = GestureState.Undetermined; } else { RaiseGestureEvent( (handler) => handler.DragStarted, () => new Microsoft.Phone.Controls.DragStartedGestureEventArgs(_gestureOrigin, orientation), true); } } } else // _state is GestureState.Pinch { var originalPrimary = transformToRoot.Transform(e.PinchManipulation.Original.PrimaryContact); var originalSecondary = transformToRoot.Transform(e.PinchManipulation.Original.SecondaryContact); var currentPrimary = transformToRoot.Transform(e.PinchManipulation.Current.PrimaryContact); var currentSecondary = transformToRoot.Transform(e.PinchManipulation.Current.SecondaryContact); if (wasGestureChanged) { OnGestureBegin(originalPrimary); } if (oldState == GestureState.Pinch) { // Continue the pinch RaiseGestureEvent( (handler) => handler.PinchDelta, () => new Microsoft.Phone.Controls.PinchGestureEventArgs(originalPrimary, originalSecondary, currentPrimary, currentSecondary), false); } else { if (oldState == GestureState.Drag) { // End the drag OnDragCompleted(_previousDelta); // Transitioning from a drag to a pinch _gestureChanged = true; } // Start the pinch RaiseGestureEvent( (handler) => handler.PinchStarted, () => new Microsoft.Phone.Controls.PinchStartedGestureEventArgs(originalPrimary, originalSecondary, currentPrimary, currentSecondary), true); } } _previousDelta = e; } private static void OnManipulationCompleted(object sender, ManipulationCompletedEventArgs e) { if (_state == GestureState.Drag) { OnDragCompleted(_previousDelta, e); } else if (_state == GestureState.Pinch) { System.Diagnostics.Debug.Assert(_previousDelta.PinchManipulation != null); OnPinchCompleted(_previousDelta, true); } else if (_state == GestureState.Hold) { var deltaTransform = GetInverseTransform(false, e.ManipulationContainer); var totalTranslation = deltaTransform.Transform(e.TotalManipulation.Translation); var currentPoint = new Point(_gestureOrigin.X + totalTranslation.X, _gestureOrigin.Y + totalTranslation.Y); OnGestureComplete(_gestureOrigin, currentPoint); } } private static void OnPinchCompleted(ManipulationDeltaEventArgs lastPinchInfo, bool gestureCompleted = false) { var transformToRoot = GetInverseTransform(true, lastPinchInfo.ManipulationContainer); var originalPrimary = transformToRoot.Transform(_previousDelta.PinchManipulation.Original.PrimaryContact); var currentPrimary = transformToRoot.Transform(_previousDelta.PinchManipulation.Current.PrimaryContact); RaiseGestureEvent( (handler) => handler.PinchCompleted, () => new Microsoft.Phone.Controls.PinchGestureEventArgs( originalPrimary, transformToRoot.Transform(_previousDelta.PinchManipulation.Original.SecondaryContact), currentPrimary, transformToRoot.Transform(_previousDelta.PinchManipulation.Current.SecondaryContact)), false); if (gestureCompleted) { OnGestureComplete(originalPrimary, currentPrimary); } } private static void OnDragCompleted(ManipulationDeltaEventArgs lastDragInfo, ManipulationCompletedEventArgs completedInfo = null) { GeneralTransform deltaTransform = null; Point releasePoint; Point totalTranslation; Point finalVelocity; Orientation orientation = Orientation.Horizontal; bool gestureCompleted = false; releasePoint = totalTranslation = finalVelocity = new Point(); if (completedInfo != null) { gestureCompleted = true; deltaTransform = GetInverseTransform(false, completedInfo.ManipulationContainer); totalTranslation = deltaTransform.Transform(completedInfo.TotalManipulation.Translation); finalVelocity = deltaTransform.Transform(completedInfo.FinalVelocities.LinearVelocity); if (completedInfo.IsInertial) { RaiseGestureEvent( (handler) => handler.Flick, () => new Microsoft.Phone.Controls.FlickGestureEventArgs( _gestureOrigin, finalVelocity), true); } } else { deltaTransform = GetInverseTransform(false, lastDragInfo.ManipulationContainer); totalTranslation = deltaTransform.Transform(lastDragInfo.CumulativeManipulation.Translation); finalVelocity = deltaTransform.Transform(lastDragInfo.Velocities.LinearVelocity); } releasePoint = new Point(_gestureOrigin.X + totalTranslation.X, _gestureOrigin.Y + totalTranslation.Y); orientation = GetOrientation(totalTranslation.X, totalTranslation.Y); RaiseGestureEvent( (handler) => handler.DragCompleted, () => new Microsoft.Phone.Controls.DragCompletedGestureEventArgs( _gestureOrigin, releasePoint, totalTranslation, orientation, finalVelocity), false); if (gestureCompleted) { OnGestureComplete(_gestureOrigin, releasePoint); } } private static void OnGestureBegin(Point touchPoint) { _gestureChanged = false; _gestureOrigin = touchPoint; _elements = new List<UIElement>(VisualTreeHelper.FindElementsInHostCoordinates(touchPoint, Application.Current.RootVisual)); if (_state == GestureState.None) { // The GestureBegin event should only be raised if there were no fingers on the screen previously. _state = GestureState.Undetermined; RaiseGestureEvent( (handler) => handler.GestureBegin, () => new Microsoft.Phone.Controls.GestureEventArgs(touchPoint, touchPoint), false); } } private static void OnGestureComplete(Point gestureOrigin, Point releasePoint) { _state = GestureState.None; _previousDelta = null; RaiseGestureEvent((handler) => handler.GestureCompleted, () => new Microsoft.Phone.Controls.GestureEventArgs(gestureOrigin, releasePoint), false); } private static GeneralTransform GetInverseTransform(bool includeOffset, UIElement target = null) { GeneralTransform transform = Application.Current.RootVisual.TransformToVisual(target).Inverse; if (!includeOffset) { MatrixTransform matrixTransform = transform as MatrixTransform; if (matrixTransform != null) { Matrix matrix = matrixTransform.Matrix; matrix.OffsetX = matrix.OffsetY = 0; matrixTransform.Matrix = matrix; } } return transform; } private static Orientation GetOrientation(double x, double y) { return Math.Abs(x) >= Math.Abs(y) ? System.Windows.Controls.Orientation.Horizontal : System.Windows.Controls.Orientation.Vertical; } /// <summary> /// This method does all the necessary work to raise a gesture event. It sets the orginal source, does the routing, /// handles Handled, and only creates the event args if they are needed. /// </summary> /// <typeparam name="T">This is the type of event args that will be raised.</typeparam> /// <param name="eventGetter">Gets the specific event to raise.</param> /// <param name="argsGetter">Lazy creator function for the event args.</param> /// <param name="releaseMouseCapture">Indicates whether the mouse capture should be released </param> private static void RaiseGestureEvent<T>( Func<GestureListener, EventHandler<T>> eventGetter, Func<T> argsGetter, bool releaseMouseCapture) where T : GestureEventArgs { T args = null; FrameworkElement originalSource = null; bool handled = false; foreach (FrameworkElement element in _elements) { if (releaseMouseCapture) { element.ReleaseMouseCapture(); } if (!handled) { if (originalSource == null) { originalSource = element; } GestureListener helper = GestureService.GetGestureListenerInternal(element, false); if (helper != null) { SafeRaise.Raise(eventGetter(helper), element, () => { if (args == null) { args = argsGetter(); args.OriginalSource = originalSource; } return args; }); } if (args != null && args.Handled == true) { handled = true; } } } } } }
45.410194
179
0.578599
[ "MIT" ]
misenhower/WPRemote
CommonLibraries/Libraries/Microsoft.Phone.Controls.Toolkit/Microsoft.Phone.Controls.Toolkit.WP8/Input/GestureListenerStatic.cs
18,711
C#
 namespace Daily_Account { partial class UpdateSuppiers { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.AC_NoTextBox = new Guna.UI2.WinForms.Guna2TextBox(); this.label10 = new System.Windows.Forms.Label(); this.IFSCCodeTextBox = new Guna.UI2.WinForms.Guna2TextBox(); this.label9 = new System.Windows.Forms.Label(); this.BankNameTextBox = new Guna.UI2.WinForms.Guna2TextBox(); this.label6 = new System.Windows.Forms.Label(); this.UpdateSuppierButton = new Guna.UI2.WinForms.Guna2Button(); this.AddressRichTextBox = new System.Windows.Forms.RichTextBox(); this.label8 = new System.Windows.Forms.Label(); this.label7 = new System.Windows.Forms.Label(); this.GSTINTextBox = new Guna.UI2.WinForms.Guna2TextBox(); this.PinCodeTextBox = new Guna.UI2.WinForms.Guna2TextBox(); this.label5 = new System.Windows.Forms.Label(); this.CityTextBox = new Guna.UI2.WinForms.Guna2TextBox(); this.label4 = new System.Windows.Forms.Label(); this.StateTextBox = new Guna.UI2.WinForms.Guna2TextBox(); this.label3 = new System.Windows.Forms.Label(); this.PhoneTextBox = new Guna.UI2.WinForms.Guna2TextBox(); this.label2 = new System.Windows.Forms.Label(); this.EmailTextBox = new Guna.UI2.WinForms.Guna2TextBox(); this.label1 = new System.Windows.Forms.Label(); this.SupplierName_TextBox = new Guna.UI2.WinForms.Guna2TextBox(); this.label11 = new System.Windows.Forms.Label(); this.lineShape1 = new Microsoft.VisualBasic.PowerPacks.LineShape(); this.shapeContainer1 = new Microsoft.VisualBasic.PowerPacks.ShapeContainer(); this.DeleteSupplierButton = new Guna.UI2.WinForms.Guna2Button(); this.SuspendLayout(); // // AC_NoTextBox // this.AC_NoTextBox.Animated = true; this.AC_NoTextBox.AutoRoundedCorners = true; this.AC_NoTextBox.BorderRadius = 17; this.AC_NoTextBox.Cursor = System.Windows.Forms.Cursors.IBeam; this.AC_NoTextBox.DefaultText = ""; this.AC_NoTextBox.DisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(208)))), ((int)(((byte)(208)))), ((int)(((byte)(208))))); this.AC_NoTextBox.DisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(226)))), ((int)(((byte)(226)))), ((int)(((byte)(226))))); this.AC_NoTextBox.DisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.AC_NoTextBox.DisabledState.Parent = this.AC_NoTextBox; this.AC_NoTextBox.DisabledState.PlaceholderForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.AC_NoTextBox.FocusedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.AC_NoTextBox.FocusedState.Parent = this.AC_NoTextBox; this.AC_NoTextBox.Font = new System.Drawing.Font("Segoe UI", 16F); this.AC_NoTextBox.HoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.AC_NoTextBox.HoverState.Parent = this.AC_NoTextBox; this.AC_NoTextBox.Location = new System.Drawing.Point(182, 452); this.AC_NoTextBox.Margin = new System.Windows.Forms.Padding(6, 7, 6, 7); this.AC_NoTextBox.Name = "AC_NoTextBox"; this.AC_NoTextBox.PasswordChar = '\0'; this.AC_NoTextBox.PlaceholderText = ""; this.AC_NoTextBox.SelectedText = ""; this.AC_NoTextBox.ShadowDecoration.Parent = this.AC_NoTextBox; this.AC_NoTextBox.Size = new System.Drawing.Size(258, 36); this.AC_NoTextBox.Style = Guna.UI2.WinForms.Enums.TextBoxStyle.Material; this.AC_NoTextBox.TabIndex = 27; // // label10 // this.label10.AutoSize = true; this.label10.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label10.Location = new System.Drawing.Point(8, 462); this.label10.Name = "label10"; this.label10.Size = new System.Drawing.Size(101, 26); this.label10.TabIndex = 40; this.label10.Text = "A/C NO."; // // IFSCCodeTextBox // this.IFSCCodeTextBox.Animated = true; this.IFSCCodeTextBox.AutoRoundedCorners = true; this.IFSCCodeTextBox.BorderRadius = 17; this.IFSCCodeTextBox.Cursor = System.Windows.Forms.Cursors.IBeam; this.IFSCCodeTextBox.DefaultText = ""; this.IFSCCodeTextBox.DisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(208)))), ((int)(((byte)(208)))), ((int)(((byte)(208))))); this.IFSCCodeTextBox.DisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(226)))), ((int)(((byte)(226)))), ((int)(((byte)(226))))); this.IFSCCodeTextBox.DisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.IFSCCodeTextBox.DisabledState.Parent = this.IFSCCodeTextBox; this.IFSCCodeTextBox.DisabledState.PlaceholderForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.IFSCCodeTextBox.FocusedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.IFSCCodeTextBox.FocusedState.Parent = this.IFSCCodeTextBox; this.IFSCCodeTextBox.Font = new System.Drawing.Font("Segoe UI", 16F); this.IFSCCodeTextBox.HoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.IFSCCodeTextBox.HoverState.Parent = this.IFSCCodeTextBox; this.IFSCCodeTextBox.Location = new System.Drawing.Point(182, 380); this.IFSCCodeTextBox.Margin = new System.Windows.Forms.Padding(6, 7, 6, 7); this.IFSCCodeTextBox.Name = "IFSCCodeTextBox"; this.IFSCCodeTextBox.PasswordChar = '\0'; this.IFSCCodeTextBox.PlaceholderText = ""; this.IFSCCodeTextBox.SelectedText = ""; this.IFSCCodeTextBox.ShadowDecoration.Parent = this.IFSCCodeTextBox; this.IFSCCodeTextBox.Size = new System.Drawing.Size(258, 36); this.IFSCCodeTextBox.Style = Guna.UI2.WinForms.Enums.TextBoxStyle.Material; this.IFSCCodeTextBox.TabIndex = 26; // // label9 // this.label9.AutoSize = true; this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label9.Location = new System.Drawing.Point(8, 390); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(129, 26); this.label9.TabIndex = 37; this.label9.Text = "IFSC Code"; // // BankNameTextBox // this.BankNameTextBox.Animated = true; this.BankNameTextBox.AutoRoundedCorners = true; this.BankNameTextBox.BorderRadius = 17; this.BankNameTextBox.Cursor = System.Windows.Forms.Cursors.IBeam; this.BankNameTextBox.DefaultText = ""; this.BankNameTextBox.DisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(208)))), ((int)(((byte)(208)))), ((int)(((byte)(208))))); this.BankNameTextBox.DisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(226)))), ((int)(((byte)(226)))), ((int)(((byte)(226))))); this.BankNameTextBox.DisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.BankNameTextBox.DisabledState.Parent = this.BankNameTextBox; this.BankNameTextBox.DisabledState.PlaceholderForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.BankNameTextBox.FocusedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.BankNameTextBox.FocusedState.Parent = this.BankNameTextBox; this.BankNameTextBox.Font = new System.Drawing.Font("Segoe UI", 16F); this.BankNameTextBox.HoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.BankNameTextBox.HoverState.Parent = this.BankNameTextBox; this.BankNameTextBox.Location = new System.Drawing.Point(182, 321); this.BankNameTextBox.Margin = new System.Windows.Forms.Padding(6, 7, 6, 7); this.BankNameTextBox.Name = "BankNameTextBox"; this.BankNameTextBox.PasswordChar = '\0'; this.BankNameTextBox.PlaceholderText = ""; this.BankNameTextBox.SelectedText = ""; this.BankNameTextBox.ShadowDecoration.Parent = this.BankNameTextBox; this.BankNameTextBox.Size = new System.Drawing.Size(258, 36); this.BankNameTextBox.Style = Guna.UI2.WinForms.Enums.TextBoxStyle.Material; this.BankNameTextBox.TabIndex = 25; // // label6 // this.label6.AutoSize = true; this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label6.Location = new System.Drawing.Point(8, 331); this.label6.Name = "label6"; this.label6.Size = new System.Drawing.Size(151, 26); this.label6.TabIndex = 35; this.label6.Text = "Bank Name:-"; // // UpdateSuppierButton // this.UpdateSuppierButton.Animated = true; this.UpdateSuppierButton.AutoRoundedCorners = true; this.UpdateSuppierButton.BorderRadius = 21; this.UpdateSuppierButton.CheckedState.Parent = this.UpdateSuppierButton; this.UpdateSuppierButton.CustomImages.Parent = this.UpdateSuppierButton; this.UpdateSuppierButton.Font = new System.Drawing.Font("Segoe UI", 18F); this.UpdateSuppierButton.ForeColor = System.Drawing.Color.White; this.UpdateSuppierButton.HoverState.Parent = this.UpdateSuppierButton; this.UpdateSuppierButton.Location = new System.Drawing.Point(462, 470); this.UpdateSuppierButton.Name = "UpdateSuppierButton"; this.UpdateSuppierButton.ShadowDecoration.Parent = this.UpdateSuppierButton; this.UpdateSuppierButton.Size = new System.Drawing.Size(425, 45); this.UpdateSuppierButton.TabIndex = 31; this.UpdateSuppierButton.Text = "Update Supplier"; this.UpdateSuppierButton.Click += new System.EventHandler(this.UpdateSuppierButton_Click); // // AddressRichTextBox // this.AddressRichTextBox.Font = new System.Drawing.Font("Segoe UI", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.AddressRichTextBox.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149))))); this.AddressRichTextBox.Location = new System.Drawing.Point(468, 230); this.AddressRichTextBox.Name = "AddressRichTextBox"; this.AddressRichTextBox.Size = new System.Drawing.Size(419, 168); this.AddressRichTextBox.TabIndex = 30; this.AddressRichTextBox.Text = ""; // // label8 // this.label8.AutoSize = true; this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label8.Location = new System.Drawing.Point(463, 182); this.label8.Name = "label8"; this.label8.Size = new System.Drawing.Size(121, 26); this.label8.TabIndex = 32; this.label8.Text = "Address: -"; // // label7 // this.label7.AutoSize = true; this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label7.Location = new System.Drawing.Point(457, 128); this.label7.Name = "label7"; this.label7.Size = new System.Drawing.Size(105, 26); this.label7.TabIndex = 33; this.label7.Text = "GSTIN: -"; // // GSTINTextBox // this.GSTINTextBox.Animated = true; this.GSTINTextBox.AutoRoundedCorners = true; this.GSTINTextBox.BorderRadius = 17; this.GSTINTextBox.Cursor = System.Windows.Forms.Cursors.IBeam; this.GSTINTextBox.DefaultText = ""; this.GSTINTextBox.DisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(208)))), ((int)(((byte)(208)))), ((int)(((byte)(208))))); this.GSTINTextBox.DisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(226)))), ((int)(((byte)(226)))), ((int)(((byte)(226))))); this.GSTINTextBox.DisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.GSTINTextBox.DisabledState.Parent = this.GSTINTextBox; this.GSTINTextBox.DisabledState.PlaceholderForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.GSTINTextBox.FocusedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.GSTINTextBox.FocusedState.Parent = this.GSTINTextBox; this.GSTINTextBox.Font = new System.Drawing.Font("Segoe UI", 16F); this.GSTINTextBox.HoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.GSTINTextBox.HoverState.Parent = this.GSTINTextBox; this.GSTINTextBox.Location = new System.Drawing.Point(635, 128); this.GSTINTextBox.Margin = new System.Windows.Forms.Padding(6, 7, 6, 7); this.GSTINTextBox.Name = "GSTINTextBox"; this.GSTINTextBox.PasswordChar = '\0'; this.GSTINTextBox.PlaceholderText = ""; this.GSTINTextBox.SelectedText = ""; this.GSTINTextBox.ShadowDecoration.Parent = this.GSTINTextBox; this.GSTINTextBox.Size = new System.Drawing.Size(258, 36); this.GSTINTextBox.Style = Guna.UI2.WinForms.Enums.TextBoxStyle.Material; this.GSTINTextBox.TabIndex = 29; // // PinCodeTextBox // this.PinCodeTextBox.Animated = true; this.PinCodeTextBox.AutoRoundedCorners = true; this.PinCodeTextBox.BorderRadius = 17; this.PinCodeTextBox.Cursor = System.Windows.Forms.Cursors.IBeam; this.PinCodeTextBox.DefaultText = ""; this.PinCodeTextBox.DisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(208)))), ((int)(((byte)(208)))), ((int)(((byte)(208))))); this.PinCodeTextBox.DisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(226)))), ((int)(((byte)(226)))), ((int)(((byte)(226))))); this.PinCodeTextBox.DisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.PinCodeTextBox.DisabledState.Parent = this.PinCodeTextBox; this.PinCodeTextBox.DisabledState.PlaceholderForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.PinCodeTextBox.FocusedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.PinCodeTextBox.FocusedState.Parent = this.PinCodeTextBox; this.PinCodeTextBox.Font = new System.Drawing.Font("Segoe UI", 16F); this.PinCodeTextBox.HoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.PinCodeTextBox.HoverState.Parent = this.PinCodeTextBox; this.PinCodeTextBox.Location = new System.Drawing.Point(182, 266); this.PinCodeTextBox.Margin = new System.Windows.Forms.Padding(6, 7, 6, 7); this.PinCodeTextBox.Name = "PinCodeTextBox"; this.PinCodeTextBox.PasswordChar = '\0'; this.PinCodeTextBox.PlaceholderText = ""; this.PinCodeTextBox.SelectedText = ""; this.PinCodeTextBox.ShadowDecoration.Parent = this.PinCodeTextBox; this.PinCodeTextBox.Size = new System.Drawing.Size(258, 36); this.PinCodeTextBox.Style = Guna.UI2.WinForms.Enums.TextBoxStyle.Material; this.PinCodeTextBox.TabIndex = 24; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.Location = new System.Drawing.Point(8, 276); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(132, 26); this.label5.TabIndex = 34; this.label5.Text = "Pin Code: -"; // // CityTextBox // this.CityTextBox.Animated = true; this.CityTextBox.AutoRoundedCorners = true; this.CityTextBox.BorderRadius = 17; this.CityTextBox.Cursor = System.Windows.Forms.Cursors.IBeam; this.CityTextBox.DefaultText = ""; this.CityTextBox.DisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(208)))), ((int)(((byte)(208)))), ((int)(((byte)(208))))); this.CityTextBox.DisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(226)))), ((int)(((byte)(226)))), ((int)(((byte)(226))))); this.CityTextBox.DisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.CityTextBox.DisabledState.Parent = this.CityTextBox; this.CityTextBox.DisabledState.PlaceholderForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.CityTextBox.FocusedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.CityTextBox.FocusedState.Parent = this.CityTextBox; this.CityTextBox.Font = new System.Drawing.Font("Segoe UI", 16F); this.CityTextBox.HoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.CityTextBox.HoverState.Parent = this.CityTextBox; this.CityTextBox.Location = new System.Drawing.Point(181, 205); this.CityTextBox.Margin = new System.Windows.Forms.Padding(6, 7, 6, 7); this.CityTextBox.Name = "CityTextBox"; this.CityTextBox.PasswordChar = '\0'; this.CityTextBox.PlaceholderText = ""; this.CityTextBox.SelectedText = ""; this.CityTextBox.ShadowDecoration.Parent = this.CityTextBox; this.CityTextBox.Size = new System.Drawing.Size(258, 36); this.CityTextBox.Style = Guna.UI2.WinForms.Enums.TextBoxStyle.Material; this.CityTextBox.TabIndex = 23; // // label4 // this.label4.AutoSize = true; this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.Location = new System.Drawing.Point(7, 215); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(76, 26); this.label4.TabIndex = 36; this.label4.Text = "City: -"; // // StateTextBox // this.StateTextBox.Animated = true; this.StateTextBox.AutoRoundedCorners = true; this.StateTextBox.BorderRadius = 17; this.StateTextBox.Cursor = System.Windows.Forms.Cursors.IBeam; this.StateTextBox.DefaultText = ""; this.StateTextBox.DisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(208)))), ((int)(((byte)(208)))), ((int)(((byte)(208))))); this.StateTextBox.DisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(226)))), ((int)(((byte)(226)))), ((int)(((byte)(226))))); this.StateTextBox.DisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.StateTextBox.DisabledState.Parent = this.StateTextBox; this.StateTextBox.DisabledState.PlaceholderForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.StateTextBox.FocusedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.StateTextBox.FocusedState.Parent = this.StateTextBox; this.StateTextBox.Font = new System.Drawing.Font("Segoe UI", 16F); this.StateTextBox.HoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.StateTextBox.HoverState.Parent = this.StateTextBox; this.StateTextBox.Location = new System.Drawing.Point(179, 147); this.StateTextBox.Margin = new System.Windows.Forms.Padding(6, 7, 6, 7); this.StateTextBox.Name = "StateTextBox"; this.StateTextBox.PasswordChar = '\0'; this.StateTextBox.PlaceholderText = ""; this.StateTextBox.SelectedText = ""; this.StateTextBox.ShadowDecoration.Parent = this.StateTextBox; this.StateTextBox.Size = new System.Drawing.Size(258, 36); this.StateTextBox.Style = Guna.UI2.WinForms.Enums.TextBoxStyle.Material; this.StateTextBox.TabIndex = 22; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.Location = new System.Drawing.Point(5, 157); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(90, 26); this.label3.TabIndex = 38; this.label3.Text = "State: -"; // // PhoneTextBox // this.PhoneTextBox.Animated = true; this.PhoneTextBox.AutoRoundedCorners = true; this.PhoneTextBox.BorderRadius = 17; this.PhoneTextBox.Cursor = System.Windows.Forms.Cursors.IBeam; this.PhoneTextBox.DefaultText = ""; this.PhoneTextBox.DisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(208)))), ((int)(((byte)(208)))), ((int)(((byte)(208))))); this.PhoneTextBox.DisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(226)))), ((int)(((byte)(226)))), ((int)(((byte)(226))))); this.PhoneTextBox.DisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.PhoneTextBox.DisabledState.Parent = this.PhoneTextBox; this.PhoneTextBox.DisabledState.PlaceholderForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.PhoneTextBox.FocusedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.PhoneTextBox.FocusedState.Parent = this.PhoneTextBox; this.PhoneTextBox.Font = new System.Drawing.Font("Segoe UI", 16F); this.PhoneTextBox.HoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.PhoneTextBox.HoverState.Parent = this.PhoneTextBox; this.PhoneTextBox.Location = new System.Drawing.Point(634, 59); this.PhoneTextBox.Margin = new System.Windows.Forms.Padding(6, 7, 6, 7); this.PhoneTextBox.Name = "PhoneTextBox"; this.PhoneTextBox.PasswordChar = '\0'; this.PhoneTextBox.PlaceholderText = ""; this.PhoneTextBox.SelectedText = ""; this.PhoneTextBox.ShadowDecoration.Parent = this.PhoneTextBox; this.PhoneTextBox.Size = new System.Drawing.Size(258, 36); this.PhoneTextBox.Style = Guna.UI2.WinForms.Enums.TextBoxStyle.Material; this.PhoneTextBox.TabIndex = 28; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.Location = new System.Drawing.Point(460, 69); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(102, 26); this.label2.TabIndex = 39; this.label2.Text = "Phone: -"; // // EmailTextBox // this.EmailTextBox.Animated = true; this.EmailTextBox.AutoRoundedCorners = true; this.EmailTextBox.BorderRadius = 17; this.EmailTextBox.Cursor = System.Windows.Forms.Cursors.IBeam; this.EmailTextBox.DefaultText = ""; this.EmailTextBox.DisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(208)))), ((int)(((byte)(208)))), ((int)(((byte)(208))))); this.EmailTextBox.DisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(226)))), ((int)(((byte)(226)))), ((int)(((byte)(226))))); this.EmailTextBox.DisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.EmailTextBox.DisabledState.Parent = this.EmailTextBox; this.EmailTextBox.DisabledState.PlaceholderForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.EmailTextBox.FocusedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.EmailTextBox.FocusedState.Parent = this.EmailTextBox; this.EmailTextBox.Font = new System.Drawing.Font("Segoe UI", 16F); this.EmailTextBox.HoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.EmailTextBox.HoverState.Parent = this.EmailTextBox; this.EmailTextBox.Location = new System.Drawing.Point(177, 88); this.EmailTextBox.Margin = new System.Windows.Forms.Padding(6, 7, 6, 7); this.EmailTextBox.Name = "EmailTextBox"; this.EmailTextBox.PasswordChar = '\0'; this.EmailTextBox.PlaceholderText = ""; this.EmailTextBox.SelectedText = ""; this.EmailTextBox.ShadowDecoration.Parent = this.EmailTextBox; this.EmailTextBox.Size = new System.Drawing.Size(258, 36); this.EmailTextBox.Style = Guna.UI2.WinForms.Enums.TextBoxStyle.Material; this.EmailTextBox.TabIndex = 21; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.Location = new System.Drawing.Point(3, 98); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(95, 26); this.label1.TabIndex = 41; this.label1.Text = "Email: -"; // // SupplierName_TextBox // this.SupplierName_TextBox.Animated = true; this.SupplierName_TextBox.AutoRoundedCorners = true; this.SupplierName_TextBox.BorderRadius = 17; this.SupplierName_TextBox.Cursor = System.Windows.Forms.Cursors.IBeam; this.SupplierName_TextBox.DefaultText = ""; this.SupplierName_TextBox.DisabledState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(208)))), ((int)(((byte)(208)))), ((int)(((byte)(208))))); this.SupplierName_TextBox.DisabledState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(226)))), ((int)(((byte)(226)))), ((int)(((byte)(226))))); this.SupplierName_TextBox.DisabledState.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.SupplierName_TextBox.DisabledState.Parent = this.SupplierName_TextBox; this.SupplierName_TextBox.DisabledState.PlaceholderForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(138)))), ((int)(((byte)(138)))), ((int)(((byte)(138))))); this.SupplierName_TextBox.FocusedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.SupplierName_TextBox.FocusedState.Parent = this.SupplierName_TextBox; this.SupplierName_TextBox.Font = new System.Drawing.Font("Segoe UI", 16F); this.SupplierName_TextBox.HoverState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255))))); this.SupplierName_TextBox.HoverState.Parent = this.SupplierName_TextBox; this.SupplierName_TextBox.Location = new System.Drawing.Point(177, 24); this.SupplierName_TextBox.Margin = new System.Windows.Forms.Padding(6, 7, 6, 7); this.SupplierName_TextBox.Name = "SupplierName_TextBox"; this.SupplierName_TextBox.PasswordChar = '\0'; this.SupplierName_TextBox.PlaceholderText = ""; this.SupplierName_TextBox.SelectedText = ""; this.SupplierName_TextBox.ShadowDecoration.Parent = this.SupplierName_TextBox; this.SupplierName_TextBox.Size = new System.Drawing.Size(258, 36); this.SupplierName_TextBox.Style = Guna.UI2.WinForms.Enums.TextBoxStyle.Material; this.SupplierName_TextBox.TabIndex = 20; // // label11 // this.label11.AutoSize = true; this.label11.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label11.Location = new System.Drawing.Point(3, 34); this.label11.Name = "label11"; this.label11.Size = new System.Drawing.Size(177, 26); this.label11.TabIndex = 42; this.label11.Text = "Supplier Name:"; // // lineShape1 // this.lineShape1.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(192)))), ((int)(((byte)(192))))); this.lineShape1.BorderWidth = 3; this.lineShape1.Name = "lineShape1"; this.lineShape1.X1 = 448; this.lineShape1.X2 = 448; this.lineShape1.Y1 = 2; this.lineShape1.Y2 = 529; // // shapeContainer1 // this.shapeContainer1.Location = new System.Drawing.Point(0, 0); this.shapeContainer1.Margin = new System.Windows.Forms.Padding(0); this.shapeContainer1.Name = "shapeContainer1"; this.shapeContainer1.Shapes.AddRange(new Microsoft.VisualBasic.PowerPacks.Shape[] { this.lineShape1}); this.shapeContainer1.Size = new System.Drawing.Size(897, 531); this.shapeContainer1.TabIndex = 43; this.shapeContainer1.TabStop = false; // // DeleteSupplierButton // this.DeleteSupplierButton.Animated = true; this.DeleteSupplierButton.AutoRoundedCorners = true; this.DeleteSupplierButton.BorderRadius = 21; this.DeleteSupplierButton.CheckedState.Parent = this.DeleteSupplierButton; this.DeleteSupplierButton.CustomImages.Parent = this.DeleteSupplierButton; this.DeleteSupplierButton.FillColor = System.Drawing.Color.Red; this.DeleteSupplierButton.Font = new System.Drawing.Font("Segoe UI", 18F); this.DeleteSupplierButton.ForeColor = System.Drawing.Color.White; this.DeleteSupplierButton.HoverState.Parent = this.DeleteSupplierButton; this.DeleteSupplierButton.Location = new System.Drawing.Point(462, 419); this.DeleteSupplierButton.Name = "DeleteSupplierButton"; this.DeleteSupplierButton.ShadowDecoration.Parent = this.DeleteSupplierButton; this.DeleteSupplierButton.Size = new System.Drawing.Size(425, 45); this.DeleteSupplierButton.TabIndex = 31; this.DeleteSupplierButton.Text = "Delete Supplier"; this.DeleteSupplierButton.Click += new System.EventHandler(this.DeleteSupplierButton_Click); // // UpdateSuppiers // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.White; this.ClientSize = new System.Drawing.Size(897, 531); this.Controls.Add(this.DeleteSupplierButton); this.Controls.Add(this.AC_NoTextBox); this.Controls.Add(this.label10); this.Controls.Add(this.IFSCCodeTextBox); this.Controls.Add(this.label9); this.Controls.Add(this.BankNameTextBox); this.Controls.Add(this.label6); this.Controls.Add(this.UpdateSuppierButton); this.Controls.Add(this.AddressRichTextBox); this.Controls.Add(this.label8); this.Controls.Add(this.label7); this.Controls.Add(this.GSTINTextBox); this.Controls.Add(this.PinCodeTextBox); this.Controls.Add(this.label5); this.Controls.Add(this.CityTextBox); this.Controls.Add(this.label4); this.Controls.Add(this.StateTextBox); this.Controls.Add(this.label3); this.Controls.Add(this.PhoneTextBox); this.Controls.Add(this.label2); this.Controls.Add(this.EmailTextBox); this.Controls.Add(this.label1); this.Controls.Add(this.SupplierName_TextBox); this.Controls.Add(this.label11); this.Controls.Add(this.shapeContainer1); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "UpdateSuppiers"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "UpdateSuppiers"; this.Load += new System.EventHandler(this.UpdateSuppiers_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private Guna.UI2.WinForms.Guna2TextBox AC_NoTextBox; private System.Windows.Forms.Label label10; private Guna.UI2.WinForms.Guna2TextBox IFSCCodeTextBox; private System.Windows.Forms.Label label9; private Guna.UI2.WinForms.Guna2TextBox BankNameTextBox; private System.Windows.Forms.Label label6; private Guna.UI2.WinForms.Guna2Button UpdateSuppierButton; private System.Windows.Forms.RichTextBox AddressRichTextBox; private System.Windows.Forms.Label label8; private System.Windows.Forms.Label label7; private Guna.UI2.WinForms.Guna2TextBox GSTINTextBox; private Guna.UI2.WinForms.Guna2TextBox PinCodeTextBox; private System.Windows.Forms.Label label5; private Guna.UI2.WinForms.Guna2TextBox CityTextBox; private System.Windows.Forms.Label label4; private Guna.UI2.WinForms.Guna2TextBox StateTextBox; private System.Windows.Forms.Label label3; private Guna.UI2.WinForms.Guna2TextBox PhoneTextBox; private System.Windows.Forms.Label label2; private Guna.UI2.WinForms.Guna2TextBox EmailTextBox; private System.Windows.Forms.Label label1; private Guna.UI2.WinForms.Guna2TextBox SupplierName_TextBox; private System.Windows.Forms.Label label11; private Microsoft.VisualBasic.PowerPacks.LineShape lineShape1; private Microsoft.VisualBasic.PowerPacks.ShapeContainer shapeContainer1; private Guna.UI2.WinForms.Guna2Button DeleteSupplierButton; } }
66.235993
177
0.617615
[ "MIT" ]
aliashfak178/Daily-Account
Daily Account/UpdateSuppiers.Designer.cs
39,015
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace Form1 { static class Program { /// <summary> /// Punto de entrada principal para la aplicación. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } }
22.130435
65
0.611002
[ "MIT" ]
jo3l17/CodiGo3
Backend/Semana8/Dia2/Form1/Form1/Program.cs
512
C#
using System; using System.Runtime.Serialization; namespace KeyboardSwitch.Core.Settings { [DataContract] public sealed class CustomLayoutSettings { [DataMember] public int Id { get; set; } [DataMember] public string Name { get; set; } = String.Empty; [DataMember] public string Chars { get; set; } = String.Empty; } }
20.315789
57
0.621762
[ "MIT" ]
TolikPylypchuk/KeyboardSwitch
KeyboardSwitch.Core/Settings/CustomLayoutSettings.cs
386
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using MyUnityEventDispatcher; namespace LinHoweShuffle { /// <summary> /// 牌库 /// </summary> public class Pukes { public int[] pukes; public Pukes(int size) { pukes = new int[size]; InitPukes(); } public void ResetPuke(int[] newpukes) { if (newpukes.Length != pukes.Length) { Debug.LogError("牌库数量出现了变化"); return; } for(int i = 0; i < newpukes.Length;++i) { NotificationCenter<KeyValuePair<int, int>>.Get().DispatchEvent ("MovePuke", new KeyValuePair<int,int>( newpukes[i],i)); } pukes = newpukes; } public void Swap(int i,int j) { NotificationCenter<KeyValuePair<int, int>>.Get().DispatchEvent ("SwapPuke", new KeyValuePair<int, int>(pukes[i], pukes[j])); int m = pukes[i]; pukes[i] = pukes[j]; pukes[j] = m; } /// <summary> /// 抽牌 i小于j /// </summary> /// <param name="i">被抽的牌</param> /// <param name="j">放的位置</param> public void Draw(int i,int j) { int num = pukes[i]; for (int k = i;k < j;++k) { NotificationCenter<KeyValuePair<int, int>>.Get().DispatchEvent ("MovePuke", new KeyValuePair<int, int>(pukes[k+1], k)); pukes[k] = pukes[k+1]; } NotificationCenter<KeyValuePair<int, int>>.Get().DispatchEvent ("MovePuke", new KeyValuePair<int, int>( num, j)); pukes[j] = num; } private void InitPukes() { for (int i = 0; i < pukes.Length; ++i) pukes[i] = i; } } }
27.430556
78
0.460253
[ "MIT" ]
IceLanguage/LinHowe_GameAlgorithm
Assets/Scripts/03-shuffle/DataStructure/Pukes.cs
2,023
C#
using System.Collections.Generic; namespace UniVRM10 { /// <summary> /// 1フレーム分の Expression を蓄える /// </summary> public interface IExpressionAccumulator { /// <summary> /// 開始時に初期化する /// </summary> /// <param name="avatar"></param> void OnStart(VRM10ExpressionAvatar avatar); /// <summary> /// 蓄えて処理(ignoreフラグなど)した結果を得る /// </summary> /// <returns></returns> IEnumerable<KeyValuePair<ExpressionKey, float>> FrameExpression(); void SetValue(ExpressionKey key, float value); void SetValues(IEnumerable<KeyValuePair<ExpressionKey, float>> values); float GetValue(ExpressionKey key); IEnumerable<KeyValuePair<ExpressionKey, float>> GetValues(); bool IgnoreBlink { get; } bool IgnoreLookAt { get; } bool IgnoreMouth { get; } } public static class ExpressionAccumulatorExtensions { public static float GetPresetValue(this IExpressionAccumulator self, VrmLib.ExpressionPreset key) { var expressionKey = new ExpressionKey(key); return self.GetValue(expressionKey); } public static float GetCustomValue(this IExpressionAccumulator self, string key) { var expressionKey = ExpressionKey.CreateCustom(key); return self.GetValue(expressionKey); } public static void SetPresetValue(this IExpressionAccumulator self, VrmLib.ExpressionPreset key, float value) { var expressionKey = new ExpressionKey(key); self.SetValue(expressionKey, value); } public static void SetCustomValue(this IExpressionAccumulator self, string key, float value) { var expressionKey = ExpressionKey.CreateCustom(key); self.SetValue(expressionKey, value); } } }
32.050847
117
0.63247
[ "MIT" ]
nowsprinting/UniVRM
Assets/VRM10/Runtime/Components/Expression/IExpressionAccumulator.cs
1,965
C#
using AppKit; namespace SkiaSharpSample.macOS { static class MainClass { static void Main(string[] args) { NSApplication.Init(); NSApplication.SharedApplication.Delegate = new App(); NSApplication.Main(args); } } }
15.8
56
0.700422
[ "MIT" ]
AlexanderSemenyak/SkiaSharp
samples/Basic/Uno/SkiaSharpSample.macOS/Main.cs
239
C#
using BizHawk.Common; namespace BizHawk.Emulation.Cores.Nintendo.NES { public sealed class NES_QJ : MMC3Board_Base { //state int block; public override void SyncState(Serializer ser) { base.SyncState(ser); ser.Sync(nameof(block), ref block); } public override void WritePRG(int addr, byte value) { base.WritePRG(addr, value); SetMirrorType(mmc3.MirrorType); //often redundant, but gets the job done } public override bool Configure(NES.EDetectionOrigin origin) { //analyze board type switch (Cart.board_type) { case "MAPPER047": // Junk roms break; case "NES-QJ": //super spike v'ball / nintendo world cup AssertPrg(256); AssertChr(256); AssertVram(0); AssertWram(0); AssertBattery(false); break; default: return false; } BaseSetup(); return true; } protected override int Get_PRGBank_8K(int addr) { //base logic will return the mmc reg, which needs to be masked without awareness of the extra block return (base.Get_PRGBank_8K(addr) & 0xF) + block * 16; } protected override int Get_CHRBank_1K(int addr) { //base logic will return the mmc reg, which needs to be masked without awareness of the extra block return (base.Get_CHRBank_1K(addr) & 0x7F) + block * 128; } public override byte ReadWRAM(int addr) { return (byte)block; } public override void WriteWRAM(int addr, byte value) { if (mmc3.wram_enable && !mmc3.wram_write_protect) { block = value & 1; } } } }
23.641791
103
0.650884
[ "MIT" ]
Diefool/BizHawk
BizHawk.Emulation.Cores/Consoles/Nintendo/NES/Boards/MMC3_family/NES-QJ.cs
1,584
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading; using SVM.Flags; namespace SVM { class VM { public const int REGISTERS = 4; public const int PORTS = 255; public const int STACKDEPTH = 16; public const int MEMSIZE = 0xFFFF; public bool RUN; public bool DEBUG; public ushort PC; public ushort[] R = new ushort[REGISTERS]; public ushort RI; public byte SP; public ushort[] STACK = new ushort[STACKDEPTH]; public byte[] MEM = new byte[MEMSIZE]; public Port[] Ports = new Port[PORTS]; public ushort FlagStart = 0xFF00; public ulong InstructionCount = 0; public int CycleDelay = 0; private Dictionary<byte, Instruction> instructions = new Dictionary<byte, Instruction>(); private Dictionary<byte, Flag> flags = new Dictionary<byte, Flag>(); private Dictionary<Type, byte> flagTypeMap = new Dictionary<Type, byte>(); public event EventHandler Breakpoint; public VM() { foreach(var instr in Instruction.GetAllInstructions()) { instructions.Add(instr.OP, instr); } foreach(var flag in Flag.GetAllFlags(this)) { flags.Add(flag.Address, flag); flagTypeMap.Add(flag.GetType(), flag.Address); } Ports[0] = new Ports.ConsolePort(this); Reset(); } public void Reset() { PC = 0; SP = 0; RI = 0; InstructionCount = 0; Array.Fill<ushort>(R, 0); Array.Fill<ushort>(STACK, 0); Array.Fill<byte>(MEM, 0); } public void Load(byte[] data, byte origin) { Array.Copy(data, 0, MEM, origin, data.Length); } public void Run() { RUN = true; while(RUN) { Step(); if (CycleDelay > 0) { Thread.Sleep(CycleDelay); } } } public void Step() { if (RUN) { var nextPC = PC++; try { InstructionCount++; if (PC == 0xFFFF) { throw new Fault(FaultType.MemoryOverflow); } var op = MEM[nextPC]; if (!instructions.ContainsKey(op)) { throw new Fault(FaultType.UndefinedOp); } var instr = instructions[op]; byte[] decoded = instr.Decode(this); //Console.Write("{4:X4} | A{0:X3} B{1:X3} C{2:X3} D{3:X3} | ", R[0], R[1], R[2], R[3], pc); //Console.WriteLine("{0}", instr.ToASM(decoded)); instr.Exec(this, decoded); //Console.ReadKey(true); } catch(Fault flt) { FLTSTS faultStatus = GetFlag<FLTSTS>(); if (!faultStatus.Trip(flt)) { //Halt system as trip failed (already tripped or not enabled) var nextBytes = BitConverter.ToString(MEM.Subset(nextPC, 4)).Replace("-", " "); Ports[0].Write(Encoding.ASCII.GetBytes( string.Format("Unhandled Fault [{0}] at 0x{1:X2}: next bytes {2}.", flt.Type, nextPC, nextBytes) )); RUN = false; } else { //Tripped ok. Get and jump to handler FLTJH faultJMPH = GetFlag<FLTJH>(); FLTJL faultJMPL = GetFlag<FLTJL>(); //Push current PC onto stack PushStack(PC); PC = (ushort)((faultJMPH.Read() << 8) + faultJMPL.Read()); } } } } #region Memory public byte Read(ushort location) { if (location >= FlagStart && location < FlagStart + 0xFF) { byte flagAddress = (byte)(location - FlagStart); if (flags.ContainsKey(flagAddress)) { return flags[flagAddress].Read(); } return 0; } return MEM[location]; } public void Write(ushort location, byte val) { if (location >= FlagStart && location < FlagStart + 0xFF) { byte flagAddress = (byte)(location - FlagStart); if (flags.ContainsKey(flagAddress)) { flags[flagAddress].Write(val); } } else { MEM[location] = val; } } public void PushStack(ushort val) { if (SP > VM.STACKDEPTH) { throw new Fault(FaultType.StackExceeded); } STACK[SP++] = val; } public ushort PopStack() { if (SP <= 0) { throw new Fault(FaultType.StackExceeded); } var val = STACK[--SP]; STACK[SP] = 0; return val; } #endregion public void InvokeBreakpoint() { Breakpoint?.Invoke(this, new EventArgs()); } public T GetFlag<T>() where T : Flag { if (flagTypeMap.ContainsKey(typeof(T))) { return flags[flagTypeMap[typeof(T)]] as T; } return default(T); } } }
30.512821
124
0.436807
[ "BSD-3-Clause" ]
sam159/SVM
SVM/VM.cs
5,952
C#
using Microsoft.AspNetCore.Builder; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.OpenApi.Models; namespace Viajante.Shared.Infrastructure.Swagger { internal static class Extensions { public static IServiceCollection AddSwagger(this IServiceCollection services, IConfiguration configuration) { var appOptions = new ApplicationOptions(); configuration.GetSection("application").Bind(appOptions); services.AddSwaggerGen(swagger => { swagger.EnableAnnotations(); swagger.CustomSchemaIds(x => x.FullName); swagger.SwaggerDoc(appOptions.ApiVersion, new OpenApiInfo { Title = appOptions.ApiTitle, Version = appOptions.ApiVersion }); }); return services; } public static IApplicationBuilder UseSwagger(this IApplicationBuilder app, IConfiguration configuration) { var appOptions = new ApplicationOptions(); configuration.GetSection("application").Bind(appOptions); app .UseSwagger() .UseReDoc(reDoc => { reDoc.RoutePrefix = "docs"; reDoc.SpecUrl($"/swagger/{appOptions.ApiVersion}/swagger.json"); reDoc.DocumentTitle = appOptions.ApiTitle; }) .UseSwaggerUI(c => c.SwaggerEndpoint($"/swagger/{appOptions.ApiVersion}/swagger.json", appOptions.ApiTitle)) .UseRouting(); return app; } } }
34.714286
124
0.588477
[ "MIT" ]
svasorcery/travel-agency
src/Shared/Viajante.Shared.Infrastructure/Swagger/Extensions.cs
1,703
C#
// Copyright (c) MOSA Project. Licensed under the New BSD License. // This code was generated by an automated template. namespace Mosa.Compiler.Framework.IR { /// <summary> /// Switch /// </summary> /// <seealso cref="Mosa.Compiler.Framework.IR.BaseIRInstruction" /> public sealed class Switch : BaseIRInstruction { public override int ID { get { return 169; } } public Switch() : base(0, 0) { } public override FlowControl FlowControl { get { return FlowControl.Switch; } } } }
21.869565
80
0.685885
[ "BSD-3-Clause" ]
TekuSP/MOSA-Project
Source/Mosa.Compiler.Framework/IR/Switch.cs
503
C#
using Microsoft.IdentityModel.Tokens; using Moq; using System; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using Nito.AsyncEx; using Newtonsoft.Json; namespace Domain0.Api.Client.Test { internal class TestContext { internal Mock<IDomain0Client> ClientMock; internal Mock<IDomain0ClientScope> ClientScopeMock; internal Mock<ILoginInfoStorage> LoginInfoStorageMock; public static TestContext MockUp( double accessValidTime = 300, double refreshValidTime = 600) { var clientMock = new Mock<IDomain0Client>(); clientMock .Setup(callFor => callFor.LoginAsync(It.IsAny<SmsLoginRequest>())) .ReturnsAsync(MakeTokenResponse(DefaultSmsUser, accessValidTime, refreshValidTime)); clientMock .Setup(callFor => callFor.LoginByEmailAsync(It.IsAny<EmailLoginRequest>())) .ReturnsAsync(MakeTokenResponse(DefaultEmailUser, accessValidTime, refreshValidTime)); clientMock .Setup(callFor => callFor.LoginByDomainUserAsync(It.IsAny<ActiveDirectoryUserLoginRequest>())) .ReturnsAsync(MakeTokenResponse(DefaultEmailUser, accessValidTime, refreshValidTime)); clientMock .Setup(callFor => callFor.LoginByDomainUserWithEnvironmentAsync(It.IsAny<ActiveDirectoryUserLoginRequest>(), It.IsAny<string>())) .ReturnsAsync(MakeTokenResponse(DefaultEmailUser, accessValidTime, refreshValidTime)); clientMock .Setup(callFor => callFor.RefreshTokenAsync(It.IsAny<RefreshTokenRequest>())) .ReturnsAsync(MakeTokenResponse(DefaultSmsUser, accessValidTime, refreshValidTime)); var clientScopeMock = new Mock<IDomain0ClientScope>(); clientScopeMock .Setup(callFor => callFor.Client) .Returns(clientMock.Object); var lockScope = new AsyncReaderWriterLock(); clientScopeMock .Setup(callFor => callFor.RequestSetupLock) .Returns(() => lockScope); var loginInfoStorageMock = new Mock<ILoginInfoStorage>(); return new TestContext { ClientMock = clientMock, ClientScopeMock = clientScopeMock, LoginInfoStorageMock = loginInfoStorageMock }; } private static AccessTokenResponse MakeTokenResponse( UserProfile profile, double accessValidTime, double refreshValidTime) { var defPermissions = new Claim[] { new Claim("permissions", JsonConvert.SerializeObject(new[] {"claimsA", "claimsB"})) }; var access = Handler.CreateToken( new SecurityTokenDescriptor { Expires = DateTime.UtcNow.AddSeconds(accessValidTime), Subject = new ClaimsIdentity(defPermissions) }); var refresh = Handler.CreateToken( new SecurityTokenDescriptor { Expires = DateTime.UtcNow.AddSeconds(refreshValidTime) }); return new AccessTokenResponse( Handler.WriteToken(access), profile, Handler.WriteToken(refresh)); } private static readonly UserProfile DefaultSmsUser = new UserProfile("description", null, 1, false, "name", "123"); private static readonly UserProfile DefaultEmailUser = new UserProfile("description", "email", 1, false, "name", null); private static readonly JwtSecurityTokenHandler Handler = new JwtSecurityTokenHandler(); } }
38.979592
145
0.619372
[ "MIT" ]
LavrentyAfanasiev/domain0
tests/Domain0.Api.Client.Test/TestContext.cs
3,822
C#
using Prism.Commands; using RaiseHand.Core.Navigation; using RaiseHand.Core.SignalR; using System.Linq; using System.Threading.Tasks; using System.Windows.Input; namespace RaiseHand.Core.ViewModels { public class MainWindowViewModel { private INavigation _navigation; public ICommand LoadedCommand { get; set; } private Connection _connection; public MainWindowViewModel(INavigation navigation, Connection connection) { _navigation = navigation; _connection = connection; LoadedCommand = new DelegateCommand(async () => { await OnLoaded(); }); } public async Task OnLoaded() { string url = "https://localhost:44362/chathub"; if (System.Configuration.ConfigurationManager.AppSettings.AllKeys.Contains("ConnectURL")) { url = System.Configuration.ConfigurationManager.AppSettings["ConnectURL"]; } await _connection.Connect(url); _navigation.Navigate("Home"); } } }
31.028571
101
0.635359
[ "MIT" ]
kevmoens/RaiseHand
RaiseHand.Core/ViewModels/MainWindowViewModel.cs
1,088
C#
// Copyright 2019 Maintainers of NUKE. // Distributed under the MIT License. // https://github.com/nuke-build/nuke/blob/master/LICENSE using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using JetBrains.Annotations; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using NuGet.Packaging; using NuGet.Versioning; using Nuke.Common.IO; using Nuke.Common.Utilities; using Nuke.Common.Utilities.Collections; namespace Nuke.Common.Tooling { [PublicAPI] public static class NuGetPackageResolver { private const int c_defaultTimeout = 2000; public static async Task<string> GetLatestPackageVersion(string packageId, bool includePrereleases, int? timeout = null) { try { var url = $"https://api-v2v3search-0.nuget.org/query?q=packageid:{packageId}&prerelease={includePrereleases}"; var response = await HttpTasks.HttpDownloadStringAsync(url, requestConfigurator: x => x.Timeout = timeout ?? c_defaultTimeout); var packageObject = JsonConvert.DeserializeObject<JObject>(response); return packageObject["data"].Single()["version"].ToString(); } catch (Exception) { return null; } } public static InstalledPackage GetLocalInstalledPackage( string packageId, string packagesConfigFile, string version = null, bool resolveDependencies = true) { return TryGetLocalInstalledPackage(packageId, packagesConfigFile, version, resolveDependencies) .NotNull($"Could not find package '{packageId}'{(version != null ? $" ({version})" : string.Empty)} via '{packagesConfigFile}'."); } [CanBeNull] public static InstalledPackage TryGetLocalInstalledPackage( string packageId, string packagesConfigFile, string version = null, bool includeDependencies = false) { return GetLocalInstalledPackages(packagesConfigFile, includeDependencies) .SingleOrDefaultOrError( x => x.Id.EqualsOrdinalIgnoreCase(packageId) && (x.Version.ToString() == version || version == null), $"Package '{packageId}' is referenced with multiple versions. Use NuGetPackageResolver and SetToolPath."); } // TODO: add HasLocalInstalledPackage() ? // ReSharper disable once CyclomaticComplexity public static IEnumerable<InstalledPackage> GetLocalInstalledPackages( string packagesConfigFile, bool resolveDependencies = true) { var packagesDirectory = GetPackagesDirectory(packagesConfigFile); var packageIds = XmlTasks.XmlPeek( packagesConfigFile, IsLegacyFile(packagesConfigFile) ? ".//package/@id" : ".//*[local-name() = 'PackageReference' or local-name() = 'PackageDownload']/@Include") .Distinct(); var installedPackages = new HashSet<InstalledPackage>(InstalledPackage.Comparer.Instance); foreach (var packageId in packageIds) { // TODO: use xml namespaces // TODO: version as tag var versions = XmlTasks.XmlPeek( packagesConfigFile, IsLegacyFile(packagesConfigFile) ? $".//package[@id='{packageId}']/@version" : $".//*[local-name() = 'PackageReference' or local-name() = 'PackageDownload'][@Include='{packageId}']/@Version"); foreach (var version in versions) { var packageData = GetGlobalInstalledPackage(packageId, version, packagesDirectory); if (packageData == null) continue; installedPackages.Add(packageData); yield return packageData; } } if (resolveDependencies && !IsLegacyFile(packagesConfigFile)) { var packagesToCheck = new Queue<InstalledPackage>(installedPackages); while (packagesToCheck.Any()) { var packageToCheck = packagesToCheck.Dequeue(); foreach (var dependentPackage in GetDependentPackages(packageToCheck, packagesDirectory)) { if (installedPackages.Contains(dependentPackage)) continue; installedPackages.Add(dependentPackage); packagesToCheck.Enqueue(dependentPackage); yield return dependentPackage; } } } } private static IEnumerable<InstalledPackage> GetDependentPackages(InstalledPackage packageToCheck, string packagesDirectory) { return packageToCheck.Metadata.GetDependencyGroups() .SelectMany(x => x.Packages) .Select(x => GetGlobalInstalledPackage(x.Id, x.VersionRange, packagesDirectory)) .WhereNotNull() .Distinct(x => new { x.Id, x.Version }); } [CanBeNull] public static InstalledPackage GetGlobalInstalledPackage(string packageId, [CanBeNull] string version, [CanBeNull] string packagesConfigFile) { if (version != null && !version.Contains("*") && !version.StartsWith("[") && !version.EndsWith("]")) version = $"[{version}]"; VersionRange.TryParse(version, out var versionRange); return GetGlobalInstalledPackage(packageId, versionRange, packagesConfigFile); } // TODO: add parameter for auto download? // TODO: add parameter for highest/lowest? [CanBeNull] public static InstalledPackage GetGlobalInstalledPackage( string packageId, [CanBeNull] VersionRange versionRange, [CanBeNull] string packagesConfigFile, bool? includePrereleases = null) { packageId = packageId.ToLowerInvariant(); var packagesDirectory = GetPackagesDirectory(packagesConfigFile); var packagesDirectoryInfo = new DirectoryInfo(packagesDirectory); var packages = packagesDirectoryInfo .GetDirectories(packageId) .SelectMany(x => x.GetDirectories()) .SelectMany(x => x.GetFiles($"{packageId}*.nupkg")) .Concat(packagesDirectoryInfo .GetDirectories($"{packageId}*") .SelectMany(x => x.GetFiles($"{packageId}*.nupkg"))) .Select(x => x.FullName); var candidatePackages = packages.Select(x => new InstalledPackage(x)) // packages can contain false positives due to present/missing version specification .Where(x => x.Id.EqualsOrdinalIgnoreCase(packageId)) .Where(x => !x.Version.IsPrerelease || !includePrereleases.HasValue || includePrereleases.Value) .OrderByDescending(x => x.Version) .ToList(); return versionRange == null ? candidatePackages.FirstOrDefault() : candidatePackages.SingleOrDefault(x => x.Version == versionRange.FindBestMatch(candidatePackages.Select(y => y.Version))); } [CanBeNull] public static string GetPackagesConfigFile(string projectDirectory) { var projectDirectoryInfo = new DirectoryInfo(projectDirectory); var packagesConfigFile = projectDirectoryInfo.GetFiles("packages.config").SingleOrDefault() ?? projectDirectoryInfo.GetFiles("*.csproj") .SingleOrDefaultOrError("Directory contains multiple project files."); return packagesConfigFile?.FullName; } // TODO: check for config ( repositoryPath / globalPackagesFolder ) public static string GetPackagesDirectory([CanBeNull] string packagesConfigFile) { string TryGetFromEnvironmentVariable() => EnvironmentInfo.Variable("NUGET_PACKAGES"); string TryGetGlobalDirectoryFromConfig() => GetConfigFiles(packagesConfigFile) .Select(x => new { File = x, Setting = XmlTasks.XmlPeekSingle(x, ".//add[@key='globalPackagesFolder']/@value") }) .Where(x => x.Setting != null) .Select(x => Path.IsPathRooted(x.Setting) ? x.Setting : Path.Combine(Path.GetDirectoryName(x.File).NotNull(), x.Setting)) .FirstOrDefault(); string TryGetDefaultGlobalDirectory() => packagesConfigFile == null || !IsLegacyFile(packagesConfigFile) ? Path.Combine( EnvironmentInfo.SpecialFolder(SpecialFolders.UserProfile) .NotNull("EnvironmentInfo.SpecialFolder(SpecialFolders.UserProfile) != null"), ".nuget", "packages") : null; string TryGetLocalDirectory() => packagesConfigFile != null ? new FileInfo(packagesConfigFile).Directory.NotNull() .DescendantsAndSelf(x => x.Parent) .SingleOrDefault(x => x.GetFiles("*.sln").Any() && x.GetDirectories("packages").Any()) ?.FullName : null; var packagesDirectory = TryGetFromEnvironmentVariable() ?? TryGetGlobalDirectoryFromConfig() ?? TryGetDefaultGlobalDirectory() ?? TryGetLocalDirectory(); ControlFlow.Assert(Directory.Exists(packagesDirectory), $"Directory.Exists({packagesDirectory})"); return packagesDirectory; } public static bool IsLegacyFile(string packagesConfigFile) { return packagesConfigFile.EndsWithOrdinalIgnoreCase(".config"); } private static bool IncludesDependencies(string packagesConfigFile) { return IsLegacyFile(packagesConfigFile); } private static IEnumerable<string> GetConfigFiles([CanBeNull] string packagesConfigFile) { var directories = new List<string>(); if (packagesConfigFile != null) { directories.AddRange(Directory.GetParent(packagesConfigFile) .DescendantsAndSelf(x => x.Parent) .Select(x => x.FullName)); } if (EnvironmentInfo.IsWin) { directories.Add(Path.Combine( EnvironmentInfo.SpecialFolder(SpecialFolders.ApplicationData).NotNull(), "NuGet")); directories.Add(Path.Combine( EnvironmentInfo.SpecialFolder(SpecialFolders.ProgramFilesX86).NotNull(), "NuGet", "Config")); } if (EnvironmentInfo.IsUnix) { directories.Add(Path.Combine( EnvironmentInfo.SpecialFolder(SpecialFolders.UserProfile).NotNull(), ".config", "NuGet")); directories.Add(Path.Combine( EnvironmentInfo.SpecialFolder(SpecialFolders.UserProfile).NotNull(), ".nuget", "NuGet")); var dataHomeDirectoy = EnvironmentInfo.Variable("XDG_DATA_HOME"); if (!string.IsNullOrEmpty(dataHomeDirectoy)) { directories.Add(dataHomeDirectoy); } else { directories.Add(Path.Combine( EnvironmentInfo.SpecialFolder(SpecialFolders.UserProfile).NotNull(), ".local", "share")); // TODO: /usr/local/share } } return directories .Where(Directory.Exists) .SelectMany(x => Directory.GetFiles(x, "nuget.config", SearchOption.TopDirectoryOnly)) .Where(File.Exists); } // TODO: move out of class public class InstalledPackage { public sealed class Comparer : IEqualityComparer<InstalledPackage> { public static readonly Comparer Instance = new Comparer(); public bool Equals([CanBeNull] InstalledPackage x, [CanBeNull] InstalledPackage y) { if (ReferenceEquals(x, y)) return true; if (ReferenceEquals(x, objB: null)) return false; if (ReferenceEquals(y, objB: null)) return false; if (x.GetType() != y.GetType()) return false; return Equals(x.Id, y.Id) && Equals(x.Version, y.Version); } public int GetHashCode([NotNull] InstalledPackage obj) { return obj.Id.GetHashCode(); } } public InstalledPackage(string fileName) { FileName = fileName; Metadata = new PackageArchiveReader(fileName).NuspecReader; } public string FileName { get; } public PathConstruction.AbsolutePath Directory => (PathConstruction.AbsolutePath) Path.GetDirectoryName(FileName).NotNull(); public NuspecReader Metadata { get; } public string Id => Metadata.GetIdentity().Id; public NuGetVersion Version => Metadata.GetIdentity().Version; public override string ToString() { return $"{Id}.{Version.ToFullString()}"; } } } }
42.247093
149
0.552811
[ "MIT" ]
NikolayPianikov/common
source/Nuke.Common/Tooling/NuGetPackageResolver.cs
14,533
C#
using System; using System.ComponentModel; using System.Windows.Input; namespace DevExpress.Mvvm.UI.Native { public class CanExecuteChangedEventHandler<TOwner> : WeakEventHandler<TOwner, EventArgs, EventHandler> where TOwner : class { static Action<WeakEventHandler<TOwner, EventArgs, EventHandler>, object> action = (h, o) => { if(o != null) ((ICommand)o).CanExecuteChanged -= h.Handler; }; static Func<WeakEventHandler<TOwner, EventArgs, EventHandler>, EventHandler> create = h => h.OnEvent; public CanExecuteChangedEventHandler(TOwner owner, Action<TOwner, object, EventArgs> onEventAction) : base(owner, onEventAction, action, create) { } } }
43.411765
129
0.684282
[ "MIT" ]
DevExpress/DevExpress.Mvvm.Free
DevExpress.Mvvm.UI/Native/CanExecuteChangedEventHandler.cs
738
C#
/* * Copyright (c) 2014-2020 GraphDefined GmbH * This file is part of WWCP OCPP <https://github.com/OpenChargingCloud/WWCP_OCPP> * * 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. */ #region Usings using System; using System.Xml.Linq; using Newtonsoft.Json.Linq; using org.GraphDefined.Vanaheimr.Illias; using org.GraphDefined.Vanaheimr.Hermod.JSON; #endregion namespace cloud.charging.adapters.OCPPv1_6.CS { /// <summary> /// A update firmware request. /// </summary> public class UpdateFirmwareRequest : ARequest<UpdateFirmwareRequest> { #region Properties /// <summary> /// The URI where to download the firmware. /// </summary> public String Location { get; } /// <summary> /// The timestamp after which the charge point must retrieve the /// firmware. /// </summary> public DateTime RetrieveDate { get; } /// <summary> /// The optional number of retries of a charge point for trying to /// download the firmware before giving up. If this field is not /// present, it is left to the charge point to decide how many times /// it wants to retry. /// </summary> public Byte? Retries { get; } /// <summary> /// The interval after which a retry may be attempted. If this field /// is not present, it is left to charge point to decide how long to /// wait between attempts. /// </summary> public TimeSpan? RetryInterval { get; } #endregion #region Constructor(s) /// <summary> /// Create a update firmware request. /// </summary> /// <param name="Location">The URI where to download the firmware.</param> /// <param name="RetrieveDate">The timestamp after which the charge point must retrieve the firmware.</param> /// <param name="Retries">The optional number of retries of a charge point for trying to download the firmware before giving up. If this field is not present, it is left to the charge point to decide how many times it wants to retry.</param> /// <param name="RetryInterval">The interval after which a retry may be attempted. If this field is not present, it is left to charge point to decide how long to wait between attempts.</param> public UpdateFirmwareRequest(String Location, DateTime RetrieveDate, Byte? Retries = null, TimeSpan? RetryInterval = null) { #region Initial checks if (Location.IsNullOrEmpty()) throw new ArgumentNullException(nameof(Location), "The given location must not be null or empty!"); #endregion this.Location = Location; this.RetrieveDate = RetrieveDate; this.Retries = Retries ?? new Byte?(); this.RetryInterval = RetryInterval ?? new TimeSpan?(); } #endregion #region Documentation // <soap:Envelope xmlns:soap = "http://www.w3.org/2003/05/soap-envelope" // xmlns:wsa = "http://www.w3.org/2005/08/addressing" // xmlns:ns = "urn://Ocpp/Cp/2015/10/"> // // <soap:Header> // ... // </soap:Header> // // <soap:Body> // <ns:updateFirmwareRequest> // // <ns:retrieveDate>?</ns:retrieveDate> // <ns:location>?</ns:location> // // <!--Optional:--> // <ns:retries>?</ns:retries> // // <!--Optional:--> // <ns:retryInterval>?</ns:retryInterval> // // </ns:updateFirmwareRequest> // </soap:Body> // // </soap:Envelope> // { // "$schema": "http://json-schema.org/draft-04/schema#", // "id": "urn:OCPP:1.6:2019:12:UpdateFirmwareRequest", // "title": "UpdateFirmwareRequest", // "type": "object", // "properties": { // "location": { // "type": "string", // "format": "uri" // }, // "retries": { // "type": "integer" // }, // "retrieveDate": { // "type": "string", // "format": "date-time" // }, // "retryInterval": { // "type": "integer" // } // }, // "additionalProperties": false, // "required": [ // "location", // "retrieveDate" // ] // } #endregion #region (static) Parse (UpdateFirmwareRequestXML, OnException = null) /// <summary> /// Parse the given XML representation of a update firmware request. /// </summary> /// <param name="UpdateFirmwareRequestXML">The XML to be parsed.</param> /// <param name="OnException">An optional delegate called whenever an exception occured.</param> public static UpdateFirmwareRequest Parse(XElement UpdateFirmwareRequestXML, OnExceptionDelegate OnException = null) { if (TryParse(UpdateFirmwareRequestXML, out UpdateFirmwareRequest updateFirmwareRequest, OnException)) { return updateFirmwareRequest; } return null; } #endregion #region (static) Parse (UpdateFirmwareRequestJSON, OnException = null) /// <summary> /// Parse the given JSON representation of a update firmware request. /// </summary> /// <param name="UpdateFirmwareRequestJSON">The JSON to be parsed.</param> /// <param name="OnException">An optional delegate called whenever an exception occured.</param> public static UpdateFirmwareRequest Parse(JObject UpdateFirmwareRequestJSON, OnExceptionDelegate OnException = null) { if (TryParse(UpdateFirmwareRequestJSON, out UpdateFirmwareRequest updateFirmwareRequest, OnException)) { return updateFirmwareRequest; } return null; } #endregion #region (static) Parse (UpdateFirmwareRequestText, OnException = null) /// <summary> /// Parse the given text representation of a update firmware request. /// </summary> /// <param name="UpdateFirmwareRequestText">The text to be parsed.</param> /// <param name="OnException">An optional delegate called whenever an exception occured.</param> public static UpdateFirmwareRequest Parse(String UpdateFirmwareRequestText, OnExceptionDelegate OnException = null) { if (TryParse(UpdateFirmwareRequestText, out UpdateFirmwareRequest updateFirmwareRequest, OnException)) { return updateFirmwareRequest; } return null; } #endregion #region (static) TryParse(UpdateFirmwareRequestXML, out UpdateFirmwareRequest, OnException = null) /// <summary> /// Try to parse the given XML representation of a update firmware request. /// </summary> /// <param name="UpdateFirmwareRequestXML">The XML to be parsed.</param> /// <param name="UpdateFirmwareRequest">The parsed update firmware request.</param> /// <param name="OnException">An optional delegate called whenever an exception occured.</param> public static Boolean TryParse(XElement UpdateFirmwareRequestXML, out UpdateFirmwareRequest UpdateFirmwareRequest, OnExceptionDelegate OnException = null) { try { UpdateFirmwareRequest = new UpdateFirmwareRequest( UpdateFirmwareRequestXML.ElementValueOrFail(OCPPNS.OCPPv1_6_CP + "location"), UpdateFirmwareRequestXML.MapValueOrFail (OCPPNS.OCPPv1_6_CP + "retrieveDate", DateTime.Parse), UpdateFirmwareRequestXML.MapValueOrNullable(OCPPNS.OCPPv1_6_CP + "retries", Byte.Parse), UpdateFirmwareRequestXML.MapValueOrNullable(OCPPNS.OCPPv1_6_CP + "retryInterval", s => TimeSpan.FromSeconds(UInt32.Parse(s))) ); return true; } catch (Exception e) { OnException?.Invoke(DateTime.UtcNow, UpdateFirmwareRequestXML, e); UpdateFirmwareRequest = null; return false; } } #endregion #region (static) TryParse(UpdateFirmwareRequestJSON, out UpdateFirmwareRequest, OnException = null) /// <summary> /// Try to parse the given JSON representation of a update firmware request. /// </summary> /// <param name="UpdateFirmwareRequestJSON">The JSON to be parsed.</param> /// <param name="UpdateFirmwareRequest">The parsed update firmware request.</param> /// <param name="OnException">An optional delegate called whenever an exception occured.</param> public static Boolean TryParse(JObject UpdateFirmwareRequestJSON, out UpdateFirmwareRequest UpdateFirmwareRequest, OnExceptionDelegate OnException = null) { try { UpdateFirmwareRequest = null; #region Location var Location = UpdateFirmwareRequestJSON.GetString("location"); #endregion #region RetrieveDate if (!UpdateFirmwareRequestJSON.ParseMandatory("retrieveDate", "retrieve date", out DateTime RetrieveDate, out String ErrorResponse)) { return false; } #endregion #region Retries if (UpdateFirmwareRequestJSON.ParseOptional("retries", "retries", out Byte? Retries, out ErrorResponse)) { if (ErrorResponse != null) return false; } #endregion #region RetryInterval if (UpdateFirmwareRequestJSON.ParseOptional("retryInterval", "retry interval", out TimeSpan? RetryInterval, out ErrorResponse)) { if (ErrorResponse != null) return false; } #endregion UpdateFirmwareRequest = new UpdateFirmwareRequest(Location, RetrieveDate, Retries, RetryInterval); return true; } catch (Exception e) { OnException?.Invoke(DateTime.UtcNow, UpdateFirmwareRequestJSON, e); UpdateFirmwareRequest = null; return false; } } #endregion #region (static) TryParse(UpdateFirmwareRequestText, out UpdateFirmwareRequest, OnException = null) /// <summary> /// Try to parse the given text representation of a update firmware request. /// </summary> /// <param name="UpdateFirmwareRequestText">The text to be parsed.</param> /// <param name="UpdateFirmwareRequest">The parsed update firmware request.</param> /// <param name="OnException">An optional delegate called whenever an exception occured.</param> public static Boolean TryParse(String UpdateFirmwareRequestText, out UpdateFirmwareRequest UpdateFirmwareRequest, OnExceptionDelegate OnException = null) { try { UpdateFirmwareRequestText = UpdateFirmwareRequestText?.Trim(); if (UpdateFirmwareRequestText.IsNotNullOrEmpty()) { if (UpdateFirmwareRequestText.StartsWith("{") && TryParse(JObject.Parse(UpdateFirmwareRequestText), out UpdateFirmwareRequest, OnException)) { return true; } if (TryParse(XDocument.Parse(UpdateFirmwareRequestText).Root, out UpdateFirmwareRequest, OnException)) { return true; } } } catch (Exception e) { OnException?.Invoke(DateTime.UtcNow, UpdateFirmwareRequestText, e); } UpdateFirmwareRequest = null; return false; } #endregion #region ToXML() /// <summary> /// Return a XML representation of this object. /// </summary> public XElement ToXML() => new XElement(OCPPNS.OCPPv1_6_CP + "getDiagnosticsRequest", new XElement(OCPPNS.OCPPv1_6_CP + "retrieveDate", RetrieveDate.ToIso8601()), new XElement(OCPPNS.OCPPv1_6_CP + "location", Location), Retries.HasValue ? new XElement(OCPPNS.OCPPv1_6_CP + "retries", Retries.Value) : null, RetryInterval.HasValue ? new XElement(OCPPNS.OCPPv1_6_CP + "retryInterval", (UInt64) RetryInterval.Value.TotalSeconds) : null ); #endregion #region ToJSON(CustomUpdateFirmwareRequestSerializer = null) /// <summary> /// Return a JSON representation of this object. /// </summary> /// <param name="CustomUpdateFirmwareRequestSerializer">A delegate to serialize custom start transaction requests.</param> public JObject ToJSON(CustomJObjectSerializerDelegate<UpdateFirmwareRequest> CustomUpdateFirmwareRequestSerializer = null) { var JSON = JSONObject.Create( new JProperty("retrieveDate", RetrieveDate.ToIso8601()), new JProperty("location", Location), Retries.HasValue ? new JProperty("retries", Retries.Value) : null, RetryInterval.HasValue ? new JProperty("retryInterval", (UInt64) RetryInterval.Value.TotalSeconds) : null ); return CustomUpdateFirmwareRequestSerializer != null ? CustomUpdateFirmwareRequestSerializer(this, JSON) : JSON; } #endregion #region Operator overloading #region Operator == (UpdateFirmwareRequest1, UpdateFirmwareRequest2) /// <summary> /// Compares two update firmware requests for equality. /// </summary> /// <param name="UpdateFirmwareRequest1">A update firmware request.</param> /// <param name="UpdateFirmwareRequest2">Another update firmware request.</param> /// <returns>True if both match; False otherwise.</returns> public static Boolean operator == (UpdateFirmwareRequest UpdateFirmwareRequest1, UpdateFirmwareRequest UpdateFirmwareRequest2) { // If both are null, or both are same instance, return true. if (ReferenceEquals(UpdateFirmwareRequest1, UpdateFirmwareRequest2)) return true; // If one is null, but not both, return false. if ((UpdateFirmwareRequest1 is null) || (UpdateFirmwareRequest2 is null)) return false; return UpdateFirmwareRequest1.Equals(UpdateFirmwareRequest2); } #endregion #region Operator != (UpdateFirmwareRequest1, UpdateFirmwareRequest2) /// <summary> /// Compares two update firmware requests for inequality. /// </summary> /// <param name="UpdateFirmwareRequest1">A update firmware request.</param> /// <param name="UpdateFirmwareRequest2">Another update firmware request.</param> /// <returns>False if both match; True otherwise.</returns> public static Boolean operator != (UpdateFirmwareRequest UpdateFirmwareRequest1, UpdateFirmwareRequest UpdateFirmwareRequest2) => !(UpdateFirmwareRequest1 == UpdateFirmwareRequest2); #endregion #endregion #region IEquatable<UpdateFirmwareRequest> Members #region Equals(Object) /// <summary> /// Compares two instances of this object. /// </summary> /// <param name="Object">An object to compare with.</param> /// <returns>true|false</returns> public override Boolean Equals(Object Object) { if (Object is null) return false; if (!(Object is UpdateFirmwareRequest UpdateFirmwareRequest)) return false; return Equals(UpdateFirmwareRequest); } #endregion #region Equals(UpdateFirmwareRequest) /// <summary> /// Compares two update firmware requests for equality. /// </summary> /// <param name="UpdateFirmwareRequest">A update firmware request to compare with.</param> /// <returns>True if both match; False otherwise.</returns> public override Boolean Equals(UpdateFirmwareRequest UpdateFirmwareRequest) { if (UpdateFirmwareRequest is null) return false; return Location. Equals(UpdateFirmwareRequest.Location) && RetrieveDate.Equals(UpdateFirmwareRequest.RetrieveDate) && ((!Retries. HasValue && !UpdateFirmwareRequest.Retries. HasValue) || (Retries. HasValue && UpdateFirmwareRequest.Retries. HasValue && Retries. Value.Equals(UpdateFirmwareRequest.Retries. Value))) && ((!RetryInterval.HasValue && !UpdateFirmwareRequest.RetryInterval.HasValue) || (RetryInterval.HasValue && UpdateFirmwareRequest.RetryInterval.HasValue && RetryInterval.Value.Equals(UpdateFirmwareRequest.RetryInterval.Value))); } #endregion #endregion #region (override) GetHashCode() /// <summary> /// Return the HashCode of this object. /// </summary> /// <returns>The HashCode of this object.</returns> public override Int32 GetHashCode() { unchecked { return Location. GetHashCode() * 11 ^ RetrieveDate.GetHashCode() * 7 ^ (Retries.HasValue ? Retries. GetHashCode() * 5 : 0) ^ (RetryInterval.HasValue ? RetryInterval.GetHashCode() : 0); } } #endregion #region (override) ToString() /// <summary> /// Return a text representation of this object. /// </summary> public override String ToString() => String.Concat(Location, " till ", RetrieveDate, Retries.HasValue ? ", " + Retries.Value + " retries" : "", RetryInterval.HasValue ? ", retry interval " + RetryInterval.Value.TotalSeconds + " sec(s)" : ""); #endregion } }
35.84219
249
0.51222
[ "Apache-2.0" ]
phoompat/WWCP_OCPP
WWCP_OCPPv1.6/Messages/ChargePoint/UpdateFirmwareRequest.cs
22,260
C#
using System; using JetBrains.Annotations; using PCG.Terrain.Core.Components; using Unity.Collections; using Unity.Entities; using Unity.Mathematics; using Unity.Transforms; using UnityEngine.Assertions; namespace PCG.Terrain.Core.Systems { public sealed class IdentifyChange { public delegate int2 OnChangedPosition(float2 followTargetPosition); public static readonly EntityArchetypeQuery EntityArchetypeQuery = new EntityArchetypeQuery { All = new[] { ComponentType.ReadOnly<Position>(), ComponentType.ReadOnly<FollowTarget>() } }; private readonly int _changeThreshold; private readonly EntityManager _entityManager; private readonly ComponentGroup _componentGroup; private int _followTargetOrderVersion = -1; private Entity _followTargetEntity = Entity.Null; public int2 CentroidPosition { get; private set; } public IdentifyChange([NotNull] EntityManager entityManager, [NotNull] ComponentGroup componentGroup, int changeThreshold, int2 centroidPosition) { #if DEBUG // ReSharper disable once JoinNullCheckWithUsage if (entityManager == null) throw new ArgumentNullException(nameof(entityManager)); // ReSharper disable once JoinNullCheckWithUsage if (componentGroup == null) throw new ArgumentNullException(nameof(componentGroup)); #endif _entityManager = entityManager; _componentGroup = componentGroup; _changeThreshold = changeThreshold; CentroidPosition = centroidPosition; } public void HandleChangeFollowTargetPosition([NotNull] OnChangedPosition onChangedPosition) { #if DEBUG if (onChangedPosition == null) throw new ArgumentNullException(nameof(onChangedPosition)); #endif UpdateFollowTargetEntity(); if (CheckNewPositionOfFollowTarget(out var followTargetPosition)) { CentroidPosition = onChangedPosition.Invoke(followTargetPosition); } } private void UpdateFollowTargetEntity() { var followTargetOrderVersion = _entityManager.GetComponentOrderVersion<FollowTarget>(); if (followTargetOrderVersion == _followTargetOrderVersion) { return; } var followTargetChunks = _componentGroup.CreateArchetypeChunkArray(Allocator.TempJob); if (followTargetChunks.Length > 0) { Assert.IsTrue( followTargetChunks.Length == 1 && followTargetChunks[0].Count == 1, $"Only one followed target is supported. Make sure component {typeof(FollowTarget)} is only in one Entity." ); _followTargetEntity = followTargetChunks[0].GetNativeArray(_entityManager.GetArchetypeChunkEntityType())[0]; } else { _followTargetEntity = Entity.Null; } followTargetChunks.Dispose(); _followTargetOrderVersion = followTargetOrderVersion; } private bool CheckNewPositionOfFollowTarget(out float2 followTargetPosition) { followTargetPosition = math.float2(0f); if (_followTargetEntity.Equals(Entity.Null)) { return false; } var position = _entityManager.GetComponentData<Position>(_followTargetEntity).Value; followTargetPosition.x = position.x; followTargetPosition.y = position.z; return CheckOverlapOfChangeThreshold(followTargetPosition); } private bool CheckOverlapOfChangeThreshold(float2 followTargetPosition) { return math.any(math.abs(followTargetPosition - CentroidPosition) > _changeThreshold + 0.5f); } } }
36.944444
127
0.643609
[ "MIT" ]
ErikMoczi/Unity.ProceduralContentGeneration-Terrain
Assets/PCG.Terrain/Core/Systems/IdentifyChange.cs
3,990
C#
using System; using MikhailKhalizev.Processor.x86.BinToCSharp; namespace MikhailKhalizev.Max.Program { public partial class RawProgram { [MethodInfo("0x100b_1a6c-1aceb1c0")] public void Method_100b_1a6c() { ii(0x100b_1a6c, 5); push(0x24); /* push 0x24 */ ii(0x100b_1a71, 5); call(Definitions.sys_check_available_stack_size, 0xb_42dc);/* call 0x10165d52 */ ii(0x100b_1a76, 1); push(ebx); /* push ebx */ ii(0x100b_1a77, 1); push(ecx); /* push ecx */ ii(0x100b_1a78, 1); push(edx); /* push edx */ ii(0x100b_1a79, 1); push(esi); /* push esi */ ii(0x100b_1a7a, 1); push(edi); /* push edi */ ii(0x100b_1a7b, 1); push(ebp); /* push ebp */ ii(0x100b_1a7c, 2); mov(ebp, esp); /* mov ebp, esp */ ii(0x100b_1a7e, 6); sub(esp, 8); /* sub esp, 0x8 */ ii(0x100b_1a84, 3); mov(memd[ss, ebp - 4], eax); /* mov [ebp-0x4], eax */ ii(0x100b_1a87, 3); mov(eax, memd[ss, ebp - 4]); /* mov eax, [ebp-0x4] */ ii(0x100b_1a8a, 3); mov(memd[ss, ebp - 8], eax); /* mov [ebp-0x8], eax */ ii(0x100b_1a8d, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */ ii(0x100b_1a90, 3); mov(edx, memd[ds, eax + 2]); /* mov edx, [eax+0x2] */ ii(0x100b_1a93, 3); mov(eax, memd[ss, ebp - 8]); /* mov eax, [ebp-0x8] */ ii(0x100b_1a96, 3); call_abs(memd[ds, edx + 60]); /* call dword [edx+0x3c] */ ii(0x100b_1a99, 2); mov(esp, ebp); /* mov esp, ebp */ ii(0x100b_1a9b, 1); pop(ebp); /* pop ebp */ ii(0x100b_1a9c, 1); pop(edi); /* pop edi */ ii(0x100b_1a9d, 1); pop(esi); /* pop esi */ ii(0x100b_1a9e, 1); pop(edx); /* pop edx */ ii(0x100b_1a9f, 1); pop(ecx); /* pop ecx */ ii(0x100b_1aa0, 1); pop(ebx); /* pop ebx */ ii(0x100b_1aa1, 1); ret(); /* ret */ } } }
65.358974
114
0.400549
[ "Apache-2.0" ]
mikhail-khalizev/max
source/MikhailKhalizev.Max/source/Program/Auto/z-100b-1a6c.cs
2,549
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 Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Testing; using Test.Utilities; using Xunit; namespace Microsoft.CodeQuality.Analyzers.Maintainability.UnitTests { public class ReviewUnusedParametersTests : DiagnosticAnalyzerTestBase { #region Unit tests for no analyzer diagnostic [Fact] [WorkItem(459, "https://github.com/dotnet/roslyn-analyzers/issues/459")] public void NoDiagnosticSimpleCasesTest() { VerifyCSharp(@" using System; public class NeatCode { // Used parameter methods public void UsedParameterMethod1(string use) { Console.WriteLine(this); Console.WriteLine(use); } public void UsedParameterMethod2(string use) { UsedParameterMethod3(ref use); } public void UsedParameterMethod3(ref string use) { use = null; } } "); VerifyBasic(@" Imports System Public Class NeatCode ' Used parameter methods Public Sub UsedParameterMethod1(use As String) Console.WriteLine(Me) Console.WriteLine(use) End Sub Public Sub UsedParameterMethod2(use As String) UsedParameterMethod3(use) End Sub Public Sub UsedParameterMethod3(ByRef use As String) use = Nothing End Sub End Class "); } [Fact] [WorkItem(459, "https://github.com/dotnet/roslyn-analyzers/issues/459")] public void NoDiagnosticDelegateTest() { VerifyCSharp(@" using System; public class NeatCode { // Used parameter methods public void UsedParameterMethod1(Action a) { a(); } public void UsedParameterMethod2(Action a1, Action a2) { try { a1(); } catch(Exception) { a2(); } } } "); VerifyBasic(@" Imports System Public Class NeatCode ' Used parameter methods Public Sub UsedParameterMethod1(a As Action) a() End Sub Public Sub UsedParameterMethod2(a1 As Action, a2 As Action) Try a1() Catch generatedExceptionName As Exception a2() End Try End Sub End Class "); } [Fact] [WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void NoDiagnosticDelegateTest2_CSharp() { VerifyCSharp(@" using System; public class NeatCode { // Used parameter methods public void UsedParameterMethod1(Action a) { Action a2 = new Action(() => { a(); }); } }"); } [Fact] [WorkItem(459, "https://github.com/dotnet/roslyn-analyzers/issues/459")] public void NoDiagnosticDelegateTest2_VB() { VerifyBasic(@" Imports System Public Class NeatCode ' Used parameter methods Public Sub UsedParameterMethod1(a As Action) Dim a2 As New Action(Sub() a() End Sub) End Sub End Class "); } [Fact] [WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void NoDiagnosticUsingTest_CSharp() { VerifyCSharp(@" using System; class C { void F(int x, IDisposable o) { using (o) { int y = x; } } } "); } [Fact] [WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void NoDiagnosticUsingTest_VB() { VerifyBasic(@" Imports System Class C Private Sub F(x As Integer, o As IDisposable) Using o Dim y As Integer = x End Using End Sub End Class "); } [Fact] [WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void NoDiagnosticLinqTest_CSharp() { VerifyCSharp(@" using System; using System.Linq; using System.Reflection; class C { private object F(Assembly assembly) { var type = (from t in assembly.GetTypes() select t.Attributes).FirstOrDefault(); return type; } } "); } [Fact] [WorkItem(8884, "https://github.com/dotnet/roslyn/issues/8884")] public void NoDiagnosticLinqTest_VB() { VerifyBasic(@" Imports System Imports System.Linq Imports System.Reflection Class C Private Function F(assembly As Assembly) As Object Dim type = (From t In assembly.DefinedTypes() Select t.Attributes).FirstOrDefault() Return type End Function End Class "); } [Fact] [WorkItem(459, "https://github.com/dotnet/roslyn-analyzers/issues/459")] public void NoDiagnosticSpecialCasesTest() { VerifyCSharp(@" using System; using System.Runtime.InteropServices; public abstract class Derived : Base, I { // Override public override void VirtualMethod(int param) { } // Abstract public abstract void AbstractMethod(int param); // Implicit interface implementation public void Method1(int param) { } // Explicit interface implementation void I.Method2(int param) { } // Event handlers public void MyEventHandler(object o, EventArgs e) { } public void MyEventHandler2(object o, MyEventArgs e) { } public class MyEventArgs : EventArgs { } } public class Base { // Virtual public virtual void VirtualMethod(int param) { } } public interface I { void Method1(int param); void Method2(int param); } public class ClassWithExtern { [DllImport(""Dependency.dll"")] public static extern void DllImportMethod(int param); public static extern void ExternalMethod(int param); } "); VerifyBasic(@" Imports System Imports System.Runtime.InteropServices Public MustInherit Class Derived Inherits Base Implements I ' Override Public Overrides Sub VirtualMethod(param As Integer) End Sub ' Abstract Public MustOverride Sub AbstractMethod(param As Integer) ' Explicit interface implementation - VB has no implicit interface implementation. Public Sub Method1(param As Integer) Implements I.Method1 End Sub ' Explicit interface implementation Private Sub I_Method2(param As Integer) Implements I.Method2 End Sub ' Event handlers Public Sub MyEventHandler(o As Object, e As EventArgs) End Sub Public Sub MyEventHandler2(o As Object, e As MyEventArgs) End Sub Public Class MyEventArgs Inherits EventArgs End Class End Class Public Class Base ' Virtual Public Overridable Sub VirtualMethod(param As Integer) End Sub End Class Public Interface I Sub Method1(param As Integer) Sub Method2(param As Integer) End Interface Public Class ClassWithExtern <DllImport(""Dependency.dll"")> Public Shared Sub DllImportMethod(param As Integer) End Sub Public Declare Function DeclareFunction Lib ""Dependency.dll"" (param As Integer) As Integer End Class "); } [Fact] [WorkItem(459, "https://github.com/dotnet/roslyn-analyzers/issues/459")] public void NoDiagnosticForMethodsWithSpecialAttributesTest() { VerifyCSharp(@" #define CONDITION_1 using System; using System.Diagnostics; using System.Runtime.Serialization; public class ConditionalMethodsClass { [Conditional(""CONDITION_1"")] private static void ConditionalMethod(int a) { AnotherConditionalMethod(a); } [Conditional(""CONDITION_2"")] private static void AnotherConditionalMethod(int b) { Console.WriteLine(b); } } public class SerializableMethodsClass { [OnSerializing] private void OnSerializingCallback(StreamingContext context) { Console.WriteLine(this); } [OnSerialized] private void OnSerializedCallback(StreamingContext context) { Console.WriteLine(this); } [OnDeserializing] private void OnDeserializingCallback(StreamingContext context) { Console.WriteLine(this); } [OnDeserialized] private void OnDeserializedCallback(StreamingContext context) { Console.WriteLine(this); } } "); VerifyBasic(@" #Const CONDITION_1 = 5 Imports System Imports System.Diagnostics Imports System.Runtime.Serialization Public Class ConditionalMethodsClass <Conditional(""CONDITION_1"")> _ Private Shared Sub ConditionalMethod(a As Integer) AnotherConditionalMethod(a) End Sub <Conditional(""CONDITION_2"")> _ Private Shared Sub AnotherConditionalMethod(b As Integer) Console.WriteLine(b) End Sub End Class Public Class SerializableMethodsClass <OnSerializing> _ Private Sub OnSerializingCallback(context As StreamingContext) Console.WriteLine(Me) End Sub <OnSerialized> _ Private Sub OnSerializedCallback(context As StreamingContext) Console.WriteLine(Me) End Sub <OnDeserializing> _ Private Sub OnDeserializingCallback(context As StreamingContext) Console.WriteLine(Me) End Sub <OnDeserialized> _ Private Sub OnDeserializedCallback(context As StreamingContext) Console.WriteLine(Me) End Sub End Class "); } [Fact, WorkItem(1218, "https://github.com/dotnet/roslyn-analyzers/issues/1218")] public void NoDiagnosticForMethodsUsedAsDelegatesCSharp() { VerifyCSharp(@" using System; public class C1 { private Action<object> _handler; public void Handler(object o1) { } public void SetupHandler() { _handler = Handler; } } public class C2 { public void Handler(object o1) { } public void TakesHandler(Action<object> handler) { handler(null); } public void SetupHandler() { TakesHandler(Handler); } } public class C3 { private Action<object> _handler; public C3() { _handler = Handler; } public void Handler(object o1) { } }"); } [Fact, WorkItem(1218, "https://github.com/dotnet/roslyn-analyzers/issues/1218")] public void NoDiagnosticForMethodsUsedAsDelegatesBasic() { VerifyBasic(@" Imports System Public Class C1 Private _handler As Action(Of Object) Public Sub Handler(o As Object) End Sub Public Sub SetupHandler() _handler = AddressOf Handler End Sub End Class Module M2 Sub Handler(o As Object) End Sub Sub TakesHandler(handler As Action(Of Object)) handler(Nothing) End Sub Sub SetupHandler() TakesHandler(AddressOf Handler) End Sub End Module Class C3 Private _handler As Action(Of Object) Sub New() _handler = AddressOf Handler End Sub Sub Handler(o As Object) End Sub End Class "); } [Fact, WorkItem(1218, "https://github.com/dotnet/roslyn-analyzers/issues/1218")] public void NoDiagnosticForObsoleteMethods() { VerifyCSharp(@" using System; public class C1 { [Obsolete] public void ObsoleteMethod(object o1) { } }"); VerifyBasic(@" Imports System Public Class C1 <Obsolete> Public Sub ObsoleteMethod(o1 as Object) End Sub End Class"); } [Fact, WorkItem(1218, "https://github.com/dotnet/roslyn-analyzers/issues/1218")] public void NoDiagnosticMethodJustThrowsNotImplemented() { VerifyCSharp(@" using System; public class MyAttribute: Attribute { public int X; public MyAttribute(int x) { X = x; } } public class C1 { public int Prop1 { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public void Method1(object o1) { throw new NotImplementedException(); } public void Method2(object o1) => throw new NotImplementedException(); [MyAttribute(0)] public void Method3(object o1) { throw new NotImplementedException(); } }"); VerifyBasic(@" Imports System Public Class C1 Property Prop1 As Integer Get Throw New NotImplementedException() End Get Set(ByVal value As Integer) Throw New NotImplementedException() End Set End Property Public Sub Method1(o1 As Object) Throw New NotImplementedException() End Sub End Class"); } [Fact, WorkItem(1218, "https://github.com/dotnet/roslyn-analyzers/issues/1218")] public void NoDiagnosticMethodJustThrowsNotSupported() { VerifyCSharp(@" using System; public class C1 { public int Prop1 { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } public void Method1(object o1) { throw new NotSupportedException(); } public void Method2(object o1) => throw new NotSupportedException(); }"); VerifyBasic(@" Imports System Public Class C1 Property Prop1 As Integer Get Throw New NotSupportedException() End Get Set(ByVal value As Integer) Throw New NotSupportedException() End Set End Property Public Sub Method1(o1 As Object) Throw New NotSupportedException() End Sub End Class"); } [Fact] public void NoDiagnosticsForIndexer() { VerifyCSharp(@" class C { public int this[int i] { get { return 0; } set { } } } "); VerifyBasic(@" Class C Public Property Item(i As Integer) As Integer Get Return 0 End Get Set End Set End Property End Class "); } [Fact] public void NoDiagnosticsForPropertySetter() { VerifyCSharp(@" class C { public int Property { get { return 0; } set { } } } "); VerifyBasic(@" Class C Public Property Property1 As Integer Get Return 0 End Get Set End Set End Property End Class "); } [Fact] public void NoDiagnosticsForFirstParameterOfExtensionMethod() { VerifyCSharp(@" static class C { static void ExtensionMethod(this int i) { } static int ExtensionMethod(this int i, int anotherParam) { return anotherParam; } } "); } [Fact] public void NoDiagnosticsForSingleStatementMethodsWithDefaultParameters() { VerifyCSharp(@" using System; public class C { public void Foo(string bar, string baz = null) { throw new NotImplementedException(); } } "); VerifyBasic(@" Imports System Public Class C Public Sub Test(bar As String, Optional baz As String = Nothing) Throw New NotImplementedException() End Sub End Class"); } [Fact] [WorkItem(2589, "https://github.com/dotnet/roslyn-analyzers/issues/2589")] [WorkItem(2593, "https://github.com/dotnet/roslyn-analyzers/issues/2593")] public void NoDiagnosticDiscardParameterNames() { VerifyCSharp(@" using System; public class C { public void M(int _, int _1, int _4) { } } "); VerifyBasic(@" Imports System Public Class C ' _ is not an allowed identifier in VB. Public Sub M(_1 As Integer, _2 As Integer, _4 As Integer) End Sub End Class "); } [Fact] [WorkItem(2466, "https://github.com/dotnet/roslyn-analyzers/issues/2466")] public void NoDiagnosticUsedLocalFunctionParameters() { VerifyCSharp(@" using System; public class C { public void M() { LocalFunction(0); return; void LocalFunction(int x) { Console.WriteLine(x); } } } "); } #endregion #region Unit tests for analyzer diagnostic(s) [Fact] [WorkItem(459, "https://github.com/dotnet/roslyn-analyzers/issues/459")] public void CSharp_DiagnosticForSimpleCasesTest() { VerifyCSharp(@" using System; class C { public C(int param) { } public void UnusedParamMethod(int param) { } public static void UnusedParamStaticMethod(int param1) { } public void UnusedDefaultParamMethod(int defaultParam = 1) { } public void UnusedParamsArrayParamMethod(params int[] paramsArr) { } public void MultipleUnusedParamsMethod(int param1, int param2) { } private void UnusedRefParamMethod(ref int param1) { } public void UnusedErrorTypeParamMethod(UndefinedType param1) // error CS0246: The type or namespace name 'UndefinedType' could not be found. { } } ", TestValidationMode.AllowCompileErrors, // Test0.cs(6,18): warning CA1801: Parameter param of method .ctor is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(6, 18, "param", ".ctor"), // Test0.cs(10,39): warning CA1801: Parameter param of method UnusedParamMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(10, 39, "param", "UnusedParamMethod"), // Test0.cs(14,52): warning CA1801: Parameter param1 of method UnusedParamStaticMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(14, 52, "param1", "UnusedParamStaticMethod"), // Test0.cs(18,46): warning CA1801: Parameter defaultParam of method UnusedDefaultParamMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(18, 46, "defaultParam", "UnusedDefaultParamMethod"), // Test0.cs(22,59): warning CA1801: Parameter paramsArr of method UnusedParamsArrayParamMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(22, 59, "paramsArr", "UnusedParamsArrayParamMethod"), // Test0.cs(26,48): warning CA1801: Parameter param1 of method MultipleUnusedParamsMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(26, 48, "param1", "MultipleUnusedParamsMethod"), // Test0.cs(26,60): warning CA1801: Parameter param2 of method MultipleUnusedParamsMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(26, 60, "param2", "MultipleUnusedParamsMethod"), // Test0.cs(30,47): warning CA1801: Parameter param1 of method UnusedRefParamMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(30, 47, "param1", "UnusedRefParamMethod"), // Test0.cs(34,58): warning CA1801: Parameter param1 of method UnusedErrorTypeParamMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(34, 58, "param1", "UnusedErrorTypeParamMethod")); } [Fact] [WorkItem(459, "https://github.com/dotnet/roslyn-analyzers/issues/459")] public void Basic_DiagnosticForSimpleCasesTest() { VerifyBasic(@" Class C Public Sub New(param As Integer) End Sub Public Sub UnusedParamMethod(param As Integer) End Sub Public Shared Sub UnusedParamStaticMethod(param1 As Integer) End Sub Public Sub UnusedDefaultParamMethod(Optional defaultParam As Integer = 1) End Sub Public Sub UnusedParamsArrayParamMethod(ParamArray paramsArr As Integer()) End Sub Public Sub MultipleUnusedParamsMethod(param1 As Integer, param2 As Integer) End Sub Private Sub UnusedRefParamMethod(ByRef param1 As Integer) End Sub Public Sub UnusedErrorTypeParamMethod(param1 As UndefinedType) ' error BC30002: Type 'UndefinedType' is not defined. End Sub End Class ", TestValidationMode.AllowCompileErrors, // Test0.vb(3,20): warning CA1801: Parameter param of method .ctor is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(3, 20, "param", ".ctor"), // Test0.vb(6,34): warning CA1801: Parameter param of method UnusedParamMethod is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(6, 34, "param", "UnusedParamMethod"), // Test0.vb(9,47): warning CA1801: Parameter param1 of method UnusedParamStaticMethod is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(9, 47, "param1", "UnusedParamStaticMethod"), // Test0.vb(12,50): warning CA1801: Parameter defaultParam of method UnusedDefaultParamMethod is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(12, 50, "defaultParam", "UnusedDefaultParamMethod"), // Test0.vb(15,56): warning CA1801: Parameter paramsArr of method UnusedParamsArrayParamMethod is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(15, 56, "paramsArr", "UnusedParamsArrayParamMethod"), // Test0.vb(18,43): warning CA1801: Parameter param1 of method MultipleUnusedParamsMethod is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(18, 43, "param1", "MultipleUnusedParamsMethod"), // Test0.vb(18,62): warning CA1801: Parameter param2 of method MultipleUnusedParamsMethod is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(18, 62, "param2", "MultipleUnusedParamsMethod"), // Test0.vb(21,44): warning CA1801: Parameter param1 of method UnusedRefParamMethod is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(21, 44, "param1", "UnusedRefParamMethod"), // Test0.vb(24,43): warning CA1801: Parameter param1 of method UnusedErrorTypeParamMethod is never used. Remove the parameter or use it in the method body. GetBasicUnusedParameterResultAt(24, 43, "param1", "UnusedErrorTypeParamMethod")); } [Fact] public void DiagnosticsForNonFirstParameterOfExtensionMethod() { VerifyCSharp(@" static class C { static void ExtensionMethod(this int i, int anotherParam) { } } ", // Test0.cs(4,49): warning CA1801: Parameter anotherParam of method ExtensionMethod is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(4, 49, "anotherParam", "ExtensionMethod")); } [Fact] [WorkItem(2466, "https://github.com/dotnet/roslyn-analyzers/issues/2466")] public void DiagnosticForUnusedLocalFunctionParameters_01() { VerifyCSharp(@" using System; public class C { public void M() { LocalFunction(0); return; void LocalFunction(int x) { } } }", // Test0.cs(11,32): warning CA1801: Parameter x of method LocalFunction is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(11, 32, "x", "LocalFunction")); } [Fact] [WorkItem(2466, "https://github.com/dotnet/roslyn-analyzers/issues/2466")] public void DiagnosticForUnusedLocalFunctionParameters_02() { VerifyCSharp(@" using System; public class C { public void M() { // Flag unused parameter even if LocalFunction is unused. void LocalFunction(int x) { } } }", // Test0.cs(9,32): warning CA1801: Parameter x of method LocalFunction is never used. Remove the parameter or use it in the method body. GetCSharpUnusedParameterResultAt(9, 32, "x", "LocalFunction")); } #endregion #region Helpers protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new ReviewUnusedParametersAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new ReviewUnusedParametersAnalyzer(); } private static DiagnosticResult GetCSharpUnusedParameterResultAt(int line, int column, string parameterName, string methodName) { string message = string.Format(MicrosoftCodeQualityAnalyzersResources.ReviewUnusedParametersMessage, parameterName, methodName); return GetCSharpResultAt(line, column, ReviewUnusedParametersAnalyzer.RuleId, message); } private static DiagnosticResult GetBasicUnusedParameterResultAt(int line, int column, string parameterName, string methodName) { string message = string.Format(MicrosoftCodeQualityAnalyzersResources.ReviewUnusedParametersMessage, parameterName, methodName); return GetBasicResultAt(line, column, ReviewUnusedParametersAnalyzer.RuleId, message); } #endregion } }
25.147233
170
0.650949
[ "Apache-2.0" ]
nathanstocking/roslyn-analyzers
src/Microsoft.CodeQuality.Analyzers/UnitTests/Maintainability/ReviewUnusedParametersTests.cs
25,449
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using AspNetCoreRestFull.Core.Models; namespace AspNetCoreRestFull.Core.Services { public interface ICariKartService: IService<CariKart> { Task<CariKart> GetWithSirketByIdAsync(int cariKartId); Task<CariKart> GetWithUlkeByIdAsync(int cariKartId); Task<CariKart> GetWithSubeByIdAsync(int cariKartId); Task<CariKart> GetWithIlByIdAsync(int cariKartId); Task<CariKart> GetWithIlceByIdAsync(int cariKartId); Task<CariKart> GetWithDovizByIdAsync(int cariKartId); } }
28.318182
62
0.754414
[ "MIT" ]
gulsenkeskin/AspNetCoreRestFullAPI1
AspNetCoreRestFull.Core/Services/ICariKartService.cs
623
C#
using System; using System.Collections.Generic; using System.Text; namespace YeeLightAPI { namespace YeeLightExceptions { public static class Exceptions { [Serializable] public class DeviceIsNotConnected : Exception { //TODO: add something here } [Serializable] public class DeviceIsAlreadyInMusicMode : Exception { //TODO: add something here } [Serializable] public class InvalidHostnameArgument : Exception { //TODO: add something here } } } }
21.870968
63
0.522124
[ "MIT" ]
Aytackydln/yeelight-api-csharp
YeeLightAPI/YeeLightAPI/YeeLightExceptions.cs
680
C#
using MessagePublisher.DTO; using RabbitMQ.Client; namespace MessagingService { public interface IMessagePublisher { IBasicProperties CreateBasicProperties(); void SendMessage(IMessage messageToSend, IBasicProperties props); } }
21.583333
73
0.749035
[ "MIT" ]
fupn26/ProjectManager_Onlab_2021
src/ProjectService/MessagePublisher/IMessagePublisher.cs
261
C#
namespace Cognition.Documents.Entity.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; public class Configuration : DbMigrationsConfiguration<Cognition.Documents.Entity.TypeContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(Cognition.Documents.Entity.TypeContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // } } }
32.03125
98
0.565854
[ "MIT" ]
mdsol/cognition
Cognition.Documents.Entity/Migrations/Configuration.cs
1,025
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace JqGridHelper.Utils { public class StronglyTyped : ExpressionVisitor { public static string PropertyName<TEntity>(Expression<Func<TEntity, object>> expression) { return new StronglyTyped().Name(expression); } private Stack<string> _stack; public string Path(Expression expression) { _stack = new Stack<string>(); Visit(expression); return _stack.Aggregate((s1, s2) => s1 + "." + s2); } protected override Expression VisitMember(MemberExpression expression) { if (_stack != null) _stack.Push(expression.Member.Name); return base.VisitMember(expression); } public string Name<TEntity>(Expression<Func<TEntity, object>> expression) { return Path(expression); } } }
28.257143
96
0.605662
[ "MIT" ]
saeed-m/N-Tier
JqGridHelper/Utils/StronglyTyped.cs
991
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.Editor.Shared.Utilities; using Microsoft.CodeAnalysis.UnifiedSuggestions.UnifiedSuggestedActions; using Microsoft.VisualStudio.Text; namespace Microsoft.CodeAnalysis.Editor.Implementation.Suggestions { /// <summary> /// Represents light bulb menu item for code refactorings. /// </summary> internal sealed class CodeRefactoringSuggestedAction : SuggestedActionWithNestedFlavors, ICodeRefactoringSuggestedAction { public CodeRefactoringProvider CodeRefactoringProvider { get; } public CodeRefactoringSuggestedAction( IThreadingContext threadingContext, SuggestedActionsSourceProvider sourceProvider, Workspace workspace, ITextBuffer subjectBuffer, CodeRefactoringProvider provider, CodeAction codeAction) : base(threadingContext, sourceProvider, workspace, subjectBuffer, provider, codeAction) { CodeRefactoringProvider = provider; } } }
39.818182
124
0.744292
[ "MIT" ]
06needhamt/roslyn
src/EditorFeatures/Core.Wpf/Suggestions/SuggestedActions/CodeRefactoringSuggestedAction.cs
1,316
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CardField : MonoBehaviour { public GameObject obj; private List<CardObject> cards; // Start is called before the first frame update void Start() { cards = new List<CardObject>(); // プレハブを元にオブジェクトを生成する GameObject cardobject = (GameObject)Instantiate(obj, this.transform.position + new Vector3(-1.75f, 1.0f, 0.0f), Quaternion.identity); CardObject card = cardobject.GetComponent<CardObject>(); card.cardindex = Random.Range(0, card.faces.Length); card.ToggleFace(true); cards.Add(card); } // Update is called once per frame void Update() { } }
27.225806
108
0.577014
[ "Unlicense" ]
koukinauglobe/Making_a_card_game_in_Unity
Project/Assets/CardField.cs
882
C#
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.ComponentModel.Composition; using System.Runtime.InteropServices; using Microsoft.PythonTools.Infrastructure; using Microsoft.PythonTools.Projects; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TestWindow.Extensibility; using Microsoft.VisualStudioTools; namespace Microsoft.PythonTools.TestAdapter { [Export(typeof(ITestMethodResolver))] class TestMethodResolver : ITestMethodResolver { private readonly IServiceProvider _serviceProvider; private readonly TestContainerDiscoverer _discoverer; #region ITestMethodResolver Members [ImportingConstructor] public TestMethodResolver([Import(typeof(SVsServiceProvider))]IServiceProvider serviceProvider, [Import]TestContainerDiscoverer discoverer) { _serviceProvider = serviceProvider; _discoverer = discoverer; } public Uri ExecutorUri { get { return TestContainerDiscoverer._ExecutorUri; } } public string GetCurrentTest(string filePath, int line, int lineCharOffset) { var pyProj = PythonProject.FromObject(PathToProject(filePath)); if (pyProj != null) { var container = _discoverer.GetTestContainer(pyProj, filePath); if (container != null) { foreach (var testCase in container.TestCases) { if (testCase.StartLine >= line && line <= testCase.EndLine) { var moduleName = PathUtils.CreateFriendlyFilePath(pyProj.ProjectHome, testCase.Filename); return moduleName + "::" + testCase.ClassName + "::" + testCase.MethodName; } } } } return null; } private IVsProject PathToProject(string filePath) { var rdt = (IVsRunningDocumentTable)_serviceProvider.GetService(typeof(SVsRunningDocumentTable)); IVsHierarchy hierarchy; uint itemId; IntPtr docData = IntPtr.Zero; uint cookie; try { var hr = rdt.FindAndLockDocument( (uint)_VSRDTFLAGS.RDT_NoLock, filePath, out hierarchy, out itemId, out docData, out cookie); ErrorHandler.ThrowOnFailure(hr); } finally { if (docData != IntPtr.Zero) { Marshal.Release(docData); docData = IntPtr.Zero; } } return hierarchy as IVsProject; } #endregion } }
38.217391
117
0.629977
[ "Apache-2.0" ]
awesome-archive/PTVS
Python/Product/TestAdapter/TestMethodResolver.cs
3,516
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.ComponentModel.Composition; using Microsoft.VisualStudio.LanguageServer.Client; using Microsoft.VisualStudio.Utilities; namespace Microsoft.VisualStudio.LanguageServerClient.Razor { internal sealed class RazorLSPContentTypeDefinition { public const string Name = "RazorLSP"; public const string CSHTMLFileExtension = ".cshtml"; public const string RazorFileExtension = ".razor"; /// <summary> /// Exports the Razor LSP content type /// </summary> [Export] [Name(Name)] [BaseDefinition(CodeRemoteContentDefinition.CodeRemoteContentTypeName)] public ContentTypeDefinition RazorLSPContentType { get; set; } // We can't associate the Razor LSP content type with the above file extensions because there's already a content type // associated with them. Instead, we utilize our RazorEditorFactory to assign the RazorLSPContentType to .razor/.cshtml // files. } }
39.931034
127
0.71848
[ "Apache-2.0" ]
devlead/aspnetcore-tooling
src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/RazorLSPContentTypeDefinition.cs
1,160
C#
#region Copyright 2014 Exceptionless // This program is free software: you can redistribute it and/or modify it // under the terms of the GNU Affero General Public License as published // by the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // http://www.gnu.org/licenses/agpl-3.0.html #endregion using System; using System.Collections.Generic; using System.Collections.ObjectModel; namespace Exceptionless.Models { public class Stack : IOwnedByOrganization, IOwnedByProject, IIdentity { public Stack() { Tags = new TagSet(); References = new Collection<string>(); SignatureInfo = new SettingsDictionary(); } /// <summary> /// Unique id that identifies a stack. /// </summary> public string Id { get; set; } /// <summary> /// The organization that the stack belongs to. /// </summary> public string OrganizationId { get; set; } /// <summary> /// The project that the stack belongs to. /// </summary> public string ProjectId { get; set; } /// <summary> /// The stack type (ie. error, log message, feature usage). Check <see cref="KnownTypes">Stack.KnownTypes</see> for standard stack types. /// </summary> public string Type { get; set; } /// <summary> /// The signature used for stacking future occurrences. /// </summary> public string SignatureHash { get; set; } /// <summary> /// The collection of information that went into creating the signature hash for the stack. /// </summary> public SettingsDictionary SignatureInfo { get; set; } /// <summary> /// The version the stack was fixed in. /// </summary> public string FixedInVersion { get; set; } /// <summary> /// The date the stack was fixed. /// </summary> public DateTime? DateFixed { get; set; } /// <summary> /// The stack title. /// </summary> public string Title { get; set; } /// <summary> /// The total number of occurrences in the stack. /// </summary> public int TotalOccurrences { get; set; } /// <summary> /// The date of the 1st occurrence of this stack in UTC time. /// </summary> public DateTime FirstOccurrence { get; set; } /// <summary> /// The date of the last occurrence of this stack in UTC time. /// </summary> public DateTime LastOccurrence { get; set; } /// <summary> /// The stack description. /// </summary> public string Description { get; set; } /// <summary> /// If true, notifications will not be sent for this stack. /// </summary> public bool DisableNotifications { get; set; } /// <summary> /// Controls whether occurrences are hidden from reports. /// </summary> public bool IsHidden { get; set; } /// <summary> /// If true, the stack was previously marked as fixed and a new occurrence came in. /// </summary> public bool IsRegressed { get; set; } /// <summary> /// If true, all future occurrences will be marked as critical. /// </summary> public bool OccurrencesAreCritical { get; set; } /// <summary> /// A list of references. /// </summary> public ICollection<string> References { get; set; } /// <summary> /// A list of tags used to categorize this stack. /// </summary> public TagSet Tags { get; set; } public static class KnownTypes { public const string Error = "error"; public const string NotFound = "404"; public const string Log = "log"; public const string FeatureUsage = "usage"; public const string SessionStart = "start"; public const string SessionEnd = "end"; } } }
32.203125
145
0.567686
[ "Apache-2.0" ]
mahizsas/Exceptionless
Source/Models/Admin/Stack.cs
4,124
C#
/* * Developer: Ramtin Jokar [ Ramtinak@live.com ] [ My Telegram Account: https://t.me/ramtinak ] * * Github source: https://github.com/ramtinak/InstagramApiSharp * Nuget package: https://www.nuget.org/packages/InstagramApiSharp * * IRANIAN DEVELOPERS */ using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Text; namespace InstagramApiSharp.Classes.Models { public class InstaContact { [JsonProperty("phone_numbers")] public List<string> PhoneNumbers { get; set; } [JsonProperty("email_addresses")] public List<string> EmailAddresses { get; set; } [JsonProperty("first_name")] public string FirstName { get; set; } [JsonProperty("last_name")] public string LastName { get; set; } } public class InstaContactList : List<InstaContact> { } public class InstaUserContact : InstaUserShort { public string ExtraDisplayName { get; set; } public bool HasExtraInfo { get { return !string.IsNullOrEmpty(ExtraDisplayName); } } } public class InstaContactUserList : List<InstaUserContact> { } }
26.326087
95
0.642444
[ "MIT" ]
AMP-VTV/InstagramApiSharp
src/InstagramApiSharp/Classes/Models/Discover/InstaContact.cs
1,213
C#
using System.Windows; namespace AdventureWorks.Client.Wpf { /// <summary> /// Interaction logic for MainView.xaml /// </summary> public partial class MainView : Window { public static void Start() { MainView main = new MainView(); Application.Current.MainWindow = main; main.Show(); } public MainView() { InitializeComponent(); } } }
19.869565
50
0.533917
[ "MIT" ]
Xomega-Net/Xomega.Examples
AdventureWorks/AdventureWorks.Client.Wpf/MainView.xaml.cs
459
C#
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using Microsoft.Build.BuildEngine; using Microsoft.Build.Framework; namespace ICSharpCode.SharpDevelop.BuildWorker { sealed class MSBuildWrapper { public void Cancel() { } readonly Engine engine; public MSBuildWrapper() { engine = new Engine(ToolsetDefinitionLocations.Registry | ToolsetDefinitionLocations.ConfigurationFile); } public bool DoBuild(BuildJob job, ILogger logger) { engine.RegisterLogger(logger); Program.Log("Building target '" + job.Target + "' in " + job.ProjectFileName); string[] targets = job.Target.Split(';'); BuildPropertyGroup globalProperties = new BuildPropertyGroup(); foreach (var pair in job.Properties) { globalProperties.SetProperty(pair.Key, pair.Value, true); } try { return engine.BuildProjectFile(job.ProjectFileName, targets, globalProperties); } finally { engine.UnregisterAllLoggers(); } } } }
35.724138
107
0.745656
[ "MIT" ]
TetradogOther/SharpDevelop
src/Main/ICSharpCode.SharpDevelop.BuildWorker35/MSBuild35.cs
2,074
C#
using UnityEngine; using UnityEditor; namespace ItchyOwl.Editor { /// <summary> /// Display a popup window with a text and a "OK" button to close the window. /// </summary> public class TextPopup : EditorWindow { private static string text; public static void Display(string msg) { text = msg; TextPopup window = GetWindow<TextPopup>(true, "Notification"); window.ShowAuxWindow(); } private void OnGUI() { EditorGUILayout.LabelField(text, EditorStyles.wordWrappedLabel); GUILayout.Space(70); if (GUILayout.Button("OK")) { Close(); } } } }
23.709677
81
0.544218
[ "MIT" ]
extraneus/general-unity-utilities
Editor/TextPopup.cs
737
C#