content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Reflection; using Autofac; using Autofac.Core; using Autofac.Core.Registration; using Nameless.DependencyInjection.Autofac; namespace Nameless.Localization.Json.Autofac.Extra { public sealed class LocalizationModule : ModuleBase { #region Protected Override Methods /// <inheritdoc/> protected override void Load(ContainerBuilder builder) { builder.Register<IPluralizationRuleProvider, DefaultPluralizationRuleProvider>(lifetimeScope: LifetimeScopeType.Singleton); builder.Register<IStringLocalizerFactory, StringLocalizerFactory>(lifetimeScope: LifetimeScopeType.Singleton); builder.Register<ITranslationStorage, FileSystemTranslationStorage>(lifetimeScope: LifetimeScopeType.Singleton); base.Load(builder); } /// <inheritdoc/> protected override void AttachToComponentRegistration(IComponentRegistryBuilder componentRegistry, IComponentRegistration registration) { registration.PipelineBuilding += (sender, pipeline) => { pipeline.Use(new FactoryResolveMiddleware( injectType: typeof(Localizer), factory: ResolveLocalizerDelegate )); }; base.AttachToComponentRegistration(componentRegistry, registration); } #endregion #region Private Static Methods private static Localizer ResolveLocalizerDelegate(MemberInfo member, IComponentContext context) => context.Resolve<IStringLocalizerFactory>().Create(member.DeclaringType).Get; #endregion } }
33.27907
177
0.803634
[ "MIT" ]
marcoaoteixeira/Nameless
src/Nameless.Localization.Json.Autofac.Extra/LocalizationModule.cs
1,433
C#
// <auto-generated /> // Built from: hl7.fhir.r5.core version: 4.6.0 // Option: "NAMESPACE" = "fhirCsR5" using fhirCsR5.Models; namespace fhirCsR5.ValueSets { /// <summary> /// Kind of precondition for the condition. /// </summary> public static class ConditionPreconditionTypeCodes { /// <summary> /// The observation is very sensitive for the condition, but may also indicate other conditions. /// </summary> public static readonly Coding Sensitive = new Coding { Code = "sensitive", Display = "Sensitive", System = "http://hl7.org/fhir/condition-precondition-type" }; /// <summary> /// The observation is very specific for this condition, but not particularly sensitive. /// </summary> public static readonly Coding Specific = new Coding { Code = "specific", Display = "Specific", System = "http://hl7.org/fhir/condition-precondition-type" }; }; }
27.970588
100
0.647739
[ "MIT" ]
FirelyTeam/fhir-codegen
src/Microsoft.Health.Fhir.SpecManager/fhir/R5/ValueSets/ConditionPreconditionType.cs
951
C#
using System; using System.IO; namespace HddTree { internal class FileNode : IThresholdItem { public string Name { get; private set; } public DateTime LastModified { get; private set; } public long Value { get; private set; } public FileNode(string filePath) { var info = new FileInfo(filePath); this.Name = info.FullName; this.LastModified = info.LastWriteTimeUtc; this.Value = info.Length; } } }
22.217391
58
0.587084
[ "Apache-2.0" ]
Sebastian-Gruchacz/Train.NetCore
src/HddTree/FileNode.cs
513
C#
namespace Dev.DevKit.Shared.Entities { public partial class msdyn_analysiscomponent { #region --- PROPERTIES --- //public DateTime? DateTime { get { return GetAliasedValue<DateTime?>("c.birthdate"); } } #endregion #region --- STATIC METHODS --- #endregion } }
18.705882
97
0.597484
[ "MIT" ]
Kayserheimer/Dynamics-Crm-DevKit
test/v.2.12.31/TestAllEntities/All-DEMO/Dev.DevKit.Shared/Entities/msdyn_analysiscomponent.cs
320
C#
using System.Threading.Tasks; using Shouldly; using Volo.Abp.Identity; using Xunit; namespace BookStore.Samples { /* This is just an example test class. * Normally, you don't test code of the modules you are using * (like IdentityUserManager here). * Only test your own domain services. */ public class SampleDomainTests : BookStoreDomainTestBase { private readonly IIdentityUserRepository _identityUserRepository; private readonly IdentityUserManager _identityUserManager; public SampleDomainTests() { _identityUserRepository = GetRequiredService<IIdentityUserRepository>(); _identityUserManager = GetRequiredService<IdentityUserManager>(); } [Fact] public async Task Should_Set_Email_Of_A_User() { IdentityUser adminUser; /* Need to manually start Unit Of Work because * FirstOrDefaultAsync should be executed while db connection / context is available. */ await WithUnitOfWorkAsync(async () => { adminUser = await _identityUserRepository .FindByNormalizedUserNameAsync("ADMIN"); await _identityUserManager.SetEmailAsync(adminUser, "newemail@abp.io"); await _identityUserRepository.UpdateAsync(adminUser); }); adminUser = await _identityUserRepository.FindByNormalizedUserNameAsync("ADMIN"); adminUser.Email.ShouldBe("newemail@abp.io"); } } }
33.956522
97
0.652369
[ "MIT" ]
271943794/abp-samples
BlazorPageUniTest/test/BookStore.Domain.Tests/Samples/SampleDomainTests.cs
1,564
C#
/** * Copyright 2015 Canada Health Infoway, Inc. * * 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. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ /* This class was auto-generated by the message builder generator tools. */ namespace Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_05_00.Pharmacy.Porx_mt060020ca { using Ca.Infoway.Messagebuilder; using Ca.Infoway.Messagebuilder.Annotation; using Ca.Infoway.Messagebuilder.Datatype; using Ca.Infoway.Messagebuilder.Datatype.Impl; using Ca.Infoway.Messagebuilder.Datatype.Lang; using Ca.Infoway.Messagebuilder.Domainvalue; using Ca.Infoway.Messagebuilder.Model; using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_05_00.Merged; using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_05_00.Pharmacy.Merged; using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_05_00.Pr.Coct_mt090108ca; using System; using System.Collections.Generic; /** * <summary>Business Name: Dispense</summary> * * <p>Communicates an overview of a patient's dispenses.</p> * <p>Represents the dispensing of a device to a patient.</p> */ [Hl7PartTypeMappingAttribute(new string[] {"PORX_MT060020CA.DeviceDispense"})] public class Dispense : MessagePartBean { private II id; private CS statusCode; private SET<CV, Code> confidentialityCode; private Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_05_00.Merged.SupervisedBy responsibleParty; private Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_05_00.Pr.Coct_mt090108ca.HealthcareWorker performerAssignedEntity; private Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_05_00.Merged.TargetedToPharmacy location; private Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_05_00.Pharmacy.Merged.DispenseDetails componentSupplyEvent; private Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_05_00.Pharmacy.Merged.SupplyOrder fulfillmentSupplyRequest; private BL subjectOf1DetectedIssueIndicator; private BL subjectOf2AnnotationIndicator; public Dispense() { this.id = new IIImpl(); this.statusCode = new CSImpl(); this.confidentialityCode = new SETImpl<CV, Code>(typeof(CVImpl)); this.subjectOf1DetectedIssueIndicator = new BLImpl(false); this.subjectOf2AnnotationIndicator = new BLImpl(false); } /** * <summary>Business Name: A:Prescription Dispense Number</summary> * * <remarks>Relationship: PORX_MT060020CA.DeviceDispense.id * Conformance/Cardinality: MANDATORY (1) <p>Allows for the * referencing of a specific dispense record.</p><p>Identifier * for a dispensed record is needed so that dispenses may be * uniquely referenced. Thus the mandatory requirement.</p> * <p>The Prescription Dispense Number is a globally unique * number assigned to a dispense (single fill) by the EHR/DIS * irrespective of the source of the dispense.</p><p>It is * created by the EHR/DIS once the dispense has passed all * edits and validation.</p></remarks> */ [Hl7XmlMappingAttribute(new string[] {"id"})] public Identifier Id { get { return this.id.Value; } set { this.id.Value = value; } } /** * <summary>Business Name: C:Dispense Status</summary> * * <remarks>Relationship: * PORX_MT060020CA.DeviceDispense.statusCode * Conformance/Cardinality: MANDATORY (1) <p>Important in * understanding what medication the patient actually has on * hand, thus the attribute is mandatory. May also influence * the ability of a different pharmacy to dispense the * medication.</p> <p>Indicates the status of the dispense * record created on the EHR/DIS. If 'Active' it means that the * dispense has been processed but not yet given to the * patient. If 'Complete', it indicates that the medication has * been delivered to the patient.</p></remarks> */ [Hl7XmlMappingAttribute(new string[] {"statusCode"})] public ActStatus StatusCode { get { return (ActStatus) this.statusCode.Value; } set { this.statusCode.Value = value; } } /** * <summary>Business Name: E:Prescription Masking Indicators</summary> * * <remarks>Relationship: * PORX_MT060020CA.DeviceDispense.confidentialityCode * Conformance/Cardinality: REQUIRED (0-2) <p>Allows the * patient to have discrete control over access to their * medication data.</p><p>Taboo allows the provider to request * restricted access to patient or their care * giver.</p><p>Constraint: Can't have both normal and one of * the other codes simultaneously.</p><p>The attribute is * required because even if a jurisdiction doesn't support * masking on the way in, it will need to need to communicate * masked data returned from other jurisdictions.</p> * <p>Communicates the intent of the patient to restrict access * to their prescriptions.</p><p>Provides support for * additional confidentiality constraint, giving patients a * level of control over their information.</p><p>Allows * providers to request restricted access by * patients.</p><p>Valid values are: 'N' (normal - denotes 'Not * Masked'); 'R' (restricted - denotes 'Masked'); 'V' (very * restricted - denotes very restricted access as declared by * the Privacy Officer of the record holder) and 'T' (taboo - * denotes 'Patient Access Restricted').</p><p>The default is * 'normal' signifying 'Not Masked'.</p></remarks> */ [Hl7XmlMappingAttribute(new string[] {"confidentialityCode"})] public ICollection<x_BasicConfidentialityKind> ConfidentialityCode { get { return this.confidentialityCode.RawSet<x_BasicConfidentialityKind>(); } } /** * <summary>Relationship: * PORX_MT060020CA.DeviceDispense.responsibleParty</summary> * * <remarks>Conformance/Cardinality: REQUIRED (0-1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"responsibleParty"})] public Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_05_00.Merged.SupervisedBy ResponsibleParty { get { return this.responsibleParty; } set { this.responsibleParty = value; } } /** * <summary>Relationship: * PORX_MT060020CA.Performer.assignedEntity</summary> * * <remarks>Conformance/Cardinality: MANDATORY (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"performer/assignedEntity"})] public Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_05_00.Pr.Coct_mt090108ca.HealthcareWorker PerformerAssignedEntity { get { return this.performerAssignedEntity; } set { this.performerAssignedEntity = value; } } /** * <summary>Relationship: * PORX_MT060020CA.DeviceDispense.location</summary> * * <remarks>Conformance/Cardinality: MANDATORY (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"location"})] public Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_05_00.Merged.TargetedToPharmacy Location { get { return this.location; } set { this.location = value; } } /** * <summary>Relationship: * PORX_MT060020CA.Component2.supplyEvent</summary> * * <remarks>Conformance/Cardinality: MANDATORY (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"component/supplyEvent"})] public Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_05_00.Pharmacy.Merged.DispenseDetails ComponentSupplyEvent { get { return this.componentSupplyEvent; } set { this.componentSupplyEvent = value; } } /** * <summary>Relationship: * PORX_MT060020CA.InFulfillmentOf.supplyRequest</summary> * * <remarks>Conformance/Cardinality: REQUIRED (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"fulfillment/supplyRequest"})] public Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_05_00.Pharmacy.Merged.SupplyOrder FulfillmentSupplyRequest { get { return this.fulfillmentSupplyRequest; } set { this.fulfillmentSupplyRequest = value; } } /** * <summary>Relationship: * PORX_MT060020CA.Subject4.detectedIssueIndicator</summary> * * <remarks>Conformance/Cardinality: REQUIRED (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"subjectOf1/detectedIssueIndicator"})] public bool? SubjectOf1DetectedIssueIndicator { get { return this.subjectOf1DetectedIssueIndicator.Value; } set { this.subjectOf1DetectedIssueIndicator.Value = value; } } /** * <summary>Relationship: * PORX_MT060020CA.Subject3.annotationIndicator</summary> * * <remarks>Conformance/Cardinality: REQUIRED (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"subjectOf2/annotationIndicator"})] public bool? SubjectOf2AnnotationIndicator { get { return this.subjectOf2AnnotationIndicator.Value; } set { this.subjectOf2AnnotationIndicator.Value = value; } } } }
47.932127
130
0.645993
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-r02_05_00/Main/Ca/Infoway/Messagebuilder/Model/Pcs_mr2009_r02_05_00/Pharmacy/Porx_mt060020ca/Dispense.cs
10,593
C#
using System; class OptimizedUnion { private int[] root; private int[] rank; // O(n) public OptimizedUnion(int vertices){ root = new int[vertices]; rank = new int[verties]; for(int i = 0; i < vertices; i++){ root[i] = i; rank[i] = 1; } } // O(h) public int Find(int x){ while(x == root[x]){ return x; } return root[x] = Find(root[x]);; } public void Union(int x, int y){ int rootX = Find(x); int rootY = Find(y); if(rootX != rootY){ if(rank[rootX] > rank[rootY]){ root[rootY] = rootX; } else if(rank[rootX] < rank[rootY]){ root[rootX] = rootY; } else { root[rootY] = rootX; rank[rootX]++; } } } public bool IsConnected(int x, int y){ return Find(x) == Find(y); } }
18.545455
43
0.512255
[ "MIT" ]
ej-sanmartin/ComputerScienceReference
graphTheory/optimizedUnionFind/main.cs
816
C#
/* * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) * See https://github.com/openiddict/openiddict-core for more information concerning * the license and the contributors participating to this project. */ using System; using System.Data.Entity; using Microsoft.Extensions.Caching.Memory; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Moq; using OpenIddict.Abstractions; using OpenIddict.EntityFramework.Models; using Xunit; using static OpenIddict.EntityFramework.OpenIddictEntityFrameworkScopeStoreResolver; using SR = OpenIddict.Abstractions.OpenIddictResources; namespace OpenIddict.EntityFramework.Tests { public class OpenIddictEntityFrameworkScopeStoreResolverTests { [Fact] public void Get_ReturnsCustomStoreCorrespondingToTheSpecifiedTypeWhenAvailable() { // Arrange var services = new ServiceCollection(); services.AddSingleton(Mock.Of<IOpenIddictScopeStore<CustomScope>>()); var options = Mock.Of<IOptionsMonitor<OpenIddictEntityFrameworkOptions>>(); var provider = services.BuildServiceProvider(); var resolver = new OpenIddictEntityFrameworkScopeStoreResolver(new TypeResolutionCache(), options, provider); // Act and assert Assert.NotNull(resolver.Get<CustomScope>()); } [Fact] public void Get_ThrowsAnExceptionForInvalidEntityType() { // Arrange var services = new ServiceCollection(); var options = Mock.Of<IOptionsMonitor<OpenIddictEntityFrameworkOptions>>(); var provider = services.BuildServiceProvider(); var resolver = new OpenIddictEntityFrameworkScopeStoreResolver(new TypeResolutionCache(), options, provider); // Act and assert var exception = Assert.Throws<InvalidOperationException>(() => resolver.Get<CustomScope>()); Assert.Equal(SR.GetResourceString(SR.ID1236), exception.Message); } [Fact] public void Get_ThrowsAnExceptionWhenDbContextTypeIsNotAvailable() { // Arrange var services = new ServiceCollection(); var options = Mock.Of<IOptionsMonitor<OpenIddictEntityFrameworkOptions>>( mock => mock.CurrentValue == new OpenIddictEntityFrameworkOptions { DbContextType = null }); var provider = services.BuildServiceProvider(); var resolver = new OpenIddictEntityFrameworkScopeStoreResolver(new TypeResolutionCache(), options, provider); // Act and assert var exception = Assert.Throws<InvalidOperationException>(() => resolver.Get<OpenIddictEntityFrameworkScope>()); Assert.Equal(SR.GetResourceString(SR.ID1234), exception.Message); } [Fact] public void Get_ReturnsDefaultStoreCorrespondingToTheSpecifiedTypeWhenAvailable() { // Arrange var services = new ServiceCollection(); services.AddSingleton(Mock.Of<IOpenIddictScopeStore<CustomScope>>()); services.AddSingleton(CreateStore()); var options = Mock.Of<IOptionsMonitor<OpenIddictEntityFrameworkOptions>>( mock => mock.CurrentValue == new OpenIddictEntityFrameworkOptions { DbContextType = typeof(DbContext) }); var provider = services.BuildServiceProvider(); var resolver = new OpenIddictEntityFrameworkScopeStoreResolver(new TypeResolutionCache(), options, provider); // Act and assert Assert.NotNull(resolver.Get<MyScope>()); } private static OpenIddictEntityFrameworkScopeStore<MyScope, DbContext, long> CreateStore() => new Mock<OpenIddictEntityFrameworkScopeStore<MyScope, DbContext, long>>( Mock.Of<IMemoryCache>(), Mock.Of<DbContext>(), Mock.Of<IOptionsMonitor<OpenIddictEntityFrameworkOptions>>()).Object; public class CustomScope { } public class MyApplication : OpenIddictEntityFrameworkApplication<long, MyAuthorization, MyToken> { } public class MyAuthorization : OpenIddictEntityFrameworkAuthorization<long, MyApplication, MyToken> { } public class MyScope : OpenIddictEntityFrameworkScope<long> { } public class MyToken : OpenIddictEntityFrameworkToken<long, MyApplication, MyAuthorization> { } } }
41.718182
123
0.677054
[ "Apache-2.0" ]
Bartmax/openiddict-core
test/OpenIddict.EntityFramework.Tests/Resolvers/OpenIddictEntityFrameworkScopeStoreResolverTests.cs
4,591
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/MSAAText.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace TerraFX.Interop { [Guid("25642426-028D-4474-977B-111BB114FE3E")] [NativeTypeName("struct ITextStoreSinkAnchorEx : ITextStoreAnchorSink")] public unsafe partial struct ITextStoreSinkAnchorEx { public void** lpVtbl; [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int QueryInterface([NativeTypeName("const IID &")] Guid* riid, [NativeTypeName("void **")] void** ppvObject) { return ((delegate* unmanaged<ITextStoreSinkAnchorEx*, Guid*, void**, int>)(lpVtbl[0]))((ITextStoreSinkAnchorEx*)Unsafe.AsPointer(ref this), riid, ppvObject); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint AddRef() { return ((delegate* unmanaged<ITextStoreSinkAnchorEx*, uint>)(lpVtbl[1]))((ITextStoreSinkAnchorEx*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("ULONG")] public uint Release() { return ((delegate* unmanaged<ITextStoreSinkAnchorEx*, uint>)(lpVtbl[2]))((ITextStoreSinkAnchorEx*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int OnTextChange([NativeTypeName("DWORD")] uint dwFlags, [NativeTypeName("IAnchor *")] IAnchor* paStart, [NativeTypeName("IAnchor *")] IAnchor* paEnd) { return ((delegate* unmanaged<ITextStoreSinkAnchorEx*, uint, IAnchor*, IAnchor*, int>)(lpVtbl[3]))((ITextStoreSinkAnchorEx*)Unsafe.AsPointer(ref this), dwFlags, paStart, paEnd); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int OnSelectionChange() { return ((delegate* unmanaged<ITextStoreSinkAnchorEx*, int>)(lpVtbl[4]))((ITextStoreSinkAnchorEx*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int OnLayoutChange(TsLayoutCode lcode, [NativeTypeName("TsViewCookie")] uint vcView) { return ((delegate* unmanaged<ITextStoreSinkAnchorEx*, TsLayoutCode, uint, int>)(lpVtbl[5]))((ITextStoreSinkAnchorEx*)Unsafe.AsPointer(ref this), lcode, vcView); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int OnStatusChange([NativeTypeName("DWORD")] uint dwFlags) { return ((delegate* unmanaged<ITextStoreSinkAnchorEx*, uint, int>)(lpVtbl[6]))((ITextStoreSinkAnchorEx*)Unsafe.AsPointer(ref this), dwFlags); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int OnAttrsChange([NativeTypeName("IAnchor *")] IAnchor* paStart, [NativeTypeName("IAnchor *")] IAnchor* paEnd, [NativeTypeName("ULONG")] uint cAttrs, [NativeTypeName("const TS_ATTRID *")] Guid* paAttrs) { return ((delegate* unmanaged<ITextStoreSinkAnchorEx*, IAnchor*, IAnchor*, uint, Guid*, int>)(lpVtbl[7]))((ITextStoreSinkAnchorEx*)Unsafe.AsPointer(ref this), paStart, paEnd, cAttrs, paAttrs); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int OnLockGranted([NativeTypeName("DWORD")] uint dwLockFlags) { return ((delegate* unmanaged<ITextStoreSinkAnchorEx*, uint, int>)(lpVtbl[8]))((ITextStoreSinkAnchorEx*)Unsafe.AsPointer(ref this), dwLockFlags); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int OnStartEditTransaction() { return ((delegate* unmanaged<ITextStoreSinkAnchorEx*, int>)(lpVtbl[9]))((ITextStoreSinkAnchorEx*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int OnEndEditTransaction() { return ((delegate* unmanaged<ITextStoreSinkAnchorEx*, int>)(lpVtbl[10]))((ITextStoreSinkAnchorEx*)Unsafe.AsPointer(ref this)); } [MethodImpl(MethodImplOptions.AggressiveInlining)] [return: NativeTypeName("HRESULT")] public int OnDisconnect() { return ((delegate* unmanaged<ITextStoreSinkAnchorEx*, int>)(lpVtbl[11]))((ITextStoreSinkAnchorEx*)Unsafe.AsPointer(ref this)); } } }
48.300971
218
0.679196
[ "MIT" ]
Perksey/terrafx.interop.windows
sources/Interop/Windows/um/MSAAText/ITextStoreSinkAnchorEx.cs
4,977
C#
using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections; using System.Xml.Schema; using System.Xml.Serialization; using Thinktecture.Tools.Web.Services.Wscf.Environment; using GenerationOptions = System.Xml.Serialization.CodeGenerationOptions; namespace Thinktecture.Tools.Web.Services.CodeGeneration { /// <summary> /// Generates the CodeDOM for data contracts. /// </summary> internal class DataContractGenerator : ICodeGenerator { #region Private members private readonly XmlSchemas schemas; private readonly CodeDomProvider codeProvider; private readonly PrimaryCodeGenerationOptions options; #endregion #region Contructors /// <summary> /// Initializes a new instance of the <see cref="DataContractGenerator"/> class. /// </summary> /// <param name="schemas">The XML schemas.</param> /// <param name="options">The code generation options.</param> /// <param name="codeProvider">The code provider.</param> public DataContractGenerator(XmlSchemas schemas, PrimaryCodeGenerationOptions options, CodeDomProvider codeProvider) { this.schemas = Enforce.IsNotNull(schemas, "schemas"); this.options = Enforce.IsNotNull(options, "options"); this.codeProvider = Enforce.IsNotNull(codeProvider, "codeProvider"); } #endregion #region Public methods /// <summary> /// Generates the data contracts for given xsd file(s). /// </summary> public CodeNamespace GenerateCode() { CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeNamespace codeNamespace = new CodeNamespace(options.ClrNamespace); codeCompileUnit.Namespaces.Add(codeNamespace); // Build the code generation options. GenerationOptions generationOptions = GenerationOptions.None; if (options.GenerateProperties) { generationOptions |= GenerationOptions.GenerateProperties; } if (options.EnableDataBinding) { generationOptions |= GenerationOptions.EnableDataBinding; } if (options.GenerateOrderIdentifiers) { generationOptions |= GenerationOptions.GenerateOrder; } // Build the CodeDom object graph. XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace, codeCompileUnit, generationOptions, null); CodeIdentifiers codeIdentifiers = new CodeIdentifiers(); ImportContext importContext = new ImportContext(codeIdentifiers, false); XmlSchemaImporter schemaimporter = new XmlSchemaImporter(schemas, generationOptions, codeProvider, importContext); for (int si = 0; si < schemas.Count; si++) { XmlSchema schema = schemas[si]; IEnumerator enumerator = schema.Elements.Values.GetEnumerator(); IEnumerator enumerator2 = schema.SchemaTypes.Values.GetEnumerator(); try { while (enumerator.MoveNext()) { XmlSchemaElement element = (XmlSchemaElement)enumerator.Current; if (element.IsAbstract) continue; XmlTypeMapping typemapping = schemaimporter.ImportTypeMapping(element.QualifiedName); codeExporter.ExportTypeMapping(typemapping); } while (enumerator2.MoveNext()) { XmlSchemaType type = (XmlSchemaType)enumerator2.Current; if (CouldBeAnArray(type)) continue; XmlTypeMapping typemapping = schemaimporter.ImportSchemaType(type.QualifiedName); codeExporter.ExportTypeMapping(typemapping); } } finally { IDisposable disposableobject = enumerator as IDisposable; if (disposableobject != null) { disposableobject.Dispose(); } IDisposable disposableobject2 = enumerator2 as IDisposable; if (disposableobject2 != null) { disposableobject2.Dispose(); } } } if (codeNamespace.Types.Count == 0) { throw new Exception("No types were generated."); } return codeNamespace; } #endregion #region Private methods /// <summary> /// Checks whether a given XmlSchemaType could be represented as an array. That is the XmlSchemaType /// has to be: /// 1. Complex type /// 2. ...with no base type /// 3. ...has no attributes /// 4. ...has only one element /// 5. ...whose maxOccurs is > 1 /// </summary> /// <returns></returns> private static bool CouldBeAnArray(XmlSchemaType schematype) { XmlSchemaComplexType complextype = schematype as XmlSchemaComplexType; if (complextype != null) { if (complextype.Attributes.Count == 0) { XmlSchemaSequence sequence = complextype.Particle as XmlSchemaSequence; if (sequence != null) { if (sequence.Items.Count == 1) { XmlSchemaElement element = sequence.Items[0] as XmlSchemaElement; if (element != null) { if (element.MaxOccurs > 1 || (element.MaxOccursString != null && element.MaxOccursString.ToLower() == "unbounded")) { return true; } } } } } } return false; } #endregion } }
30.48503
124
0.678649
[ "BSD-3-Clause" ]
gimmemoore/wscf.green
Branches/V1/Thinktecture.Tools.Web.Services.CodeGeneration/DataContractGenerator.cs
5,093
C#
using System.Collections.Generic; using esharp.solidity.compiler.Syntax; namespace esharp.solidity.compiler { internal sealed class Lexer { private readonly string _text; private int _position; // private DiagnosticBag _diagnostics = new DiagnosticBag(); public Lexer(string text) { _text = text; } // public DiagnosticBag Diagnostics => _diagnostics; private char Current => Peek(0); private char Lookahead => Peek(1); private char Peek(int offset) { var index = _position + offset; if (index >= _text.Length) return '\0'; return _text[index]; } private void Next() { _position++; } public SyntaxToken Lex() { if (_position >= _text.Length) return new SyntaxToken(SyntaxKind.EndOfFileToken, _position, "\0", null); var start = _position; if (char.IsDigit(Current)) { while (char.IsDigit(Current)) Next(); var length = _position - start; var text = _text.Substring(start, length); if (!int.TryParse(text, out var value)) //_diagnostics.ReportInvalidNumber(new TextSpan(start, length), _text, typeof(int)); return new SyntaxToken(SyntaxKind.NumberToken, start, text, value); } if (char.IsWhiteSpace(Current)) { while (char.IsWhiteSpace(Current)) Next(); var length = _position - start; var text = _text.Substring(start, length); return new SyntaxToken(SyntaxKind.WhitespaceToken, start, text, null); } if (char.IsLetter(Current)) { while (char.IsLetter(Current)) Next(); var length = _position - start; var text = _text.Substring(start, length); var kind = SyntaxFacts.GetKeywordKind(text); return new SyntaxToken(kind, start, text, null); } switch (Current) { case '+': return new SyntaxToken(SyntaxKind.PlusToken, _position++, "+", null); case '-': return new SyntaxToken(SyntaxKind.MinusToken, _position++, "-", null); case '*': return new SyntaxToken(SyntaxKind.StarToken, _position++, "*", null); case '/': return new SyntaxToken(SyntaxKind.SlashToken, _position++, "/", null); case '(': return new SyntaxToken(SyntaxKind.OpenParenthesisToken, _position++, "(", null); case ')': return new SyntaxToken(SyntaxKind.CloseParenthesisToken, _position++, ")", null); case '&': if (Lookahead == '&') { _position += 2; return new SyntaxToken(SyntaxKind.AmpersandAmpersandToken, start, "&&", null); } break; case '|': if (Lookahead == '|') { _position += 2; return new SyntaxToken(SyntaxKind.PipePipeToken, start, "||", null); } break; case '=': if (Lookahead == '=') { _position += 2; return new SyntaxToken(SyntaxKind.EqualsEqualsToken, start, "==", null); } else { _position += 1; return new SyntaxToken(SyntaxKind.EqualsToken, start, "=", null); } case '!': if (Lookahead == '=') { _position += 2; return new SyntaxToken(SyntaxKind.BangEqualsToken, start, "!=", null); } else { _position += 1; return new SyntaxToken(SyntaxKind.BangToken, start, "!", null); } } //_diagnostics.ReportBadCharacter(_position, Current); return new SyntaxToken(SyntaxKind.BadToken, _position++, _text.Substring(_position - 1, 1), null); } } }
34.459259
110
0.454428
[ "CC0-1.0" ]
esharpio/esharp.solidity.compiler
src/esharp.solidity.compiler/Lexer.cs
4,652
C#
using UnityEngine; public class FrostArmorEffect : DurationEffect { private const int resistanceIncrease = 30; public FrostArmorEffect() { name = "Frost Armor"; } protected override void onActivate() { owner.attrChange.physicalDefense += effectValue; owner.attrChange.iceResistance += resistanceIncrease; } protected override void onDeactivateEffects() { owner.attrChange.physicalDefense -= effectValue; owner.attrChange.iceResistance -= resistanceIncrease; } }
27.666667
57
0.748996
[ "MIT" ]
Fellowship-of-the-Bus/Draconia-Unity
Assets/Script/Effects/IceWizard/FrostArmorEffect.cs
498
C#
// WARNING // // This file has been generated automatically by Xamarin Studio to store outlets and // actions made in the UI designer. If it is removed, they will be lost. // Manual changes to this file may not be handled correctly. // using MonoTouch.Foundation; using System.CodeDom.Compiler; namespace Sunny.iOS.Views { [Register("NewsOverviewView")] partial class NewsOverviewView { [Outlet] MonoTouch.UIKit.UIButton backButton { get; set; } void ReleaseDesignerOutlets() { if (backButton != null) { backButton.Dispose(); backButton = null; } } } }
24.25
84
0.614138
[ "MIT" ]
rootdevelop/Sunny
App/Sunny.iOS/Views/NewsOverviewView.designer.cs
679
C#
using System; using System.IO; namespace YAF.Lucene.Net.Analysis { /* * 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. */ /// <summary> /// Extension to <see cref="Analyzer"/> suitable for <see cref="Analyzer"/>s which wrap /// other <see cref="Analyzer"/>s. /// <para/> /// <see cref="GetWrappedAnalyzer(string)"/> allows the <see cref="Analyzer"/> /// to wrap multiple <see cref="Analyzer"/>s which are selected on a per field basis. /// <para/> /// <see cref="WrapComponents(string, TokenStreamComponents)"/> allows the /// <see cref="TokenStreamComponents"/> of the wrapped <see cref="Analyzer"/> to then be wrapped /// (such as adding a new <see cref="TokenFilter"/> to form new <see cref="TokenStreamComponents"/>). /// </summary> public abstract class AnalyzerWrapper : Analyzer { /// <summary> /// Creates a new <see cref="AnalyzerWrapper"/>. Since the <see cref="ReuseStrategy"/> of /// the wrapped <see cref="Analyzer"/>s are unknown, <see cref="Analyzer.PER_FIELD_REUSE_STRATEGY"/> is assumed. /// </summary> [Obsolete("Use AnalyzerWrapper(Analyzer.ReuseStrategy) and specify a valid Analyzer.ReuseStrategy, probably retrieved from the wrapped analyzer using Analyzer.Strategy.")] protected internal AnalyzerWrapper() : this(PER_FIELD_REUSE_STRATEGY) { } /// <summary> /// Creates a new <see cref="AnalyzerWrapper"/> with the given reuse strategy. /// <para/>If you want to wrap a single delegate <see cref="Analyzer"/> you can probably /// reuse its strategy when instantiating this subclass: /// <c>base(innerAnalyzer.Strategy)</c>. /// <para/>If you choose different analyzers per field, use /// <see cref="Analyzer.PER_FIELD_REUSE_STRATEGY"/>. /// </summary> /// <seealso cref="Analyzer.Strategy"/> protected internal AnalyzerWrapper(ReuseStrategy reuseStrategy) : base(reuseStrategy) { } /// <summary> /// Retrieves the wrapped <see cref="Analyzer"/> appropriate for analyzing the field with /// the given name /// </summary> /// <param name="fieldName"> Name of the field which is to be analyzed </param> /// <returns> <see cref="Analyzer"/> for the field with the given name. Assumed to be non-null </returns> protected abstract Analyzer GetWrappedAnalyzer(string fieldName); /// <summary> /// Wraps / alters the given <see cref="TokenStreamComponents"/>, taken from the wrapped /// <see cref="Analyzer"/>, to form new components. It is through this method that new /// <see cref="TokenFilter"/>s can be added by <see cref="AnalyzerWrapper"/>s. By default, the given /// components are returned. /// </summary> /// <param name="fieldName"> /// Name of the field which is to be analyzed </param> /// <param name="components"> /// <see cref="TokenStreamComponents"/> taken from the wrapped <see cref="Analyzer"/> </param> /// <returns> Wrapped / altered <see cref="TokenStreamComponents"/>. </returns> protected virtual TokenStreamComponents WrapComponents(string fieldName, TokenStreamComponents components) { return components; } /// <summary> /// Wraps / alters the given <see cref="TextReader"/>. Through this method <see cref="AnalyzerWrapper"/>s can /// implement <see cref="InitReader(string, TextReader)"/>. By default, the given reader /// is returned. /// </summary> /// <param name="fieldName"> /// name of the field which is to be analyzed </param> /// <param name="reader"> /// the reader to wrap </param> /// <returns> the wrapped reader </returns> protected virtual TextReader WrapReader(string fieldName, TextReader reader) { return reader; } protected internal override sealed TokenStreamComponents CreateComponents(string fieldName, TextReader aReader) { var wrappedAnalyzer = GetWrappedAnalyzer(fieldName); var component = wrappedAnalyzer.CreateComponents(fieldName, aReader); return WrapComponents(fieldName, component); } public override int GetPositionIncrementGap(string fieldName) { return GetWrappedAnalyzer(fieldName).GetPositionIncrementGap(fieldName); } public override int GetOffsetGap(string fieldName) { return GetWrappedAnalyzer(fieldName).GetOffsetGap(fieldName); } protected internal override TextReader InitReader(string fieldName, TextReader reader) { return GetWrappedAnalyzer(fieldName).InitReader(fieldName, WrapReader(fieldName, reader)); } } }
48.619835
180
0.626891
[ "Apache-2.0" ]
10by10pixel/YAFNET
yafsrc/Lucene.Net/Lucene.Net/Analysis/AnalyzerWrapper.cs
5,763
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections; using System.Collections.Generic; namespace System.Text.Json.Serialization.Converters { /// <summary> /// Converter for <cref>System.Collections.IDictionary</cref> that (de)serializes as a JSON object with properties /// representing the dictionary element key and value. /// </summary> internal sealed class IDictionaryConverter<TCollection> : DictionaryDefaultConverter<TCollection, object?> where TCollection : IDictionary { protected override void Add(in object? value, JsonSerializerOptions options, ref ReadStack state) { string key = state.Current.JsonPropertyNameAsString!; ((IDictionary)state.Current.ReturnValue!)[key] = value; } protected override void CreateCollection(ref Utf8JsonReader reader, ref ReadStack state) { JsonClassInfo classInfo = state.Current.JsonClassInfo; if (TypeToConvert.IsInterface || TypeToConvert.IsAbstract) { if (!TypeToConvert.IsAssignableFrom(RuntimeType)) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = new Dictionary<string, object>(); } else { if (classInfo.CreateObject == null) { ThrowHelper.ThrowNotSupportedException_DeserializeNoConstructor(TypeToConvert, ref reader, ref state); } TCollection returnValue = (TCollection)classInfo.CreateObject()!; if (returnValue.IsReadOnly) { ThrowHelper.ThrowNotSupportedException_CannotPopulateCollection(TypeToConvert, ref reader, ref state); } state.Current.ReturnValue = returnValue; } } protected internal override bool OnWriteResume(Utf8JsonWriter writer, TCollection value, JsonSerializerOptions options, ref WriteStack state) { IDictionaryEnumerator enumerator; if (state.Current.CollectionEnumerator == null) { enumerator = value.GetEnumerator(); if (!enumerator.MoveNext()) { return true; } } else { enumerator = (IDictionaryEnumerator)state.Current.CollectionEnumerator; } JsonConverter<object?> converter = GetValueConverter(ref state); do { if (ShouldFlush(writer, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } if (state.Current.PropertyState < StackFramePropertyState.Name) { state.Current.PropertyState = StackFramePropertyState.Name; if (enumerator.Key is string key) { key = GetKeyName(key, ref state, options); writer.WritePropertyName(key); } else { ThrowHelper.ThrowJsonException_DeserializeUnableToConvertValue(state.Current.DeclaredJsonPropertyInfo!.RuntimePropertyType!); } } object? element = enumerator.Value; if (!converter.TryWrite(writer, element, options, ref state)) { state.Current.CollectionEnumerator = enumerator; return false; } state.Current.EndDictionaryElement(); } while (enumerator.MoveNext()); return true; } internal override Type RuntimeType { get { if (TypeToConvert.IsAbstract || TypeToConvert.IsInterface) { return typeof(Dictionary<string, object>); } return TypeToConvert; } } } }
36.172131
149
0.557897
[ "MIT" ]
06needhamt/runtime
src/libraries/System.Text.Json/src/System/Text/Json/Serialization/Converters/Collection/IDictionaryConverter.cs
4,415
C#
using UnityEngine; using UnityEngine.UI; using Mods; using SquadBuilderNS; using Editions; public partial class MainMenu : MonoBehaviour { public GameObject RosterBuilderPrefab; public GameObject UpgradeLinePrefab; public GameObject CurrentPanel; public string PreviousPanelName; private void SetCurrentPanel() { CurrentPanel = GameObject.Find("UI/Panels/MainMenuPanel"); } public void ChangePanel(GameObject panel) { ChangePanel(panel.name); } public void ChangePanel(string panelName) { PreviousPanelName = CurrentPanel.name; if (Edition.Current.IsSquadBuilderLocked) { if (panelName == "SquadronOptionsPanel") { if (CurrentPanel.name == "SquadBuilderPanel") { Messages.ShowError("This part of squad builder is disabled"); return; } else { panelName = "SelectFactionPanel"; } } } CurrentPanel.SetActive(false); GameObject panel = GameObject.Find("UI/Panels").transform.Find(panelName).gameObject; InitializePanelContent(panelName, CurrentPanel.name); panel.SetActive(true); CurrentPanel = panel; } private void InitializePanelContent(string panelName, string previousPanelName) { switch (panelName) { case "MainMenuPanel": ClearBatchAiSquadsTestingMode(); break; case "OptionsPanel": OptionsUI.Instance.InitializeOptionsPanel(); break; case "StatsPanel": StatsUI.Instance.InitializeStatsPanel(); break; case "ModsPanel": ModsManager.InitializePanel(); break; case "CreditsPanel": CreditsUI.InitializePanel(); break; case "BrowseRoomsPanel": BrowseMatches(); break; case "SelectFactionPanel": Global.SquadBuilder.CurrentSquad.ClearAll(); Global.SquadBuilder.View.ShowFactionsImages(); break; case "SquadBuilderPanel": Global.SquadBuilder.View.ShowShipsAndUpgrades(); Global.SquadBuilder.View.UpdateNextButton(); break; case "SelectShipPanel": Global.SquadBuilder.View.ShowShipsFilteredByFaction(); break; case "SelectPilotPanel": Global.SquadBuilder.View.ShowPilotsFilteredByShipAndFaction(); break; case "ShipSlotsPanel": Global.SquadBuilder.View.ShowPilotWithSlots(); break; case "SelectUpgradePanel": Global.SquadBuilder.View.ShowUpgradesList(); break; case "BrowseSavedSquadsPanel": Global.SquadBuilder.View.BrowseSavedSquads(); break; case "BrowseCampaignMissionsPanel": Global.SquadBuilder.View.BrowseCampaignMissions(); break; case "SaveSquadronPanel": Global.SquadBuilder.View.PrepareSaveSquadronPanel(); break; case "AvatarsPanel": InitializePlayerCustomization(); break; case "EditionPanel": ShowActiveEdition(Options.Edition); break; case "ShipInfoPanel": Global.SquadBuilder.View.ShowShipInformation(); break; case "SkinsPanel": Global.SquadBuilder.View.ShowSkinsPanel(); break; case "ChosenObstaclesPanel": Global.SquadBuilder.View.ShowChosenObstaclesPanel(); break; case "BrowseObstaclesPanel": Global.SquadBuilder.View.ShowBrowseObstaclesPanel(); break; case "BrowsePopularSquadsPanel": if (previousPanelName == "SquadOptionsPanel") PopularSquads.LastChosenFaction = "All"; PopularSquads.LoadPopularSquads(); break; case "BrowsePopularSquadsVariantsPanel": PopularSquads.LoadPopularSquadsVariants(); break; case "BrowseAvatarsPanel": AvatarsManager.LoadAvatars(Faction.None); break; } } private void ShowNewVersionIsAvailable(string newVersion, string downloadUrl) { GameObject mainMenuPanel = GameObject.Find("UI/Panels").transform.Find("MainMenuPanel").gameObject; if (!mainMenuPanel.activeSelf) return; GameObject panel = GameObject.Find("UI/Panels").transform.Find("MainMenuPanel").Find("NewVersionIsAvailable").gameObject; panel.transform.Find("Text").GetComponent<Text>().text = "New version\nis available!\n\n" + newVersion; panel.transform.position = new Vector2(Screen.width - 20, 20); NewVersionUrl = downloadUrl; panel.SetActive(true); } private void ShowSupportOnPatreon(int support) { //Don't show if new version is available if (Global.LatestVersionInt <= Global.CurrentVersionInt) { GameObject mainMenuPanel = GameObject.Find("UI/Panels").transform.Find("MainMenuPanel").gameObject; if (!mainMenuPanel.activeSelf) return; GameObject panel = GameObject.Find("UI/Panels").transform.Find("MainMenuPanel").Find("SupportOnPatreon").gameObject; panel.transform.Find("Text").GetComponent<Text>().text = $"\"Rules 2.5\" and new expansions are coming! If you want\nto see them in Fly Casual -\nsupport me on patreon\n{support} / 200"; panel.transform.position = new Vector2(Screen.width - 20, 20); panel.SetActive(true); } } public void ChangeEditionIsClicked(GameObject editionGO) { ShowActiveEdition(editionGO.name); SetEdition(editionGO.name); } private void ShowActiveEdition(string editionName) { foreach (Transform panelTransform in GameObject.Find("UI/Panels/EditionPanel/Content").gameObject.transform) { Image backgroundImage = panelTransform.GetComponent<Image>(); if (backgroundImage != null) backgroundImage.enabled = false; } GameObject.Find("UI/Panels/EditionPanel/Content/" + editionName).GetComponent<Image>().enabled = true; } public static void SetEdition(string editionName) { Options.Edition = editionName; Options.ChangeParameterValue("Edition", editionName); switch (editionName) { /*case "FirstEdition": new FirstEdition(); break;*/ case "SecondEdition": new SecondEdition(); break; default: break; } } public void PreviousPanel() { CurrentMainMenu.ChangePanel(CurrentMainMenu.PreviousPanelName); } public void GameModeDecisionPanel() { MainMenu.CurrentMainMenu.ChangePanel("GameModeDecisionPanel"); } public void OpenPatreon() { Application.OpenURL("https://www.patreon.com/Sandrem"); } public void SetFaction(string factionChar) { PopularSquads.SetFaction(factionChar); } public void SetFactionForAvatars(string factionChar) { AvatarsManager.LoadAvatars(factionChar); } }
33.823789
198
0.589476
[ "MIT" ]
sampson-matt/FlyCasual
Assets/Scripts/MainMenu/View/MainMenu.cs
7,680
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; using ILCompiler.DependencyAnalysis.ReadyToRun; using Internal.JitInterface; using Internal.TypeSystem; namespace ILCompiler.DependencyAnalysis { public enum ReadyToRunHelperId { Invalid, NewHelper, NewArr1, IsInstanceOf, CastClass, GetNonGCStaticBase, GetGCStaticBase, GetThreadStaticBase, GetThreadNonGcStaticBase, CctorTrigger, //// The following helpers are used for generic lookups only TypeHandle, DeclaringTypeHandle, MethodHandle, FieldHandle, MethodDictionary, TypeDictionary, MethodEntry, VirtualDispatchCell, } public sealed class ReadyToRunSymbolNodeFactory { private readonly ReadyToRunCodegenNodeFactory _codegenNodeFactory; public ReadyToRunSymbolNodeFactory(ReadyToRunCodegenNodeFactory codegenNodeFactory) { _codegenNodeFactory = codegenNodeFactory; CreateNodeCaches(); } private void CreateNodeCaches() { _importStrings = new NodeCache<ModuleTokenAndSignatureContext, ISymbolNode>(key => { return new StringImport(_codegenNodeFactory.StringImports, key.ModuleToken, key.SignatureContext); }); _r2rHelpers = new NodeCache<ReadyToRunHelperKey, ISymbolNode>(CreateReadyToRunHelper); _fieldAddressCache = new NodeCache<FieldAndSignatureContext, ISymbolNode>(key => { return new DelayLoadHelperImport( _codegenNodeFactory, _codegenNodeFactory.HelperImports, ILCompiler.ReadyToRunHelper.DelayLoad_Helper, new FieldFixupSignature(ReadyToRunFixupKind.READYTORUN_FIXUP_FieldAddress, key.Field, key.SignatureContext) ); }); _fieldOffsetCache = new NodeCache<FieldAndSignatureContext, ISymbolNode>(key => { return new PrecodeHelperImport( _codegenNodeFactory, new FieldFixupSignature(ReadyToRunFixupKind.READYTORUN_FIXUP_FieldOffset, key.Field, key.SignatureContext) ); }); _fieldBaseOffsetCache = new NodeCache<TypeAndSignatureContext, ISymbolNode>(key => { return new PrecodeHelperImport( _codegenNodeFactory, _codegenNodeFactory.TypeSignature(ReadyToRunFixupKind.READYTORUN_FIXUP_FieldBaseOffset, key.Type, key.SignatureContext) ); }); _interfaceDispatchCells = new NodeCache<MethodAndCallSite, ISymbolNode>(cellKey => { return new DelayLoadHelperMethodImport( _codegenNodeFactory, _codegenNodeFactory.DispatchImports, ILCompiler.ReadyToRunHelper.DelayLoad_MethodCall, cellKey.Method, useVirtualCall: true, useInstantiatingStub: false, _codegenNodeFactory.MethodSignature(ReadyToRunFixupKind.READYTORUN_FIXUP_VirtualEntry, cellKey.Method, cellKey.IsUnboxingStub, isInstantiatingStub: false, cellKey.SignatureContext), cellKey.SignatureContext, cellKey.CallSite); }); _delegateCtors = new NodeCache<TypeAndMethod, ISymbolNode>(ctorKey => { SignatureContext signatureContext = ctorKey.SignatureContext; IMethodNode targetMethodNode = _codegenNodeFactory.MethodEntrypoint( ctorKey.Method, isUnboxingStub: false, isInstantiatingStub: false, isPrecodeImportRequired: false, signatureContext: signatureContext); return new DelayLoadHelperImport( _codegenNodeFactory, _codegenNodeFactory.HelperImports, ILCompiler.ReadyToRunHelper.DelayLoad_Helper, new DelegateCtorSignature(ctorKey.Type, targetMethodNode, ctorKey.Method.Token, signatureContext)); }); _genericLookupHelpers = new NodeCache<GenericLookupKey, ISymbolNode>(key => { return new DelayLoadHelperImport( _codegenNodeFactory, _codegenNodeFactory.HelperImports, ILCompiler.ReadyToRunHelper.DelayLoad_Helper, new GenericLookupSignature( key.LookupKind, key.FixupKind, key.TypeArgument, key.MethodArgument, key.FieldArgument, key.MethodContext, key.SignatureContext)); }); _indirectPInvokeTargetNodes = new NodeCache<IndirectPInvokeTargetKey, ISymbolNode>(key => { return new PrecodeHelperImport( _codegenNodeFactory, _codegenNodeFactory.MethodSignature( ReadyToRunFixupKind.READYTORUN_FIXUP_IndirectPInvokeTarget, key.MethodWithToken, signatureContext: key.SignatureContext, isUnboxingStub: false, isInstantiatingStub: false)); }); } private struct ModuleTokenAndSignatureContext : IEquatable<ModuleTokenAndSignatureContext> { public readonly ModuleToken ModuleToken; public readonly SignatureContext SignatureContext; public ModuleTokenAndSignatureContext(ModuleToken moduleToken, SignatureContext signatureContext) { ModuleToken = moduleToken; SignatureContext = signatureContext; } public bool Equals(ModuleTokenAndSignatureContext other) { return ModuleToken.Equals(other.ModuleToken) && SignatureContext.Equals(other.SignatureContext); } public override bool Equals(object obj) { return obj is ModuleTokenAndSignatureContext other && Equals(other); } public override int GetHashCode() { return ModuleToken.GetHashCode() ^ (SignatureContext.GetHashCode() * 31); } } private NodeCache<ModuleTokenAndSignatureContext, ISymbolNode> _importStrings; public ISymbolNode StringLiteral(ModuleToken moduleToken, SignatureContext signatureContext) { return _importStrings.GetOrAdd(new ModuleTokenAndSignatureContext(moduleToken, signatureContext)); } private struct ReadyToRunHelperKey { public readonly ReadyToRunHelperId Id; public readonly object Target; public readonly SignatureContext SignatureContext; public ReadyToRunHelperKey(ReadyToRunHelperId id, object target, SignatureContext signatureContext) { Id = id; Target = target; SignatureContext = signatureContext; } public bool Equals(ReadyToRunHelperKey other) { return Id == other.Id && Target.Equals(other.Target) && SignatureContext.Equals(other.SignatureContext); } public override bool Equals(object obj) { return obj is ReadyToRunHelperKey other && Equals(other); } public override int GetHashCode() { return Id.GetHashCode() ^ (Target.GetHashCode() * 23) ^ (SignatureContext.GetHashCode() * 31); } } private NodeCache<ReadyToRunHelperKey, ISymbolNode> _r2rHelpers; private ISymbolNode CreateReadyToRunHelper(ReadyToRunHelperKey key) { switch (key.Id) { case ReadyToRunHelperId.NewHelper: return CreateNewHelper((TypeDesc)key.Target, key.SignatureContext); case ReadyToRunHelperId.NewArr1: return CreateNewArrayHelper((ArrayType)key.Target, key.SignatureContext); case ReadyToRunHelperId.GetGCStaticBase: return CreateGCStaticBaseHelper((TypeDesc)key.Target, key.SignatureContext); case ReadyToRunHelperId.GetNonGCStaticBase: return CreateNonGCStaticBaseHelper((TypeDesc)key.Target, key.SignatureContext); case ReadyToRunHelperId.GetThreadStaticBase: return CreateThreadGcStaticBaseHelper((TypeDesc)key.Target, key.SignatureContext); case ReadyToRunHelperId.GetThreadNonGcStaticBase: return CreateThreadNonGcStaticBaseHelper((TypeDesc)key.Target, key.SignatureContext); case ReadyToRunHelperId.IsInstanceOf: return CreateIsInstanceOfHelper((TypeDesc)key.Target, key.SignatureContext); case ReadyToRunHelperId.CastClass: return CreateCastClassHelper((TypeDesc)key.Target, key.SignatureContext); case ReadyToRunHelperId.TypeHandle: return CreateTypeHandleHelper((TypeDesc)key.Target, key.SignatureContext); case ReadyToRunHelperId.MethodHandle: return CreateMethodHandleHelper((MethodWithToken)key.Target, key.SignatureContext); case ReadyToRunHelperId.FieldHandle: return CreateFieldHandleHelper((FieldDesc)key.Target, key.SignatureContext); case ReadyToRunHelperId.CctorTrigger: return CreateCctorTrigger((TypeDesc)key.Target, key.SignatureContext); case ReadyToRunHelperId.TypeDictionary: return CreateTypeDictionary((TypeDesc)key.Target, key.SignatureContext); case ReadyToRunHelperId.MethodDictionary: return CreateMethodDictionary((MethodWithToken)key.Target, key.SignatureContext); default: throw new NotImplementedException(key.Id.ToString()); } } public ISymbolNode ReadyToRunHelper(ReadyToRunHelperId id, object target, SignatureContext signatureContext) { return _r2rHelpers.GetOrAdd(new ReadyToRunHelperKey(id, target, signatureContext)); } private ISymbolNode CreateNewHelper(TypeDesc type, SignatureContext signatureContext) { return new DelayLoadHelperImport( _codegenNodeFactory, _codegenNodeFactory.HelperImports, ILCompiler.ReadyToRunHelper.DelayLoad_Helper, new NewObjectFixupSignature(type, signatureContext)); } private ISymbolNode CreateNewArrayHelper(ArrayType type, SignatureContext signatureContext) { return new DelayLoadHelperImport( _codegenNodeFactory, _codegenNodeFactory.HelperImports, ILCompiler.ReadyToRunHelper.DelayLoad_Helper, new NewArrayFixupSignature(type, signatureContext)); } private ISymbolNode CreateGCStaticBaseHelper(TypeDesc type, SignatureContext signatureContext) { return new DelayLoadHelperImport( _codegenNodeFactory, _codegenNodeFactory.HelperImports, ILCompiler.ReadyToRunHelper.DelayLoad_Helper, _codegenNodeFactory.TypeSignature(ReadyToRunFixupKind.READYTORUN_FIXUP_StaticBaseGC, type, signatureContext)); } private ISymbolNode CreateNonGCStaticBaseHelper(TypeDesc type, SignatureContext signatureContext) { return new DelayLoadHelperImport( _codegenNodeFactory, _codegenNodeFactory.HelperImports, ILCompiler.ReadyToRunHelper.DelayLoad_Helper, _codegenNodeFactory.TypeSignature(ReadyToRunFixupKind.READYTORUN_FIXUP_StaticBaseNonGC, type, signatureContext)); } private ISymbolNode CreateThreadGcStaticBaseHelper(TypeDesc type, SignatureContext signatureContext) { return new DelayLoadHelperImport( _codegenNodeFactory, _codegenNodeFactory.HelperImports, ILCompiler.ReadyToRunHelper.DelayLoad_Helper, _codegenNodeFactory.TypeSignature(ReadyToRunFixupKind.READYTORUN_FIXUP_ThreadStaticBaseGC, type, signatureContext)); } private ISymbolNode CreateThreadNonGcStaticBaseHelper(TypeDesc type, SignatureContext signatureContext) { return new DelayLoadHelperImport( _codegenNodeFactory, _codegenNodeFactory.HelperImports, ILCompiler.ReadyToRunHelper.DelayLoad_Helper, _codegenNodeFactory.TypeSignature(ReadyToRunFixupKind.READYTORUN_FIXUP_ThreadStaticBaseNonGC, type, signatureContext)); } private ISymbolNode CreateIsInstanceOfHelper(TypeDesc type, SignatureContext signatureContext) { return new DelayLoadHelperImport( _codegenNodeFactory, _codegenNodeFactory.HelperImports, ILCompiler.ReadyToRunHelper.DelayLoad_Helper, _codegenNodeFactory.TypeSignature(ReadyToRunFixupKind.READYTORUN_FIXUP_IsInstanceOf, type, signatureContext)); } private ISymbolNode CreateCastClassHelper(TypeDesc type, SignatureContext signatureContext) { return new DelayLoadHelperImport( _codegenNodeFactory, _codegenNodeFactory.HelperImports, ILCompiler.ReadyToRunHelper.DelayLoad_Helper_Obj, _codegenNodeFactory.TypeSignature(ReadyToRunFixupKind.READYTORUN_FIXUP_ChkCast, type, signatureContext)); } private ISymbolNode CreateTypeHandleHelper(TypeDesc type, SignatureContext signatureContext) { return new PrecodeHelperImport( _codegenNodeFactory, _codegenNodeFactory.TypeSignature(ReadyToRunFixupKind.READYTORUN_FIXUP_TypeHandle, type, signatureContext)); } private ISymbolNode CreateMethodHandleHelper(MethodWithToken method, SignatureContext signatureContext) { bool useInstantiatingStub = method.Method.GetCanonMethodTarget(CanonicalFormKind.Specific) != method.Method; return new PrecodeHelperImport( _codegenNodeFactory, _codegenNodeFactory.MethodSignature( ReadyToRunFixupKind.READYTORUN_FIXUP_MethodHandle, method, isUnboxingStub: false, isInstantiatingStub: useInstantiatingStub, signatureContext)); } private ISymbolNode CreateFieldHandleHelper(FieldDesc field, SignatureContext signatureContext) { return new PrecodeHelperImport( _codegenNodeFactory, new FieldFixupSignature(ReadyToRunFixupKind.READYTORUN_FIXUP_FieldHandle, field, signatureContext)); } private ISymbolNode CreateCctorTrigger(TypeDesc type, SignatureContext signatureContext) { return new DelayLoadHelperImport( _codegenNodeFactory, _codegenNodeFactory.HelperImports, ILCompiler.ReadyToRunHelper.DelayLoad_Helper, _codegenNodeFactory.TypeSignature(ReadyToRunFixupKind.READYTORUN_FIXUP_CctorTrigger, type, signatureContext)); } private ISymbolNode CreateTypeDictionary(TypeDesc type, SignatureContext signatureContext) { return new PrecodeHelperImport( _codegenNodeFactory, _codegenNodeFactory.TypeSignature(ReadyToRunFixupKind.READYTORUN_FIXUP_TypeDictionary, type, signatureContext) ); } private ISymbolNode CreateMethodDictionary(MethodWithToken method, SignatureContext signatureContext) { return new PrecodeHelperImport( _codegenNodeFactory, _codegenNodeFactory.MethodSignature( ReadyToRunFixupKind.READYTORUN_FIXUP_MethodDictionary, method, isUnboxingStub: false, isInstantiatingStub: true, signatureContext)); } private struct FieldAndSignatureContext : IEquatable<FieldAndSignatureContext> { public readonly FieldDesc Field; public readonly SignatureContext SignatureContext; public FieldAndSignatureContext(FieldDesc fieldDesc, SignatureContext signatureContext) { Field = fieldDesc; SignatureContext = signatureContext; } public bool Equals(FieldAndSignatureContext other) { return Field.Equals(other.Field) && SignatureContext.Equals(other.SignatureContext); } public override bool Equals(object obj) { return obj is FieldAndSignatureContext other && Equals(other); } public override int GetHashCode() { return Field.GetHashCode() ^ (SignatureContext.GetHashCode() * 31); } } private NodeCache<FieldAndSignatureContext, ISymbolNode> _fieldAddressCache; public ISymbolNode FieldAddress(FieldDesc fieldDesc, SignatureContext signatureContext) { return _fieldAddressCache.GetOrAdd(new FieldAndSignatureContext(fieldDesc, signatureContext)); } private NodeCache<FieldAndSignatureContext, ISymbolNode> _fieldOffsetCache; public ISymbolNode FieldOffset(FieldDesc fieldDesc, SignatureContext signatureContext) { return _fieldOffsetCache.GetOrAdd(new FieldAndSignatureContext(fieldDesc, signatureContext)); } private struct TypeAndSignatureContext : IEquatable<TypeAndSignatureContext> { public readonly TypeDesc Type; public readonly SignatureContext SignatureContext; public TypeAndSignatureContext(TypeDesc typeDesc, SignatureContext signatureContext) { Type = typeDesc; SignatureContext = signatureContext; } public bool Equals(TypeAndSignatureContext other) { return Type.Equals(other.Type) && SignatureContext.Equals(other.SignatureContext); } public override bool Equals(object obj) { return obj is FieldAndSignatureContext other && Equals(other); } public override int GetHashCode() { return Type.GetHashCode() ^ (SignatureContext.GetHashCode() * 31); } } private NodeCache<TypeAndSignatureContext, ISymbolNode> _fieldBaseOffsetCache; public ISymbolNode FieldBaseOffset(TypeDesc typeDesc, SignatureContext signatureContext) { return _fieldBaseOffsetCache.GetOrAdd(new TypeAndSignatureContext(typeDesc, signatureContext)); } private NodeCache<MethodAndCallSite, ISymbolNode> _interfaceDispatchCells = new NodeCache<MethodAndCallSite, ISymbolNode>(); public ISymbolNode InterfaceDispatchCell(MethodWithToken method, SignatureContext signatureContext, bool isUnboxingStub, string callSite) { MethodAndCallSite cellKey = new MethodAndCallSite(method, isUnboxingStub, callSite, signatureContext); return _interfaceDispatchCells.GetOrAdd(cellKey); } private NodeCache<TypeAndMethod, ISymbolNode> _delegateCtors = new NodeCache<TypeAndMethod, ISymbolNode>(); public ISymbolNode DelegateCtor(TypeDesc delegateType, MethodWithToken method, SignatureContext signatureContext) { TypeAndMethod ctorKey = new TypeAndMethod( delegateType, method, isUnboxingStub: false, isInstantiatingStub: false, isPrecodeImportRequired: false, signatureContext); return _delegateCtors.GetOrAdd(ctorKey); } struct MethodAndCallSite : IEquatable<MethodAndCallSite> { public readonly MethodWithToken Method; public readonly bool IsUnboxingStub; public readonly string CallSite; public readonly SignatureContext SignatureContext; public MethodAndCallSite(MethodWithToken method, bool isUnboxingStub, string callSite, SignatureContext signatureContext) { CallSite = callSite; IsUnboxingStub = isUnboxingStub; Method = method; SignatureContext = signatureContext; } public bool Equals(MethodAndCallSite other) { return CallSite == other.CallSite && Method.Equals(other.Method) && IsUnboxingStub == other.IsUnboxingStub && SignatureContext.Equals(other.SignatureContext); } public override bool Equals(object obj) { return obj is MethodAndCallSite other && Equals(other); } public override int GetHashCode() { return (CallSite != null ? CallSite.GetHashCode() : 0) ^ unchecked(31 * Method.GetHashCode()) ^ (IsUnboxingStub ? -0x80000000 : 0) ^ (23 * SignatureContext.GetHashCode()); } } private struct GenericLookupKey : IEquatable<GenericLookupKey> { public readonly CORINFO_RUNTIME_LOOKUP_KIND LookupKind; public readonly ReadyToRunFixupKind FixupKind; public readonly TypeDesc TypeArgument; public readonly MethodWithToken MethodArgument; public readonly FieldDesc FieldArgument; public readonly GenericContext MethodContext; public readonly SignatureContext SignatureContext; public GenericLookupKey( CORINFO_RUNTIME_LOOKUP_KIND lookupKind, ReadyToRunFixupKind fixupKind, TypeDesc typeArgument, MethodWithToken methodArgument, FieldDesc fieldArgument, GenericContext methodContext, SignatureContext signatureContext) { LookupKind = lookupKind; FixupKind = fixupKind; TypeArgument = typeArgument; MethodArgument = methodArgument; FieldArgument = fieldArgument; MethodContext = methodContext; SignatureContext = signatureContext; } public bool Equals(GenericLookupKey other) { return LookupKind == other.LookupKind && FixupKind == other.FixupKind && RuntimeDeterminedTypeHelper.Equals(TypeArgument, other.TypeArgument) && RuntimeDeterminedTypeHelper.Equals(MethodArgument?.Method ?? null, other.MethodArgument?.Method ?? null) && RuntimeDeterminedTypeHelper.Equals(FieldArgument, other.FieldArgument) && MethodContext.Equals(other.MethodContext); } public override bool Equals(object obj) { return obj is GenericLookupKey other && Equals(other); } public override int GetHashCode() { return unchecked(((int)LookupKind << 24) + (int)FixupKind + (TypeArgument != null ? 31 * RuntimeDeterminedTypeHelper.GetHashCode(TypeArgument) : 0) + (MethodArgument != null ? 31 * RuntimeDeterminedTypeHelper.GetHashCode(MethodArgument.Method) : 0) + (FieldArgument != null ? 31 * RuntimeDeterminedTypeHelper.GetHashCode(FieldArgument) : 0) + MethodContext.GetHashCode()); } } private NodeCache<GenericLookupKey, ISymbolNode> _genericLookupHelpers; public ISymbolNode GenericLookupHelper( CORINFO_RUNTIME_LOOKUP_KIND runtimeLookupKind, ReadyToRunHelperId helperId, object helperArgument, GenericContext methodContext, SignatureContext signatureContext) { switch (helperId) { case ReadyToRunHelperId.TypeHandle: return GenericLookupTypeHelper( runtimeLookupKind, ReadyToRunFixupKind.READYTORUN_FIXUP_TypeHandle, helperArgument, methodContext, signatureContext); case ReadyToRunHelperId.MethodHandle: return GenericLookupMethodHelper( runtimeLookupKind, ReadyToRunFixupKind.READYTORUN_FIXUP_MethodHandle, (MethodWithToken)helperArgument, methodContext, signatureContext); case ReadyToRunHelperId.MethodEntry: return GenericLookupMethodHelper( runtimeLookupKind, ReadyToRunFixupKind.READYTORUN_FIXUP_MethodEntry, (MethodWithToken)helperArgument, methodContext, signatureContext); case ReadyToRunHelperId.MethodDictionary: return GenericLookupMethodHelper( runtimeLookupKind, ReadyToRunFixupKind.READYTORUN_FIXUP_MethodHandle, (MethodWithToken)helperArgument, methodContext, signatureContext); case ReadyToRunHelperId.TypeDictionary: return GenericLookupTypeHelper( runtimeLookupKind, ReadyToRunFixupKind.READYTORUN_FIXUP_TypeDictionary, (TypeDesc)helperArgument, methodContext, signatureContext); case ReadyToRunHelperId.VirtualDispatchCell: return GenericLookupMethodHelper( runtimeLookupKind, ReadyToRunFixupKind.READYTORUN_FIXUP_VirtualEntry, (MethodWithToken)helperArgument, methodContext, signatureContext); case ReadyToRunHelperId.FieldHandle: return GenericLookupFieldHelper( runtimeLookupKind, ReadyToRunFixupKind.READYTORUN_FIXUP_FieldHandle, (FieldDesc)helperArgument, methodContext, signatureContext); default: throw new NotImplementedException(helperId.ToString()); } } private ISymbolNode GenericLookupTypeHelper( CORINFO_RUNTIME_LOOKUP_KIND runtimeLookupKind, ReadyToRunFixupKind fixupKind, object helperArgument, GenericContext methodContext, SignatureContext signatureContext) { TypeDesc typeArgument; if (helperArgument is MethodWithToken methodWithToken) { typeArgument = methodWithToken.Method.OwningType; } else if (helperArgument is FieldDesc fieldDesc) { typeArgument = fieldDesc.OwningType; } else { typeArgument = (TypeDesc)helperArgument; } GenericLookupKey key = new GenericLookupKey(runtimeLookupKind, fixupKind, typeArgument, methodArgument: null, fieldArgument: null, methodContext, signatureContext); return _genericLookupHelpers.GetOrAdd(key); } private ISymbolNode GenericLookupFieldHelper( CORINFO_RUNTIME_LOOKUP_KIND runtimeLookupKind, ReadyToRunFixupKind fixupKind, FieldDesc fieldArgument, GenericContext methodContext, SignatureContext signatureContext) { GenericLookupKey key = new GenericLookupKey(runtimeLookupKind, fixupKind, typeArgument: null, methodArgument: null, fieldArgument: fieldArgument, methodContext, signatureContext); return _genericLookupHelpers.GetOrAdd(key); } private ISymbolNode GenericLookupMethodHelper( CORINFO_RUNTIME_LOOKUP_KIND runtimeLookupKind, ReadyToRunFixupKind fixupKind, MethodWithToken methodArgument, GenericContext methodContext, SignatureContext signatureContext) { GenericLookupKey key = new GenericLookupKey(runtimeLookupKind, fixupKind, typeArgument: null, methodArgument, fieldArgument: null, methodContext, signatureContext); return _genericLookupHelpers.GetOrAdd(key); } private struct IndirectPInvokeTargetKey : IEquatable<IndirectPInvokeTargetKey> { public readonly MethodWithToken MethodWithToken; public readonly SignatureContext SignatureContext; public IndirectPInvokeTargetKey(MethodWithToken methodWithToken, SignatureContext signatureContext) { MethodWithToken = methodWithToken; SignatureContext = signatureContext; } public bool Equals(IndirectPInvokeTargetKey other) { return MethodWithToken.Equals(other.MethodWithToken) && SignatureContext.Equals(other.SignatureContext); } public override bool Equals(object obj) { return obj is IndirectPInvokeTargetKey other && Equals(other); } public override int GetHashCode() { return MethodWithToken.GetHashCode() ^ (SignatureContext.GetHashCode() * 31); } } private NodeCache<IndirectPInvokeTargetKey, ISymbolNode> _indirectPInvokeTargetNodes = new NodeCache<IndirectPInvokeTargetKey, ISymbolNode>(); public ISymbolNode GetIndirectPInvokeTargetNode(MethodWithToken methodWithToken, SignatureContext signatureContext) { return _indirectPInvokeTargetNodes.GetOrAdd(new IndirectPInvokeTargetKey(methodWithToken, signatureContext)); } } }
42.254032
191
0.615739
[ "MIT" ]
AndyAyersMS/coreclr
src/tools/crossgen2/ILCompiler.ReadyToRun/Compiler/DependencyAnalysis/ReadyToRunSymbolNodeFactory.cs
31,439
C#
using CinemaRolfoBot.Utils; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace CinemaRolfoBot.Model.DB { public class Showing { [Key] [Required] public string Id { get; set; } [Required] public DateTime DateAndTime { get => _DateAndTime; set { _DateAndTime = value.SetKindUtc(); } } [NotMapped] private DateTime _DateAndTime; public string Screen { get; set; } //Foreign key for Film [Required] public string FilmId { get; set; } public Film Standard { get; set; } public static Showing Where { get; internal set; } public override bool Equals(object? obj) { if (obj == null || obj.GetType() != typeof(Showing)) return base.Equals(obj); Showing typedObj = (Showing)obj; return (this.Id == typedObj.Id && this.DateAndTime == typedObj.DateAndTime && this.Screen == typedObj.Screen); } public Showing() { } public Showing(Json.Time timeJson) { this.Id = timeJson.session_id; this.DateAndTime = timeJson.date; this.Screen = timeJson.screen_number; } } }
25.259259
64
0.550587
[ "MIT" ]
r0lf0/NET-cinema-bologna-bot
CinemaRolfoBot/CinemaRolfoBot/Model/DB/Showing.cs
1,366
C#
using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Json; using System.Text; using System.Text.Json; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace CiscoEndpointCertificateDeployer { public class TcDeployer: BaseDeployer { private string? csrfToken { get; set; } public TcDeployer(Endpoint endpoint): base(endpoint) { } protected override bool isHttpAndHttpsConfigurationSeparate => true; /// <exception cref="CiscoException">if authentication fails</exception> public override async Task logIn() { if (isDisposed) { throw new ObjectDisposedException($"{nameof(TcDeployer)} instance has already been disposed and cannot be reused."); } FormUrlEncodedContent requestBody = new((IEnumerable<KeyValuePair<string?, string?>>) new Dictionary<string, string> { { "username", endpoint.username }, { "password", endpoint.password } }); using HttpResponseMessage response = await httpClient.PostAsync(new UriBuilder(endpointBaseUri) { Path = "/web/signin/open" }.Uri, requestBody); JsonElement result = default; if (response.IsSuccessStatusCode && ((await response.Content.ReadFromJsonAsync<JsonDocument>())?.RootElement.TryGetProperty("result", out result) ?? false) && result.ValueKind == JsonValueKind.String && result.GetString() == "ok") { //logged in, cookie has been set using HttpResponseMessage csrfResponse = await httpClient.GetAsync(new UriBuilder(endpointBaseUri) { Path = "/web/security/cert" }.Uri); string csrfResponseBody = await csrfResponse.Content.ReadAsStringAsync(); Match csrfMatch = Regex.Match(csrfResponseBody, @"\bvega\.csrfToken\s*=\s*['""](?<csrfToken>\w+)['""]"); csrfToken = csrfMatch.Success ? csrfMatch.Groups["csrfToken"].Value : null; loggedIn = true; Console.WriteLine("Logged in with web session."); } else { throw new CiscoException("Authentication to TC7 endpoint failed"); } } /// <exception cref="CiscoException">if upload does not result in a 303 to the certificate list page</exception> public override async Task uploadCertificate(string pemCertificate) { ensureLoggedInAndNotDisposed(); HttpContent pemContent; pemContent = new StringContent(pemCertificate, Encoding.UTF8, "application/octet-stream"); // pemContent = new(Encoding.UTF8.GetBytes(pemCertificate)); // pemContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); MultipartFormDataContent requestBody = new() { { pemContent, "certificate", "ciscocert.pem" }, { new ByteArrayContent(Array.Empty<byte>()), "privkey", string.Empty }, { new ByteArrayContent(Array.Empty<byte>()), "passphrase" }, { new StringContent(csrfToken ?? "no token", Encoding.UTF8), "token" } }; using HttpResponseMessage response = await httpClient.PostAsync(new UriBuilder(endpointBaseUri) { Path = "/web/security/certAdd" }.Uri, requestBody); if (response.StatusCode == HttpStatusCode.SeeOther) { Console.WriteLine("Uploaded certificate"); } else { throw new CiscoException("Failed to upload certificate"); } } public override async Task activateCertificate(string certificateFingerprintSha1, ServicePurpose servicePurpose) { ensureLoggedInAndNotDisposed(); Dictionary<string, string?> requestBody = new() { { "id", servicePurpose.vegaIdTc() }, { "name", servicePurpose.vegaNameTc() }, { "success", "success" }, { "certificate", certificateFingerprintSha1.ToUpperInvariant() } }; using HttpResponseMessage response = await httpClient.PutAsJsonAsync(new UriBuilder(endpointBaseUri) { Path = "/web/api/certificates/service/https_server" }.Uri, requestBody); if (response.IsSuccessStatusCode) { Console.WriteLine($"Activated certificate {certificateFingerprintSha1}"); } else { throw new CiscoException("Failed to activate new certificate"); } } } }
48.103093
188
0.62066
[ "Apache-2.0" ]
Aldaviva/CiscoEndpointCertificateDeployer
CiscoEndpointCertificateDeployer/TcDeployer.cs
4,668
C#
using System; using System.Windows; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Effects; namespace MaterialDesignThemes.Wpf { public enum ShadowDepth { Depth0, Depth1, Depth2, Depth3, Depth4, Depth5 } [Flags] public enum ShadowEdges { None = 0, Left = 1, Top = 2, Right = 4, Bottom = 8, All = Left | Top | Right | Bottom } internal class ShadowLocalInfo { public ShadowLocalInfo(double standardOpacity) { StandardOpacity = standardOpacity; } public double StandardOpacity { get; } } public static class ShadowAssist { public static readonly DependencyProperty ShadowDepthProperty = DependencyProperty.RegisterAttached( "ShadowDepth", typeof(ShadowDepth), typeof(ShadowAssist), new FrameworkPropertyMetadata(default(ShadowDepth), FrameworkPropertyMetadataOptions.AffectsRender)); public static void SetShadowDepth(DependencyObject element, ShadowDepth value) { element.SetValue(ShadowDepthProperty, value); } public static ShadowDepth GetShadowDepth(DependencyObject element) { return (ShadowDepth)element.GetValue(ShadowDepthProperty); } private static readonly DependencyPropertyKey LocalInfoPropertyKey = DependencyProperty.RegisterAttachedReadOnly( "LocalInfo", typeof(ShadowLocalInfo), typeof(ShadowAssist), new PropertyMetadata(default(ShadowLocalInfo))); private static void SetLocalInfo(DependencyObject element, ShadowLocalInfo value) { element.SetValue(LocalInfoPropertyKey, value); } private static ShadowLocalInfo GetLocalInfo(DependencyObject element) { return (ShadowLocalInfo)element.GetValue(LocalInfoPropertyKey.DependencyProperty); } public static readonly DependencyProperty DarkenProperty = DependencyProperty.RegisterAttached( "Darken", typeof(bool), typeof(ShadowAssist), new FrameworkPropertyMetadata(default(bool), FrameworkPropertyMetadataOptions.AffectsRender, DarkenPropertyChangedCallback)); private static void DarkenPropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs) { var uiElement = dependencyObject as UIElement; var dropShadowEffect = uiElement?.Effect as DropShadowEffect; if (dropShadowEffect == null) return; if ((bool)dependencyPropertyChangedEventArgs.NewValue) { SetLocalInfo(dependencyObject, new ShadowLocalInfo(dropShadowEffect.Opacity)); var doubleAnimation = new DoubleAnimation(1, new Duration(TimeSpan.FromMilliseconds(350))) { FillBehavior = FillBehavior.HoldEnd }; dropShadowEffect.BeginAnimation(DropShadowEffect.OpacityProperty, doubleAnimation); } else { var shadowLocalInfo = GetLocalInfo(dependencyObject); if (shadowLocalInfo == null) return; var doubleAnimation = new DoubleAnimation(shadowLocalInfo.StandardOpacity, new Duration(TimeSpan.FromMilliseconds(350))) { FillBehavior = FillBehavior.HoldEnd }; dropShadowEffect.BeginAnimation(DropShadowEffect.OpacityProperty, doubleAnimation); } } public static void SetDarken(DependencyObject element, bool value) { element.SetValue(DarkenProperty, value); } public static bool GetDarken(DependencyObject element) { return (bool)element.GetValue(DarkenProperty); } public static readonly DependencyProperty CacheModeProperty = DependencyProperty.RegisterAttached( "CacheMode", typeof(CacheMode), typeof(ShadowAssist), new FrameworkPropertyMetadata(new BitmapCache { EnableClearType = true, SnapsToDevicePixels = true }, FrameworkPropertyMetadataOptions.Inherits)); public static void SetCacheMode(DependencyObject element, CacheMode value) { element.SetValue(CacheModeProperty, value); } public static CacheMode GetCacheMode(DependencyObject element) { return (CacheMode)element.GetValue(CacheModeProperty); } public static readonly DependencyProperty ShadowEdgesProperty = DependencyProperty.RegisterAttached( "ShadowEdges", typeof(ShadowEdges), typeof(ShadowAssist), new PropertyMetadata(ShadowEdges.All)); public static void SetShadowEdges(DependencyObject element, ShadowEdges value) { element.SetValue(ShadowEdgesProperty, value); } public static ShadowEdges GetShadowEdges(DependencyObject element) { return (ShadowEdges)element.GetValue(ShadowEdgesProperty); } } }
37.394161
212
0.670896
[ "MIT" ]
15217711253/MaterialDesignInXamlToolkit
MaterialDesignThemes.Wpf/ShadowAssist.cs
5,123
C#
namespace Shared.Models.Helpers { public class UserResourcePair { public User User { get; set; } public Resource Resource { get; set; } } }
18.777778
46
0.609467
[ "MIT" ]
RogerBestMsft/CoraBot
Shared/Models/Helpers/UserResourcePair.cs
171
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="IResultsOutput.cs" company="www.jameswiseman.com"> // This license governs use of the accompanying software. If you use the software, you // accept this license. If you do not accept the license, do not use the software. // // 1. Definitions // The terms "reproduce," "reproduction," "derivative works," and "distribution" have the // same meaning here as under U.S. copyright law. // A "contribution" is the original software, or any additions or changes to the software. // A "contributor" is any person that distributes its contribution under this license. // "Licensed patents" are a contributor's patent claims that read directly on its contribution. // // 2. Grant of Rights // (A) Copyright Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free copyright license to reproduce its contribution, prepare derivative works of its contribution, and distribute its contribution or any derivative works that you create. // (B) Patent Grant- Subject to the terms of this license, including the license conditions and limitations in section 3, each contributor grants you a non-exclusive, worldwide, royalty-free license under its licensed patents to make, have made, use, sell, offer for sale, import, and/or otherwise dispose of its contribution in the software or derivative works of the contribution in the software. // // 3. Conditions and Limitations // (A) No Trademark License- This license does not grant you rights to use any contributors' name, logo, or trademarks. // (B) If you bring a patent claim against any contributor over patents that you claim are infringed by the software, your patent license from such contributor to the software ends automatically. // (C) If you distribute any portion of the software, you must retain all copyright, patent, trademark, and attribution notices that are present in the software. // (D) If you distribute any portion of the software in source code form, you may do so only under this license by including a complete copy of this license with your distribution. If you distribute any portion of the software in compiled or object code form, you may only do so under a license that complies with this license. // (E) The software is licensed "as-is." You bear the risk of using it. The contributors give no express warranties, guarantees or conditions. You may have additional consumer rights under your local laws which this license cannot change. To the extent permitted under your local laws, the contributors exclude the implied warranties of merchantability, fitness for a particular purpose and non-infringement. // </copyright> // <summary> // Interface for results writing // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace JsGoogleCompile { /// <summary> /// Results Output Interface /// </summary> public interface IResultsOutput { /// <summary> /// Emits warnings. /// </summary> /// <param name="compilerResults">The compiler results.</param> void EmitWarnings(ICompilerResults compilerResults); /// <summary> /// Emits warnings. /// </summary> /// <param name="compilerResults">The compiler results.</param> void EmitErrors(ICompilerResults compilerResults); /// <summary> /// Emits a summary of the results. /// </summary> /// <param name="compilerResults">The compiler results.</param> void EmitSummary(ICompilerResults compilerResults); } }
70.648148
408
0.693578
[ "MIT" ]
jameswiseman76/JsGoogleCompile
JsGoogleCompile/IResultsOutput.cs
3,817
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sums_Of_Subsets { class Program { static void Main(string[] args) { Sums first = new Sums(new List<int> { 3, 10, 5, 17, 8, 7, 4, 4 }, 21); List<int> val = first.find(); Console.WriteLine(string.Join(",",val)); process(); //my random method works the best (Sums.cs) Standard_Sum(); Console.ReadKey(); } static void process() //for Sum { for(int i=0; i < 12; ++i) { List<int> now = generate(); int now2 = ran(); Console.WriteLine($"List is {string.Join(",", now)}"); Console.WriteLine($"p is {now2}"); Sums trial = new Sums(now, now2); DateTime tnow = DateTime.Now; List<int> val4 = trial.find(); //likelyhood of i being in list is very high, hence it is more dependant on how fast can computer spot i in list. if (val4 != null) Console.WriteLine($"subset is {string.Join(",", val4)}"); else if (val4 == null) Console.WriteLine("Not possible"); DateTime tnow2 = DateTime.Now; Console.WriteLine($"time taken is {tnow2.Second - tnow.Second }"); } } static List<int> generate() //for Sum { List<int> to_return = new List<int>(); Random val = new Random(); int length = val.Next(1, 100); while (to_return.Count() < length) { int num = val.Next(1, 100); to_return.Add(num); } return to_return; } static int ran() //for Sum { Random val = new Random(); return val.Next(0, 50); } static void Standard_Sum() { List<int> Standard = new List<int> { 3, 10, 5, 17, 8, 7, 4, 4 }; int val = 21; Sums_Standard norm = new Sums_Standard(Standard, val); norm.find2(); } } }
33.641791
160
0.476486
[ "MIT" ]
sps-lco-2020-21/subset-sum-LimESPS
Sums Of Subsets/Sums Of Subsets/Program.cs
2,256
C#
namespace SharpLearning.Optimization.ParameterSamplers { /// <summary> /// Defines the interface for a parameter samplers. /// </summary> public interface IParameterSampler { /// <summary> /// Returns a sample within in the specified min/max boundaries. /// </summary> /// <param name="min">Minimum bound</param> /// <param name="max">Maximum bound</param> /// <param name="parameterType">Selects the type of parameter. Should the parameter be sampled as discrete values, or as continuous values.</param> /// <returns></returns> double Sample(double min, double max, ParameterType parameterType); } }
39.333333
156
0.627119
[ "Apache-2.0" ]
AwesomeTrading/LeanParameterOptimization
SharpLearning.Optimization/ParameterSamplers/IParameterSampler.cs
710
C#
using System; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Utilities; namespace Org.BouncyCastle.Crypto.Engines { /** * an implementation of the AES (Rijndael)), from FIPS-197. * <p> * For further details see: <a href="http://csrc.nist.gov/encryption/aes/">http://csrc.nist.gov/encryption/aes/</a>. * * This implementation is based on optimizations from Dr. Brian Gladman's paper and C code at * <a href="http://fp.gladman.plus.com/cryptography_technology/rijndael/">http://fp.gladman.plus.com/cryptography_technology/rijndael/</a> * * There are three levels of tradeoff of speed vs memory * Because java has no preprocessor), they are written as three separate classes from which to choose * * The fastest uses 8Kbytes of static tables to precompute round calculations), 4 256 word tables for encryption * and 4 for decryption. * * The middle performance version uses only one 256 word table for each), for a total of 2Kbytes), * adding 12 rotate operations per round to compute the values contained in the other tables from * the contents of the first * * The slowest version uses no static tables at all and computes the values in each round * </p> * <p> * This file contains the fast version with 8Kbytes of static tables for round precomputation * </p> */ public class AesFastEngine : IBlockCipher { // The S box private static readonly byte[] _s = { 99, 124, 119, 123, 242, 107, 111, 197, 48, 1, 103, 43, 254, 215, 171, 118, 202, 130, 201, 125, 250, 89, 71, 240, 173, 212, 162, 175, 156, 164, 114, 192, 183, 253, 147, 38, 54, 63, 247, 204, 52, 165, 229, 241, 113, 216, 49, 21, 4, 199, 35, 195, 24, 150, 5, 154, 7, 18, 128, 226, 235, 39, 178, 117, 9, 131, 44, 26, 27, 110, 90, 160, 82, 59, 214, 179, 41, 227, 47, 132, 83, 209, 0, 237, 32, 252, 177, 91, 106, 203, 190, 57, 74, 76, 88, 207, 208, 239, 170, 251, 67, 77, 51, 133, 69, 249, 2, 127, 80, 60, 159, 168, 81, 163, 64, 143, 146, 157, 56, 245, 188, 182, 218, 33, 16, 255, 243, 210, 205, 12, 19, 236, 95, 151, 68, 23, 196, 167, 126, 61, 100, 93, 25, 115, 96, 129, 79, 220, 34, 42, 144, 136, 70, 238, 184, 20, 222, 94, 11, 219, 224, 50, 58, 10, 73, 6, 36, 92, 194, 211, 172, 98, 145, 149, 228, 121, 231, 200, 55, 109, 141, 213, 78, 169, 108, 86, 244, 234, 101, 122, 174, 8, 186, 120, 37, 46, 28, 166, 180, 198, 232, 221, 116, 31, 75, 189, 139, 138, 112, 62, 181, 102, 72, 3, 246, 14, 97, 53, 87, 185, 134, 193, 29, 158, 225, 248, 152, 17, 105, 217, 142, 148, 155, 30, 135, 233, 206, 85, 40, 223, 140, 161, 137, 13, 191, 230, 66, 104, 65, 153, 45, 15, 176, 84, 187, 22 }; // The inverse S-box private static readonly byte[] _si = { 82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37, 114, 248, 246, 100, 134, 104, 152, 22, 212, 164, 92, 204, 93, 101, 182, 146, 108, 112, 72, 80, 253, 237, 185, 218, 94, 21, 70, 87, 167, 141, 157, 132, 144, 216, 171, 0, 140, 188, 211, 10, 247, 228, 88, 5, 184, 179, 69, 6, 208, 44, 30, 143, 202, 63, 15, 2, 193, 175, 189, 3, 1, 19, 138, 107, 58, 145, 17, 65, 79, 103, 220, 234, 151, 242, 207, 206, 240, 180, 230, 115, 150, 172, 116, 34, 231, 173, 53, 133, 226, 249, 55, 232, 28, 117, 223, 110, 71, 241, 26, 113, 29, 41, 197, 137, 111, 183, 98, 14, 170, 24, 190, 27, 252, 86, 62, 75, 198, 210, 121, 32, 154, 219, 192, 254, 120, 205, 90, 244, 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125 }; // vector used in calculating key schedule (powers of x in GF(256)) private static readonly byte[] _rcon = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5, 0x91 }; // precomputation tables of calculations for rounds private static readonly uint[] _t0 = { 0xa56363c6, 0x847c7cf8, 0x997777ee, 0x8d7b7bf6, 0x0df2f2ff, 0xbd6b6bd6, 0xb16f6fde, 0x54c5c591, 0x50303060, 0x03010102, 0xa96767ce, 0x7d2b2b56, 0x19fefee7, 0x62d7d7b5, 0xe6abab4d, 0x9a7676ec, 0x45caca8f, 0x9d82821f, 0x40c9c989, 0x877d7dfa, 0x15fafaef, 0xeb5959b2, 0xc947478e, 0x0bf0f0fb, 0xecadad41, 0x67d4d4b3, 0xfda2a25f, 0xeaafaf45, 0xbf9c9c23, 0xf7a4a453, 0x967272e4, 0x5bc0c09b, 0xc2b7b775, 0x1cfdfde1, 0xae93933d, 0x6a26264c, 0x5a36366c, 0x413f3f7e, 0x02f7f7f5, 0x4fcccc83, 0x5c343468, 0xf4a5a551, 0x34e5e5d1, 0x08f1f1f9, 0x937171e2, 0x73d8d8ab, 0x53313162, 0x3f15152a, 0x0c040408, 0x52c7c795, 0x65232346, 0x5ec3c39d, 0x28181830, 0xa1969637, 0x0f05050a, 0xb59a9a2f, 0x0907070e, 0x36121224, 0x9b80801b, 0x3de2e2df, 0x26ebebcd, 0x6927274e, 0xcdb2b27f, 0x9f7575ea, 0x1b090912, 0x9e83831d, 0x742c2c58, 0x2e1a1a34, 0x2d1b1b36, 0xb26e6edc, 0xee5a5ab4, 0xfba0a05b, 0xf65252a4, 0x4d3b3b76, 0x61d6d6b7, 0xceb3b37d, 0x7b292952, 0x3ee3e3dd, 0x712f2f5e, 0x97848413, 0xf55353a6, 0x68d1d1b9, 0x00000000, 0x2cededc1, 0x60202040, 0x1ffcfce3, 0xc8b1b179, 0xed5b5bb6, 0xbe6a6ad4, 0x46cbcb8d, 0xd9bebe67, 0x4b393972, 0xde4a4a94, 0xd44c4c98, 0xe85858b0, 0x4acfcf85, 0x6bd0d0bb, 0x2aefefc5, 0xe5aaaa4f, 0x16fbfbed, 0xc5434386, 0xd74d4d9a, 0x55333366, 0x94858511, 0xcf45458a, 0x10f9f9e9, 0x06020204, 0x817f7ffe, 0xf05050a0, 0x443c3c78, 0xba9f9f25, 0xe3a8a84b, 0xf35151a2, 0xfea3a35d, 0xc0404080, 0x8a8f8f05, 0xad92923f, 0xbc9d9d21, 0x48383870, 0x04f5f5f1, 0xdfbcbc63, 0xc1b6b677, 0x75dadaaf, 0x63212142, 0x30101020, 0x1affffe5, 0x0ef3f3fd, 0x6dd2d2bf, 0x4ccdcd81, 0x140c0c18, 0x35131326, 0x2fececc3, 0xe15f5fbe, 0xa2979735, 0xcc444488, 0x3917172e, 0x57c4c493, 0xf2a7a755, 0x827e7efc, 0x473d3d7a, 0xac6464c8, 0xe75d5dba, 0x2b191932, 0x957373e6, 0xa06060c0, 0x98818119, 0xd14f4f9e, 0x7fdcdca3, 0x66222244, 0x7e2a2a54, 0xab90903b, 0x8388880b, 0xca46468c, 0x29eeeec7, 0xd3b8b86b, 0x3c141428, 0x79dedea7, 0xe25e5ebc, 0x1d0b0b16, 0x76dbdbad, 0x3be0e0db, 0x56323264, 0x4e3a3a74, 0x1e0a0a14, 0xdb494992, 0x0a06060c, 0x6c242448, 0xe45c5cb8, 0x5dc2c29f, 0x6ed3d3bd, 0xefacac43, 0xa66262c4, 0xa8919139, 0xa4959531, 0x37e4e4d3, 0x8b7979f2, 0x32e7e7d5, 0x43c8c88b, 0x5937376e, 0xb76d6dda, 0x8c8d8d01, 0x64d5d5b1, 0xd24e4e9c, 0xe0a9a949, 0xb46c6cd8, 0xfa5656ac, 0x07f4f4f3, 0x25eaeacf, 0xaf6565ca, 0x8e7a7af4, 0xe9aeae47, 0x18080810, 0xd5baba6f, 0x887878f0, 0x6f25254a, 0x722e2e5c, 0x241c1c38, 0xf1a6a657, 0xc7b4b473, 0x51c6c697, 0x23e8e8cb, 0x7cdddda1, 0x9c7474e8, 0x211f1f3e, 0xdd4b4b96, 0xdcbdbd61, 0x868b8b0d, 0x858a8a0f, 0x907070e0, 0x423e3e7c, 0xc4b5b571, 0xaa6666cc, 0xd8484890, 0x05030306, 0x01f6f6f7, 0x120e0e1c, 0xa36161c2, 0x5f35356a, 0xf95757ae, 0xd0b9b969, 0x91868617, 0x58c1c199, 0x271d1d3a, 0xb99e9e27, 0x38e1e1d9, 0x13f8f8eb, 0xb398982b, 0x33111122, 0xbb6969d2, 0x70d9d9a9, 0x898e8e07, 0xa7949433, 0xb69b9b2d, 0x221e1e3c, 0x92878715, 0x20e9e9c9, 0x49cece87, 0xff5555aa, 0x78282850, 0x7adfdfa5, 0x8f8c8c03, 0xf8a1a159, 0x80898909, 0x170d0d1a, 0xdabfbf65, 0x31e6e6d7, 0xc6424284, 0xb86868d0, 0xc3414182, 0xb0999929, 0x772d2d5a, 0x110f0f1e, 0xcbb0b07b, 0xfc5454a8, 0xd6bbbb6d, 0x3a16162c }; private static readonly uint[] _t1 = { 0x6363c6a5, 0x7c7cf884, 0x7777ee99, 0x7b7bf68d, 0xf2f2ff0d, 0x6b6bd6bd, 0x6f6fdeb1, 0xc5c59154, 0x30306050, 0x01010203, 0x6767cea9, 0x2b2b567d, 0xfefee719, 0xd7d7b562, 0xabab4de6, 0x7676ec9a, 0xcaca8f45, 0x82821f9d, 0xc9c98940, 0x7d7dfa87, 0xfafaef15, 0x5959b2eb, 0x47478ec9, 0xf0f0fb0b, 0xadad41ec, 0xd4d4b367, 0xa2a25ffd, 0xafaf45ea, 0x9c9c23bf, 0xa4a453f7, 0x7272e496, 0xc0c09b5b, 0xb7b775c2, 0xfdfde11c, 0x93933dae, 0x26264c6a, 0x36366c5a, 0x3f3f7e41, 0xf7f7f502, 0xcccc834f, 0x3434685c, 0xa5a551f4, 0xe5e5d134, 0xf1f1f908, 0x7171e293, 0xd8d8ab73, 0x31316253, 0x15152a3f, 0x0404080c, 0xc7c79552, 0x23234665, 0xc3c39d5e, 0x18183028, 0x969637a1, 0x05050a0f, 0x9a9a2fb5, 0x07070e09, 0x12122436, 0x80801b9b, 0xe2e2df3d, 0xebebcd26, 0x27274e69, 0xb2b27fcd, 0x7575ea9f, 0x0909121b, 0x83831d9e, 0x2c2c5874, 0x1a1a342e, 0x1b1b362d, 0x6e6edcb2, 0x5a5ab4ee, 0xa0a05bfb, 0x5252a4f6, 0x3b3b764d, 0xd6d6b761, 0xb3b37dce, 0x2929527b, 0xe3e3dd3e, 0x2f2f5e71, 0x84841397, 0x5353a6f5, 0xd1d1b968, 0x00000000, 0xededc12c, 0x20204060, 0xfcfce31f, 0xb1b179c8, 0x5b5bb6ed, 0x6a6ad4be, 0xcbcb8d46, 0xbebe67d9, 0x3939724b, 0x4a4a94de, 0x4c4c98d4, 0x5858b0e8, 0xcfcf854a, 0xd0d0bb6b, 0xefefc52a, 0xaaaa4fe5, 0xfbfbed16, 0x434386c5, 0x4d4d9ad7, 0x33336655, 0x85851194, 0x45458acf, 0xf9f9e910, 0x02020406, 0x7f7ffe81, 0x5050a0f0, 0x3c3c7844, 0x9f9f25ba, 0xa8a84be3, 0x5151a2f3, 0xa3a35dfe, 0x404080c0, 0x8f8f058a, 0x92923fad, 0x9d9d21bc, 0x38387048, 0xf5f5f104, 0xbcbc63df, 0xb6b677c1, 0xdadaaf75, 0x21214263, 0x10102030, 0xffffe51a, 0xf3f3fd0e, 0xd2d2bf6d, 0xcdcd814c, 0x0c0c1814, 0x13132635, 0xececc32f, 0x5f5fbee1, 0x979735a2, 0x444488cc, 0x17172e39, 0xc4c49357, 0xa7a755f2, 0x7e7efc82, 0x3d3d7a47, 0x6464c8ac, 0x5d5dbae7, 0x1919322b, 0x7373e695, 0x6060c0a0, 0x81811998, 0x4f4f9ed1, 0xdcdca37f, 0x22224466, 0x2a2a547e, 0x90903bab, 0x88880b83, 0x46468cca, 0xeeeec729, 0xb8b86bd3, 0x1414283c, 0xdedea779, 0x5e5ebce2, 0x0b0b161d, 0xdbdbad76, 0xe0e0db3b, 0x32326456, 0x3a3a744e, 0x0a0a141e, 0x494992db, 0x06060c0a, 0x2424486c, 0x5c5cb8e4, 0xc2c29f5d, 0xd3d3bd6e, 0xacac43ef, 0x6262c4a6, 0x919139a8, 0x959531a4, 0xe4e4d337, 0x7979f28b, 0xe7e7d532, 0xc8c88b43, 0x37376e59, 0x6d6ddab7, 0x8d8d018c, 0xd5d5b164, 0x4e4e9cd2, 0xa9a949e0, 0x6c6cd8b4, 0x5656acfa, 0xf4f4f307, 0xeaeacf25, 0x6565caaf, 0x7a7af48e, 0xaeae47e9, 0x08081018, 0xbaba6fd5, 0x7878f088, 0x25254a6f, 0x2e2e5c72, 0x1c1c3824, 0xa6a657f1, 0xb4b473c7, 0xc6c69751, 0xe8e8cb23, 0xdddda17c, 0x7474e89c, 0x1f1f3e21, 0x4b4b96dd, 0xbdbd61dc, 0x8b8b0d86, 0x8a8a0f85, 0x7070e090, 0x3e3e7c42, 0xb5b571c4, 0x6666ccaa, 0x484890d8, 0x03030605, 0xf6f6f701, 0x0e0e1c12, 0x6161c2a3, 0x35356a5f, 0x5757aef9, 0xb9b969d0, 0x86861791, 0xc1c19958, 0x1d1d3a27, 0x9e9e27b9, 0xe1e1d938, 0xf8f8eb13, 0x98982bb3, 0x11112233, 0x6969d2bb, 0xd9d9a970, 0x8e8e0789, 0x949433a7, 0x9b9b2db6, 0x1e1e3c22, 0x87871592, 0xe9e9c920, 0xcece8749, 0x5555aaff, 0x28285078, 0xdfdfa57a, 0x8c8c038f, 0xa1a159f8, 0x89890980, 0x0d0d1a17, 0xbfbf65da, 0xe6e6d731, 0x424284c6, 0x6868d0b8, 0x414182c3, 0x999929b0, 0x2d2d5a77, 0x0f0f1e11, 0xb0b07bcb, 0x5454a8fc, 0xbbbb6dd6, 0x16162c3a }; private static readonly uint[] _t2 = { 0x63c6a563, 0x7cf8847c, 0x77ee9977, 0x7bf68d7b, 0xf2ff0df2, 0x6bd6bd6b, 0x6fdeb16f, 0xc59154c5, 0x30605030, 0x01020301, 0x67cea967, 0x2b567d2b, 0xfee719fe, 0xd7b562d7, 0xab4de6ab, 0x76ec9a76, 0xca8f45ca, 0x821f9d82, 0xc98940c9, 0x7dfa877d, 0xfaef15fa, 0x59b2eb59, 0x478ec947, 0xf0fb0bf0, 0xad41ecad, 0xd4b367d4, 0xa25ffda2, 0xaf45eaaf, 0x9c23bf9c, 0xa453f7a4, 0x72e49672, 0xc09b5bc0, 0xb775c2b7, 0xfde11cfd, 0x933dae93, 0x264c6a26, 0x366c5a36, 0x3f7e413f, 0xf7f502f7, 0xcc834fcc, 0x34685c34, 0xa551f4a5, 0xe5d134e5, 0xf1f908f1, 0x71e29371, 0xd8ab73d8, 0x31625331, 0x152a3f15, 0x04080c04, 0xc79552c7, 0x23466523, 0xc39d5ec3, 0x18302818, 0x9637a196, 0x050a0f05, 0x9a2fb59a, 0x070e0907, 0x12243612, 0x801b9b80, 0xe2df3de2, 0xebcd26eb, 0x274e6927, 0xb27fcdb2, 0x75ea9f75, 0x09121b09, 0x831d9e83, 0x2c58742c, 0x1a342e1a, 0x1b362d1b, 0x6edcb26e, 0x5ab4ee5a, 0xa05bfba0, 0x52a4f652, 0x3b764d3b, 0xd6b761d6, 0xb37dceb3, 0x29527b29, 0xe3dd3ee3, 0x2f5e712f, 0x84139784, 0x53a6f553, 0xd1b968d1, 0x00000000, 0xedc12ced, 0x20406020, 0xfce31ffc, 0xb179c8b1, 0x5bb6ed5b, 0x6ad4be6a, 0xcb8d46cb, 0xbe67d9be, 0x39724b39, 0x4a94de4a, 0x4c98d44c, 0x58b0e858, 0xcf854acf, 0xd0bb6bd0, 0xefc52aef, 0xaa4fe5aa, 0xfbed16fb, 0x4386c543, 0x4d9ad74d, 0x33665533, 0x85119485, 0x458acf45, 0xf9e910f9, 0x02040602, 0x7ffe817f, 0x50a0f050, 0x3c78443c, 0x9f25ba9f, 0xa84be3a8, 0x51a2f351, 0xa35dfea3, 0x4080c040, 0x8f058a8f, 0x923fad92, 0x9d21bc9d, 0x38704838, 0xf5f104f5, 0xbc63dfbc, 0xb677c1b6, 0xdaaf75da, 0x21426321, 0x10203010, 0xffe51aff, 0xf3fd0ef3, 0xd2bf6dd2, 0xcd814ccd, 0x0c18140c, 0x13263513, 0xecc32fec, 0x5fbee15f, 0x9735a297, 0x4488cc44, 0x172e3917, 0xc49357c4, 0xa755f2a7, 0x7efc827e, 0x3d7a473d, 0x64c8ac64, 0x5dbae75d, 0x19322b19, 0x73e69573, 0x60c0a060, 0x81199881, 0x4f9ed14f, 0xdca37fdc, 0x22446622, 0x2a547e2a, 0x903bab90, 0x880b8388, 0x468cca46, 0xeec729ee, 0xb86bd3b8, 0x14283c14, 0xdea779de, 0x5ebce25e, 0x0b161d0b, 0xdbad76db, 0xe0db3be0, 0x32645632, 0x3a744e3a, 0x0a141e0a, 0x4992db49, 0x060c0a06, 0x24486c24, 0x5cb8e45c, 0xc29f5dc2, 0xd3bd6ed3, 0xac43efac, 0x62c4a662, 0x9139a891, 0x9531a495, 0xe4d337e4, 0x79f28b79, 0xe7d532e7, 0xc88b43c8, 0x376e5937, 0x6ddab76d, 0x8d018c8d, 0xd5b164d5, 0x4e9cd24e, 0xa949e0a9, 0x6cd8b46c, 0x56acfa56, 0xf4f307f4, 0xeacf25ea, 0x65caaf65, 0x7af48e7a, 0xae47e9ae, 0x08101808, 0xba6fd5ba, 0x78f08878, 0x254a6f25, 0x2e5c722e, 0x1c38241c, 0xa657f1a6, 0xb473c7b4, 0xc69751c6, 0xe8cb23e8, 0xdda17cdd, 0x74e89c74, 0x1f3e211f, 0x4b96dd4b, 0xbd61dcbd, 0x8b0d868b, 0x8a0f858a, 0x70e09070, 0x3e7c423e, 0xb571c4b5, 0x66ccaa66, 0x4890d848, 0x03060503, 0xf6f701f6, 0x0e1c120e, 0x61c2a361, 0x356a5f35, 0x57aef957, 0xb969d0b9, 0x86179186, 0xc19958c1, 0x1d3a271d, 0x9e27b99e, 0xe1d938e1, 0xf8eb13f8, 0x982bb398, 0x11223311, 0x69d2bb69, 0xd9a970d9, 0x8e07898e, 0x9433a794, 0x9b2db69b, 0x1e3c221e, 0x87159287, 0xe9c920e9, 0xce8749ce, 0x55aaff55, 0x28507828, 0xdfa57adf, 0x8c038f8c, 0xa159f8a1, 0x89098089, 0x0d1a170d, 0xbf65dabf, 0xe6d731e6, 0x4284c642, 0x68d0b868, 0x4182c341, 0x9929b099, 0x2d5a772d, 0x0f1e110f, 0xb07bcbb0, 0x54a8fc54, 0xbb6dd6bb, 0x162c3a16 }; private static readonly uint[] _t3 = { 0xc6a56363, 0xf8847c7c, 0xee997777, 0xf68d7b7b, 0xff0df2f2, 0xd6bd6b6b, 0xdeb16f6f, 0x9154c5c5, 0x60503030, 0x02030101, 0xcea96767, 0x567d2b2b, 0xe719fefe, 0xb562d7d7, 0x4de6abab, 0xec9a7676, 0x8f45caca, 0x1f9d8282, 0x8940c9c9, 0xfa877d7d, 0xef15fafa, 0xb2eb5959, 0x8ec94747, 0xfb0bf0f0, 0x41ecadad, 0xb367d4d4, 0x5ffda2a2, 0x45eaafaf, 0x23bf9c9c, 0x53f7a4a4, 0xe4967272, 0x9b5bc0c0, 0x75c2b7b7, 0xe11cfdfd, 0x3dae9393, 0x4c6a2626, 0x6c5a3636, 0x7e413f3f, 0xf502f7f7, 0x834fcccc, 0x685c3434, 0x51f4a5a5, 0xd134e5e5, 0xf908f1f1, 0xe2937171, 0xab73d8d8, 0x62533131, 0x2a3f1515, 0x080c0404, 0x9552c7c7, 0x46652323, 0x9d5ec3c3, 0x30281818, 0x37a19696, 0x0a0f0505, 0x2fb59a9a, 0x0e090707, 0x24361212, 0x1b9b8080, 0xdf3de2e2, 0xcd26ebeb, 0x4e692727, 0x7fcdb2b2, 0xea9f7575, 0x121b0909, 0x1d9e8383, 0x58742c2c, 0x342e1a1a, 0x362d1b1b, 0xdcb26e6e, 0xb4ee5a5a, 0x5bfba0a0, 0xa4f65252, 0x764d3b3b, 0xb761d6d6, 0x7dceb3b3, 0x527b2929, 0xdd3ee3e3, 0x5e712f2f, 0x13978484, 0xa6f55353, 0xb968d1d1, 0x00000000, 0xc12ceded, 0x40602020, 0xe31ffcfc, 0x79c8b1b1, 0xb6ed5b5b, 0xd4be6a6a, 0x8d46cbcb, 0x67d9bebe, 0x724b3939, 0x94de4a4a, 0x98d44c4c, 0xb0e85858, 0x854acfcf, 0xbb6bd0d0, 0xc52aefef, 0x4fe5aaaa, 0xed16fbfb, 0x86c54343, 0x9ad74d4d, 0x66553333, 0x11948585, 0x8acf4545, 0xe910f9f9, 0x04060202, 0xfe817f7f, 0xa0f05050, 0x78443c3c, 0x25ba9f9f, 0x4be3a8a8, 0xa2f35151, 0x5dfea3a3, 0x80c04040, 0x058a8f8f, 0x3fad9292, 0x21bc9d9d, 0x70483838, 0xf104f5f5, 0x63dfbcbc, 0x77c1b6b6, 0xaf75dada, 0x42632121, 0x20301010, 0xe51affff, 0xfd0ef3f3, 0xbf6dd2d2, 0x814ccdcd, 0x18140c0c, 0x26351313, 0xc32fecec, 0xbee15f5f, 0x35a29797, 0x88cc4444, 0x2e391717, 0x9357c4c4, 0x55f2a7a7, 0xfc827e7e, 0x7a473d3d, 0xc8ac6464, 0xbae75d5d, 0x322b1919, 0xe6957373, 0xc0a06060, 0x19988181, 0x9ed14f4f, 0xa37fdcdc, 0x44662222, 0x547e2a2a, 0x3bab9090, 0x0b838888, 0x8cca4646, 0xc729eeee, 0x6bd3b8b8, 0x283c1414, 0xa779dede, 0xbce25e5e, 0x161d0b0b, 0xad76dbdb, 0xdb3be0e0, 0x64563232, 0x744e3a3a, 0x141e0a0a, 0x92db4949, 0x0c0a0606, 0x486c2424, 0xb8e45c5c, 0x9f5dc2c2, 0xbd6ed3d3, 0x43efacac, 0xc4a66262, 0x39a89191, 0x31a49595, 0xd337e4e4, 0xf28b7979, 0xd532e7e7, 0x8b43c8c8, 0x6e593737, 0xdab76d6d, 0x018c8d8d, 0xb164d5d5, 0x9cd24e4e, 0x49e0a9a9, 0xd8b46c6c, 0xacfa5656, 0xf307f4f4, 0xcf25eaea, 0xcaaf6565, 0xf48e7a7a, 0x47e9aeae, 0x10180808, 0x6fd5baba, 0xf0887878, 0x4a6f2525, 0x5c722e2e, 0x38241c1c, 0x57f1a6a6, 0x73c7b4b4, 0x9751c6c6, 0xcb23e8e8, 0xa17cdddd, 0xe89c7474, 0x3e211f1f, 0x96dd4b4b, 0x61dcbdbd, 0x0d868b8b, 0x0f858a8a, 0xe0907070, 0x7c423e3e, 0x71c4b5b5, 0xccaa6666, 0x90d84848, 0x06050303, 0xf701f6f6, 0x1c120e0e, 0xc2a36161, 0x6a5f3535, 0xaef95757, 0x69d0b9b9, 0x17918686, 0x9958c1c1, 0x3a271d1d, 0x27b99e9e, 0xd938e1e1, 0xeb13f8f8, 0x2bb39898, 0x22331111, 0xd2bb6969, 0xa970d9d9, 0x07898e8e, 0x33a79494, 0x2db69b9b, 0x3c221e1e, 0x15928787, 0xc920e9e9, 0x8749cece, 0xaaff5555, 0x50782828, 0xa57adfdf, 0x038f8c8c, 0x59f8a1a1, 0x09808989, 0x1a170d0d, 0x65dabfbf, 0xd731e6e6, 0x84c64242, 0xd0b86868, 0x82c34141, 0x29b09999, 0x5a772d2d, 0x1e110f0f, 0x7bcbb0b0, 0xa8fc5454, 0x6dd6bbbb, 0x2c3a1616 }; private static readonly uint[] _tinv0 = { 0x50a7f451, 0x5365417e, 0xc3a4171a, 0x965e273a, 0xcb6bab3b, 0xf1459d1f, 0xab58faac, 0x9303e34b, 0x55fa3020, 0xf66d76ad, 0x9176cc88, 0x254c02f5, 0xfcd7e54f, 0xd7cb2ac5, 0x80443526, 0x8fa362b5, 0x495ab1de, 0x671bba25, 0x980eea45, 0xe1c0fe5d, 0x02752fc3, 0x12f04c81, 0xa397468d, 0xc6f9d36b, 0xe75f8f03, 0x959c9215, 0xeb7a6dbf, 0xda595295, 0x2d83bed4, 0xd3217458, 0x2969e049, 0x44c8c98e, 0x6a89c275, 0x78798ef4, 0x6b3e5899, 0xdd71b927, 0xb64fe1be, 0x17ad88f0, 0x66ac20c9, 0xb43ace7d, 0x184adf63, 0x82311ae5, 0x60335197, 0x457f5362, 0xe07764b1, 0x84ae6bbb, 0x1ca081fe, 0x942b08f9, 0x58684870, 0x19fd458f, 0x876cde94, 0xb7f87b52, 0x23d373ab, 0xe2024b72, 0x578f1fe3, 0x2aab5566, 0x0728ebb2, 0x03c2b52f, 0x9a7bc586, 0xa50837d3, 0xf2872830, 0xb2a5bf23, 0xba6a0302, 0x5c8216ed, 0x2b1ccf8a, 0x92b479a7, 0xf0f207f3, 0xa1e2694e, 0xcdf4da65, 0xd5be0506, 0x1f6234d1, 0x8afea6c4, 0x9d532e34, 0xa055f3a2, 0x32e18a05, 0x75ebf6a4, 0x39ec830b, 0xaaef6040, 0x069f715e, 0x51106ebd, 0xf98a213e, 0x3d06dd96, 0xae053edd, 0x46bde64d, 0xb58d5491, 0x055dc471, 0x6fd40604, 0xff155060, 0x24fb9819, 0x97e9bdd6, 0xcc434089, 0x779ed967, 0xbd42e8b0, 0x888b8907, 0x385b19e7, 0xdbeec879, 0x470a7ca1, 0xe90f427c, 0xc91e84f8, 0x00000000, 0x83868009, 0x48ed2b32, 0xac70111e, 0x4e725a6c, 0xfbff0efd, 0x5638850f, 0x1ed5ae3d, 0x27392d36, 0x64d90f0a, 0x21a65c68, 0xd1545b9b, 0x3a2e3624, 0xb1670a0c, 0x0fe75793, 0xd296eeb4, 0x9e919b1b, 0x4fc5c080, 0xa220dc61, 0x694b775a, 0x161a121c, 0x0aba93e2, 0xe52aa0c0, 0x43e0223c, 0x1d171b12, 0x0b0d090e, 0xadc78bf2, 0xb9a8b62d, 0xc8a91e14, 0x8519f157, 0x4c0775af, 0xbbdd99ee, 0xfd607fa3, 0x9f2601f7, 0xbcf5725c, 0xc53b6644, 0x347efb5b, 0x7629438b, 0xdcc623cb, 0x68fcedb6, 0x63f1e4b8, 0xcadc31d7, 0x10856342, 0x40229713, 0x2011c684, 0x7d244a85, 0xf83dbbd2, 0x1132f9ae, 0x6da129c7, 0x4b2f9e1d, 0xf330b2dc, 0xec52860d, 0xd0e3c177, 0x6c16b32b, 0x99b970a9, 0xfa489411, 0x2264e947, 0xc48cfca8, 0x1a3ff0a0, 0xd82c7d56, 0xef903322, 0xc74e4987, 0xc1d138d9, 0xfea2ca8c, 0x360bd498, 0xcf81f5a6, 0x28de7aa5, 0x268eb7da, 0xa4bfad3f, 0xe49d3a2c, 0x0d927850, 0x9bcc5f6a, 0x62467e54, 0xc2138df6, 0xe8b8d890, 0x5ef7392e, 0xf5afc382, 0xbe805d9f, 0x7c93d069, 0xa92dd56f, 0xb31225cf, 0x3b99acc8, 0xa77d1810, 0x6e639ce8, 0x7bbb3bdb, 0x097826cd, 0xf418596e, 0x01b79aec, 0xa89a4f83, 0x656e95e6, 0x7ee6ffaa, 0x08cfbc21, 0xe6e815ef, 0xd99be7ba, 0xce366f4a, 0xd4099fea, 0xd67cb029, 0xafb2a431, 0x31233f2a, 0x3094a5c6, 0xc066a235, 0x37bc4e74, 0xa6ca82fc, 0xb0d090e0, 0x15d8a733, 0x4a9804f1, 0xf7daec41, 0x0e50cd7f, 0x2ff69117, 0x8dd64d76, 0x4db0ef43, 0x544daacc, 0xdf0496e4, 0xe3b5d19e, 0x1b886a4c, 0xb81f2cc1, 0x7f516546, 0x04ea5e9d, 0x5d358c01, 0x737487fa, 0x2e410bfb, 0x5a1d67b3, 0x52d2db92, 0x335610e9, 0x1347d66d, 0x8c61d79a, 0x7a0ca137, 0x8e14f859, 0x893c13eb, 0xee27a9ce, 0x35c961b7, 0xede51ce1, 0x3cb1477a, 0x59dfd29c, 0x3f73f255, 0x79ce1418, 0xbf37c773, 0xeacdf753, 0x5baafd5f, 0x146f3ddf, 0x86db4478, 0x81f3afca, 0x3ec468b9, 0x2c342438, 0x5f40a3c2, 0x72c31d16, 0x0c25e2bc, 0x8b493c28, 0x41950dff, 0x7101a839, 0xdeb30c08, 0x9ce4b4d8, 0x90c15664, 0x6184cb7b, 0x70b632d5, 0x745c6c48, 0x4257b8d0 }; private static readonly uint[] _tinv1 = { 0xa7f45150, 0x65417e53, 0xa4171ac3, 0x5e273a96, 0x6bab3bcb, 0x459d1ff1, 0x58faacab, 0x03e34b93, 0xfa302055, 0x6d76adf6, 0x76cc8891, 0x4c02f525, 0xd7e54ffc, 0xcb2ac5d7, 0x44352680, 0xa362b58f, 0x5ab1de49, 0x1bba2567, 0x0eea4598, 0xc0fe5de1, 0x752fc302, 0xf04c8112, 0x97468da3, 0xf9d36bc6, 0x5f8f03e7, 0x9c921595, 0x7a6dbfeb, 0x595295da, 0x83bed42d, 0x217458d3, 0x69e04929, 0xc8c98e44, 0x89c2756a, 0x798ef478, 0x3e58996b, 0x71b927dd, 0x4fe1beb6, 0xad88f017, 0xac20c966, 0x3ace7db4, 0x4adf6318, 0x311ae582, 0x33519760, 0x7f536245, 0x7764b1e0, 0xae6bbb84, 0xa081fe1c, 0x2b08f994, 0x68487058, 0xfd458f19, 0x6cde9487, 0xf87b52b7, 0xd373ab23, 0x024b72e2, 0x8f1fe357, 0xab55662a, 0x28ebb207, 0xc2b52f03, 0x7bc5869a, 0x0837d3a5, 0x872830f2, 0xa5bf23b2, 0x6a0302ba, 0x8216ed5c, 0x1ccf8a2b, 0xb479a792, 0xf207f3f0, 0xe2694ea1, 0xf4da65cd, 0xbe0506d5, 0x6234d11f, 0xfea6c48a, 0x532e349d, 0x55f3a2a0, 0xe18a0532, 0xebf6a475, 0xec830b39, 0xef6040aa, 0x9f715e06, 0x106ebd51, 0x8a213ef9, 0x06dd963d, 0x053eddae, 0xbde64d46, 0x8d5491b5, 0x5dc47105, 0xd406046f, 0x155060ff, 0xfb981924, 0xe9bdd697, 0x434089cc, 0x9ed96777, 0x42e8b0bd, 0x8b890788, 0x5b19e738, 0xeec879db, 0x0a7ca147, 0x0f427ce9, 0x1e84f8c9, 0x00000000, 0x86800983, 0xed2b3248, 0x70111eac, 0x725a6c4e, 0xff0efdfb, 0x38850f56, 0xd5ae3d1e, 0x392d3627, 0xd90f0a64, 0xa65c6821, 0x545b9bd1, 0x2e36243a, 0x670a0cb1, 0xe757930f, 0x96eeb4d2, 0x919b1b9e, 0xc5c0804f, 0x20dc61a2, 0x4b775a69, 0x1a121c16, 0xba93e20a, 0x2aa0c0e5, 0xe0223c43, 0x171b121d, 0x0d090e0b, 0xc78bf2ad, 0xa8b62db9, 0xa91e14c8, 0x19f15785, 0x0775af4c, 0xdd99eebb, 0x607fa3fd, 0x2601f79f, 0xf5725cbc, 0x3b6644c5, 0x7efb5b34, 0x29438b76, 0xc623cbdc, 0xfcedb668, 0xf1e4b863, 0xdc31d7ca, 0x85634210, 0x22971340, 0x11c68420, 0x244a857d, 0x3dbbd2f8, 0x32f9ae11, 0xa129c76d, 0x2f9e1d4b, 0x30b2dcf3, 0x52860dec, 0xe3c177d0, 0x16b32b6c, 0xb970a999, 0x489411fa, 0x64e94722, 0x8cfca8c4, 0x3ff0a01a, 0x2c7d56d8, 0x903322ef, 0x4e4987c7, 0xd138d9c1, 0xa2ca8cfe, 0x0bd49836, 0x81f5a6cf, 0xde7aa528, 0x8eb7da26, 0xbfad3fa4, 0x9d3a2ce4, 0x9278500d, 0xcc5f6a9b, 0x467e5462, 0x138df6c2, 0xb8d890e8, 0xf7392e5e, 0xafc382f5, 0x805d9fbe, 0x93d0697c, 0x2dd56fa9, 0x1225cfb3, 0x99acc83b, 0x7d1810a7, 0x639ce86e, 0xbb3bdb7b, 0x7826cd09, 0x18596ef4, 0xb79aec01, 0x9a4f83a8, 0x6e95e665, 0xe6ffaa7e, 0xcfbc2108, 0xe815efe6, 0x9be7bad9, 0x366f4ace, 0x099fead4, 0x7cb029d6, 0xb2a431af, 0x233f2a31, 0x94a5c630, 0x66a235c0, 0xbc4e7437, 0xca82fca6, 0xd090e0b0, 0xd8a73315, 0x9804f14a, 0xdaec41f7, 0x50cd7f0e, 0xf691172f, 0xd64d768d, 0xb0ef434d, 0x4daacc54, 0x0496e4df, 0xb5d19ee3, 0x886a4c1b, 0x1f2cc1b8, 0x5165467f, 0xea5e9d04, 0x358c015d, 0x7487fa73, 0x410bfb2e, 0x1d67b35a, 0xd2db9252, 0x5610e933, 0x47d66d13, 0x61d79a8c, 0x0ca1377a, 0x14f8598e, 0x3c13eb89, 0x27a9ceee, 0xc961b735, 0xe51ce1ed, 0xb1477a3c, 0xdfd29c59, 0x73f2553f, 0xce141879, 0x37c773bf, 0xcdf753ea, 0xaafd5f5b, 0x6f3ddf14, 0xdb447886, 0xf3afca81, 0xc468b93e, 0x3424382c, 0x40a3c25f, 0xc31d1672, 0x25e2bc0c, 0x493c288b, 0x950dff41, 0x01a83971, 0xb30c08de, 0xe4b4d89c, 0xc1566490, 0x84cb7b61, 0xb632d570, 0x5c6c4874, 0x57b8d042 }; private static readonly uint[] _tinv2 = { 0xf45150a7, 0x417e5365, 0x171ac3a4, 0x273a965e, 0xab3bcb6b, 0x9d1ff145, 0xfaacab58, 0xe34b9303, 0x302055fa, 0x76adf66d, 0xcc889176, 0x02f5254c, 0xe54ffcd7, 0x2ac5d7cb, 0x35268044, 0x62b58fa3, 0xb1de495a, 0xba25671b, 0xea45980e, 0xfe5de1c0, 0x2fc30275, 0x4c8112f0, 0x468da397, 0xd36bc6f9, 0x8f03e75f, 0x9215959c, 0x6dbfeb7a, 0x5295da59, 0xbed42d83, 0x7458d321, 0xe0492969, 0xc98e44c8, 0xc2756a89, 0x8ef47879, 0x58996b3e, 0xb927dd71, 0xe1beb64f, 0x88f017ad, 0x20c966ac, 0xce7db43a, 0xdf63184a, 0x1ae58231, 0x51976033, 0x5362457f, 0x64b1e077, 0x6bbb84ae, 0x81fe1ca0, 0x08f9942b, 0x48705868, 0x458f19fd, 0xde94876c, 0x7b52b7f8, 0x73ab23d3, 0x4b72e202, 0x1fe3578f, 0x55662aab, 0xebb20728, 0xb52f03c2, 0xc5869a7b, 0x37d3a508, 0x2830f287, 0xbf23b2a5, 0x0302ba6a, 0x16ed5c82, 0xcf8a2b1c, 0x79a792b4, 0x07f3f0f2, 0x694ea1e2, 0xda65cdf4, 0x0506d5be, 0x34d11f62, 0xa6c48afe, 0x2e349d53, 0xf3a2a055, 0x8a0532e1, 0xf6a475eb, 0x830b39ec, 0x6040aaef, 0x715e069f, 0x6ebd5110, 0x213ef98a, 0xdd963d06, 0x3eddae05, 0xe64d46bd, 0x5491b58d, 0xc471055d, 0x06046fd4, 0x5060ff15, 0x981924fb, 0xbdd697e9, 0x4089cc43, 0xd967779e, 0xe8b0bd42, 0x8907888b, 0x19e7385b, 0xc879dbee, 0x7ca1470a, 0x427ce90f, 0x84f8c91e, 0x00000000, 0x80098386, 0x2b3248ed, 0x111eac70, 0x5a6c4e72, 0x0efdfbff, 0x850f5638, 0xae3d1ed5, 0x2d362739, 0x0f0a64d9, 0x5c6821a6, 0x5b9bd154, 0x36243a2e, 0x0a0cb167, 0x57930fe7, 0xeeb4d296, 0x9b1b9e91, 0xc0804fc5, 0xdc61a220, 0x775a694b, 0x121c161a, 0x93e20aba, 0xa0c0e52a, 0x223c43e0, 0x1b121d17, 0x090e0b0d, 0x8bf2adc7, 0xb62db9a8, 0x1e14c8a9, 0xf1578519, 0x75af4c07, 0x99eebbdd, 0x7fa3fd60, 0x01f79f26, 0x725cbcf5, 0x6644c53b, 0xfb5b347e, 0x438b7629, 0x23cbdcc6, 0xedb668fc, 0xe4b863f1, 0x31d7cadc, 0x63421085, 0x97134022, 0xc6842011, 0x4a857d24, 0xbbd2f83d, 0xf9ae1132, 0x29c76da1, 0x9e1d4b2f, 0xb2dcf330, 0x860dec52, 0xc177d0e3, 0xb32b6c16, 0x70a999b9, 0x9411fa48, 0xe9472264, 0xfca8c48c, 0xf0a01a3f, 0x7d56d82c, 0x3322ef90, 0x4987c74e, 0x38d9c1d1, 0xca8cfea2, 0xd498360b, 0xf5a6cf81, 0x7aa528de, 0xb7da268e, 0xad3fa4bf, 0x3a2ce49d, 0x78500d92, 0x5f6a9bcc, 0x7e546246, 0x8df6c213, 0xd890e8b8, 0x392e5ef7, 0xc382f5af, 0x5d9fbe80, 0xd0697c93, 0xd56fa92d, 0x25cfb312, 0xacc83b99, 0x1810a77d, 0x9ce86e63, 0x3bdb7bbb, 0x26cd0978, 0x596ef418, 0x9aec01b7, 0x4f83a89a, 0x95e6656e, 0xffaa7ee6, 0xbc2108cf, 0x15efe6e8, 0xe7bad99b, 0x6f4ace36, 0x9fead409, 0xb029d67c, 0xa431afb2, 0x3f2a3123, 0xa5c63094, 0xa235c066, 0x4e7437bc, 0x82fca6ca, 0x90e0b0d0, 0xa73315d8, 0x04f14a98, 0xec41f7da, 0xcd7f0e50, 0x91172ff6, 0x4d768dd6, 0xef434db0, 0xaacc544d, 0x96e4df04, 0xd19ee3b5, 0x6a4c1b88, 0x2cc1b81f, 0x65467f51, 0x5e9d04ea, 0x8c015d35, 0x87fa7374, 0x0bfb2e41, 0x67b35a1d, 0xdb9252d2, 0x10e93356, 0xd66d1347, 0xd79a8c61, 0xa1377a0c, 0xf8598e14, 0x13eb893c, 0xa9ceee27, 0x61b735c9, 0x1ce1ede5, 0x477a3cb1, 0xd29c59df, 0xf2553f73, 0x141879ce, 0xc773bf37, 0xf753eacd, 0xfd5f5baa, 0x3ddf146f, 0x447886db, 0xafca81f3, 0x68b93ec4, 0x24382c34, 0xa3c25f40, 0x1d1672c3, 0xe2bc0c25, 0x3c288b49, 0x0dff4195, 0xa8397101, 0x0c08deb3, 0xb4d89ce4, 0x566490c1, 0xcb7b6184, 0x32d570b6, 0x6c48745c, 0xb8d04257 }; private static readonly uint[] _tinv3 = { 0x5150a7f4, 0x7e536541, 0x1ac3a417, 0x3a965e27, 0x3bcb6bab, 0x1ff1459d, 0xacab58fa, 0x4b9303e3, 0x2055fa30, 0xadf66d76, 0x889176cc, 0xf5254c02, 0x4ffcd7e5, 0xc5d7cb2a, 0x26804435, 0xb58fa362, 0xde495ab1, 0x25671bba, 0x45980eea, 0x5de1c0fe, 0xc302752f, 0x8112f04c, 0x8da39746, 0x6bc6f9d3, 0x03e75f8f, 0x15959c92, 0xbfeb7a6d, 0x95da5952, 0xd42d83be, 0x58d32174, 0x492969e0, 0x8e44c8c9, 0x756a89c2, 0xf478798e, 0x996b3e58, 0x27dd71b9, 0xbeb64fe1, 0xf017ad88, 0xc966ac20, 0x7db43ace, 0x63184adf, 0xe582311a, 0x97603351, 0x62457f53, 0xb1e07764, 0xbb84ae6b, 0xfe1ca081, 0xf9942b08, 0x70586848, 0x8f19fd45, 0x94876cde, 0x52b7f87b, 0xab23d373, 0x72e2024b, 0xe3578f1f, 0x662aab55, 0xb20728eb, 0x2f03c2b5, 0x869a7bc5, 0xd3a50837, 0x30f28728, 0x23b2a5bf, 0x02ba6a03, 0xed5c8216, 0x8a2b1ccf, 0xa792b479, 0xf3f0f207, 0x4ea1e269, 0x65cdf4da, 0x06d5be05, 0xd11f6234, 0xc48afea6, 0x349d532e, 0xa2a055f3, 0x0532e18a, 0xa475ebf6, 0x0b39ec83, 0x40aaef60, 0x5e069f71, 0xbd51106e, 0x3ef98a21, 0x963d06dd, 0xddae053e, 0x4d46bde6, 0x91b58d54, 0x71055dc4, 0x046fd406, 0x60ff1550, 0x1924fb98, 0xd697e9bd, 0x89cc4340, 0x67779ed9, 0xb0bd42e8, 0x07888b89, 0xe7385b19, 0x79dbeec8, 0xa1470a7c, 0x7ce90f42, 0xf8c91e84, 0x00000000, 0x09838680, 0x3248ed2b, 0x1eac7011, 0x6c4e725a, 0xfdfbff0e, 0x0f563885, 0x3d1ed5ae, 0x3627392d, 0x0a64d90f, 0x6821a65c, 0x9bd1545b, 0x243a2e36, 0x0cb1670a, 0x930fe757, 0xb4d296ee, 0x1b9e919b, 0x804fc5c0, 0x61a220dc, 0x5a694b77, 0x1c161a12, 0xe20aba93, 0xc0e52aa0, 0x3c43e022, 0x121d171b, 0x0e0b0d09, 0xf2adc78b, 0x2db9a8b6, 0x14c8a91e, 0x578519f1, 0xaf4c0775, 0xeebbdd99, 0xa3fd607f, 0xf79f2601, 0x5cbcf572, 0x44c53b66, 0x5b347efb, 0x8b762943, 0xcbdcc623, 0xb668fced, 0xb863f1e4, 0xd7cadc31, 0x42108563, 0x13402297, 0x842011c6, 0x857d244a, 0xd2f83dbb, 0xae1132f9, 0xc76da129, 0x1d4b2f9e, 0xdcf330b2, 0x0dec5286, 0x77d0e3c1, 0x2b6c16b3, 0xa999b970, 0x11fa4894, 0x472264e9, 0xa8c48cfc, 0xa01a3ff0, 0x56d82c7d, 0x22ef9033, 0x87c74e49, 0xd9c1d138, 0x8cfea2ca, 0x98360bd4, 0xa6cf81f5, 0xa528de7a, 0xda268eb7, 0x3fa4bfad, 0x2ce49d3a, 0x500d9278, 0x6a9bcc5f, 0x5462467e, 0xf6c2138d, 0x90e8b8d8, 0x2e5ef739, 0x82f5afc3, 0x9fbe805d, 0x697c93d0, 0x6fa92dd5, 0xcfb31225, 0xc83b99ac, 0x10a77d18, 0xe86e639c, 0xdb7bbb3b, 0xcd097826, 0x6ef41859, 0xec01b79a, 0x83a89a4f, 0xe6656e95, 0xaa7ee6ff, 0x2108cfbc, 0xefe6e815, 0xbad99be7, 0x4ace366f, 0xead4099f, 0x29d67cb0, 0x31afb2a4, 0x2a31233f, 0xc63094a5, 0x35c066a2, 0x7437bc4e, 0xfca6ca82, 0xe0b0d090, 0x3315d8a7, 0xf14a9804, 0x41f7daec, 0x7f0e50cd, 0x172ff691, 0x768dd64d, 0x434db0ef, 0xcc544daa, 0xe4df0496, 0x9ee3b5d1, 0x4c1b886a, 0xc1b81f2c, 0x467f5165, 0x9d04ea5e, 0x015d358c, 0xfa737487, 0xfb2e410b, 0xb35a1d67, 0x9252d2db, 0xe9335610, 0x6d1347d6, 0x9a8c61d7, 0x377a0ca1, 0x598e14f8, 0xeb893c13, 0xceee27a9, 0xb735c961, 0xe1ede51c, 0x7a3cb147, 0x9c59dfd2, 0x553f73f2, 0x1879ce14, 0x73bf37c7, 0x53eacdf7, 0x5f5baafd, 0xdf146f3d, 0x7886db44, 0xca81f3af, 0xb93ec468, 0x382c3424, 0xc25f40a3, 0x1672c31d, 0xbc0c25e2, 0x288b493c, 0xff41950d, 0x397101a8, 0x08deb30c, 0xd89ce4b4, 0x6490c156, 0x7b6184cb, 0xd570b632, 0x48745c6c, 0xd04257b8 }; private static uint Shift(uint r, int shift) { return (r >> shift) | (r << (32 - shift)); } /* multiply four bytes in GF(2^8) by 'x' {02} in parallel */ private const uint M1 = 0x80808080; private const uint M2 = 0x7f7f7f7f; private const uint M3 = 0x0000001b; private static uint FFmulX(uint x) { return ((x & M2) << 1) ^ (((x & M1) >> 7) * M3); } /* The following defines provide alternative definitions of FFmulX that might give improved performance if a fast 32-bit multiply is not available. private int FFmulX(int x) { int u = x & m1; u |= (u >> 1); return ((x & m2) << 1) ^ ((u >>> 3) | (u >>> 6)); } private static final int m4 = 0x1b1b1b1b; private int FFmulX(int x) { int u = x & m1; return ((x & m2) << 1) ^ ((u - (u >>> 7)) & m4); } */ private static uint InvMcol(uint x) { var f2 = FFmulX(x); var f4 = FFmulX(f2); var f8 = FFmulX(f4); var f9 = x ^ f8; return f2 ^ f4 ^ f8 ^ Shift(f2 ^ f9, 8) ^ Shift(f4 ^ f9, 16) ^ Shift(f9, 24); } private static uint SubWord(uint x) { return _s[x & 255] | (((uint)_s[(x >> 8) & 255]) << 8) | (((uint)_s[(x >> 16) & 255]) << 16) | (((uint)_s[(x >> 24) & 255]) << 24); } /** * Calculate the necessary round keys * The number of calculations depends on key size and block size * AES specified a fixed block size of 128 bits and key sizes 128/192/256 bits * This code is written assuming those are the only possible values */ private uint[,] GenerateWorkingKey(byte[] key, bool forEncryption) { var kc = key.Length / 4; // key length in words if (((kc != 4) && (kc != 6) && (kc != 8)) || ((kc * 4) != key.Length)) throw new ArgumentException("Key length not 128/192/256 bits."); _rounds = kc + 6; // This is not always true for the generalized Rijndael that allows larger block sizes var w = new uint[_rounds + 1, 4]; // 4 words in a block // // copy the key into the round key array // var t = 0; for (var i = 0; i < key.Length; t++) { w[t >> 2, t & 3] = Pack.LE_To_UInt32(key, i); i += 4; } // // while not enough round key material calculated // calculate new values // var k = (_rounds + 1) << 2; for (var i = kc; (i < k); i++) { var temp = w[(i - 1) >> 2, (i - 1) & 3]; if ((i % kc) == 0) { temp = SubWord(Shift(temp, 8)) ^ _rcon[(i / kc) - 1]; } else if ((kc > 6) && ((i % kc) == 4)) { temp = SubWord(temp); } w[i >> 2, i & 3] = w[(i - kc) >> 2, (i - kc) & 3] ^ temp; } if (!forEncryption) { for (var j = 1; j < _rounds; j++) { for (var i = 0; i < 4; i++) { w[j, i] = InvMcol(w[j, i]); } } } return w; } private int _rounds; private uint[,] _workingKey; private uint _c0, _c1, _c2, _c3; private bool _forEncryption; private const int BlockSize = 16; /** * initialise an AES cipher. * * @param forEncryption whether or not we are for encryption. * @param parameters the parameters required to set up the cipher. * @exception ArgumentException if the parameters argument is * inappropriate. */ public void Init(bool forEncryption, ICipherParameters parameters) { if (!(parameters is KeyParameter)) throw new ArgumentException("invalid parameter passed to AES init - " + parameters.GetType()); _workingKey = GenerateWorkingKey(((KeyParameter)parameters).GetKey(), forEncryption); _forEncryption = forEncryption; } public string AlgorithmName { get { return "AES"; } } public bool IsPartialBlockOkay { get { return false; } } public int GetBlockSize() { return BlockSize; } public int ProcessBlock(byte[] input, int inOff, byte[] output, int outOff) { if (_workingKey == null) { throw new InvalidOperationException("AES engine not initialised"); } if ((inOff + (32 / 2)) > input.Length) { throw new DataLengthException("input buffer too short"); } if ((outOff + (32 / 2)) > output.Length) { throw new DataLengthException("output buffer too short"); } UnPackBlock(input, inOff); if (_forEncryption) { EncryptBlock(_workingKey); } else { DecryptBlock(_workingKey); } PackBlock(output, outOff); return BlockSize; } public void Reset() { } private void UnPackBlock(byte[] bytes, int off) { _c0 = Pack.LE_To_UInt32(bytes, off); _c1 = Pack.LE_To_UInt32(bytes, off + 4); _c2 = Pack.LE_To_UInt32(bytes, off + 8); _c3 = Pack.LE_To_UInt32(bytes, off + 12); } private void PackBlock(byte[] bytes, int off) { Pack.UInt32_To_LE(_c0, bytes, off); Pack.UInt32_To_LE(_c1, bytes, off + 4); Pack.UInt32_To_LE(_c2, bytes, off + 8); Pack.UInt32_To_LE(_c3, bytes, off + 12); } private void EncryptBlock(uint[,] kw) { int r; uint r0, r1, r2, r3; _c0 ^= kw[0, 0]; _c1 ^= kw[0, 1]; _c2 ^= kw[0, 2]; _c3 ^= kw[0, 3]; for (r = 1; r < _rounds - 1; ) { r0 = _t0[_c0 & 255] ^ _t1[(_c1 >> 8) & 255] ^ _t2[(_c2 >> 16) & 255] ^ _t3[_c3 >> 24] ^ kw[r, 0]; r1 = _t0[_c1 & 255] ^ _t1[(_c2 >> 8) & 255] ^ _t2[(_c3 >> 16) & 255] ^ _t3[_c0 >> 24] ^ kw[r, 1]; r2 = _t0[_c2 & 255] ^ _t1[(_c3 >> 8) & 255] ^ _t2[(_c0 >> 16) & 255] ^ _t3[_c1 >> 24] ^ kw[r, 2]; r3 = _t0[_c3 & 255] ^ _t1[(_c0 >> 8) & 255] ^ _t2[(_c1 >> 16) & 255] ^ _t3[_c2 >> 24] ^ kw[r++, 3]; _c0 = _t0[r0 & 255] ^ _t1[(r1 >> 8) & 255] ^ _t2[(r2 >> 16) & 255] ^ _t3[r3 >> 24] ^ kw[r, 0]; _c1 = _t0[r1 & 255] ^ _t1[(r2 >> 8) & 255] ^ _t2[(r3 >> 16) & 255] ^ _t3[r0 >> 24] ^ kw[r, 1]; _c2 = _t0[r2 & 255] ^ _t1[(r3 >> 8) & 255] ^ _t2[(r0 >> 16) & 255] ^ _t3[r1 >> 24] ^ kw[r, 2]; _c3 = _t0[r3 & 255] ^ _t1[(r0 >> 8) & 255] ^ _t2[(r1 >> 16) & 255] ^ _t3[r2 >> 24] ^ kw[r++, 3]; } r0 = _t0[_c0 & 255] ^ _t1[(_c1 >> 8) & 255] ^ _t2[(_c2 >> 16) & 255] ^ _t3[_c3 >> 24] ^ kw[r, 0]; r1 = _t0[_c1 & 255] ^ _t1[(_c2 >> 8) & 255] ^ _t2[(_c3 >> 16) & 255] ^ _t3[_c0 >> 24] ^ kw[r, 1]; r2 = _t0[_c2 & 255] ^ _t1[(_c3 >> 8) & 255] ^ _t2[(_c0 >> 16) & 255] ^ _t3[_c1 >> 24] ^ kw[r, 2]; r3 = _t0[_c3 & 255] ^ _t1[(_c0 >> 8) & 255] ^ _t2[(_c1 >> 16) & 255] ^ _t3[_c2 >> 24] ^ kw[r++, 3]; // the final round's table is a simple function of S so we don't use a whole other four tables for it _c0 = _s[r0 & 255] ^ (((uint)_s[(r1 >> 8) & 255]) << 8) ^ (((uint)_s[(r2 >> 16) & 255]) << 16) ^ (((uint)_s[r3 >> 24]) << 24) ^ kw[r, 0]; _c1 = _s[r1 & 255] ^ (((uint)_s[(r2 >> 8) & 255]) << 8) ^ (((uint)_s[(r3 >> 16) & 255]) << 16) ^ (((uint)_s[r0 >> 24]) << 24) ^ kw[r, 1]; _c2 = _s[r2 & 255] ^ (((uint)_s[(r3 >> 8) & 255]) << 8) ^ (((uint)_s[(r0 >> 16) & 255]) << 16) ^ (((uint)_s[r1 >> 24]) << 24) ^ kw[r, 2]; _c3 = _s[r3 & 255] ^ (((uint)_s[(r0 >> 8) & 255]) << 8) ^ (((uint)_s[(r1 >> 16) & 255]) << 16) ^ (((uint)_s[r2 >> 24]) << 24) ^ kw[r, 3]; } private void DecryptBlock(uint[,] kw) { int r; uint r0, r1, r2, r3; _c0 ^= kw[_rounds, 0]; _c1 ^= kw[_rounds, 1]; _c2 ^= kw[_rounds, 2]; _c3 ^= kw[_rounds, 3]; for (r = _rounds - 1; r > 1; ) { r0 = _tinv0[_c0 & 255] ^ _tinv1[(_c3 >> 8) & 255] ^ _tinv2[(_c2 >> 16) & 255] ^ _tinv3[_c1 >> 24] ^ kw[r, 0]; r1 = _tinv0[_c1 & 255] ^ _tinv1[(_c0 >> 8) & 255] ^ _tinv2[(_c3 >> 16) & 255] ^ _tinv3[_c2 >> 24] ^ kw[r, 1]; r2 = _tinv0[_c2 & 255] ^ _tinv1[(_c1 >> 8) & 255] ^ _tinv2[(_c0 >> 16) & 255] ^ _tinv3[_c3 >> 24] ^ kw[r, 2]; r3 = _tinv0[_c3 & 255] ^ _tinv1[(_c2 >> 8) & 255] ^ _tinv2[(_c1 >> 16) & 255] ^ _tinv3[_c0 >> 24] ^ kw[r--, 3]; _c0 = _tinv0[r0 & 255] ^ _tinv1[(r3 >> 8) & 255] ^ _tinv2[(r2 >> 16) & 255] ^ _tinv3[r1 >> 24] ^ kw[r, 0]; _c1 = _tinv0[r1 & 255] ^ _tinv1[(r0 >> 8) & 255] ^ _tinv2[(r3 >> 16) & 255] ^ _tinv3[r2 >> 24] ^ kw[r, 1]; _c2 = _tinv0[r2 & 255] ^ _tinv1[(r1 >> 8) & 255] ^ _tinv2[(r0 >> 16) & 255] ^ _tinv3[r3 >> 24] ^ kw[r, 2]; _c3 = _tinv0[r3 & 255] ^ _tinv1[(r2 >> 8) & 255] ^ _tinv2[(r1 >> 16) & 255] ^ _tinv3[r0 >> 24] ^ kw[r--, 3]; } r0 = _tinv0[_c0 & 255] ^ _tinv1[(_c3 >> 8) & 255] ^ _tinv2[(_c2 >> 16) & 255] ^ _tinv3[_c1 >> 24] ^ kw[r, 0]; r1 = _tinv0[_c1 & 255] ^ _tinv1[(_c0 >> 8) & 255] ^ _tinv2[(_c3 >> 16) & 255] ^ _tinv3[_c2 >> 24] ^ kw[r, 1]; r2 = _tinv0[_c2 & 255] ^ _tinv1[(_c1 >> 8) & 255] ^ _tinv2[(_c0 >> 16) & 255] ^ _tinv3[_c3 >> 24] ^ kw[r, 2]; r3 = _tinv0[_c3 & 255] ^ _tinv1[(_c2 >> 8) & 255] ^ _tinv2[(_c1 >> 16) & 255] ^ _tinv3[_c0 >> 24] ^ kw[r, 3]; // the final round's table is a simple function of Si so we don't use a whole other four tables for it _c0 = _si[r0 & 255] ^ (((uint)_si[(r3 >> 8) & 255]) << 8) ^ (((uint)_si[(r2 >> 16) & 255]) << 16) ^ (((uint)_si[r1 >> 24]) << 24) ^ kw[0, 0]; _c1 = _si[r1 & 255] ^ (((uint)_si[(r0 >> 8) & 255]) << 8) ^ (((uint)_si[(r3 >> 16) & 255]) << 16) ^ (((uint)_si[r2 >> 24]) << 24) ^ kw[0, 1]; _c2 = _si[r2 & 255] ^ (((uint)_si[(r1 >> 8) & 255]) << 8) ^ (((uint)_si[(r0 >> 16) & 255]) << 16) ^ (((uint)_si[r3 >> 24]) << 24) ^ kw[0, 2]; _c3 = _si[r3 & 255] ^ (((uint)_si[(r2 >> 8) & 255]) << 8) ^ (((uint)_si[(r1 >> 16) & 255]) << 16) ^ (((uint)_si[r0 >> 24]) << 24) ^ kw[0, 3]; } } }
50.890625
153
0.665194
[ "MIT" ]
SchmooseSA/Schmoose-BouncyCastle
Crypto/crypto/engines/AesFastEngine.cs
42,341
C#
using System; using Microsoft.EntityFrameworkCore; namespace RecursosCompartilhados.Dados.Contexto { public abstract class BaseContexto : DbContext { public override int SaveChanges() { foreach (var entry in ChangeTracker.Entries()) { if (entry.Entity.GetType().GetProperty("DataCriacaoRegistro") == null) continue; if (entry.State == EntityState.Added) { entry.Property("DataCriacaoRegistro").CurrentValue = DateTime.Now; entry.Property("DataAtualizacaoRegistro").CurrentValue = DateTime.Now; } if (entry.State == EntityState.Modified) { entry.Property("DataCriacaoRegistro").IsModified = false; entry.Property("DataAtualizacaoRegistro").CurrentValue = DateTime.Now; } } return base.SaveChanges(); } } }
32.8
96
0.564024
[ "MIT" ]
lennonalvesdias/BigBang
RecursosCompartilhados/4 - Infra/RecursosCompartilhados.Dados/Contexto/BaseContexto.cs
984
C#
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Razor.TagHelpers; namespace GovUk.Frontend.AspNetCore.TagHelpers { [HtmlTargetElement("govuk-character-count")] [RestrictChildren("govuk-character-count-label", "govuk-character-count-hint", "govuk-character-count-error-message", "govuk-character-count-element")] public class CharacterCountTagHelper : TextAreaTagHelper { private const string MaxLengthAttributeName = "max-length"; private const string MaxWordsLengthAttributeName = "max-words"; private const string ThresholdAttributeName = "threshold"; public CharacterCountTagHelper(IGovUkHtmlGenerator htmlGenerator, IModelHelper modelHelper) : base(htmlGenerator, modelHelper) { } [HtmlAttributeName(MaxLengthAttributeName)] public int? MaxLength { get; set; } [HtmlAttributeName(MaxWordsLengthAttributeName)] public int? MaxWords { get; set; } [HtmlAttributeName(ThresholdAttributeName)] public decimal? Threshold { get; set; } public override Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { if (MaxLength.HasValue && MaxWords.HasValue) { throw new InvalidOperationException($"The '{MaxLengthAttributeName}' and '{MaxWordsLengthAttributeName}' attributes are mutually exclusive."); } else if (!MaxLength.HasValue && !MaxWords.HasValue) { throw new InvalidOperationException($"One of the '{MaxLengthAttributeName}' and '{MaxWordsLengthAttributeName}' attributes must be specified."); } if (Threshold.HasValue && (Threshold.Value < 0 || Threshold.Value > 100)) { throw new InvalidOperationException($"The '{ThresholdAttributeName}' attribute is invalid."); } return base.ProcessAsync(context, output); } protected override TagBuilder GenerateElement( TagHelperContext context, FormGroupBuilder builder, FormGroupElementContext elementContext) { var textArea = base.GenerateElement(context, builder, elementContext); textArea.AddCssClass("govuk-js-character-count"); return textArea; } protected override TagBuilder GenerateContent(TagHelperContext context, FormGroupBuilder builder) { var generated = base.GenerateContent(context, builder); return Generator.GenerateCharacterCount(ResolvedId, MaxLength, MaxWords, Threshold, generated); } } [HtmlTargetElement("govuk-character-count-label", ParentTag = "govuk-character-count")] public class CharacterCountLabelTagHelper : TextAreaLabelTagHelper { } [HtmlTargetElement("govuk-character-count-hint", ParentTag = "govuk-character-count")] public class CharacterCountHintTagHelper : TextAreaHintTagHelper { } [HtmlTargetElement("govuk-character-count-error-message", ParentTag = "govuk-character-count")] public class CharacterCountErrorMessageTagHelper : TextAreaErrorMessageTagHelper { } [HtmlTargetElement("govuk-character-count-element", ParentTag = "govuk-character-count")] public class CharacterCountElementTagHelper : TextAreaElementTagHelper { } }
39.965116
160
0.687227
[ "MIT" ]
gunndabad/govuk-frontend-aspnetcore
src/GovUk.Frontend.AspNetCore/TagHelpers/CharacterCountTagHelper.cs
3,439
C#
using System; using System.Globalization; using System.IO; using stdlibXtf.Common; namespace stdlibXtf.Packets { /// <summary> /// Define an annotation data packet. /// </summary> public class Notes : IPacket { #region IPacket implementation private Byte _HeaderType; private ushort _MagicNumber; private byte _SubChannelNumber; private ushort _NumberChannelsToFollow; private uint _NumberBytesThisRecord; private DateTime _PacketTime; /// <summary> /// Gets the type of the packet header. /// </summary> public Byte HeaderType { get { return _HeaderType; } } /// <summary> /// Gets the number that identify the correct start of the packet. /// </summary> public ushort MagicNumber { get { return _MagicNumber; } } /// <summary> /// Gets the index number of which channels this packet are referred. /// </summary> public byte SubChannelNumber { get { return _SubChannelNumber; } } /// <summary> /// Gets the number of channels that follow this packet. /// </summary> public ushort NumberChannelsToFollow { get { return _NumberChannelsToFollow; } } /// <summary> /// Total byte count for this packet, including the header and the data if available. /// </summary> public uint NumberBytesThisRecord { get { return _NumberBytesThisRecord; } } /// <summary> /// Gets the packet recording time. /// </summary> public DateTime PacketTime { get { return _PacketTime; } } #endregion IPacket implementation #region private properties private String _Text; #endregion private properties #region public properties /// <summary> /// Gets the annotation text. /// The maximum size is of 200 characters. /// </summary> public String Text { get { return _Text; } //set //{ // if (String.IsNullOrEmpty(value)) { value = " "; } // if (value.Length > 200) { _Text = value.Substring(0, 200); } //} } #endregion public properties #region constructors /// <summary> /// Initializes a new instance of the Notes class that has default zero values. /// </summary> public Notes() { _HeaderType = 1; _MagicNumber = 0; _SubChannelNumber = 0; _NumberChannelsToFollow = 0; _NumberBytesThisRecord = 256; _PacketTime = DateTime.MinValue; _Text = " "; } /// <summary> /// Initializes a new instance of the Notes class that contain the values extracted from the given byte array. /// </summary> /// <param name="byteArray">The size of array need to be at least of 256 bytes.</param> public Notes(Byte[] byteArray) { _HeaderType = 1; _MagicNumber = 0; _SubChannelNumber = 0; _NumberChannelsToFollow = 0; _NumberBytesThisRecord = 256; _PacketTime = DateTime.MinValue; _Text = " "; UInt16 chkNumber; UInt16 Year; Byte Month; Byte Day; Byte Hour; Byte Minutes; Byte Seconds; //UInt32 MSeconds; String TimeString; DateTime outTime; using (BinaryReader dp = new BinaryReader(ArrayToStream.BytesToMemory(byteArray))) { if (byteArray.Length >= 256) { chkNumber = dp.ReadUInt16(); // 0-1 if (chkNumber == XtfDocument.MagicNumber) { dp.ReadByte(); //HeaderType 2 _SubChannelNumber = dp.ReadByte(); // 3 _NumberChannelsToFollow = dp.ReadUInt16(); // 4-5 dp.ReadUInt16(); //Unused 6-7 dp.ReadUInt16(); //Unused 8-9 _NumberBytesThisRecord = dp.ReadUInt32(); // 10-11-12-13 //Read the ping time values Year = dp.ReadUInt16(); // 14-15 Month = dp.ReadByte(); // 16 Day = dp.ReadByte(); // 17 Hour = dp.ReadByte(); // 18 Minutes = dp.ReadByte(); // 19 Seconds = dp.ReadByte(); // 20 //MSeconds = dp.ReadUInt32(); //Compose the ping time value TimeString = Year.ToString("0000", CultureInfo.InvariantCulture); TimeString = TimeString + "-" + Month.ToString("00", CultureInfo.InvariantCulture); TimeString = TimeString + "-" + Day.ToString("00", CultureInfo.InvariantCulture); TimeString = TimeString + "-" + Hour.ToString("00", CultureInfo.InvariantCulture); TimeString = TimeString + "-" + Minutes.ToString("00", CultureInfo.InvariantCulture); TimeString = TimeString + "-" + Seconds.ToString("00", CultureInfo.InvariantCulture); //TimeString = TimeString + "-" + MSeconds.ToString("000000", CultureInfo.InvariantCulture); if (DateTime.TryParseExact(TimeString, "yyyy-MM-dd-HH-mm-ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out outTime)) { _PacketTime = outTime; } else { _PacketTime = DateTime.MinValue; } dp.ReadBytes(35); // Unused 21 to 55 _Text = new String(dp.ReadChars(200)); // 56 to 255 } } } } #endregion constructors } }
36.689024
150
0.520691
[ "MIT" ]
jaksg82/stdlibXtf
Packets/Notes.cs
6,019
C#
using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using UnityEngine.Rendering; using UnityEngine.SceneManagement; namespace UnityEngine { public sealed class Resources { internal static T[] ConvertObjects<T>( Object[] rawObjects ) where T : Object { if( rawObjects == null ) { return null; } T[] array = new T[ rawObjects.Length ]; for( int i = 0 ; i < array.Length ; i++ ) { array[ i ] = (T)rawObjects[ i ]; } return array; } public static extern Object[] FindObjectsOfTypeAll( Type type ); public static T[] FindObjectsOfTypeAll<T>() where T : Object { return ConvertObjects<T>( FindObjectsOfTypeAll( typeof( T ) ) ); } public static Object Load( string path ) { return Load( path, typeof( Object ) ); } public static T Load<T>( string path ) where T : Object { return (T)Load( path, typeof( T ) ); } public static extern Object Load( string path, Type systemTypeInstance ); public static ResourceRequest LoadAsync( string path ) { return LoadAsync( path, typeof( Object ) ); } public static ResourceRequest LoadAsync<T>( string path ) where T : Object { return LoadAsync( path, typeof( T ) ); } public static extern ResourceRequest LoadAsync( string path, Type type ); public static extern Object[] LoadAll( string path, Type systemTypeInstance ); public static Object[] LoadAll( string path ) { return LoadAll( path, typeof( Object ) ); } public static T[] LoadAll<T>( string path ) where T : Object { return ConvertObjects<T>( LoadAll( path, typeof( T ) ) ); } public static extern Object GetBuiltinResource( Type type, string path ); public static T GetBuiltinResource<T>( string path ) where T : Object { return (T)GetBuiltinResource( typeof( T ), path ); } public static extern void UnloadAsset( Object assetToUnload ); public static extern AsyncOperation UnloadUnusedAssets(); } }
26.825581
84
0.61075
[ "MIT" ]
Divers102/XUnity.AutoTranslator
src/UnityEngine/Resources.cs
2,309
C#
using System.IO; using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class AISubActionSetEquipWeaponsUtils : IScriptable { public AISubActionSetEquipWeaponsUtils(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
22.666667
118
0.747059
[ "MIT" ]
Eingin/CP77Tools
CP77.CR2W/Types/cp77/AISubActionSetEquipWeaponsUtils.cs
326
C#
//------------------------------------------------------------------------------ // <copyright file="SqlConnectionString.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // <owner current="true" primary="true">[....]</owner> // <owner current="true" primary="false">[....]</owner> //------------------------------------------------------------------------------ namespace System.Data.SqlClient { using System; using System.Collections; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Globalization; using System.IO; using System.Security; using System.Security.Permissions; using System.Text; using System.Runtime.Versioning; internal sealed class SqlConnectionString : DbConnectionOptions { // instances of this class are intended to be immutable, i.e readonly // used by pooling classes so it is much easier to verify correctness // when not worried about the class being modified during execution internal static class DEFAULT { internal const ApplicationIntent ApplicationIntent = DbConnectionStringDefaults.ApplicationIntent; internal const string Application_Name = TdsEnums.SQL_PROVIDER_NAME; internal const bool Asynchronous = false; internal const string AttachDBFilename = ""; internal const int Connect_Timeout = ADP.DefaultConnectionTimeout; internal const bool Connection_Reset = true; internal const bool Context_Connection = false; internal const string Current_Language = ""; internal const string Data_Source = ""; internal const bool Encrypt = false; internal const bool Enlist = true; internal const string FailoverPartner = ""; internal const string Initial_Catalog = ""; internal const bool Integrated_Security = false; internal const int Load_Balance_Timeout = 0; // default of 0 means don't use internal const bool MARS = false; internal const int Max_Pool_Size = 100; internal const int Min_Pool_Size = 0; internal const bool MultiSubnetFailover = DbConnectionStringDefaults.MultiSubnetFailover; internal const string Network_Library = ""; internal const int Packet_Size = 8000; internal const string Password = ""; internal const bool Persist_Security_Info = false; internal const bool Pooling = true; internal const bool TrustServerCertificate = false; internal const string Type_System_Version = ""; internal const string User_ID = ""; internal const bool User_Instance = false; internal const bool Replication = false; internal const int Connect_Retry_Count = 1; internal const int Connect_Retry_Interval = 10; internal static readonly SqlAuthenticationMethod Authentication = SqlAuthenticationMethod.NotSpecified; internal static readonly SqlConnectionColumnEncryptionSetting ColumnEncryptionSetting = SqlConnectionColumnEncryptionSetting.Disabled; } // SqlConnection ConnectionString Options // keys must be lowercase! internal static class KEY { internal const string ApplicationIntent = "applicationintent"; internal const string Application_Name = "application name"; internal const string AsynchronousProcessing = "asynchronous processing"; internal const string AttachDBFilename = "attachdbfilename"; internal const string ColumnEncryptionSetting = "column encryption setting"; internal const string Connect_Timeout = "connect timeout"; internal const string Connection_Reset = "connection reset"; internal const string Context_Connection = "context connection"; internal const string Current_Language = "current language"; internal const string Data_Source = "data source"; internal const string Encrypt = "encrypt"; internal const string Enlist = "enlist"; internal const string FailoverPartner = "failover partner"; internal const string Initial_Catalog = "initial catalog"; internal const string Integrated_Security = "integrated security"; internal const string Load_Balance_Timeout = "load balance timeout"; internal const string MARS = "multipleactiveresultsets"; internal const string Max_Pool_Size = "max pool size"; internal const string Min_Pool_Size = "min pool size"; internal const string MultiSubnetFailover = "multisubnetfailover"; internal const string Network_Library = "network library"; internal const string Packet_Size = "packet size"; internal const string Password = "password"; internal const string Persist_Security_Info = "persist security info"; internal const string Pooling = "pooling"; internal const string TransactionBinding = "transaction binding"; internal const string TrustServerCertificate = "trustservercertificate"; internal const string Type_System_Version = "type system version"; internal const string User_ID = "user id"; internal const string User_Instance = "user instance"; internal const string Workstation_Id = "workstation id"; internal const string Replication = "replication"; internal const string Connect_Retry_Count = "connectretrycount"; internal const string Connect_Retry_Interval = "connectretryinterval"; internal const string Authentication = "authentication"; } // Constant for the number of duplicate options in the connnection string private static class SYNONYM { // application name internal const string APP = "app"; internal const string Async = "async"; // attachDBFilename internal const string EXTENDED_PROPERTIES = "extended properties"; internal const string INITIAL_FILE_NAME = "initial file name"; // connect timeout internal const string CONNECTION_TIMEOUT = "connection timeout"; internal const string TIMEOUT = "timeout"; // current language internal const string LANGUAGE = "language"; // data source internal const string ADDR = "addr"; internal const string ADDRESS = "address"; internal const string SERVER = "server"; internal const string NETWORK_ADDRESS = "network address"; // initial catalog internal const string DATABASE = "database"; // integrated security internal const string TRUSTED_CONNECTION = "trusted_connection"; // load balance timeout internal const string Connection_Lifetime = "connection lifetime"; // network library internal const string NET = "net"; internal const string NETWORK = "network"; // password internal const string Pwd = "pwd"; // persist security info internal const string PERSISTSECURITYINFO = "persistsecurityinfo"; // user id internal const string UID = "uid"; internal const string User = "user"; // workstation id internal const string WSID = "wsid"; // make sure to update SynonymCount value below when adding or removing synonyms } internal const int SynonymCount = 21; // the following are all inserted as keys into the _netlibMapping hash internal static class NETLIB { internal const string AppleTalk = "dbmsadsn"; internal const string BanyanVines = "dbmsvinn"; internal const string IPXSPX = "dbmsspxn"; internal const string Multiprotocol = "dbmsrpcn"; internal const string NamedPipes = "dbnmpntw"; internal const string SharedMemory = "dbmslpcn"; internal const string TCPIP = "dbmssocn"; internal const string VIA = "dbmsgnet"; } internal enum TypeSystem { Latest = 2008, SQLServer2000 = 2000, SQLServer2005 = 2005, SQLServer2008 = 2008, SQLServer2012 = 2012, } internal static class TYPESYSTEMVERSION { internal const string Latest = "Latest"; internal const string SQL_Server_2000 = "SQL Server 2000"; internal const string SQL_Server_2005 = "SQL Server 2005"; internal const string SQL_Server_2008 = "SQL Server 2008"; internal const string SQL_Server_2012 = "SQL Server 2012"; } internal enum TransactionBindingEnum { ImplicitUnbind, ExplicitUnbind } internal static class TRANSACIONBINDING { internal const string ImplicitUnbind = "Implicit Unbind"; internal const string ExplicitUnbind = "Explicit Unbind"; } static private Hashtable _sqlClientSynonyms; static private Hashtable _netlibMapping; private readonly bool _integratedSecurity; private readonly bool _connectionReset; private readonly bool _contextConnection; private readonly bool _encrypt; private readonly bool _trustServerCertificate; private readonly bool _enlist; private readonly bool _mars; private readonly bool _persistSecurityInfo; private readonly bool _pooling; private readonly bool _replication; private readonly bool _userInstance; private readonly bool _multiSubnetFailover; private readonly SqlAuthenticationMethod _authType; private readonly SqlConnectionColumnEncryptionSetting _columnEncryptionSetting; private readonly int _connectTimeout; private readonly int _loadBalanceTimeout; private readonly int _maxPoolSize; private readonly int _minPoolSize; private readonly int _packetSize; private readonly int _connectRetryCount; private readonly int _connectRetryInterval; private readonly ApplicationIntent _applicationIntent; private readonly string _applicationName; private readonly string _attachDBFileName; private readonly string _currentLanguage; private readonly string _dataSource; private readonly string _localDBInstance; // created based on datasource, set to NULL if datasource is not LocalDB private readonly string _failoverPartner; private readonly string _initialCatalog; private readonly string _password; private readonly string _userID; private readonly string _networkLibrary; private readonly string _workstationId; private readonly TypeSystem _typeSystemVersion; private readonly Version _typeSystemAssemblyVersion; private static readonly Version constTypeSystemAsmVersion10 = new Version("10.0.0.0"); private static readonly Version constTypeSystemAsmVersion11 = new Version("11.0.0.0"); private readonly TransactionBindingEnum _transactionBinding; private readonly string _expandedAttachDBFilename; // expanded during construction so that CreatePermissionSet & Expand are consistent // SxS: reading Software\\Microsoft\\MSSQLServer\\Client\\SuperSocketNetLib\Encrypt value from registry [ResourceExposure(ResourceScope.None)] [ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)] internal SqlConnectionString(string connectionString) : base(connectionString, GetParseSynonyms(), false) { bool runningInProc = InOutOfProcHelper.InProc; _integratedSecurity = ConvertValueToIntegratedSecurity(); ConvertValueToBoolean(KEY.AsynchronousProcessing, DEFAULT.Asynchronous); // while we don't use it anymore, we still need to verify it is true/false // SQLPT 41700: Ignore ResetConnection=False (still validate the keyword/value) _connectionReset = ConvertValueToBoolean(KEY.Connection_Reset, DEFAULT.Connection_Reset); _contextConnection = ConvertValueToBoolean(KEY.Context_Connection, DEFAULT.Context_Connection); _encrypt = ConvertValueToEncrypt(); _enlist = ConvertValueToBoolean(KEY.Enlist, ADP.IsWindowsNT); _mars = ConvertValueToBoolean(KEY.MARS, DEFAULT.MARS); _persistSecurityInfo = ConvertValueToBoolean(KEY.Persist_Security_Info, DEFAULT.Persist_Security_Info); _pooling = ConvertValueToBoolean(KEY.Pooling, DEFAULT.Pooling); _replication = ConvertValueToBoolean(KEY.Replication, DEFAULT.Replication); _userInstance = ConvertValueToBoolean(KEY.User_Instance, DEFAULT.User_Instance); _multiSubnetFailover = ConvertValueToBoolean(KEY.MultiSubnetFailover, DEFAULT.MultiSubnetFailover); _connectTimeout = ConvertValueToInt32(KEY.Connect_Timeout, DEFAULT.Connect_Timeout); _loadBalanceTimeout = ConvertValueToInt32(KEY.Load_Balance_Timeout, DEFAULT.Load_Balance_Timeout); _maxPoolSize = ConvertValueToInt32(KEY.Max_Pool_Size, DEFAULT.Max_Pool_Size); _minPoolSize = ConvertValueToInt32(KEY.Min_Pool_Size, DEFAULT.Min_Pool_Size); _packetSize = ConvertValueToInt32(KEY.Packet_Size, DEFAULT.Packet_Size); _connectRetryCount = ConvertValueToInt32(KEY.Connect_Retry_Count, DEFAULT.Connect_Retry_Count); _connectRetryInterval = ConvertValueToInt32(KEY.Connect_Retry_Interval, DEFAULT.Connect_Retry_Interval); _applicationIntent = ConvertValueToApplicationIntent(); _applicationName = ConvertValueToString(KEY.Application_Name, DEFAULT.Application_Name); _attachDBFileName = ConvertValueToString(KEY.AttachDBFilename, DEFAULT.AttachDBFilename); _currentLanguage = ConvertValueToString(KEY.Current_Language, DEFAULT.Current_Language); _dataSource = ConvertValueToString(KEY.Data_Source, DEFAULT.Data_Source); _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource); _failoverPartner = ConvertValueToString(KEY.FailoverPartner, DEFAULT.FailoverPartner); _initialCatalog = ConvertValueToString(KEY.Initial_Catalog, DEFAULT.Initial_Catalog); _networkLibrary = ConvertValueToString(KEY.Network_Library, null); _password = ConvertValueToString(KEY.Password, DEFAULT.Password); _trustServerCertificate = ConvertValueToBoolean(KEY.TrustServerCertificate, DEFAULT.TrustServerCertificate); _authType = ConvertValueToAuthenticationType(); _columnEncryptionSetting = ConvertValueToColumnEncryptionSetting(); // Temporary string - this value is stored internally as an enum. string typeSystemVersionString = ConvertValueToString(KEY.Type_System_Version, null); string transactionBindingString = ConvertValueToString(KEY.TransactionBinding, null); _userID = ConvertValueToString(KEY.User_ID, DEFAULT.User_ID); _workstationId = ConvertValueToString(KEY.Workstation_Id, null); if (_contextConnection) { // We have to be running in the engine for you to request a // context connection. if (!runningInProc) { throw SQL.ContextUnavailableOutOfProc(); } // When using a context connection, we need to ensure that no // other connection string keywords are specified. foreach (DictionaryEntry entry in Parsetable) { if ((string) entry.Key != KEY.Context_Connection && (string) entry.Key != KEY.Type_System_Version) { throw SQL.ContextAllowsLimitedKeywords(); } } } if (!_encrypt) { // Support legacy registry encryption settings const string folder = "Software\\Microsoft\\MSSQLServer\\Client\\SuperSocketNetLib"; const string value = "Encrypt"; Object obj = ADP.LocalMachineRegistryValue(folder, value); if ((obj is Int32) && (1 == (int)obj)) { // If the registry key exists _encrypt = true; } } if (_loadBalanceTimeout < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Load_Balance_Timeout); } if (_connectTimeout < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Connect_Timeout); } if (_maxPoolSize < 1) { throw ADP.InvalidConnectionOptionValue(KEY.Max_Pool_Size); } if (_minPoolSize < 0) { throw ADP.InvalidConnectionOptionValue(KEY.Min_Pool_Size); } if (_maxPoolSize < _minPoolSize) { throw ADP.InvalidMinMaxPoolSizeValues(); } if ((_packetSize < TdsEnums.MIN_PACKET_SIZE) || (TdsEnums.MAX_PACKET_SIZE < _packetSize)) { throw SQL.InvalidPacketSizeValue(); } if (null != _networkLibrary) { // MDAC 83525 string networkLibrary = _networkLibrary.Trim().ToLower(CultureInfo.InvariantCulture); Hashtable netlib = NetlibMapping(); if (!netlib.ContainsKey(networkLibrary)) { throw ADP.InvalidConnectionOptionValue(KEY.Network_Library); } _networkLibrary = (string) netlib[networkLibrary]; } else { _networkLibrary = DEFAULT.Network_Library; } ValidateValueLength(_applicationName, TdsEnums.MAXLEN_APPNAME, KEY.Application_Name); ValidateValueLength(_currentLanguage , TdsEnums.MAXLEN_LANGUAGE, KEY.Current_Language); ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source); ValidateValueLength(_failoverPartner, TdsEnums.MAXLEN_SERVERNAME, KEY.FailoverPartner); ValidateValueLength(_initialCatalog, TdsEnums.MAXLEN_DATABASE, KEY.Initial_Catalog); ValidateValueLength(_password, TdsEnums.MAXLEN_PASSWORD, KEY.Password); ValidateValueLength(_userID, TdsEnums.MAXLEN_USERNAME, KEY.User_ID); if (null != _workstationId) { ValidateValueLength(_workstationId, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id); } if (!String.Equals(DEFAULT.FailoverPartner, _failoverPartner, StringComparison.OrdinalIgnoreCase)) { // fail-over partner is set if (_multiSubnetFailover) { throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: false, internalConnection: null); } if (String.Equals(DEFAULT.Initial_Catalog, _initialCatalog, StringComparison.OrdinalIgnoreCase)) { throw ADP.MissingConnectionOptionValue(KEY.FailoverPartner, KEY.Initial_Catalog); } } // expand during construction so that CreatePermissionSet and Expand are consistent string datadir = null; _expandedAttachDBFilename = ExpandDataDirectory(KEY.AttachDBFilename, _attachDBFileName, ref datadir); if (null != _expandedAttachDBFilename) { if (0 <= _expandedAttachDBFilename.IndexOf('|')) { throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename); } ValidateValueLength(_expandedAttachDBFilename, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename); if (_localDBInstance == null) { // fail fast to verify LocalHost when using |DataDirectory| // still must check again at connect time string host = _dataSource; string protocol = _networkLibrary; TdsParserStaticMethods.AliasRegistryLookup(ref host, ref protocol); VerifyLocalHostAndFixup(ref host, true, false /*don't fix-up*/); } } else if (0 <= _attachDBFileName.IndexOf('|')) { throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename); } else { ValidateValueLength(_attachDBFileName, TdsEnums.MAXLEN_ATTACHDBFILE, KEY.AttachDBFilename); } _typeSystemAssemblyVersion = constTypeSystemAsmVersion10; if (true == _userInstance && !ADP.IsEmpty(_failoverPartner)) { throw SQL.UserInstanceFailoverNotCompatible(); } if (ADP.IsEmpty(typeSystemVersionString)) { typeSystemVersionString = DbConnectionStringDefaults.TypeSystemVersion; } if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.Latest, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.Latest; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2000, StringComparison.OrdinalIgnoreCase)) { if (_contextConnection) { throw SQL.ContextAllowsOnlyTypeSystem2005(); } _typeSystemVersion = TypeSystem.SQLServer2000; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2005, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2005; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2008, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2008; } else if (typeSystemVersionString.Equals(TYPESYSTEMVERSION.SQL_Server_2012, StringComparison.OrdinalIgnoreCase)) { _typeSystemVersion = TypeSystem.SQLServer2012; _typeSystemAssemblyVersion = constTypeSystemAsmVersion11; } else { throw ADP.InvalidConnectionOptionValue(KEY.Type_System_Version); } if (ADP.IsEmpty(transactionBindingString)) { transactionBindingString = DbConnectionStringDefaults.TransactionBinding; } if (transactionBindingString.Equals(TRANSACIONBINDING.ImplicitUnbind, StringComparison.OrdinalIgnoreCase)) { _transactionBinding = TransactionBindingEnum.ImplicitUnbind; } else if (transactionBindingString.Equals(TRANSACIONBINDING.ExplicitUnbind, StringComparison.OrdinalIgnoreCase)) { _transactionBinding = TransactionBindingEnum.ExplicitUnbind; } else { throw ADP.InvalidConnectionOptionValue(KEY.TransactionBinding); } if (_applicationIntent == ApplicationIntent.ReadOnly && !String.IsNullOrEmpty(_failoverPartner)) throw SQL.ROR_FailoverNotSupportedConnString(); if ((_connectRetryCount<0) || (_connectRetryCount>255)) { throw ADP.InvalidConnectRetryCountValue(); } if ((_connectRetryInterval < 1) || (_connectRetryInterval > 60)) { throw ADP.InvalidConnectRetryIntervalValue(); } if (Authentication != SqlAuthenticationMethod.NotSpecified && _integratedSecurity == true) { throw SQL.AuthenticationAndIntegratedSecurity(); } if (Authentication == SqlClient.SqlAuthenticationMethod.ActiveDirectoryIntegrated && (HasUserIdKeyword || HasPasswordKeyword)) { throw SQL.IntegratedWithUserIDAndPassword(); } } // This c-tor is used to create SSE and user instance connection strings when user instance is set to true // internal SqlConnectionString(SqlConnectionString connectionOptions, string dataSource, bool userInstance, bool? setEnlistValue) : base(connectionOptions) { _integratedSecurity = connectionOptions._integratedSecurity; _connectionReset = connectionOptions._connectionReset; _contextConnection = connectionOptions._contextConnection; _encrypt = connectionOptions._encrypt; if (setEnlistValue.HasValue) { _enlist = setEnlistValue.Value; } else { _enlist = connectionOptions._enlist; } _mars = connectionOptions._mars; _persistSecurityInfo = connectionOptions._persistSecurityInfo; _pooling = connectionOptions._pooling; _replication = connectionOptions._replication; _userInstance = userInstance; _connectTimeout = connectionOptions._connectTimeout; _loadBalanceTimeout = connectionOptions._loadBalanceTimeout; _maxPoolSize = connectionOptions._maxPoolSize; _minPoolSize = connectionOptions._minPoolSize; _multiSubnetFailover = connectionOptions._multiSubnetFailover; _packetSize = connectionOptions._packetSize; _applicationName = connectionOptions._applicationName; _attachDBFileName = connectionOptions._attachDBFileName; _currentLanguage = connectionOptions._currentLanguage; _dataSource = dataSource; _localDBInstance = LocalDBAPI.GetLocalDbInstanceNameFromServerName(_dataSource); _failoverPartner = connectionOptions._failoverPartner; _initialCatalog = connectionOptions._initialCatalog; _password = connectionOptions._password; _userID = connectionOptions._userID; _networkLibrary = connectionOptions._networkLibrary; _workstationId = connectionOptions._workstationId; _expandedAttachDBFilename = connectionOptions._expandedAttachDBFilename; _typeSystemVersion = connectionOptions._typeSystemVersion; _typeSystemAssemblyVersion =connectionOptions._typeSystemAssemblyVersion; _transactionBinding = connectionOptions._transactionBinding; _applicationIntent = connectionOptions._applicationIntent; _connectRetryCount = connectionOptions._connectRetryCount; _connectRetryInterval = connectionOptions._connectRetryInterval; _authType = connectionOptions._authType; _columnEncryptionSetting = connectionOptions._columnEncryptionSetting; ValidateValueLength(_dataSource, TdsEnums.MAXLEN_SERVERNAME, KEY.Data_Source); } internal bool IntegratedSecurity { get { return _integratedSecurity; } } // We always initialize in Async mode so that both synchronous and asynchronous methods // will work. In the future we can deprecate the keyword entirely. internal bool Asynchronous { get { return true; } } // SQLPT 41700: Ignore ResetConnection=False, always reset the connection for security internal bool ConnectionReset { get { return true; } } internal bool ContextConnection { get { return _contextConnection; } } // internal bool EnableUdtDownload { get { return _enableUdtDownload;} } internal bool Encrypt { get { return _encrypt; } } internal bool TrustServerCertificate { get { return _trustServerCertificate; } } internal bool Enlist { get { return _enlist; } } internal bool MARS { get { return _mars; } } internal bool MultiSubnetFailover { get { return _multiSubnetFailover; } } internal SqlAuthenticationMethod Authentication { get { return _authType; } } internal SqlConnectionColumnEncryptionSetting ColumnEncryptionSetting { get { return _columnEncryptionSetting; } } internal bool PersistSecurityInfo { get { return _persistSecurityInfo; } } internal bool Pooling { get { return _pooling; } } internal bool Replication { get { return _replication; } } internal bool UserInstance { get { return _userInstance; } } internal int ConnectTimeout { get { return _connectTimeout; } } internal int LoadBalanceTimeout { get { return _loadBalanceTimeout; } } internal int MaxPoolSize { get { return _maxPoolSize; } } internal int MinPoolSize { get { return _minPoolSize; } } internal int PacketSize { get { return _packetSize; } } internal int ConnectRetryCount { get { return _connectRetryCount; } } internal int ConnectRetryInterval { get { return _connectRetryInterval; } } internal ApplicationIntent ApplicationIntent { get { return _applicationIntent; } } internal string ApplicationName { get { return _applicationName; } } internal string AttachDBFilename { get { return _attachDBFileName; } } internal string CurrentLanguage { get { return _currentLanguage; } } internal string DataSource { get { return _dataSource; } } internal string LocalDBInstance { get { return _localDBInstance; } } internal string FailoverPartner { get { return _failoverPartner; } } internal string InitialCatalog { get { return _initialCatalog; } } internal string NetworkLibrary { get { return _networkLibrary; } } internal string Password { get { return _password; } } internal string UserID { get { return _userID; } } internal string WorkstationId { get { return _workstationId; } } internal TypeSystem TypeSystemVersion { get { return _typeSystemVersion; } } internal Version TypeSystemAssemblyVersion { get { return _typeSystemAssemblyVersion; } } internal TransactionBindingEnum TransactionBinding { get { return _transactionBinding; } } internal bool EnforceLocalHost { get { // so tdsparser.connect can determine if SqlConnection.UserConnectionOptions // needs to enfoce local host after datasource alias lookup return (null != _expandedAttachDBFilename) && (null == _localDBInstance); } } protected internal override System.Security.PermissionSet CreatePermissionSet() { System.Security.PermissionSet permissionSet = new System.Security.PermissionSet(System.Security.Permissions.PermissionState.None); permissionSet.AddPermission(new SqlClientPermission(this)); return permissionSet; } protected internal override string Expand() { if (null != _expandedAttachDBFilename) { return ExpandKeyword(KEY.AttachDBFilename, _expandedAttachDBFilename); } else { return base.Expand(); } } private static bool CompareHostName(ref string host, string name, bool fixup) { // same computer name or same computer name + "\named instance" bool equal = false; if (host.Equals(name, StringComparison.OrdinalIgnoreCase)) { if (fixup) { host = "."; } equal = true; } else if (host.StartsWith(name+@"\", StringComparison.OrdinalIgnoreCase)) { if (fixup) { host = "." + host.Substring(name.Length); } equal = true; } return equal; } // this hashtable is meant to be read-only translation of parsed string // keywords/synonyms to a known keyword string internal static Hashtable GetParseSynonyms() { Hashtable hash = _sqlClientSynonyms; if (null == hash) { hash = new Hashtable(SqlConnectionStringBuilder.KeywordsCount + SynonymCount); hash.Add(KEY.ApplicationIntent, KEY.ApplicationIntent); hash.Add(KEY.Application_Name, KEY.Application_Name); hash.Add(KEY.AsynchronousProcessing, KEY.AsynchronousProcessing); hash.Add(KEY.AttachDBFilename, KEY.AttachDBFilename); hash.Add(KEY.Connect_Timeout, KEY.Connect_Timeout); hash.Add(KEY.Connection_Reset, KEY.Connection_Reset); hash.Add(KEY.Context_Connection, KEY.Context_Connection); hash.Add(KEY.Current_Language, KEY.Current_Language); hash.Add(KEY.Data_Source, KEY.Data_Source); hash.Add(KEY.Encrypt, KEY.Encrypt); hash.Add(KEY.Enlist, KEY.Enlist); hash.Add(KEY.FailoverPartner, KEY.FailoverPartner); hash.Add(KEY.Initial_Catalog, KEY.Initial_Catalog); hash.Add(KEY.Integrated_Security, KEY.Integrated_Security); hash.Add(KEY.Load_Balance_Timeout, KEY.Load_Balance_Timeout); hash.Add(KEY.MARS, KEY.MARS); hash.Add(KEY.Max_Pool_Size, KEY.Max_Pool_Size); hash.Add(KEY.Min_Pool_Size, KEY.Min_Pool_Size); hash.Add(KEY.MultiSubnetFailover, KEY.MultiSubnetFailover); hash.Add(KEY.Network_Library, KEY.Network_Library); hash.Add(KEY.Packet_Size, KEY.Packet_Size); hash.Add(KEY.Password, KEY.Password); hash.Add(KEY.Persist_Security_Info, KEY.Persist_Security_Info); hash.Add(KEY.Pooling, KEY.Pooling); hash.Add(KEY.Replication, KEY.Replication); hash.Add(KEY.TrustServerCertificate, KEY.TrustServerCertificate); hash.Add(KEY.TransactionBinding, KEY.TransactionBinding); hash.Add(KEY.Type_System_Version, KEY.Type_System_Version); hash.Add(KEY.ColumnEncryptionSetting, KEY.ColumnEncryptionSetting); hash.Add(KEY.User_ID, KEY.User_ID); hash.Add(KEY.User_Instance, KEY.User_Instance); hash.Add(KEY.Workstation_Id, KEY.Workstation_Id); hash.Add(KEY.Connect_Retry_Count, KEY.Connect_Retry_Count); hash.Add(KEY.Connect_Retry_Interval, KEY.Connect_Retry_Interval); hash.Add(KEY.Authentication, KEY.Authentication); hash.Add(SYNONYM.APP, KEY.Application_Name); hash.Add(SYNONYM.Async, KEY.AsynchronousProcessing); hash.Add(SYNONYM.EXTENDED_PROPERTIES, KEY.AttachDBFilename); hash.Add(SYNONYM.INITIAL_FILE_NAME, KEY.AttachDBFilename); hash.Add(SYNONYM.CONNECTION_TIMEOUT, KEY.Connect_Timeout); hash.Add(SYNONYM.TIMEOUT, KEY.Connect_Timeout); hash.Add(SYNONYM.LANGUAGE, KEY.Current_Language); hash.Add(SYNONYM.ADDR, KEY.Data_Source); hash.Add(SYNONYM.ADDRESS, KEY.Data_Source); hash.Add(SYNONYM.NETWORK_ADDRESS, KEY.Data_Source); hash.Add(SYNONYM.SERVER, KEY.Data_Source); hash.Add(SYNONYM.DATABASE, KEY.Initial_Catalog); hash.Add(SYNONYM.TRUSTED_CONNECTION, KEY.Integrated_Security); hash.Add(SYNONYM.Connection_Lifetime, KEY.Load_Balance_Timeout); hash.Add(SYNONYM.NET, KEY.Network_Library); hash.Add(SYNONYM.NETWORK, KEY.Network_Library); hash.Add(SYNONYM.Pwd, KEY.Password); hash.Add(SYNONYM.PERSISTSECURITYINFO, KEY.Persist_Security_Info); hash.Add(SYNONYM.UID, KEY.User_ID); hash.Add(SYNONYM.User, KEY.User_ID); hash.Add(SYNONYM.WSID, KEY.Workstation_Id); Debug.Assert(SqlConnectionStringBuilder.KeywordsCount + SynonymCount == hash.Count, "incorrect initial ParseSynonyms size"); _sqlClientSynonyms = hash; } return hash; } internal string ObtainWorkstationId() { // If not supplied by the user, the default value is the MachineName // Note: In Longhorn you'll be able to rename a machine without // rebooting. Therefore, don't cache this machine name. string result = WorkstationId; if (null == result) { // permission to obtain Environment.MachineName is Asserted // since permission to open the connection has been granted // the information is shared with the server, but not directly with the user result = ADP.MachineName(); ValidateValueLength(result, TdsEnums.MAXLEN_HOSTNAME, KEY.Workstation_Id); } return result; } static internal Hashtable NetlibMapping() { const int NetLibCount = 8; Hashtable hash = _netlibMapping; if (null == hash) { hash = new Hashtable(NetLibCount); hash.Add(NETLIB.TCPIP, TdsEnums.TCP); hash.Add(NETLIB.NamedPipes, TdsEnums.NP); hash.Add(NETLIB.Multiprotocol, TdsEnums.RPC); hash.Add(NETLIB.BanyanVines, TdsEnums.BV); hash.Add(NETLIB.AppleTalk, TdsEnums.ADSP); hash.Add(NETLIB.IPXSPX, TdsEnums.SPX); hash.Add(NETLIB.VIA, TdsEnums.VIA); hash.Add(NETLIB.SharedMemory, TdsEnums.LPC); Debug.Assert(NetLibCount == hash.Count, "incorrect initial NetlibMapping size"); _netlibMapping = hash; } return hash; } static internal bool ValidProtocal (string protocal) { switch (protocal) { case TdsEnums.TCP : case TdsEnums.NP : case TdsEnums.VIA : case TdsEnums.LPC : return true; // case TdsEnums.RPC : Invalid Protocals // case TdsEnums.BV : // case TdsEnums.ADSP : // case TdsEnums.SPX : default : return false; } } private void ValidateValueLength (string value, int limit, string key) { if (limit < value.Length) { throw ADP.InvalidConnectionOptionValueLength(key, limit); } } internal static void VerifyLocalHostAndFixup(ref string host, bool enforceLocalHost, bool fixup) { if (ADP.IsEmpty(host)) { if (fixup) { host = "."; } } else if (!CompareHostName(ref host, @".", fixup) && !CompareHostName(ref host, @"(local)", fixup)) { // Fix-up completed in CompareHostName if return value true. string name = ADP.GetComputerNameDnsFullyQualified(); // i.e, machine.location.corp.company.com if (!CompareHostName(ref host, name, fixup)) { int separatorPos = name.IndexOf('.'); // to compare just 'machine' part if ((separatorPos <= 0) || !CompareHostName(ref host, name.Substring(0, separatorPos), fixup)) { if (enforceLocalHost) { throw ADP.InvalidConnectionOptionValue(KEY.AttachDBFilename); } } } } } internal System.Data.SqlClient.ApplicationIntent ConvertValueToApplicationIntent() { object value = base.Parsetable[KEY.ApplicationIntent]; if (value == null) { return DEFAULT.ApplicationIntent; } // when wrong value is used in the connection string provided to SqlConnection.ConnectionString or c-tor, // wrap Format and Overflow exceptions with Argument one, to be consistent with rest of the keyword types (like int and bool) try { return DbConnectionStringBuilderUtil.ConvertToApplicationIntent(KEY.ApplicationIntent, value); } catch (FormatException e) { throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e); } catch (OverflowException e) { throw ADP.InvalidConnectionOptionValue(KEY.ApplicationIntent, e); } // ArgumentException and other types are raised as is (no wrapping) } internal SqlAuthenticationMethod ConvertValueToAuthenticationType() { object value = base.Parsetable[KEY.Authentication]; string valStr = value as string; if (valStr == null) { return DEFAULT.Authentication; } try { return DbConnectionStringBuilderUtil.ConvertToAuthenticationType(KEY.Authentication, valStr); } catch (FormatException e) { throw ADP.InvalidConnectionOptionValue(KEY.Authentication, e); } catch (OverflowException e) { throw ADP.InvalidConnectionOptionValue(KEY.Authentication, e); } } /// <summary> /// Convert the value to SqlConnectionColumnEncryptionSetting. /// </summary> /// <returns></returns> internal SqlConnectionColumnEncryptionSetting ConvertValueToColumnEncryptionSetting() { object value = base.Parsetable[KEY.ColumnEncryptionSetting]; string valStr = value as string; if (valStr == null) { return DEFAULT.ColumnEncryptionSetting; } try { return DbConnectionStringBuilderUtil.ConvertToColumnEncryptionSetting(KEY.ColumnEncryptionSetting, valStr); } catch (FormatException e) { throw ADP.InvalidConnectionOptionValue(KEY.ColumnEncryptionSetting, e); } catch (OverflowException e) { throw ADP.InvalidConnectionOptionValue(KEY.ColumnEncryptionSetting, e); } } internal bool ConvertValueToEncrypt() { // If the Authentication keyword is provided, default to Encrypt=true; // otherwise keep old default for backwards compatibility object authValue = base.Parsetable[KEY.Authentication]; bool defaultEncryptValue = (authValue == null) ? DEFAULT.Encrypt : true; return ConvertValueToBoolean(KEY.Encrypt, defaultEncryptValue); } } }
54.282424
163
0.613067
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/fx/src/data/System/Data/SqlClient/SqlConnectionString.cs
44,783
C#
using System; using System.Collections.Generic; using System.Linq; using Gablarski.Audio; namespace Gablarski.Tests.Mocks.Audio { public class MockAudioCaptureProvider : IAudioCaptureProvider { private int frameSize = 256; public int FrameSize { get { return this.frameSize; } set { this.frameSize = value; } } #region Implementation of IAudioDeviceProvider /// <summary> /// Gets a listing of devices for this provider. /// </summary> /// <returns>A listing of devices to choose from.</returns> public IEnumerable<IAudioDevice> GetDevices() { return new[] { captureDevice }; } /// <summary> /// Gets the default device for this provider. /// </summary> public IAudioDevice DefaultDevice { get { return captureDevice; } } public IEnumerable<AudioFormat> SupportedFormats { get { return new[] { AudioFormat.Mono16bitLPCM, AudioFormat.Stereo16bitLPCM }; } } public int AvailableSampleCount { get { return this.frameSize; } } #endregion #region Implementation of IDisposable /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> /// <filterpriority>2</filterpriority> public void Dispose() { } #endregion #region Implementation of IAudioCaptureProvider public event EventHandler<SamplesAvailableEventArgs> SamplesAvailable; public IAudioDevice Device { get; set; } public bool IsCapturing { get; private set; } public void BeginCapture (AudioFormat format, int frameSize) { this.IsCapturing = true; } public void EndCapture() { this.IsCapturing = false; } public byte[] ReadSamples(int samples) { return new byte[samples]; } #endregion private readonly MockAudioDevice captureDevice = new MockAudioDevice ("MockCaptureDevice"); } }
20.357143
111
0.662155
[ "BSD-3-Clause" ]
ermau/Gablarski
src/Gablarski.Tests/Mocks/Audio/MockAudioCaptureProvider.cs
1,997
C#
using DBFileReaderLib.Attributes; namespace SpellWork.DBC.Structures { public sealed class SkillLineAbilityEntry { public long RaceMask; [Index(false)] public uint ID; public short SkillLine; public int Spell; public short MinSkillLineRank; public int ClassMask; public int SupercedesSpell; public sbyte AcquireMethod; public short TrivialSkillLineRankHigh; public short TrivialSkillLineRankLow; public sbyte Flags; public sbyte NumSkillUps; public short UniqueBit; public short TradeSkillCategoryID; public short SkillupSkillLineID; } }
27.2
46
0.666176
[ "MIT" ]
DerEnderman/SpellWork
SpellWork/DBC/Structures/SkillLineAbilityEntry.cs
682
C#
using System.Collections.Generic; using dnlib.DotNet; using dnlib.DotNet.MD; namespace ConfuserExTools.ConstantKiller { internal static class ModuleDefExtensions { public static IEnumerable<MethodDef> EnumerateMethods(this ModuleDef module) { if (module is ModuleDefMD moduleDefMD) { uint methodTableLength = moduleDefMD.TablesStream.MethodTable.Rows; for (uint rid = 1; rid <= methodTableLength; rid++) yield return moduleDefMD.ResolveMethod(rid); } else { for (uint rid = 1; ; rid++) { if (!(module.ResolveToken(new MDToken(Table.Method, rid)) is MethodDef method)) yield break; yield return method; } } } } }
29.043478
84
0.711078
[ "MIT" ]
levisre/ConfuserExTools
ConstantKiller/ModuleDefExtensions.cs
668
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; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Xunit; namespace Microsoft.AspNetCore.Identity.Test { public class IdentityBuilderTest { [Fact] public void AddRolesServicesAdded() { var services = new ServiceCollection(); services.AddIdentityCore<PocoUser>(o => { }) .AddRoles<PocoRole>() .AddUserStore<NoopUserStore>() .AddRoleStore<NoopRoleStore>(); var sp = services.BuildServiceProvider(); Assert.NotNull(sp.GetRequiredService<IRoleValidator<PocoRole>>()); Assert.IsType<NoopRoleStore>(sp.GetRequiredService<IRoleStore<PocoRole>>()); Assert.IsType<RoleManager<PocoRole>>(sp.GetRequiredService<RoleManager<PocoRole>>()); Assert.NotNull(sp.GetRequiredService<RoleManager<PocoRole>>()); Assert.IsType<UserClaimsPrincipalFactory<PocoUser, PocoRole>>(sp.GetRequiredService<IUserClaimsPrincipalFactory<PocoUser>>()); } [Fact] public void AddRolesWithoutStoreWillError() { var services = new ServiceCollection(); services.AddIdentityCore<PocoUser>(o => { }) .AddRoles<PocoRole>(); var sp = services.BuildServiceProvider(); Assert.NotNull(sp.GetRequiredService<IRoleValidator<PocoRole>>()); Assert.Null(sp.GetService<IRoleStore<PocoRole>>()); Assert.Throws<InvalidOperationException>(() => sp.GetService<RoleManager<PocoRole>>()); } [Fact] public void CanOverrideUserStore() { var services = new ServiceCollection() .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); services.AddIdentity<PocoUser,PocoRole>().AddUserStore<MyUberThingy>(); var thingy = services.BuildServiceProvider().GetRequiredService<IUserStore<PocoUser>>() as MyUberThingy; Assert.NotNull(thingy); } [Fact] public void CanOverrideRoleStore() { var services = new ServiceCollection() .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); services.AddIdentity<PocoUser,PocoRole>().AddRoleStore<MyUberThingy>(); var thingy = services.BuildServiceProvider().GetRequiredService<IRoleStore<PocoRole>>() as MyUberThingy; Assert.NotNull(thingy); } [Fact] public void CanOverridePrincipalFactory() { var services = new ServiceCollection() .AddLogging() .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); services.AddIdentity<PocoUser, PocoRole>() .AddClaimsPrincipalFactory<MyClaimsPrincipalFactory>() .AddUserManager<MyUserManager>() .AddUserStore<NoopUserStore>() .AddRoleStore<NoopRoleStore>(); var thingy = services.BuildServiceProvider().GetRequiredService<IUserClaimsPrincipalFactory<PocoUser>>() as MyClaimsPrincipalFactory; Assert.NotNull(thingy); } [Fact] public void CanOverrideRoleValidator() { var services = new ServiceCollection() .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); services.AddIdentity<PocoUser,PocoRole>().AddRoleValidator<MyUberThingy>(); var thingy = services.BuildServiceProvider().GetRequiredService<IRoleValidator<PocoRole>>() as MyUberThingy; Assert.NotNull(thingy); } [Fact] public void CanOverrideUserValidator() { var services = new ServiceCollection() .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); services.AddIdentity<PocoUser,PocoRole>().AddUserValidator<MyUberThingy>(); var thingy = services.BuildServiceProvider().GetRequiredService<IUserValidator<PocoUser>>() as MyUberThingy; Assert.NotNull(thingy); } [Fact] public void CanOverridePasswordValidator() { var services = new ServiceCollection() .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); services.AddIdentity<PocoUser,PocoRole>().AddPasswordValidator<MyUberThingy>(); var thingy = services.BuildServiceProvider().GetRequiredService<IPasswordValidator<PocoUser>>() as MyUberThingy; Assert.NotNull(thingy); } [Fact] public void CanOverrideUserManager() { var services = new ServiceCollection() .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); services.AddIdentity<PocoUser, PocoRole>() .AddUserStore<NoopUserStore>() .AddUserManager<MyUserManager>(); var myUserManager = services.BuildServiceProvider().GetRequiredService(typeof(UserManager<PocoUser>)) as MyUserManager; Assert.NotNull(myUserManager); } [Fact] public void CanOverrideRoleManager() { var services = new ServiceCollection() .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); services.AddIdentity<PocoUser, PocoRole>() .AddRoleStore<NoopRoleStore>() .AddRoleManager<MyRoleManager>(); var myRoleManager = services.BuildServiceProvider().GetRequiredService<RoleManager<PocoRole>>() as MyRoleManager; Assert.NotNull(myRoleManager); } [Fact] public void CanOverrideSignInManager() { var services = new ServiceCollection() .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()) .AddHttpContextAccessor() .AddLogging(); services.AddIdentity<PocoUser, PocoRole>() .AddUserStore<NoopUserStore>() .AddRoleStore<NoopRoleStore>() .AddUserManager<MyUserManager>() .AddClaimsPrincipalFactory<MyClaimsPrincipalFactory>() .AddSignInManager<MySignInManager>(); var myUserManager = services.BuildServiceProvider().GetRequiredService(typeof(SignInManager<PocoUser>)) as MySignInManager; Assert.NotNull(myUserManager); } [Fact] public void EnsureDefaultServices() { var services = new ServiceCollection() .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); services.AddLogging() .AddIdentity<PocoUser,PocoRole>() .AddUserStore<NoopUserStore>() .AddRoleStore<NoopRoleStore>(); var provider = services.BuildServiceProvider(); var userValidator = provider.GetRequiredService<IUserValidator<PocoUser>>() as UserValidator<PocoUser>; Assert.NotNull(userValidator); var pwdValidator = provider.GetRequiredService<IPasswordValidator<PocoUser>>() as PasswordValidator<PocoUser>; Assert.NotNull(pwdValidator); var hasher = provider.GetRequiredService<IPasswordHasher<PocoUser>>() as PasswordHasher<PocoUser>; Assert.NotNull(hasher); Assert.IsType<RoleManager<PocoRole>>(provider.GetRequiredService<RoleManager<PocoRole>>()); Assert.IsType<UserManager<PocoUser>>(provider.GetRequiredService<UserManager<PocoUser>>()); } [Fact] public void EnsureDefaultTokenProviders() { var services = new ServiceCollection() .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); services.AddIdentity<PocoUser,PocoRole>().AddDefaultTokenProviders(); var provider = services.BuildServiceProvider(); var tokenProviders = provider.GetRequiredService<IOptions<IdentityOptions>>().Value.Tokens.ProviderMap.Values; Assert.Equal(4, tokenProviders.Count()); } [Fact] public void AddManagerWithWrongTypesThrows() { var services = new ServiceCollection() .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); var builder = services.AddIdentity<PocoUser, PocoRole>(); Assert.Throws<InvalidOperationException>(() => builder.AddUserManager<object>()); Assert.Throws<InvalidOperationException>(() => builder.AddRoleManager<object>()); Assert.Throws<InvalidOperationException>(() => builder.AddSignInManager<object>()); } [Fact] public void AddTokenProviderWithWrongTypesThrows() { var services = new ServiceCollection() .AddSingleton<IConfiguration>(new ConfigurationBuilder().Build()); var builder = services.AddIdentity<PocoUser, PocoRole>(); Assert.Throws<InvalidOperationException>(() => builder.AddTokenProvider<object>("whatevs")); Assert.Throws<InvalidOperationException>(() => builder.AddTokenProvider("whatevs", typeof(object))); } private class MyUberThingy : IUserValidator<PocoUser>, IPasswordValidator<PocoUser>, IRoleValidator<PocoRole>, IUserStore<PocoUser>, IRoleStore<PocoRole> { public Task<IdentityResult> CreateAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task<IdentityResult> CreateAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task<IdentityResult> DeleteAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task<IdentityResult> DeleteAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public void Dispose() { throw new NotImplementedException(); } public Task<PocoUser> FindByIdAsync(string userId, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task<PocoUser> FindByNameAsync(string normalizedUserName, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task<string> GetNormalizedRoleNameAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task<string> GetNormalizedUserNameAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task<string> GetRoleIdAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task<string> GetRoleNameAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task<string> GetUserIdAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task<string> GetUserNameAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task SetNormalizedRoleNameAsync(PocoRole role, string normalizedName, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task SetNormalizedUserNameAsync(PocoUser user, string normalizedName, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task SetRoleNameAsync(PocoRole role, string roleName, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task SetUserNameAsync(PocoUser user, string userName, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task<IdentityResult> UpdateAsync(PocoRole role, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task<IdentityResult> UpdateAsync(PocoUser user, CancellationToken cancellationToken = default(CancellationToken)) { throw new NotImplementedException(); } public Task<IdentityResult> ValidateAsync(RoleManager<PocoRole> manager, PocoRole role) { throw new NotImplementedException(); } public Task<IdentityResult> ValidateAsync(UserManager<PocoUser> manager, PocoUser user) { throw new NotImplementedException(); } public Task<IdentityResult> ValidateAsync(UserManager<PocoUser> manager, PocoUser user, string password) { throw new NotImplementedException(); } Task<PocoRole> IRoleStore<PocoRole>.FindByIdAsync(string roleId, CancellationToken cancellationToken) { throw new NotImplementedException(); } Task<PocoRole> IRoleStore<PocoRole>.FindByNameAsync(string roleName, CancellationToken cancellationToken) { throw new NotImplementedException(); } } private class MySignInManager : SignInManager<PocoUser> { public MySignInManager(UserManager<PocoUser> manager, IHttpContextAccessor context, IUserClaimsPrincipalFactory<PocoUser> claimsFactory) : base(manager, context, claimsFactory, null, null, null, null) { } } private class MyUserManager : UserManager<PocoUser> { public MyUserManager(IUserStore<PocoUser> store) : base(store, null, null, null, null, null, null, null, null) { } } private class MyClaimsPrincipalFactory : UserClaimsPrincipalFactory<PocoUser, PocoRole> { public MyClaimsPrincipalFactory(UserManager<PocoUser> userManager, RoleManager<PocoRole> roleManager, IOptions<IdentityOptions> optionsAccessor) : base(userManager, roleManager, optionsAccessor) { } } private class MyRoleManager : RoleManager<PocoRole> { public MyRoleManager(IRoleStore<PocoRole> store, IEnumerable<IRoleValidator<PocoRole>> roleValidators) : base(store, null, null, null, null) { } } } }
44.108033
216
0.637505
[ "Apache-2.0" ]
06b/AspNetCore
src/Identity/test/Identity.Test/IdentityBuilderTest.cs
15,923
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.Azure.Management.PostgreSQL { 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> /// ServerSecurityAlertPoliciesOperations operations. /// </summary> internal partial class ServerSecurityAlertPoliciesOperations : IServiceOperations<PostgreSQLManagementClient>, IServerSecurityAlertPoliciesOperations { /// <summary> /// Initializes a new instance of the ServerSecurityAlertPoliciesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ServerSecurityAlertPoliciesOperations(PostgreSQLManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the PostgreSQLManagementClient /// </summary> public PostgreSQLManagementClient Client { get; private set; } /// <summary> /// Get a server's security alert policy. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// 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<ServerSecurityAlertPolicy>> GetWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (serverName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serverName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.SubscriptionId != null) { if (Client.SubscriptionId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "Client.SubscriptionId", 1); } } string securityAlertPolicyName = "Default"; string apiVersion = "2017-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("securityAlertPolicyName", securityAlertPolicyName); tracingParameters.Add("apiVersion", apiVersion); 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}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName)); _url = _url.Replace("{securityAlertPolicyName}", System.Uri.EscapeDataString(securityAlertPolicyName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ServerSecurityAlertPolicy>(); _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<ServerSecurityAlertPolicy>(_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> /// Creates or updates a threat detection policy. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='parameters'> /// The server security alert policy. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public async Task<AzureOperationResponse<ServerSecurityAlertPolicy>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, ServerSecurityAlertPolicy parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { // Send Request AzureOperationResponse<ServerSecurityAlertPolicy> _response = await BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, serverName, parameters, customHeaders, cancellationToken).ConfigureAwait(false); return await Client.GetPutOrPatchOperationResultAsync(_response, customHeaders, cancellationToken).ConfigureAwait(false); } /// <summary> /// Get the server's threat detection policies. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// 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<ServerSecurityAlertPolicy>>> ListByServerWithHttpMessagesAsync(string resourceGroupName, string serverName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (serverName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serverName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.SubscriptionId != null) { if (Client.SubscriptionId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "Client.SubscriptionId", 1); } } string apiVersion = "2017-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListByServer", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ServerSecurityAlertPolicy>>(); _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<Page1<ServerSecurityAlertPolicy>>(_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> /// Creates or updates a threat detection policy. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='serverName'> /// The name of the server. /// </param> /// <param name='parameters'> /// The server security alert policy. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// 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<ServerSecurityAlertPolicy>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serverName, ServerSecurityAlertPolicy parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (resourceGroupName != null) { if (resourceGroupName.Length > 90) { throw new ValidationException(ValidationRules.MaxLength, "resourceGroupName", 90); } if (resourceGroupName.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "resourceGroupName", 1); } } if (serverName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serverName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (parameters != null) { parameters.Validate(); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (Client.SubscriptionId != null) { if (Client.SubscriptionId.Length < 1) { throw new ValidationException(ValidationRules.MinLength, "Client.SubscriptionId", 1); } } string securityAlertPolicyName = "Default"; string apiVersion = "2017-12-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serverName", serverName); tracingParameters.Add("securityAlertPolicyName", securityAlertPolicyName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BeginCreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforPostgreSQL/servers/{serverName}/securityAlertPolicies/{securityAlertPolicyName}").ToString(); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serverName}", System.Uri.EscapeDataString(serverName)); _url = _url.Replace("{securityAlertPolicyName}", System.Uri.EscapeDataString(securityAlertPolicyName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(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("PUT"); _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; if(parameters != null) { _requestContent = Rest.Serialization.SafeJsonConvert.SerializeObject(parameters, Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // 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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ServerSecurityAlertPolicy>(); _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<ServerSecurityAlertPolicy>(_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> /// Get the server's threat detection policies. /// </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="CloudException"> /// 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<ServerSecurityAlertPolicy>>> ListByServerNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing 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, "ListByServerNext", 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(_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 CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ServerSecurityAlertPolicy>>(); _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<Page1<ServerSecurityAlertPolicy>>(_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; } } }
46.213582
321
0.565663
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/postgresql/Microsoft.Azure.Management.PostgreSQL/src/postgresql/Generated/ServerSecurityAlertPoliciesOperations.cs
42,193
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Bing.Samples.Api.Models { public class ReqInfo { public string Ip { get; set; } public string Url { get; set; } public string Host { get; set; } public string Browser { get; set; } } }
18.666667
43
0.607143
[ "MIT" ]
jianxuanbing/Bing
sample/Bing.Samples.Api/Models/ReqInfo.cs
338
C#
// <auto-generated> using KyGunCo.Counterpoint.Sdk.Entities; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace KyGunCo.Counterpoint.Sdk.Configuration { // SY_MAIL public class SyMailConfiguration : IEntityTypeConfiguration<SyMail> { public void Configure(EntityTypeBuilder<SyMail> builder) { builder.ToTable("SY_MAIL", "dbo"); builder.HasKey(x => x.MailId).HasName("PK_SY_MAIL").IsClustered(); builder.Property(x => x.MailId).HasColumnName(@"MAIL_ID").HasColumnType("bigint").IsRequired().ValueGeneratedNever(); builder.Property(x => x.SenderId).HasColumnName(@"SENDER_ID").HasColumnType("varchar(10)").IsRequired().IsUnicode(false).HasMaxLength(10); builder.Property(x => x.SentDt).HasColumnName(@"SENT_DT").HasColumnType("datetime").IsRequired(false); builder.Property(x => x.Subj).HasColumnName(@"SUBJ").HasColumnType("varchar(50)").IsRequired(false).IsUnicode(false).HasMaxLength(50); builder.Property(x => x.Msg).HasColumnName(@"MSG").HasColumnType("text(2147483647)").IsRequired(false).IsUnicode(false).HasMaxLength(2147483647); builder.Property(x => x.MsgTxt).HasColumnName(@"MSG_TXT").HasColumnType("text(2147483647)").IsRequired(false).IsUnicode(false).HasMaxLength(2147483647); builder.Property(x => x.Importance).HasColumnName(@"IMPORTANCE").HasColumnType("varchar(1)").IsRequired().IsUnicode(false).HasMaxLength(1); builder.Property(x => x.SentTo).HasColumnName(@"SENT_TO").HasColumnType("text(2147483647)").IsRequired().IsUnicode(false).HasMaxLength(2147483647); builder.Property(x => x.IsPopup).HasColumnName(@"IS_POPUP").HasColumnType("varchar(1)").IsRequired().IsUnicode(false).HasMaxLength(1); builder.Property(x => x.DeltdBySender).HasColumnName(@"DELTD_BY_SENDER").HasColumnType("varchar(1)").IsRequired().IsUnicode(false).HasMaxLength(1); builder.Property(x => x.AutoDelPopup).HasColumnName(@"AUTO_DEL_POPUP").HasColumnType("varchar(1)").IsRequired().IsUnicode(false).HasMaxLength(1); builder.Property(x => x.RsUtcDt).HasColumnName(@"RS_UTC_DT").HasColumnType("datetime").IsRequired(false); // Foreign keys builder.HasOne(a => a.SyUsr).WithMany(b => b.SyMails).HasForeignKey(c => c.SenderId).OnDelete(DeleteBehavior.ClientSetNull).HasConstraintName("FK_SY_MAIL_SY_USR"); builder.HasIndex(x => x.RsUtcDt).HasDatabaseName("SY_MAIL_X_RS_UTC_DT"); } } } // </auto-generated>
66.487179
175
0.704975
[ "MIT" ]
kygunco/KyGunCo.Counterpoint
Source/KyGunCo.Counterpoint.Sdk/Configuration/SyMailConfiguration.cs
2,593
C#
using System; namespace Snake { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); char[,] matrix = new char[n, n]; int snakeRow = -1; int snakeCol = -1; int firsBurrowRow = -1; int firsBurrowCol = -1; int secondBurrowRow = -1; int secondBurrowCol = -1; for (int row = 0; row < n; row++) { string line = Console.ReadLine(); for (int col = 0; col < line.Length; col++) { matrix[row, col] = line[col]; if (matrix[row, col] == 'S') { snakeRow = row; snakeCol = col; } if (matrix[row,col] == 'B') { if (firsBurrowRow == -1) { firsBurrowRow = row; firsBurrowCol = col; } else { secondBurrowRow = row; secondBurrowCol = col; } } } } matrix[snakeRow, snakeCol] = '.'; int foodCount = 0; while (true) { if (foodCount >= 10) { Console.WriteLine("You won! You fed the snake."); matrix[snakeRow, snakeCol] = 'S'; break; } string command = Console.ReadLine(); if (command == "up") { snakeRow--; } if (command == "down") { snakeRow++; } if (command == "left") { snakeCol--; } if (command == "right") { snakeCol++; } if (!IsSafePosition(matrix, snakeRow, snakeCol)) { Console.WriteLine("Game over!"); break; } if (matrix[snakeRow, snakeCol] == '*') { foodCount++; } if (matrix[snakeRow,snakeCol] == 'B') { matrix[snakeRow, snakeCol] = '.'; if (firsBurrowRow == snakeRow && firsBurrowCol == snakeCol) // if we are on the firs Burrow { // we set it to second Burrow snakeRow = secondBurrowRow; snakeCol = secondBurrowCol; } else { snakeRow = firsBurrowRow; snakeCol = firsBurrowCol; } } matrix[snakeRow, snakeCol] = '.'; //Print(matrix); } Console.WriteLine($"Food eaten: {foodCount}"); Print(matrix); } static void Print(char[,] matrix) { for (int row = 0; row < matrix.GetLength(0); row++) { for (int col = 0; col < matrix.GetLength(1); col++) { Console.Write(matrix[row, col]); } Console.WriteLine(); } } static bool IsSafePosition(char[,] matrix, int row, int col) { if (row < 0 || col < 0) { return false; } if (row >= matrix.GetLength(0) || col >= matrix.GetLength(1)) { return false; } return true; } } }
28.624113
86
0.3278
[ "MIT" ]
IvanBerov/C-Advanced
ExamPreparation/Advanced Exam - 28 June 2020/Snake/Program.cs
4,038
C#
using Microsoft.AspNetCore.Authorization; namespace FilmesAPI.Authorization { public class IdadeMinimaRequirement : IAuthorizationRequirement { public IdadeMinimaRequirement(int idadeMinima) { IdadeMinima = idadeMinima; } public int IdadeMinima { get; set; } } }
21.466667
67
0.670807
[ "MIT" ]
flaviomegrecarvalho42/7_net5_e_identity_autenticando_e_autorizando_usuarios
FilmesAPI/Authorization/IdadeMinimaRequirement.cs
324
C#
namespace ishtar; using vein.reflection; using vein.runtime; public static class KnowTypes { public static QualityTypeName TypeInfoTypeName = new QualityTypeName("std", nameof(Type), "global::vein/lang"); public static QualityTypeName FieldInfoTypeName = new QualityTypeName("std", nameof(Field), "global::vein/lang"); public static QualityTypeName FunctionInfoTypeName = new QualityTypeName("std", nameof(Function), "global::vein/lang"); public static QualityTypeName NullPointerExceptionTypeName = new QualityTypeName("std", "NullPointerException", "global::vein/lang"); public static QualityTypeName IncorrectCastFaultTypeName = new QualityTypeName("std", "IncorrectCastFault", "global::vein/lang"); public static QualityTypeName FreeImmortalObjectFaultTypeName = new QualityTypeName("std", nameof(FreeImmortalObjectFault), "global::vein/lang"); public static QualityTypeName TypeNotFoundFaultTypeName = new QualityTypeName("std", nameof(TypeNotFoundFault), "global::vein/lang/reflection"); public static QualityTypeName MultipleTypeFoundFaultTypeName = new QualityTypeName("std", nameof(MultipleTypeFoundFault), "global::vein/lang/reflection"); public static QualityTypeName PlatformIsNotSupportFaultTypeName = new QualityTypeName("std", nameof(PlatformIsNotSupportFault), "global::vein/lang"); public static RuntimeIshtarClass NullPointerException(CallFrame frame) => findType(NullPointerExceptionTypeName, frame); public static RuntimeIshtarClass IncorrectCastFault(CallFrame frame) => findType(IncorrectCastFaultTypeName, frame); public static RuntimeIshtarClass FreeImmortalObjectFault(CallFrame frame) => findType(FreeImmortalObjectFaultTypeName, frame); public static RuntimeIshtarClass TypeNotFoundFault(CallFrame frame) => findType(TypeNotFoundFaultTypeName, frame); public static RuntimeIshtarClass MultipleTypeFoundFault(CallFrame frame) => findType(MultipleTypeFoundFaultTypeName, frame); public static RuntimeIshtarClass PlatformIsNotSupportFault(CallFrame frame) => findType(PlatformIsNotSupportFaultTypeName, frame); public static RuntimeIshtarClass Type(CallFrame frame) => findType(TypeInfoTypeName, frame); public static RuntimeIshtarClass Field(CallFrame frame) => findType(FieldInfoTypeName, frame); public static RuntimeIshtarClass Function(CallFrame frame) => findType(FunctionInfoTypeName, frame); private static Dictionary<QualityTypeName, RuntimeIshtarClass> _cache = new Dictionary<QualityTypeName, RuntimeIshtarClass>(); public static RuntimeIshtarClass FromCache(QualityTypeName q, CallFrame frame) => findType(q, frame); private static RuntimeIshtarClass findType(QualityTypeName q, CallFrame frame) { if (_cache.ContainsKey(q)) return _cache[q]; var t = frame.method.Owner.Owner.FindType(q, true, false); if (t is UnresolvedVeinClass) { VM.FastFail(WNE.MISSING_TYPE, $"Cannot find '{q}' bulitin type", frame); return null; } if (t is not RuntimeIshtarClass r) { VM.FastFail(WNE.STATE_CORRUPT, $"'{q}' bulitin type found, but is not runtime class.", frame); return null; } return _cache[q] = r; } }
40.892857
106
0.723726
[ "MIT" ]
0xF6/mana_lang
runtime/ishtar.vm/runtime/KnowTypes.cs
3,435
C#
using System; using System.Collections.Generic; using System.Text; namespace GestionPedidosService.Domain.Models { public class PagedList<T> { public ICollection<T> Items { get; set; } public int Total{ get; set; } public int MaxPage { get; set; } public int PageNumber { get; set; } public int ItemsPerPage { get; set; } } }
23.75
49
0.634211
[ "MIT" ]
Patronaje-A-Medida/GestionPedidosService
GestionPedidosService.Domain/Models/PagedList.cs
382
C#
using UnityEditor; using BehaviorDesigner.Runtime; namespace BehaviorDesigner.Editor { [CustomEditor(typeof(BehaviorTree))] public class BehaviorTreeInspector : BehaviorInspector { // intentionally left blank } }
22.454545
59
0.712551
[ "MIT" ]
654306663/UnityExtensions
Tools/Behavior Designer/Editor/BehaviorTreeInspector.cs
247
C#
using gView.Framework.UI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace gView.Win.DataSources.GeoJson.UI.ExplorerObjects { class GeoJsonServiceConnectionsIcon : IExplorerIcon { #region IExplorerIcon Members public Guid GUID { get { return new Guid("B2533892-923D-4FC7-AD45-115855D67C42"); } } public System.Drawing.Image Image { get { return global::gView.Win.DataSources.GeoJson.UI.Properties.Resources.json_16; } } #endregion } class GeoJsonServiceNewConnectionIcon : IExplorerIcon { #region IExplorerIcon Members public Guid GUID { get { return new Guid("CD88930C-1110-49C4-9F2A-A641E416E3A7"); } } public System.Drawing.Image Image { get { return global::gView.Win.DataSources.GeoJson.UI.Properties.Resources.gps_point; } } #endregion } public class GeoJsonServicePointIcon : IExplorerIcon { #region IExplorerIcon Members public Guid GUID { get { return new Guid("D7256D73-2AC9-45F5-AF2B-E60DCFFC0041"); } } public System.Drawing.Image Image { get { return global::gView.Win.DataSources.GeoJson.UI.Properties.Resources.img_32; } } #endregion } public class GeoJsonServiceLineIcon : IExplorerIcon { #region IExplorerIcon Members public Guid GUID { get { return new Guid("02B673EB-463B-4C73-AA8B-3FFBFE31E9A6"); } } public System.Drawing.Image Image { get { return global::gView.Win.DataSources.GeoJson.UI.Properties.Resources.img_33; } } #endregion } public class GeoJsonServicePolygonIcon : IExplorerIcon { #region IExplorerIcon Members public Guid GUID { get { return new Guid("02B673EB-463B-4C73-AA8B-3FFBFE31E9A6"); } } public System.Drawing.Image Image { get { return global::gView.Win.DataSources.GeoJson.UI.Properties.Resources.img_34; } } #endregion } }
22.672897
96
0.568838
[ "Apache-2.0" ]
jugstalt/gview5
NetFramework/gView.Win.DataSources.GeoJson.UI/ExplorerObjects/Icons.cs
2,428
C#
using NUnit.Framework; using DnDGen.TreasureGen.Coins; using DnDGen.TreasureGen.Tables; namespace DnDGen.TreasureGen.Tests.Integration.Tables.Coins { [TestFixture] public class Level28CoinsTests : TypeAndAmountPercentileTests { protected override string tableName { get { return string.Format(TableNameConstants.Percentiles.Formattable.LevelXCoins, 28); } } [Test] public override void ReplacementStringsAreValid() { AssertReplacementStringsAreValid(); } [TestCase(EmptyContent, 1, 2)] public override void Percentile(string content, int lower, int upper) { base.Percentile(content, lower, upper); } [TestCase(CoinConstants.Gold, AmountConstants.Range4d8x1000, 3, 65)] [TestCase(CoinConstants.Platinum, AmountConstants.Range4d10x100, 66, 100)] public override void TypeAndAmountPercentile(string type, string amount, int lower, int upper) { base.TypeAndAmountPercentile(type, amount, lower, upper); } [Test] public override void TableIsComplete() { AssertTableIsComplete(); } } }
30.525
102
0.648649
[ "MIT" ]
DnDGen/TreasureGen
DnDGen.TreasureGen.Tests.Integration.Tables/Coins/Level28CoinsTests.cs
1,223
C#
// // SecPolicy Unit Tests // // Authors: // Sebastien Pouliot <sebastien@xamarin.com> // // Copyright 2012-2013 Xamarin Inc. // using System; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; #if XAMCORE_2_0 using Foundation; using UIKit; using Security; using ObjCRuntime; #else using MonoTouch; using MonoTouch.Foundation; using MonoTouch.Security; using MonoTouch.UIKit; #endif using NUnit.Framework; #if XAMCORE_2_0 using RectangleF=CoreGraphics.CGRect; using SizeF=CoreGraphics.CGSize; using PointF=CoreGraphics.CGPoint; #else using nfloat=global::System.Single; using nint=global::System.Int32; using nuint=global::System.UInt32; #endif namespace MonoTouchFixtures.Security { [TestFixture] // we want the test to be availble if we use the linker [Preserve (AllMembers = true)] public class SecPolicyTest { [DllImport (Constants.CoreFoundationLibrary)] extern static nint CFGetRetainCount (IntPtr handle); [Test] public void SslServerNoHost () { using (var policy = SecPolicy.CreateSslPolicy (true, null)) { Assert.That (policy.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); Assert.That (CFGetRetainCount (policy.Handle), Is.EqualTo ((nint) 1), "RetainCount"); if (TestRuntime.CheckXcodeVersion (5, 0)) { using (var properties = policy.GetProperties ()) { Assert.That (properties.Handle, Is.Not.EqualTo (IntPtr.Zero), "Properties.Handle"); Assert.That (CFGetRetainCount (properties.Handle), Is.EqualTo ((nint) 1), "Properties.RetainCount"); Assert.That (properties.Count, Is.EqualTo ((nuint) 1), "Count"); Assert.That (properties [SecPolicyPropertyKey.Oid].ToString (), Is.EqualTo ("1.2.840.113635.100.1.3"), "SecPolicyOid"); } } } } [Test] public void SslServer () { using (var policy = SecPolicy.CreateSslPolicy (true, "google.com")) { Assert.That (policy.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); Assert.That (CFGetRetainCount (policy.Handle), Is.EqualTo ((nint) 1), "RetainCount"); if (TestRuntime.CheckXcodeVersion (5, 0)) { using (var properties = policy.GetProperties ()) { Assert.That (properties.Handle, Is.Not.EqualTo (IntPtr.Zero), "Properties.Handle"); Assert.That (CFGetRetainCount (properties.Handle), Is.EqualTo ((nint) 1), "Properties.RetainCount"); Assert.That (properties.Count, Is.EqualTo ((nuint) 2), "Count"); Assert.That (properties [SecPolicyPropertyKey.Oid].ToString (), Is.EqualTo ("1.2.840.113635.100.1.3"), "SecPolicyOid"); Assert.That (properties [SecPolicyPropertyKey.Name].ToString (), Is.EqualTo ("google.com"), "SecPolicyName"); } } } } [Test] public void SslClient () { using (var policy = SecPolicy.CreateSslPolicy (false, null)) { Assert.That (policy.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); Assert.That (CFGetRetainCount (policy.Handle), Is.EqualTo ((nint) 1), "RetainCount"); if (TestRuntime.CheckXcodeVersion (5, 0)) { using (var properties = policy.GetProperties ()) { Assert.That (properties.Handle, Is.Not.EqualTo (IntPtr.Zero), "Properties.Handle"); Assert.That (CFGetRetainCount (properties.Handle), Is.EqualTo ((nint) 1), "Properties.RetainCount"); Assert.That (properties.Count, Is.EqualTo ((nuint) 2), "Count"); Assert.That (properties [SecPolicyPropertyKey.Oid].ToString (), Is.EqualTo ("1.2.840.113635.100.1.3"), "SecPolicyOid"); Assert.That (properties [SecPolicyPropertyKey.Client].ToString (), Is.EqualTo ("1"), "SecPolicyClient"); } } } } [Test] public void BasicX509Policy () { using (var policy = SecPolicy.CreateBasicX509Policy ()) { Assert.That (policy.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); Assert.That (CFGetRetainCount (policy.Handle), Is.EqualTo ((nint) 1), "RetainCount"); if (TestRuntime.CheckXcodeVersion (5, 0)) { using (var properties = policy.GetProperties ()) { Assert.That (properties.Handle, Is.Not.EqualTo (IntPtr.Zero), "Properties.Handle"); Assert.That (CFGetRetainCount (properties.Handle), Is.EqualTo ((nint) 1), "Properties.RetainCount"); Assert.That (properties.Count, Is.EqualTo ((nuint) 1), "Count"); Assert.That (properties [SecPolicyPropertyKey.Oid].ToString (), Is.EqualTo ("1.2.840.113635.100.1.2"), "SecPolicyOid"); } } } } [Test] public void RevocationPolicy () { TestRuntime.AssertXcodeVersion (5, 0); using (var policy = SecPolicy.CreateRevocationPolicy (SecRevocation.UseAnyAvailableMethod | SecRevocation.RequirePositiveResponse)) { Assert.That (policy.Handle, Is.Not.EqualTo (IntPtr.Zero), "Handle"); Assert.That (CFGetRetainCount (policy.Handle), Is.EqualTo ((nint) 1), "RetainCount"); using (var properties = policy.GetProperties ()) { Assert.That (properties.Handle, Is.Not.EqualTo (IntPtr.Zero), "Properties.Handle"); Assert.That (CFGetRetainCount (properties.Handle), Is.EqualTo ((nint) 1), "Properties.RetainCount"); Assert.That (properties.Count, Is.EqualTo ((nuint) 1), "Count"); Assert.That (properties [SecPolicyPropertyKey.Oid].ToString (), Is.EqualTo ("1.2.840.113635.100.1.21"), "SecPolicyOid"); } } } void CreatePolicy (NSString oid) { string name = oid + "."; using (var policy = SecPolicy.CreatePolicy (oid, null)) { Assert.That (CFGetRetainCount (policy.Handle), Is.EqualTo ((nint) 1), name + "RetainCount"); Assert.That (policy.GetProperties ().Values [0], Is.EqualTo (oid), name + "SecPolicyOid"); } } [Test] public void CreatWellKnownPolicies () { TestRuntime.AssertXcodeVersion (5, 0); CreatePolicy (SecPolicyIdentifier.AppleX509Basic); CreatePolicy (SecPolicyIdentifier.AppleSSL); CreatePolicy (SecPolicyIdentifier.AppleSMIME); // crash // CreatePolicy (SecPolicyIdentifier.AppleEAP); CreatePolicy (SecPolicyIdentifier.AppleIPsec); CreatePolicy (SecPolicyIdentifier.AppleCodeSigning); CreatePolicy (SecPolicyIdentifier.AppleIDValidation); // invalid handle ? not yet supported ?!? // CreatePolicy (SecPolicyIdentifier.AppleTimeStamping); CreatePolicy (SecPolicyIdentifier.AppleRevocation); } [Test] public void CreateUnknownPolicy () { TestRuntime.AssertXcodeVersion (5, 0); using (var oid = new NSString ("1.2.3.4")) { Assert.Throws<ArgumentException> (delegate { SecPolicy.CreatePolicy (oid, null); }); } } } }
36.223464
136
0.699414
[ "BSD-3-Clause" ]
pjcollins/xamarin-macios
tests/monotouch-test/Security/PolicyTest.cs
6,484
C#
using System; using System.Collections.Generic; namespace Project0.DataAccess { public partial class Content { public Content() { ContentIngredient = new HashSet<ContentIngredient>(); OrderContent = new HashSet<OrderContent>(); } public int ContentId { get; set; } public string Name { get; set; } public decimal? Price { get; set; } public virtual ICollection<ContentIngredient> ContentIngredient { get; set; } public virtual ICollection<OrderContent> OrderContent { get; set; } } }
26.727273
85
0.630952
[ "MIT" ]
1811-nov27-net/ConnerKnight-Project0
Project0/Project0.DataAccess/Content.cs
590
C#
using System; using System.IO; using NUnit.Framework; using SimpleScanner; using SimpleParser; namespace TestGeneratedParser { [TestFixture] public class GeneratedParserTests { private bool Parse(string text) { Scanner scanner = new Scanner(); scanner.SetSource(text, 0); Parser parser = new Parser(scanner); return parser.Parse(); } [Test] public void TestWhile() { Assert.True(Parse(@"begin while 2 do a:=2 end")); } [Test] public void TestRepeat() { Assert.True(Parse(@"begin repeat a:=2; b:=3 until 3 end")); } [Test] public void TestFor() { Assert.True(Parse(@"begin for i:= 1 to 5 do a:=2 end")); Assert.True(Parse(@"begin for i:= 1 to 5 do if 3 then a:=2 else a:=5 end")); } [Test] public void TestWrite() { Assert.True(Parse(@"begin for i:= 1 to 5 do begin a:=2; write(a) end end")); Assert.True(Parse(@"begin if 2 then write(3) else write(4) end")); Assert.True(Parse(@"begin repeat write(5) until 2 end")); } [Test] public void TestIf() { Assert.True(Parse(@"begin if 2 then a:=3 else c:=8; if 3 then if 5 then z:=0 else n:=12 else g:=7 end")); Assert.True(Parse(@"begin while 1 do begin if 2 then a:=1 else b:=2 end end")); } [Test] public void TestVar() { Assert.True(Parse(@"begin var a,b,d end")); } [Test] public void TestExr() { Assert.True(Parse("begin \na:=x-z*3/(c+3-(ddz)+2) end")); Assert.True(Parse(@"begin for i:=2+2*(c-3) to 5+6*2 do begin a:=x-z*3/(c+3-(ddz)+2); if (2-2) then c:=a-2 else write(2+2) end end")); } } }
27.891892
145
0.469961
[ "MIT" ]
Melano2011/MMCS_CS311
TestGeneratedParser/Tests.cs
2,066
C#
using System.Collections.Generic; using System.Linq; namespace ContinuationToken.Providers { internal class OffsetContinuation<T> : IQueryContinuation<T> where T : class { public OffsetContinuation(OffsetToken<T> token, IQueryable<T> query, int? offset) { Token = token; Query = query; Offset = offset; } public OffsetToken<T> Token { get; } public IQueryable<T> Query { get; } public int? Offset { get; } public string? GetNextToken(IEnumerable<T> results) => Token.GetNextToken(Offset.GetValueOrDefault(), results.Count()); } }
26.12
89
0.617152
[ "MIT" ]
mpetito/continuation-token
src/ContinuationToken/Providers/OffsetContinuation.cs
655
C#
using System; using System.Collections.Generic; using System.Text; namespace SmartFridgeApp.IntegrationTests.FakeDatabases { public class FakeSmartFridgeAppContext { } }
16.727273
55
0.777174
[ "MIT" ]
Dariusz151/SmartFridgeApp
SmartFridgeApp.IntegrationTests/FakeDatabases/FakeSmartFridgeAppContext.cs
186
C#
// <auto-generated /> using System; using GRA.Data.SqlServer; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace GRA.Data.SqlServer.Migrations { [DbContext(typeof(SqlServerContext))] [Migration("20201204210511_add-avatarlayer-i18n")] partial class addavatarlayeri18n { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .UseIdentityColumns() .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "5.0.0"); modelBuilder.Entity("GRA.Data.Model.Answer", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<int>("QuestionId") .HasColumnType("int"); b.Property<int>("SortOrder") .HasColumnType("int"); b.Property<string>("Text") .IsRequired() .HasMaxLength(1500) .HasColumnType("nvarchar(1500)"); b.HasKey("Id"); b.HasIndex("QuestionId"); b.ToTable("Answers"); }); modelBuilder.Entity("GRA.Data.Model.AuditLog", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("CurrentValue") .HasColumnType("nvarchar(max)"); b.Property<int>("EntityId") .HasColumnType("int"); b.Property<string>("EntityType") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("PreviousValue") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("UpdatedAt") .HasColumnType("datetime2"); b.Property<int>("UpdatedBy") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("AuditLogs"); }); modelBuilder.Entity("GRA.Data.Model.AuthorizationCode", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("Code") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsSingleUse") .HasColumnType("bit"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<int>("Uses") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AuthorizationCodes"); }); modelBuilder.Entity("GRA.Data.Model.AvatarBundle", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<bool>("CanBeUnlocked") .HasColumnType("bit"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<bool>("HasBeenAwarded") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("SiteId") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("AvatarBundles"); }); modelBuilder.Entity("GRA.Data.Model.AvatarBundleItem", b => { b.Property<int>("AvatarBundleId") .HasColumnType("int"); b.Property<int>("AvatarItemId") .HasColumnType("int"); b.HasKey("AvatarBundleId", "AvatarItemId"); b.HasIndex("AvatarItemId"); b.ToTable("AvatarBundleItems"); }); modelBuilder.Entity("GRA.Data.Model.AvatarColor", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int>("AvatarLayerId") .HasColumnType("int"); b.Property<string>("Color") .IsRequired() .HasMaxLength(15) .HasColumnType("nvarchar(15)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<int>("SortOrder") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("AvatarLayerId"); b.ToTable("AvatarColors"); }); modelBuilder.Entity("GRA.Data.Model.AvatarElement", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int?>("AvatarColorId") .HasColumnType("int"); b.Property<int>("AvatarItemId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Filename") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.HasIndex("AvatarColorId"); b.HasIndex("AvatarItemId"); b.ToTable("AvatarElements"); }); modelBuilder.Entity("GRA.Data.Model.AvatarItem", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int>("AvatarLayerId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("SortOrder") .HasColumnType("int"); b.Property<string>("Thumbnail") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<bool>("Unlockable") .HasColumnType("bit"); b.HasKey("Id"); b.HasIndex("AvatarLayerId"); b.ToTable("AvatarItems"); }); modelBuilder.Entity("GRA.Data.Model.AvatarLayer", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<bool>("CanBeEmpty") .HasColumnType("bit"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<bool>("DefaultLayer") .HasColumnType("bit"); b.Property<int>("GroupId") .HasColumnType("int"); b.Property<string>("Icon") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("Position") .HasColumnType("int"); b.Property<bool>("ShowColorSelector") .HasColumnType("bit"); b.Property<bool>("ShowItemSelector") .HasColumnType("bit"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<int>("SortOrder") .HasColumnType("int"); b.Property<decimal>("ZoomScale") .HasColumnType("decimal(4,2)"); b.Property<int>("ZoomYOffset") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("AvatarLayers"); }); modelBuilder.Entity("GRA.Data.Model.AvatarLayerText", b => { b.Property<int>("AvatarLayerId") .HasColumnType("int"); b.Property<int>("LanguageId") .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("RemoveLabel") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("AvatarLayerId", "LanguageId"); b.HasIndex("LanguageId"); b.ToTable("AvatarLayerTexts"); }); modelBuilder.Entity("GRA.Data.Model.Badge", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Filename") .HasColumnType("nvarchar(max)"); b.Property<int>("SiteId") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("Badges"); }); modelBuilder.Entity("GRA.Data.Model.Book", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("Author") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int?>("ChallengeId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Isbn") .HasMaxLength(30) .HasColumnType("nvarchar(30)"); b.Property<string>("Title") .IsRequired() .HasMaxLength(500) .HasColumnType("nvarchar(500)"); b.Property<string>("Url") .HasMaxLength(500) .HasColumnType("nvarchar(500)"); b.HasKey("Id"); b.ToTable("Books"); }); modelBuilder.Entity("GRA.Data.Model.Branch", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("Address") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Geolocation") .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("SystemId") .HasColumnType("int"); b.Property<string>("Telephone") .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.Property<string>("Url") .HasMaxLength(500) .HasColumnType("nvarchar(500)"); b.HasKey("Id"); b.HasIndex("SystemId"); b.ToTable("Branches"); }); modelBuilder.Entity("GRA.Data.Model.Broadcast", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("Body") .IsRequired() .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<DateTime>("SendAt") .HasColumnType("datetime2"); b.Property<bool>("SendToNewUsers") .HasColumnType("bit"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<string>("Subject") .IsRequired() .HasMaxLength(500) .HasColumnType("nvarchar(500)"); b.HasKey("Id"); b.ToTable("Broadcasts"); }); modelBuilder.Entity("GRA.Data.Model.Carousel", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Heading") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<bool>("IsForDashboard") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<DateTime>("StartTime") .HasColumnType("datetime2"); b.HasKey("Id"); b.ToTable("Carousels"); }); modelBuilder.Entity("GRA.Data.Model.CarouselItem", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int>("CarouselId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Description") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("ImageUrl") .IsRequired() .HasMaxLength(500) .HasColumnType("nvarchar(500)"); b.Property<int>("SortOrder") .HasColumnType("int"); b.Property<string>("Title") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.ToTable("CarouselItems"); }); modelBuilder.Entity("GRA.Data.Model.Category", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("Color") .HasMaxLength(10) .HasColumnType("nvarchar(10)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Description") .HasMaxLength(500) .HasColumnType("nvarchar(500)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("SiteId") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("Categories"); }); modelBuilder.Entity("GRA.Data.Model.Challenge", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int?>("AssociatedProgramId") .HasColumnType("int"); b.Property<int?>("BadgeId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Description") .HasMaxLength(500) .HasColumnType("nvarchar(500)"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsValid") .HasColumnType("bit"); b.Property<int?>("LimitToBranchId") .HasColumnType("int"); b.Property<int?>("LimitToSystemId") .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("PointsAwarded") .HasColumnType("int"); b.Property<int>("RelatedBranchId") .HasColumnType("int"); b.Property<int>("RelatedSystemId") .HasColumnType("int"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<int>("TasksToComplete") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("SiteId"); b.ToTable("Challenges"); }); modelBuilder.Entity("GRA.Data.Model.ChallengeCategory", b => { b.Property<int>("ChallengeId") .HasColumnType("int"); b.Property<int>("CategoryId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.HasKey("ChallengeId", "CategoryId"); b.HasIndex("CategoryId"); b.ToTable("ChallengeCategories"); }); modelBuilder.Entity("GRA.Data.Model.ChallengeGroup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Description") .IsRequired() .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<string>("Stub") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.ToTable("ChallengeGroups"); }); modelBuilder.Entity("GRA.Data.Model.ChallengeGroupChallenge", b => { b.Property<int>("ChallengeGroupId") .HasColumnType("int"); b.Property<int>("ChallengeId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.HasKey("ChallengeGroupId", "ChallengeId"); b.HasIndex("ChallengeId"); b.ToTable("ChallengeGroupChallenges"); }); modelBuilder.Entity("GRA.Data.Model.ChallengeTask", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("Author") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("ChallengeId") .HasColumnType("int"); b.Property<int>("ChallengeTaskTypeId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Filename") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("Isbn") .HasMaxLength(30) .HasColumnType("nvarchar(30)"); b.Property<int>("Position") .HasColumnType("int"); b.Property<string>("Title") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("Url") .HasMaxLength(500) .HasColumnType("nvarchar(500)"); b.HasKey("Id"); b.HasIndex("ChallengeId"); b.ToTable("ChallengeTasks"); }); modelBuilder.Entity("GRA.Data.Model.ChallengeTaskType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int?>("ActivityCount") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int?>("PointTranslationId") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("ChallengeTaskTypes"); }); modelBuilder.Entity("GRA.Data.Model.DailyLiteracyTip", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<bool>("IsLarge") .HasColumnType("bit"); b.Property<string>("Message") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("SiteId") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("DailyLiteracyTip"); }); modelBuilder.Entity("GRA.Data.Model.DailyLiteracyTipImage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<int>("DailyLiteracyTipId") .HasColumnType("int"); b.Property<int>("Day") .HasColumnType("int"); b.Property<string>("Extension") .IsRequired() .HasMaxLength(10) .HasColumnType("nvarchar(10)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.HasIndex("DailyLiteracyTipId"); b.ToTable("DailyLiteracyTipImage"); }); modelBuilder.Entity("GRA.Data.Model.DashboardContent", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("Content") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<DateTime>("StartTime") .HasColumnType("datetime2"); b.HasKey("Id"); b.ToTable("DashboardContents"); }); modelBuilder.Entity("GRA.Data.Model.Drawing", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<int>("DrawingCriterionId") .HasColumnType("int"); b.Property<bool>("IsArchived") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("NotificationMessage") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.Property<string>("NotificationSubject") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("RedemptionInstructions") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<int>("RelatedBranchId") .HasColumnType("int"); b.Property<int>("RelatedSystemId") .HasColumnType("int"); b.Property<int>("WinnerCount") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("DrawingCriterionId"); b.ToTable("Drawings"); }); modelBuilder.Entity("GRA.Data.Model.DrawingCriterion", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int?>("BranchId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<DateTime?>("EndOfPeriod") .HasColumnType("datetime2"); b.Property<bool>("ExcludePreviousWinners") .HasColumnType("bit"); b.Property<bool>("IncludeAdmin") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int?>("PointsMaximum") .HasColumnType("int"); b.Property<int?>("PointsMinimum") .HasColumnType("int"); b.Property<int?>("ProgramId") .HasColumnType("int"); b.Property<bool>("ReadABook") .HasColumnType("bit"); b.Property<int>("RelatedBranchId") .HasColumnType("int"); b.Property<int>("RelatedSystemId") .HasColumnType("int"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<DateTime?>("StartOfPeriod") .HasColumnType("datetime2"); b.Property<int?>("SystemId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("BranchId"); b.HasIndex("SystemId"); b.ToTable("DrawingCriteria"); }); modelBuilder.Entity("GRA.Data.Model.DrawingCriterionProgram", b => { b.Property<int>("DrawingCriterionId") .HasColumnType("int"); b.Property<int>("ProgramId") .HasColumnType("int"); b.HasKey("DrawingCriterionId", "ProgramId"); b.ToTable("DrawingCriterionPrograms"); }); modelBuilder.Entity("GRA.Data.Model.EmailReminder", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Email") .IsRequired() .HasColumnType("nvarchar(450)"); b.Property<DateTime?>("SentAt") .HasColumnType("datetime2"); b.Property<string>("SignUpSource") .IsRequired() .HasColumnType("nvarchar(450)"); b.HasKey("Id"); b.HasIndex("Email", "SignUpSource") .IsUnique(); b.ToTable("EmailReminders"); }); modelBuilder.Entity("GRA.Data.Model.EmailSubscriptionAuditLog", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<bool>("Subscribed") .HasColumnType("bit"); b.Property<bool>("TokenUsed") .HasColumnType("bit"); b.Property<int>("UserId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("CreatedBy"); b.ToTable("EmailSubscriptionAuditLogs"); }); modelBuilder.Entity("GRA.Data.Model.EmailTemplate", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("BodyHtml") .HasColumnType("nvarchar(max)"); b.Property<string>("BodyText") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Description") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("EmailsSent") .HasColumnType("int"); b.Property<string>("FromAddress") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("FromName") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<string>("Subject") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.ToTable("EmailTemplates"); }); modelBuilder.Entity("GRA.Data.Model.EmailUserLog", b => { b.Property<int>("UserId") .HasColumnType("int"); b.Property<int>("EmailTemplateId") .HasColumnType("int"); b.Property<string>("EmailAddress") .IsRequired() .HasColumnType("nvarchar(450)"); b.Property<DateTime>("SentAt") .HasColumnType("datetime2"); b.HasKey("UserId", "EmailTemplateId"); b.HasIndex("EmailTemplateId", "EmailAddress") .IsUnique(); b.ToTable("EmailUserLogs"); }); modelBuilder.Entity("GRA.Data.Model.Event", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<bool>("AllDay") .HasColumnType("bit"); b.Property<int?>("AtBranchId") .HasColumnType("int"); b.Property<int?>("AtLocationId") .HasColumnType("int"); b.Property<int?>("ChallengeGroupId") .HasColumnType("int"); b.Property<int?>("ChallengeId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Description") .IsRequired() .HasMaxLength(1500) .HasColumnType("nvarchar(1500)"); b.Property<DateTime?>("EndDate") .HasColumnType("datetime2"); b.Property<string>("ExternalLink") .HasMaxLength(300) .HasColumnType("nvarchar(300)"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsCommunityExperience") .HasColumnType("bit"); b.Property<bool>("IsStreaming") .HasColumnType("bit"); b.Property<bool>("IsStreamingEmbed") .HasColumnType("bit"); b.Property<bool>("IsValid") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int?>("ParentEventId") .HasColumnType("int"); b.Property<int?>("ProgramId") .HasColumnType("int"); b.Property<int>("RelatedBranchId") .HasColumnType("int"); b.Property<int>("RelatedSystemId") .HasColumnType("int"); b.Property<int?>("RelatedTriggerId") .HasColumnType("int"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<DateTime>("StartDate") .HasColumnType("datetime2"); b.Property<DateTime?>("StreamingAccessEnds") .HasColumnType("datetime2"); b.Property<string>("StreamingLinkData") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.HasIndex("ChallengeGroupId"); b.HasIndex("ChallengeId"); b.ToTable("Events"); }); modelBuilder.Entity("GRA.Data.Model.GroupInfo", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<int>("GroupTypeId") .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("UserId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("GroupTypeId"); b.HasIndex("UserId"); b.ToTable("GroupInfos"); }); modelBuilder.Entity("GRA.Data.Model.GroupType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("SiteId") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("GroupTypes"); }); modelBuilder.Entity("GRA.Data.Model.Job", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime?>("Cancelled") .HasColumnType("datetime2"); b.Property<DateTime?>("Completed") .HasColumnType("datetime2"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<Guid>("JobToken") .HasColumnType("uniqueidentifier"); b.Property<int>("JobType") .HasColumnType("int"); b.Property<string>("SerializedParameters") .HasColumnType("nvarchar(max)"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<DateTime?>("Started") .HasColumnType("datetime2"); b.Property<string>("Status") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<DateTime?>("StatusAsOf") .HasColumnType("datetime2"); b.HasKey("Id"); b.HasIndex("JobToken") .IsUnique(); b.ToTable("Jobs"); }); modelBuilder.Entity("GRA.Data.Model.Language", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Description") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsDefault") .HasColumnType("bit"); b.Property<string>("Name") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.ToTable("Languages"); }); modelBuilder.Entity("GRA.Data.Model.Location", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("Address") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Geolocation") .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<string>("Telephone") .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.Property<string>("Url") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.ToTable("Locations"); }); modelBuilder.Entity("GRA.Data.Model.Mail", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("Body") .IsRequired() .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.Property<bool>("CanParticipantDelete") .HasColumnType("bit"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<int?>("DrawingId") .HasColumnType("int"); b.Property<int>("FromUserId") .HasColumnType("int"); b.Property<int?>("InReplyToId") .HasColumnType("int"); b.Property<bool>("IsBroadcast") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsNew") .HasColumnType("bit"); b.Property<bool>("IsRepliedTo") .HasColumnType("bit"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<string>("Subject") .IsRequired() .HasMaxLength(500) .HasColumnType("nvarchar(500)"); b.Property<int?>("ThreadId") .HasColumnType("int"); b.Property<int?>("ToUserId") .HasColumnType("int"); b.Property<int?>("TriggerId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ToUserId", "IsDeleted", "IsNew"); b.ToTable("Mails"); }); modelBuilder.Entity("GRA.Data.Model.NewsCategory", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<bool>("IsDefault") .HasColumnType("bit"); b.Property<DateTime?>("LastPostDate") .HasColumnType("datetime2"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("SiteId") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("NewsCateories"); }); modelBuilder.Entity("GRA.Data.Model.NewsPost", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int>("CategoryId") .HasColumnType("int"); b.Property<string>("Content") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<DateTime?>("PublishedAt") .HasColumnType("datetime2"); b.Property<string>("Title") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.HasIndex("CategoryId"); b.ToTable("NewsPosts"); }); modelBuilder.Entity("GRA.Data.Model.Notification", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int?>("AvatarBundleId") .HasColumnType("int"); b.Property<string>("BadgeFilename") .HasColumnType("nvarchar(max)"); b.Property<int?>("BadgeId") .HasColumnType("int"); b.Property<int?>("ChallengeId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<bool>("IsAchiever") .HasColumnType("bit"); b.Property<bool>("IsJoiner") .HasColumnType("bit"); b.Property<int?>("PointsEarned") .HasColumnType("int"); b.Property<string>("Text") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<int>("UserId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("Notifications"); }); modelBuilder.Entity("GRA.Data.Model.Page", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("Content") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("FooterText") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<bool>("IsPublished") .HasColumnType("bit"); b.Property<int>("LanguageId") .HasColumnType("int"); b.Property<string>("MetaDescription") .HasMaxLength(150) .HasColumnType("nvarchar(150)"); b.Property<string>("NavText") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("PageHeaderId") .HasColumnType("int"); b.Property<string>("Title") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.HasIndex("LanguageId"); b.HasIndex("PageHeaderId"); b.ToTable("Pages"); }); modelBuilder.Entity("GRA.Data.Model.PageHeader", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("PageName") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<string>("Stub") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.HasIndex("SiteId", "Stub") .IsUnique(); b.ToTable("PageHeaders"); }); modelBuilder.Entity("GRA.Data.Model.Permission", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.ToTable("Permissions"); }); modelBuilder.Entity("GRA.Data.Model.PointTranslation", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int>("ActivityAmount") .HasColumnType("int"); b.Property<string>("ActivityDescription") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("ActivityDescriptionPlural") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<bool>("IsSingleEvent") .HasColumnType("bit"); b.Property<int>("PointsEarned") .HasColumnType("int"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<string>("TranslationDescriptionPastTense") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("TranslationDescriptionPresentTense") .IsRequired() .HasColumnType("nvarchar(max)"); b.Property<string>("TranslationName") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.ToTable("PointTranslations"); }); modelBuilder.Entity("GRA.Data.Model.PrizeWinner", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<int?>("DrawingId") .HasColumnType("int"); b.Property<int?>("MailId") .HasColumnType("int"); b.Property<DateTime?>("RedeemedAt") .HasColumnType("datetime2"); b.Property<int?>("RedeemedBy") .HasColumnType("int"); b.Property<int?>("RedeemedByBranch") .HasColumnType("int"); b.Property<int?>("RedeemedBySystem") .HasColumnType("int"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<int?>("TriggerId") .HasColumnType("int"); b.Property<int>("UserId") .HasColumnType("int"); b.Property<int?>("VendorCodeId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("TriggerId"); b.HasIndex("UserId"); b.HasIndex("DrawingId", "UserId", "RedeemedAt") .IsUnique() .HasFilter("[DrawingId] IS NOT NULL AND [RedeemedAt] IS NOT NULL"); b.ToTable("PrizeWinners"); }); modelBuilder.Entity("GRA.Data.Model.Program", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int>("AchieverPointAmount") .HasColumnType("int"); b.Property<int?>("AgeMaximum") .HasColumnType("int"); b.Property<int?>("AgeMinimum") .HasColumnType("int"); b.Property<bool>("AgeRequired") .HasColumnType("bit"); b.Property<bool>("AskAge") .HasColumnType("bit"); b.Property<bool>("AskSchool") .HasColumnType("bit"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<int?>("DailyLiteracyTipId") .HasColumnType("int"); b.Property<int?>("JoinBadgeId") .HasColumnType("int"); b.Property<string>("JoinBadgeName") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("PointTranslationId") .HasColumnType("int"); b.Property<int>("Position") .HasColumnType("int"); b.Property<bool>("SchoolRequired") .HasColumnType("bit"); b.Property<int>("SiteId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("DailyLiteracyTipId"); b.HasIndex("PointTranslationId"); b.HasIndex("SiteId"); b.ToTable("Programs"); }); modelBuilder.Entity("GRA.Data.Model.PsAgeGroup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("IconColor") .IsRequired() .HasMaxLength(32) .HasColumnType("nvarchar(32)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.ToTable("PsAgeGroups"); }); modelBuilder.Entity("GRA.Data.Model.PsBackToBack", b => { b.Property<int>("PsAgeGroupId") .HasColumnType("int"); b.Property<int>("BranchId") .HasColumnType("int"); b.HasKey("PsAgeGroupId", "BranchId"); b.HasIndex("BranchId"); b.ToTable("PsBackToBack"); }); modelBuilder.Entity("GRA.Data.Model.PsBlackoutDate", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<DateTime>("Date") .HasColumnType("datetime2"); b.Property<string>("Reason") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.ToTable("PsBlackoutDates"); }); modelBuilder.Entity("GRA.Data.Model.PsBranchSelection", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int>("AgeGroupId") .HasColumnType("int"); b.Property<bool>("BackToBackProgram") .HasColumnType("bit"); b.Property<int>("BranchId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<int?>("KitId") .HasColumnType("int"); b.Property<int?>("ProgramId") .HasColumnType("int"); b.Property<DateTime>("RequestedStartTime") .HasColumnType("datetime2"); b.Property<int>("ScheduleDuration") .HasColumnType("int"); b.Property<DateTime>("ScheduleStartTime") .HasColumnType("datetime2"); b.Property<string>("SecretCode") .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.Property<DateTime>("SelectedAt") .HasColumnType("datetime2"); b.Property<int>("UserId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("AgeGroupId"); b.HasIndex("BranchId"); b.HasIndex("KitId"); b.HasIndex("ProgramId"); b.HasIndex("UserId"); b.ToTable("PsBranchSelections"); }); modelBuilder.Entity("GRA.Data.Model.PsExcludeBranch", b => { b.Property<int>("BranchId") .HasColumnType("int"); b.HasKey("BranchId"); b.ToTable("PsExcludeBranches"); }); modelBuilder.Entity("GRA.Data.Model.PsKit", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Description") .IsRequired() .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("Website") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.ToTable("PsKits"); }); modelBuilder.Entity("GRA.Data.Model.PsKitAgeGroup", b => { b.Property<int>("KitId") .HasColumnType("int"); b.Property<int>("AgeGroupId") .HasColumnType("int"); b.HasKey("KitId", "AgeGroupId"); b.HasIndex("AgeGroupId"); b.ToTable("PsKitAgeGroups"); }); modelBuilder.Entity("GRA.Data.Model.PsKitImage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Filename") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("KitId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("KitId"); b.ToTable("PsKitImages"); }); modelBuilder.Entity("GRA.Data.Model.PsPerformer", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<bool>("AllBranches") .HasColumnType("bit"); b.Property<string>("BillingAddress") .IsRequired() .HasMaxLength(500) .HasColumnType("nvarchar(500)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Email") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<bool>("HasFingerprintCard") .HasColumnType("bit"); b.Property<bool>("IsApproved") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("Phone") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<bool>("PhonePreferred") .HasColumnType("bit"); b.Property<string>("ReferencesFilename") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<bool>("RegistrationCompleted") .HasColumnType("bit"); b.Property<bool>("SetSchedule") .HasColumnType("bit"); b.Property<int>("UserId") .HasColumnType("int"); b.Property<string>("VendorId") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("Website") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("PsPerformers"); }); modelBuilder.Entity("GRA.Data.Model.PsPerformerBranch", b => { b.Property<int>("PsPerformerId") .HasColumnType("int"); b.Property<int>("BranchId") .HasColumnType("int"); b.HasKey("PsPerformerId", "BranchId"); b.HasIndex("BranchId"); b.ToTable("PsPerformerBranches"); }); modelBuilder.Entity("GRA.Data.Model.PsPerformerImage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Filename") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("PerformerId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("PerformerId"); b.ToTable("PsPerformerImages"); }); modelBuilder.Entity("GRA.Data.Model.PsPerformerSchedule", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<DateTime>("Date") .HasColumnType("datetime2"); b.Property<DateTime?>("EndTime") .HasColumnType("datetime2"); b.Property<int>("PerformerId") .HasColumnType("int"); b.Property<DateTime?>("StartTime") .HasColumnType("datetime2"); b.HasKey("Id"); b.HasIndex("PerformerId"); b.ToTable("PsPerformerSchedules"); }); modelBuilder.Entity("GRA.Data.Model.PsProgram", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<bool>("AllowArchiving") .HasColumnType("bit"); b.Property<bool>("AllowStreaming") .HasColumnType("bit"); b.Property<int>("BackToBackMinutes") .HasColumnType("int"); b.Property<int>("BreakdownTimeMinutes") .HasColumnType("int"); b.Property<decimal>("Cost") .HasColumnType("decimal(19,4)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Description") .IsRequired() .HasMaxLength(375) .HasColumnType("nvarchar(375)"); b.Property<int>("MaximumCapacity") .HasColumnType("int"); b.Property<int>("MinimumCapacity") .HasColumnType("int"); b.Property<int>("PerformerId") .HasColumnType("int"); b.Property<int>("ProgramLengthMinutes") .HasColumnType("int"); b.Property<string>("Setup") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<int>("SetupTimeMinutes") .HasColumnType("int"); b.Property<string>("Title") .IsRequired() .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.HasKey("Id"); b.HasIndex("PerformerId"); b.ToTable("PsPrograms"); }); modelBuilder.Entity("GRA.Data.Model.PsProgramAgeGroup", b => { b.Property<int>("ProgramId") .HasColumnType("int"); b.Property<int>("AgeGroupId") .HasColumnType("int"); b.HasKey("ProgramId", "AgeGroupId"); b.HasIndex("AgeGroupId"); b.ToTable("PsProgramAgeGroups"); }); modelBuilder.Entity("GRA.Data.Model.PsProgramImage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Filename") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("ProgramId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("ProgramId"); b.ToTable("PsProgramImages"); }); modelBuilder.Entity("GRA.Data.Model.PsSettings", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("BranchAvailabilitySupplementalText") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("ContactEmail") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<DateTime?>("RegistrationClosed") .HasColumnType("datetime2"); b.Property<DateTime?>("RegistrationOpen") .HasColumnType("datetime2"); b.Property<DateTime?>("ScheduleEndDate") .HasColumnType("datetime2"); b.Property<DateTime?>("SchedulePosted") .HasColumnType("datetime2"); b.Property<DateTime?>("ScheduleStartDate") .HasColumnType("datetime2"); b.Property<DateTime?>("SchedulingClosed") .HasColumnType("datetime2"); b.Property<DateTime?>("SchedulingOpen") .HasColumnType("datetime2"); b.Property<DateTime?>("SchedulingPreview") .HasColumnType("datetime2"); b.Property<int?>("SelectionsPerBranch") .HasColumnType("int"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<string>("VendorCodeFormat") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("VendorIdPrompt") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.HasIndex("SiteId"); b.ToTable("PsSettings"); }); modelBuilder.Entity("GRA.Data.Model.Question", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int>("CorrectAnswerId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("QuestionnaireId") .HasColumnType("int"); b.Property<int>("SortOrder") .HasColumnType("int"); b.Property<string>("Text") .IsRequired() .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.HasIndex("QuestionnaireId"); b.ToTable("Questions"); }); modelBuilder.Entity("GRA.Data.Model.Questionnaire", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int?>("BadgeId") .HasColumnType("int"); b.Property<string>("BadgeName") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("BadgeNotificationMessage") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsLocked") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("RelatedBranchId") .HasColumnType("int"); b.Property<int>("RelatedSystemId") .HasColumnType("int"); b.Property<int>("SiteId") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("Questionnaires"); }); modelBuilder.Entity("GRA.Data.Model.RecoveryToken", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Token") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("UserId") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("RecoveryTokens"); }); modelBuilder.Entity("GRA.Data.Model.ReportCriterion", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("BadgeRequiredList") .HasColumnType("nvarchar(max)"); b.Property<int?>("BranchId") .HasColumnType("int"); b.Property<string>("ChallengeRequiredList") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<DateTime?>("EndDate") .HasColumnType("datetime2"); b.Property<bool>("Favorite") .HasColumnType("bit"); b.Property<int?>("GroupInfoId") .HasColumnType("int"); b.Property<int?>("MaximumAllowableActivity") .HasColumnType("int"); b.Property<string>("Name") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int?>("ProgramId") .HasColumnType("int"); b.Property<int?>("SchoolDistrictId") .HasColumnType("int"); b.Property<int?>("SchoolId") .HasColumnType("int"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<DateTime?>("StartDate") .HasColumnType("datetime2"); b.Property<int?>("SystemId") .HasColumnType("int"); b.Property<string>("TriggerList") .HasColumnType("nvarchar(max)"); b.Property<int?>("VendorCodeTypeId") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("ReportCriteria"); }); modelBuilder.Entity("GRA.Data.Model.ReportRequest", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<bool>("Favorite") .HasColumnType("bit"); b.Property<DateTime?>("Finished") .HasColumnType("datetime2"); b.Property<string>("InstanceName") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("Name") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("ReportCriteriaId") .HasColumnType("int"); b.Property<int>("ReportId") .HasColumnType("int"); b.Property<string>("ResultJson") .HasColumnType("nvarchar(max)"); b.Property<DateTime?>("Started") .HasColumnType("datetime2"); b.Property<bool?>("Success") .HasColumnType("bit"); b.HasKey("Id"); b.ToTable("ReportRequests"); }); modelBuilder.Entity("GRA.Data.Model.RequiredQuestionnaire", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int?>("AgeMaximum") .HasColumnType("int"); b.Property<int?>("AgeMinimum") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<DateTime?>("EndDate") .HasColumnType("datetime2"); b.Property<int>("QuestionnaireId") .HasColumnType("int"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<DateTime?>("StartDate") .HasColumnType("datetime2"); b.HasKey("Id"); b.ToTable("RequiredQuestionnaires"); }); modelBuilder.Entity("GRA.Data.Model.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<bool>("IsAdmin") .HasColumnType("bit"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.ToTable("Roles"); }); modelBuilder.Entity("GRA.Data.Model.RolePermission", b => { b.Property<int>("RoleId") .HasColumnType("int"); b.Property<int>("PermissionId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.HasKey("RoleId", "PermissionId"); b.HasIndex("PermissionId"); b.ToTable("RolePermissions"); }); modelBuilder.Entity("GRA.Data.Model.School", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("SchoolDistrictId") .HasColumnType("int"); b.Property<int>("SiteId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("SchoolDistrictId"); b.ToTable("Schools"); }); modelBuilder.Entity("GRA.Data.Model.SchoolDistrict", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("SiteId") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("SchoolDistricts"); }); modelBuilder.Entity("GRA.Data.Model.Site", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime?>("AccessClosed") .HasColumnType("datetime2"); b.Property<int?>("AccessClosedPage") .HasColumnType("int"); b.Property<string>("AvatarCardDescription") .HasMaxLength(150) .HasColumnType("nvarchar(150)"); b.Property<int?>("BeforeRegistrationPage") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Domain") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("ExternalEventListUrl") .HasColumnType("nvarchar(max)"); b.Property<string>("FacebookAppId") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<string>("FacebookImageUrl") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("Footer") .HasColumnType("nvarchar(max)"); b.Property<string>("FromEmailAddress") .HasColumnType("nvarchar(max)"); b.Property<string>("FromEmailName") .HasColumnType("nvarchar(max)"); b.Property<string>("GoogleAnalyticsTrackingId") .HasColumnType("nvarchar(max)"); b.Property<bool>("IsDefault") .HasColumnType("bit"); b.Property<bool>("IsHttpsForced") .HasColumnType("bit"); b.Property<string>("MetaDescription") .HasMaxLength(150) .HasColumnType("nvarchar(150)"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("OutgoingMailHost") .HasColumnType("nvarchar(max)"); b.Property<string>("OutgoingMailLogin") .HasColumnType("nvarchar(max)"); b.Property<string>("OutgoingMailPassword") .HasColumnType("nvarchar(max)"); b.Property<int?>("OutgoingMailPort") .HasColumnType("int"); b.Property<string>("PageTitle") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("Path") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int?>("ProgramEndedPage") .HasColumnType("int"); b.Property<DateTime?>("ProgramEnds") .HasColumnType("datetime2"); b.Property<int?>("ProgramOpenPage") .HasColumnType("int"); b.Property<DateTime?>("ProgramStarts") .HasColumnType("datetime2"); b.Property<int?>("RegistrationOpenPage") .HasColumnType("int"); b.Property<DateTime?>("RegistrationOpens") .HasColumnType("datetime2"); b.Property<bool>("RequirePostalCode") .HasColumnType("bit"); b.Property<bool>("SinglePageSignUp") .HasColumnType("bit"); b.Property<string>("SiteLogoUrl") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("TwitterAvatarHashtags") .HasMaxLength(100) .HasColumnType("nvarchar(100)"); b.Property<string>("TwitterAvatarMessage") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("TwitterCardImageUrl") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<bool?>("TwitterLargeCard") .HasColumnType("bit"); b.Property<string>("TwitterUsername") .HasMaxLength(15) .HasColumnType("nvarchar(15)"); b.HasKey("Id"); b.ToTable("Sites"); }); modelBuilder.Entity("GRA.Data.Model.SiteSetting", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Key") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<string>("Value") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.ToTable("SiteSettings"); }); modelBuilder.Entity("GRA.Data.Model.SpatialDistanceDetail", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int?>("BranchId") .HasColumnType("int"); b.Property<double>("Distance") .HasColumnType("float"); b.Property<int?>("LocationId") .HasColumnType("int"); b.Property<int>("SpatialDistanceHeaderId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("BranchId"); b.HasIndex("LocationId"); b.HasIndex("SpatialDistanceHeaderId"); b.ToTable("SpatialDistanceDetails"); }); modelBuilder.Entity("GRA.Data.Model.SpatialDistanceHeader", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Geolocation") .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.Property<bool>("IsValid") .HasColumnType("bit"); b.Property<int>("SiteId") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("SpatialDistanceHeaders"); }); modelBuilder.Entity("GRA.Data.Model.System", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("SiteId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("SiteId"); b.ToTable("Systems"); }); modelBuilder.Entity("GRA.Data.Model.Trigger", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime?>("ActivationDate") .HasColumnType("datetime2"); b.Property<int?>("AwardAvatarBundleId") .HasColumnType("int"); b.Property<int>("AwardBadgeId") .HasColumnType("int"); b.Property<string>("AwardMail") .HasMaxLength(2000) .HasColumnType("nvarchar(2000)"); b.Property<string>("AwardMailSubject") .HasMaxLength(500) .HasColumnType("nvarchar(500)"); b.Property<string>("AwardMessage") .IsRequired() .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<int>("AwardPoints") .HasColumnType("int"); b.Property<string>("AwardPrizeName") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("AwardPrizeRedemptionInstructions") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.Property<int?>("AwardVendorCodeTypeId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<int>("ItemsRequired") .HasColumnType("int"); b.Property<int?>("LimitToBranchId") .HasColumnType("int"); b.Property<int?>("LimitToProgramId") .HasColumnType("int"); b.Property<int?>("LimitToSystemId") .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int>("Points") .HasColumnType("int"); b.Property<int>("RelatedBranchId") .HasColumnType("int"); b.Property<int>("RelatedSystemId") .HasColumnType("int"); b.Property<string>("SecretCode") .HasMaxLength(50) .HasColumnType("nvarchar(50)"); b.Property<int>("SiteId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("AwardAvatarBundleId"); b.HasIndex("AwardBadgeId"); b.HasIndex("AwardVendorCodeTypeId"); b.HasIndex("LimitToBranchId"); b.HasIndex("LimitToProgramId"); b.HasIndex("LimitToSystemId"); b.ToTable("Triggers"); }); modelBuilder.Entity("GRA.Data.Model.TriggerBadge", b => { b.Property<int>("TriggerId") .HasColumnType("int"); b.Property<int>("BadgeId") .HasColumnType("int"); b.HasKey("TriggerId", "BadgeId"); b.HasIndex("BadgeId"); b.ToTable("TriggerBadges"); }); modelBuilder.Entity("GRA.Data.Model.TriggerChallenge", b => { b.Property<int>("TriggerId") .HasColumnType("int"); b.Property<int>("ChallengeId") .HasColumnType("int"); b.HasKey("TriggerId", "ChallengeId"); b.HasIndex("ChallengeId"); b.ToTable("TriggerChallenges"); }); modelBuilder.Entity("GRA.Data.Model.User", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<DateTime?>("AchievedAt") .HasColumnType("datetime2"); b.Property<int?>("Age") .HasColumnType("int"); b.Property<int>("BranchId") .HasColumnType("int"); b.Property<bool>("CanBeDeleted") .HasColumnType("bit"); b.Property<string>("CardNumber") .HasMaxLength(64) .HasColumnType("nvarchar(64)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Culture") .HasMaxLength(8) .HasColumnType("nvarchar(8)"); b.Property<int?>("DailyPersonalGoal") .HasColumnType("int"); b.Property<string>("Email") .HasMaxLength(254) .HasColumnType("nvarchar(254)"); b.Property<string>("FirstName") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<int?>("HouseholdHeadUserId") .HasColumnType("int"); b.Property<bool>("IsActive") .HasColumnType("bit"); b.Property<bool>("IsAdmin") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<bool>("IsEmailSubscribed") .HasColumnType("bit"); b.Property<bool>("IsFirstTime") .HasColumnType("bit"); b.Property<bool>("IsHomeschooled") .HasColumnType("bit"); b.Property<bool>("IsLockedOut") .HasColumnType("bit"); b.Property<bool>("IsNewsSubscribed") .HasColumnType("bit"); b.Property<bool>("IsSystemUser") .HasColumnType("bit"); b.Property<DateTime?>("LastAccess") .HasColumnType("datetime2"); b.Property<DateTime?>("LastActivityDate") .HasColumnType("datetime2"); b.Property<DateTime?>("LastBroadcast") .HasColumnType("datetime2"); b.Property<string>("LastName") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<DateTime>("LockedOutAt") .HasColumnType("datetime2"); b.Property<string>("LockedOutFor") .HasColumnType("nvarchar(max)"); b.Property<string>("PasswordHash") .HasColumnType("nvarchar(max)"); b.Property<string>("PhoneNumber") .HasMaxLength(15) .HasColumnType("nvarchar(15)"); b.Property<int>("PointsEarned") .HasColumnType("int"); b.Property<string>("PostalCode") .HasMaxLength(32) .HasColumnType("nvarchar(32)"); b.Property<int>("ProgramId") .HasColumnType("int"); b.Property<int?>("SchoolId") .HasColumnType("int"); b.Property<bool>("SchoolNotListed") .HasColumnType("bit"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<int>("SystemId") .HasColumnType("int"); b.Property<string>("UnsubscribeToken") .HasMaxLength(16) .HasColumnType("nvarchar(16)"); b.Property<string>("Username") .HasMaxLength(36) .HasColumnType("nvarchar(36)"); b.HasKey("Id"); b.HasIndex("BranchId"); b.HasIndex("ProgramId"); b.HasIndex("SystemId"); b.HasIndex("SiteId", "IsDeleted", "Username") .IsUnique() .HasFilter("[Username] IS NOT NULL"); b.HasIndex("SiteId", "Id", "IsDeleted", "HouseholdHeadUserId") .IsUnique() .HasFilter("[HouseholdHeadUserId] IS NOT NULL"); b.ToTable("Users"); }); modelBuilder.Entity("GRA.Data.Model.UserAnswer", b => { b.Property<int>("UserId") .HasColumnType("int"); b.Property<int>("AnswerId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.HasKey("UserId", "AnswerId"); b.HasIndex("AnswerId"); b.ToTable("UserAnswers"); }); modelBuilder.Entity("GRA.Data.Model.UserAvatar", b => { b.Property<int>("UserId") .HasColumnType("int"); b.Property<int>("AvatarElementId") .HasColumnType("int"); b.HasKey("UserId", "AvatarElementId"); b.HasIndex("AvatarElementId"); b.ToTable("UserAvatars"); }); modelBuilder.Entity("GRA.Data.Model.UserAvatarItem", b => { b.Property<int>("UserId") .HasColumnType("int"); b.Property<int>("AvatarItemId") .HasColumnType("int"); b.HasKey("UserId", "AvatarItemId"); b.HasIndex("AvatarItemId"); b.ToTable("UserAvatarItems"); }); modelBuilder.Entity("GRA.Data.Model.UserBadge", b => { b.Property<int>("UserId") .HasColumnType("int"); b.Property<int>("BadgeId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.HasKey("UserId", "BadgeId"); b.HasIndex("BadgeId"); b.ToTable("UserBadges"); }); modelBuilder.Entity("GRA.Data.Model.UserBook", b => { b.Property<int>("UserId") .HasColumnType("int"); b.Property<int>("BookId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.HasKey("UserId", "BookId"); b.HasIndex("BookId"); b.ToTable("UserBooks"); }); modelBuilder.Entity("GRA.Data.Model.UserChallengeTask", b => { b.Property<int>("UserId") .HasColumnType("int"); b.Property<int>("ChallengeTaskId") .HasColumnType("int"); b.Property<int?>("BookId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<bool>("IsCompleted") .HasColumnType("bit"); b.Property<int?>("UserLogId") .HasColumnType("int"); b.HasKey("UserId", "ChallengeTaskId"); b.HasIndex("ChallengeTaskId"); b.ToTable("UserChallengeTasks"); }); modelBuilder.Entity("GRA.Data.Model.UserFavoriteChallenge", b => { b.Property<int>("UserId") .HasColumnType("int"); b.Property<int>("ChallengeId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.HasKey("UserId", "ChallengeId"); b.HasIndex("ChallengeId"); b.ToTable("UserFavoriteChallenges"); }); modelBuilder.Entity("GRA.Data.Model.UserFavoriteEvent", b => { b.Property<int>("UserId") .HasColumnType("int"); b.Property<int>("EventId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.HasKey("UserId", "EventId"); b.HasIndex("EventId"); b.ToTable("UserFavoriteEvents"); }); modelBuilder.Entity("GRA.Data.Model.UserLog", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int?>("ActivityEarned") .HasColumnType("int"); b.Property<int?>("AvatarBundleId") .HasColumnType("int"); b.Property<int?>("AwardedBy") .HasColumnType("int"); b.Property<int?>("BadgeId") .HasColumnType("int"); b.Property<int?>("ChallengeId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<int?>("DeletedBy") .HasColumnType("int"); b.Property<string>("Description") .HasColumnType("nvarchar(max)"); b.Property<int?>("EventId") .HasColumnType("int"); b.Property<bool?>("HasBeenViewed") .HasColumnType("bit"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<int?>("PointTranslationId") .HasColumnType("int"); b.Property<int>("PointsEarned") .HasColumnType("int"); b.Property<int?>("TriggerId") .HasColumnType("int"); b.Property<int>("UserId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("UserId", "IsDeleted", "BadgeId"); b.HasIndex("UserId", "IsDeleted", "ChallengeId"); b.HasIndex("UserId", "IsDeleted", "PointTranslationId", "ActivityEarned"); b.ToTable("UserLogs"); }); modelBuilder.Entity("GRA.Data.Model.UserQuestionnaire", b => { b.Property<int>("UserId") .HasColumnType("int"); b.Property<int>("QuestionnaireId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.HasKey("UserId", "QuestionnaireId"); b.HasIndex("QuestionnaireId"); b.ToTable("UserQuestionnaires"); }); modelBuilder.Entity("GRA.Data.Model.UserRole", b => { b.Property<int>("UserId") .HasColumnType("int"); b.Property<int>("RoleId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("UserRoles"); }); modelBuilder.Entity("GRA.Data.Model.UserTrigger", b => { b.Property<int>("UserId") .HasColumnType("int"); b.Property<int>("TriggerId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.HasKey("UserId", "TriggerId"); b.HasIndex("TriggerId"); b.ToTable("UserTriggers"); }); modelBuilder.Entity("GRA.Data.Model.VendorCode", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<int?>("BranchId") .HasColumnType("int"); b.Property<string>("Code") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<DateTime>("DateUsed") .HasColumnType("datetime2"); b.Property<string>("Details") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("EmailAwardAddress") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<DateTime?>("EmailAwardReported") .HasColumnType("datetime2"); b.Property<DateTime?>("EmailAwardSent") .HasColumnType("datetime2"); b.Property<bool?>("IsDonated") .HasColumnType("bit"); b.Property<bool?>("IsEmailAward") .HasColumnType("bit"); b.Property<bool>("IsUsed") .HasColumnType("bit"); b.Property<DateTime?>("OrderDate") .HasColumnType("datetime2"); b.Property<DateTime?>("ShipDate") .HasColumnType("datetime2"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<int?>("UserId") .IsConcurrencyToken() .HasColumnType("int"); b.Property<int>("VendorCodeTypeId") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("VendorCodeTypeId"); b.ToTable("VendorCodes"); }); modelBuilder.Entity("GRA.Data.Model.VendorCodeType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<bool>("AwardPrizeOnShipDate") .HasColumnType("bit"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<int>("CreatedBy") .HasColumnType("int"); b.Property<string>("Description") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("DonationMail") .HasMaxLength(1250) .HasColumnType("nvarchar(1250)"); b.Property<string>("DonationMessage") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("DonationSubject") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("EmailAwardMail") .HasMaxLength(1250) .HasColumnType("nvarchar(1250)"); b.Property<string>("EmailAwardMessage") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("EmailAwardSubject") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<DateTime?>("ExpirationDate") .HasColumnType("datetime2"); b.Property<string>("Mail") .IsRequired() .HasMaxLength(1250) .HasColumnType("nvarchar(1250)"); b.Property<string>("MailSubject") .IsRequired() .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.Property<string>("OptionMail") .HasMaxLength(1250) .HasColumnType("nvarchar(1250)"); b.Property<string>("OptionSubject") .HasColumnType("nvarchar(max)"); b.Property<int>("SiteId") .HasColumnType("int"); b.Property<string>("Url") .HasMaxLength(255) .HasColumnType("nvarchar(255)"); b.HasKey("Id"); b.HasIndex("SiteId"); b.ToTable("VendorCodeTypes"); }); modelBuilder.Entity("GRA.Data.Model.VendorCodeTypeText", b => { b.Property<int>("LanguageId") .HasColumnType("int"); b.Property<int>("VendorCodeTypeId") .HasColumnType("int"); b.Property<string>("EmailAwardInstructions") .HasMaxLength(1000) .HasColumnType("nvarchar(1000)"); b.HasKey("LanguageId", "VendorCodeTypeId"); b.HasIndex("VendorCodeTypeId"); b.ToTable("VendorCodeTypeTexts"); }); modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int") .UseIdentityColumn(); b.Property<string>("FriendlyName") .HasColumnType("nvarchar(max)"); b.Property<string>("Xml") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("DataProtectionKeys"); }); modelBuilder.Entity("GRA.Data.Model.Answer", b => { b.HasOne("GRA.Data.Model.Question", "Question") .WithMany("Answers") .HasForeignKey("QuestionId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Question"); }); modelBuilder.Entity("GRA.Data.Model.AuthorizationCode", b => { b.HasOne("GRA.Data.Model.Role", "Role") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Role"); }); modelBuilder.Entity("GRA.Data.Model.AvatarBundleItem", b => { b.HasOne("GRA.Data.Model.AvatarBundle", "AvatarBundle") .WithMany("AvatarBundleItems") .HasForeignKey("AvatarBundleId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.AvatarItem", "AvatarItem") .WithMany() .HasForeignKey("AvatarItemId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("AvatarBundle"); b.Navigation("AvatarItem"); }); modelBuilder.Entity("GRA.Data.Model.AvatarColor", b => { b.HasOne("GRA.Data.Model.AvatarLayer", "AvatarLayer") .WithMany("AvatarColors") .HasForeignKey("AvatarLayerId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("AvatarLayer"); }); modelBuilder.Entity("GRA.Data.Model.AvatarElement", b => { b.HasOne("GRA.Data.Model.AvatarColor", "AvatarColor") .WithMany() .HasForeignKey("AvatarColorId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("GRA.Data.Model.AvatarItem", "AvatarItem") .WithMany() .HasForeignKey("AvatarItemId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("AvatarColor"); b.Navigation("AvatarItem"); }); modelBuilder.Entity("GRA.Data.Model.AvatarItem", b => { b.HasOne("GRA.Data.Model.AvatarLayer", "AvatarLayer") .WithMany("AvatarItems") .HasForeignKey("AvatarLayerId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("AvatarLayer"); }); modelBuilder.Entity("GRA.Data.Model.AvatarLayerText", b => { b.HasOne("GRA.Data.Model.AvatarLayer", "AvatarLayer") .WithMany() .HasForeignKey("AvatarLayerId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.Language", "Language") .WithMany() .HasForeignKey("LanguageId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("AvatarLayer"); b.Navigation("Language"); }); modelBuilder.Entity("GRA.Data.Model.Branch", b => { b.HasOne("GRA.Data.Model.System", "System") .WithMany("Branches") .HasForeignKey("SystemId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("System"); }); modelBuilder.Entity("GRA.Data.Model.Challenge", b => { b.HasOne("GRA.Data.Model.Site", null) .WithMany("Challenges") .HasForeignKey("SiteId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("GRA.Data.Model.ChallengeCategory", b => { b.HasOne("GRA.Data.Model.Category", "Category") .WithMany() .HasForeignKey("CategoryId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.Challenge", "Challenge") .WithMany("ChallengeCategories") .HasForeignKey("ChallengeId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Category"); b.Navigation("Challenge"); }); modelBuilder.Entity("GRA.Data.Model.ChallengeGroupChallenge", b => { b.HasOne("GRA.Data.Model.ChallengeGroup", "ChallengeGroup") .WithMany("ChallengeGroupChallenges") .HasForeignKey("ChallengeGroupId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.Challenge", "Challenge") .WithMany("ChallengeGroupChallenges") .HasForeignKey("ChallengeId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Challenge"); b.Navigation("ChallengeGroup"); }); modelBuilder.Entity("GRA.Data.Model.ChallengeTask", b => { b.HasOne("GRA.Data.Model.Challenge", null) .WithMany("Tasks") .HasForeignKey("ChallengeId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("GRA.Data.Model.DailyLiteracyTipImage", b => { b.HasOne("GRA.Data.Model.DailyLiteracyTip", "DailyLiteracyTip") .WithMany("DailyLiteracyTipImages") .HasForeignKey("DailyLiteracyTipId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("DailyLiteracyTip"); }); modelBuilder.Entity("GRA.Data.Model.Drawing", b => { b.HasOne("GRA.Data.Model.DrawingCriterion", "DrawingCriterion") .WithMany() .HasForeignKey("DrawingCriterionId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("DrawingCriterion"); }); modelBuilder.Entity("GRA.Data.Model.DrawingCriterion", b => { b.HasOne("GRA.Data.Model.Branch", "Branch") .WithMany() .HasForeignKey("BranchId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("GRA.Data.Model.System", "System") .WithMany() .HasForeignKey("SystemId") .OnDelete(DeleteBehavior.Restrict); b.Navigation("Branch"); b.Navigation("System"); }); modelBuilder.Entity("GRA.Data.Model.DrawingCriterionProgram", b => { b.HasOne("GRA.Data.Model.DrawingCriterion", null) .WithMany("CriterionPrograms") .HasForeignKey("DrawingCriterionId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("GRA.Data.Model.EmailSubscriptionAuditLog", b => { b.HasOne("GRA.Data.Model.User", "CreatedByUser") .WithMany() .HasForeignKey("CreatedBy") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("CreatedByUser"); }); modelBuilder.Entity("GRA.Data.Model.EmailUserLog", b => { b.HasOne("GRA.Data.Model.EmailTemplate", "EmailTemplate") .WithMany() .HasForeignKey("EmailTemplateId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("EmailTemplate"); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.Event", b => { b.HasOne("GRA.Data.Model.ChallengeGroup", "ChallengeGroup") .WithMany() .HasForeignKey("ChallengeGroupId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("GRA.Data.Model.Challenge", "Challenge") .WithMany() .HasForeignKey("ChallengeId") .OnDelete(DeleteBehavior.Restrict); b.Navigation("Challenge"); b.Navigation("ChallengeGroup"); }); modelBuilder.Entity("GRA.Data.Model.GroupInfo", b => { b.HasOne("GRA.Data.Model.GroupType", "GroupType") .WithMany() .HasForeignKey("GroupTypeId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("GroupType"); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.NewsPost", b => { b.HasOne("GRA.Data.Model.NewsCategory", "Category") .WithMany("Posts") .HasForeignKey("CategoryId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Category"); }); modelBuilder.Entity("GRA.Data.Model.Page", b => { b.HasOne("GRA.Data.Model.Language", "Language") .WithMany() .HasForeignKey("LanguageId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.PageHeader", "PageHeader") .WithMany("Pages") .HasForeignKey("PageHeaderId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Language"); b.Navigation("PageHeader"); }); modelBuilder.Entity("GRA.Data.Model.PrizeWinner", b => { b.HasOne("GRA.Data.Model.Drawing", "Drawing") .WithMany("Winners") .HasForeignKey("DrawingId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("GRA.Data.Model.Trigger", "Trigger") .WithMany() .HasForeignKey("TriggerId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("GRA.Data.Model.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Drawing"); b.Navigation("Trigger"); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.Program", b => { b.HasOne("GRA.Data.Model.DailyLiteracyTip", "DailyLiteracy") .WithMany() .HasForeignKey("DailyLiteracyTipId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("GRA.Data.Model.PointTranslation", "PointTranslation") .WithMany() .HasForeignKey("PointTranslationId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.Site", null) .WithMany("Programs") .HasForeignKey("SiteId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("DailyLiteracy"); b.Navigation("PointTranslation"); }); modelBuilder.Entity("GRA.Data.Model.PsBackToBack", b => { b.HasOne("GRA.Data.Model.Branch", "Branch") .WithMany() .HasForeignKey("BranchId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.PsAgeGroup", "PsAgeGroup") .WithMany() .HasForeignKey("PsAgeGroupId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Branch"); b.Navigation("PsAgeGroup"); }); modelBuilder.Entity("GRA.Data.Model.PsBranchSelection", b => { b.HasOne("GRA.Data.Model.PsAgeGroup", "AgeGroup") .WithMany() .HasForeignKey("AgeGroupId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.Branch", "Branch") .WithMany() .HasForeignKey("BranchId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.PsKit", "Kit") .WithMany() .HasForeignKey("KitId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("GRA.Data.Model.PsProgram", "Program") .WithMany() .HasForeignKey("ProgramId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("GRA.Data.Model.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("AgeGroup"); b.Navigation("Branch"); b.Navigation("Kit"); b.Navigation("Program"); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.PsExcludeBranch", b => { b.HasOne("GRA.Data.Model.Branch", "Branch") .WithMany() .HasForeignKey("BranchId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Branch"); }); modelBuilder.Entity("GRA.Data.Model.PsKitAgeGroup", b => { b.HasOne("GRA.Data.Model.PsAgeGroup", "AgeGroup") .WithMany() .HasForeignKey("AgeGroupId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.PsKit", "Kit") .WithMany() .HasForeignKey("KitId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("AgeGroup"); b.Navigation("Kit"); }); modelBuilder.Entity("GRA.Data.Model.PsKitImage", b => { b.HasOne("GRA.Data.Model.PsKit", "Kit") .WithMany() .HasForeignKey("KitId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Kit"); }); modelBuilder.Entity("GRA.Data.Model.PsPerformer", b => { b.HasOne("GRA.Data.Model.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.PsPerformerBranch", b => { b.HasOne("GRA.Data.Model.Branch", "Branch") .WithMany() .HasForeignKey("BranchId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.PsPerformer", "PsPerformer") .WithMany() .HasForeignKey("PsPerformerId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Branch"); b.Navigation("PsPerformer"); }); modelBuilder.Entity("GRA.Data.Model.PsPerformerImage", b => { b.HasOne("GRA.Data.Model.PsPerformer", "Performer") .WithMany() .HasForeignKey("PerformerId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Performer"); }); modelBuilder.Entity("GRA.Data.Model.PsPerformerSchedule", b => { b.HasOne("GRA.Data.Model.PsPerformer", "Performer") .WithMany() .HasForeignKey("PerformerId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Performer"); }); modelBuilder.Entity("GRA.Data.Model.PsProgram", b => { b.HasOne("GRA.Data.Model.PsPerformer", "Performer") .WithMany() .HasForeignKey("PerformerId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Performer"); }); modelBuilder.Entity("GRA.Data.Model.PsProgramAgeGroup", b => { b.HasOne("GRA.Data.Model.PsAgeGroup", "AgeGroup") .WithMany() .HasForeignKey("AgeGroupId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.PsProgram", "Program") .WithMany() .HasForeignKey("ProgramId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("AgeGroup"); b.Navigation("Program"); }); modelBuilder.Entity("GRA.Data.Model.PsProgramImage", b => { b.HasOne("GRA.Data.Model.PsProgram", "Program") .WithMany() .HasForeignKey("ProgramId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Program"); }); modelBuilder.Entity("GRA.Data.Model.PsSettings", b => { b.HasOne("GRA.Data.Model.Site", "Site") .WithMany() .HasForeignKey("SiteId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Site"); }); modelBuilder.Entity("GRA.Data.Model.Question", b => { b.HasOne("GRA.Data.Model.Questionnaire", "Questionnaire") .WithMany("Questions") .HasForeignKey("QuestionnaireId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Questionnaire"); }); modelBuilder.Entity("GRA.Data.Model.RolePermission", b => { b.HasOne("GRA.Data.Model.Permission", "Permission") .WithMany() .HasForeignKey("PermissionId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.Role", "Role") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Permission"); b.Navigation("Role"); }); modelBuilder.Entity("GRA.Data.Model.School", b => { b.HasOne("GRA.Data.Model.SchoolDistrict", "SchoolDistrict") .WithMany("Schools") .HasForeignKey("SchoolDistrictId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("SchoolDistrict"); }); modelBuilder.Entity("GRA.Data.Model.SpatialDistanceDetail", b => { b.HasOne("GRA.Data.Model.Branch", "Branch") .WithMany() .HasForeignKey("BranchId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("GRA.Data.Model.Location", "Location") .WithMany() .HasForeignKey("LocationId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("GRA.Data.Model.SpatialDistanceHeader", "SpatialDistanceHeader") .WithMany() .HasForeignKey("SpatialDistanceHeaderId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Branch"); b.Navigation("Location"); b.Navigation("SpatialDistanceHeader"); }); modelBuilder.Entity("GRA.Data.Model.System", b => { b.HasOne("GRA.Data.Model.Site", null) .WithMany("Systems") .HasForeignKey("SiteId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); }); modelBuilder.Entity("GRA.Data.Model.Trigger", b => { b.HasOne("GRA.Data.Model.AvatarBundle", "AwardAvatarBundle") .WithMany() .HasForeignKey("AwardAvatarBundleId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("GRA.Data.Model.Badge", "AwardBadge") .WithMany() .HasForeignKey("AwardBadgeId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.VendorCodeType", "AwardVendorCodeType") .WithMany() .HasForeignKey("AwardVendorCodeTypeId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("GRA.Data.Model.Branch", "LimitToBranch") .WithMany() .HasForeignKey("LimitToBranchId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("GRA.Data.Model.Program", "LimitToProgram") .WithMany() .HasForeignKey("LimitToProgramId") .OnDelete(DeleteBehavior.Restrict); b.HasOne("GRA.Data.Model.System", "LimitToSystem") .WithMany() .HasForeignKey("LimitToSystemId") .OnDelete(DeleteBehavior.Restrict); b.Navigation("AwardAvatarBundle"); b.Navigation("AwardBadge"); b.Navigation("AwardVendorCodeType"); b.Navigation("LimitToBranch"); b.Navigation("LimitToProgram"); b.Navigation("LimitToSystem"); }); modelBuilder.Entity("GRA.Data.Model.TriggerBadge", b => { b.HasOne("GRA.Data.Model.Badge", "Badge") .WithMany() .HasForeignKey("BadgeId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.Trigger", "Trigger") .WithMany("RequiredBadges") .HasForeignKey("TriggerId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Badge"); b.Navigation("Trigger"); }); modelBuilder.Entity("GRA.Data.Model.TriggerChallenge", b => { b.HasOne("GRA.Data.Model.Challenge", "Challenge") .WithMany() .HasForeignKey("ChallengeId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.Trigger", "Trigger") .WithMany("RequiredChallenges") .HasForeignKey("TriggerId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Challenge"); b.Navigation("Trigger"); }); modelBuilder.Entity("GRA.Data.Model.User", b => { b.HasOne("GRA.Data.Model.Branch", "Branch") .WithMany("Users") .HasForeignKey("BranchId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.Program", "Program") .WithMany() .HasForeignKey("ProgramId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.Site", "Site") .WithMany() .HasForeignKey("SiteId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.System", "System") .WithMany() .HasForeignKey("SystemId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Branch"); b.Navigation("Program"); b.Navigation("Site"); b.Navigation("System"); }); modelBuilder.Entity("GRA.Data.Model.UserAnswer", b => { b.HasOne("GRA.Data.Model.Answer", "Answer") .WithMany() .HasForeignKey("AnswerId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Answer"); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.UserAvatar", b => { b.HasOne("GRA.Data.Model.AvatarElement", "AvatarElement") .WithMany() .HasForeignKey("AvatarElementId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("AvatarElement"); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.UserAvatarItem", b => { b.HasOne("GRA.Data.Model.AvatarItem", "AvatarItem") .WithMany() .HasForeignKey("AvatarItemId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("AvatarItem"); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.UserBadge", b => { b.HasOne("GRA.Data.Model.Badge", "Badge") .WithMany() .HasForeignKey("BadgeId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Badge"); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.UserBook", b => { b.HasOne("GRA.Data.Model.Book", "Book") .WithMany() .HasForeignKey("BookId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Book"); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.UserChallengeTask", b => { b.HasOne("GRA.Data.Model.ChallengeTask", "ChallengeTask") .WithMany() .HasForeignKey("ChallengeTaskId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("ChallengeTask"); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.UserFavoriteChallenge", b => { b.HasOne("GRA.Data.Model.Challenge", "Challenge") .WithMany() .HasForeignKey("ChallengeId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Challenge"); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.UserFavoriteEvent", b => { b.HasOne("GRA.Data.Model.Event", "Event") .WithMany() .HasForeignKey("EventId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Event"); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.UserLog", b => { b.HasOne("GRA.Data.Model.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.UserQuestionnaire", b => { b.HasOne("GRA.Data.Model.Questionnaire", "Questionnaire") .WithMany() .HasForeignKey("QuestionnaireId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Questionnaire"); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.UserRole", b => { b.HasOne("GRA.Data.Model.Role", "Role") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.User", "User") .WithMany("UserRoles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Role"); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.UserTrigger", b => { b.HasOne("GRA.Data.Model.Trigger", "Trigger") .WithMany() .HasForeignKey("TriggerId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.User", "User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Trigger"); b.Navigation("User"); }); modelBuilder.Entity("GRA.Data.Model.VendorCode", b => { b.HasOne("GRA.Data.Model.VendorCodeType", "VendorCodeType") .WithMany() .HasForeignKey("VendorCodeTypeId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("VendorCodeType"); }); modelBuilder.Entity("GRA.Data.Model.VendorCodeType", b => { b.HasOne("GRA.Data.Model.Site", "Site") .WithMany() .HasForeignKey("SiteId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Site"); }); modelBuilder.Entity("GRA.Data.Model.VendorCodeTypeText", b => { b.HasOne("GRA.Data.Model.Language", "Language") .WithMany() .HasForeignKey("LanguageId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.HasOne("GRA.Data.Model.VendorCodeType", "VendorCodeType") .WithMany() .HasForeignKey("VendorCodeTypeId") .OnDelete(DeleteBehavior.Restrict) .IsRequired(); b.Navigation("Language"); b.Navigation("VendorCodeType"); }); modelBuilder.Entity("GRA.Data.Model.AvatarBundle", b => { b.Navigation("AvatarBundleItems"); }); modelBuilder.Entity("GRA.Data.Model.AvatarLayer", b => { b.Navigation("AvatarColors"); b.Navigation("AvatarItems"); }); modelBuilder.Entity("GRA.Data.Model.Branch", b => { b.Navigation("Users"); }); modelBuilder.Entity("GRA.Data.Model.Challenge", b => { b.Navigation("ChallengeCategories"); b.Navigation("ChallengeGroupChallenges"); b.Navigation("Tasks"); }); modelBuilder.Entity("GRA.Data.Model.ChallengeGroup", b => { b.Navigation("ChallengeGroupChallenges"); }); modelBuilder.Entity("GRA.Data.Model.DailyLiteracyTip", b => { b.Navigation("DailyLiteracyTipImages"); }); modelBuilder.Entity("GRA.Data.Model.Drawing", b => { b.Navigation("Winners"); }); modelBuilder.Entity("GRA.Data.Model.DrawingCriterion", b => { b.Navigation("CriterionPrograms"); }); modelBuilder.Entity("GRA.Data.Model.NewsCategory", b => { b.Navigation("Posts"); }); modelBuilder.Entity("GRA.Data.Model.PageHeader", b => { b.Navigation("Pages"); }); modelBuilder.Entity("GRA.Data.Model.Question", b => { b.Navigation("Answers"); }); modelBuilder.Entity("GRA.Data.Model.Questionnaire", b => { b.Navigation("Questions"); }); modelBuilder.Entity("GRA.Data.Model.SchoolDistrict", b => { b.Navigation("Schools"); }); modelBuilder.Entity("GRA.Data.Model.Site", b => { b.Navigation("Challenges"); b.Navigation("Programs"); b.Navigation("Systems"); }); modelBuilder.Entity("GRA.Data.Model.System", b => { b.Navigation("Branches"); }); modelBuilder.Entity("GRA.Data.Model.Trigger", b => { b.Navigation("RequiredBadges"); b.Navigation("RequiredChallenges"); }); modelBuilder.Entity("GRA.Data.Model.User", b => { b.Navigation("UserRoles"); }); #pragma warning restore 612, 618 } } }
34.462851
113
0.405425
[ "MIT" ]
MCLD/greatreadingadventure
src/GRA.Data.SqlServer/Migrations/20201204210511_add-avatarlayer-i18n.Designer.cs
171,627
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices.Client.Transport { using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Amqp; using Microsoft.Azure.Amqp.Framing; using Microsoft.Azure.Devices.Client.Exceptions; using Microsoft.Azure.Devices.Client.Extensions; using Microsoft.Azure.Devices.Shared; using System.Collections.Concurrent; using System.Linq.Expressions; using Newtonsoft.Json; sealed class AmqpTransportHandler : TransportHandler { public const string ResponseStatusName = "status"; static readonly IotHubConnectionCache TcpConnectionCache = new IotHubConnectionCache(); static readonly IotHubConnectionCache WsConnectionCache = new IotHubConnectionCache(); readonly string deviceId; readonly Client.FaultTolerantAmqpObject<SendingAmqpLink> faultTolerantEventSendingLink; readonly Client.FaultTolerantAmqpObject<ReceivingAmqpLink> faultTolerantDeviceBoundReceivingLink; volatile Client.FaultTolerantAmqpObject<SendingAmqpLink> faultTolerantMethodSendingLink; volatile Client.FaultTolerantAmqpObject<ReceivingAmqpLink> faultTolerantMethodReceivingLink; volatile Client.FaultTolerantAmqpObject<SendingAmqpLink> faultTolerantTwinSendingLink; volatile Client.FaultTolerantAmqpObject<ReceivingAmqpLink> faultTolerantTwinReceivingLink; readonly IotHubConnectionString iotHubConnectionString; readonly TimeSpan openTimeout; readonly TimeSpan operationTimeout; readonly uint prefetchCount; readonly SemaphoreSlim recoverySemaphore = new SemaphoreSlim(1, 1); Func<MethodRequestInternal, Task> messageListener; Action<TwinCollection> onDesiredStatePatchListener; Action<object, ConnectionEventArgs> linkOpenedListener; Func<object, ConnectionEventArgs, Task> linkClosedListener; Func<object, ConnectionEventArgs, Task> SafeAddClosedMethodReceivingLinkHandler; Func<object, ConnectionEventArgs, Task> SafeAddClosedMethodSendingLinkHandler; Func<object, ConnectionEventArgs, Task> SafeAddClosedTwinReceivingLinkHandler; Func<object, ConnectionEventArgs, Task> SafeAddClosedTwinSendingLinkHandler; internal delegate void OnConnectionClosedDelegate(object sender, EventArgs e); string methodConnectionCorrelationId = Guid.NewGuid().ToString("N"); string twinConnectionCorrelationId = Guid.NewGuid().ToString("N"); private string methodSendingLinkName; private string methodReceivingLinkName; private string twinSendingLinkName; private string twinReceivingLinkName; const int ResponseTimeoutInSeconds = 10; ConcurrentDictionary<string, TaskCompletionSource<AmqpMessage>> twinResponseCompletions = new ConcurrentDictionary<string, TaskCompletionSource<AmqpMessage>>(); ProductInfo productInfo; internal AmqpTransportHandler( IPipelineContext context, IotHubConnectionString connectionString, AmqpTransportSettings transportSettings, Action<object, ConnectionEventArgs> onLinkOpenedCallback, Func<object, ConnectionEventArgs, Task> onLinkClosedCallback, Func<MethodRequestInternal, Task> onMethodCallback = null, Action<TwinCollection> onDesiredStatePatchReceived = null) :base(context, transportSettings) { this.linkOpenedListener = onLinkOpenedCallback; this.linkClosedListener = onLinkClosedCallback; this.productInfo = context.Get<ProductInfo>(); TransportType transportType = transportSettings.GetTransportType(); this.deviceId = connectionString.DeviceId; switch (transportType) { case TransportType.Amqp_Tcp_Only: this.IotHubConnection = TcpConnectionCache.GetConnection(connectionString, transportSettings); break; case TransportType.Amqp_WebSocket_Only: this.IotHubConnection = WsConnectionCache.GetConnection(connectionString, transportSettings); break; default: throw new InvalidOperationException("Invalid Transport Type {0}".FormatInvariant(transportType)); } this.openTimeout = transportSettings.OpenTimeout; this.operationTimeout = transportSettings.OperationTimeout; this.prefetchCount = transportSettings.PrefetchCount; this.faultTolerantEventSendingLink = new Client.FaultTolerantAmqpObject<SendingAmqpLink>(this.CreateEventSendingLinkAsync, this.IotHubConnection.CloseLink); this.faultTolerantDeviceBoundReceivingLink = new Client.FaultTolerantAmqpObject<ReceivingAmqpLink>(this.CreateDeviceBoundReceivingLinkAsync, this.IotHubConnection.CloseLink); this.iotHubConnectionString = connectionString; this.messageListener = onMethodCallback; this.onDesiredStatePatchListener = onDesiredStatePatchReceived; } internal IotHubConnection IotHubConnection { get; } public override async Task OpenAsync(bool explicitOpen, CancellationToken cancellationToken) { if (!explicitOpen) { return; } await this.HandleTimeoutCancellation(async () => { try { await Task.WhenAll( this.faultTolerantEventSendingLink.OpenAsync(this.openTimeout, cancellationToken), this.faultTolerantDeviceBoundReceivingLink.OpenAsync(this.openTimeout, cancellationToken)).ConfigureAwait(false); this.linkOpenedListener( this.faultTolerantEventSendingLink, new ConnectionEventArgs { ConnectionType = ConnectionType.AmqpTelemetry, ConnectionStatus = ConnectionStatus.Connected, ConnectionStatusChangeReason = ConnectionStatusChangeReason.Connection_Ok }); this.linkOpenedListener( this.faultTolerantDeviceBoundReceivingLink, new ConnectionEventArgs { ConnectionType = ConnectionType.AmqpMessaging, ConnectionStatus = ConnectionStatus.Connected, ConnectionStatusChangeReason = ConnectionStatusChangeReason.Connection_Ok }); } catch (Exception exception) { if (exception.IsFatal()) { throw; } throw AmqpClientHelper.ToIotHubClientContract(exception); } }, cancellationToken).ConfigureAwait(false); } public override async Task SendEventAsync(Message message, CancellationToken cancellationToken) { await this.HandleTimeoutCancellation(async () => { Outcome outcome; using (AmqpMessage amqpMessage = message.ToAmqpMessage()) { outcome = await this.SendAmqpMessageAsync(amqpMessage, cancellationToken).ConfigureAwait(false); } if (outcome.DescriptorCode != Accepted.Code) { throw AmqpErrorMapper.GetExceptionFromOutcome(outcome); } }, cancellationToken).ConfigureAwait(false); } public override async Task SendEventAsync(IEnumerable<Message> messages, CancellationToken cancellationToken) { await this.HandleTimeoutCancellation(async () => { // List to hold messages in Amqp friendly format var messageList = new List<Data>(); foreach (Message message in messages) { using (AmqpMessage amqpMessage = message.ToAmqpMessage()) { var data = new Data() { Value = MessageConverter.ReadStream(amqpMessage.ToStream()) }; messageList.Add(data); } } Outcome outcome; using (AmqpMessage amqpMessage = AmqpMessage.Create(messageList)) { amqpMessage.MessageFormat = AmqpConstants.AmqpBatchedMessageFormat; outcome = await this.SendAmqpMessageAsync(amqpMessage, cancellationToken).ConfigureAwait(false); } if (outcome.DescriptorCode != Accepted.Code) { throw AmqpErrorMapper.GetExceptionFromOutcome(outcome); } }, cancellationToken).ConfigureAwait(false); } public override async Task<Message> ReceiveAsync(TimeSpan timeout, CancellationToken cancellationToken) { Message message = null; await this.HandleTimeoutCancellation(async () => { AmqpMessage amqpMessage; try { ReceivingAmqpLink deviceBoundReceivingLink = await this.GetDeviceBoundReceivingLinkAsync(cancellationToken).ConfigureAwait(false); amqpMessage = await deviceBoundReceivingLink.ReceiveMessageAsync(timeout).ConfigureAwait(false); } catch (Exception exception) { if (exception.IsFatal()) { throw; } throw AmqpClientHelper.ToIotHubClientContract(exception); } if (amqpMessage != null) { message = new Message(amqpMessage) { LockToken = new Guid(amqpMessage.DeliveryTag.Array).ToString() }; } else { message = null; } }, cancellationToken).ConfigureAwait(false); return message; } public override async Task RecoverConnections(object link, ConnectionType connectionType, CancellationToken cancellationToken) { bool needMethodRecovery = false; bool needTwinRecovery = false; await recoverySemaphore.WaitAsync().ConfigureAwait(false); // disconnected link belongs to the current sets if (((connectionType == ConnectionType.AmqpMethodSending) && ((link as SendingAmqpLink).Name == methodSendingLinkName)) || ((connectionType == ConnectionType.AmqpMethodReceiving) && ((link as ReceivingAmqpLink).Name == methodReceivingLinkName))) { methodSendingLinkName = null; methodReceivingLinkName = null; needMethodRecovery = true; } if (((connectionType == ConnectionType.AmqpTwinSending) && ((link as SendingAmqpLink).Name == twinSendingLinkName)) || ((connectionType == ConnectionType.AmqpTwinReceiving) && ((link as ReceivingAmqpLink).Name == twinReceivingLinkName))) { twinSendingLinkName = null; twinReceivingLinkName = null; needTwinRecovery = true; } recoverySemaphore.Release(1); if (needMethodRecovery) { this.faultTolerantMethodSendingLink = null; this.faultTolerantMethodReceivingLink = null; await this.EnableMethodsAsync(cancellationToken).ConfigureAwait(false); } if (needTwinRecovery) { this.faultTolerantTwinSendingLink = null; this.faultTolerantTwinReceivingLink = null; await this.EnableTwinPatchAsync(cancellationToken).ConfigureAwait(false); } } public override async Task EnableMethodsAsync(CancellationToken cancellationToken) { if (this.faultTolerantMethodSendingLink == null) { this.faultTolerantMethodSendingLink = new Client.FaultTolerantAmqpObject<SendingAmqpLink>(this.CreateMethodSendingLinkAsync, this.IotHubConnection.CloseLink); } if (this.faultTolerantMethodReceivingLink == null) { this.faultTolerantMethodReceivingLink = new Client.FaultTolerantAmqpObject<ReceivingAmqpLink>(this.CreateMethodReceivingLinkAsync, this.IotHubConnection.CloseLink); } await this.HandleTimeoutCancellation(async () => { try { if (this.messageListener != null) { await Task.WhenAll(EnableMethodSendingLinkAsync(cancellationToken), EnableMethodReceivingLinkAsync(cancellationToken)).ConfigureAwait(false); this.linkOpenedListener( this.faultTolerantMethodSendingLink, new ConnectionEventArgs { ConnectionType = ConnectionType.AmqpMethodSending, ConnectionStatus = ConnectionStatus.Connected, ConnectionStatusChangeReason = ConnectionStatusChangeReason.Connection_Ok }); this.linkOpenedListener( this.faultTolerantMethodReceivingLink, new ConnectionEventArgs { ConnectionType = ConnectionType.AmqpMethodReceiving, ConnectionStatus = ConnectionStatus.Connected, ConnectionStatusChangeReason = ConnectionStatusChangeReason.Connection_Ok }); // generate new guid for reconnection methodConnectionCorrelationId = Guid.NewGuid().ToString("N"); } } catch (Exception ex) when (!ex.IsFatal()) { throw AmqpClientHelper.ToIotHubClientContract(ex); } }, cancellationToken).ConfigureAwait(false); } public override async Task EnableTwinPatchAsync(CancellationToken cancellationToken) { if (this.faultTolerantTwinSendingLink == null) { this.faultTolerantTwinSendingLink = new Client.FaultTolerantAmqpObject<SendingAmqpLink>(this.CreateTwinSendingLinkAsync, this.IotHubConnection.CloseLink); } if (this.faultTolerantTwinReceivingLink == null) { this.faultTolerantTwinReceivingLink = new Client.FaultTolerantAmqpObject<ReceivingAmqpLink>(this.CreateTwinReceivingLinkAsync, this.IotHubConnection.CloseLink); } await this.HandleTimeoutCancellation(async () => { try { if (this.messageListener != null) { await Task.WhenAll(EnableTwinSendingLinkAsync(cancellationToken), EnableTwinReceivingLinkAsync(cancellationToken)).ConfigureAwait(false); this.linkOpenedListener( this.faultTolerantTwinSendingLink, new ConnectionEventArgs { ConnectionType = ConnectionType.AmqpTwinSending, ConnectionStatus = ConnectionStatus.Connected, ConnectionStatusChangeReason = ConnectionStatusChangeReason.Connection_Ok }); this.linkOpenedListener( this.faultTolerantTwinReceivingLink, new ConnectionEventArgs { ConnectionType = ConnectionType.AmqpTwinReceiving, ConnectionStatus = ConnectionStatus.Connected, ConnectionStatusChangeReason = ConnectionStatusChangeReason.Connection_Ok }); // generate new guid for reconnection twinConnectionCorrelationId = Guid.NewGuid().ToString("N"); } } catch (Exception ex) when (!ex.IsFatal()) { throw AmqpClientHelper.ToIotHubClientContract(ex); } }, cancellationToken).ConfigureAwait(false); } private async Task EnableMethodSendingLinkAsync(CancellationToken cancellationToken) { await this.GetMethodSendingLinkAsync(cancellationToken).ConfigureAwait(false); } private async Task EnableMethodReceivingLinkAsync(CancellationToken cancellationToken) { await this.GetMethodReceivingLinkAsync(cancellationToken).ConfigureAwait(false); } private async Task EnableTwinSendingLinkAsync(CancellationToken cancellationToken) { await this.GetTwinSendingLinkAsync(cancellationToken).ConfigureAwait(false); } private async Task EnableTwinReceivingLinkAsync(CancellationToken cancellationToken) { await this.GetTwinReceivingLinkAsync(cancellationToken).ConfigureAwait(false); } public override async Task DisableMethodsAsync(CancellationToken cancellationToken) { Task receivingLinkCloseTask; this.SafeAddClosedMethodSendingLinkHandler = (o, ea) => { return TaskHelpers.CompletedTask; }; this.SafeAddClosedMethodReceivingLinkHandler = (o, ea) => { return TaskHelpers.CompletedTask; }; if (this.faultTolerantMethodReceivingLink != null) { receivingLinkCloseTask = this.faultTolerantMethodReceivingLink.CloseAsync(); this.faultTolerantMethodReceivingLink = null; } else { receivingLinkCloseTask = TaskHelpers.CompletedTask; } Task sendingLinkCloseTask; if (this.faultTolerantMethodSendingLink != null) { sendingLinkCloseTask = this.faultTolerantMethodSendingLink.CloseAsync(); this.faultTolerantMethodSendingLink = null; } else { sendingLinkCloseTask = TaskHelpers.CompletedTask; } await Task.WhenAll(receivingLinkCloseTask, sendingLinkCloseTask).ConfigureAwait(false); await this.linkClosedListener( this.faultTolerantMethodSendingLink, new ConnectionEventArgs { ConnectionType = ConnectionType.AmqpMethodSending, ConnectionStatus = ConnectionStatus.Disabled, ConnectionStatusChangeReason = ConnectionStatusChangeReason.Client_Close }).ConfigureAwait(false); await this.linkClosedListener( this.faultTolerantMethodReceivingLink, new ConnectionEventArgs { ConnectionType = ConnectionType.AmqpMethodReceiving, ConnectionStatus = ConnectionStatus.Disabled, ConnectionStatusChangeReason = ConnectionStatusChangeReason.Client_Close }).ConfigureAwait(false); } public async Task DisableTwinAsync(CancellationToken cancellationToken) { Task receivingLinkCloseTask; this.SafeAddClosedTwinSendingLinkHandler = (o, ea) => { return TaskHelpers.CompletedTask; }; this.SafeAddClosedTwinReceivingLinkHandler = (o, ea) => { return TaskHelpers.CompletedTask; }; if (this.faultTolerantTwinReceivingLink != null) { receivingLinkCloseTask = this.faultTolerantTwinReceivingLink.CloseAsync(); this.faultTolerantTwinReceivingLink = null; } else { receivingLinkCloseTask = TaskHelpers.CompletedTask; } Task sendingLinkCloseTask; if (this.faultTolerantTwinSendingLink != null) { sendingLinkCloseTask = this.faultTolerantTwinSendingLink.CloseAsync(); this.faultTolerantTwinSendingLink = null; } else { sendingLinkCloseTask = TaskHelpers.CompletedTask; } await Task.WhenAll(receivingLinkCloseTask, sendingLinkCloseTask).ConfigureAwait(false); await this.linkClosedListener( this.faultTolerantTwinSendingLink, new ConnectionEventArgs { ConnectionType = ConnectionType.AmqpTwinSending, ConnectionStatus = ConnectionStatus.Disabled, ConnectionStatusChangeReason = ConnectionStatusChangeReason.Client_Close }).ConfigureAwait(false); await this.linkClosedListener( this.faultTolerantTwinReceivingLink, new ConnectionEventArgs { ConnectionType = ConnectionType.AmqpTwinReceiving, ConnectionStatus = ConnectionStatus.Disabled, ConnectionStatusChangeReason = ConnectionStatusChangeReason.Client_Close }).ConfigureAwait(false); } public override async Task SendMethodResponseAsync(MethodResponseInternal methodResponse, CancellationToken cancellationToken) { await this.HandleTimeoutCancellation(async () => { Outcome outcome; using (AmqpMessage amqpMessage = methodResponse.ToAmqpMessage()) { outcome = await this.SendAmqpMethodResponseAsync(amqpMessage, cancellationToken).ConfigureAwait(false); } if (outcome.DescriptorCode != Accepted.Code) { throw AmqpErrorMapper.GetExceptionFromOutcome(outcome); } }, cancellationToken).ConfigureAwait(false); } public override Task CompleteAsync(string lockToken, CancellationToken cancellationToken) { return this.HandleTimeoutCancellation(() => this.DisposeMessageAsync(lockToken, AmqpConstants.AcceptedOutcome, cancellationToken), cancellationToken); } public override Task AbandonAsync(string lockToken, CancellationToken cancellationToken) { return this.HandleTimeoutCancellation(() => this.DisposeMessageAsync(lockToken, AmqpConstants.ReleasedOutcome, cancellationToken), cancellationToken); } public override Task RejectAsync(string lockToken, CancellationToken cancellationToken) { return this.HandleTimeoutCancellation(() => this.DisposeMessageAsync(lockToken, AmqpConstants.RejectedOutcome, cancellationToken), cancellationToken); } protected override async void Dispose(bool disposing) { try { await this.CloseAsync().ConfigureAwait(false); } catch { // TODO: add traces here } finally { base.Dispose(disposing); } } public override async Task CloseAsync() { GC.SuppressFinalize(this); Task eventSendingLinkCloseTask = this.faultTolerantEventSendingLink.CloseAsync(); Task deviceBoundReceivingLinkCloseTask = this.faultTolerantDeviceBoundReceivingLink.CloseAsync(); Task disabledMethodTask = this.DisableMethodsAsync(CancellationToken.None); Task disableTwinTask = this.DisableTwinAsync(CancellationToken.None); await Task.WhenAll(eventSendingLinkCloseTask, deviceBoundReceivingLinkCloseTask, disabledMethodTask, disableTwinTask).ConfigureAwait(false); await this.linkClosedListener( this.faultTolerantEventSendingLink, new ConnectionEventArgs { ConnectionType = ConnectionType.AmqpTelemetry, ConnectionStatus = ConnectionStatus.Disabled, ConnectionStatusChangeReason = ConnectionStatusChangeReason.Client_Close }).ConfigureAwait(false); await this.linkClosedListener( this.faultTolerantDeviceBoundReceivingLink, new ConnectionEventArgs { ConnectionType = ConnectionType.AmqpMessaging, ConnectionStatus = ConnectionStatus.Disabled, ConnectionStatusChangeReason = ConnectionStatusChangeReason.Client_Close }).ConfigureAwait(false); this.IotHubConnection.Release(this.deviceId); } async Task<Outcome> SendAmqpMessageAsync(AmqpMessage amqpMessage, CancellationToken cancellationToken) { Outcome outcome; try { SendingAmqpLink eventSendingLink = await this.GetEventSendingLinkAsync(cancellationToken).ConfigureAwait(false); outcome = await eventSendingLink.SendMessageAsync(amqpMessage, new ArraySegment<byte>(Guid.NewGuid().ToByteArray()), AmqpConstants.NullBinary, this.operationTimeout).ConfigureAwait(false); } catch (Exception exception) { if (exception.IsFatal()) { throw; } throw AmqpClientHelper.ToIotHubClientContract(exception); } return outcome; } async Task<Outcome> SendAmqpMethodResponseAsync(AmqpMessage amqpMessage, CancellationToken cancellationToken) { Outcome outcome; try { SendingAmqpLink methodRespSendingLink = await this.GetMethodSendingLinkAsync(cancellationToken).ConfigureAwait(false); outcome = await methodRespSendingLink.SendMessageAsync(amqpMessage, new ArraySegment<byte>(Guid.NewGuid().ToByteArray()), AmqpConstants.NullBinary, this.operationTimeout).ConfigureAwait(false); } catch (Exception exception) { if (exception.IsFatal()) { throw; } throw AmqpClientHelper.ToIotHubClientContract(exception); } return outcome; } private async Task<AmqpMessage> RoundTripTwinMessage(AmqpMessage amqpMessage, CancellationToken cancellationToken) { string correlationId = Guid.NewGuid().ToString(); AmqpMessage response = null; try { Outcome outcome; SendingAmqpLink eventSendingLink = await this.GetTwinSendingLinkAsync(cancellationToken).ConfigureAwait(false); amqpMessage.Properties.CorrelationId = correlationId; this.twinResponseCompletions[correlationId] = new TaskCompletionSource<AmqpMessage>(); outcome = await eventSendingLink.SendMessageAsync(amqpMessage, new ArraySegment<byte>(Guid.NewGuid().ToByteArray()), AmqpConstants.NullBinary, this.operationTimeout).ConfigureAwait(false); if (outcome.DescriptorCode != Accepted.Code) { throw AmqpErrorMapper.GetExceptionFromOutcome(outcome); } var receivingTask = this.twinResponseCompletions[correlationId].Task; if (await Task.WhenAny(receivingTask, Task.Delay(TimeSpan.FromSeconds(ResponseTimeoutInSeconds))).ConfigureAwait(false) == receivingTask) { // Task completed within timeout. // Consider that the task may have faulted or been canceled. // We re-await the task so that any exceptions/cancellation is rethrown. response = await receivingTask.ConfigureAwait(false); } else { // Timeout happen throw new TimeoutException(); } } finally { TaskCompletionSource<AmqpMessage> throwAway; this.twinResponseCompletions.TryRemove(correlationId, out throwAway); } return response; } public override async Task<Twin> SendTwinGetAsync(CancellationToken cancellationToken) { try { await EnableTwinPatchAsync(cancellationToken).ConfigureAwait(false); AmqpMessage amqpMessage = AmqpMessage.Create(); amqpMessage.MessageAnnotations.Map["operation"] = "GET"; var response = await RoundTripTwinMessage(amqpMessage, cancellationToken).ConfigureAwait(false); return TwinFromResponse(response); } catch (Exception exception) { if (exception.IsFatal()) { throw; } throw AmqpClientHelper.ToIotHubClientContract(exception); } } public override async Task SendTwinPatchAsync(TwinCollection reportedProperties, CancellationToken cancellationToken) { try { await EnableTwinPatchAsync(cancellationToken).ConfigureAwait(false); var body = JsonConvert.SerializeObject(reportedProperties); var bodyStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(body)); var amqpMessage = AmqpMessage.Create(bodyStream, true); amqpMessage.MessageAnnotations.Map["operation"] = "PATCH"; amqpMessage.MessageAnnotations.Map["resource"] = "/properties/reported"; amqpMessage.MessageAnnotations.Map["version"] = null; var response = await RoundTripTwinMessage(amqpMessage, cancellationToken).ConfigureAwait(false); VerifyResponseMessage(response); } catch (Exception exception) { if (exception.IsFatal()) { throw; } throw AmqpClientHelper.ToIotHubClientContract(exception); } } private void VerifyResponseMessage(AmqpMessage response) { if (response != null) { int status; if (response.MessageAnnotations.Map.TryGetValue(ResponseStatusName, out status)) { if (status >= 400) { throw new InvalidOperationException("Service rejected the message with status: "+ status); } } } else { throw new InvalidOperationException("Service response is null."); } } private void HandleTwinMessage(AmqpMessage message, ReceivingAmqpLink link) { link.DisposeDelivery(message, true, AmqpConstants.AcceptedOutcome); string correlationId = message.Properties?.CorrelationId?.ToString(); if (correlationId != null) { // If we have a correlation id, it must be a response, complete the task. TaskCompletionSource<AmqpMessage> task; if (this.twinResponseCompletions.TryRemove(correlationId, out task)) { task.SetResult(message); } } else { // No correlation id? Must be a patch. if (this.onDesiredStatePatchListener != null) { using (StreamReader reader = new StreamReader(message.BodyStream, System.Text.Encoding.UTF8)) { string patch = reader.ReadToEnd(); var props = JsonConvert.DeserializeObject<TwinCollection>(patch); this.onDesiredStatePatchListener(props); } } } } private Twin TwinFromResponse(AmqpMessage message) { using (StreamReader reader = new StreamReader(message.BodyStream, System.Text.Encoding.UTF8)) { string body = reader.ReadToEnd(); var props = JsonConvert.DeserializeObject<Microsoft.Azure.Devices.Shared.TwinProperties>(body); return new Twin(props); } } async Task DisposeMessageAsync(string lockToken, Outcome outcome, CancellationToken cancellationToken) { ArraySegment<byte> deliveryTag = IotHubConnection.ConvertToDeliveryTag(lockToken); Outcome disposeOutcome; try { ReceivingAmqpLink deviceBoundReceivingLink = await this.GetDeviceBoundReceivingLinkAsync(cancellationToken).ConfigureAwait(false); disposeOutcome = await deviceBoundReceivingLink.DisposeMessageAsync(deliveryTag, outcome, batchable: true, timeout: this.operationTimeout).ConfigureAwait(false); } catch (Exception exception) { if (exception.IsFatal()) { throw; } throw AmqpClientHelper.ToIotHubClientContract(exception); } if (disposeOutcome.DescriptorCode != Accepted.Code) { if (disposeOutcome.DescriptorCode == Rejected.Code) { var rejected = (Rejected)disposeOutcome; // Special treatment for NotFound amqp rejected error code in case of DisposeMessage if (rejected.Error != null && rejected.Error.Condition.Equals(AmqpErrorCode.NotFound)) { throw new DeviceMessageLockLostException(rejected.Error.Description); } } throw AmqpErrorMapper.GetExceptionFromOutcome(disposeOutcome); } } async Task<SendingAmqpLink> GetEventSendingLinkAsync(CancellationToken cancellationToken) { SendingAmqpLink eventSendingLink; if (!this.faultTolerantEventSendingLink.TryGetOpenedObject(out eventSendingLink)) { eventSendingLink = await this.faultTolerantEventSendingLink.GetOrCreateAsync(this.openTimeout, cancellationToken).ConfigureAwait(false); } return eventSendingLink; } async Task<SendingAmqpLink> CreateEventSendingLinkAsync(TimeSpan timeout, CancellationToken cancellationToken) { string path = string.Format(CultureInfo.InvariantCulture, CommonConstants.DeviceEventPathTemplate, System.Net.WebUtility.UrlEncode(this.deviceId)); return await this.IotHubConnection.CreateSendingLinkAsync(path, this.iotHubConnectionString, this.deviceId, IotHubConnection.SendingLinkType.TelemetryEvents, timeout, this.productInfo, cancellationToken).ConfigureAwait(false); } async Task<ReceivingAmqpLink> GetDeviceBoundReceivingLinkAsync(CancellationToken cancellationToken) { ReceivingAmqpLink deviceBoundReceivingLink; if (!this.faultTolerantDeviceBoundReceivingLink.TryGetOpenedObject(out deviceBoundReceivingLink)) { deviceBoundReceivingLink = await this.faultTolerantDeviceBoundReceivingLink.GetOrCreateAsync(this.openTimeout, cancellationToken).ConfigureAwait(false); } return deviceBoundReceivingLink; } async Task<ReceivingAmqpLink> CreateDeviceBoundReceivingLinkAsync(TimeSpan timeout, CancellationToken cancellationToken) { string path = string.Format(CultureInfo.InvariantCulture, CommonConstants.DeviceBoundPathTemplate, System.Net.WebUtility.UrlEncode(this.deviceId)); return await this.IotHubConnection.CreateReceivingLinkAsync(path, this.iotHubConnectionString, this.deviceId, IotHubConnection.ReceivingLinkType.C2DMessages, this.prefetchCount, timeout, this.productInfo, cancellationToken).ConfigureAwait(false); } async Task<SendingAmqpLink> GetMethodSendingLinkAsync(CancellationToken cancellationToken) { SendingAmqpLink methodSendingLink; if (!this.faultTolerantMethodSendingLink.TryGetOpenedObject(out methodSendingLink)) { methodSendingLink = await this.faultTolerantMethodSendingLink.GetOrCreateAsync(this.openTimeout, cancellationToken).ConfigureAwait(false); } return methodSendingLink; } async Task<SendingAmqpLink> CreateMethodSendingLinkAsync(TimeSpan timeout, CancellationToken cancellationToken) { string path = string.Format(CultureInfo.InvariantCulture, CommonConstants.DeviceMethodPathTemplate, System.Net.WebUtility.UrlEncode(this.deviceId)); SendingAmqpLink methodSendingLink = await this.IotHubConnection.CreateSendingLinkAsync(path, this.iotHubConnectionString, this.methodConnectionCorrelationId, IotHubConnection.SendingLinkType.Methods, timeout, this.productInfo, cancellationToken).ConfigureAwait(false); MyStringCopy(methodSendingLink.Name, out methodSendingLinkName); this.SafeAddClosedMethodSendingLinkHandler = this.linkClosedListener; methodSendingLink.SafeAddClosed(async (o, ea) => await Task.Run(async () => { await this.SafeAddClosedMethodSendingLinkHandler( o, new ConnectionEventArgs { ConnectionType = ConnectionType.AmqpMethodSending, ConnectionStatus = ConnectionStatus.Disconnected_Retrying, ConnectionStatusChangeReason = ConnectionStatusChangeReason.No_Network }).ConfigureAwait(false); } ).ConfigureAwait(false)); return methodSendingLink; } async Task<ReceivingAmqpLink> GetMethodReceivingLinkAsync(CancellationToken cancellationToken) { ReceivingAmqpLink methodReceivingLink; if (!this.faultTolerantMethodReceivingLink.TryGetOpenedObject(out methodReceivingLink)) { methodReceivingLink = await this.faultTolerantMethodReceivingLink.GetOrCreateAsync(this.openTimeout, cancellationToken).ConfigureAwait(false); } return methodReceivingLink; } async Task<ReceivingAmqpLink> CreateMethodReceivingLinkAsync(TimeSpan timeout, CancellationToken cancellationToken) { string path = string.Format(CultureInfo.InvariantCulture, CommonConstants.DeviceMethodPathTemplate, System.Net.WebUtility.UrlEncode(this.deviceId)); ReceivingAmqpLink methodReceivingLink = await IotHubConnection.CreateReceivingLinkAsync(path, iotHubConnectionString, methodConnectionCorrelationId, IotHubConnection.ReceivingLinkType.Methods, prefetchCount, timeout, productInfo, cancellationToken).ConfigureAwait(false); methodReceivingLink.RegisterMessageListener(amqpMessage => { MethodRequestInternal methodRequestInternal = MethodConverter.ConstructMethodRequestFromAmqpMessage(amqpMessage); methodReceivingLink.DisposeDelivery(amqpMessage, true, AmqpConstants.AcceptedOutcome); this.messageListener(methodRequestInternal); }); MyStringCopy(methodReceivingLink.Name, out methodReceivingLinkName); this.SafeAddClosedMethodReceivingLinkHandler = this.linkClosedListener; methodReceivingLink.SafeAddClosed(async (o, ea) => await Task.Run(async () => { await this.SafeAddClosedMethodReceivingLinkHandler( o, new ConnectionEventArgs { ConnectionType = ConnectionType.AmqpMethodReceiving, ConnectionStatus = ConnectionStatus.Disconnected_Retrying, ConnectionStatusChangeReason = ConnectionStatusChangeReason.No_Network }).ConfigureAwait(false); } ).ConfigureAwait(false)); return methodReceivingLink; } async Task<SendingAmqpLink> GetTwinSendingLinkAsync(CancellationToken cancellationToken) { SendingAmqpLink twinSendingLink; if (!this.faultTolerantTwinSendingLink.TryGetOpenedObject(out twinSendingLink)) { twinSendingLink = await this.faultTolerantTwinSendingLink.GetOrCreateAsync(this.openTimeout, cancellationToken).ConfigureAwait(false); } return twinSendingLink; } async Task<SendingAmqpLink> CreateTwinSendingLinkAsync(TimeSpan timeout, CancellationToken cancellationToken) { string path = string.Format(CultureInfo.InvariantCulture, CommonConstants.DeviceTwinPathTemplate, System.Net.WebUtility.UrlEncode(this.deviceId)); SendingAmqpLink twinSendingLink = await this.IotHubConnection.CreateSendingLinkAsync(path, this.iotHubConnectionString, this.twinConnectionCorrelationId, IotHubConnection.SendingLinkType.Twin, timeout, this.productInfo, cancellationToken).ConfigureAwait(false); MyStringCopy(twinSendingLink.Name, out twinSendingLinkName); this.SafeAddClosedTwinSendingLinkHandler = this.linkClosedListener; twinSendingLink.SafeAddClosed(async (o, ea) => await Task.Run(async () => { await this.SafeAddClosedTwinSendingLinkHandler( o, new ConnectionEventArgs { ConnectionType = ConnectionType.AmqpTwinSending, ConnectionStatus = ConnectionStatus.Disconnected_Retrying, ConnectionStatusChangeReason = ConnectionStatusChangeReason.No_Network }).ConfigureAwait(false); foreach (var entry in twinResponseCompletions) { TaskCompletionSource<AmqpMessage> task; if (this.twinResponseCompletions.TryRemove(entry.Key, out task)) { task.SetCanceled(); } } } ).ConfigureAwait(false)); return twinSendingLink; } async Task<ReceivingAmqpLink> GetTwinReceivingLinkAsync(CancellationToken cancellationToken) { ReceivingAmqpLink twinReceivingLink; if (!this.faultTolerantTwinReceivingLink.TryGetOpenedObject(out twinReceivingLink)) { twinReceivingLink = await this.faultTolerantTwinReceivingLink.GetOrCreateAsync(this.openTimeout, cancellationToken).ConfigureAwait(false); } return twinReceivingLink; } async Task<ReceivingAmqpLink> CreateTwinReceivingLinkAsync(TimeSpan timeout, CancellationToken cancellationToken) { string path = string.Format(CultureInfo.InvariantCulture, CommonConstants.DeviceTwinPathTemplate, System.Net.WebUtility.UrlEncode(this.deviceId)); ReceivingAmqpLink twinReceivingLink = await this.IotHubConnection.CreateReceivingLinkAsync(path, this.iotHubConnectionString, this.twinConnectionCorrelationId, IotHubConnection.ReceivingLinkType.Twin, this.prefetchCount, timeout, this.productInfo, cancellationToken).ConfigureAwait(false); MyStringCopy(twinReceivingLink.Name, out twinReceivingLinkName); this.SafeAddClosedTwinReceivingLinkHandler = this.linkClosedListener; twinReceivingLink.SafeAddClosed(async (o, ea) => await Task.Run(async () => { await this.SafeAddClosedTwinReceivingLinkHandler( o, new ConnectionEventArgs { ConnectionType = ConnectionType.AmqpTwinReceiving, ConnectionStatus = ConnectionStatus.Disconnected_Retrying, ConnectionStatusChangeReason = ConnectionStatusChangeReason.No_Network }).ConfigureAwait(false); } ).ConfigureAwait(false)); twinReceivingLink.RegisterMessageListener(message => this.HandleTwinMessage(message, twinReceivingLink)); return twinReceivingLink; } private void MyStringCopy(String source, out String destination) { char[] chars = new Char[source.Length]; source.CopyTo(0, chars, 0, source.Length); destination = new String(chars); } } }
47.97983
301
0.626679
[ "MIT" ]
nikoruhe54/x509Auth
iothub/device/src/Transport/AmqpTransportHandler.cs
45,199
C#
using NetworkService.Model; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace NetworkService.ViewModel { public class NetworkGraphViewModel :BindableBase { public static ObservableCollection<Entity> Entities { get; set; } = new ObservableCollection<Entity>(); public ObservableCollection<string> Ids { get; private set; } = new ObservableCollection<string>(); private int value0; private int value1; private int value2; private int value3; private int value4; public int Value0 { get { return value0; } set { if(value != value0) { value0 = value; OnPropertyChanged("Value0"); } } } public int Value1 { get { return value1; } set { if (value != value1) { value1 = value; OnPropertyChanged("Value1"); } } } public int Value2 { get { return value2; } set { if (value != value2) { value2 = value; OnPropertyChanged("Value2"); } } } public int Value3 { get { return value3; } set { if (value != value3) { value3 = value; OnPropertyChanged("Value3"); } } } public int Value4 { get { return value4; } set { if (value != value4) { value4 = value; OnPropertyChanged("Value4"); } } } private string selectedValue; public string SelectedValue { get { return selectedValue; } set { if(value != selectedValue) { selectedValue = value; OnPropertyChanged("SelectedValue"); } } } private string FilterValue = null; public MyICommand ShowFilter { get; set; } public NetworkGraphViewModel() { for(int i=0; i<MainWindowViewModel.Entities.Count; i++) { Ids.Add(i.ToString()); } value0 = 550; value1 = 550; value2 = 550; value3 = 550; value4 = 550; ShowFilter = new MyICommand(OnShowFilter); ReadNewEntities(MainWindowViewModel.Path); } public void ReadNewEntities(string s) { var readThread = new Thread(() => { while (true) { try { if (File.Exists(s)) { string str; string[] value; double num; string index; using (StreamReader reader = new StreamReader(s)) { Entities.Clear(); while (reader.Peek() >= 0) { str = reader.ReadLine(); value = str.Split(':', '_'); num = int.Parse(value[5]); num = 550 - num * 4; index = value[4]; Entity entity = new Entity(); entity.EntityValue = num; entity.Id = index; if (FilterValue == null) { Entities.Insert(0, entity); } else { if (FilterValue.Equals(entity.Id)) Entities.Insert(0, entity); } } } Value0 = (int)Entities[0].EntityValue; Value1 = (int)Entities[1].EntityValue; Value2 = (int)Entities[2].EntityValue; Value3 = (int)Entities[3].EntityValue; Value4 = (int)Entities[4].EntityValue; } }catch (Exception ex) { Console.WriteLine(ex.Message); } Thread.Sleep(1000); } }); readThread.IsBackground = true; readThread.Start(); } private void OnShowFilter() { FilterValue = SelectedValue; Console.WriteLine("FilterValue = "); Console.WriteLine(FilterValue); } } }
28.659898
111
0.362735
[ "MIT" ]
sdragan15/Evidencija_Parkinga
NetworkService/NetworkService/ViewModel/NetworkGraphViewModel.cs
5,648
C#
// ReSharper disable UnusedMember.Global namespace System.Net.WebSockets.Wamp; public static class WampBasicProfile { public enum WampBrokerMessageTypeCode : ushort { Hello = 1, Welcome = 2, Abort = 3, Goodbye = 6, Error = 8, Publish = 16, Published = 17, Subscribe = 33, Subscribed = 33, Unsubscribe = 34, Unsubscribed = 35, Event = 36, Extension = 0 } public enum WampCalleeMessageTypeCode : ushort { Hello = 1, Welcome = 2, Abort = 3, Goodbye = 6, Error = 8, Register = 64, Registered = 65, Unregister = 66, Unregistered = 67, Invocation = 68, Yield = 70, Extension = 0 } public enum WampCallerMessageTypeCode : ushort { Hello = 1, Welcome = 2, Abort = 3, Goodbye = 6, Error = 8, Subscribe = 33, Subscribed = 33, Unsubscribe = 34, Unsubscribed = 35, Event = 36, Extension = 0 } public enum WampDealerMessageTypeCode : ushort { Hello = 1, Welcome = 2, Abort = 3, Goodbye = 6, Error = 8, Call = 48, Result = 58, Register = 64, Registered = 65, Unregister = 66, Unregistered = 67, Invocation = 68, Yield = 70, Extension = 0 } public enum WampMessageTypeCode : ushort { Hello = 1, Welcome = 2, Abort = 3, Goodbye = 6, Error = 8, Publish = 16, Published = 17, Subscribe = 33, Subscribed = 33, Unsubscribe = 34, Unsubscribed = 35, Event = 36, Call = 48, Result = 58, Register = 64, Registered = 65, Unregister = 66, Unregistered = 67, Invocation = 68, Yield = 70, Extension = 0 } public enum WampPublisherMessageTypeCode : ushort { Hello = 1, Welcome = 2, Abort = 3, Goodbye = 6, Error = 8, Publish = 16, Published = 17, Extension = 0 } public enum WampRoleMessageTypeCode : ushort { Hello = 1, Welcome = 2, Abort = 3, Goodbye = 6, Error = 8 } public enum WampSubscriberMessageTypeCode : ushort { Hello = 1, Welcome = 2, Abort = 3, Goodbye = 6, Error = 8, Subscribe = 33, Subscribed = 33, Unsubscribe = 34, Unsubscribed = 35, Event = 36, Extension = 0 } }
18.15
55
0.442493
[ "Unlicense" ]
mikaeldui/dotnet-net-websockets-wamp
DotNet.Net.WebSockets.Wamp/Messages/WampBasicProfile.cs
2,906
C#
using System; using System.Text; using System.Collections.Generic; namespace PowerForensics.FileSystems.Ntfs { /// <summary> /// /// </summary> public class AttrDef { #region Enums /// <summary> /// /// </summary> [Flags] public enum ATTR_DEF_ENTRY { /// <summary> /// /// </summary> INDEX = 0x02, /// <summary> /// /// </summary> ALWAYS_RESIDENT = 0x40, /// <summary> /// /// </summary> ALWAYS_NONRESIDENT = 0x80 } #endregion Enums #region Properties /// <summary> /// /// </summary> public readonly string Name; /// <summary> /// /// </summary> public readonly uint Type; /// <summary> /// /// </summary> public readonly uint DisplayRule; /// <summary> /// /// </summary> public readonly string CollationRule; /// <summary> /// /// </summary> public readonly ATTR_DEF_ENTRY Flags; /// <summary> /// /// </summary> public readonly ulong MinSize; /// <summary> /// /// </summary> public readonly ulong MaxSize; #endregion Properties #region Constructors private AttrDef(byte[] bytes, int offset) { Name = Encoding.Unicode.GetString(bytes, offset, 0x80).TrimEnd('\0'); Type = BitConverter.ToUInt32(bytes, offset + 0x80); DisplayRule = BitConverter.ToUInt32(bytes, offset + 0x84); #region CollationRuleSwitch switch (BitConverter.ToUInt32(bytes, 0x88)) { case 0x00: CollationRule = "Binary"; break; case 0x01: CollationRule = "Filename"; break; case 0x02: CollationRule = "Unicode String"; break; case 0x10: CollationRule = "Unsigned Long"; break; case 0x11: CollationRule = "SID"; break; case 0x12: CollationRule = "Security Hash"; break; case 0x13: CollationRule = "Multiple Unsigned Longs"; break; default: CollationRule = "unknown"; break; } #endregion CollationRuleSwitch Flags = (ATTR_DEF_ENTRY)BitConverter.ToUInt32(bytes, offset + 0x8C); MinSize = BitConverter.ToUInt64(bytes, offset + 0x90); MaxSize = BitConverter.ToUInt64(bytes, offset + 0x98); } #endregion Constructors #region Static Methods /// <summary> /// /// </summary> /// <param name="volume"></param> /// <returns></returns> public static AttrDef[] GetInstances(string volume) { Helper.getVolumeName(ref volume); FileRecord record = FileRecord.Get(volume, MftIndex.ATTRDEF_INDEX, true); return AttrDef.GetInstances(record.GetContent()); } /// <summary> /// /// </summary> /// <param name="path"></param> /// <returns></returns> public static AttrDef[] GetInstancesByPath(string path) { FileRecord record = FileRecord.Get(path, true); return AttrDef.GetInstances(record.GetContent()); } private static AttrDef[] GetInstances(byte[] bytes) { // Instantiate a List of AttrDef objects for output List<AttrDef> adList = new List<AttrDef>(); // Iterate through 160 byte chunks (representing an AttrDef object) for (int i = 0; (i < bytes.Length) && (bytes[i] != 0); i += 0xA0) { // Intantiate a new AttrDef object and add it to the adList List of AttrDef objects adList.Add(new AttrDef(bytes, i)); } return adList.ToArray(); } #endregion Static Methods } }
27.006135
99
0.471149
[ "MIT" ]
Cyberdeep/PowerForensics
src/PowerForensicsCore/src/PowerForensics.FileSystems.Ntfs/AttrDef.cs
4,404
C#
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json.Linq; using System.Runtime.Serialization; namespace XBMCRPC.Audio.Details { public class Artist : XBMCRPC.Audio.Details.Base { public string artist { get; set; } public int artistid { get; set; } public string born { get; set; } public bool compilationartist { get; set; } public string description { get; set; } public string died { get; set; } public string disbanded { get; set; } public string formed { get; set; } public global::System.Collections.Generic.List<string> instrument { get; set; } public global::System.Collections.Generic.List<string> mood { get; set; } public string musicbrainzartistid { get; set; } public global::System.Collections.Generic.List<string> style { get; set; } public global::System.Collections.Generic.List<string> yearsactive { get; set; } } }
38.84
87
0.675592
[ "MIT" ]
RyanMelenaNoesis/ElveKodiDriver
src/NoesisLabs.Elve.Kodi/XBMCRPC/XBMCRPC/Audio/Details/Artist.cs
971
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Kusto.Cmdlets { using static Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Extensions; /// <summary>Updates a database.</summary> /// <remarks> /// [OpenAPI] Update=>PATCH:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Kusto/Clusters/{clusterName}/Databases/{databaseName}" /// </remarks> [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.InternalExport] [global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsData.Update, @"AzKustoDatabase_UpdateViaIdentityExpanded", SupportsShouldProcess = true)] [global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabase))] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Description(@"Updates a database.")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Generated] public partial class UpdateAzKustoDatabase_UpdateViaIdentityExpanded : global::System.Management.Automation.PSCmdlet, Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener { /// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary> private string __correlationId = System.Guid.NewGuid().ToString(); /// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary> private global::System.Management.Automation.InvocationInfo __invocationInfo; /// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary> private string __processRecordId; /// <summary> /// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation. /// </summary> private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource(); /// <summary>when specified, runs this cmdlet as a PowerShell job</summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command as a job")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter AsJob { get; set; } /// <summary>Wait for .NET debugger to attach</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter Break { get; set; } /// <summary>The reference to the client API class.</summary> public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Kusto Client => Microsoft.Azure.PowerShell.Cmdlets.Kusto.Module.Instance.ClientAPI; /// <summary> /// The credentials, account, tenant, and subscription used for communication with Azure /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")] [global::System.Management.Automation.ValidateNotNull] [global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Azure)] public global::System.Management.Automation.PSObject DefaultProfile { get; set; } /// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; } /// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; } /// <summary>Backing field for <see cref="InputObject" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.IKustoIdentity _inputObject; /// <summary>Identity Parameter</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Identity Parameter", ValueFromPipeline = true)] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Path)] public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.IKustoIdentity InputObject { get => this._inputObject; set => this._inputObject = value; } /// <summary>Accessor for our copy of the InvocationInfo.</summary> public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } } /// <summary>Kind of the database</summary> [global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Kind of the database")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Info( Required = true, ReadOnly = false, Description = @"Kind of the database", SerializedName = @"kind", PossibleTypes = new [] { typeof(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.Kind) })] [global::System.Management.Automation.ArgumentCompleter(typeof(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.Kind))] public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support.Kind Kind { get => ParametersBody.Kind; set => ParametersBody.Kind = value; } /// <summary>Resource location.</summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Resource location.")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Body)] [Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Info( Required = false, ReadOnly = false, Description = @"Resource location.", SerializedName = @"location", PossibleTypes = new [] { typeof(string) })] public string Location { get => ParametersBody.Location ?? null; set => ParametersBody.Location = value; } /// <summary> /// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called. /// </summary> global::System.Action Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel; /// <summary><see cref="IEventListener" /> cancellation token.</summary> global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener.Token => _cancellationTokenSource.Token; /// <summary> /// when specified, will make the remote call, and return an AsyncOperationResponse, letting the remote operation continue /// asynchronously. /// </summary> [global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "Run the command asynchronously")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter NoWait { get; set; } /// <summary>Backing field for <see cref="ParametersBody" /> property.</summary> private Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabase _parametersBody= new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.Database(); /// <summary>Class representing a Kusto database.</summary> private Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabase ParametersBody { get => this._parametersBody; set => this._parametersBody = value; } /// <summary> /// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.HttpPipeline" /> that the remote call will use. /// </summary> private Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.HttpPipeline Pipeline { get; set; } /// <summary>The URI for the proxy server to use</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public global::System.Uri Proxy { get; set; } /// <summary>Credentials for a proxy server to use for the remote call</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")] [global::System.Management.Automation.ValidateNotNull] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public global::System.Management.Automation.PSCredential ProxyCredential { get; set; } /// <summary>Use the default credentials for the proxy</summary> [global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")] [global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.Category(global::Microsoft.Azure.PowerShell.Cmdlets.Kusto.ParameterCategory.Runtime)] public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; } /// <summary> /// <c>overrideOnDefault</c> will be called before the regular onDefault has been processed, allowing customization of what /// happens on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.ICloudError" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onDefault method should be processed, or if the method should /// return immediately (set to true to skip further processing )</param> partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.ICloudError> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens /// on that response. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabase" /// /> from the remote call</param> /// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return /// immediately (set to true to skip further processing )</param> partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabase> response, ref global::System.Threading.Tasks.Task<bool> returnNow); /// <summary> /// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet) /// </summary> protected override void BeginProcessing() { Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials); if (Break) { Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.AttachDebugger.Break(); } ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Creates a duplicate instance of this cmdlet (via JSON serialization).</summary> /// <returns>a duplicate instance of UpdateAzKustoDatabase_UpdateViaIdentityExpanded</returns> public Microsoft.Azure.PowerShell.Cmdlets.Kusto.Cmdlets.UpdateAzKustoDatabase_UpdateViaIdentityExpanded Clone() { var clone = new UpdateAzKustoDatabase_UpdateViaIdentityExpanded(); clone.__correlationId = this.__correlationId; clone.__processRecordId = this.__processRecordId; clone.DefaultProfile = this.DefaultProfile; clone.InvocationInformation = this.InvocationInformation; clone.Proxy = this.Proxy; clone.Pipeline = this.Pipeline; clone.AsJob = this.AsJob; clone.Break = this.Break; clone.ProxyCredential = this.ProxyCredential; clone.ProxyUseDefaultCredentials = this.ProxyUseDefaultCredentials; clone.HttpPipelinePrepend = this.HttpPipelinePrepend; clone.HttpPipelineAppend = this.HttpPipelineAppend; clone.ParametersBody = this.ParametersBody; return clone; } /// <summary>Performs clean-up after the command execution</summary> protected override void EndProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } /// <summary>Handles/Dispatches events during the call to the REST service.</summary> /// <param name="id">The message id</param> /// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param> /// <param name="messageData">Detailed message data for the message event.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed. /// </returns> async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.EventData> messageData) { using( NoSynchronizationContext ) { if (token.IsCancellationRequested) { return ; } switch ( id ) { case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Verbose: { WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Warning: { WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Information: { // When an operation supports asjob, Information messages must go thru verbose. WriteVerbose($"INFORMATION: {(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Debug: { WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}"); return ; } case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.Error: { WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) ); return ; } case Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.DelayBeforePolling: { if (true == MyInvocation?.BoundParameters?.ContainsKey("NoWait")) { var data = messageData(); if (data.ResponseMessage is System.Net.Http.HttpResponseMessage response) { var asyncOperation = response.GetFirstHeader(@"Azure-AsyncOperation"); var location = response.GetFirstHeader(@"Location"); var uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? response.RequestMessage.RequestUri.AbsoluteUri : location : asyncOperation; WriteObject(new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell.AsyncOperationResponse { Target = uri }); // do nothing more. data.Cancel(); return; } } break; } } await Microsoft.Azure.PowerShell.Cmdlets.Kusto.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null ); if (token.IsCancellationRequested) { return ; } WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}"); } } /// <summary>Performs execution of the command.</summary> protected override void ProcessRecord() { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } __processRecordId = System.Guid.NewGuid().ToString(); try { // work if (ShouldProcess($"Call remote 'DatabasesUpdate' operation")) { if (true == MyInvocation?.BoundParameters?.ContainsKey("AsJob")) { var instance = this.Clone(); var job = new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell.AsyncJob(instance, this.MyInvocation.Line, this.MyInvocation.MyCommand.Name, this._cancellationTokenSource.Token, this._cancellationTokenSource.Cancel); JobRepository.Add(job); var task = instance.ProcessRecordAsync(); job.Monitor(task); WriteObject(job); } else { using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token) ) { asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token); } } } } catch (global::System.AggregateException aggregateException) { // unroll the inner exceptions to get the root cause foreach( var innerException in aggregateException.Flatten().InnerExceptions ) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } } catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null) { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } // Write exception out to error channel. WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) ); } finally { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletProcessRecordEnd).Wait(); } } /// <summary>Performs execution of the command, working asynchronously if required.</summary> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> protected async global::System.Threading.Tasks.Task ProcessRecordAsync() { using( NoSynchronizationContext ) { await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } Pipeline = Microsoft.Azure.PowerShell.Cmdlets.Kusto.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName); if (null != HttpPipelinePrepend) { Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend); } if (null != HttpPipelineAppend) { Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend); } // get the client instance try { await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } if (InputObject?.Id != null) { await this.Client.DatabasesUpdateViaIdentity(InputObject.Id, ParametersBody, onOk, onDefault, this, Pipeline); } else { // try to call with PATH parameters from Input Object if (null == InputObject.ResourceGroupName) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ResourceGroupName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } if (null == InputObject.ClusterName) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.ClusterName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } if (null == InputObject.DatabaseName) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.DatabaseName"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } if (null == InputObject.SubscriptionId) { ThrowTerminatingError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception("InputObject has null value for InputObject.SubscriptionId"),string.Empty, global::System.Management.Automation.ErrorCategory.InvalidArgument, InputObject) ); } await this.Client.DatabasesUpdate(InputObject.ResourceGroupName ?? null, InputObject.ClusterName ?? null, InputObject.DatabaseName ?? null, InputObject.SubscriptionId ?? null, ParametersBody, onOk, onDefault, this, Pipeline); } await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; } } catch (Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.UndeclaredResponseException urexception) { WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ParametersBody}) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action } }); } finally { await ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.Events.CmdletProcessRecordAsyncEnd); } } } /// <summary>Interrupts currently running code within the command.</summary> protected override void StopProcessing() { ((Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.IEventListener)this).Cancel(); base.StopProcessing(); } /// <summary> /// Intializes a new instance of the <see cref="UpdateAzKustoDatabase_UpdateViaIdentityExpanded" /> cmdlet class. /// </summary> public UpdateAzKustoDatabase_UpdateViaIdentityExpanded() { } /// <summary> /// a delegate that is called when the remote service returns default (any response code not handled elsewhere). /// </summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.ICloudError" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.ICloudError> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnDefault(responseMessage, response, ref _returnNow); // if overrideOnDefault has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // Error Response : default var code = (await response)?.Code; var message = (await response)?.Message; if ((null == code || null == message)) { // Unrecognized Response. Create an error record based on what we have. var ex = new Microsoft.Azure.PowerShell.Cmdlets.Kusto.Runtime.RestException<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.ICloudError>(responseMessage, await response); WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ParametersBody }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action } }); } else { WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { body=ParametersBody }) { ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty } }); } } } /// <summary>a delegate that is called when the remote service returns 200 (OK).</summary> /// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param> /// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabase" /// /> from the remote call</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed. /// </returns> private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabase> response) { using( NoSynchronizationContext ) { var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false); overrideOnOk(responseMessage, response, ref _returnNow); // if overrideOnOk has returned true, then return right away. if ((null != _returnNow && await _returnNow)) { return ; } // onOk - response for 200 / application/json // (await response) // should be Microsoft.Azure.PowerShell.Cmdlets.Kusto.Models.Api202101.IDatabase WriteObject((await response)); } } } }
73.052301
451
0.654601
[ "MIT" ]
Agazoth/azure-powershell
src/Kusto/generated/cmdlets/UpdateAzKustoDatabase_UpdateViaIdentityExpanded.cs
34,442
C#
/********************************************* 作者:曹旭升 QQ:279060597 访问博客了解详细介绍及更多内容: http://blog.shengxunwei.com **********************************************/ using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Xml; using Microsoft.Practices.EnterpriseLibrary.Logging; using Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.Tests; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging.Tests { [TestClass] public class LoggingExceptionHandlerFixture { [TestMethod] public void ExceptionHandledThroughLoggingBlock() { MockTraceListener.Reset(); Assert.IsFalse(ExceptionPolicy.HandleException(new Exception("TEST EXCEPTION"), "Logging Policy")); Assert.AreEqual(1, MockTraceListener.LastEntry.Categories.Count); Assert.IsTrue(MockTraceListener.LastEntry.Categories.Contains("TestCat")); Assert.AreEqual(5, MockTraceListener.LastEntry.EventId); Assert.AreEqual(TraceEventType.Error, MockTraceListener.LastEntry.Severity); Assert.AreEqual("TestTitle", MockTraceListener.LastEntry.Title); } [TestMethod] [ExpectedException(typeof(ExceptionHandlingException))] public void BadFormatterThrowsExceptionWhenHandlingExceptionWithLoggingBlock() { ExceptionPolicy.HandleException(new Exception("TEST EXCEPTION"), "Bad Formatter Logging Policy"); } [TestMethod] public void MultipleRequestsUseSameLogWriterInstance() { MockTraceListener.Reset(); Assert.IsFalse(ExceptionPolicy.HandleException(new Exception("TEST EXCEPTION"), "Logging Policy")); Assert.IsFalse(ExceptionPolicy.HandleException(new Exception("TEST EXCEPTION"), "Logging Policy")); Assert.IsFalse(ExceptionPolicy.HandleException(new Exception("TEST EXCEPTION"), "Logging Policy")); Assert.AreEqual(3, MockTraceListener.Entries.Count); Assert.AreEqual(3, MockTraceListener.Instances.Count); Assert.AreSame(MockTraceListener.Instances[0], MockTraceListener.Instances[1]); Assert.AreSame(MockTraceListener.Instances[0], MockTraceListener.Instances[2]); } [TestMethod] public void LoggedExceptionCopiesExceptionDataForStringKeys() { MockTraceListener.Reset(); Exception exception = new Exception("TEST EXCEPTION"); object value = new object(); object key4 = new object(); exception.Data.Add("key1", value); exception.Data.Add("key2", "value"); exception.Data.Add("key3", 3); exception.Data.Add(key4, "value"); Assert.IsFalse(ExceptionPolicy.HandleException(exception, "Logging Policy")); Assert.AreEqual(1, MockTraceListener.Entries.Count); Assert.AreEqual(3, MockTraceListener.Entries[0].ExtendedProperties.Count); Assert.AreEqual(value, MockTraceListener.Entries[0].ExtendedProperties["key1"]); Assert.AreEqual("value", MockTraceListener.Entries[0].ExtendedProperties["key2"]); Assert.AreEqual(3, MockTraceListener.Entries[0].ExtendedProperties["key3"]); } [TestMethod] public void LoggedExceptionWithoutExceptionDataWorks() { MockTraceListener.Reset(); Exception exception = new Exception("TEST EXCEPTION"); Assert.IsFalse(ExceptionPolicy.HandleException(exception, "Logging Policy")); Assert.AreEqual(1, MockTraceListener.Entries.Count); Assert.AreEqual(0, MockTraceListener.Entries[0].ExtendedProperties.Count); } [TestMethod] public void LoggingHandlerUsesNewLoggingStackByDefault() { MockTraceListener.Reset(); Assert.IsFalse(ExceptionPolicy.HandleException(new Exception("TEST EXCEPTION"), "Logging Policy")); Logger.Write("Test"); Assert.AreEqual(2, MockTraceListener.Entries.Count); Assert.AreEqual(2, MockTraceListener.Instances.Count); Assert.AreNotSame(MockTraceListener.Instances[0], MockTraceListener.Instances[1]); } [TestMethod] public void LoggingHandlerUsesDefaultLoggingStackWhenIndicated() { MockTraceListener.Reset(); Assert.IsFalse(ExceptionPolicy.HandleException(new Exception("TEST EXCEPTION"), "Logging Policy - use default logger")); Logger.Write("Test"); Assert.AreEqual(2, MockTraceListener.Entries.Count); Assert.AreEqual(2, MockTraceListener.Instances.Count); Assert.AreSame(MockTraceListener.Instances[0], MockTraceListener.Instances[1]); } [TestMethod] public void LoggingHandlerCreatesFormatterWithTheDocumentedConstructor() { MockTraceListener.Reset(); ConstructorSensingExceptionFormatter.Instances.Clear(); Exception exception = new Exception("test exception"); Guid testGuid = Guid.NewGuid(); LoggingExceptionHandler handler = new LoggingExceptionHandler( "TestCat", 0, TraceEventType.Warning, "test", 0, typeof(ConstructorSensingExceptionFormatter), Logger.Writer); handler.HandleException(exception, testGuid); Assert.AreEqual(1, ConstructorSensingExceptionFormatter.Instances.Count); Assert.AreSame(exception, ConstructorSensingExceptionFormatter.Instances[0].Exception); Assert.AreEqual(testGuid, ConstructorSensingExceptionFormatter.Instances[0].HandlingInstanceId); } [TestMethod] public void CanUseLoggingHandlerWithXmlExceptionFormatter() { MockTraceListener.Reset(); Exception exception = new Exception("test exception"); Guid testGuid = Guid.NewGuid(); LoggingExceptionHandler handler = new LoggingExceptionHandler( "TestCat", 0, TraceEventType.Warning, "test", 10, typeof(XmlExceptionFormatter), Logger.Writer); handler.HandleException(exception, testGuid); Assert.AreEqual(1, MockTraceListener.Entries.Count); XmlDocument doc = new XmlDocument(); doc.LoadXml(MockTraceListener.Entries[0].Message); XmlNode element = doc.DocumentElement.SelectSingleNode("/Exception/@handlingInstanceId"); Assert.IsNotNull(element); Assert.AreEqual(testGuid.ToString("D", CultureInfo.InvariantCulture), element.InnerText); } public class ConstructorSensingExceptionFormatter : ExceptionFormatter { TextWriter writer; internal static readonly List<ConstructorSensingExceptionFormatter> Instances = new List<ConstructorSensingExceptionFormatter>(); public ConstructorSensingExceptionFormatter(TextWriter writer, Exception exception, Guid handlingInstanceId) : base(exception, handlingInstanceId) { this.writer = writer; Instances.Add(this); } public override void Format() { } protected override void WriteDescription() { throw new NotImplementedException(); } protected override void WriteDateTime(DateTime utcNow) { throw new NotImplementedException(); } protected override void WriteExceptionType(Type exceptionType) { throw new NotImplementedException(); } protected override void WriteMessage(string message) { throw new NotImplementedException(); } protected override void WriteSource(string source) { throw new NotImplementedException(); } protected override void WriteHelpLink(string helpLink) { throw new NotImplementedException(); } protected override void WriteStackTrace(string stackTrace) { throw new NotImplementedException(); } protected override void WritePropertyInfo(System.Reflection.PropertyInfo propertyInfo, object value) { throw new NotImplementedException(); } protected override void WriteFieldInfo(System.Reflection.FieldInfo fieldInfo, object value) { throw new NotImplementedException(); } protected override void WriteAdditionalInfo(System.Collections.Specialized.NameValueCollection additionalInformation) { throw new NotImplementedException(); } } } }
47.873737
133
0.613883
[ "MIT" ]
ckalvin-hub/Sheng.Winform.IDE
SourceCode/Source/EnterpriseLibrary/ExceptionHandling/Tests/Logging/LoggingExceptionHandlerFixture.cs
9,527
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Get the list of Service Providers that use a specific /// Communication Barring Incoming Criteria. /// The response is either a SystemCommunicationBarringServiceProviderGetIncomingCriteriaUsageListResponse or an ErrorResponse. /// <see cref="SystemCommunicationBarringServiceProviderGetIncomingCriteriaUsageListResponse"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""7f663d5135470c33ca64b0eed3c3aa0c:6566""}]")] public class SystemCommunicationBarringServiceProviderGetIncomingCriteriaUsageListRequest : BroadWorksConnector.Ocip.Models.C.OCIRequest { private string _name; [XmlElement(ElementName = "name", IsNullable = false, Namespace = "")] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:6566")] [MinLength(1)] [MaxLength(40)] public string Name { get => _name; set { NameSpecified = true; _name = value; } } [XmlIgnore] protected bool NameSpecified { get; set; } } }
32.727273
140
0.670139
[ "MIT" ]
Rogn/broadworks-connector-net
BroadworksConnector/Ocip/Models/SystemCommunicationBarringServiceProviderGetIncomingCriteriaUsageListRequest.cs
1,440
C#
using System.Collections.Generic; namespace Aris.Moe.Configuration { public interface INeedConfiguration { public string Name { get; } IEnumerable<string> GetConfigurationIssues(); } }
21.4
53
0.696262
[ "MIT" ]
Amiron49/Aris.Moe.Ocr.Translation.Overlay
Aris.Moe.Configuration/INeedConfiguration.cs
216
C#
using System.Text; using System; using PasswordManager.Bot.Commands.Enums; using System.Linq; namespace PasswordManager.Bot.Extensions { public static class StringExtensions { ///<summary></summary> ///<returns>https://value</returns> public static string BuildUrl(this string value) { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("string is null, whitespace or empty"); return (value.StartsWith("https://") || value.StartsWith("http://")) ? value.Trim() : "https://" + value.Trim(); } ///<summary></summary> /// ///<returns>first_word_in_string.com</returns> public static string AutoDomain(this string value) { if (string.IsNullOrWhiteSpace(value)) throw new ArgumentException("string is null, whitespace or empty"); int spaceIndex; string autoLink = (spaceIndex = value.IndexOf(' ')) == -1 ? value.ToLower() : value.Substring(0, spaceIndex).ToLower(); StringBuilder autoLinkBuilder = new StringBuilder(autoLink); int dotIndex; if (!((dotIndex = autoLink.IndexOf('.')) != -1)) { if(dotIndex == autoLink.Length-1) autoLinkBuilder.Append("com"); } else { autoLinkBuilder.Append(".com"); } return autoLinkBuilder.ToString(); } public static string ToZeroOneString(this bool param) { return param ? "1" : "0"; } /// <summary> /// This function retunrs reverse bool because it will be handled as new setting /// which must be opposite to last setting /// </summary> /// <param name="param"></param> /// <returns></returns> public static string ToReverseZeroOneString(this bool param) { return param ? "0" : "1"; } public static string ToEmojiString(this bool param, bool addSpace = false) { string result = param ? "✅" : "✖️"; if (addSpace) result += " "; return result; } public static string ToStringCode(this CallbackQueryCommandCode callbackCommandCode) => ((char)callbackCommandCode).ToString(); ///<summary></summary> /// <param name="setUpPasswordGeneratorCommandCode"></param> /// <returns><see cref="CallbackQueryCommandCode.SetUpPasswordGenerator"/> + setUpPasswordGeneratorCommandCode</returns> public static string ToStringCode(this SetUpPasswordGeneratorCommandCode setUpPasswordGeneratorCommandCode) => GetStringCode(CallbackQueryCommandCode.SetUpPasswordGenerator, (char)setUpPasswordGeneratorCommandCode); ///<summary></summary> /// <param name="addAccountCommandCode"></param> /// <returns><see cref="CallbackQueryCommandCode.AddAccount"/> + addAccountCommandCode</returns> public static string ToStringCode(this AddAccountCommandCode addAccountCommandCode) => GetStringCode(CallbackQueryCommandCode.AddAccount, (char)addAccountCommandCode); ///<summary></summary> /// <param name="selectLanguageCommandCode"></param> /// <returns><see cref="CallbackQueryCommandCode.SelectLanguage"/> + selectLanguageCommandCode</returns> public static string ToStringCode(this SelectLanguageCommandCode selectLanguageCommandCode) => GetStringCode(CallbackQueryCommandCode.SelectLanguage, (char)selectLanguageCommandCode); ///<summary></summary> /// <param name="updateAccountCommandCode"></param> /// <param name="accountId">Id of account to update</param> /// <returns><see cref="CallbackQueryCommandCode.UpdateAccount"/> + updateAccountCommandCode</returns> public static string ToStringCode(this UpdateAccountCommandCode updateAccountCommandCode, long accountId) => GetStringCode(CallbackQueryCommandCode.UpdateAccount, (char)updateAccountCommandCode, accountId); ///<summary></summary> /// <param name="updateAccountCommandCode"></param> /// <returns><see cref="CallbackQueryCommandCode.UpdateAccount"/> + updateAccountCommandCode</returns> public static string ToStringCode(this UpdateAccountCommandCode updateAccountCommandCode) => GetStringCode(CallbackQueryCommandCode.UpdateAccount, (char)updateAccountCommandCode); ///<summary></summary> /// <param name="deleteAccountCommandCode"></param> /// /// <param name="accountId">Id of account to update</param> /// <returns><see cref="CallbackQueryCommandCode.DeleteAccount"/> + deleteAccountCommandCode</returns> public static string ToStringCode(this DeleteAccountCommandCode deleteAccountCommandCode, long accountId) => GetStringCode(CallbackQueryCommandCode.DeleteAccount, (char)deleteAccountCommandCode, accountId); ///<summary></summary> /// <param name="generatePasswordCommandCode"></param> /// <returns><see cref="CallbackQueryCommandCode.GeneratePassword"/> + generatePasswordCommandCode</returns> public static string ToStringCode(this GeneratePasswordCommandCode generatePasswordCommandCode) => GetStringCode(CallbackQueryCommandCode.GeneratePassword, (char)generatePasswordCommandCode); /// <summary></summary> /// <param name="additionalCommand">Command that need to be appended to <paramref name="callbackQueryCommandCode"/></param> /// <returns><paramref name="callbackQueryCommandCode"/> + <paramref name="additionalCommand"/></returns> private static string GetStringCode(CallbackQueryCommandCode callbackQueryCommandCode, char additionalCommand) => new StringBuilder(callbackQueryCommandCode.ToStringCode()).Append(additionalCommand).ToString(); /// <summary></summary> /// <param name="additionalCommand">Command that need to be appended to <paramref name="callbackQueryCommandCode"/></param> /// <returns><paramref name="callbackQueryCommandCode"/> + <paramref name="additionalCommand"/></returns> private static string GetStringCode(CallbackQueryCommandCode callbackQueryCommandCode, char additionalCommand, object param) => new StringBuilder(callbackQueryCommandCode.ToStringCode()) .Append(additionalCommand) .Append(param.ToString()) .ToString(); ///returns null if there is no command in message public static string GetTextCommand(this string messageText) { //TODO: //remove '/' from returned message when using new commands without / if (messageText == null) throw new ArgumentNullException(nameof(messageText)); //Command that starts with '/' may contain args and must be separated from them if (messageText.StartsWith('/')) { string commandString = messageText.ToLower(); int cIndex = commandString.IndexOfAny(new char[] { ' ', '\n' }); return cIndex != -1 ? commandString.Substring(0, cIndex) : commandString; } return null; } //TODO: //unit test /// <param name="commandText">command with args</param> /// <returns>All commands args separated by new line, except command itself</returns> public static string[] GetCommandArgsByNewLine(this string commandText) { if (commandText == null) throw new ArgumentNullException(nameof(commandText)); if (commandText[0] != '/') throw new ArgumentException("command must start with '/'", nameof(commandText)); int indexOfSpace = commandText.IndexOf(' '); int indexOfNewLine = commandText.IndexOf('\n'); int firstArgStartIndex; //Equals to length of /command + space|\n after it //Assign to firstArgStartIndex lowest index + 1 if it's not -1 if (indexOfSpace == -1) { if (indexOfNewLine == -1) return null; firstArgStartIndex = indexOfNewLine + 1; } else { firstArgStartIndex = indexOfNewLine == -1 ? indexOfSpace + 1 : indexOfNewLine < indexOfSpace ? indexOfNewLine + 1 : indexOfSpace + 1; } return commandText.Remove(0, firstArgStartIndex) .Split('\n', StringSplitOptions.RemoveEmptyEntries); } //Chars that need to be escaped in Telegram MarkdownV2 private static readonly string[] charsToEscape = new char[] { '\\', '`', '_', '*', '[', ']', '(', ')', '~', '>', '#', '+', '-', '=', '|', '{', '}', '.', '!' } .Select(x => x.ToString()).ToArray(); private static readonly string[] escapedChars = charsToEscape.Select(x => string.Concat('\\', x)).ToArray(); public static string EscapeMarkdownV2Chars(this string value) { for(int i = 0; i< charsToEscape.Length; i++) { value = value.Replace(charsToEscape[i], escapedChars[i]); } return value; } public static string EscapeCodeBlockMarkdownV2Chars(this string value) => value.Replace(charsToEscape[0], escapedChars[0]) .Replace(charsToEscape[1], escapedChars[1]); public static string EscapeInlineLinkMarkdownV2Chars(this string value) => value.Replace(charsToEscape[0], escapedChars[0]) .Replace(charsToEscape[7], escapedChars[7]); } }
45.816216
126
0.726404
[ "MIT" ]
Zankomag/PasswordManager
src/PasswordManager.Bot/Extensions/StringExtensions.cs
8,484
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _10.PairsByDifference { class PairsByDifference { static void Main(string[] args) { int[] nums = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); int diff = int.Parse(Console.ReadLine()); int count = 0; for (int i = 0; i < nums.Length; i++) { for (int j = i; j < nums.Length; j++) { if (Math.Abs(nums[i] - nums[j]) == diff) { count++; } } } Console.WriteLine(count); } } }
25.433333
83
0.453473
[ "MIT" ]
DimchoLakov/ProgrammingFundamentalsMay2017
06.Arrays-Exercises/10.PairsByDifference/PairsByDifference.cs
765
C#
// Copyright (C) Microsoft. All rights reserved. Licensed under the MIT License. using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.DevSkim.CLI.Tests { [TestClass] public class AnalyzeTest { [TestMethod] public void AnalyzeGoodRunTest() { } } }
21
80
0.666667
[ "MIT" ]
Bhaskers-Blu-Org2/DevSkim
DevSkim-DotNet/Microsoft.DevSkim.CLI.Tests/AnalyzeTest.cs
315
C#
//----------------------------------------------------------------------------- // Copyright : (c) Chris Moore, 2020 // License : MIT //----------------------------------------------------------------------------- namespace Z0 { using System; using System.Runtime.CompilerServices; using static Root; partial class BitVector { /// <summary> /// Computes the two's complement bitvector z := ~x + 1 for a bitvector x /// </summary> /// <param name="x">The left bitvector</param> [MethodImpl(Inline), Negate] public static BitVector4 negate(BitVector4 x) => gmath.negate(x.State); /// <summary> /// Computes the two's complement bitvector z := ~x + 1 for a bitvector x /// </summary> /// <param name="x">The source bitvector</param> [MethodImpl(Inline), Negate] public static BitVector8 negate(BitVector8 x) => gmath.negate(x.State); /// <summary> /// Computes the two's complement bitvector z := ~x + 1 for a bitvector x /// </summary> /// <param name="x">The source bitvector</param> [MethodImpl(Inline), Negate] public static BitVector16 negate(BitVector16 x) => gmath.negate(x.State); /// <summary> /// Computes the two's complement bitvector z := ~x + 1 for a bitvector x /// </summary> /// <param name="x">The source bitvector</param> [MethodImpl(Inline), Negate] public static BitVector32 negate(BitVector32 x) => gmath.negate(x.State); /// <summary> /// Computes the two's complement bitvector z := ~x + 1 for a bitvector x /// </summary> /// <param name="x">The source bitvector</param> [MethodImpl(Inline), Negate] public static BitVector64 negate(BitVector64 x) => gmath.negate(x.State); } }
35.87037
81
0.521425
[ "BSD-3-Clause" ]
0xCM/z0
src/bitvectors/src/ops/direct/negate.cs
1,937
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. namespace System.ServiceModel.Channels { // Bindings can implement this interface in order to advertise capabilities // that DeliveryRequirementsAttribute consumes public interface IBindingDeliveryCapabilities { // This bool gives an assurance: "true" means you get Ordered, "false" means you may not // [DeliveryRequirements(RequireOrderedDelivery)] consumes this bool AssuresOrderedDelivery { get; } // Is this binding a queue (in the transacted-receive sense) // [DeliveryRequirements(QueuedDeliveryRequirements)] consumes this bool QueuedDelivery { get; } } }
39.952381
96
0.728248
[ "MIT" ]
Bencargs/wcf
src/System.Private.ServiceModel/src/System/ServiceModel/Channels/IBindingDeliveryCapabilities.cs
839
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V4.Resources; using gaxgrpc = Google.Api.Gax.Grpc; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using NUnit.Framework; using Google.Ads.GoogleAds.V4.Services; namespace Google.Ads.GoogleAds.Tests.V4.Services { /// <summary>Generated unit tests.</summary> public sealed class GeneratedProductGroupViewServiceClientTest { [Category("Smoke")][Test] public void GetProductGroupViewRequestObject() { moq::Mock<ProductGroupViewService.ProductGroupViewServiceClient> mockGrpcClient = new moq::Mock<ProductGroupViewService.ProductGroupViewServiceClient>(moq::MockBehavior.Strict); GetProductGroupViewRequest request = new GetProductGroupViewRequest { ResourceNameAsProductGroupViewName = gagvr::ProductGroupViewName.FromCustomerProductGroupView("[CUSTOMER]", "[PRODUCT_GROUP_VIEW]"), }; gagvr::ProductGroupView expectedResponse = new gagvr::ProductGroupView { ResourceNameAsProductGroupViewName = gagvr::ProductGroupViewName.FromCustomerProductGroupView("[CUSTOMER]", "[PRODUCT_GROUP_VIEW]"), }; mockGrpcClient.Setup(x => x.GetProductGroupView(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ProductGroupViewServiceClient client = new ProductGroupViewServiceClientImpl(mockGrpcClient.Object, null); gagvr::ProductGroupView response = client.GetProductGroupView(request); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public async stt::Task GetProductGroupViewRequestObjectAsync() { moq::Mock<ProductGroupViewService.ProductGroupViewServiceClient> mockGrpcClient = new moq::Mock<ProductGroupViewService.ProductGroupViewServiceClient>(moq::MockBehavior.Strict); GetProductGroupViewRequest request = new GetProductGroupViewRequest { ResourceNameAsProductGroupViewName = gagvr::ProductGroupViewName.FromCustomerProductGroupView("[CUSTOMER]", "[PRODUCT_GROUP_VIEW]"), }; gagvr::ProductGroupView expectedResponse = new gagvr::ProductGroupView { ResourceNameAsProductGroupViewName = gagvr::ProductGroupViewName.FromCustomerProductGroupView("[CUSTOMER]", "[PRODUCT_GROUP_VIEW]"), }; mockGrpcClient.Setup(x => x.GetProductGroupViewAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ProductGroupView>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ProductGroupViewServiceClient client = new ProductGroupViewServiceClientImpl(mockGrpcClient.Object, null); gagvr::ProductGroupView responseCallSettings = await client.GetProductGroupViewAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::ProductGroupView responseCancellationToken = await client.GetProductGroupViewAsync(request, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public void GetProductGroupView() { moq::Mock<ProductGroupViewService.ProductGroupViewServiceClient> mockGrpcClient = new moq::Mock<ProductGroupViewService.ProductGroupViewServiceClient>(moq::MockBehavior.Strict); GetProductGroupViewRequest request = new GetProductGroupViewRequest { ResourceNameAsProductGroupViewName = gagvr::ProductGroupViewName.FromCustomerProductGroupView("[CUSTOMER]", "[PRODUCT_GROUP_VIEW]"), }; gagvr::ProductGroupView expectedResponse = new gagvr::ProductGroupView { ResourceNameAsProductGroupViewName = gagvr::ProductGroupViewName.FromCustomerProductGroupView("[CUSTOMER]", "[PRODUCT_GROUP_VIEW]"), }; mockGrpcClient.Setup(x => x.GetProductGroupView(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ProductGroupViewServiceClient client = new ProductGroupViewServiceClientImpl(mockGrpcClient.Object, null); gagvr::ProductGroupView response = client.GetProductGroupView(request.ResourceName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public async stt::Task GetProductGroupViewAsync() { moq::Mock<ProductGroupViewService.ProductGroupViewServiceClient> mockGrpcClient = new moq::Mock<ProductGroupViewService.ProductGroupViewServiceClient>(moq::MockBehavior.Strict); GetProductGroupViewRequest request = new GetProductGroupViewRequest { ResourceNameAsProductGroupViewName = gagvr::ProductGroupViewName.FromCustomerProductGroupView("[CUSTOMER]", "[PRODUCT_GROUP_VIEW]"), }; gagvr::ProductGroupView expectedResponse = new gagvr::ProductGroupView { ResourceNameAsProductGroupViewName = gagvr::ProductGroupViewName.FromCustomerProductGroupView("[CUSTOMER]", "[PRODUCT_GROUP_VIEW]"), }; mockGrpcClient.Setup(x => x.GetProductGroupViewAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ProductGroupView>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ProductGroupViewServiceClient client = new ProductGroupViewServiceClientImpl(mockGrpcClient.Object, null); gagvr::ProductGroupView responseCallSettings = await client.GetProductGroupViewAsync(request.ResourceName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::ProductGroupView responseCancellationToken = await client.GetProductGroupViewAsync(request.ResourceName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public void GetProductGroupViewResourceNames() { moq::Mock<ProductGroupViewService.ProductGroupViewServiceClient> mockGrpcClient = new moq::Mock<ProductGroupViewService.ProductGroupViewServiceClient>(moq::MockBehavior.Strict); GetProductGroupViewRequest request = new GetProductGroupViewRequest { ResourceNameAsProductGroupViewName = gagvr::ProductGroupViewName.FromCustomerProductGroupView("[CUSTOMER]", "[PRODUCT_GROUP_VIEW]"), }; gagvr::ProductGroupView expectedResponse = new gagvr::ProductGroupView { ResourceNameAsProductGroupViewName = gagvr::ProductGroupViewName.FromCustomerProductGroupView("[CUSTOMER]", "[PRODUCT_GROUP_VIEW]"), }; mockGrpcClient.Setup(x => x.GetProductGroupView(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); ProductGroupViewServiceClient client = new ProductGroupViewServiceClientImpl(mockGrpcClient.Object, null); gagvr::ProductGroupView response = client.GetProductGroupView(request.ResourceNameAsProductGroupViewName); Assert.AreEqual(expectedResponse, response); mockGrpcClient.VerifyAll(); } [Category("Smoke")][Test] public async stt::Task GetProductGroupViewResourceNamesAsync() { moq::Mock<ProductGroupViewService.ProductGroupViewServiceClient> mockGrpcClient = new moq::Mock<ProductGroupViewService.ProductGroupViewServiceClient>(moq::MockBehavior.Strict); GetProductGroupViewRequest request = new GetProductGroupViewRequest { ResourceNameAsProductGroupViewName = gagvr::ProductGroupViewName.FromCustomerProductGroupView("[CUSTOMER]", "[PRODUCT_GROUP_VIEW]"), }; gagvr::ProductGroupView expectedResponse = new gagvr::ProductGroupView { ResourceNameAsProductGroupViewName = gagvr::ProductGroupViewName.FromCustomerProductGroupView("[CUSTOMER]", "[PRODUCT_GROUP_VIEW]"), }; mockGrpcClient.Setup(x => x.GetProductGroupViewAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<gagvr::ProductGroupView>(stt::Task.FromResult(expectedResponse), null, null, null, null)); ProductGroupViewServiceClient client = new ProductGroupViewServiceClientImpl(mockGrpcClient.Object, null); gagvr::ProductGroupView responseCallSettings = await client.GetProductGroupViewAsync(request.ResourceNameAsProductGroupViewName, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); Assert.AreEqual(expectedResponse, responseCallSettings); gagvr::ProductGroupView responseCancellationToken = await client.GetProductGroupViewAsync(request.ResourceNameAsProductGroupViewName, st::CancellationToken.None); Assert.AreEqual(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
66.105263
242
0.723229
[ "Apache-2.0" ]
GraphikaPS/google-ads-dotnet
tests/V4/Services/ProductGroupViewServiceClientTest.g.cs
10,048
C#
using LibraryApi.Dtos; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace LibraryApi.Controllers { [Route("api")] public class RootController : ControllerBase { private readonly IUrlHelper _urlHelper; public RootController(IUrlHelper urlHelper) { _urlHelper = urlHelper; } [HttpGet(Name ="GetRoot")] public IActionResult GetRoot( [FromHeader(Name ="Accept")] string mediaType) { if (mediaType == "application/vnd.vivustore.hateoas+json") { var links = new List<LinkDto>(); links.Add(new LinkDto(_urlHelper.Link("GetRoot", new { }), "self", "GET")); links.Add(new LinkDto(_urlHelper.Link("GetAuthors", new { }), "authors", "GET")); links.Add(new LinkDto(_urlHelper.Link("CreateAuthor", new { }), "create_author", "POST")); return Ok(links); } return NoContent(); } } }
25.62
70
0.498048
[ "MIT" ]
congdinh2008/LibraryWebApi
Library/LibraryApi/Controllers/RootController.cs
1,283
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ using Opc.Ua; using System; using System.Globalization; using System.Threading.Tasks; using static OpcPublisher.Program; namespace OpcPublisher.Configurations { /// <summary> /// Class for OPC Application configuration. /// </summary> public partial class OpcApplicationConfiguration { /// <summary> /// Configuration info for the OPC application. /// </summary> public static ApplicationConfiguration ApplicationConfiguration { get; private set; } public static string Hostname { get => _hostname; #pragma warning disable CA1308 // Normalize strings to uppercase set => _hostname = value.ToLowerInvariant(); #pragma warning restore CA1308 // Normalize strings to uppercase } public static string ApplicationName { get; set; } = "publisher"; public static string ApplicationUri => $"urn:{Hostname}:{ApplicationName}:microsoft:"; public static string ProductUri => $"https://github.com/azure/iot-edge-opc-publisher"; public static ushort ServerPort { get; set; } = 62222; public static string ServerPath { get; set; } = "/UA/Publisher"; /// <summary> /// Default endpoint security of the application. /// </summary> public static string ServerSecurityPolicy { get; set; } = SecurityPolicies.Basic128Rsa15; /// <summary> /// Enables unsecure endpoint access to the application. /// </summary> public static bool EnableUnsecureTransport { get; set; } = false; /// <summary> /// Sets the LDS registration interval. /// </summary> public static int LdsRegistrationInterval { get; set; } = 0; /// <summary> /// Set the max string length the OPC stack supports. /// </summary> public static int OpcMaxStringLength { get; set; } = HubCommunicationBase.MaxResponsePayloadLength; /// <summary> /// Mapping of the application logging levels to OPC stack logging levels. /// </summary> public static int OpcTraceToLoggerVerbose { get; set; } = 0; public static int OpcTraceToLoggerDebug { get; set; } = 0; public static int OpcTraceToLoggerInformation { get; set; } = 0; public static int OpcTraceToLoggerWarning { get; set; } = 0; public static int OpcTraceToLoggerError { get; set; } = 0; public static int OpcTraceToLoggerFatal { get; set; } = 0; /// <summary> /// Set the OPC stack log level. /// </summary> public static int OpcStackTraceMask { get; set; } = Utils.TraceMasks.Error | Utils.TraceMasks.Security | Utils.TraceMasks.StackTrace | Utils.TraceMasks.StartStop; /// <summary> /// Timeout for OPC operations. /// </summary> public static int OpcOperationTimeout { get; set; } = 120000; public static uint OpcSessionCreationTimeout { get; set; } = 10; public static uint OpcSessionCreationBackoffMax { get; set; } = 5; public static uint OpcKeepAliveDisconnectThreshold { get; set; } = 5; public static int OpcKeepAliveIntervalInSec { get; set; } = 2; public const int OpcSamplingIntervalDefault = 1000; public static int OpcSamplingInterval { get; set; } = OpcSamplingIntervalDefault; public const int OpcPublishingIntervalDefault = 0; public static int OpcPublishingInterval { get; set; } = OpcPublishingIntervalDefault; public static string PublisherServerSecurityPolicy { get; set; } = SecurityPolicies.Basic128Rsa15; /// <summary> /// Ctor of the OPC application configuration. /// </summary> public OpcApplicationConfiguration() { } /// <summary> /// Configures all OPC stack settings. /// </summary> public async Task<ApplicationConfiguration> ConfigureAsync() { // instead of using a configuration XML file, we configure everything programmatically // passed in as command line argument ApplicationConfiguration = new ApplicationConfiguration(); ApplicationConfiguration.ApplicationName = ApplicationName; ApplicationConfiguration.ApplicationUri = ApplicationUri; ApplicationConfiguration.ProductUri = ProductUri; ApplicationConfiguration.ApplicationType = ApplicationType.ClientAndServer; // configure OPC stack tracing ApplicationConfiguration.TraceConfiguration = new TraceConfiguration(); ApplicationConfiguration.TraceConfiguration.TraceMasks = OpcStackTraceMask; ApplicationConfiguration.TraceConfiguration.ApplySettings(); Utils.Tracing.TraceEventHandler += new EventHandler<TraceEventArgs>(LoggerOpcUaTraceHandler); Logger.Information($"opcstacktracemask set to: 0x{OpcStackTraceMask:X}"); // configure transport settings ApplicationConfiguration.TransportQuotas = new TransportQuotas(); ApplicationConfiguration.TransportQuotas.MaxStringLength = OpcMaxStringLength; ApplicationConfiguration.TransportQuotas.MaxMessageSize = 4 * 1024 * 1024; // the OperationTimeout should be twice the minimum value for PublishingInterval * KeepAliveCount, so set to 120s ApplicationConfiguration.TransportQuotas.OperationTimeout = OpcOperationTimeout; Logger.Information($"OperationTimeout set to {ApplicationConfiguration.TransportQuotas.OperationTimeout}"); // configure OPC UA server ApplicationConfiguration.ServerConfiguration = new ServerConfiguration(); // configure server base addresses if (ApplicationConfiguration.ServerConfiguration.BaseAddresses.Count == 0) { // we do not use the localhost replacement mechanism of the configuration loading, to immediately show the base address here ApplicationConfiguration.ServerConfiguration.BaseAddresses.Add($"opc.tcp://{Hostname}:{ServerPort}{ServerPath}"); } foreach (var endpoint in ApplicationConfiguration.ServerConfiguration.BaseAddresses) { Logger.Information($"OPC UA server base address: {endpoint}"); } // by default use high secure transport ServerSecurityPolicy newPolicy = new ServerSecurityPolicy { SecurityMode = MessageSecurityMode.SignAndEncrypt, SecurityPolicyUri = SecurityPolicies.Basic256Sha256 }; ApplicationConfiguration.ServerConfiguration.SecurityPolicies.Add(newPolicy); Logger.Information($"Security policy {newPolicy.SecurityPolicyUri} with mode {newPolicy.SecurityMode} added"); // add none secure transport on request if (EnableUnsecureTransport) { newPolicy = new ServerSecurityPolicy { SecurityMode = MessageSecurityMode.None, SecurityPolicyUri = SecurityPolicies.None }; ApplicationConfiguration.ServerConfiguration.SecurityPolicies.Add(newPolicy); Logger.Information($"Unsecure security policy {newPolicy.SecurityPolicyUri} with mode {newPolicy.SecurityMode} added"); Logger.Warning($"Note: This is a security risk and needs to be disabled for production use"); } // add default client configuration ApplicationConfiguration.ClientConfiguration = new ClientConfiguration(); // security configuration await InitApplicationSecurityAsync().ConfigureAwait(false); // set LDS registration interval ApplicationConfiguration.ServerConfiguration.MaxRegistrationInterval = LdsRegistrationInterval; Logger.Information($"LDS(-ME) registration intervall set to {LdsRegistrationInterval} ms (0 means no registration)"); // show certificate store information await ShowCertificateStoreInformationAsync().ConfigureAwait(false); return ApplicationConfiguration; } /// <summary> /// Event handler to log OPC UA stack trace messages into own logger. /// </summary> private static void LoggerOpcUaTraceHandler(object sender, TraceEventArgs e) { // return fast if no trace needed if ((e.TraceMask & OpcStackTraceMask) == 0) { return; } // e.Exception and e.Message are always null // format the trace message string message = string.Empty; message = string.Format(CultureInfo.InvariantCulture, e.Format, e.Arguments).Trim(); message = "OPC: " + message; // map logging level if ((e.TraceMask & OpcTraceToLoggerVerbose) != 0) { Logger.Verbose(message); return; } if ((e.TraceMask & OpcTraceToLoggerDebug) != 0) { Logger.Debug(message); return; } if ((e.TraceMask & OpcTraceToLoggerInformation) != 0) { Logger.Information(message); return; } if ((e.TraceMask & OpcTraceToLoggerWarning) != 0) { Logger.Warning(message); return; } if ((e.TraceMask & OpcTraceToLoggerError) != 0) { Logger.Error(message); return; } if ((e.TraceMask & OpcTraceToLoggerFatal) != 0) { Logger.Fatal(message); return; } return; } #pragma warning disable CA1308 // Normalize strings to uppercase private static string _hostname = $"{Utils.GetHostName().ToLowerInvariant()}"; #pragma warning restore CA1308 // Normalize strings to uppercase } }
42.489796
170
0.624015
[ "MIT" ]
Azure/iot-edge-opc-publisher-v1
opcpublisher/Configurations/OpcApplicationConfiguration.cs
10,412
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.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("NuGet.Monitoring.RebootSearchInstance.Tests")] [assembly: ComVisible(false)] [assembly: Guid("21c0a0ee-8696-4013-950f-d6495d0c6e40")]
39.3
111
0.788804
[ "Apache-2.0" ]
fredatgithub/NuGet.Jobs
tests/Monitoring.RebootSearchInstance.Tests/Properties/AssemblyInfo.cs
395
C#
/* * _____ ______ * /_ / ____ ____ ____ _________ / __/ /_ * / / / __ \/ __ \/ __ \/ ___/ __ \/ /_/ __/ * / /__/ /_/ / / / / /_/ /\_ \/ /_/ / __/ /_ * /____/\____/_/ /_/\__ /____/\____/_/ \__/ * /____/ * * Authors: * 钟峰(Popeye Zhong) <zongsoft@gmail.com> * * Copyright (C) 2010-2020 Zongsoft Studio <http://www.zongsoft.com> * * This file is part of Zongsoft.Core library. * * The Zongsoft.Core is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3.0 of the License, * or (at your option) any later version. * * The Zongsoft.Core is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with the Zongsoft.Core library. If not, see <http://www.gnu.org/licenses/>. */ using System; using System.Security.Claims; using System.Collections.Generic; namespace Zongsoft.Security.Membership { public class AuthenticatedEventArgs : EventArgs { #region 成员字段 private IDictionary<string, object> _parameters; #endregion #region 构造函数 public AuthenticatedEventArgs(Authentication authentication, ClaimsPrincipal principal, string scenario, IEnumerable<KeyValuePair<string, object>> parameters = null) { this.Authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); this.Principal = principal ?? throw new ArgumentNullException(nameof(principal)); this.Scenario = scenario; if(parameters != null) _parameters = new Dictionary<string, object>(parameters, StringComparer.OrdinalIgnoreCase); } #endregion #region 公共属性 /// <summary>获取激发的身份验证对象。</summary> public Authentication Authentication { get; } /// <summary>获取身份验证的用户身份。</summary> public ClaimsPrincipal Principal { get; } /// <summary>获取身份验证的应用场景。</summary> public string Scenario { get; } /// <summary>获取身份验证是否通过。</summary> public bool IsAuthenticated { get => Principal != null && this.Principal.Identity != null && Principal.Identity.IsAuthenticated && !string.IsNullOrEmpty(Principal.Identity.Name); } /// <summary>获取一个值,指示扩展参数集是否有内容。</summary> public bool HasParameters { get => _parameters != null && _parameters.Count > 0; } /// <summary>获取验证结果的扩展参数集。</summary> public IDictionary<string, object> Parameters { get { if(_parameters == null) System.Threading.Interlocked.CompareExchange(ref _parameters, new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase), null); return _parameters; } } #endregion } public class AuthenticatingEventArgs : EventArgs { #region 成员字段 private IDictionary<string, object> _parameters; #endregion #region 构造函数 public AuthenticatingEventArgs(Authentication authentication, object ticket, string scenario, IEnumerable<KeyValuePair<string, object>> parameters = null) { this.Authentication = authentication ?? throw new ArgumentNullException(nameof(authentication)); this.Ticket = ticket; this.Scenario = scenario; if(parameters != null) _parameters = new Dictionary<string, object>(parameters, StringComparer.OrdinalIgnoreCase); } #endregion #region 公共属性 /// <summary>获取激发的身份验证对象。</summary> public Authentication Authentication { get; } /// <summary>获取待验证的票证对象。</summary> public object Ticket { get; } /// <summary>获取身份验证的应用场景。</summary> public string Scenario { get; } /// <summary>获取一个值,指示扩展参数集是否有内容。</summary> public bool HasParameters { get => _parameters != null && _parameters.Count > 0; } /// <summary>获取验证结果的扩展参数集。</summary> public IDictionary<string, object> Parameters { get { if(_parameters == null) System.Threading.Interlocked.CompareExchange(ref _parameters, new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase), null); return _parameters; } } #endregion } }
30.280576
167
0.701829
[ "MIT" ]
Zongsoft/Zongsoft.Framework
Zongsoft.Core/src/Security/Membership/AuthenticationEventArgs.cs
4,555
C#
namespace IllusionsPerception.Teacher { partial class Form18 { /// <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.pictureBox1 = new System.Windows.Forms.PictureBox(); this.comboBox1 = new System.Windows.Forms.ComboBox(); this.label1 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); this.SuspendLayout(); // // pictureBox1 // this.pictureBox1.Location = new System.Drawing.Point(12, 100); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(346, 207); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBox1.TabIndex = 44; this.pictureBox1.TabStop = false; // // comboBox1 // this.comboBox1.FormattingEnabled = true; this.comboBox1.Items.AddRange(new object[] { "1,2", "1,4", "1,6", "1,8"}); this.comboBox1.Location = new System.Drawing.Point(303, 43); this.comboBox1.Name = "comboBox1"; this.comboBox1.Size = new System.Drawing.Size(129, 21); this.comboBox1.TabIndex = 46; this.comboBox1.Text = "Выберите значение"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(243, 24); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(248, 13); this.label1.TabIndex = 47; this.label1.Text = "Выберите коэффициент различия окружностей"; // // button1 // this.button1.Location = new System.Drawing.Point(13, 427); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 48; this.button1.Text = "Назад"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // button2 // this.button2.Location = new System.Drawing.Point(331, 371); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(75, 23); this.button2.TabIndex = 49; this.button2.Text = "Сохранить"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // pictureBox2 // this.pictureBox2.Location = new System.Drawing.Point(376, 100); this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.Size = new System.Drawing.Size(346, 207); this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBox2.TabIndex = 50; this.pictureBox2.TabStop = false; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(151, 314); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(35, 13); this.label2.TabIndex = 51; this.label2.Text = "label2"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(532, 314); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(35, 13); this.label3.TabIndex = 52; this.label3.Text = "label3"; // // Form18 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(734, 462); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.pictureBox2); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Controls.Add(this.label1); this.Controls.Add(this.comboBox1); this.Controls.Add(this.pictureBox1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow; this.Name = "Form18"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Исследование иллюзий восприятия"; ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.ComboBox comboBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.PictureBox pictureBox2; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; } }
42.579618
107
0.573074
[ "MIT" ]
IManfis/IllusionsPerception
IllusionsPerception/IllusionsPerception/Teacher/Form18.Designer.cs
6,784
C#
/* * Copyright (c) 2016-2019 Håkan Edling * * This software may be modified and distributed under the terms * of the MIT license. See the LICENSE file for details. * * https://github.com/piranhacms/piranha.core * */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Piranha.Data; using Piranha.Services; namespace Piranha.Repositories { public class PostRepository : IPostRepository { private readonly IDb _db; private readonly IContentService<Post, PostField, Models.PostBase> _contentService; /// <summary> /// Default constructor. /// </summary> /// <param name="db">The current db connection</param> /// <param name="factory">The current content service factory</param> public PostRepository(IDb db, IContentServiceFactory factory) { _db = db; _contentService = factory.CreatePostService(); } /// <summary> /// Gets the available posts for the specified archive. /// </summary> /// <param name="blogId">The blog id</param> /// <returns>The posts</returns> public async Task<IEnumerable<Guid>> GetAll(Guid blogId) { return await _db.Posts .AsNoTracking() .Where(p => p.BlogId == blogId) .OrderByDescending(p => p.Published) .ThenByDescending(p => p.LastModified) .ThenBy(p => p.Title) .Select(p => p.Id) .ToListAsync() .ConfigureAwait(false); } /// <summary> /// Gets the available post items for the given site. /// </summary> /// <param name="siteId">The site id</param> /// <returns>The posts</returns> public async Task<IEnumerable<Guid>> GetAllBySiteId(Guid siteId) { return await _db.Posts .AsNoTracking() .Where(p => p.Blog.SiteId == siteId) .OrderByDescending(p => p.Published) .ThenByDescending(p => p.LastModified) .ThenBy(p => p.Title) .Select(p => p.Id) .ToListAsync() .ConfigureAwait(false); } /// <summary> /// Gets all available categories for the specified blog. /// </summary> /// <param name="id">The blog id</param> /// <returns>The available categories</returns> public async Task<IEnumerable<Models.Taxonomy>> GetAllCategories(Guid blogId) { return await _db.Categories .AsNoTracking() .Where(c => c.BlogId == blogId) .OrderBy(c => c.Title) .Select(c => new Models.Taxonomy { Id = c.Id, Title = c.Title, Slug = c.Slug }) .ToListAsync() .ConfigureAwait(false); } /// <summary> /// Gets all available tags for the specified blog. /// </summary> /// <param name="id">The blog id</param> /// <returns>The available tags</returns> public async Task<IEnumerable<Models.Taxonomy>> GetAllTags(Guid blogId) { return await _db.Tags .AsNoTracking() .Where(c => c.BlogId == blogId) .OrderBy(c => c.Title) .Select(c => new Models.Taxonomy { Id = c.Id, Title = c.Title, Slug = c.Slug }) .ToListAsync() .ConfigureAwait(false); } /// <summary> /// Gets the post model with the specified id. /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="id">The unique id</param> /// <returns>The post model</returns> public async Task<T> GetById<T>(Guid id) where T : Models.PostBase { var post = await GetQuery<T>() .FirstOrDefaultAsync(p => p.Id == id) .ConfigureAwait(false); if (post != null) { return _contentService.Transform<T>(post, App.PostTypes.GetById(post.PostTypeId), Process); } return null; } /// <summary> /// Gets the post model with the specified slug. /// </summary> /// <typeparam name="T">The model type</typeparam> /// <param name="blogId">The blog id</param> /// <param name="slug">The unique slug</param> /// <returns>The post model</returns> public async Task<T> GetBySlug<T>(Guid blogId, string slug) where T : Models.PostBase { // No cache found, load from database var post = await GetQuery<T>() .FirstOrDefaultAsync(p => p.BlogId == blogId && p.Slug == slug) .ConfigureAwait(false); if (post != null) { return _contentService.Transform<T>(post, App.PostTypes.GetById(post.PostTypeId), Process); } return null; } /// <summary> /// Gets the category with the given slug. /// </summary> /// <param name="blogId">The blog id</param> /// <param name="slug">The unique slug</param> /// <returns>The category</returns> public Task<Models.Taxonomy> GetCategoryBySlug(Guid blogId, string slug) { return _db.Categories .Where(c => c.BlogId == blogId && c.Slug == slug) .Select(c => new Models.Taxonomy { Id = c.Id, Title = c.Title, Slug = c.Slug }).FirstOrDefaultAsync(); } /// <summary> /// Gets the tag with the given slug. /// </summary> /// <param name="blogId">The blog id</param> /// <param name="slug">The unique slug</param> /// <returns>The tag</returns> public Task<Models.Taxonomy> GetTagBySlug(Guid blogId, string slug) { return _db.Tags .Where(c => c.BlogId == blogId && c.Slug == slug) .Select(c => new Models.Taxonomy { Id = c.Id, Title = c.Title, Slug = c.Slug }).FirstOrDefaultAsync(); } /// <summary> /// Saves the given post model /// </summary> /// <param name="model">The post model</param> public async Task Save<T>(T model) where T : Models.PostBase { var type = App.PostTypes.GetById(model.TypeId); if (type != null) { // Ensure category var category = await _db.Categories .FirstOrDefaultAsync(c => c.Id == model.Category.Id) .ConfigureAwait(false); if (category == null) { if (!string.IsNullOrWhiteSpace(model.Category.Slug)) { category = await _db.Categories .FirstOrDefaultAsync(c => c.BlogId == model.BlogId && c.Slug == model.Category.Slug) .ConfigureAwait(false); } if (category == null && !string.IsNullOrWhiteSpace(model.Category.Title)) { category = await _db.Categories .FirstOrDefaultAsync(c => c.BlogId == model.BlogId && c.Title == model.Category.Title) .ConfigureAwait(false); } if (category == null) { category = new Category { Id = model.Category.Id != Guid.Empty ? model.Category.Id : Guid.NewGuid(), BlogId = model.BlogId, Title = model.Category.Title, Slug = Utils.GenerateSlug(model.Category.Title), Created = DateTime.Now, LastModified = DateTime.Now }; await _db.Categories.AddAsync(category).ConfigureAwait(false); } model.Category.Id = category.Id; } // Ensure tags foreach (var t in model.Tags) { var tag = await _db.Tags .FirstOrDefaultAsync(tg => tg.Id == t.Id) .ConfigureAwait(false); if (tag == null) { if (!string.IsNullOrWhiteSpace(t.Slug)) { tag = await _db.Tags .FirstOrDefaultAsync(tg => tg.BlogId == model.BlogId && tg.Slug == t.Slug) .ConfigureAwait(false); } if (tag == null && !string.IsNullOrWhiteSpace(t.Title)) { tag = await _db.Tags .FirstOrDefaultAsync(tg => tg.BlogId == model.BlogId && tg.Title == t.Title) .ConfigureAwait(false); } if (tag == null) { tag = new Tag { Id = t.Id != Guid.Empty ? t.Id : Guid.NewGuid(), BlogId = model.BlogId, Title = t.Title, Slug = Utils.GenerateSlug(t.Title), Created = DateTime.Now, LastModified = DateTime.Now }; await _db.Tags.AddAsync(tag).ConfigureAwait(false); } t.Id = tag.Id; } } // Ensure that we have a slug if (string.IsNullOrWhiteSpace(model.Slug)) { model.Slug = Utils.GenerateSlug(model.Title, false); } else { model.Slug = Utils.GenerateSlug(model.Slug, false); } var post = await _db.Posts .Include(p => p.Blocks).ThenInclude(b => b.Block).ThenInclude(b => b.Fields) .Include(p => p.Fields) .Include(p => p.Tags) .FirstOrDefaultAsync(p => p.Id == model.Id) .ConfigureAwait(false); // If not, create a new post if (post == null) { post = new Post { Id = model.Id != Guid.Empty ? model.Id : Guid.NewGuid(), Created = DateTime.Now, LastModified = DateTime.Now }; await _db.Posts.AddAsync(post).ConfigureAwait(false); model.Id = post.Id; } else { post.LastModified = DateTime.Now; } post = _contentService.Transform<T>(model, type, post); // Transform blocks var blockModels = model.Blocks; if (blockModels != null) { var blocks = _contentService.TransformBlocks(blockModels); var current = blocks.Select(b => b.Id).ToArray(); // Delete removed blocks var removed = post.Blocks .Where(b => !current.Contains(b.BlockId) && !b.Block.IsReusable) .Select(b => b.Block); _db.Blocks.RemoveRange(removed); // Delete the old page blocks post.Blocks.Clear(); // Now map the new block for (var n = 0; n < blocks.Count; n++) { var block = _db.Blocks .Include(b => b.Fields) .FirstOrDefault(b => b.Id == blocks[n].Id); if (block == null) { block = new Block { Id = blocks[n].Id != Guid.Empty ? blocks[n].Id : Guid.NewGuid(), Created = DateTime.Now }; await _db.Blocks.AddAsync(block).ConfigureAwait(false); } block.CLRType = blocks[n].CLRType; block.IsReusable = blocks[n].IsReusable; block.Title = blocks[n].Title; block.LastModified = DateTime.Now; var currentFields = blocks[n].Fields.Select(f => f.FieldId).Distinct(); var removedFields = block.Fields.Where(f => !currentFields.Contains(f.FieldId)); _db.BlockFields.RemoveRange(removedFields); foreach (var newField in blocks[n].Fields) { var field = block.Fields.FirstOrDefault(f => f.FieldId == newField.FieldId); if (field == null) { field = new BlockField { Id = newField.Id != Guid.Empty ? newField.Id : Guid.NewGuid(), BlockId = block.Id, FieldId = newField.FieldId }; await _db.BlockFields.AddAsync(field).ConfigureAwait(false); block.Fields.Add(field); } field.SortOrder = newField.SortOrder; field.CLRType = newField.CLRType; field.Value = newField.Value; } // Create the page block post.Blocks.Add(new PostBlock { Id = Guid.NewGuid(), BlockId = block.Id, ParentId = blocks[n].ParentId, Block = block, PostId = post.Id, SortOrder = n }); } } // Remove tags var removedTags = new List<PostTag>(); foreach (var tag in post.Tags) { if (!model.Tags.Any(t => t.Id == tag.TagId)) { removedTags.Add(tag); } } foreach (var removed in removedTags) { post.Tags.Remove(removed); } // Add tags foreach (var tag in model.Tags) { if (!post.Tags.Any(t => t.PostId == post.Id && t.TagId == tag.Id)) post.Tags.Add(new PostTag { PostId = post.Id, TagId = tag.Id }); } await _db.SaveChangesAsync().ConfigureAwait(false); await DeleteUnusedCategories(model.BlogId).ConfigureAwait(false); await DeleteUnusedTags(model.BlogId).ConfigureAwait(false); } } /// <summary> /// Deletes the model with the specified id. /// </summary> /// <param name="id">The unique id</param> public async Task Delete(Guid id) { var model = await _db.Posts .Include(p => p.Blocks).ThenInclude(b => b.Block).ThenInclude(b => b.Fields) .Include(p => p.Fields) .FirstOrDefaultAsync(p => p.Id == id) .ConfigureAwait(false); if (model != null) { // Remove all blocks that are not reusable foreach (var postBlock in model.Blocks) { if (!postBlock.Block.IsReusable) { _db.Blocks.Remove(postBlock.Block); } } _db.Posts.Remove(model); // // TODO // // If this is a published post, update last modified for the // blog page for caching purposes. if (model.Published.HasValue) { var page = await _db.Pages .FirstOrDefaultAsync(p => p.Id == model.BlogId) .ConfigureAwait(false); page.LastModified = DateTime.Now; } await _db.SaveChangesAsync().ConfigureAwait(false); await DeleteUnusedCategories(model.BlogId).ConfigureAwait(false); await DeleteUnusedTags(model.BlogId).ConfigureAwait(false); } } /// <summary> /// Deletes all unused categories for the specified blog. /// </summary> /// <param name="blogId">The blog id</param> private async Task DeleteUnusedCategories(Guid blogId) { var used = await _db.Posts .Where(p => p.BlogId == blogId) .Select(p => p.CategoryId) .Distinct() .ToArrayAsync() .ConfigureAwait(false); var unused = await _db.Categories .Where(c => c.BlogId == blogId && !used.Contains(c.Id)) .ToListAsync() .ConfigureAwait(false); if (unused.Count > 0) { _db.Categories.RemoveRange(unused); await _db.SaveChangesAsync().ConfigureAwait(false); } } /// <summary> /// Deletes all unused tags for the specified blog. /// </summary> /// <param name="blogId">The blog id</param> private async Task DeleteUnusedTags(Guid blogId) { var used = await _db.PostTags .Where(t => t.Post.BlogId == blogId) .Select(t => t.TagId) .Distinct() .ToArrayAsync() .ConfigureAwait(false); var unused = await _db.Tags .Where(t => t.BlogId == blogId && !used.Contains(t.Id)) .ToListAsync() .ConfigureAwait(false); if (unused.Count > 0) { _db.Tags.RemoveRange(unused); await _db.SaveChangesAsync().ConfigureAwait(false); } } /// <summary> /// Gets the base query for loading posts. /// </summary> /// <typeparam name="T">The requested model type</typeparam> /// <returns>The queryable</returns> private IQueryable<Post> GetQuery<T>() { var loadRelated = !typeof(Models.IContentInfo).IsAssignableFrom(typeof(T)); IQueryable<Post> query = _db.Posts .AsNoTracking() .Include(p => p.Category) .Include(p => p.Tags).ThenInclude(t => t.Tag); if (loadRelated) { query = query .Include(p => p.Blocks).ThenInclude(b => b.Block).ThenInclude(b => b.Fields) .Include(p => p.Fields); } return query; } /// <summary> /// Performs additional processing and loads related models. /// </summary> /// <param name="post">The source post</param> /// <param name="model">The targe model</param> private void Process<T>(Data.Post post, T model) where T : Models.PostBase { if (!(model is Models.IContentInfo)) { if (post.Blocks.Count > 0) { var blocks = post.Blocks .OrderBy(b => b.SortOrder) .Select(b => b.Block) .ToList(); model.Blocks = _contentService.TransformBlocks(blocks); } } } } }
38.081374
114
0.43815
[ "MIT" ]
naydyonov/piranha.core
data/Piranha.Data.EF/Repositories/PostRepository.cs
21,060
C#
namespace TechMentorApi.Controllers { using Microsoft.AspNetCore.Mvc; using TechMentorApi.Security; /// <summary> /// The <see cref="AuthController" /> /// class provides access to common authentication logic for derived controllers. /// </summary> public abstract class AuthController : Controller { protected bool IsAdministrator() { if (User == null) { return false; } if (User.Identity?.IsAuthenticated == false) { return false; } if (User.IsInRole(Role.Administrator)) { return true; } return false; } } }
23.46875
89
0.505992
[ "MIT" ]
Divergic/techmentorapi
TechMentorApi/Controllers/AuthController.cs
753
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.CloudFormation")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS CloudFormation. AWS CloudFormation gives developers and systems administrators an easy way to create and manage a collection of related AWS resources, provisioning and updating them in an orderly and predictable fashion.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS CloudFormation. AWS CloudFormation gives developers and systems administrators an easy way to create and manage a collection of related AWS resources, provisioning and updating them in an orderly and predictable fashion.")] #elif PCL [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (PCL) - AWS CloudFormation. AWS CloudFormation gives developers and systems administrators an easy way to create and manage a collection of related AWS resources, provisioning and updating them in an orderly and predictable fashion.")] #elif UNITY [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (Unity) - AWS CloudFormation. AWS CloudFormation gives developers and systems administrators an easy way to create and manage a collection of related AWS resources, provisioning and updating them in an orderly and predictable fashion.")] #elif NETSTANDARD13 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 1.3)- AWS CloudFormation. AWS CloudFormation gives developers and systems administrators an easy way to create and manage a collection of related AWS resources, provisioning and updating them in an orderly and predictable fashion.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0)- AWS CloudFormation. AWS CloudFormation gives developers and systems administrators an easy way to create and manage a collection of related AWS resources, provisioning and updating them in an orderly and predictable fashion.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.3.106.16")] #if WINDOWS_PHONE || UNITY [assembly: System.CLSCompliant(false)] # else [assembly: System.CLSCompliant(true)] #endif #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
60.237288
315
0.788689
[ "Apache-2.0" ]
alefranz/aws-sdk-net
sdk/src/Services/CloudFormation/Properties/AssemblyInfo.cs
3,554
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Batch.Inputs { public sealed class AzureBlobFileSystemConfigurationArgs : Pulumi.ResourceArgs { /// <summary> /// This property is mutually exclusive with sasKey and one must be specified. /// </summary> [Input("accountKey")] public Input<string>? AccountKey { get; set; } [Input("accountName", required: true)] public Input<string> AccountName { get; set; } = null!; /// <summary> /// These are 'net use' options in Windows and 'mount' options in Linux. /// </summary> [Input("blobfuseOptions")] public Input<string>? BlobfuseOptions { get; set; } [Input("containerName", required: true)] public Input<string> ContainerName { get; set; } = null!; /// <summary> /// All file systems are mounted relative to the Batch mounts directory, accessible via the AZ_BATCH_NODE_MOUNTS_DIR environment variable. /// </summary> [Input("relativeMountPath", required: true)] public Input<string> RelativeMountPath { get; set; } = null!; /// <summary> /// This property is mutually exclusive with accountKey and one must be specified. /// </summary> [Input("sasKey")] public Input<string>? SasKey { get; set; } public AzureBlobFileSystemConfigurationArgs() { } } }
34.26
146
0.634559
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Batch/Inputs/AzureBlobFileSystemConfigurationArgs.cs
1,713
C#
using System; using System.IO; using System.Text; using System.Text.RegularExpressions; using Microsoft.Build.Utilities; using Microsoft.Win32; using NUnit.Framework; namespace MSBuild.Community.Tasks.Tests { /// <summary> /// Summary description for NUnitTest /// </summary> [TestFixture] public class NUnitTest { [Test(Description = "Excute NUnit tests of the NUnit framework")] public void NUnitExecute() { #region Find NUnit installation string nunitPath = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); nunitPath = Path.Combine(nunitPath, NUnit.DEFAULT_NUNIT_DIRECTORY); RegistryKey buildKey = Registry.ClassesRoot.OpenSubKey(@"NUnitTestProject\shell\open\command"); if (buildKey == null) Assert.Ignore(@"Can't find NUnit installation"); nunitPath = buildKey.GetValue(null, nunitPath).ToString(); Regex nunitRegex = new Regex("(.+)nunit-gui\\.exe", RegexOptions.IgnoreCase); Match pathMatch = nunitRegex.Match(nunitPath); nunitPath = pathMatch.Groups[1].Value.Replace("\"", ""); #endregion Find NUnit installation MockBuild buildEngine = new MockBuild(); string testDirectory = TaskUtility.makeTestDirectory(buildEngine); NUnit task = new NUnit(); task.BuildEngine = buildEngine; task.Assemblies = TaskUtility.StringArrayToItemArray( Path.Combine(nunitPath, "nunit.framework.tests.dll")); task.WorkingDirectory = testDirectory; task.OutputXmlFile = Path.Combine(testDirectory, @"nunit.framework.tests-results.xml"); Assert.IsTrue(task.Execute(), "Execute Failed"); } } }
36.18
107
0.651189
[ "Unlicense" ]
Byndyusoft/msbuildtasks
Source/MSBuild.Community.Tasks.Tests/NUnitTest.cs
1,809
C#
using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using BrightChain.Engine.Models.Agents; using BrightChain.Engine.Models.Blocks; using BrightChain.Engine.Models.Keys; namespace BrightChain.Engine.Models.Nodes { /// <summary> /// Representation of a bright chain participartory node. /// </summary> public class BrightChainNode { /// <summary> /// Initializes a new instance of the <see cref="BrightChainNode"/> class. /// </summary> public BrightChainNode() { } /// <summary> /// Gets the Id of the Node. /// The Id of a Node is tied to its key once the block is accepted. /// Duplicate Ids should not be accepted. /// This will be used in TrustedNode lists. /// </summary> public BlockHash Id { get; } public ECDiffieHellmanCngPublicKey PublicKey { get; } public BrightChainAgent NodeAgent { get; } public BrightChainNodeInfo NodeInfo { get; } } }
27.75
82
0.645946
[ "Apache-2.0" ]
MaxMood96/BrightChain
src/BrightChain.Engine/Models/Nodes/BrightChainNode.cs
1,112
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 Wider.Content.VirtualCanvas.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
40.074074
151
0.585952
[ "MIT" ]
TorisanKitsune/Wider
Modules/Wider.Content.VirtualCanvas/Properties/Settings.Designer.cs
1,084
C#
using System; using System.Collections.Generic; using System.Text; using System.Windows.Input; using VolleMoehre.Contracts.Interfaces; using VolleMoehre.Contracts.Model; using VolleMoehre.App.Shared.ViewModels; using VolleMoehre.Shared.Services; using Plugin.Connectivity; namespace VolleMoehre.App.Shared.Commands { public class ChangeTrainingStatusCommand : ICommand { private SpielerStatus NewSpielerStatus; private TrainingsViewModel Model; public event EventHandler CanExecuteChanged; public ChangeTrainingStatusCommand(SpielerStatus newSpielerStatus, TrainingsViewModel model) { NewSpielerStatus = newSpielerStatus; Model = model; } public bool CanExecute(object parameter) { return true; } public async void Execute(object parameter) { if (!ServiceBase.IsOnline()) { Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog("Du bist gerade leider nicht online. Bitte prüfe deine Verbindung."); await dialog.ShowAsync(); return; } TrainingsterminViewModel model = parameter as TrainingsterminViewModel; model.Loading = true; model.LoadingFinished = false; ITrainingsService service = new TrainingsService(App.__APIKey); var success = await service.ChangeStatusAsync(App.__spieler, model.Termin, NewSpielerStatus); if(success.Erfolgreich) { var newTraining = await service.GetTrainingAsync(model.Termin.Id); model.RefreshFrom(newTraining, App.__spieler); var index = Model.Trainings.IndexOf(model); Model.Trainings.RemoveAt(index); Model.Trainings.Insert(index, model); } else { Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog(success.Fehlermeldung); await dialog.ShowAsync(); return; } model.DoneLoading(); } } }
32.522388
162
0.627811
[ "MIT" ]
TopperDEL/VolleMoehre
VolleMoehre.App/VolleMoehre.App.Shared/Commands/ChangeTrainingStatusCommand.cs
2,182
C#
namespace Firebase.Auth { using System; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Linq; /// <summary> /// The auth token provider. /// </summary> public class FirebaseAuthProvider : IDisposable, IFirebaseAuthProvider { private const string GoogleRefreshAuth = "https://securetoken.googleapis.com/v1/token?key={0}"; private const string GoogleCustomAuthUrl = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyCustomToken?key={0}"; private const string GoogleGetUser = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/getAccountInfo?key={0}"; private const string GoogleIdentityUrl = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyAssertion?key={0}"; private const string GoogleSignUpUrl = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key={0}"; private const string GooglePasswordUrl = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key={0}"; private const string GoogleDeleteUserUrl = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/deleteAccount?key={0}"; private const string GoogleGetConfirmationCodeUrl = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/getOobConfirmationCode?key={0}"; private const string GoogleSetAccountUrl = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/setAccountInfo?key={0}"; private const string GoogleCreateAuthUrl = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/createAuthUri?key={0}"; private readonly FirebaseConfig authConfig; private readonly HttpClient client; /// <summary> /// Initializes a new instance of the <see cref="FirebaseAuthProvider"/> class. /// </summary> /// <param name="authConfig"> The auth config. </param> public FirebaseAuthProvider(FirebaseConfig authConfig) { this.authConfig = authConfig; this.client = new HttpClient(); } /// <summary> /// Sign in with a custom token. You would usually create and sign such a token on your server to integrate with your existing authentiocation system. /// </summary> /// <param name="customToken"> The access token retrieved from login provider of your choice. </param> /// <returns> The <see cref="FirebaseAuth"/>. </returns> public async Task<FirebaseAuthLink> SignInWithCustomTokenAsync(string customToken) { string content = $"{{\"token\":\"{customToken}\",\"returnSecureToken\":true}}"; FirebaseAuthLink firebaseAuthLink = await this.ExecuteWithPostContentAsync(GoogleCustomAuthUrl, content).ConfigureAwait(false); firebaseAuthLink.User = await this.GetUserAsync(firebaseAuthLink.FirebaseToken).ConfigureAwait(false); return firebaseAuthLink; } /// <summary> /// Using the idToken of an authenticated user, get the details of the user's account /// </summary> /// <param name="firebaseToken"> The FirebaseToken (idToken) of an authenticated user. </param> /// <returns> The <see cref="User"/>. </returns> public async Task<User> GetUserAsync(string firebaseToken) { var content = $"{{\"idToken\":\"{firebaseToken}\"}}"; var response = await this.client.PostAsync(new Uri(string.Format(GoogleGetUser, this.authConfig.ApiKey)), new StringContent(content, Encoding.UTF8, "application/json")).ConfigureAwait(false); JObject resultJson = JObject.Parse(await response.Content.ReadAsStringAsync().ConfigureAwait(false)); var user = JsonConvert.DeserializeObject<User>(resultJson["users"].First().ToString()); return user; } /// <summary> /// Sends user an email with a link to verify his email address. /// </summary> /// <param name="auth"> The authenticated user to verify email address. </param> public async Task<User> GetUserAsync(FirebaseAuth auth) { return await this.GetUserAsync(auth.FirebaseToken).ConfigureAwait(false); } /// <summary> /// Using the provided access token from third party auth provider (google, facebook...), get the firebase auth with token and basic user credentials. /// </summary> /// <param name="authType"> The auth type. </param> /// <param name="oauthAccessToken"> The access token retrieved from login provider of your choice. </param> /// <returns> The <see cref="FirebaseAuth"/>. </returns> public async Task<FirebaseAuthLink> SignInWithOAuthAsync(FirebaseAuthType authType, string oauthAccessToken) { var providerId = this.GetProviderId(authType); var content = $"{{\"postBody\":\"access_token={oauthAccessToken}&providerId={providerId}\",\"requestUri\":\"http://localhost\",\"returnSecureToken\":true}}"; return await this.ExecuteWithPostContentAsync(GoogleIdentityUrl, content).ConfigureAwait(false); } /// <summary> /// Sign in user anonymously. He would still have a user id and access token generated, but name and other personal user properties will be null. /// </summary> /// <returns> The <see cref="FirebaseAuth"/>. </returns> public async Task<FirebaseAuthLink> SignInAnonymouslyAsync() { var content = $"{{\"returnSecureToken\":true}}"; return await this.ExecuteWithPostContentAsync(GoogleSignUpUrl, content).ConfigureAwait(false); } /// <summary> /// Using the provided email and password, get the firebase auth with token and basic user credentials. /// </summary> /// <param name="email"> The email. </param> /// <param name="password"> The password. </param> /// <returns> The <see cref="FirebaseAuth"/>. </returns> public async Task<FirebaseAuthLink> SignInWithEmailAndPasswordAsync(string email, string password) { var content = $"{{\"email\":\"{email}\",\"password\":\"{password}\",\"returnSecureToken\":true}}"; return await this.ExecuteWithPostContentAsync(GooglePasswordUrl, content).ConfigureAwait(false); } /// <summary> /// Creates new user with given credentials. /// </summary> /// <param name="email"> The email. </param> /// <param name="password"> The password. </param> /// <param name="displayName"> Optional display name. </param> /// <param name="sendVerificationEmail"> Optional. Whether to send user a link to verfiy his email address. </param> /// <returns> The <see cref="FirebaseAuth"/>. </returns> public async Task<FirebaseAuthLink> CreateUserWithEmailAndPasswordAsync(string email, string password, string displayName = "", bool sendVerificationEmail = false) { var content = $"{{\"email\":\"{email}\",\"password\":\"{password}\",\"returnSecureToken\":true}}"; var signup = await this.ExecuteWithPostContentAsync(GoogleSignUpUrl, content).ConfigureAwait(false); if (!string.IsNullOrWhiteSpace(displayName)) { // set display name content = $"{{\"displayName\":\"{displayName}\",\"idToken\":\"{signup.FirebaseToken}\",\"returnSecureToken\":true}}"; await this.ExecuteWithPostContentAsync(GoogleSetAccountUrl, content).ConfigureAwait(false); signup.User.DisplayName = displayName; } if (sendVerificationEmail) { //send verification email await this.SendEmailVerificationAsync(signup).ConfigureAwait(false); } return signup; } /// <summary> /// Deletes the user with a recent Firebase Token. /// </summary> /// <param name="token"> Recent Firebase Token. </param> [Obsolete("This method will be removed in future release in favor of DeleteUserAsync")] public Task DeleteUser(string firebaseToken) { return this.DeleteUserAsync(firebaseToken); } /// <summary> /// Deletes the user with a recent Firebase Token. /// </summary> /// <param name="token"> Recent Firebase Token. </param> public async Task DeleteUserAsync(string firebaseToken) { var content = $"{{ \"idToken\": \"{firebaseToken}\" }}"; var responseData = "N/A"; try { var response = await this.client.PostAsync(new Uri(string.Format(GoogleDeleteUserUrl, this.authConfig.ApiKey)), new StringContent(content, Encoding.UTF8, "application/json")).ConfigureAwait(false); responseData = await response.Content.ReadAsStringAsync().ConfigureAwait(false); response.EnsureSuccessStatusCode(); } catch(Exception ex) { AuthErrorReason errorReason = GetFailureReason(responseData); throw new FirebaseAuthException(GoogleDeleteUserUrl, content, responseData, ex, errorReason); } } /// <summary> /// Sends user an email with a link to reset his password. /// </summary> /// <param name="email"> The email. </param> public async Task SendPasswordResetEmailAsync(string email) { var content = $"{{\"requestType\":\"PASSWORD_RESET\",\"email\":\"{email}\"}}"; var response = await this.client.PostAsync(new Uri(string.Format(GoogleGetConfirmationCodeUrl, this.authConfig.ApiKey)), new StringContent(content, Encoding.UTF8, "application/json")).ConfigureAwait(false); response.EnsureSuccessStatusCode(); } /// <summary> /// Sends user an email with a link to verify his email address. /// </summary> /// <param name="firebaseToken"> The FirebaseToken (idToken) of an authenticated user. </param> public async Task SendEmailVerificationAsync(string firebaseToken) { var content = $"{{\"requestType\":\"VERIFY_EMAIL\",\"idToken\":\"{firebaseToken}\"}}"; var response = await this.client.PostAsync(new Uri(string.Format(GoogleGetConfirmationCodeUrl, this.authConfig.ApiKey)), new StringContent(content, Encoding.UTF8, "application/json")).ConfigureAwait(false); response.EnsureSuccessStatusCode(); } /// <summary> /// Sends user an email with a link to verify his email address. /// </summary> /// <param name="auth"> The authenticated user to verify email address. </param> public async Task SendEmailVerificationAsync(FirebaseAuth auth) { await this.SendEmailVerificationAsync(auth.FirebaseToken).ConfigureAwait(false); } /// <summary> /// Links the given <see cref="firebaseToken"/> with an email and password. /// </summary> /// <param name="firebaseToken"> The FirebaseToken (idToken) of an authenticated user. </param> /// <param name="email"> The email. </param> /// <param name="password"> The password. </param> /// <returns> The <see cref="FirebaseAuthLink"/>. </returns> public async Task<FirebaseAuthLink> LinkAccountsAsync(string firebaseToken, string email, string password) { var content = $"{{\"idToken\":\"{firebaseToken}\",\"email\":\"{email}\",\"password\":\"{password}\",\"returnSecureToken\":true}}"; return await this.ExecuteWithPostContentAsync(GoogleSetAccountUrl, content).ConfigureAwait(false); } /// <summary> /// Links the authenticated user represented by <see cref="auth"/> with an email and password. /// </summary> /// <param name="auth"> The authenticated user to link with specified email and password. </param> /// <param name="email"> The email. </param> /// <param name="password"> The password. </param> /// <returns> The <see cref="FirebaseAuthLink"/>. </returns> public async Task<FirebaseAuthLink> LinkAccountsAsync(FirebaseAuth auth, string email, string password) { return await this.LinkAccountsAsync(auth.FirebaseToken, email, password).ConfigureAwait(false); } /// <summary> /// Links the given <see cref="firebaseToken"/> with an account from a third party provider. /// </summary> /// <param name="firebaseToken"> The FirebaseToken (idToken) of an authenticated user. </param> /// <param name="authType"> The auth type. </param> /// <param name="oauthAccessToken"> The access token retrieved from login provider of your choice. </param> /// <returns> The <see cref="FirebaseAuthLink"/>. </returns> public async Task<FirebaseAuthLink> LinkAccountsAsync(string firebaseToken, FirebaseAuthType authType, string oauthAccessToken) { var providerId = this.GetProviderId(authType); var content = $"{{\"idToken\":\"{firebaseToken}\",\"postBody\":\"access_token={oauthAccessToken}&providerId={providerId}\",\"requestUri\":\"http://localhost\",\"returnSecureToken\":true}}"; return await this.ExecuteWithPostContentAsync(GoogleIdentityUrl, content).ConfigureAwait(false); } /// <summary> /// Links the authenticated user represented by <see cref="auth"/> with an account from a third party provider. /// </summary> /// <param name="auth"> The auth. </param> /// <param name="authType"> The auth type. </param> /// <param name="oauthAccessToken"> The access token retrieved from login provider of your choice. </param> /// <returns> The <see cref="FirebaseAuthLink"/>. </returns> public async Task<FirebaseAuthLink> LinkAccountsAsync(FirebaseAuth auth, FirebaseAuthType authType, string oauthAccessToken) { return await this.LinkAccountsAsync(auth.FirebaseToken, authType, oauthAccessToken).ConfigureAwait(false); } /// <summary> /// Unlinks the given <see cref="authType"/> from the account associated with <see cref="firebaseToken"/>. /// </summary> /// <param name="firebaseToken"> The FirebaseToken (idToken) of an authenticated user. </param> /// <param name="authType"> The auth type. </param> /// <returns> The <see cref="FirebaseAuthLink"/>. </returns> public async Task<FirebaseAuthLink> UnlinkAccountsAsync(string firebaseToken, FirebaseAuthType authType) { string providerId = null; if (authType == FirebaseAuthType.EmailAndPassword) { providerId = authType.ToEnumString(); } else { providerId = this.GetProviderId(authType); } var content = $"{{\"idToken\":\"{firebaseToken}\",\"deleteProvider\":[\"{providerId}\"]}}"; return await this.ExecuteWithPostContentAsync(GoogleSetAccountUrl, content).ConfigureAwait(false); } /// <summary> /// Unlinks the given <see cref="authType"/> from the authenticated user represented by <see cref="auth"/>. /// </summary> /// <param name="auth"> The auth. </param> /// <param name="authType"> The auth type. </param> /// <returns> The <see cref="FirebaseAuthLink"/>. </returns> public async Task<FirebaseAuthLink> UnlinkAccountsAsync(FirebaseAuth auth, FirebaseAuthType authType) { return await this.UnlinkAccountsAsync(auth.FirebaseToken, authType).ConfigureAwait(false); } /// <summary> /// Gets a list of accounts linked to given email. /// </summary> /// <param name="email"> Email address. </param> /// <returns> The <see cref="ProviderQueryResult"/></returns> public async Task<ProviderQueryResult> GetLinkedAccountsAsync(string email) { string content = $"{{\"identifier\":\"{email}\", \"continueUri\": \"http://localhost\"}}"; string responseData = "N/A"; try { var response = await this.client.PostAsync(new Uri(string.Format(GoogleCreateAuthUrl, this.authConfig.ApiKey)), new StringContent(content, Encoding.UTF8, "application/json")).ConfigureAwait(false); responseData = await response.Content.ReadAsStringAsync().ConfigureAwait(false); response.EnsureSuccessStatusCode(); var data = JsonConvert.DeserializeObject<ProviderQueryResult>(responseData); data.Email = email; return data; } catch (Exception ex) { throw new FirebaseAuthException(GoogleCreateAuthUrl, content, responseData, ex); } } public async Task<FirebaseAuthLink> RefreshAuthAsync(FirebaseAuth auth) { var content = $"{{\"grant_type\":\"refresh_token\", \"refresh_token\":\"{auth.RefreshToken}\"}}"; var responseData = "N/A"; try { var response = await this.client.PostAsync(new Uri(string.Format(GoogleRefreshAuth, this.authConfig.ApiKey)), new StringContent(content, Encoding.UTF8, "application/json")).ConfigureAwait(false); responseData = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var refreshAuth = JsonConvert.DeserializeObject<RefreshAuth>(responseData); return new FirebaseAuthLink { AuthProvider = this, User = auth.User, ExpiresIn = refreshAuth.ExpiresIn, RefreshToken = refreshAuth.RefreshToken, FirebaseToken = refreshAuth.AccessToken }; } catch (Exception ex) { throw new FirebaseAuthException(GoogleRefreshAuth, content, responseData, ex); } } /// <summary> /// Disposes all allocated resources. /// </summary> public void Dispose() { this.client.Dispose(); } private async Task<FirebaseAuthLink> ExecuteWithPostContentAsync(string googleUrl, string postContent) { string responseData = "N/A"; try { var response = await this.client.PostAsync(new Uri(string.Format(googleUrl, this.authConfig.ApiKey)), new StringContent(postContent, Encoding.UTF8, "application/json")).ConfigureAwait(false); responseData = await response.Content.ReadAsStringAsync().ConfigureAwait(false); response.EnsureSuccessStatusCode(); var user = JsonConvert.DeserializeObject<User>(responseData); var auth = JsonConvert.DeserializeObject<FirebaseAuthLink>(responseData); auth.AuthProvider = this; auth.User = user; return auth; } catch (Exception ex) { AuthErrorReason errorReason = GetFailureReason(responseData); throw new FirebaseAuthException(googleUrl, postContent, responseData, ex, errorReason); } } /// <summary> /// Resolves failure reason flags based on the returned error code. /// </summary> /// <remarks>Currently only provides support for failed email auth flags.</remarks> private static AuthErrorReason GetFailureReason(string responseData) { var failureReason = AuthErrorReason.Undefined; try { if (!string.IsNullOrEmpty(responseData) && responseData != "N/A") { //create error data template and try to parse JSON var errorData = new { error = new { code = 0, message = "errorid" } }; errorData = JsonConvert.DeserializeAnonymousType(responseData, errorData); //errorData is just null if different JSON was received switch (errorData?.error?.message) { //general errors case "invalid access_token, error code 43.": failureReason = AuthErrorReason.InvalidAccessToken; break; case "CREDENTIAL_TOO_OLD_LOGIN_AGAIN": failureReason = AuthErrorReason.LoginCredentialsTooOld; break; //possible errors from Third Party Authentication using GoogleIdentityUrl case "INVALID_PROVIDER_ID : Provider Id is not supported.": failureReason = AuthErrorReason.InvalidProviderID; break; case "MISSING_REQUEST_URI": failureReason = AuthErrorReason.MissingRequestURI; break; case "A system error has occurred - missing or invalid postBody": failureReason = AuthErrorReason.SystemError; break; //possible errors from Email/Password Account Signup (via signupNewUser or setAccountInfo) or Signin case "INVALID_EMAIL": failureReason = AuthErrorReason.InvalidEmailAddress; break; case "MISSING_PASSWORD": failureReason = AuthErrorReason.MissingPassword; break; //possible errors from Email/Password Account Signup (via signupNewUser or setAccountInfo) case "WEAK_PASSWORD : Password should be at least 6 characters": failureReason = AuthErrorReason.WeakPassword; break; case "EMAIL_EXISTS": failureReason = AuthErrorReason.EmailExists; break; //possible errors from Account Delete case "USER_NOT_FOUND": failureReason = AuthErrorReason.UserNotFound; break; //possible errors from Email/Password Signin case "INVALID_PASSWORD": failureReason = AuthErrorReason.WrongPassword; break; case "EMAIL_NOT_FOUND": failureReason = AuthErrorReason.UnknownEmailAddress; break; case "USER_DISABLED": failureReason = AuthErrorReason.UserDisabled; break; //possible errors from Email/Password Signin or Password Recovery or Email/Password Sign up using setAccountInfo case "MISSING_EMAIL": failureReason = AuthErrorReason.MissingEmail; break; //possible errors from Password Recovery case "MISSING_REQ_TYPE": failureReason = AuthErrorReason.MissingRequestType; break; //possible errors from Account Linking case "INVALID_ID_TOKEN": failureReason = AuthErrorReason.InvalidIDToken; break; //possible errors from Getting Linked Accounts case "INVALID_IDENTIFIER": failureReason = AuthErrorReason.InvalidIdentifier; break; case "MISSING_IDENTIFIER": failureReason = AuthErrorReason.MissingIdentifier; break; case "FEDERATED_USER_ID_ALREADY_LINKED": failureReason = AuthErrorReason.AlreadyLinked; break; } } } catch (JsonReaderException) { //the response wasn't JSON - no data to be parsed } catch (Exception e) { Debug.WriteLine($"Unexpected error trying to parse the response: {e}"); } return failureReason; } private string GetProviderId(FirebaseAuthType authType) { switch (authType) { case FirebaseAuthType.Facebook: case FirebaseAuthType.Google: case FirebaseAuthType.Github: case FirebaseAuthType.Twitter: return authType.ToEnumString(); case FirebaseAuthType.EmailAndPassword: throw new InvalidOperationException("Email auth type cannot be used like this. Use methods specific to email & password authentication."); default: throw new NotImplementedException(""); } } } }
49.414587
218
0.593436
[ "MIT" ]
cabauman/firebase-authentication-dotnet
src/Firebase.Auth/FirebaseAuthProvider.cs
25,747
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Core.Core; using Dominio; namespace Core.Negocio { public class GerarBandeira : IStrategy { public string processar(EntidadeDominio entidade) { Cartao_Credito car = (Cartao_Credito)entidade; if (!string.IsNullOrEmpty( car.Numero)) { if (car.Numero.StartsWith("509048") || car.Numero.StartsWith("509067") || car.Numero.StartsWith("509049") || car.Numero.StartsWith("509069") || car.Numero.StartsWith("509050") || car.Numero.StartsWith("509074") || car.Numero.StartsWith("509068") || car.Numero.StartsWith("509040") || car.Numero.StartsWith("509045") || car.Numero.StartsWith("509051") || car.Numero.StartsWith("509046") || car.Numero.StartsWith("509066") || car.Numero.StartsWith("509047") || car.Numero.StartsWith("509042") || car.Numero.StartsWith("509052") || car.Numero.StartsWith("509043") || car.Numero.StartsWith("509064") || car.Numero.StartsWith("509040")) { return "bandeira invalida"; } else if (car.Numero.StartsWith("5")) { car.Bandeira.ID = 1; } else if (car.Numero.StartsWith("4")) { car.Bandeira.ID = 2; } else return "bandeira invalida"; } else { return "numero nulo ou invalida"; } return null; } } }
36.367347
89
0.508418
[ "MIT" ]
Luiz-HSSD/LES_passagens_areas
Core/Negocio/GerarBandeira.cs
1,784
C#
namespace CpuSchedulingAlgorithms; public class ShortestJobFirstScheduler : IProcessScheduler { private readonly ArrivalSchedule schedule; private readonly PriorityQueue<ProcessControlBlock, int> readyQueue = new(); private readonly List<CompletedProcess> completedProcesses = new(); private bool HasNextProcess => readyQueue.Count > 0; public IReadOnlyList<CompletedProcess> CompletedProcesses => completedProcesses.AsReadOnly(); public ProcessTimeline Timeline { get; } = new(); public ProcessControlBlock? CurrentProcess { get; private set; } public int Now { get; private set; } public ProcessQueueView RunQueue => new(readyQueue.UnorderedItems.Select(i => i.Element)); public ShortestJobFirstScheduler(ArrivalSchedule schedule) { this.schedule = schedule; } /// <inheritdoc/> public bool Proceed() { // Return false because no more processes will arrive if: // * no current process exists or if the current process is complete and // * no next process (ready queue is empty) and // * current time quantum is more than the schedule end time/maximum arrival time of all processes) if (CurrentProcess is null or { IsComplete: true } && !HasNextProcess && Now > schedule.EndTime) { return false; } // Add processes arrived at current time(Now) to the ready queue if (Now <= schedule.EndTime) { foreach (var process in schedule.GetProcessesArrivedAt(Now)) { readyQueue.Enqueue(new ProcessControlBlock(process, arrivalTime: Now), process.BurstTime); } } // If no current process exists or if the current process is complete, get next process if exists if (CurrentProcess is null or { IsComplete: true }) { CurrentProcess = HasNextProcess ? readyQueue.Dequeue() : null; } // Execute the current process and increment to the next time quantum CurrentProcess?.Execute(Now); Now++; // Add the process that consumed the current time quantum to the timeline Timeline.Add(Now, CurrentProcess); // If process is complete, add process to the list of completed processes if (CurrentProcess is { IsComplete: true }) { completedProcesses.Add(CompletedProcess.FromProcessControlBlock(CurrentProcess, Now)); } return true; } }
34.164384
108
0.661588
[ "MIT" ]
amal-stack/CpuSchedulingAlgorithms
CpuSchedulingAlgorithms/ShortestJobFirstScheduler.cs
2,496
C#
namespace Vidly.ViewModels { public class FactorViewModel { public string Purpose { get; set; } } }
17.142857
43
0.625
[ "MIT" ]
briang123/Vidly
Vidly/ViewModels/FactorViewModel.cs
122
C#
namespace BoomBang.Game.Laptop { using BoomBang; using BoomBang.Communication; using BoomBang.Communication.Incoming; using BoomBang.Communication.Outgoing; using BoomBang.Game.Characters; using BoomBang.Game.Sessions; using BoomBang.Storage; using BoomBang.Utils; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; public static class LaptopHandler { public static void CreateFriendship(SqlDatabaseClient MySqlClient, uint UserId1, uint UserId2, bool Confirmed) { // This item is obfuscated and can not be translated. int num = 0; while (true) { if (Confirmed) { } if (num >= 2) { return; } string query; if (num == 1) { if (Confirmed) query = "INSERT INTO laptop_amigos (id_usuario,id_amigo,aceptado) VALUES ('" + UserId1 + "','" + UserId2 + "',1)"; else query = "INSERT INTO laptop_amigos (id_usuario,id_amigo,aceptado) VALUES ('" + UserId1 + "','" + UserId2 + "',0)"; } else { if (Confirmed) query = "INSERT INTO laptop_amigos (id_usuario,id_amigo,aceptado) VALUES ('" + UserId2 + "','" + UserId1 + "',1)"; else query = "INSERT INTO laptop_amigos (id_usuario,id_amigo,aceptado) VALUES ('" + UserId2 + "','" + UserId1 + "',0)"; } MySqlClient.ExecuteNonQuery(query); // Console.WriteLine(query); num++; } } public static bool DestroyFriendship(SqlDatabaseClient MySqlClient, uint UserId1, uint UserId2) { int num = 0; for (int i = 0; i < 2; i++) { MySqlClient.SetParameter("user1", (i == 1) ? UserId1 : UserId2); MySqlClient.SetParameter("user2", (i == 1) ? UserId2 : UserId1); num += MySqlClient.ExecuteNonQuery("DELETE FROM laptop_amigos WHERE id_usuario = @user1 AND id_amigo = @user2 LIMIT 1"); } return (num > 0); } public static void ForceLaptopUpdateForSession(Session SessionToUpdate) { SessionToUpdate.SendData(SessionToUpdate.LaptopFriendCache.ComposeUpdateList(), false); } public static bool FriendshipExists(SqlDatabaseClient MySqlClient, uint UserId1, uint UserId2, bool ConfirmedOnly) { MySqlClient.SetParameter("user1", UserId1); MySqlClient.SetParameter("user2", UserId2); MySqlClient.SetParameter("confirmed", ConfirmedOnly ? 0 : 2); return (MySqlClient.ExecuteQueryRow("SELECT null FROM laptop_amigos WHERE id_usuario = @user1 AND id_amigo = @user2 AND aceptado != @confirmed OR id_amigo = @user1 AND id_usuario = @user2 AND aceptado != @confirmed LIMIT 1") != null); } public static List<uint> GetFriendsForUser(SqlDatabaseClient MySqlClient, uint UserId, int Confirmed) { List<uint> list = new List<uint>(); MySqlClient.SetParameter("id", UserId); MySqlClient.SetParameter("confirmed", Confirmed); foreach (DataRow row in MySqlClient.ExecuteQueryTable("SELECT id_amigo FROM laptop_amigos WHERE id_usuario = @id AND aceptado = @confirmed").Rows) { list.Add((uint)row[0]); } return list; } public static void Initialize() { DataRouter.RegisterHandler(FlagcodesIn.LAPTOP, ItemcodesIn.LAPTOP_LOAD_FRIENDS, new ProcessRequestCallback(LaptopHandler.smethod_0), false); DataRouter.RegisterHandler(FlagcodesIn.LAPTOP, ItemcodesIn.LAPTOP_LOAD_MESSAGES, new ProcessRequestCallback(LaptopHandler.smethod_1), false); DataRouter.RegisterHandler(FlagcodesIn.LAPTOP, ItemcodesIn.LAPTOP_SEARCH_BUDDY, new ProcessRequestCallback(LaptopHandler.smethod_3), false); DataRouter.RegisterHandler(FlagcodesIn.LAPTOP, ItemcodesIn.LAPTOP_UPDATE_LAPTOP, new ProcessRequestCallback(LaptopHandler.smethod_2), false); DataRouter.RegisterHandler(FlagcodesIn.LAPTOP, ItemcodesIn.LAPTOP_UPDATE_BUDDY, new ProcessRequestCallback(LaptopHandler.smethod_4), false); DataRouter.RegisterHandler(FlagcodesIn.LAPTOP, ItemcodesIn.LAPTOP_FRIEND_REQUEST, new ProcessRequestCallback(LaptopHandler.smethod_5), false); DataRouter.RegisterHandler(FlagcodesIn.LAPTOP, ItemcodesIn.LAPTOP_FRIEND_DECLINE, new ProcessRequestCallback(LaptopHandler.smethod_7), false); DataRouter.RegisterHandler(FlagcodesIn.LAPTOP, ItemcodesIn.LAPTOP_FRIEND_ACCEPT, new ProcessRequestCallback(LaptopHandler.smethod_6), false); DataRouter.RegisterHandler(FlagcodesIn.LAPTOP, ItemcodesIn.LAPTOP_FRIEND_DELETE, new ProcessRequestCallback(LaptopHandler.smethod_8), false); DataRouter.RegisterHandler(FlagcodesIn.LAPTOP, ItemcodesIn.LAPTOP_SEND_MESSAGE, new ProcessRequestCallback(LaptopHandler.smethod_9), false); DataRouter.RegisterHandler(FlagcodesIn.LAPTOP, ItemcodesIn.LAPTOP_DELETE_MESSAGE, new ProcessRequestCallback(LaptopHandler.smethod_10), false); } public static void MarkUpdateNeeded(Session UpdatedSession, int Mode, bool ForceInstant) { ReadOnlyCollection<uint> friends = UpdatedSession.LaptopFriendCache.Friends; if (friends != null) { foreach (uint num in friends) { Session sessionByCharacterId = SessionManager.GetSessionByCharacterId(num); if (sessionByCharacterId != null) { sessionByCharacterId.LaptopFriendCache.MarkUpdateNeeded(UpdatedSession.CharacterId, Mode); ForceLaptopUpdateForSession(sessionByCharacterId); } } } } private static void smethod_0(Session session_0, ClientMessage clientMessage_0) { ReadOnlyCollection<uint> friends = session_0.LaptopFriendCache.Friends; List<uint> requests = new List<uint>(); using (SqlDatabaseClient client = SqlDatabaseManager.GetClient()) { requests = GetFriendsForUser(client, session_0.CharacterId, 0); } session_0.SendData(LaptopFriendListComposer.Compose(friends, requests), false); } private static void smethod_1(Session session_0, ClientMessage clientMessage_0) { using (SqlDatabaseClient client = SqlDatabaseManager.GetClient()) { client.SetParameter("receptor", session_0.CharacterId); DataTable table = client.ExecuteQueryTable("SELECT * FROM laptop_mensajes WHERE (receptor = @receptor AND leido = '0') OR general = '1'"); session_0.SendData(Class0.smethod_0(table), false); } } private static void smethod_10(Session session_0, ClientMessage clientMessage_0) { uint num = clientMessage_0.ReadUnsignedInteger(); using (SqlDatabaseClient client = SqlDatabaseManager.GetClient()) { client.SetParameter("id", num); client.SetParameter("receptor", session_0.CharacterId); client.ExecuteNonQuery("UPDATE laptop_mensajes SET leido = '1' WHERE id = @id AND receptor = @receptor LIMIT 1"); } } private static void smethod_2(Session session_0, ClientMessage clientMessage_0) { ForceLaptopUpdateForSession(session_0); } private static void smethod_3(Session session_0, ClientMessage clientMessage_0) { string str = InputFilter.FilterString(clientMessage_0.ReadString().Replace('%', ' '), false); if (str.Length >= 1) { CharacterInfo characterInfo = null; using (SqlDatabaseClient client = SqlDatabaseManager.GetClient()) { client.SetParameter("query", str); DataRow row = client.ExecuteQueryRow("SELECT id FROM usuarios WHERE usuario = @query LIMIT 1"); if (row != null) { characterInfo = CharacterInfoLoader.GetCharacterInfo(client, (uint)row["id"]); } } session_0.SendData(LaptopSearchResultComposer.Compose(characterInfo), false); } } private static void smethod_4(Session session_0, ClientMessage clientMessage_0) { } private static void smethod_5(Session session_0, ClientMessage clientMessage_0) { uint characterId = clientMessage_0.ReadUnsignedInteger(); if ((characterId >= 1) && (characterId != session_0.CharacterId)) { CharacterInfo characterInfo = null; using (SqlDatabaseClient client = SqlDatabaseManager.GetClient()) { characterInfo = CharacterInfoLoader.GetCharacterInfo(client, characterId); if (FriendshipExists(client, session_0.CharacterId, characterInfo.UInt32_0, false)) { return; } CreateFriendship(client, session_0.CharacterId, characterInfo.UInt32_0, false); } Session sessionByCharacterId = SessionManager.GetSessionByCharacterId(characterInfo.UInt32_0); if (sessionByCharacterId != null) { sessionByCharacterId.SendData(LaptopRequestNotificationComposer.Compose(session_0.CharacterInfo), false); } } } private static void smethod_6(Session session_0, ClientMessage clientMessage_0) { uint num = clientMessage_0.ReadUnsignedInteger(); using (SqlDatabaseClient client = SqlDatabaseManager.GetClient()) { client.SetParameter("user1", session_0.CharacterId); client.SetParameter("user2", num); client.SetParameter("confirmed", 1); if (client.ExecuteNonQuery("UPDATE laptop_amigos SET aceptado = @confirmed WHERE id_usuario = @user1 AND id_amigo = @user2 LIMIT 1") > 0) { client.SetParameter("user1", num); client.SetParameter("user2", session_0.CharacterId); client.SetParameter("confirmed", 1); client.ExecuteNonQuery("INSERT INTO laptop_amigos (id_usuario,id_amigo,aceptado) VALUES (@user1,@user2,@confirmed)"); session_0.LaptopFriendCache.AddToCache(num); Session sessionByCharacterId = SessionManager.GetSessionByCharacterId(num); if (sessionByCharacterId != null) { sessionByCharacterId.LaptopFriendCache.AddToCache(session_0.CharacterId); ForceLaptopUpdateForSession(sessionByCharacterId); sessionByCharacterId.SendData(LaptopNewFriendComposer.Compose(session_0.CharacterInfo), false); } session_0.SendData(LaptopAcceptFriendComposer.Compose(num), false); } } } private static void smethod_7(Session session_0, ClientMessage clientMessage_0) { uint num = clientMessage_0.ReadUnsignedInteger(); using (SqlDatabaseClient client = SqlDatabaseManager.GetClient()) { DestroyFriendship(client, session_0.CharacterId, num); } session_0.SendData(LaptopDeclineBuddyComposer.Compose(session_0.CharacterId), false); } private static void smethod_8(Session session_0, ClientMessage clientMessage_0) { uint num = clientMessage_0.ReadUnsignedInteger(); using (SqlDatabaseClient client = SqlDatabaseManager.GetClient()) { if (DestroyFriendship(client, session_0.CharacterId, num)) { session_0.LaptopFriendCache.RemoveFromCache(num); Session sessionByCharacterId = SessionManager.GetSessionByCharacterId(num); if (sessionByCharacterId != null) { sessionByCharacterId.LaptopFriendCache.RemoveFromCache(session_0.CharacterId); sessionByCharacterId.SendData(LaptopDeleteFriendComposer.Compose(session_0.CharacterId), false); } } } session_0.SendData(LaptopDeleteFriendComposer.Compose(num), false); } private static void smethod_9(Session session_0, ClientMessage clientMessage_0) { uint num = clientMessage_0.ReadUnsignedInteger(); string str = InputFilter.FilterString(clientMessage_0.ReadString(), false).Trim(); if ((((num > 0) && (str.Length >= 1)) && (num != session_0.CharacterId)) && session_0.LaptopFriendCache.Friends.Contains(num)) { Session sessionByCharacterId = SessionManager.GetSessionByCharacterId(num); if (sessionByCharacterId == null) { using (SqlDatabaseClient client = SqlDatabaseManager.GetClient()) { client.SetParameter("sender", session_0.CharacterId); client.SetParameter("receptor", num); client.SetParameter("text", str); client.SetParameter("time", UnixTimestamp.GetCurrent()); client.SetParameter("color", session_0.CharacterInfo.Staff); client.ExecuteNonQuery("INSERT INTO laptop_mensajes (emisor, receptor, contenido, timestamp, color, leido) VALUES (@sender, @receptor, @text, @time, @color, 0)"); } } else { sessionByCharacterId.SendData(LaptopMessageComposer.Compose(session_0.CharacterId, str, session_0.CharacterInfo.Staff), false); } } } } }
54.587413
250
0.564117
[ "MIT" ]
DaLoE99/Servidores-DaLoE
3/BoomBang/BoomBang/Game/Laptop/LaptopHandler.cs
15,614
C#
using System; namespace LibHac.IO.Save { public class AllocationTableStorage : StorageBase { private IStorage BaseStorage { get; } private int BlockSize { get; } private int InitialBlock { get; } private AllocationTable Fat { get; } private long _length; public AllocationTableStorage(IStorage data, AllocationTable table, int blockSize, int initialBlock, long length) { BaseStorage = data; BlockSize = blockSize; _length = length; Fat = table; InitialBlock = initialBlock; } protected override void ReadImpl(Span<byte> destination, long offset) { var iterator = new AllocationTableIterator(Fat, InitialBlock); long inPos = offset; int outPos = 0; int remaining = destination.Length; while (remaining > 0) { int blockNum = (int)(inPos / BlockSize); iterator.Seek(blockNum); int segmentPos = (int)(inPos - (long)iterator.VirtualBlock * BlockSize); long physicalOffset = iterator.PhysicalBlock * BlockSize + segmentPos; int remainingInSegment = iterator.CurrentSegmentSize * BlockSize - segmentPos; int bytesToRead = Math.Min(remaining, remainingInSegment); BaseStorage.Read(destination.Slice(outPos, bytesToRead), physicalOffset); outPos += bytesToRead; inPos += bytesToRead; remaining -= bytesToRead; } } protected override void WriteImpl(ReadOnlySpan<byte> source, long offset) { var iterator = new AllocationTableIterator(Fat, InitialBlock); long inPos = offset; int outPos = 0; int remaining = source.Length; while (remaining > 0) { int blockNum = (int)(inPos / BlockSize); iterator.Seek(blockNum); int segmentPos = (int)(inPos - (long)iterator.VirtualBlock * BlockSize); long physicalOffset = iterator.PhysicalBlock * BlockSize + segmentPos; int remainingInSegment = iterator.CurrentSegmentSize * BlockSize - segmentPos; int bytesToWrite = Math.Min(remaining, remainingInSegment); BaseStorage.Write(source.Slice(outPos, bytesToWrite), physicalOffset); outPos += bytesToWrite; inPos += bytesToWrite; remaining -= bytesToWrite; } } public override void Flush() { BaseStorage.Flush(); } public override long GetSize() => _length; } }
33.588235
122
0.553415
[ "BSD-3-Clause" ]
shchmue/LibHac
src/LibHac/IO/Save/AllocationTableStorage.cs
2,773
C#
/* * FactSet Symbology API * * The FactSet Symbology API provides symbol resolution services, allowing clients to translate market identifiers into various symbology types such as, FactSet Permanent Identifiers, CUSIP, ISIN, SEDOL, Tickers, and Bloomberg FIGIs. <p>Factset's Symbology API sits at the center of its hub-and-spoke data model, enabling you to quickly harmonize the expanding catalog of Content APIs. Translate market IDs into CUSIP, SEDOL, ISIN, Tickers as of a point in time or for the entire history of the requested id allowing Data Management workflows to normalize ids over time.</p> * * The version of the OpenAPI document: 2.1.1 * Contact: api@factset.com * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = FactSet.SDK.Symbology.Client.OpenAPIDateConverter; namespace FactSet.SDK.Symbology.Model { /// <summary> /// Request object for Ticker endpoint. /// </summary> [DataContract(Name = "tickerHistoryTranslationRequest")] public partial class TickerHistoryTranslationRequest : IEquatable<TickerHistoryTranslationRequest>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="TickerHistoryTranslationRequest" /> class. /// </summary> [JsonConstructorAttribute] protected TickerHistoryTranslationRequest() { } /// <summary> /// Initializes a new instance of the <see cref="TickerHistoryTranslationRequest" /> class. /// </summary> /// <param name="ids">Requested market securities or entities. Accepted identifiers include all FactSet Permanent Identifiers types, CUSIP, SEDOL, ISIN, and Tickers. This request value is sent back in the response as, &#x60;requestId&#39;. (required).</param> /// <param name="tickerType">Controls the Ticker Type returned. * **REGION** &#x3D; Ticker-Regional * **EXCHANGE** &#x3D; Ticker-Exchange (required).</param> /// <param name="asOfDate">As-Of date for historical symbol request in YYYY-MM-DD format..</param> public TickerHistoryTranslationRequest(List<string> ids = default(List<string>), string tickerType = default(string), string asOfDate = default(string)) { // to ensure "ids" is required (not null) if (ids == null) { throw new ArgumentNullException("ids is a required property for TickerHistoryTranslationRequest and cannot be null"); } this.Ids = ids; // to ensure "tickerType" is required (not null) if (tickerType == null) { throw new ArgumentNullException("tickerType is a required property for TickerHistoryTranslationRequest and cannot be null"); } this.TickerType = tickerType; this.AsOfDate = asOfDate; } /// <summary> /// Requested market securities or entities. Accepted identifiers include all FactSet Permanent Identifiers types, CUSIP, SEDOL, ISIN, and Tickers. This request value is sent back in the response as, &#x60;requestId&#39;. /// </summary> /// <value>Requested market securities or entities. Accepted identifiers include all FactSet Permanent Identifiers types, CUSIP, SEDOL, ISIN, and Tickers. This request value is sent back in the response as, &#x60;requestId&#39;.</value> [DataMember(Name = "ids", IsRequired = true, EmitDefaultValue = false)] public List<string> Ids { get; set; } /// <summary> /// Controls the Ticker Type returned. * **REGION** &#x3D; Ticker-Regional * **EXCHANGE** &#x3D; Ticker-Exchange /// </summary> /// <value>Controls the Ticker Type returned. * **REGION** &#x3D; Ticker-Regional * **EXCHANGE** &#x3D; Ticker-Exchange </value> [DataMember(Name = "tickerType", IsRequired = true, EmitDefaultValue = false)] public string TickerType { get; set; } /// <summary> /// As-Of date for historical symbol request in YYYY-MM-DD format. /// </summary> /// <value>As-Of date for historical symbol request in YYYY-MM-DD format.</value> [DataMember(Name = "asOfDate", EmitDefaultValue = false)] public string AsOfDate { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class TickerHistoryTranslationRequest {\n"); sb.Append(" Ids: ").Append(Ids).Append("\n"); sb.Append(" TickerType: ").Append(TickerType).Append("\n"); sb.Append(" AsOfDate: ").Append(AsOfDate).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as TickerHistoryTranslationRequest); } /// <summary> /// Returns true if TickerHistoryTranslationRequest instances are equal /// </summary> /// <param name="input">Instance of TickerHistoryTranslationRequest to be compared</param> /// <returns>Boolean</returns> public bool Equals(TickerHistoryTranslationRequest input) { if (input == null) { return false; } return ( this.Ids == input.Ids || this.Ids != null && input.Ids != null && this.Ids.SequenceEqual(input.Ids) ) && ( this.TickerType == input.TickerType || (this.TickerType != null && this.TickerType.Equals(input.TickerType)) ) && ( this.AsOfDate == input.AsOfDate || (this.AsOfDate != null && this.AsOfDate.Equals(input.AsOfDate)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Ids != null) { hashCode = (hashCode * 59) + this.Ids.GetHashCode(); } if (this.TickerType != null) { hashCode = (hashCode * 59) + this.TickerType.GetHashCode(); } if (this.AsOfDate != null) { hashCode = (hashCode * 59) + this.AsOfDate.GetHashCode(); } return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> public IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> Validate(ValidationContext validationContext) { yield break; } } }
44.934426
575
0.602943
[ "Apache-2.0" ]
factset/enterprise-sdk
code/dotnet/Symbology/v2/src/FactSet.SDK.Symbology/Model/TickerHistoryTranslationRequest.cs
8,223
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; using System.Reflection.Emit; /// <summary> /// OpCodes.Leave_S [v-minch] /// </summary> public class OpCodesLeave_S { public static int Main() { OpCodesLeave_S test = new OpCodesLeave_S(); TestLibrary.TestFramework.BeginTestCase("Test for the field of OpCodes.Leave_S"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; return retVal; } #region PositiveTest public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Verify OpCodes Leave_Sfield value"); try { retVal = VerificationHelper(OpCodes.Leave_S, "leave.s", StackBehaviour.Pop0, StackBehaviour.Push0, OperandType.ShortInlineBrTarget, OpCodeType.Primitive, 1, (byte)0xfe, (byte)0xde, FlowControl.Branch, "001.", "Leave_S") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #region Private Methods private bool VerificationHelper(OpCode code, string name, StackBehaviour pop, StackBehaviour push, OperandType oprandType, OpCodeType type, int size, byte s1, byte s2, FlowControl ctrl, string errorno, string errordesp) { bool retVal = true; string actualName = code.Name; if (actualName != name) { TestLibrary.TestFramework.LogError(errorno + ".0", "Name returns wrong value for OpCode " + errordesp); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualName = " + actualName + ", name = " + name); retVal = false; } StackBehaviour actualPop = code.StackBehaviourPop; if (actualPop != pop) { TestLibrary.TestFramework.LogError(errorno + ".1", "StackBehaviourPop returns wrong value for OpCode " + errordesp); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualPop = " + actualPop + ", pop = " + pop); retVal = false; } StackBehaviour actualPush = code.StackBehaviourPush; if (actualPush != push) { TestLibrary.TestFramework.LogError(errorno + ".2", "StackBehaviourPush returns wrong value for OpCode " + errordesp); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualPush = " + actualPush + ", push = " + push); retVal = false; } OperandType actualOperandType = code.OperandType; if (actualOperandType != oprandType) { TestLibrary.TestFramework.LogError(errorno + ".3", "OperandType returns wrong value for OpCode " + errordesp); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualOperandType = " + actualOperandType + ", oprandType = " + oprandType); retVal = false; } OpCodeType actualOpCodeType = code.OpCodeType; if (actualOpCodeType != type) { TestLibrary.TestFramework.LogError(errorno + ".4", "OpCodeType returns wrong value for OpCode " + errordesp); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualOpCodeType = " + actualOpCodeType + ", type = " + type); retVal = false; } int actualSize = code.Size; if (actualSize != size) { TestLibrary.TestFramework.LogError(errorno + ".5", "Size returns wrong value for OpCode " + errordesp); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualSize = " + actualSize + ", size = " + size); retVal = false; } short expectedValue = 0; if (size == 2) expectedValue = (short)(s1 << 8 | s2); else expectedValue = (short)s2; short actualValue = code.Value; if (actualValue != expectedValue) { TestLibrary.TestFramework.LogError(errorno + ".6", "Value returns wrong value for OpCode " + errordesp); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualValue = " + actualValue + ", s1 = " + s1 + ", s2 = " + s2 + ", expectedValue = " + expectedValue); retVal = false; } FlowControl actualCtrl = code.FlowControl; if (actualCtrl != ctrl) { TestLibrary.TestFramework.LogError(errorno + ".7", "FlowControl returns wrong value for OpCode " + errordesp); TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLE] actualCtrl = " + actualCtrl + ", ctrl = " + ctrl); retVal = false; } return retVal; } #endregion }
37.24026
183
0.591282
[ "MIT" ]
AaronRobinsonMSFT/coreclr
tests/src/CoreMangLib/cti/system/reflection/emit/opcodes/opcodesleave_s.cs
5,735
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System; using System.Collections.Generic; using System.IO; using System.Security; using Microsoft.Identity.Client; using Microsoft.Graph; using Microsoft.Extensions.Configuration; using Helpers; namespace graphconsoleapp { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); var config = LoadAppSettings(); if (config == null) { Console.WriteLine("Invalid appsettings.json file."); return; } var userName = ReadUsername(); var userPassword = ReadPassword(); var client = GetAuthenticatedGraphClient(config, userName, userPassword); // request 1 - get trending files around a specific user (me) // var request = client.Me.Insights.Trending.Request(); // var results = request.GetAsync().Result; // foreach (var resource in results) // { // Console.WriteLine("(" + resource.ResourceVisualization.Type + ") - " + resource.ResourceVisualization.Title); // Console.WriteLine(" Weight: " + resource.Weight); // Console.WriteLine(" Id: " + resource.Id); // Console.WriteLine(" ResourceId: " + resource.ResourceReference.Id); // } // request 2 - used files var request = client.Me.Insights.Used.Request(); var results = request.GetAsync().Result; foreach (var resource in results) { Console.WriteLine("(" + resource.ResourceVisualization.Type + ") - " + resource.ResourceVisualization.Title); Console.WriteLine(" Last Accessed: " + resource.LastUsed.LastAccessedDateTime.ToString()); Console.WriteLine(" Last Modified: " + resource.LastUsed.LastModifiedDateTime.ToString()); Console.WriteLine(" Id: " + resource.Id); Console.WriteLine(" ResourceId: " + resource.ResourceReference.Id); } } private static IConfigurationRoot LoadAppSettings() { try { var config = new ConfigurationBuilder() .SetBasePath(System.IO.Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", false, true) .Build(); if (string.IsNullOrEmpty(config["applicationId"]) || string.IsNullOrEmpty(config["tenantId"])) { return null; } return config; } catch (System.IO.FileNotFoundException) { return null; } } private static IAuthenticationProvider CreateAuthorizationProvider(IConfigurationRoot config, string userName, SecureString userPassword) { var clientId = config["applicationId"]; var authority = $"https://login.microsoftonline.com/{config["tenantId"]}/v2.0"; List<string> scopes = new List<string>(); scopes.Add("User.Read"); scopes.Add("Files.Read"); scopes.Add("Files.ReadWrite"); var cca = PublicClientApplicationBuilder.Create(clientId) .WithAuthority(authority) .Build(); return MsalAuthenticationProvider.GetInstance(cca, scopes.ToArray(), userName, userPassword); } private static GraphServiceClient GetAuthenticatedGraphClient(IConfigurationRoot config, string userName, SecureString userPassword) { var authenticationProvider = CreateAuthorizationProvider(config, userName, userPassword); var graphClient = new GraphServiceClient(authenticationProvider); return graphClient; } private static SecureString ReadPassword() { Console.WriteLine("Enter your password"); SecureString password = new SecureString(); while (true) { ConsoleKeyInfo c = Console.ReadKey(true); if (c.Key == ConsoleKey.Enter) { break; } password.AppendChar(c.KeyChar); Console.Write("*"); } Console.WriteLine(); return password; } private static string ReadUsername() { string username; Console.WriteLine("Enter your username"); username = Console.ReadLine(); return username; } } }
33.242424
142
0.610073
[ "MIT" ]
andrewconnell/msgraph-access-files-data
demos/03-trending-used/Program.cs
4,390
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WcfClientFactory Castle Windsor Facility")] [assembly: AssemblyDescription("Castle Windsor Facility for creation of runtime generated Wcf proxy clients")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Wcf Client Factory")] [assembly: AssemblyCopyright("Michael Yarichuk")] [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("3a617c04-42a9-4dc7-990b-a1f24fd69e87")] // 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")]
40.675676
110
0.755482
[ "Apache-2.0" ]
myarichuk/WcfClientFactory
Source/WcfClientFactory.CastleWindsor/Properties/AssemblyInfo.cs
1,507
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Redshift.Model { /// <summary> /// Describes event subscriptions. /// </summary> public partial class EventSubscription { private string _customerAwsId; private string _custSubscriptionId; private bool? _enabled; private List<string> _eventCategoriesList = new List<string>(); private string _severity; private string _snsTopicArn; private List<string> _sourceIdsList = new List<string>(); private string _sourceType; private string _status; private DateTime? _subscriptionCreationTime; private List<Tag> _tags = new List<Tag>(); /// <summary> /// Gets and sets the property CustomerAwsId. /// <para> /// The AWS customer account associated with the Amazon Redshift event notification subscription. /// </para> /// </summary> public string CustomerAwsId { get { return this._customerAwsId; } set { this._customerAwsId = value; } } // Check to see if CustomerAwsId property is set internal bool IsSetCustomerAwsId() { return this._customerAwsId != null; } /// <summary> /// Gets and sets the property CustSubscriptionId. /// <para> /// The name of the Amazon Redshift event notification subscription. /// </para> /// </summary> public string CustSubscriptionId { get { return this._custSubscriptionId; } set { this._custSubscriptionId = value; } } // Check to see if CustSubscriptionId property is set internal bool IsSetCustSubscriptionId() { return this._custSubscriptionId != null; } /// <summary> /// Gets and sets the property Enabled. /// <para> /// A boolean value indicating whether the subscription is enabled; <code>true</code> /// indicates that the subscription is enabled. /// </para> /// </summary> public bool Enabled { get { return this._enabled.GetValueOrDefault(); } set { this._enabled = value; } } // Check to see if Enabled property is set internal bool IsSetEnabled() { return this._enabled.HasValue; } /// <summary> /// Gets and sets the property EventCategoriesList. /// <para> /// The list of Amazon Redshift event categories specified in the event notification subscription. /// </para> /// /// <para> /// Values: Configuration, Management, Monitoring, Security /// </para> /// </summary> public List<string> EventCategoriesList { get { return this._eventCategoriesList; } set { this._eventCategoriesList = value; } } // Check to see if EventCategoriesList property is set internal bool IsSetEventCategoriesList() { return this._eventCategoriesList != null && this._eventCategoriesList.Count > 0; } /// <summary> /// Gets and sets the property Severity. /// <para> /// The event severity specified in the Amazon Redshift event notification subscription. /// </para> /// /// <para> /// Values: ERROR, INFO /// </para> /// </summary> public string Severity { get { return this._severity; } set { this._severity = value; } } // Check to see if Severity property is set internal bool IsSetSeverity() { return this._severity != null; } /// <summary> /// Gets and sets the property SnsTopicArn. /// <para> /// The Amazon Resource Name (ARN) of the Amazon SNS topic used by the event notification /// subscription. /// </para> /// </summary> public string SnsTopicArn { get { return this._snsTopicArn; } set { this._snsTopicArn = value; } } // Check to see if SnsTopicArn property is set internal bool IsSetSnsTopicArn() { return this._snsTopicArn != null; } /// <summary> /// Gets and sets the property SourceIdsList. /// <para> /// A list of the sources that publish events to the Amazon Redshift event notification /// subscription. /// </para> /// </summary> public List<string> SourceIdsList { get { return this._sourceIdsList; } set { this._sourceIdsList = value; } } // Check to see if SourceIdsList property is set internal bool IsSetSourceIdsList() { return this._sourceIdsList != null && this._sourceIdsList.Count > 0; } /// <summary> /// Gets and sets the property SourceType. /// <para> /// The source type of the events returned by the Amazon Redshift event notification, /// such as cluster, cluster-snapshot, cluster-parameter-group, cluster-security-group, /// or scheduled-action. /// </para> /// </summary> public string SourceType { get { return this._sourceType; } set { this._sourceType = value; } } // Check to see if SourceType property is set internal bool IsSetSourceType() { return this._sourceType != null; } /// <summary> /// Gets and sets the property Status. /// <para> /// The status of the Amazon Redshift event notification subscription. /// </para> /// /// <para> /// Constraints: /// </para> /// <ul> <li> /// <para> /// Can be one of the following: active | no-permission | topic-not-exist /// </para> /// </li> <li> /// <para> /// The status "no-permission" indicates that Amazon Redshift no longer has permission /// to post to the Amazon SNS topic. The status "topic-not-exist" indicates that the topic /// was deleted after the subscription was created. /// </para> /// </li> </ul> /// </summary> public string Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } /// <summary> /// Gets and sets the property SubscriptionCreationTime. /// <para> /// The date and time the Amazon Redshift event notification subscription was created. /// </para> /// </summary> public DateTime SubscriptionCreationTime { get { return this._subscriptionCreationTime.GetValueOrDefault(); } set { this._subscriptionCreationTime = value; } } // Check to see if SubscriptionCreationTime property is set internal bool IsSetSubscriptionCreationTime() { return this._subscriptionCreationTime.HasValue; } /// <summary> /// Gets and sets the property Tags. /// <para> /// The list of tags for the event subscription. /// </para> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } } }
31.813869
106
0.562808
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/Redshift/Generated/Model/EventSubscription.cs
8,717
C#
namespace DataFlow.EdFi.Models.EnrollmentComposite { public class School_educationOrganizationInternationalAddress { /// <summary> /// Key for Address /// </summary> public string addressType { get; set; } /// <summary> /// The first line of the address. /// </summary> public string addressLine1 { get; set; } /// <summary> /// The second line of the address. /// </summary> public string addressLine2 { get; set; } /// <summary> /// The third line of the address. /// </summary> public string addressLine3 { get; set; } /// <summary> /// The fourth line of the address. /// </summary> public string addressLine4 { get; set; } /// <summary> /// A unique identifier used as Primary Key, not derived from business logic, when acting as Foreign Key, references the parent table. /// </summary> public string countryDescriptor { get; set; } } }
27.868421
142
0.557129
[ "Apache-2.0" ]
schoolstacks/dataflow
DataFlow.EdFi/Models/EnrollmentComposite/School_educationOrganizationInternationalAddress.cs
1,059
C#
using PointyStickBlend.Models; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PointyStickBlend.ViewModels { public class LibraryViewModel : INotifyPropertyChanged { private LibraryModel model; public LibraryModel Model { get { return model; } set { model = value; } } public LibraryViewModel() { model = new LibraryModel(); } #region INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(String info) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(info)); } } #endregion } }
23.3
75
0.590129
[ "Apache-2.0" ]
stkerr/PointyStick
PointyStickBlend/PointyStickBlend/ViewModels/LibraryViewModel.cs
934
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class AnalogActor : MonoBehaviour { RectTransform rectTramsform; public float Deslocaton = 20f; public Vector3 InitialPosition; public float speed=10f; public Vector3 initialScale; public Vector3 ScaleSmear = new Vector3(1.5f, 0.7f, 0f); Vector3 oldPosition; public float _MaxVelocitySmear = 0.2f; public float MinvelocitySmear; //public float MaxXScale; // Use this for initialization void Start () { rectTramsform = GetComponent<RectTransform>(); InitialPosition = rectTramsform.anchoredPosition3D; initialScale = rectTramsform.localScale; } // Update is called once per frame void Update () { float x = Input.GetAxis("Horizontal"); float y = Input.GetAxis("Vertical"); if (x > 0.05f) x = 1; if (x < -0.05f) x = -1; if (y > 0.05f) y = 1f; if (y < -0.05f) y = -1f; rectTramsform.anchoredPosition3D = Vector3.Lerp(rectTramsform.anchoredPosition3D,(InitialPosition + (new Vector3(x * Deslocaton, y * Deslocaton, 0f))), speed * Time.deltaTime); Vector3 diff = transform.position - oldPosition; //print(diff.magnitude); if (diff.magnitude > 0.001f) { float factor = Mathf.Clamp(diff.magnitude / _MaxVelocitySmear, 0f, 1f); transform.localScale = Vector3.Lerp(transform.localScale, Vector3.Lerp(initialScale, ScaleSmear, factor),speed*Time.deltaTime); // print("diff magni" + diff.magnitude); transform.rotation = Quaternion.FromToRotation(Vector3.right, new Vector3(diff.x, diff.y, 0f).normalized); } else { transform.rotation = Quaternion.identity; transform.localScale = initialScale; } oldPosition = transform.position; } }
34.350877
184
0.636874
[ "MIT" ]
RabbitWhite/UNITY_AIS
UNITY_AIS/Assets/plugins/LeoLuz/Virtual Plug and Play Joystick/Scripts/AnalogActor.cs
1,960
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. using System; using System.ComponentModel.Composition; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.ExternalAccess.Razor; using Microsoft.CodeAnalysis.Razor.Workspaces; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.LanguageServer.ContainedLanguage; using Microsoft.VisualStudio.LanguageServerClient.Razor.HtmlCSharp; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Utilities; using CodeAnalysisWorkspace = Microsoft.CodeAnalysis.Workspace; namespace Microsoft.VisualStudio.LanguageServerClient.Razor { [Export(typeof(LSPDocumentChangeListener))] [ContentType(RazorLSPConstants.RazorLSPContentTypeName)] internal class CSharpVirtualDocumentPublisher : LSPDocumentChangeListener { private readonly RazorDynamicFileInfoProvider _dynamicFileInfoProvider; private readonly LSPDocumentMappingProvider _lspDocumentMappingProvider; [ImportingConstructor] public CSharpVirtualDocumentPublisher(RazorDynamicFileInfoProvider dynamicFileInfoProvider!!, LSPDocumentMappingProvider lspDocumentMappingProvider!!) { _dynamicFileInfoProvider = dynamicFileInfoProvider; _lspDocumentMappingProvider = lspDocumentMappingProvider; } // Internal for testing public override void Changed(LSPDocumentSnapshot old, LSPDocumentSnapshot @new, VirtualDocumentSnapshot virtualOld, VirtualDocumentSnapshot virtualNew, LSPDocumentChangeKind kind) { // We need the below check to address a race condition between when a request is sent to the C# server // for a generated document and when the C# server receives a document/didOpen notification. This race // condition may occur when the Razor server finishes initializing before C# receives and processes the // document open request. // This workaround adds the Razor client name to the generated document so the C# server will recognize // it, despite the document not being formally opened. Note this is meant to only be a temporary // workaround until a longer-term solution is implemented in the future. if (kind == LSPDocumentChangeKind.Added && _dynamicFileInfoProvider is DefaultRazorDynamicFileInfoProvider defaultProvider) { defaultProvider.PromoteBackgroundDocument(@new.Uri, CSharpDocumentPropertiesService.Instance); } if (kind != LSPDocumentChangeKind.VirtualDocumentChanged) { return; } if (virtualNew is CSharpVirtualDocumentSnapshot) { var csharpContainer = new CSharpVirtualDocumentContainer(_lspDocumentMappingProvider, @new, virtualNew.Snapshot); _dynamicFileInfoProvider.UpdateLSPFileInfo(@new.Uri, csharpContainer); } } private class CSharpVirtualDocumentContainer : DynamicDocumentContainer { private readonly ITextSnapshot _textSnapshot; private readonly LSPDocumentMappingProvider _lspDocumentMappingProvider; private readonly LSPDocumentSnapshot _documentSnapshot; private IRazorSpanMappingService? _mappingService; private IRazorDocumentExcerptServiceImplementation? _excerptService; public override string FilePath => _documentSnapshot.Uri.LocalPath; public override bool SupportsDiagnostics => true; public CSharpVirtualDocumentContainer(LSPDocumentMappingProvider lspDocumentMappingProvider!!, LSPDocumentSnapshot documentSnapshot!!, ITextSnapshot textSnapshot!!) { _lspDocumentMappingProvider = lspDocumentMappingProvider; _textSnapshot = textSnapshot; _documentSnapshot = documentSnapshot; } public override IRazorDocumentExcerptServiceImplementation GetExcerptService() { if (_excerptService is null) { var mappingService = GetMappingService(); _excerptService = new CSharpDocumentExcerptService(mappingService, _documentSnapshot); } return _excerptService; } public override IRazorSpanMappingService GetMappingService() { if (_mappingService is null) { _mappingService = new RazorLSPSpanMappingService(_lspDocumentMappingProvider, _documentSnapshot, _textSnapshot); } return _mappingService; } public override IRazorDocumentPropertiesService GetDocumentPropertiesService() { return CSharpDocumentPropertiesService.Instance; } public override TextLoader GetTextLoader(string filePath) { var sourceText = _textSnapshot.AsText(); var textLoader = new SourceTextLoader(sourceText, filePath); return textLoader; } private sealed class SourceTextLoader : TextLoader { private readonly SourceText _sourceText; private readonly string _filePath; public SourceTextLoader(SourceText sourceText!!, string filePath!!) { _sourceText = sourceText; _filePath = filePath; } public override Task<TextAndVersion> LoadTextAndVersionAsync(CodeAnalysisWorkspace workspace, DocumentId documentId, CancellationToken cancellationToken) { return Task.FromResult(TextAndVersion.Create(_sourceText, VersionStamp.Default, _filePath)); } } } } }
45.383459
187
0.681743
[ "MIT" ]
adrianwright109/razor-tooling
src/Razor/src/Microsoft.VisualStudio.LanguageServerClient.Razor/CSharpVirtualDocumentPublisher.cs
6,038
C#
using System.Collections.Generic; namespace Shared.Messages { public class CalculateFormulaRequest { public int TimeoutSeconds { get; set; } public string Formula { get; set; } public IEnumerable<FormulaRequestType> Data { get; set; } } }
25.090909
65
0.67029
[ "MIT" ]
ctrmcubed/TradeCube-Services
src/Shared/Messages/CalculateFormulaRequest.cs
278
C#
#if !WATCH using System; using Foundation; using ObjCRuntime; using System.Runtime.Versioning; namespace AVFoundation { public partial class AVPlayerItem { #if NET [SupportedOSPlatform ("tvos11.0")] [SupportedOSPlatform ("macos10.13")] [SupportedOSPlatform ("ios11.0")] #else [TV (11, 0)] [NoWatch] [Mac (10, 13)] [iOS (11, 0)] #endif public AVVideoApertureMode VideoApertureMode { get { return AVVideoApertureModeExtensions.GetValue (_VideoApertureMode); } set { _VideoApertureMode = value.GetConstant (); } } } } #endif
18.433333
78
0.712477
[ "BSD-3-Clause" ]
NormanChiflen/xamarin-all-IOS
src/AVFoundation/AVPlayerItem.cs
553
C#
namespace Swifter.Test.WPF.Serializers { public sealed class Utf8JsonSerializer : BaseSerializer<byte[]> { public override TObject Deserialize<TObject>(byte[] symbols) { return Utf8Json.JsonSerializer.Deserialize<TObject>(symbols); } public override byte[] Serialize<TObject>(TObject obj) { return Utf8Json.JsonSerializer.Serialize(obj); } } }
26.875
73
0.637209
[ "MIT" ]
Dogwei/Swifter.Json
Swifter.Test.WPF/Serializers/Utf8JsonSerializer.cs
432
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("_02_Simple_Calculator")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("_02_Simple_Calculator")] [assembly: AssemblyCopyright("Copyright © Microsoft 2017")] [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("f4ff4068-641a-4ef4-897e-ac42b3599276")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.72973
84
0.75157
[ "MIT" ]
NadiaKaradjova/SoftUni
C# Advanced/Stacks and Queues/02 Simple Calculator/Properties/AssemblyInfo.cs
1,436
C#
using System; namespace _04._Fold_and_Sum { class Program { static void Main() { int partySize = int.Parse(Console.ReadLine()); int days = int.Parse(Console.ReadLine()); } } }
15
58
0.529167
[ "MIT" ]
dMundov/SoftUni-HomeWorks
CSharp-TechFundamentals/08.Arrays - More Exercise/04. Fold and Sum/Program.cs
242
C#
 // IFile.cs // Copyright (c) 2014+ by Michael Penner. All rights reserved. using System.Text; namespace Eamon.Framework.Portability { /// <summary></summary> public interface IFile { /// <summary></summary> /// <param name="path"></param> /// <returns></returns> bool Exists(string path); /// <summary></summary> /// <param name="path"></param> void Delete(string path); /// <summary></summary> /// <param name="sourceFileName"></param> /// <param name="destFileName"></param> /// <param name="overwrite"></param> void Copy(string sourceFileName, string destFileName, bool overwrite); /// <summary></summary> /// <param name="path"></param> /// <param name="encoding"></param> /// <returns></returns> string ReadFirstLine(string path, Encoding encoding = null); /// <summary></summary> /// <param name="path"></param> /// <param name="encoding"></param> /// <returns></returns> string ReadAllText(string path, Encoding encoding = null); /// <summary></summary> /// <param name="path"></param> /// <param name="contents"></param> /// <param name="encoding"></param> void WriteAllText(string path, string contents, Encoding encoding = null); /// <summary></summary> /// <param name="path"></param> /// <param name="contents"></param> /// <param name="encoding"></param> void AppendAllText(string path, string contents, Encoding encoding = null); } }
27.924528
78
0.614189
[ "MIT" ]
skyhoshi/Eamon-CS
System/Eamon/Framework/Portability/IFile.cs
1,430
C#