content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
sequence
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace BibleForum.Data.Migrations { public partial class NewPropertiesforPostReply : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<DateTime>( name: "EditedDate", table: "PostReplies", nullable: false, defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); migrationBuilder.AddColumn<bool>( name: "IsEdited", table: "PostReplies", nullable: false, defaultValue: false); migrationBuilder.AddColumn<int>( name: "VoteCount", table: "PostReplies", nullable: false, defaultValue: 0); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "EditedDate", table: "PostReplies"); migrationBuilder.DropColumn( name: "IsEdited", table: "PostReplies"); migrationBuilder.DropColumn( name: "VoteCount", table: "PostReplies"); } } }
29.76087
91
0.543462
[ "Apache-2.0" ]
kelvincrtz/BibleForum
BibleForumSolution/BibleForum.Data/Migrations/20181126222413_New Properties for Post Reply.cs
1,371
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the eventbridge-2015-10-07.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.EventBridge.Model { /// <summary> /// Container for the parameters to the ActivateEventSource operation. /// Activates a partner event source that has been deactivated. Once activated, your matching /// event bus will start receiving events from the event source. /// </summary> public partial class ActivateEventSourceRequest : AmazonEventBridgeRequest { private string _name; /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the partner event source to activate. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=256)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } } }
31.616667
110
0.640485
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/EventBridge/Generated/Model/ActivateEventSourceRequest.cs
1,897
C#
using Xunit; namespace _860_LemonadeChange { class Program { static void Main(string[] args) { var solution = new Solution(); Assert.True(solution.LemonadeChange(new[] { 5, 5, 5, 10, 20 })); Assert.True(solution.LemonadeChange(new[] { 5, 5, 10 })); Assert.False(solution.LemonadeChange(new[] { 10, 10 })); Assert.False(solution.LemonadeChange(new[] { 5, 5, 10, 10, 20 })); } } }
26.555556
78
0.546025
[ "MIT" ]
kodoftw/LeetCode
LeetCode/860-LemonadeChange/Program.cs
480
C#
// This file was automatically generated and may be regenerated at any // time. To ensure any changes are retained, modify the tool with any segment/component/group/field name // or type changes. namespace Machete.HL7Schema.V26 { using HL7; /// <summary> /// OSR_Q06_PATIENT (Group) - /// </summary> public interface OSR_Q06_PATIENT : HL7V26Layout { /// <summary> /// PID /// </summary> Segment<PID> PID { get; } /// <summary> /// NTE /// </summary> SegmentList<NTE> NTE { get; } } }
24.416667
104
0.571672
[ "Apache-2.0" ]
ahives/Machete
src/Machete.HL7Schema/V26/Groups/OSR_Q06_PATIENT.cs
586
C#
using System; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.TestingHost; using TestExtensions; using UnitTests.GrainInterfaces; using UnitTests.Grains; using Xunit; using System.Collections.Generic; using System.Linq; namespace UnitTests.General { [TestCategory("DI")] public class DependencyInjectionGrainTests : OrleansTestingBase, IClassFixture<DependencyInjectionGrainTests.Fixture> { private readonly Fixture fixture; public class Fixture : BaseTestClusterFixture { protected override TestCluster CreateTestCluster() { var options = new TestClusterOptions(1); options.ClusterConfiguration.UseStartupType<TestStartup>(); return new TestCluster(options); } } public DependencyInjectionGrainTests(Fixture fixture) { this.fixture = fixture; } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task CanGetGrainWithInjectedDependencies() { IDIGrainWithInjectedServices grain = this.fixture.GrainFactory.GetGrain<IDIGrainWithInjectedServices>(GetRandomGrainId()); long ignored = await grain.GetLongValue(); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task CanGetGrainWithInjectedGrainFactory() { // please don't inject your implemetation of IGrainFactory to DI container in Startup Class, // since we are currently not supporting replacing IGrainFactory IDIGrainWithInjectedServices grain = this.fixture.GrainFactory.GetGrain<IDIGrainWithInjectedServices>(GetRandomGrainId()); long ignored = await grain.GetGrainFactoryId(); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task CanResolveSingletonDependencies() { var grain1 = this.fixture.GrainFactory.GetGrain<IDIGrainWithInjectedServices>(GetRandomGrainId()); var grain2 = this.fixture.GrainFactory.GetGrain<IDIGrainWithInjectedServices>(GetRandomGrainId()); // the injected service will return the same value only if it's the same instance Assert.Equal( await grain1.GetInjectedSingletonServiceValue(), await grain2.GetInjectedSingletonServiceValue()); await grain1.DoDeactivate(); await grain2.DoDeactivate(); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task CanResolveScopedDependencies() { var grain1 = this.fixture.GrainFactory.GetGrain<IDIGrainWithInjectedServices>(GetRandomGrainId()); var grain2 = this.fixture.GrainFactory.GetGrain<IDIGrainWithInjectedServices>(GetRandomGrainId()); // the injected service will only return a different value if it's a different instance Assert.NotEqual( await grain1.GetInjectedScopedServiceValue(), await grain2.GetInjectedScopedServiceValue()); await grain1.DoDeactivate(); await grain2.DoDeactivate(); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task CanResolveScopedGrainActivationContext() { long id1 = GetRandomGrainId(); long id2 = GetRandomGrainId(); var grain1 = this.fixture.GrainFactory.GetGrain<IDIGrainWithInjectedServices>(id1); var grain2 = this.fixture.GrainFactory.GetGrain<IDIGrainWithInjectedServices>(id2); // the injected service will only return a different value if it's a different instance Assert.Contains(id1.ToString(), await grain1.GetStringValue()); Assert.Contains(id2.ToString(), await grain2.GetStringValue()); await grain1.DoDeactivate(); await grain2.DoDeactivate(); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task ScopedDependenciesAreThreadSafe() { const int parallelCalls = 10; var grain1 = this.fixture.GrainFactory.GetGrain<IDIGrainWithInjectedServices>(GetRandomGrainId()); var calls = Enumerable.Range(0, parallelCalls) .Select(i => grain1.GetInjectedScopedServiceValue()) .ToList(); await Task.WhenAll(calls); string expected = calls[0].Result; foreach (var value in calls.Select(x => x.Result)) { Assert.Equal(expected, value); } await grain1.DoDeactivate(); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task CanResolveSameDependenciesViaServiceProvider() { var grain1 = this.fixture.GrainFactory.GetGrain<IDIGrainWithInjectedServices>(GetRandomGrainId()); var grain2 = this.fixture.GrainFactory.GetGrain<IDIGrainWithInjectedServices>(GetRandomGrainId()); await grain1.AssertCanResolveSameServiceInstances(); await grain2.AssertCanResolveSameServiceInstances(); await grain1.DoDeactivate(); await grain2.DoDeactivate(); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task CanResolveSingletonGrainFactory() { var grain1 = this.fixture.GrainFactory.GetGrain<IDIGrainWithInjectedServices>(GetRandomGrainId()); var grain2 = this.fixture.GrainFactory.GetGrain<IDIGrainWithInjectedServices>(GetRandomGrainId()); // the injected grain factory will return the same value only if it's the same instance, Assert.Equal( await grain1.GetGrainFactoryId(), await grain2.GetGrainFactoryId()); } [Fact, TestCategory("BVT"), TestCategory("Functional")] public async Task CannotGetExplictlyRegisteredGrain() { ISimpleDIGrain grain = this.fixture.GrainFactory.GetGrain<ISimpleDIGrain>(GetRandomGrainId(), grainClassNamePrefix: "UnitTests.Grains.ExplicitlyRegistered"); var exception = await Assert.ThrowsAsync<OrleansException>(() => grain.GetLongValue()); Assert.Contains("Error creating activation for", exception.Message); Assert.Contains(nameof(ExplicitlyRegisteredSimpleDIGrain), exception.Message); } public class TestStartup { public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddSingleton<IInjectedService, InjectedService>(); services.AddScoped<IInjectedScopedService, InjectedScopedService>(); // explicitly register a grain class to assert that it will NOT use the registration, // as by design this is not supported. services.AddTransient<ExplicitlyRegisteredSimpleDIGrain>( sp => new ExplicitlyRegisteredSimpleDIGrain( sp.GetRequiredService<IInjectedService>(), "some value", 5)); return services.BuildServiceProvider(); } } } }
42.786127
169
0.651446
[ "MIT" ]
berdon/orleans
test/Tester/DependencyInjectionGrainTests.cs
7,402
C#
using Amazon.JSII.Runtime.Deputy; using Amazon.JSII.Tests.Calculator.Lib; namespace Amazon.JSII.Tests.Calculator { [JsiiClass(typeof(GiveMeStructs), "jsii-calc.GiveMeStructs", "[]")] public class GiveMeStructs : DeputyBase { public GiveMeStructs(): base(new DeputyProps(new object[]{})) { } protected GiveMeStructs(ByRefValue reference): base(reference) { } protected GiveMeStructs(DeputyProps props): base(props) { } [JsiiProperty("structLiteral", "{\"fqn\":\"@scope/jsii-calc-lib.StructWithOnlyOptionals\"}")] public virtual IStructWithOnlyOptionals StructLiteral { get => GetInstanceProperty<IStructWithOnlyOptionals>(); } /// <summary>Returns the "anumber" from a MyFirstStruct struct;</summary> [JsiiMethod("readFirstNumber", "{\"primitive\":\"number\"}", "[{\"name\":\"first\",\"type\":{\"fqn\":\"@scope/jsii-calc-lib.MyFirstStruct\"}}]")] public virtual double ReadFirstNumber(IMyFirstStruct first) { return InvokeInstanceMethod<double>(new object[]{first}); } /// <summary>Returns the boolean from a DerivedStruct struct.</summary> [JsiiMethod("readDerivedNonPrimitive", "{\"fqn\":\"jsii-calc.DoubleTrouble\"}", "[{\"name\":\"derived\",\"type\":{\"fqn\":\"jsii-calc.DerivedStruct\"}}]")] public virtual DoubleTrouble ReadDerivedNonPrimitive(IDerivedStruct derived) { return InvokeInstanceMethod<DoubleTrouble>(new object[]{derived}); } /// <summary>Accepts a struct of type DerivedStruct and returns a struct of type FirstStruct.</summary> [JsiiMethod("derivedToFirst", "{\"fqn\":\"@scope/jsii-calc-lib.MyFirstStruct\"}", "[{\"name\":\"derived\",\"type\":{\"fqn\":\"jsii-calc.DerivedStruct\"}}]")] public virtual IMyFirstStruct DerivedToFirst(IDerivedStruct derived) { return InvokeInstanceMethod<IMyFirstStruct>(new object[]{derived}); } } }
42.604167
165
0.63423
[ "Apache-2.0" ]
mindstorms6/jsii
packages/jsii-pacmak/test/expected.jsii-calc/dotnet/Amazon.JSII.Tests.Calculator/GiveMeStructs.cs
2,045
C#
// Copyright 2007-2008 The Apache Software Foundation. // // 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. namespace MassTransit.Services.Subscriptions { using System; using Internal; using Util; public class LocalSubscriptionService : ISubscriptionService { private RegistrationList<IEndpointSubscriptionEvent> _clients = new RegistrationList<IEndpointSubscriptionEvent>(); public UnsubscribeAction SubscribedTo<T>(Uri endpointUri) where T : class { UnsubscribeAction result = () => false; _clients.Each(x => { result += x.SubscribedTo<T>(endpointUri); }); return result; } public UnsubscribeAction SubscribedTo<T, K>(K correlationId, Uri endpointUri) where T : class, CorrelatedBy<K> { UnsubscribeAction result = () => false; _clients.Each(x => { result += x.SubscribedTo<T,K>(correlationId, endpointUri); }); return result; } public UnregisterAction Register(IEndpointSubscriptionEvent consumer) { return _clients.Register(consumer); } } }
29.962264
118
0.703401
[ "Apache-2.0" ]
DavidChristiansen/MassTransit
src/MassTransit/Services/Subscriptions/LocalSubscriptionService.cs
1,588
C#
using System; namespace DontPanic.API.Areas.HelpPage { /// <summary> /// This represents a preformatted text sample on the help page. There's a display template named TextSample associated with this class. /// </summary> public class TextSample { public TextSample(string text) { if (text == null) { throw new ArgumentNullException("text"); } Text = text; } public string Text { get; private set; } public override bool Equals(object obj) { TextSample other = obj as TextSample; return other != null && Text == other.Text; } public override int GetHashCode() { return Text.GetHashCode(); } public override string ToString() { return Text; } } }
24.027027
140
0.533183
[ "MIT" ]
andy-c-jones/event-app-backend
DontPanic/DontPanic.API/Areas/HelpPage/SampleGeneration/TextSample.cs
889
C#
using System.Linq; using System.Threading.Tasks; using Bedrock.DomainBuilder.EntityFramework; using Bedrock.DomainBuilder.Enumerations; namespace Bedrock.DomainBuilder.Builder { public class BuilderEnumeration : BuilderBase, IBuilder { #region Protected Methods protected override async Task<int> BuildInternal(BuildSettings settings) { var filesToCreate = EntityHelper.EntityTypes.Where(e => Enums.Contains(e.Name)); BuilderFileCountUpdate(filesToCreate.Count()); await Pause.WaitWhilePausedAsync(); foreach (var file in filesToCreate) { var filePath = string.Concat(settings.EnumerationPath, file.Name, settings.FileExtension); await BuildFile<eBuildSectionEnumeration>(filePath, file, settings); await Pause.WaitWhilePausedAsync(); if (Cancellation.IsCancellationRequested) break; } return filesToCreate.Count(); } #endregion } }
30.314286
106
0.64656
[ "MIT" ]
BedrockNet/Bedrock.DomainBuilder
Bedrock.DomainBuilder/Builder/BuilderEnumeration.cs
1,063
C#
using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Baskerville.Data.Contracts.Repository { public interface IDbContext { IDbSet<TEntity> Set<TEntity>() where TEntity : class; int SaveChanges(); } }
19.411765
61
0.721212
[ "Apache-2.0" ]
MarioZisov/Baskerville
BaskervilleWebsite/Baskerville.Data/Repository/Contracts/IDbContext.cs
332
C#
using UnityEngine; using System.Collections.Generic; using System; public enum AttrTraitName{ strPlus, intPlus, speedPlus, maxHPPlus, pDefPlus, mDefPlus, mvRangePlus, strPluspDefMinus, strPlusmDefMinus, strPlusHPMinus, intPlusmDefMinus, intPluspDefMinus, intPlusHPMinus, speedPlusHPMinus, speedPlusDefMinus, pDefPlusSpeedMinus, pDefPlusDmgMinus, mDefPlusSpeedMinus, mDefPlusDmgMinus, healingPlus, } public enum SpecTraitName{ swordPlus, bowPlus, axePlus, staffPlus, humanSlayer, lizardSlayer, chameleonSlayer, snakeSlayer, dragonSlayer, icePlus, firePlus, lightningPlus, elementPlus, expGainPlus, } public enum UniqueTraitName{ brodric, sisdric } [System.Serializable] public class Trait { [System.Serializable] public class TraitAttr { public float strength = 0; public float intelligence = 0; public float speed = 0; public float maxHealth = 0; public float physicalDefense = 0; public float magicDefense = 0; public int moveRange = 0; public float healingMultiplier = 0; } [System.Serializable] public class TraitSpec { public static List<Weapon.EquipmentClass> equips = new List<Weapon.EquipmentClass>((IEnumerable<Weapon.EquipmentClass>)Enum.GetValues(typeof(Weapon.EquipmentClass))); public static List<EnemyType> enemies = new List<EnemyType>((IEnumerable<EnemyType>)Enum.GetValues(typeof(EnemyType))); public static List<DamageElement> elements = new List<DamageElement>((IEnumerable<DamageElement>)Enum.GetValues(typeof(DamageElement))); public float expGain = 0; public Dictionary<Weapon.EquipmentClass, float> wepSpec = new Dictionary<Weapon.EquipmentClass, float>(); public Dictionary<EnemyType, float> enemySpec = new Dictionary<EnemyType, float>(); public Dictionary<DamageElement, float> elementSpec = new Dictionary<DamageElement, float>(); public TraitSpec() { foreach (Weapon.EquipmentClass e in equips) { wepSpec[e] = 0; } foreach (EnemyType e in enemies) { enemySpec[e] = 0; } foreach (DamageElement e in elements) { elementSpec[e] = 0; } } } public string name; public string description; public TraitAttr attr = new TraitAttr(); public TraitSpec spec = new TraitSpec(); public Trait(string name = "") { this.name = name; } public static Trait operator+(Trait a1, Trait a2) { Trait ret = new Trait(); ret.attr.strength = a1.attr.strength + a2.attr.strength; ret.attr.intelligence = a1.attr.intelligence + a2.attr.intelligence; ret.attr.speed = a1.attr.speed + a2.attr.speed; ret.attr.maxHealth = a1.attr.maxHealth + a2.attr.maxHealth; ret.attr.physicalDefense = a1.attr.physicalDefense + a2.attr.physicalDefense; ret.attr.magicDefense = a1.attr.magicDefense + a2.attr.magicDefense; ret.attr.moveRange = a1.attr.moveRange + a2.attr.moveRange; ret.attr.healingMultiplier = a1.attr.healingMultiplier + a2.attr.healingMultiplier; ret.spec.expGain = a1.spec.expGain + a2.spec.expGain; foreach (var e in TraitSpec.equips) { ret.spec.wepSpec[e] = a1.spec.wepSpec[e] + a2.spec.wepSpec[e]; } foreach (var e in TraitSpec.enemies) { ret.spec.enemySpec[e] = a1.spec.enemySpec[e] + a2.spec.enemySpec[e]; } foreach (var e in TraitSpec.elements) { ret.spec.elementSpec[e] = a1.spec.elementSpec[e] + a2.spec.elementSpec[e]; } return ret; } public Attributes applyTrait(Attributes baseAttr) { Attributes ret = baseAttr.clone(); ret.strength += (int)(ret.strength * attr.strength); ret.intelligence += (int)(ret.intelligence * attr.intelligence); ret.speed += (int)(ret.speed * attr.speed); ret.maxHealth += (int)(ret.maxHealth * attr.maxHealth); ret.physicalDefense += (int)(ret.physicalDefense * attr.physicalDefense); ret.magicDefense += (int)(ret.magicDefense * attr.magicDefense); ret.moveRange += attr.moveRange; ret.healingMultiplier += attr.healingMultiplier; return ret; } }
35.324561
170
0.711448
[ "MIT" ]
Fellowship-of-the-Bus/Draconia-Unity
Assets/Script/Character/Trait.cs
4,027
C#
using System; using System.Collections.Generic; namespace PnP.Core.Transformation.SharePoint.KQL { /// <summary> /// Class to parse KQL queries /// </summary> public class KQLParser { /// <summary> /// Parses a KQL query and returns a list of tokens /// </summary> /// <param name="searchQuery">Query to parse</param> /// <returns>List of <see cref="KQLElement"/> tokens</returns> public List<KQLElement> Parse(string searchQuery) { // See https://docs.microsoft.com/en-us/sharepoint/dev/general-development/keyword-query-language-kql-syntax-reference List<KQLElement> parsedQuery = new List<KQLElement>(10); try { if (string.IsNullOrEmpty(searchQuery)) { return parsedQuery; } var parts = searchQuery.Trim().Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries); int group = 0; bool groupOpen = false; bool groupToClose = false; for (int i = 0; i < parts.Length; i++) { var part = parts[i]; if (!groupOpen && part.StartsWith("(")) { group = group + 1; groupOpen = true; // Strip the ( part = part.Substring(1); } if (groupOpen && part.EndsWith(")")) { groupToClose = true; // Strip the ) part = part.TrimEnd(new char[] { ')' }); } KQLPropertyOperator op = DetectOperator(part); if (op != KQLPropertyOperator.Undefined) { string opAsString = OperatorToString(op); KQLElement k = new KQLElement() { Type = KQLFilterType.PropertyFilter, Operator = op, Group = groupOpen ? group : 0, Filter = part.Substring(0, part.IndexOf(opAsString)), Value = part.Substring(part.IndexOf(opAsString) + opAsString.Length) }; parsedQuery.Add(k); } else if (part.StartsWith("{") && part.EndsWith("}")) { KQLElement k = new KQLElement() { Type = KQLFilterType.KeywordFilter, Operator = KQLPropertyOperator.Undefined, Group = groupOpen ? group : 0, Filter = part.Replace("{", "").Replace("}", ""), Value = "", }; parsedQuery.Add(k); } else { if (part.Equals("OR", StringComparison.InvariantCultureIgnoreCase) || part.Equals("AND", StringComparison.InvariantCultureIgnoreCase) || part.Equals("NEAR", StringComparison.InvariantCultureIgnoreCase) || part.StartsWith("NEAR(", StringComparison.InvariantCultureIgnoreCase) || part.Equals("ONENEAR", StringComparison.InvariantCultureIgnoreCase) || part.StartsWith("ONENEAR(", StringComparison.InvariantCultureIgnoreCase) || part.StartsWith("XRANK(", StringComparison.InvariantCultureIgnoreCase) || part.Equals("NOT", StringComparison.InvariantCultureIgnoreCase)) { // Don't add operators as KQL elements } else { KQLElement k = new KQLElement() { Type = KQLFilterType.Text, Operator = KQLPropertyOperator.Undefined, Group = groupOpen ? group : 0, Filter = "", Value = part, }; parsedQuery.Add(k); } } if (groupToClose) { groupOpen = false; groupToClose = false; } } } catch(Exception) { // Eat exceptions for now, KQL query parsing will be obsolete when the AdvancedQuery option becomes available } return parsedQuery; } #region Helper methods private string OperatorToString(KQLPropertyOperator ops) { switch (ops) { case KQLPropertyOperator.DoesNoEqual: return "<>"; case KQLPropertyOperator.EqualTo: return "="; case KQLPropertyOperator.GreaterThanOrEqualTo: return ">="; case KQLPropertyOperator.GreaterThan: return ">"; case KQLPropertyOperator.LesserThan: return "<"; case KQLPropertyOperator.LesserThanOrEqualTo: return "<="; case KQLPropertyOperator.Matches: return ":"; case KQLPropertyOperator.Restriction: return ".."; } return ""; } private KQLPropertyOperator DetectOperator(string part) { if (part.Contains(">=")) { return KQLPropertyOperator.GreaterThanOrEqualTo; } else if (part.Contains("<=")) { return KQLPropertyOperator.LesserThanOrEqualTo; } else if (part.Contains("<>")) { return KQLPropertyOperator.DoesNoEqual; } else if (part.Contains("..")) { return KQLPropertyOperator.Restriction; } else if (part.Contains(">")) { return KQLPropertyOperator.GreaterThan; } else if (part.Contains("<")) { return KQLPropertyOperator.LesserThan; } else if (part.Contains("=")) { return KQLPropertyOperator.EqualTo; } else if (part.Contains(":")) { return KQLPropertyOperator.Matches; } else { return KQLPropertyOperator.Undefined; } } #endregion } }
38.032787
130
0.436351
[ "MIT" ]
PaoloPia/pnpcore
src/sdk/PnP.Core.Transformation.SharePoint/Utilities/KQL/KQLParser.cs
6,962
C#
using System; using System.Collections.Generic; using System.Net.Http; using System.Text; using YouGe.Core.Commons.Helper; using YouGe.Core.Commons.SystemConst; using YouGe.Core.Commons; using System.Threading.Tasks; using Newtonsoft.Json.Linq; using Newtonsoft.Json; namespace YouGe.Core.Common.Helper { public class IPAddressHelper { // IP地址查询 public static readonly string IP_URL = "http://whois.pconline.com.cn/ipJson.jsp"; // 未知地址 public static readonly string UNKNOWN = "XX XX"; public static async Task<string> getRealAddressByIP(string ip) { string address = UNKNOWN; // 内网不查询 if (IpUtils.internalIp(ip)) { return "内网IP"; } try { HttpClient client = new HttpClient(); Dictionary<string, string> parmas = new Dictionary<string, string>(); parmas.Add("ip",ip); parmas.Add("json", "true"); string rspStr = await client.GetJsonAsync(parmas, IP_URL); if (string.IsNullOrEmpty(rspStr)) { Log4NetHelper.Info(string.Format("获取地理位置异常 {0}", ip)); return UNKNOWN; } JObject obj = (JObject)JsonConvert.DeserializeObject(rspStr); string region = obj["pro"].ToString(); string city = obj["city"].ToString(); return string.Format("{0} {1}", region, city); } catch (Exception e) { Log4NetHelper.Info(string.Format("获取地理位置异常 {0} {1}", ip,e.Message)); } return address; } } }
30.606557
88
0.506695
[ "MIT" ]
chenqiangdage/YouGe.Core
YouGe.Core.Common/Helper/IPAddressHelper.cs
1,931
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.Diagnostics; using System.Linq; using System.Reflection; using System.Threading; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Utilities; namespace Microsoft.EntityFrameworkCore.Metadata.Internal { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public abstract class TypeBase : ConventionAnnotatable, IMutableTypeBase, IConventionTypeBase { private ConfigurationSource _configurationSource; private readonly Dictionary<string, ConfigurationSource> _ignoredMembers = new Dictionary<string, ConfigurationSource>(StringComparer.Ordinal); private Dictionary<string, PropertyInfo> _runtimeProperties; private Dictionary<string, FieldInfo> _runtimeFields; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected TypeBase([NotNull] string name, [NotNull] Model model, ConfigurationSource configurationSource) : this(model, configurationSource) { Check.NotEmpty(name, nameof(name)); Check.NotNull(model, nameof(model)); Name = name; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected TypeBase([NotNull] Type clrType, [NotNull] Model model, ConfigurationSource configurationSource) : this(model, configurationSource) { Check.NotNull(model, nameof(model)); Name = model.GetDisplayName(clrType); ClrType = clrType; } private TypeBase([NotNull] Model model, ConfigurationSource configurationSource) { Model = model; _configurationSource = configurationSource; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual Type ClrType { [DebuggerStepThrough] get; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual Model Model { [DebuggerStepThrough] get; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual string Name { [DebuggerStepThrough] get; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] public virtual ConfigurationSource GetConfigurationSource() => _configurationSource; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void UpdateConfigurationSource(ConfigurationSource configurationSource) => _configurationSource = configurationSource.Max(_configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IReadOnlyDictionary<string, PropertyInfo> GetRuntimeProperties() { if (ClrType == null) { return null; } if (_runtimeProperties == null) { var runtimeProperties = new Dictionary<string, PropertyInfo>(StringComparer.Ordinal); foreach (var property in ClrType.GetRuntimeProperties()) { if (!property.IsStatic() && !runtimeProperties.ContainsKey(property.Name)) { runtimeProperties[property.Name] = property; } } Interlocked.CompareExchange(ref _runtimeProperties, runtimeProperties, null); } return _runtimeProperties; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IReadOnlyDictionary<string, FieldInfo> GetRuntimeFields() { if (ClrType == null) { return null; } if (_runtimeFields == null) { var runtimeFields = new Dictionary<string, FieldInfo>(StringComparer.Ordinal); foreach (var field in ClrType.GetRuntimeFields()) { if (!field.IsStatic && !runtimeFields.ContainsKey(field.Name)) { runtimeFields[field.Name] = field; } } Interlocked.CompareExchange(ref _runtimeFields, runtimeFields, null); } return _runtimeFields; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void SetPropertyAccessMode( PropertyAccessMode? propertyAccessMode, ConfigurationSource configurationSource) => this.SetOrRemoveAnnotation(CoreAnnotationNames.PropertyAccessMode, propertyAccessMode, configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void SetNavigationAccessMode( PropertyAccessMode? propertyAccessMode, ConfigurationSource configurationSource) => this.SetOrRemoveAnnotation(CoreAnnotationNames.NavigationAccessMode, propertyAccessMode, configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void ClearCaches() { _runtimeProperties = null; _runtimeFields = null; Thread.MemoryBarrier(); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void AddIgnored([NotNull] string name, ConfigurationSource configurationSource) { Check.NotNull(name, nameof(name)); if (_ignoredMembers.TryGetValue(name, out var existingIgnoredConfigurationSource)) { _ignoredMembers[name] = configurationSource.Max(existingIgnoredConfigurationSource); return; } _ignoredMembers[name] = configurationSource; OnTypeMemberIgnored(name); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public abstract void OnTypeMemberIgnored([NotNull] string name); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IReadOnlyList<string> GetIgnoredMembers() => _ignoredMembers.Keys.ToList(); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual ConfigurationSource? FindDeclaredIgnoredConfigurationSource([NotNull] string name) => _ignoredMembers.TryGetValue(Check.NotEmpty(name, nameof(name)), out var ignoredConfigurationSource) ? (ConfigurationSource?)ignoredConfigurationSource : null; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual ConfigurationSource? FindIgnoredConfigurationSource(string name) => FindDeclaredIgnoredConfigurationSource(name); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool IsIgnored(string name) => FindIgnoredConfigurationSource(name) != null; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void RemoveIgnored(string name) { Check.NotNull(name, nameof(name)); _ignoredMembers.Remove(name); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> IModel ITypeBase.Model { [DebuggerStepThrough] get => Model; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> IMutableModel IMutableTypeBase.Model { [DebuggerStepThrough] get => Model; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> IConventionModel IConventionTypeBase.Model { [DebuggerStepThrough] get => Model; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> Type ITypeBase.ClrType { [DebuggerStepThrough] get => ClrType; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> void IMutableTypeBase.AddIgnored(string name) => AddIgnored(name, ConfigurationSource.Explicit); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> void IConventionTypeBase.AddIgnored(string name, bool fromDataAnnotation) => AddIgnored(name, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); } }
57.043478
125
0.659451
[ "Apache-2.0" ]
Pankraty/EntityFrameworkCore
src/EFCore/Metadata/Internal/TypeBase.cs
19,680
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fixatic.Types { public interface IDBConnector { public string GetCns(); } }
16
33
0.71875
[ "MIT" ]
Fjarik/Fixatic
src/Fixatic/Infrastructure/Fixatic.Types/IDBConnector.cs
226
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HypermediaAPI.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } } }
28.625
110
0.600873
[ "MIT" ]
ngiakhanh96/k8s-playground
HypermediaAPI/Controllers/WeatherForecastController.cs
1,147
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401 { using static Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Extensions; /// <summary>Lease Container request schema.</summary> public partial class LeaseContainerRequest { /// <summary> /// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json); /// <summary> /// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject" /// /> before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject container); /// <summary> /// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of /// the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> /// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return /// instantly.</param> partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json, ref bool returnNow); /// <summary> /// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the /// object before it is serialized. /// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.ILeaseContainerRequest. /// </summary> /// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns> /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.ILeaseContainerRequest. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190401.ILeaseContainerRequest FromJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode node) { return node is Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json ? new LeaseContainerRequest(json) : null; } /// <summary> /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject into a new instance of <see cref="LeaseContainerRequest" />. /// </summary> /// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject instance to deserialize from.</param> internal LeaseContainerRequest(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject json) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } {_action = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString>("action"), out var __jsonAction) ? (string)__jsonAction : (string)Action;} {_breakPeriod = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNumber>("breakPeriod"), out var __jsonBreakPeriod) ? (int?)__jsonBreakPeriod : BreakPeriod;} {_leaseDuration = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNumber>("leaseDuration"), out var __jsonLeaseDuration) ? (int?)__jsonLeaseDuration : LeaseDuration;} {_leaseId = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString>("leaseId"), out var __jsonLeaseId) ? (string)__jsonLeaseId : (string)LeaseId;} {_proposedLeaseId = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString>("proposedLeaseId"), out var __jsonProposedLeaseId) ? (string)__jsonProposedLeaseId : (string)ProposedLeaseId;} AfterFromJson(json); } /// <summary> /// Serializes this instance of <see cref="LeaseContainerRequest" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode" />. /// </summary> /// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="LeaseContainerRequest" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode" />. /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.SerializationMode serializationMode) { container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } AddIf( null != (((object)this._action)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString(this._action.ToString()) : null, "action" ,container.Add ); AddIf( null != this._breakPeriod ? (Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNumber((int)this._breakPeriod) : null, "breakPeriod" ,container.Add ); AddIf( null != this._leaseDuration ? (Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode)new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNumber((int)this._leaseDuration) : null, "leaseDuration" ,container.Add ); AddIf( null != (((object)this._leaseId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString(this._leaseId.ToString()) : null, "leaseId" ,container.Add ); AddIf( null != (((object)this._proposedLeaseId)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonString(this._proposedLeaseId.ToString()) : null, "proposedLeaseId" ,container.Add ); AfterToJson(ref container); return container; } } }
79.376147
295
0.699723
[ "MIT" ]
Arsasana/azure-powershell
src/Functions/generated/api/Models/Api20190401/LeaseContainerRequest.json.cs
8,544
C#
using System; using System.Collections.Generic; using System.Linq; using BizHawk.Emulation.Common; namespace BizHawk.Emulation.Cores.WonderSwan { [Core("Cygne/Mednafen", "Dox, Mednafen Team", true, true, "0.9.36.5", "http://mednafen.sourceforge.net/")] [ServiceNotApplicable(typeof(IDriveLight), typeof(IRegionable))] public partial class WonderSwan : IEmulator, IVideoProvider, ISoundProvider, IInputPollable, IDebuggable { [CoreConstructor("WSWAN")] public WonderSwan(CoreComm comm, byte[] file, bool deterministic, object settings, object syncSettings) { ServiceProvider = new BasicServiceProvider(this); CoreComm = comm; _Settings = (Settings)settings ?? new Settings(); _SyncSettings = (SyncSettings)syncSettings ?? new SyncSettings(); DeterministicEmulation = deterministic; // when true, remember to force the RTC flag! Core = BizSwan.bizswan_new(); if (Core == IntPtr.Zero) throw new InvalidOperationException("bizswan_new() returned NULL!"); try { var ss = _SyncSettings.GetNativeSettings(); if (deterministic) ss.userealtime = false; bool rotate = false; if (!BizSwan.bizswan_load(Core, file, file.Length, ref ss, ref rotate)) throw new InvalidOperationException("bizswan_load() returned FALSE!"); InitISaveRam(); InitVideo(rotate); PutSettings(_Settings); InitIMemoryDomains(); InitIStatable(); InitDebugCallbacks(); } catch { Dispose(); throw; } } public IEmulatorServiceProvider ServiceProvider { get; private set; } public void Dispose() { if (Core != IntPtr.Zero) { BizSwan.bizswan_delete(Core); Core = IntPtr.Zero; } } public void FrameAdvance(IController controller, bool render, bool rendersound = true) { Frame++; IsLagFrame = true; if (controller.IsPressed("Power")) BizSwan.bizswan_reset(Core); bool rotate = false; int soundbuffsize = sbuff.Length; IsLagFrame = BizSwan.bizswan_advance(Core, GetButtons(controller), !render, vbuff, sbuff, ref soundbuffsize, ref rotate); if (soundbuffsize == sbuff.Length) throw new Exception(); sbuffcontains = soundbuffsize; InitVideo(rotate); if (IsLagFrame) LagCount++; } public CoreComm CoreComm { get; private set; } public void ResetCounters() { Frame = 0; IsLagFrame = false; LagCount = 0; } IntPtr Core; public int Frame { get; private set; } public int LagCount { get; set; } public bool IsLagFrame { get; set; } public string SystemId { get { return "WSWAN"; } } public bool DeterministicEmulation { get; private set; } #region Debugging private readonly InputCallbackSystem _inputCallbacks = new InputCallbackSystem(); public IInputCallbackSystem InputCallbacks { get { return _inputCallbacks; } } private readonly MemoryCallbackSystem _memorycallbacks = new MemoryCallbackSystem(new[] { "System Bus" }); // This isn't an actual memory domain in this core (yet), but there's nothing that enforces that it has to be public IMemoryCallbackSystem MemoryCallbacks { get { return _memorycallbacks; } } public IDictionary<string, RegisterValue> GetCpuFlagsAndRegisters() { var ret = new Dictionary<string, RegisterValue>(); for (int i = (int)BizSwan.NecRegsMin; i <= (int)BizSwan.NecRegsMax; i++) { BizSwan.NecRegs en = (BizSwan.NecRegs)i; uint val = BizSwan.bizswan_getnecreg(Core, en); ret[Enum.GetName(typeof(BizSwan.NecRegs), en)] = (ushort)val; } return ret; } [FeatureNotImplemented] public void SetCpuRegister(string register, int value) { throw new NotImplementedException(); } public bool CanStep(StepType type) { return false; } [FeatureNotImplemented] public void Step(StepType type) { throw new NotImplementedException(); } [FeatureNotImplemented] public long TotalExecutedCycles { get { throw new NotImplementedException(); } } BizSwan.MemoryCallback ReadCallbackD; BizSwan.MemoryCallback WriteCallbackD; BizSwan.MemoryCallback ExecCallbackD; BizSwan.ButtonCallback ButtonCallbackD; void ReadCallback(uint addr) { MemoryCallbacks.CallReads(addr, "System Bus"); } void WriteCallback(uint addr) { MemoryCallbacks.CallWrites(addr, "System Bus"); } void ExecCallback(uint addr) { MemoryCallbacks.CallExecutes(addr, "System Bus"); } void ButtonCallback() { InputCallbacks.Call(); } void InitDebugCallbacks() { ReadCallbackD = new BizSwan.MemoryCallback(ReadCallback); WriteCallbackD = new BizSwan.MemoryCallback(WriteCallback); ExecCallbackD = new BizSwan.MemoryCallback(ExecCallback); ButtonCallbackD = new BizSwan.ButtonCallback(ButtonCallback); _inputCallbacks.ActiveChanged += SetInputCallback; _memorycallbacks.ActiveChanged += SetMemoryCallbacks; } void SetInputCallback() { BizSwan.bizswan_setbuttoncallback(Core, InputCallbacks.Any() ? ButtonCallbackD : null); } void SetMemoryCallbacks() { BizSwan.bizswan_setmemorycallbacks(Core, MemoryCallbacks.HasReads ? ReadCallbackD : null, MemoryCallbacks.HasWrites ? WriteCallbackD : null, MemoryCallbacks.HasExecutes ? ExecCallbackD : null); } #endregion #region IVideoProvider void InitVideo(bool rotate) { if (rotate) { BufferWidth = 144; BufferHeight = 224; } else { BufferWidth = 224; BufferHeight = 144; } } private int[] vbuff = new int[224 * 144]; public int[] GetVideoBuffer() { return vbuff; } public int VirtualWidth { get { return BufferWidth; } } public int VirtualHeight { get { return BufferHeight; } } public int BufferWidth { get; private set; } public int BufferHeight { get; private set; } public int BackgroundColor { get { return unchecked((int)0xff000000); } } public int VsyncNumerator => 3072000; // master CPU clock, also pixel clock public int VsyncDenominator => (144 + 15) * (224 + 32); // 144 vislines, 15 vblank lines; 224 vispixels, 32 hblank pixels #endregion } }
28.568807
219
0.685774
[ "MIT" ]
Asnivor/BizHawk
BizHawk.Emulation.Cores/Consoles/WonderSwan/WonderSwan.cs
6,230
C#
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. internal class Foo { } internal interface FooInterface { } internal struct FooStruct { } internal enum FooEnum { } internal delegate void FooDelegate(); namespace Roslynator.CSharp.Analyzers.Test { internal class DeclareTypeInsideNamespace { } }
15.740741
160
0.752941
[ "Apache-2.0" ]
TechnoridersForks/Roslynator
source/Test/AnalyzersTest/DeclareTypeInsideNamespace.cs
427
C#
using Forum.Models; using System; using System.Collections.Generic; using System.Text; namespace Forum.Data { public class ForumData { public List<Category> Categories { get; set; } public List<User> Users { get; set; } public List<Post> Posts { get; set; } public List<Reply> Replies { get; set; } public ForumData() { this.Users = DataMapper.LoadUsers(); this.Categories = DataMapper.LoadCategories(); this.Posts = DataMapper.LoadPosts(); this.Replies = DataMapper.LoadReplies(); } public void SaveChanges() { DataMapper.SaveUsers(this.Users); DataMapper.SaveCategories(this.Categories); DataMapper.SavePosts(this.Posts); DataMapper.SaveReplies(this.Replies); } } }
26.875
58
0.59186
[ "MIT" ]
ewgeni-dinew/06.C_Sharp-OOP_I
OOP-Fundamentals/08.Forum/Forum.Data/ForumData.cs
862
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 lambda-2015-03-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Lambda.Model { /// <summary> /// The Security Group ID provided in the Lambda function VPC configuration is invalid. /// </summary> #if !NETSTANDARD [Serializable] #endif public partial class InvalidSecurityGroupIDException : AmazonLambdaException { private string _type; /// <summary> /// Constructs a new InvalidSecurityGroupIDException with the specified error /// message. /// </summary> /// <param name="message"> /// Describes the error encountered. /// </param> public InvalidSecurityGroupIDException(string message) : base(message) {} /// <summary> /// Construct instance of InvalidSecurityGroupIDException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> public InvalidSecurityGroupIDException(string message, Exception innerException) : base(message, innerException) {} /// <summary> /// Construct instance of InvalidSecurityGroupIDException /// </summary> /// <param name="innerException"></param> public InvalidSecurityGroupIDException(Exception innerException) : base(innerException) {} /// <summary> /// Construct instance of InvalidSecurityGroupIDException /// </summary> /// <param name="message"></param> /// <param name="innerException"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public InvalidSecurityGroupIDException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, innerException, errorType, errorCode, requestId, statusCode) {} /// <summary> /// Construct instance of InvalidSecurityGroupIDException /// </summary> /// <param name="message"></param> /// <param name="errorType"></param> /// <param name="errorCode"></param> /// <param name="requestId"></param> /// <param name="statusCode"></param> public InvalidSecurityGroupIDException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode) : base(message, errorType, errorCode, requestId, statusCode) {} #if !NETSTANDARD /// <summary> /// Constructs a new instance of the InvalidSecurityGroupIDException class with serialized data. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception> /// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception> protected InvalidSecurityGroupIDException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) : base(info, context) { this.Type = (string)info.GetValue("Type", typeof(string)); } /// <summary> /// Sets the <see cref="T:System.Runtime.Serialization.SerializationInfo" /> with information about the exception. /// </summary> /// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param> /// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param> /// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is a null reference (Nothing in Visual Basic). </exception> #if BCL35 [System.Security.Permissions.SecurityPermission( System.Security.Permissions.SecurityAction.LinkDemand, Flags = System.Security.Permissions.SecurityPermissionFlag.SerializationFormatter)] #endif [System.Security.SecurityCritical] // These FxCop rules are giving false-positives for this method [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2123:OverrideLinkDemandsShouldBeIdenticalToBase")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2134:MethodsMustOverrideWithConsistentTransparencyFxCopRule")] public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { base.GetObjectData(info, context); info.AddValue("Type", this.Type); } #endif /// <summary> /// Gets and sets the property Type. /// </summary> public string Type { get { return this._type; } set { this._type = value; } } // Check to see if Type property is set internal bool IsSetType() { return this._type != null; } } }
45.5
178
0.669556
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Lambda/Generated/Model/InvalidSecurityGroupIDException.cs
6,461
C#
using System.Threading; using System.Threading.Tasks; namespace TIKSN.Data.Mongo { public interface IMongoUnitOfWorkFactory { Task<IMongoUnitOfWork> CreateAsync(CancellationToken cancellationToken); } }
20.363636
80
0.763393
[ "MIT" ]
tiksn/TIKSN-Framework
TIKSN.Core/Data/Mongo/IMongoUnitOfWorkFactory.cs
224
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.EventHubs; namespace EventHubSender { class Program { static string eventHubName = "xxxx"; static string connectionString = "Endpoint=sb://xxxx.servicebus.windows.net/;SharedAccessKeyName=xxxx;SharedAccessKey=xxxx;EntityPath=xxxx"; static void Main(string[] args) { Console.WriteLine("Press Ctrl-C to stop the sender process"); Console.WriteLine("Press Enter to start now"); Console.ReadLine(); SendingRandomMessages(); } static void SendingRandomMessages() { var connectionStringBuilder = new EventHubsConnectionStringBuilder(connectionString) { EntityPath = eventHubName }; var eventHubClient = EventHubClient.CreateFromConnectionString(connectionStringBuilder.ToString()); while (true) { try { var message = Guid.NewGuid().ToString(); Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, message); eventHubClient.SendAsync(new EventData(Encoding.UTF8.GetBytes(message))); } catch (Exception exception) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("{0} > Exception: {1}", DateTime.Now, exception.Message); Console.ResetColor(); } Thread.Sleep(200); } } } }
32.301887
148
0.574766
[ "MIT" ]
gjuljo/HelloAzureEventHub
CSharp/EventHubSender/EventHubSender/Program.cs
1,714
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using AngleSharp.Html.Dom; using AngleSharp.Html.Parser; using Newtonsoft.Json; using Tw.Net.Core; using Tw.Net.Models; namespace Tw.Net { public class Twitter { private readonly List<RequestProxy> proxies = new List<RequestProxy>(); public List<RequestProxy> Proxies => proxies; public Twitter() { DebugSettings.IsDebug = true; } RequestProxy GetRandomProxy() { if (proxies.Count < 1) { return null; } if (proxies.Count == 1) { return proxies[0]; } Random random = new Random(); var index = random.Next(0, proxies.Count); return proxies[index]; } public async Task InitAsync() { var isOfflineOk = await HtmlLoader.TryLoadAgentSource(true); if (!isOfflineOk) { var isOnlineOk = await HtmlLoader.TryLoadAgentSource(false); } } public async Task<TwitterFollowPageModel> GetFollowingAsync(string username,string cursor="-1") { var url = AddressLocator.Following(username,cursor); var htmlDoc = await HtmlLoader.TryLoadAndParsePageAsync(url, GetRandomProxy(),false,false); if (htmlDoc!=null) { if (HtmlExtracter.TryParseFollowing(htmlDoc,out var followingPage)) { followingPage.BelongUserName = username; return followingPage; } } return null; } public async Task<TwitterFollowPageModel> GetFollowerAsync(string username, string cursor = "-1") { var url = AddressLocator.Follower(username,cursor); var htmlDoc = await HtmlLoader.TryLoadAndParsePageAsync(url, GetRandomProxy(), false, false); if (htmlDoc != null) { if (HtmlExtracter.TryParseFollower(htmlDoc, out var followerPage)) { followerPage.BelongUserName = username; return followerPage; } } return null; } public async Task<TwitterUserModel> GetUserProfileAsync(string username) { var htmlDoc = await HtmlLoader.TryLoadAndParsePageAsync($"https://twitter.com/{username}?lang=en", GetRandomProxy()); if (htmlDoc != null) { if (HtmlExtracter.TryParseUser(htmlDoc, out var user)) { return user; } } return null; } public async Task<TwitterTweetPageModel> GetUserTweetsAsync(TwitterOption option,long init=-1) { var paramDict = new Dictionary<string, string>() { {"vertical","default" }, {"src","unkn" }, {"include_available_features","1" }, {"include_entities","1" }, {"max_position",$"{init}" }, {"reset_error_state","false" }, }; StringBuilder query = new StringBuilder(); if (!option.PopularTweets) { paramDict.Add("f", "tweets"); } if (!string.IsNullOrEmpty(option.Lang)) { paramDict.Add("l", option.Lang); paramDict.Add("lang", "en"); } if (!string.IsNullOrEmpty(option.Query)) { query.Append($" from:{option.Query}"); } if (!string.IsNullOrEmpty(option.UserName)) { query.Append($" from:{option.UserName}"); } if (!string.IsNullOrEmpty(option.Geo)) { option.Geo = option.Geo.Replace(" ", ""); query.Append($" geocode:{option.Geo}"); } if (!string.IsNullOrEmpty(option.Search)) { query.Append($" {option.Search}"); } if (option.Year>0) { query.Append($" until:{option.Year}-1-1"); } if (option.Since!=null) { query.Append($" since:{option.Since.Value.ToString("yyyy-MM-dd")}"); } if (option.Until!=null) { query.Append($" until:{option.Until.Value.ToString("yyyy-MM-dd")}"); } if (option.Email) { query.Append(" \"mail\" OR \"email\" OR"); query.Append(" \"gmail\" OR \"e-mail\""); } if (option.Phone) { query.Append($" \"phone\" OR \"call me\" OR \"text me\""); } if (option.Verified) { query.Append($" filter:verified"); } if (!string.IsNullOrEmpty(option.To)) { query.Append($" to:{option.To}"); } if (!string.IsNullOrEmpty(option.All)) { query.Append($" to:{option.All} OR from:{option.All} OR @{option.All}"); } if (!string.IsNullOrEmpty(option.Near)) { query.Append($" near:\"{option.Near}\""); } if (option.Images) { query.Append($" filter:images"); } if (option.Videos) { query.Append($" filter:videos"); } if (option.Media) { query.Append($" filter:media"); } if (option.Replies) { query.Append($" filter:replies"); } if (option.NativeRetweets) { query.Append($" filter:nativeretweets"); } if (option.MinLikes>0) { query.Append($" min_faves:{option.MinLikes}"); } if (option.MinRetweets > 0) { query.Append($" min_retweets:{option.MinRetweets}"); } if (option.MinReplies > 0) { query.Append($" min_replies:{option.MinReplies}"); } if (option.Links == "include") { query.Append(" filter:links"); } else if (option.Links=="exclude") { query.Append(" exclude:links"); } if (!string.IsNullOrEmpty(option.Source)) { query.Append($" source:\"{option.Source}\""); } if (!string.IsNullOrEmpty(option.MembersList)) { query.Append($" list:{option.MembersList}"); } if (option.FilterRetweets) { query.Append(" exclude:nativeretweets exclude:retweets"); } if (!string.IsNullOrEmpty(option.CustomQuery)) { query.Clear(); query.Append(option.CustomQuery); } paramDict.Add("q", query.ToString()); return await GetUserTweetsAsync(option, paramDict); } public async Task<TwitterTweetPageModel> GetUserTweetsAsync(TwitterOption option, Dictionary<string,string> paramDict) { var url = $"{AddressLocator.Web}/search/timeline"; url = AddressLocator.SanitizeQuery(url, paramDict); var htmlSource = await HtmlLoader.TryLoadPageAsync(url, GetRandomProxy(),true,false); if (!string.IsNullOrEmpty(htmlSource)) { if (RawTweetPage.TryParse(htmlSource,out var rawPage)) { var parser = new HtmlParser(); IHtmlDocument htmlDoc = null; try { htmlDoc = await parser.ParseDocumentAsync(rawPage.ItemsHtml); } catch (Exception) { } if (htmlDoc != null) { if (HtmlExtracter.TryParseTweet(option,htmlDoc, out var pageModel)) { pageModel.NextPageParams = new Dictionary<string, string>(paramDict); pageModel.HasNext = rawPage.HasMoreItems; pageModel.SetMaxPosition(rawPage.MinPosition); pageModel.Options = option; return pageModel; } } } } return null; } } }
32.98227
130
0.449414
[ "MIT" ]
BenDerPan/Tw.Net
Tw.Net/Twitter.cs
9,303
C#
using System.IO; namespace MatrixIO.IO.Bmff.IO.Bmff.Boxes.Dash { /// <summary> /// Segment Index Box ("sidx") /// </summary> [Box("sidx", "Segment Index Box")] public class SegmentIndexBox : FullBox { public SegmentIndexBox() : base() { } public SegmentIndexBox(Stream stream) : base(stream) { } public uint ReferenceId { get; set; } public uint Timescale { get; set; } public ulong EarliestPresentationTime { get; set; } public ulong FirstOffset { get; set; } public ushort Reserved1 { get; set; } public ushort ReferenceCount { get; set; } public SegmentIndexEntry[] Entries { get; set; } public override ulong CalculateSize() { ulong size = base.CalculateSize() + 20; if (Version == 1) { size += 8; } size += (ulong)(SegmentIndexEntry.Size * ReferenceCount); return size; } protected override void LoadFromStream(Stream stream) { base.LoadFromStream(stream); ReferenceId = stream.ReadBEUInt32(); Timescale = stream.ReadBEUInt32(); if (Version == 1) { EarliestPresentationTime = stream.ReadBEUInt64(); FirstOffset = stream.ReadBEUInt64(); } else // v0 { EarliestPresentationTime = stream.ReadBEUInt32(); FirstOffset = stream.ReadBEUInt32(); } Reserved1 = stream.ReadBEUInt16(); ReferenceCount = stream.ReadBEUInt16(); Entries = new SegmentIndexEntry[ReferenceCount]; for (int i = 0; i < ReferenceCount; i++) { uint referenceValue = stream.ReadBEUInt32(); uint duration = stream.ReadBEUInt32(); uint sapValue = stream.ReadBEUInt32(); Entries[i] = new SegmentIndexEntry(referenceValue, duration, sapValue); } } protected override void SaveToStream(Stream stream) { base.SaveToStream(stream); stream.WriteBEUInt32(ReferenceId); stream.WriteBEUInt32(Timescale); if (Version == 1) { stream.WriteBEUInt64(EarliestPresentationTime); stream.WriteBEUInt64(FirstOffset); } else // v0 { stream.WriteBEUInt32((uint)EarliestPresentationTime); stream.WriteBEUInt32((uint)FirstOffset); } stream.WriteBEUInt16(Reserved1); stream.WriteBEUInt16(ReferenceCount); for (int i = 0; i < Entries.Length; i++) { ref SegmentIndexEntry entry = ref Entries[i]; entry.WriteTo(stream); } } } public readonly struct SegmentIndexEntry { public const int Size = 12; private readonly uint referenceValue; private readonly uint sapValue; public SegmentIndexEntry(uint referenceValue, uint duration, uint sapValue) { this.referenceValue = referenceValue; this.Duration = duration; this.sapValue = sapValue; } public bool ReferenceType => (referenceValue >> 31) > 0; public uint ReferenceSize => (referenceValue & 0x7FFF_FFFF); public uint Duration { get; } public bool StartWithSap => (sapValue >> 31) > 0; public uint SapType => ((sapValue >> 28) & 0x07); public uint SapDeltaTime => (sapValue & 0x0FFF_FFFF); internal void WriteTo(Stream stream) { stream.WriteBEUInt32(referenceValue); stream.WriteBEUInt32(Duration); stream.WriteBEUInt32(sapValue); } } }
27.612676
87
0.544249
[ "MIT" ]
electric-monk/bmff
MatrixIO.IO.Bmff/IO/Bmff/Boxes/Dash/SegmentIndexBox.cs
3,923
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace fac.ASTs.Types { public class AstType_ArrayWrap: IAstType { public IAstType ItemType { init; get; } public override string ToString () => $"{ItemType}[]"; public override string GenerateCSharp (int _indent) => $"List<{ItemType.GenerateCSharp (_indent)}>"; public override string GenerateCpp (int _indent) => $"std::vector<{ItemType.GenerateCpp (_indent)}>"; } }
27.944444
103
0.735586
[ "MIT" ]
fa-org/fa
fa/fac/ASTs/Types/AstType_ArrayWrap.cs
505
C#
using System.Collections.Generic; using System.Linq; using ESFA.DC.ILR.Model.Interface; using ESFA.DC.ILR.ValidationService.Interface; using ESFA.DC.ILR.ValidationService.Rules.Abstract; using ESFA.DC.ILR.ValidationService.Rules.Constants; namespace ESFA.DC.ILR.ValidationService.Rules.CrossEntity { public class R125Rule : AbstractRule, IRule<ILearner> { private readonly HashSet<int> _aimTypes = new HashSet<int>() { AimTypes.ComponentAimInAProgramme, AimTypes.CoreAim16To19ExcludingApprenticeships }; private readonly HashSet<int?> _progTypes = new HashSet<int?>() { ProgTypes.TLevelTransition, ProgTypes.TLevel }; public R125Rule(IValidationErrorHandler validationErrorHandler) : base(validationErrorHandler, RuleNameConstants.R125) { } public void Validate(ILearner learner) { if (learner?.LearningDeliveries == null) { return; } var tLevelDeliveries = learner.LearningDeliveries.Where(ld => _aimTypes.Contains(ld.AimType) && _progTypes.Contains(ld.ProgTypeNullable)); foreach (var tLevelDelivery in tLevelDeliveries.Where(tLevelDelivery => ConditionMet(learner.LearningDeliveries, tLevelDelivery))) { HandleValidationError( learner.LearnRefNumber, tLevelDelivery.AimSeqNumber, BuildErrorMessageParameters(tLevelDelivery.AimType, tLevelDelivery.ProgTypeNullable, tLevelDelivery.FundModel)); } } public bool ConditionMet(IEnumerable<ILearningDelivery> learningDeliveries, ILearningDelivery tLevelDelivery) { return !learningDeliveries.Any(ld => ld.AimType == AimTypes.ProgrammeAim && tLevelDelivery.ProgTypeNullable == ld.ProgTypeNullable && tLevelDelivery.FundModel == ld.FundModel); } public IEnumerable<IErrorMessageParameter> BuildErrorMessageParameters(int aimType, int? progType, int fundModel) { return new[] { BuildErrorMessageParameter(PropertyNameConstants.AimType, aimType), BuildErrorMessageParameter(PropertyNameConstants.ProgType, progType), BuildErrorMessageParameter(PropertyNameConstants.FundModel, fundModel) }; } } }
39.246154
150
0.632693
[ "MIT" ]
SkillsFundingAgency/DC-ILR-2021-ValidationService
src/ESFA.DC.ILR.ValidationService.Rules/CrossEntity/R125Rule.cs
2,553
C#
using ExampleToDo.Application.BusinessModels; using ExampleToDo.Application.BusinessModels.Response; using ExampleToDo.Application.Interfaces.Services.Results; using System.Threading.Tasks; namespace ExampleToDo.Application.Interfaces.Services { public interface ICustomTaskListGroupService { Task<IServiceResult> CreateGroupAsync(NamedIdentifiableModel customTaskListGroupModel); Task<IServiceResult> UpdateGroupAsync(NamedIdentifiableModel customTaskListGroupModel); Task<IServiceResult> DeleteGroupAsync(int customTaskListGroupId); Task<IServiceObjectResult<CustomTaskListGroupDto[]>> GetGroupsAsync(bool includeTaskLists); } }
39.882353
99
0.820059
[ "MIT" ]
PrizrakNight/ExampleToDo
ExampleToDo/ExampleToDo.Application/Interfaces/Services/ICustomTaskListGroupService.cs
680
C#
namespace MediaApps.Series.Core.Models { public class Actor { public string Image { get; set; } public string Name { get; set; } public string Role { get; set; } public int SortOrder { get; set; } } }
22.363636
42
0.573171
[ "MIT" ]
wernervn/media-apps
src/series/MediaApps.Series.Core/Models/Actor.cs
248
C#
using System; using System.Collections.Generic; namespace RockPaperScissors { public class Program { public static void Main() { ConsoleKeyInfo moveA; ConsoleKeyInfo moveB; string move1 = "error: invalid move"; string move2 = "error: invalid move"; while (move1 == "error: invalid move" || move2 == "error: invalid move") { Console.WriteLine("Player 1 make your move: (a:rock s:paper d:scissors)"); moveA = Console.ReadKey(true); Console.WriteLine("Player 2 make your move: (arrow keys left:rock down:paper right:scissors)"); moveB = Console.ReadKey(true); move1 = moveA.Key.ToString(); move2 = moveB.Key.ToString(); move1 = findMove(move1); move2 = findMove2(move2); Console.WriteLine("____________________________________"); Console.WriteLine("Player 1 move: " + move1); Console.WriteLine("Player 2 move: " + move2); if (move1 == "error: invalid move" || move2 == "error: invalid move") { Console.WriteLine("invalid move made, try again"); } } Console.WriteLine(winCheck(move1, move2)); Console.WriteLine("Play again? ( y / n )?"); string rpsChoice = Console.ReadLine(); if (rpsChoice == "y") { Main(); } else { return; } } static string findMove(string rawMove) { if (rawMove == "A") { rawMove = "rock"; } else if (rawMove == "S") { rawMove = "paper"; } else if (rawMove == "D") { rawMove = "scissors"; } else { rawMove = "error: invalid move"; } return rawMove; } static string findMove2(string rawMove) { if (rawMove == "LeftArrow") { rawMove = "rock"; } else if (rawMove == "DownArrow") { rawMove = "paper"; } else if (rawMove == "RightArrow") { rawMove = "scissors"; } else { rawMove = "error: invalid move"; } return rawMove; } static string winCheck(string aMove, string bMove) { string winner; if ((aMove == "rock" && bMove == "scissors") || (aMove == "paper" && bMove == "rock") || (aMove == "scissors" && bMove == "paper")) { winner = "Player 1 wins!"; } else if (aMove == bMove) { winner = "Tie game!"; } else { winner = "Player 2 wins!"; } return winner; } } }
23.080357
137
0.516828
[ "MIT" ]
HoldenJC/rps-c
RPS/Program.cs
2,585
C#
/****************************************************************************** * Copyright (C) Ultraleap, Inc. 2011-2021. * * * * Use subject to the terms of the Apache License 2.0 available at * * http://www.apache.org/licenses/LICENSE-2.0, or another agreement * * between Ultraleap and you, your company or other organization. * ******************************************************************************/ using UnityEngine; namespace Leap.Interaction.Internal.InteractionEngineUtility { public class GrabClassifierHeuristics { public static void UpdateClassifier(GrabClassifier classifier, ClassifierParameters grabParameters, ref Collider[][] collidingCandidates, ref int[] numberOfColliders, bool ignoreTemporal = false) { // Store actual minimum curl in case we override it with the ignoreTemporal flag. float tempMinCurl = grabParameters.MINIMUM_CURL; if (ignoreTemporal) { grabParameters.MINIMUM_CURL = -1f; } //For each probe (fingertip) for (int j = 0; j < classifier.probes.Length; j++) { //Calculate how extended the finger is float tempCurl = Vector3.Dot(classifier.probes[j].direction, (j != 0) ? classifier.handDirection : (classifier.handChirality ? 1f : -1f) * classifier.handXBasis); float curlVelocity = tempCurl - classifier.probes[j].prevTempCurl; classifier.probes[j].prevTempCurl = tempCurl; //Determine if this probe is intersecting an object bool collidingWithObject = false; for (int i = 0; i < numberOfColliders[j]; i++) { if (collidingCandidates[j][i].attachedRigidbody != null && collidingCandidates[j][i].attachedRigidbody == classifier.body) { collidingWithObject = true; break; } } //Nullify above findings if fingers are extended float conditionalMaxCurlVelocity = (classifier.isGrabbed ? grabParameters.GRABBED_MAXIMUM_CURL_VELOCITY : grabParameters.MAXIMUM_CURL_VELOCITY); collidingWithObject = collidingWithObject && (tempCurl < grabParameters.MAXIMUM_CURL) && (tempCurl > grabParameters.MINIMUM_CURL) && (ignoreTemporal || curlVelocity < conditionalMaxCurlVelocity); //Probes go inside when they intersect, probes come out when they uncurl if (!classifier.probes[j].isInside) { classifier.probes[j].isInside = collidingWithObject; classifier.probes[j].curl = tempCurl + (j == 0 ? grabParameters.THUMB_STICKINESS : grabParameters.FINGER_STICKINESS); if (ignoreTemporal) { classifier.probes[j].curl = 0f + (j == 0 ? grabParameters.THUMB_STICKINESS : grabParameters.FINGER_STICKINESS); } } else { if (tempCurl > classifier.probes[j].curl) { classifier.probes[j].isInside = collidingWithObject; } } } //If thumb and one other finger is "inside" the object, it's a grab! //This is the trick! classifier.isThisControllerGrabbing = (classifier.probes[0].isInside && (classifier.probes[1].isInside || classifier.probes[2].isInside || classifier.probes[3].isInside || classifier.probes[4].isInside)); //If grabbing within 10 frames of releasing, discard grab. //Suppresses spurious regrabs and makes throws work better. if (classifier.coolDownProgress <= grabParameters.GRAB_COOLDOWN && !ignoreTemporal) { if (classifier.isThisControllerGrabbing) { classifier.isThisControllerGrabbing = false; } classifier.coolDownProgress += Time.fixedDeltaTime; } //Determine if the object is near the hand or if it's too far away if (classifier.isThisControllerGrabbing && !classifier.prevThisControllerGrabbing) { bool nearObject = false; numberOfColliders[5] = Physics.OverlapSphereNonAlloc(classifier.handGrabCenter, grabParameters.MAXIMUM_DISTANCE_FROM_HAND, collidingCandidates[5], grabParameters.LAYER_MASK, grabParameters.GRAB_TRIGGERS); for (int i = 0; i < numberOfColliders[5]; i++) { if (collidingCandidates[5][i].attachedRigidbody != null && collidingCandidates[5][i].attachedRigidbody == classifier.body) { nearObject = true; break; } } if (!nearObject) { classifier.isThisControllerGrabbing = false; classifier.probes[0].isInside = false; } } // Reset the minimum curl parameter if we modified it due to the ignoreTemporal // flag. if (ignoreTemporal) { grabParameters.MINIMUM_CURL = tempMinCurl; } } //Expensive collider query optimization that somehow got undone before public static void UpdateAllProbeColliders(Vector3[] aPositions, Vector3[] bPositions, ref Collider[][] collidingCandidates, ref int[] numberOfColliders, ClassifierParameters grabParameters) { for (int i = 0; i < 5; i++) { numberOfColliders[i] = Physics.OverlapCapsuleNonAlloc( point0: aPositions[i], point1: bPositions[i], radius: i == 0 ? grabParameters.THUMBTIP_RADIUS : grabParameters.FINGERTIP_RADIUS, results: collidingCandidates[i], layerMask: grabParameters.LAYER_MASK, queryTriggerInteraction: grabParameters.GRAB_TRIGGERS); } } //Per-Object Per-Hand Classifier public class GrabClassifier { public bool isThisControllerGrabbing; public bool prevThisControllerGrabbing; public GrabProbe[] probes = new GrabProbe[5]; public Transform transform; public Rigidbody body; public bool isGrabbed; public float coolDownProgress; public Vector3 handGrabCenter; public Vector3 handDirection; public Vector3 handXBasis; public bool handChirality; public GrabClassifier(GameObject behaviour) { probes = new GrabProbe[5]; for (int i = 0; i < probes.Length; i++) { probes[i].prevTempCurl = 1f; } transform = behaviour.transform; body = behaviour.GetComponent<Rigidbody>(); coolDownProgress = 0; } } //Per-Finger Per-Object Probe public struct GrabProbe { public Vector3 direction; public bool isInside; public float curl; public float prevTempCurl; }; //The parameters that tune how grabbing feels public struct ClassifierParameters { /** <summary> The amount of curl hysteresis on each finger type </summary> */ public float FINGER_STICKINESS, THUMB_STICKINESS; /** <summary> The minimum and maximum curl values fingers are allowed to "Grab" within </summary> */ public float MAXIMUM_CURL, MINIMUM_CURL; /** <summary> The radius considered for intersection around the fingertips </summary> */ public float FINGERTIP_RADIUS, THUMBTIP_RADIUS; /** <summary> The minimum amount of time between repeated grabs of a single object </summary> */ public float GRAB_COOLDOWN; /** <summary> The maximum rate that the fingers are extending where grabs are considered. </summary> */ public float MAXIMUM_CURL_VELOCITY; public float GRABBED_MAXIMUM_CURL_VELOCITY; public float MAXIMUM_DISTANCE_FROM_HAND; public int LAYER_MASK; public QueryTriggerInteraction GRAB_TRIGGERS; public ClassifierParameters(float fingerStickiness = 0f, float thumbStickiness = 0.05f, float maxCurl = 0.65f, float minCurl = -0.1f, float fingerRadius = 0.01f, float thumbRadius = 0.015f, float grabCooldown = 0.2f, float maxCurlVel = 0.0f, float grabbedMaxCurlVel = -0.05f, float maxHandDist = 0.1f, int layerMask = 0, QueryTriggerInteraction queryTriggers = QueryTriggerInteraction.UseGlobal) { FINGER_STICKINESS = fingerStickiness; THUMB_STICKINESS = thumbStickiness; MAXIMUM_CURL = maxCurl; MINIMUM_CURL = minCurl; FINGERTIP_RADIUS = fingerRadius; THUMBTIP_RADIUS = thumbRadius; GRAB_COOLDOWN = grabCooldown; MAXIMUM_CURL_VELOCITY = maxCurlVel; GRABBED_MAXIMUM_CURL_VELOCITY = grabbedMaxCurlVel; MAXIMUM_DISTANCE_FROM_HAND = maxHandDist; LAYER_MASK = layerMask; GRAB_TRIGGERS = queryTriggers; } } } }
50.762136
407
0.529406
[ "MIT" ]
Gustav-Rixon/M7012E-DRv3
Remote control/Assets/ThirdParty/Ultraleap/Tracking/Interaction Engine/Runtime/Plugins/GrabClassifierHeuristics.cs
10,457
C#
using System; namespace Spice_Must_Flow { class Program { static void Main(string[] args) { int startingYield = int.Parse(Console.ReadLine()); int totalSpice = 0; int daysCount = 0; while (startingYield>=100) { totalSpice += startingYield; totalSpice -= 26; //for workers// daysCount++; startingYield -= 10; } if (totalSpice<26) totalSpice = 0; else totalSpice -= 26; Console.WriteLine($"{daysCount}\n{totalSpice}"); } } }
21.965517
62
0.477237
[ "MIT" ]
ITonev/SoftUni
Technology-Fundamentals-C#/Data-Types-and-Variable/Exercise/Spice Must Flow/Program.cs
639
C#
using System; using System.Threading; using Xwt; using Xwt.Backends; using Xwt.GtkBackend; using Xwt.Drawing; using Gtk; namespace GtkTest { class MainClass { public static void Main (string [] args) { using (var engine = new GtkEngine ()) { engine.Initialize (false); ApplicationContext ctx = new ApplicationContext (engine, Thread.CurrentThread); using (IWindowBackend wb = new WindowBackend ()) { wb.InitializeBackend (null, ctx); // Connecting to event sink wb.Initialize (new Xwt.Backends.WindowFrameEventSink.Default ()); //wb.BackgroundColor = Colors.Red; wb.SetSize (600, 400); IWidgetContainerBackend container = new WidgetContainerBackend (); container.InitializeBackend (null, ctx); container.Initialize (new Xwt.Backends.CanvasEventSink.Default ()); container.BackgroundColor = Colors.Blue; container.BoundsRequest = new Rectangle (0, 0, 600, 400); // ContentViewの制約は有効にならない wb.SetChild (container, false); IWidgetContainerBackend box = new WidgetContainerBackend (); box.InitializeBackend (null, ctx); box.Initialize (new Xwt.Backends.WidgetEventSink.Default ()); box.BackgroundColor = Colors.Lime; box.BoundsRequest = (new Rectangle (16, 16, 568, 368)); container.AddChild (box); // -- ComposeItems (ctx, box); PopulateMenu (ctx, wb); wb.EventSink.OnShown.Register (e => { // As Visible property is true, fired. return; }); wb.EventSink.OnHidden.Register (e => { // As Visible property is true, fired. return; }); wb.EventSink.OnCloseRequested.Register (e => { // As Visible property is true, fired. return; }); wb.EventSink.OnClosed.Register (e => { // As Visible property is true, fired. return; }); wb.EventSink.OnBoundsChanged.Register (e => { return; }); wb.Visible = true; SynchronizationContext.SetSynchronizationContext (new XwtSynchronizationContext (ctx)); engine.RunApplication (); } } } private static int countedValue; private static void ComposeItems (ApplicationContext ctx, IWidgetContainerBackend contaner) { ILabelBackend label = new LabelBackend (); label.InitializeBackend (null, ctx); label.Initialize (new Xwt.Backends.WidgetEventSink.Default ()); label.Text = "Hello minimum xwt"; label.BackgroundColor = Colors.LightSkyBlue; label.BoundsRequest = (new Rectangle (8, 8, 120, 30)); // TODO: AutoResizing contaner.AddChild (label); ILabelBackend countLabel = new LabelBackend (); countLabel.InitializeBackend (null, ctx); countLabel.Initialize (new Xwt.Backends.WidgetEventSink.Default ()); countLabel.Text = "-"; countLabel.BackgroundColor = Colors.LightSkyBlue; countLabel.BoundsRequest = (new Rectangle (8, 42, 120, 30)); // TODO: AutoResizing contaner.AddChild (countLabel); countedValue = 0; // Upボタン IButtonBackend up = new ButtonBackend (); up.InitializeBackend (null, ctx); up.Initialize (new Xwt.Backends.ButtonEventSink.Default ()); up.Text = "Count up"; up.BoundsRequest = (new Rectangle (8, 320, 120, 30)); // TODO: AutoResizing up.EventSink.OnClicked.Register ( (obj) => { ++countedValue; countLabel.Text = countedValue.ToString (); } ); contaner.AddChild (up); // Resetボタン IButtonBackend reset = new ButtonBackend (); reset.InitializeBackend (null, ctx); reset.Initialize (new Xwt.Backends.ButtonEventSink.Default ()); reset.Text = "Reset"; reset.BoundsRequest = (new Rectangle (132, 320, 120, 30)); // TODO: AutoResizing reset.EventSink.OnClicked.Register ( (obj) => { countedValue = 0; countLabel.Text = "-"; } ); contaner.AddChild (reset); } private static void PopulateMenu (ApplicationContext ctx, IWindowBackend wb) { var mainMenu = new MenuBackend (); mainMenu.InitializeBackend (null, ctx); var fileMenu = new MenuItemBackend (); fileMenu.InitializeBackend (null, ctx); { fileMenu.Label = "File"; { var m = new MenuBackend (); m.InitializeBackend (null, ctx); fileMenu.SetSubmenu (m); { var mi = new MenuItemBackend (); mi.InitializeBackend (null, ctx); mi.Initialize (new Xwt.Backends.MenuItemEventSink.Default ()); mi.Label = "Close"; m.InsertItem (0, mi); mi.EventSink.OnClicked.Register (delegate { ctx.Engine.ExitApplication (); }); } } } mainMenu.InsertItem (0, fileMenu); wb.SetMainMenu (mainMenu); } } }
37.396341
107
0.497962
[ "MIT" ]
ritalin/Xwt.Minimum
MacTest/GtkTest/Program.cs
6,169
C#
namespace iWay.RemoteControlClient.RemoteExplorer { partial class ContentGetWindow { /// <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.mLogTextBox = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // textBox1 // this.mLogTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None; this.mLogTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this.mLogTextBox.Location = new System.Drawing.Point(0, 0); this.mLogTextBox.Multiline = true; this.mLogTextBox.Name = "textBox1"; this.mLogTextBox.ReadOnly = true; this.mLogTextBox.Size = new System.Drawing.Size(384, 162); this.mLogTextBox.TabIndex = 0; // // ContentGetWindow // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(384, 162); this.Controls.Add(this.mLogTextBox); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ContentGetWindow"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "下载"; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.ContentGetWindow_FormClosed); this.Load += new System.EventHandler(this.ContentGetWindow_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox mLogTextBox; } }
37.61194
113
0.586905
[ "Apache-2.0" ]
PHPPlay/RemoteControl
RemoteControlClient/RemoteExplorer/ContentGetWindow.Designer.cs
2,526
C#
using MinecraftMappings.Internal; using MinecraftMappings.Internal.Textures.Block; namespace MinecraftMappings.Minecraft.Java.Textures.Block { public class Torch : JavaBlockTexture { public Torch() : base("Torch") { BlendMode = BlendModes.Cutout; AddVersion("torch") .WithDefaultModel<Java.Models.Block.Torch>() .MapsToBedrockBlock<MinecraftMappings.Minecraft.Bedrock.Textures.Block.TorchOn>(); } } }
27.555556
98
0.653226
[ "MIT" ]
null511/MinecraftMappings.NET
MinecraftMappings.NET/Minecraft/Java/Textures/Block/Torch.cs
498
C#
using System; using System.Collections.Generic; using System.Text; namespace UtilKits.RabbitMQ { public interface IProducerBase<in T> { /// <summary> /// 上傳 QUEUE /// </summary> /// <param name="Source">QUEUE 字串</param> void Publish(T Source); } }
18.9375
49
0.584158
[ "MIT" ]
kai-sheng/RabbitMQ
UtilKits/RabbitMQ/IProducerBase.cs
313
C#
using AutoMapper; using MediatR; using Microsoft.Extensions.Logging; using Ordering.Application.Contracts.Persistence; using Ordering.Application.Exceptions; using Ordering.Domain.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Ordering.Application.Features.Orders.Commands.DeleteOrder { public class DeleteOrderCommandHandler : IRequestHandler<DeleteOrderCommand> { private readonly IOrderRepository orderRepository; private readonly IMapper mapper; private readonly ILogger<DeleteOrderCommandHandler> logger; public DeleteOrderCommandHandler(IOrderRepository orderRepository, IMapper mapper, ILogger<DeleteOrderCommandHandler> logger) { this.orderRepository = orderRepository ?? throw new ArgumentNullException(nameof(orderRepository)); this.mapper = mapper ?? throw new ArgumentNullException(nameof(mapper)); this.logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task<Unit> Handle(DeleteOrderCommand request, CancellationToken cancellationToken) { var orderToDelete = await orderRepository.GetByIdAsync(request.Id); if(orderToDelete == null) { // logger.LogError("Order does not exist on the database"); throw new NotFoundException(nameof(Order), request.Id); } await orderRepository.DeleteAsync(orderToDelete); logger.LogInformation($"Order {orderToDelete.Id} is successfully deleted."); return Unit.Value; } } }
37.888889
133
0.71261
[ "MIT" ]
pmakanga/AspnetMicroservices
src/Services/Ordering/Ordering.Application/Features/Orders/Commands/DeleteOrder/DeleteOrderCommandHandler.cs
1,707
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.AspNetCore.Identity; using PierresTreats.Models; using PierresTreats.ViewModels; using System.Threading.Tasks; using System.Security.Claims; namespace PierresTreats.Controllers { public class AccountController : Controller { private readonly PierresTreatsContext _db; private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; public AccountController(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, PierresTreatsContext db) { _userManager = userManager; _signInManager = signInManager; _db = db; } public ActionResult Index() { return View(); } public ActionResult Register() { return View(); } [HttpPost] public async Task<ActionResult> Register(RegisterViewModel model) { var user = new ApplicationUser { UserName = model.UserName, Email = model.Email }; IdentityResult result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { return RedirectToAction("Login"); } else { return View(); } } public ActionResult Login() { return View(); } [HttpPost] public async Task<ActionResult> Login(LoginViewModel model) { Microsoft.AspNetCore.Identity.SignInResult result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, isPersistent: true, lockoutOnFailure: false); if (result.Succeeded) { return View(); } else { return View(); } } [HttpPost] public async Task<ActionResult> LogOff() { await _signInManager.SignOutAsync(); return RedirectToAction("Index", "Home"); } } }
28.073529
176
0.67627
[ "MIT" ]
JohnNilsOlson/PierresTreats.Solution
PierresTreats/Controllers/AccountController.cs
1,909
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34209 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace TextAnalyzer.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TextAnalyzer.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.546875
178
0.613563
[ "Unlicense" ]
oggy22/LanguageTools
TextAnalyzer/Properties/Resources.Designer.cs
2,789
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.38967 // <NameSpace>NPOI.OpenXmlFormats.Dml</NameSpace><Collection>List</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>False</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>False</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>False</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net20</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>True</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>True</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace NPOI.OpenXmlFormats.Dml { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.Collections.Generic; using NPOI.OpenXml4Net.Util; using System.IO; using System.Xml; [Serializable] [DebuggerStepThrough] [System.ComponentModel.DesignerCategoryAttribute("code")] [XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")] [XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)] public class CT_TextFont { private string typefaceField; private byte[] panoseField; private sbyte pitchFamilyField; private sbyte charsetField; public CT_TextFont() { this.pitchFamilyField = ((sbyte)(0)); this.charsetField = ((sbyte)(1)); } public static CT_TextFont Parse(XmlNode node, XmlNamespaceManager namespaceManager) { if (node == null) return null; CT_TextFont ctObj = new CT_TextFont(); ctObj.typeface = XmlHelper.ReadString(node.Attributes["typeface"]); ctObj.panose = XmlHelper.ReadBytes(node.Attributes["panose"]); ctObj.pitchFamily = XmlHelper.ReadSByte(node.Attributes["pitchFamily"]); if (node.Attributes["charset"]!=null) ctObj.charsetField = XmlHelper.ReadSByte(node.Attributes["charset"]); return ctObj; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<a:{0}", nodeName)); XmlHelper.WriteAttribute(sw, "typeface", this.typeface); XmlHelper.WriteAttribute(sw, "panose", this.panose); XmlHelper.WriteAttribute(sw, "pitchFamily", this.pitchFamily); if(charsetField!=(sbyte)1) XmlHelper.WriteAttribute(sw, "charset", this.charset); sw.Write("/>"); } [XmlAttribute] public string typeface { get { return this.typefaceField; } set { this.typefaceField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType = "hexBinary")] public byte[] panose { get { return this.panoseField; } set { this.panoseField = value; } } [XmlAttribute] [DefaultValue(typeof(sbyte), "0")] public sbyte pitchFamily { get { return this.pitchFamilyField; } set { this.pitchFamilyField = value; } } [XmlAttribute] [DefaultValue(typeof(sbyte), "1")] public sbyte charset { get { return this.charsetField; } set { this.charsetField = value; } } } [Serializable] [DebuggerStepThrough] [System.ComponentModel.DesignerCategoryAttribute("code")] [XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")] [XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)] public class CT_TextUnderlineLineFollowText { } [Serializable] [DebuggerStepThrough] [System.ComponentModel.DesignerCategoryAttribute("code")] [XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")] [XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)] public class CT_TextUnderlineFillFollowText { } [Serializable] [DebuggerStepThrough] [System.ComponentModel.DesignerCategoryAttribute("code")] [XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")] [XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)] public class CT_TextUnderlineFillGroupWrapper { private CT_BlipFillProperties blipFillField; private CT_GroupFillProperties grpFillField; private CT_NoFillProperties noFillField; private CT_SolidColorFillProperties solidFillField; private CT_GradientFillProperties gradFillField; private CT_PatternFillProperties pattFillField; public static CT_TextUnderlineFillGroupWrapper Parse(XmlNode node, XmlNamespaceManager namespaceManager) { if (node == null) return null; CT_TextUnderlineFillGroupWrapper ctObj = new CT_TextUnderlineFillGroupWrapper(); foreach (XmlNode childNode in node.ChildNodes) { if (childNode.LocalName == "noFill") ctObj.noFill = new CT_NoFillProperties(); else if (childNode.LocalName == "solidFill") ctObj.solidFill = CT_SolidColorFillProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "gradFill") ctObj.gradFill = CT_GradientFillProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "blipFill") ctObj.blipFill = CT_BlipFillProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "pattFill") ctObj.pattFill = CT_PatternFillProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "grpFill") ctObj.grpFill = new CT_GroupFillProperties(); } return ctObj; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<a:{0}", nodeName)); sw.Write(">"); if (this.noFill != null) sw.Write("<a:noFill/>"); if (this.solidFill != null) this.solidFill.Write(sw, "solidFill"); if (this.gradFill != null) this.gradFill.Write(sw, "gradFill"); if (this.blipFill != null) this.blipFill.Write(sw, "a:blipFill"); if (this.pattFill != null) this.pattFill.Write(sw, "pattFill"); if (this.grpFill != null) sw.Write("<a:grpFill/>"); sw.Write(string.Format("</a:{0}>", nodeName)); } [XmlElement(Order = 1)] public CT_NoFillProperties noFill { get { return this.noFillField; } set { this.noFillField = value; } } [XmlElement(Order = 2)] public CT_SolidColorFillProperties solidFill { get { return this.solidFillField; } set { this.solidFillField = value; } } [XmlElement(Order = 3)] public CT_GradientFillProperties gradFill { get { return this.gradFillField; } set { this.gradFillField = value; } } [XmlElement(Order = 4)] public CT_BlipFillProperties blipFill { get { return this.blipFillField; } set { this.blipFillField = value; } } [XmlElement(Order = 5)] public CT_PatternFillProperties pattFill { get { return this.pattFillField; } set { this.pattFillField = value; } } [XmlElement(Order = 6)] public CT_GroupFillProperties grpFill { get { return this.grpFillField; } set { this.grpFillField = value; } } } [Serializable] [DebuggerStepThrough] [System.ComponentModel.DesignerCategoryAttribute("code")] [XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")] [XmlRoot(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main", IsNullable = true)] public class CT_TextCharacterProperties { private CT_LineProperties lnField; private CT_NoFillProperties noFillField; private CT_SolidColorFillProperties solidFillField; private CT_GradientFillProperties gradFillField; private CT_BlipFillProperties blipFillField; private CT_PatternFillProperties pattFillField; private CT_GroupFillProperties grpFillField; private CT_EffectList effectLstField; private CT_EffectContainer effectDagField; private CT_Color highlightField; private CT_TextUnderlineLineFollowText uLnTxField; private CT_LineProperties uLnField; private CT_TextUnderlineFillFollowText uFillTxField; private CT_TextUnderlineFillGroupWrapper uFillField; private CT_TextFont latinField; private CT_TextFont eaField; private CT_TextFont csField; private CT_TextFont symField; private CT_Hyperlink hlinkClickField; private CT_Hyperlink hlinkMouseOverField; private CT_OfficeArtExtensionList extLstField; private bool kumimojiField; private bool kumimojiFieldSpecified; private string langField; private string altLangField; private int szField; private bool szFieldSpecified; private bool bField; private bool bFieldSpecified; private bool iField; private bool iFieldSpecified; private ST_TextUnderlineType uField; private bool uFieldSpecified; private ST_TextStrikeType strikeField; private bool strikeFieldSpecified; private int kernField; private bool kernFieldSpecified; private ST_TextCapsType capField; private bool capFieldSpecified; private int spcField; private bool spcFieldSpecified; private bool normalizeHField; private bool normalizeHFieldSpecified; private int baselineField; private bool baselineFieldSpecified; private bool noProofField; private bool noProofFieldSpecified; private bool dirtyField=true; private bool errField; private bool smtCleanField=true; private uint smtIdField; private string bmkField; public static CT_TextCharacterProperties Parse(XmlNode node, XmlNamespaceManager namespaceManager) { if (node == null) return null; CT_TextCharacterProperties ctObj = new CT_TextCharacterProperties(); ctObj.kumimoji = XmlHelper.ReadBool(node.Attributes["kumimoji"]); ctObj.lang = XmlHelper.ReadString(node.Attributes["lang"]); ctObj.altLang = XmlHelper.ReadString(node.Attributes["altLang"]); ctObj.sz = XmlHelper.ReadInt(node.Attributes["sz"]); if (node.Attributes["b"] != null) ctObj.b = XmlHelper.ReadBool(node.Attributes["b"]); if (node.Attributes["i"] != null) ctObj.i = XmlHelper.ReadBool(node.Attributes["i"]); if (node.Attributes["u"] != null) ctObj.u = (ST_TextUnderlineType)Enum.Parse(typeof(ST_TextUnderlineType), node.Attributes["u"].Value); if (node.Attributes["strike"] != null) ctObj.strike = (ST_TextStrikeType)Enum.Parse(typeof(ST_TextStrikeType), node.Attributes["strike"].Value); ctObj.kern = XmlHelper.ReadInt(node.Attributes["kern"]); if (node.Attributes["cap"] != null) ctObj.cap = (ST_TextCapsType)Enum.Parse(typeof(ST_TextCapsType), node.Attributes["cap"].Value); ctObj.spc = XmlHelper.ReadInt(node.Attributes["spc"]); ctObj.normalizeH = XmlHelper.ReadBool(node.Attributes["normalizeH"]); ctObj.baseline = XmlHelper.ReadInt(node.Attributes["baseline"]); ctObj.noProof = XmlHelper.ReadBool(node.Attributes["noProof"]); if (node.Attributes["dirty"]!=null) ctObj.dirty = XmlHelper.ReadBool(node.Attributes["dirty"]); ctObj.err = XmlHelper.ReadBool(node.Attributes["err"]); if (node.Attributes["smtClean"] != null) ctObj.smtClean = XmlHelper.ReadBool(node.Attributes["smtClean"]); ctObj.smtId = XmlHelper.ReadUInt(node.Attributes["smtId"]); ctObj.bmk = XmlHelper.ReadString(node.Attributes["bmk"]); foreach (XmlNode childNode in node.ChildNodes) { if (childNode.LocalName == "ln") ctObj.ln = CT_LineProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "noFill") ctObj.noFill = new CT_NoFillProperties(); else if (childNode.LocalName == "solidFill") ctObj.solidFill = CT_SolidColorFillProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "gradFill") ctObj.gradFill = CT_GradientFillProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "blipFill") ctObj.blipFill = CT_BlipFillProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "pattFill") ctObj.pattFill = CT_PatternFillProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "grpFill") ctObj.grpFill = new CT_GroupFillProperties(); else if (childNode.LocalName == "effectLst") ctObj.effectLst = CT_EffectList.Parse(childNode, namespaceManager); else if (childNode.LocalName == "effectDag") ctObj.effectDag = CT_EffectContainer.Parse(childNode, namespaceManager); else if (childNode.LocalName == "highlight") ctObj.highlight = CT_Color.Parse(childNode, namespaceManager); else if (childNode.LocalName == "uLnTx") ctObj.uLnTx = new CT_TextUnderlineLineFollowText(); else if (childNode.LocalName == "uLn") ctObj.uLn = CT_LineProperties.Parse(childNode, namespaceManager); else if (childNode.LocalName == "uFillTx") ctObj.uFillTx = new CT_TextUnderlineFillFollowText(); else if (childNode.LocalName == "uFill") ctObj.uFill = CT_TextUnderlineFillGroupWrapper.Parse(childNode, namespaceManager); else if (childNode.LocalName == "latin") ctObj.latin = CT_TextFont.Parse(childNode, namespaceManager); else if (childNode.LocalName == "ea") ctObj.ea = CT_TextFont.Parse(childNode, namespaceManager); else if (childNode.LocalName == "cs") ctObj.cs = CT_TextFont.Parse(childNode, namespaceManager); else if (childNode.LocalName == "sym") ctObj.sym = CT_TextFont.Parse(childNode, namespaceManager); else if (childNode.LocalName == "hlinkClick") ctObj.hlinkClick = CT_Hyperlink.Parse(childNode, namespaceManager); else if (childNode.LocalName == "hlinkMouseOver") ctObj.hlinkMouseOver = CT_Hyperlink.Parse(childNode, namespaceManager); else if (childNode.LocalName == "extLst") ctObj.extLst = CT_OfficeArtExtensionList.Parse(childNode, namespaceManager); } return ctObj; } internal void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<a:{0}", nodeName)); XmlHelper.WriteAttribute(sw, "kumimoji", this.kumimoji, false); XmlHelper.WriteAttribute(sw, "lang", this.lang); XmlHelper.WriteAttribute(sw, "altLang", this.altLang); XmlHelper.WriteAttribute(sw, "sz", this.sz); XmlHelper.WriteAttribute(sw, "b", this.b); if(i) XmlHelper.WriteAttribute(sw, "i", this.i); if(this.u!= ST_TextUnderlineType.none) XmlHelper.WriteAttribute(sw, "u", this.u.ToString()); if(strike!= ST_TextStrikeType.noStrike) XmlHelper.WriteAttribute(sw, "strike", this.strike.ToString()); XmlHelper.WriteAttribute(sw, "kern", this.kern); if(this.cap!= ST_TextCapsType.none) XmlHelper.WriteAttribute(sw, "cap", this.cap.ToString()); XmlHelper.WriteAttribute(sw, "spc", this.spc); XmlHelper.WriteAttribute(sw, "normalizeH", this.normalizeH, false); XmlHelper.WriteAttribute(sw, "baseline", this.baseline); XmlHelper.WriteAttribute(sw, "noProof", this.noProof, false); if (!dirty) XmlHelper.WriteAttribute(sw, "dirty", this.dirty); XmlHelper.WriteAttribute(sw, "err", this.err, false); if (!smtCleanField) XmlHelper.WriteAttribute(sw, "smtClean", this.smtClean); XmlHelper.WriteAttribute(sw, "smtId", this.smtId); XmlHelper.WriteAttribute(sw, "bmk", this.bmk); sw.Write(">"); if (this.ln != null) this.ln.Write(sw, "ln"); if (this.noFill != null) sw.Write("<a:noFill/>"); if (this.solidFill != null) this.solidFill.Write(sw, "solidFill"); if (this.gradFill != null) this.gradFill.Write(sw, "gradFill"); if (this.blipFill != null) this.blipFill.Write(sw, "a:blipFill"); if (this.pattFill != null) this.pattFill.Write(sw, "pattFill"); if (this.grpFill != null) sw.Write("<a:grpFill/>"); if (this.effectLst != null) this.effectLst.Write(sw, "effectLst"); if (this.effectDag != null) this.effectDag.Write(sw, "effectDag"); if (this.highlight != null) this.highlight.Write(sw, "highlight"); if (this.uLnTx != null) sw.Write("<a:uLnTx/>"); if (this.uLn != null) this.uLn.Write(sw, "uLn"); if (this.uFillTx != null) sw.Write("<a:uFillTx/>"); if (this.uFill != null) this.uFill.Write(sw, "uFill"); if (this.latin != null) this.latin.Write(sw, "latin"); if (this.ea != null) this.ea.Write(sw, "ea"); if (this.cs != null) this.cs.Write(sw, "cs"); if (this.sym != null) this.sym.Write(sw, "sym"); if (this.hlinkClick != null) this.hlinkClick.Write(sw, "hlinkClick"); if (this.hlinkMouseOver != null) this.hlinkMouseOver.Write(sw, "hlinkMouseOver"); if (this.extLst != null) this.extLst.Write(sw, "extLst"); sw.Write(string.Format("</a:{0}>", nodeName)); } public CT_TextCharacterProperties() { this.strike = ST_TextStrikeType.noStrike; this.dirtyField = true; this.errField = false; this.smtCleanField = true; this.smtIdField = ((uint)(0)); } [XmlElement(Order = 0)] public CT_LineProperties ln { get { return this.lnField; } set { this.lnField = value; } } [XmlElement(Order = 1)] public CT_NoFillProperties noFill { get { return this.noFillField; } set { this.noFillField = value; } } [XmlElement(Order = 2)] public CT_SolidColorFillProperties solidFill { get { return this.solidFillField; } set { this.solidFillField = value; } } [XmlElement(Order = 3)] public CT_GradientFillProperties gradFill { get { return this.gradFillField; } set { this.gradFillField = value; } } [XmlElement(Order = 4)] public CT_BlipFillProperties blipFill { get { return this.blipFillField; } set { this.blipFillField = value; } } [XmlElement(Order = 5)] public CT_PatternFillProperties pattFill { get { return this.pattFillField; } set { this.pattFillField = value; } } [XmlElement(Order = 6)] public CT_GroupFillProperties grpFill { get { return this.grpFillField; } set { this.grpFillField = value; } } [XmlElement(Order = 7)] public CT_EffectList effectLst { get { return this.effectLstField; } set { this.effectLstField = value; } } [XmlElement(Order = 8)] public CT_EffectContainer effectDag { get { return this.effectDagField; } set { this.effectDagField = value; } } [XmlElement(Order = 9)] public CT_Color highlight { get { return this.highlightField; } set { this.highlightField = value; } } [XmlElement(Order = 10)] public CT_TextUnderlineLineFollowText uLnTx { get { return this.uLnTxField; } set { this.uLnTxField = value; } } [XmlElement(Order = 11)] public CT_LineProperties uLn { get { return this.uLnField; } set { this.uLnField = value; } } [XmlElement(Order = 12)] public CT_TextUnderlineFillFollowText uFillTx { get { return this.uFillTxField; } set { this.uFillTxField = value; } } [XmlElement(Order = 13)] public CT_TextUnderlineFillGroupWrapper uFill { get { return this.uFillField; } set { this.uFillField = value; } } [XmlElement(Order = 14)] public CT_TextFont latin { get { return this.latinField; } set { this.latinField = value; } } [XmlElement(Order = 15)] public CT_TextFont ea { get { return this.eaField; } set { this.eaField = value; } } [XmlElement(Order = 16)] public CT_TextFont cs { get { return this.csField; } set { this.csField = value; } } [XmlElement(Order = 17)] public CT_TextFont sym { get { return this.symField; } set { this.symField = value; } } [XmlElement(Order = 18)] public CT_Hyperlink hlinkClick { get { return this.hlinkClickField; } set { this.hlinkClickField = value; } } [XmlElement(Order = 19)] public CT_Hyperlink hlinkMouseOver { get { return this.hlinkMouseOverField; } set { this.hlinkMouseOverField = value; } } [XmlElement(Order = 20)] public CT_OfficeArtExtensionList extLst { get { return this.extLstField; } set { this.extLstField = value; } } [XmlAttribute] public bool kumimoji { get { return this.kumimojiField; } set { this.kumimojiField = value; } } [XmlIgnore] public bool kumimojiSpecified { get { return this.kumimojiFieldSpecified; } set { this.kumimojiFieldSpecified = value; } } [XmlAttribute] public string lang { get { return this.langField; } set { this.langField = value; } } [XmlAttribute] public string altLang { get { return this.altLangField; } set { this.altLangField = value; } } [XmlAttribute] public int sz { get { return this.szField; } set { this.szField = value; } } [XmlIgnore] public bool szSpecified { get { return this.szFieldSpecified; } set { this.szFieldSpecified = value; } } [XmlAttribute] public bool b { get { return this.bField; } set { this.bField = value; } } [XmlIgnore] public bool bSpecified { get { return this.bFieldSpecified; } set { this.bFieldSpecified = value; } } [XmlAttribute] public bool i { get { return this.iField; } set { this.iField = value; } } [XmlIgnore] public bool iSpecified { get { return this.iFieldSpecified; } set { this.iFieldSpecified = value; } } [XmlAttribute] public ST_TextUnderlineType u { get { return this.uField; } set { this.uField = value; } } [XmlIgnore] public bool uSpecified { get { return this.uFieldSpecified; } set { this.uFieldSpecified = value; } } [XmlAttribute] public ST_TextStrikeType strike { get { return this.strikeField; } set { this.strikeField = value; } } [XmlIgnore] public bool strikeSpecified { get { return this.strikeFieldSpecified; } set { this.strikeFieldSpecified = value; } } [XmlAttribute] public int kern { get { return this.kernField; } set { this.kernField = value; } } [XmlIgnore] public bool kernSpecified { get { return this.kernFieldSpecified; } set { this.kernFieldSpecified = value; } } [XmlAttribute] public ST_TextCapsType cap { get { return this.capField; } set { this.capField = value; } } [XmlIgnore] public bool capSpecified { get { return this.capFieldSpecified; } set { this.capFieldSpecified = value; } } [XmlAttribute] public int spc { get { return this.spcField; } set { this.spcField = value; } } [XmlIgnore] public bool spcSpecified { get { return this.spcFieldSpecified; } set { this.spcFieldSpecified = value; } } [XmlAttribute] public bool normalizeH { get { return this.normalizeHField; } set { this.normalizeHField = value; } } [XmlIgnore] public bool normalizeHSpecified { get { return this.normalizeHFieldSpecified; } set { this.normalizeHFieldSpecified = value; } } [XmlAttribute] public int baseline { get { return this.baselineField; } set { this.baselineField = value; } } [XmlIgnore] public bool baselineSpecified { get { return this.baselineFieldSpecified; } set { this.baselineFieldSpecified = value; } } [XmlAttribute] public bool noProof { get { return this.noProofField; } set { this.noProofField = value; } } [XmlIgnore] public bool noProofSpecified { get { return this.noProofFieldSpecified; } set { this.noProofFieldSpecified = value; } } [XmlAttribute] [DefaultValue(true)] public bool dirty { get { return this.dirtyField; } set { this.dirtyField = value; } } [XmlAttribute] [DefaultValue(false)] public bool err { get { return this.errField; } set { this.errField = value; } } [XmlAttribute] [DefaultValue(true)] public bool smtClean { get { return this.smtCleanField; } set { this.smtCleanField = value; } } [XmlAttribute] [DefaultValue(typeof(uint), "0")] public uint smtId { get { return this.smtIdField; } set { this.smtIdField = value; } } [XmlAttribute] public string bmk { get { return this.bmkField; } set { this.bmkField = value; } } public CT_TextFont AddNewLatin() { this.latinField = new CT_TextFont(); return this.latinField; } public bool IsSetSolidFill() { return this.solidFill != null; } public CT_SolidColorFillProperties AddNewSolidFill() { this.solidFillField = new CT_SolidColorFillProperties(); return solidFillField; } public bool IsSetStrike() { return this.strikeFieldSpecified; } public bool IsSetBaseline() { return this.baselineFieldSpecified && this.baselineField != 0; } public bool IsSetB() { return this.bFieldSpecified; } public bool IsSetI() { return this.iFieldSpecified; } public bool IsSetU() { return this.uFieldSpecified; } public bool IsSetCap() { return this.capFieldSpecified; } public bool IsSetSz() { return this.szFieldSpecified; } public void UnsetSz() { this.szFieldSpecified = false; this.szField = 0; } public bool IsSetSpc() { return this.spcFieldSpecified; } public void UnsetSpc() { this.spcFieldSpecified = false; this.spcField = 0; } public bool IsSetLatin() { return this.latinField != null; } public void UnsetLatin() { this.latinField = null; } public bool IsSetCs() { return this.csField != null; } public void UnsetCs() { this.csField = null; } public bool IsSetSym() { return this.symField != null; } public void UnsetSym() { this.symField = null; } public CT_TextFont AddNewSym() { this.symField = new CT_TextFont(); return this.symField; } } [Serializable] [XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")] public enum ST_TextUnderlineType { /// <remarks/> none, /// <remarks/> words, /// <remarks/> sng, /// <remarks/> dbl, /// <remarks/> heavy, /// <remarks/> dotted, /// <remarks/> dottedHeavy, /// <remarks/> dash, /// <remarks/> dashHeavy, /// <remarks/> dashLong, /// <remarks/> dashLongHeavy, /// <remarks/> dotDash, /// <remarks/> dotDashHeavy, /// <remarks/> dotDotDash, /// <remarks/> dotDotDashHeavy, /// <remarks/> wavy, /// <remarks/> wavyHeavy, /// <remarks/> wavyDbl, } [Serializable] [XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")] public enum ST_TextStrikeType { /// <remarks/> noStrike, /// <remarks/> sngStrike, /// <remarks/> dblStrike, } [Serializable] [XmlType(Namespace = "http://schemas.openxmlformats.org/drawingml/2006/main")] public enum ST_TextCapsType { /// <remarks/> none, /// <remarks/> small, /// <remarks/> all, } }
26.802221
1,334
0.490886
[ "Apache-2.0" ]
Cy-Team/npoi
ooxml/OpenXmlFormats/Drawing/TextCharacter.cs
38,622
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 Microsoft.EntityFrameworkCore.Storage; namespace Microsoft.EntityFrameworkCore.Metadata { /// <summary> /// Represents a database function parameter in an <see cref="IDbFunction" />. /// </summary> public interface IDbFunctionParameter { /// <summary> /// Gets the <see cref="IDbFunction" /> to which this parameter belongs. /// </summary> IDbFunction Function { get; } /// <summary> /// Gets the parameter name. /// </summary> string Name { get; } /// <summary> /// Gets the parameter type. /// </summary> Type ClrType { get; } /// <summary> /// Gets the store type of this parameter. /// </summary> string StoreType { get; } /// <summary> /// Gets the <see cref="RelationalTypeMapping" /> for this parameter. /// </summary> RelationalTypeMapping TypeMapping { get; } } }
29.35
111
0.576661
[ "Apache-2.0" ]
computamike/efcore
src/EFCore.Relational/Metadata/IDbFunctionParameter.cs
1,174
C#
using UnityEngine; using UnityEngine.UI; using System.Collections; using MoreMountains.Tools; using System; using System.Collections.Generic; using UnityEngine.Tilemaps; namespace MoreMountains.Tools { /// <summary> /// A class to put on a tilemap so it acts as a shadow/copy of another reference tilemap. /// Useful for wall shadows for example. /// Offsetting the tilemap and changing its sorting order etc is done via the regular components /// </summary> [ExecuteAlways] [AddComponentMenu("More Mountains/Tools/Tilemaps/MMTilemapShadow")] [RequireComponent(typeof(Tilemap))] public class MMTilemapShadow : MonoBehaviour { /// the tilemap to copy public Tilemap ReferenceTilemap; [MMInspectorButton("UpdateShadows")] public bool UpdateShadowButton; protected Tilemap _tilemap; /// <summary> /// This method will copy the reference tilemap into the one on this gameobject /// </summary> protected virtual void UpdateShadows() { if (ReferenceTilemap == null) { return; } _tilemap = this.gameObject.GetComponent<Tilemap>(); List<Vector3Int> referenceTilemapPositions = new List<Vector3Int>(); // we grab all filled positions from the ref tilemap foreach (var pos in ReferenceTilemap.cellBounds.allPositionsWithin) { Vector3Int localPlace = new Vector3Int(pos.x, pos.y, pos.z); if (ReferenceTilemap.HasTile(localPlace)) { referenceTilemapPositions.Add(localPlace); } } // we turn our list into an array Vector3Int[] positions = new Vector3Int[referenceTilemapPositions.Count]; TileBase[] allTiles = new TileBase[referenceTilemapPositions.Count]; int i = 0; foreach(Vector3Int tilePosition in referenceTilemapPositions) { positions[i] = tilePosition; allTiles[i] = ReferenceTilemap.GetTile(tilePosition); i++; } // we clear our tilemap and resize it _tilemap.ClearAllTiles(); _tilemap.RefreshAllTiles(); _tilemap.size = ReferenceTilemap.size; _tilemap.origin = ReferenceTilemap.origin; _tilemap.ResizeBounds(); // we feed it our positions _tilemap.SetTiles(positions, allTiles); } } }
35.368421
101
0.580729
[ "Apache-2.0" ]
notFR/Game-Economics-Template
Assets/ThirdParty/LoadingScene/MMTools/Tools/Tilemaps/MMTilemapShadow.cs
2,690
C#
/* * VRChat API Documentation * * * The version of the OpenAPI document: 1.6.7 * Contact: [email protected] * 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 = VRChat.API.Client.OpenAPIDateConverter; namespace VRChat.API.Model { /// <summary> /// ModerateUserRequest /// </summary> [DataContract(Name = "ModerateUserRequest")] public partial class ModerateUserRequest : IEquatable<ModerateUserRequest>, IValidatableObject { /// <summary> /// Gets or Sets Type /// </summary> [DataMember(Name = "type", IsRequired = true, EmitDefaultValue = false)] public PlayerModerationType Type { get; set; } /// <summary> /// Initializes a new instance of the <see cref="ModerateUserRequest" /> class. /// </summary> [JsonConstructorAttribute] protected ModerateUserRequest() { } /// <summary> /// Initializes a new instance of the <see cref="ModerateUserRequest" /> class. /// </summary> /// <param name="moderated">A users unique ID, usually in the form of &#x60;usr_c1644b5b-3ca4-45b4-97c6-a2a0de70d469&#x60;. Legacy players can have old IDs in the form of &#x60;8JoV9XEdpo&#x60;. The ID can never be changed. (required).</param> /// <param name="type">type (required).</param> public ModerateUserRequest(string moderated = default(string), PlayerModerationType type = default(PlayerModerationType)) { // to ensure "moderated" is required (not null) if (moderated == null) { throw new ArgumentNullException("moderated is a required property for ModerateUserRequest and cannot be null"); } this.Moderated = moderated; this.Type = type; } /// <summary> /// A users unique ID, usually in the form of &#x60;usr_c1644b5b-3ca4-45b4-97c6-a2a0de70d469&#x60;. Legacy players can have old IDs in the form of &#x60;8JoV9XEdpo&#x60;. The ID can never be changed. /// </summary> /// <value>A users unique ID, usually in the form of &#x60;usr_c1644b5b-3ca4-45b4-97c6-a2a0de70d469&#x60;. Legacy players can have old IDs in the form of &#x60;8JoV9XEdpo&#x60;. The ID can never be changed.</value> [DataMember(Name = "moderated", IsRequired = true, EmitDefaultValue = false)] public string Moderated { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ModerateUserRequest {\n"); sb.Append(" Moderated: ").Append(Moderated).Append("\n"); sb.Append(" Type: ").Append(Type).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 ModerateUserRequest); } /// <summary> /// Returns true if ModerateUserRequest instances are equal /// </summary> /// <param name="input">Instance of ModerateUserRequest to be compared</param> /// <returns>Boolean</returns> public bool Equals(ModerateUserRequest input) { if (input == null) return false; return ( this.Moderated == input.Moderated || (this.Moderated != null && this.Moderated.Equals(input.Moderated)) ) && ( this.Type == input.Type || this.Type.Equals(input.Type) ); } /// <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.Moderated != null) hashCode = hashCode * 59 + this.Moderated.GetHashCode(); hashCode = hashCode * 59 + this.Type.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; } } }
37.726667
251
0.593921
[ "MIT" ]
vrchatapi/vrchatapi-csharp
src/VRChat.API/Model/ModerateUserRequest.cs
5,659
C#
using System; using System.Net.Http; using System.Security.Claims; using System.Threading.Tasks; using System.Web.Mvc; namespace GymLog.Client.Controllers { public class MusclesController : Controller { /* HttpClient client; string url = GymLogConstants.API + "api/muscles"; public MusclesController() { client = new HttpClient() { BaseAddress = new Uri(url), }; client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); }*/ /* public async Task<ActionResult> Index() { HttpResponseMessage responseMessage = await client.GetAsync(url); if (responseMessage.IsSuccessStatusCode) { var responseData = responseMessage.Content.ReadAsStringAsync().Result; var muscles = JsonConvert.DeserializeObject<List<MuscleModel>>(responseData); return View(muscles); } return Content("An error occurred."); }*/ /* private async Task<String> Index() { var user = User as ClaimsPrincipal; var token = user.FindFirst("access_token").Value; var client = new HttpClient(); client.SetBearerToken(token); HttpResponseMessage response = await client.GetAsync(GymLogConstants.API+ "api/muscles"); return await response.Content.ReadAsStringAsync(); }*/ } }
32.125
109
0.619326
[ "MIT" ]
piters3/GymLogIdServ
GymLog.Client/Controllers/MusclesController.cs
1,544
C#
using System.Collections.Generic; namespace AndreyAndBilliard { class Customer { public string Name { get; set; } public Dictionary<string, int> ShopList { get; set; } public decimal Bill { get; set; } } }
17.571429
61
0.617886
[ "MIT" ]
Iliyan7/SoftUni
ProgrammingFundamentals/Objects_and_Classes-Exercises/AndreyAndBilliard/Customer.cs
248
C#
using System; namespace STTClient.Models { /// <summary> /// Wrapper of the pointer used for the decoding stream. /// </summary> public class Stream : IDisposable { private unsafe IntPtr** _streamingStatePp; /// <summary> /// Initializes a new instance of <see cref="Stream"/>. /// </summary> /// <param name="streamingStatePP">Native pointer of the native stream.</param> public unsafe Stream(IntPtr** streamingStatePP) { _streamingStatePp = streamingStatePP; } /// <summary> /// Gets the native pointer. /// </summary> /// <exception cref="InvalidOperationException">Thrown when the stream has been disposed or not yet initialized.</exception> /// <returns>Native pointer of the stream.</returns> internal unsafe IntPtr** GetNativePointer() { if (_streamingStatePp == null) throw new InvalidOperationException("Cannot use a disposed or uninitialized stream."); return _streamingStatePp; } public unsafe void Dispose() => _streamingStatePp = null; } }
32.5
132
0.607692
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AigizK/STT
native_client/dotnet/STTClient/Models/Stream.cs
1,172
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading.Tasks; using BaselineTypeDiscovery; using LamarCodeGeneration.Util; using Microsoft.Extensions.DependencyInjection; #pragma warning disable 1591 [assembly:IgnoreAssembly] namespace Lamar.Scanning.Conventions { [LamarIgnore] public class AssemblyScanner : IAssemblyScanner { private readonly List<Assembly> _assemblies = new List<Assembly>(); private readonly CompositeFilter<Type> _filter = new CompositeFilter<Type>(); private readonly ServiceRegistry _parent; public AssemblyScanner(ServiceRegistry parent) { _parent = parent; Exclude(type => type.HasAttribute<LamarIgnoreAttribute>()); } public List<IRegistrationConvention> Conventions { get; } = new List<IRegistrationConvention>(); public Task<TypeSet> TypeFinder { get; private set; } public string Description { get; set; } public void Assembly(Assembly assembly) { if (!_assemblies.Contains(assembly)) _assemblies.Add(assembly); } public void Assembly(string assemblyName) { Assembly(AssemblyLoader.ByName(assemblyName)); } public void Convention<T>() where T : IRegistrationConvention, new() { var previous = Conventions.FirstOrDefault(scanner => scanner is T); if (previous == null) With(new T()); } public void AssemblyContainingType<T>() { AssemblyContainingType(typeof(T)); } public void AssemblyContainingType(Type type) { _assemblies.Add(type.GetTypeInfo().Assembly); } public FindAllTypesFilter AddAllTypesOf<TServiceType>() { return AddAllTypesOf(typeof(TServiceType), ServiceLifetime.Transient); } public FindAllTypesFilter AddAllTypesOf<TServiceType>(ServiceLifetime lifetime) { return AddAllTypesOf(typeof(TServiceType), lifetime); } public FindAllTypesFilter AddAllTypesOf(Type pluginType) { return AddAllTypesOf(pluginType, ServiceLifetime.Transient); } public FindAllTypesFilter AddAllTypesOf(Type pluginType, ServiceLifetime lifetime) { var filter = new FindAllTypesFilter(pluginType, lifetime); With(filter); return filter; } public void Exclude(Func<Type, bool> exclude) { _filter.Excludes += exclude; } public void ExcludeNamespace(string nameSpace) { Exclude(type => type.IsInNamespace(nameSpace)); } public void ExcludeNamespaceContainingType<T>() { ExcludeNamespace(typeof(T).Namespace); } public void Include(Func<Type, bool> predicate) { _filter.Includes += predicate; } public void IncludeNamespace(string nameSpace) { Include(type => type.IsInNamespace(nameSpace)); } public void IncludeNamespaceContainingType<T>() { IncludeNamespace(typeof(T).Namespace); } public void ExcludeType<T>() { Exclude(type => type == typeof(T)); } public void With(IRegistrationConvention convention) { Conventions.Fill(convention); } public void WithDefaultConventions() { WithDefaultConventions(ServiceLifetime.Transient); } public void WithDefaultConventions(ServiceLifetime lifetime) { var convention = new DefaultConventionScanner(lifetime); With(convention); } public void WithDefaultConventions(OverwriteBehavior behavior) { WithDefaultConventions(behavior, ServiceLifetime.Transient); } public void WithDefaultConventions(OverwriteBehavior behavior, ServiceLifetime lifetime) { var convention = new DefaultConventionScanner(lifetime) { Overwrites = behavior }; With(convention); } public void ConnectImplementationsToTypesClosing(Type openGenericType) { ConnectImplementationsToTypesClosing(openGenericType, ServiceLifetime.Transient); } public void ConnectImplementationsToTypesClosing(Type openGenericType, ServiceLifetime lifetime) { var convention = new GenericConnectionScanner(openGenericType, lifetime); With(convention); } public void RegisterConcreteTypesAgainstTheFirstInterface() { RegisterConcreteTypesAgainstTheFirstInterface(ServiceLifetime.Transient); } public void RegisterConcreteTypesAgainstTheFirstInterface(ServiceLifetime lifetime) { var convention = new FirstInterfaceConvention(lifetime); With(convention); } public void SingleImplementationsOfInterface() { SingleImplementationsOfInterface(ServiceLifetime.Transient); } public void SingleImplementationsOfInterface(ServiceLifetime lifetime) { var convention = new ImplementationMap(lifetime); With(convention); } public void LookForRegistries() { Convention<FindRegistriesScanner>(); } public void TheCallingAssembly() { if (_parent.GetType().Assembly != typeof(ServiceRegistry).Assembly) { Assembly(_parent.GetType().Assembly); return; } var callingAssembly = CallingAssembly.Find(); if (callingAssembly != null) Assembly(callingAssembly); else throw new InvalidOperationException( "Could not determine the calling assembly, you may need to explicitly call IAssemblyScanner.Assembly()"); } public void AssembliesFromApplicationBaseDirectory() { AssembliesFromApplicationBaseDirectory(a => true); } public void AssembliesFromApplicationBaseDirectory(Func<Assembly, bool> assemblyFilter) { var assemblies = AssemblyFinder.FindAssemblies(assemblyFilter, txt => { Console.WriteLine("Jasper could not load assembly from file " + txt); }); foreach (var assembly in assemblies) Assembly(assembly); } /// <summary> /// Choosing option will direct Jasper to *also* scan files ending in '*.exe' /// </summary> /// <param name="scanner"></param> /// <param name="assemblyFilter"></param> /// <param name="includeExeFiles"></param> public void AssembliesAndExecutablesFromApplicationBaseDirectory(Func<Assembly, bool> assemblyFilter = null) { var assemblies = AssemblyFinder.FindAssemblies(assemblyFilter, txt => { Console.WriteLine("Jasper could not load assembly from file " + txt); }, true); foreach (var assembly in assemblies) Assembly(assembly); } [Obsolete("It is very strongly recommended to use the overload with an Assembly filter to improve performance")] public void AssembliesAndExecutablesFromPath(string path) { var assemblies = AssemblyFinder.FindAssemblies(a => true, path, txt => { Console.WriteLine("Jasper could not load assembly from file " + txt); }, true); foreach (var assembly in assemblies) Assembly(assembly); } [Obsolete("It is very strongly recommended to use the overload with an Assembly filter to improve performance")] public void AssembliesFromPath(string path) { var assemblies = AssemblyFinder.FindAssemblies(a => true, path, txt => { Console.WriteLine("Jasper could not load assembly from file " + txt); }, false); foreach (var assembly in assemblies) Assembly(assembly); } public void AssembliesAndExecutablesFromPath(string path, Func<Assembly, bool> assemblyFilter) { var assemblies = AssemblyFinder.FindAssemblies(assemblyFilter, path, txt => { Console.WriteLine("Jasper could not load assembly from file " + txt); }, true); foreach (var assembly in assemblies) Assembly(assembly); } public void AssembliesFromPath(string path, Func<Assembly, bool> assemblyFilter) { var assemblies = AssemblyFinder.FindAssemblies(assemblyFilter, path, txt => { Console.WriteLine("Jasper could not load assembly from file " + txt); }, false); foreach (var assembly in assemblies) Assembly(assembly); } public void Describe(StringWriter writer) { writer.WriteLine(Description); writer.WriteLine("Assemblies"); writer.WriteLine("----------"); _assemblies.OrderBy(x => x.FullName).Each(x => writer.WriteLine("* " + x)); writer.WriteLine(); writer.WriteLine("Conventions"); writer.WriteLine("--------"); Conventions.Each(x => writer.WriteLine("* " + x)); } public void Start() { if (!Conventions.Any()) throw new InvalidOperationException( $"There are no {nameof(IRegistrationConvention)}'s in this scanning operation. "); TypeFinder = TypeRepository.FindTypes(_assemblies, type => _filter.Matches(type)); } public void ApplyRegistrations(ServiceRegistry services) { foreach (var convention in Conventions) { convention.ScanTypes(TypeFinder.Result, services); } } public bool Contains(string assemblyName) { return _assemblies .Select(assembly => new AssemblyName(assembly.FullName)) .Any(aName => aName.Name == assemblyName); } } } #pragma warning restore 1591
32.41433
125
0.607689
[ "MIT" ]
JasperFx/lamar
src/Lamar/Scanning/Conventions/AssemblyScanner.cs
10,405
C#
/* Poly2Tri * Copyright (c) 2009-2010, Poly2Tri Contributors * http://code.google.com/p/poly2tri/ * * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Poly2Tri nor the names of its contributors may be * used to endorse or promote products derived from this software without specific * prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Poly2Tri { /** * @author Thomas Åhlén, [email protected] */ public class TriangulationUtil { public const double EPSILON = 1e-12; /// <summary> /// Requirements: /// 1. a,b and c form a triangle. /// 2. a and d is know to be on opposite side of bc /// <code> /// a /// + /// / \ /// / \ /// b/ \c /// +-------+ /// / B \ /// / \ /// </code> /// Facts: /// d has to be in area B to have a chance to be inside the circle formed by a,b and c /// d is outside B if orient2d(a,b,d) or orient2d(c,a,d) is CW /// This preknowledge gives us a way to optimize the incircle test /// </summary> /// <param name="pa">triangle point, opposite d</param> /// <param name="pb">triangle point</param> /// <param name="pc">triangle point</param> /// <param name="pd">point opposite a</param> /// <returns>true if d is inside circle, false if on circle edge</returns> public static bool SmartInCircle(TriangulationPoint pa, TriangulationPoint pb, TriangulationPoint pc, TriangulationPoint pd) { double pdx = pd.X; double pdy = pd.Y; double adx = pa.X - pdx; double ady = pa.Y - pdy; double bdx = pb.X - pdx; double bdy = pb.Y - pdy; double adxbdy = adx * bdy; double bdxady = bdx * ady; double oabd = adxbdy - bdxady; // oabd = orient2d(pa,pb,pd); if (oabd <= 0) return false; double cdx = pc.X - pdx; double cdy = pc.Y - pdy; double cdxady = cdx * ady; double adxcdy = adx * cdy; double ocad = cdxady - adxcdy; // ocad = orient2d(pc,pa,pd); if (ocad <= 0) return false; double bdxcdy = bdx * cdy; double cdxbdy = cdx * bdy; double alift = adx * adx + ady * ady; double blift = bdx * bdx + bdy * bdy; double clift = cdx * cdx + cdy * cdy; double det = alift * (bdxcdy - cdxbdy) + blift * ocad + clift * oabd; return det > 0; } public static bool InScanArea(TriangulationPoint pa, TriangulationPoint pb, TriangulationPoint pc, TriangulationPoint pd) { double pdx = pd.X; double pdy = pd.Y; double adx = pa.X - pdx; double ady = pa.Y - pdy; double bdx = pb.X - pdx; double bdy = pb.Y - pdy; double adxbdy = adx * bdy; double bdxady = bdx * ady; double oabd = adxbdy - bdxady; // oabd = orient2d(pa,pb,pd); if (oabd <= 0) { return false; } double cdx = pc.X - pdx; double cdy = pc.Y - pdy; double cdxady = cdx * ady; double adxcdy = adx * cdy; double ocad = cdxady - adxcdy; // ocad = orient2d(pc,pa,pd); return ocad > 0; //if (ocad <= 0) //{ // return false; //} //return true; } /// Forumla to calculate signed area /// Positive if CCW /// Negative if CW /// 0 if collinear /// A[P1,P2,P3] = (x1*y2 - y1*x2) + (x2*y3 - y2*x3) + (x3*y1 - y3*x1) /// = (x1-x3)*(y2-y3) - (y1-y3)*(x2-x3) public static Orientation Orient2d(TriangulationPoint pa, TriangulationPoint pb, TriangulationPoint pc) { double detleft = (pa.X - pc.X) * (pb.Y - pc.Y); double detright = (pa.Y - pc.Y) * (pb.X - pc.X); double val = detleft - detright; if (val > -EPSILON && val < EPSILON) { return Orientation.Collinear; } else if (val > 0) { return Orientation.CCW; } return Orientation.CW; } } }
40.668919
133
0.524173
[ "BSD-3-Clause" ]
PaintLab/poly2tri-cs
Triangulation/TriangulationUtil.cs
6,023
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.HybridData.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Error Details /// </summary> public partial class ErrorDetails { /// <summary> /// Initializes a new instance of the ErrorDetails class. /// </summary> public ErrorDetails() { CustomInit(); } /// <summary> /// Initializes a new instance of the ErrorDetails class. /// </summary> /// <param name="errorMessage">Error message.</param> /// <param name="errorCode">Error code.</param> /// <param name="recommendedAction">Recommended action for the /// error.</param> /// <param name="exceptionMessage">Contains the non localized exception /// message</param> public ErrorDetails(string errorMessage = default(string), int? errorCode = default(int?), string recommendedAction = default(string), string exceptionMessage = default(string)) { ErrorMessage = errorMessage; ErrorCode = errorCode; RecommendedAction = recommendedAction; ExceptionMessage = exceptionMessage; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets error message. /// </summary> [JsonProperty(PropertyName = "errorMessage")] public string ErrorMessage { get; set; } /// <summary> /// Gets or sets error code. /// </summary> [JsonProperty(PropertyName = "errorCode")] public int? ErrorCode { get; set; } /// <summary> /// Gets or sets recommended action for the error. /// </summary> [JsonProperty(PropertyName = "recommendedAction")] public string RecommendedAction { get; set; } /// <summary> /// Gets or sets contains the non localized exception message /// </summary> [JsonProperty(PropertyName = "exceptionMessage")] public string ExceptionMessage { get; set; } } }
33.179487
185
0.6051
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/hybriddatamanager/Microsoft.Azure.Management.HybridDataManager/src/Generated/Models/ErrorDetails.cs
2,588
C#
using System; using NHapi.Base.Model; using NHapi.Base.Log; using NHapi.Base; using NHapi.Base.Model.Primitive; namespace NHapi.Model.V25.Datatype { ///<summary> /// <p>The HL7 DLT (Delta) data type. Consists of the following components: </p><ol> /// <li>Normal Range (NR)</li> /// <li>Numeric Threshold (NM)</li> /// <li>Change Computation (ID)</li> /// <li>Days Retained (NM)</li> /// </ol> ///</summary> [Serializable] public class DLT : AbstractType, IComposite{ private IType[] data; ///<summary> /// Creates a DLT. /// <param name="message">The Message to which this Type belongs</param> ///</summary> public DLT(IMessage message) : this(message, null){} ///<summary> /// Creates a DLT. /// <param name="message">The Message to which this Type belongs</param> /// <param name="description">The description of this type</param> ///</summary> public DLT(IMessage message, string description) : base(message, description){ data = new IType[4]; data[0] = new NR(message,"Normal Range"); data[1] = new NM(message,"Numeric Threshold"); data[2] = new ID(message, 523,"Change Computation"); data[3] = new NM(message,"Days Retained"); } ///<summary> /// Returns an array containing the data elements. ///</summary> public IType[] Components { get{ return this.data; } } ///<summary> /// Returns an individual data component. /// @throws DataTypeException if the given element number is out of range. ///<param name="index">The index item to get (zero based)</param> ///<returns>The data component (as a type) at the requested number (ordinal)</returns> ///</summary> public IType this[int index] { get{ try { return this.data[index]; } catch (System.ArgumentOutOfRangeException) { throw new DataTypeException("Element " + index + " doesn't exist in 4 element DLT composite"); } } } ///<summary> /// Returns Normal Range (component #0). This is a convenience method that saves you from /// casting and handling an exception. ///</summary> public NR NormalRange { get{ NR ret = null; try { ret = (NR)this[0]; } catch (DataTypeException e) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem accessing known data type component - this is a bug.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns Numeric Threshold (component #1). This is a convenience method that saves you from /// casting and handling an exception. ///</summary> public NM NumericThreshold { get{ NM ret = null; try { ret = (NM)this[1]; } catch (DataTypeException e) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem accessing known data type component - this is a bug.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns Change Computation (component #2). This is a convenience method that saves you from /// casting and handling an exception. ///</summary> public ID ChangeComputation { get{ ID ret = null; try { ret = (ID)this[2]; } catch (DataTypeException e) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem accessing known data type component - this is a bug.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns Days Retained (component #3). This is a convenience method that saves you from /// casting and handling an exception. ///</summary> public NM DaysRetained { get{ NM ret = null; try { ret = (NM)this[3]; } catch (DataTypeException e) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem accessing known data type component - this is a bug.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } }}
30.059259
134
0.641695
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
afaonline/nHapi
src/NHapi.Model.V25/Datatype/DLT.cs
4,058
C#
namespace JL.Core.Dicts.CustomWordDict; public class CustomWordEntry : IResult { public string PrimarySpelling { get; } public List<string>? AlternativeSpellings { get; } public List<string>? Readings { get; } public List<string> Definitions { get; } public List<string> WordClasses { get; } public CustomWordEntry(string primarySpelling, List<string>? alternativeSpellings, List<string>? readings, List<string> definitions, List<string> wordClasses) { PrimarySpelling = primarySpelling; AlternativeSpellings = alternativeSpellings; Readings = readings; Definitions = definitions; WordClasses = wordClasses; } public override bool Equals(object? obj) { if (obj == null) return false; CustomWordEntry customWordEntryObj = (obj as CustomWordEntry)!; return PrimarySpelling == customWordEntryObj.PrimarySpelling && ((customWordEntryObj.AlternativeSpellings?.SequenceEqual(AlternativeSpellings ?? new())) ?? AlternativeSpellings == null) && ((customWordEntryObj.Readings?.SequenceEqual(Readings ?? new())) ?? Readings == null) && customWordEntryObj.Definitions.SequenceEqual(Definitions) && customWordEntryObj.WordClasses.SequenceEqual(WordClasses); } public override int GetHashCode() { unchecked { int hash = 17; hash = hash * 37 + PrimarySpelling.GetHashCode(); if (AlternativeSpellings != null) { foreach (string spelling in AlternativeSpellings) hash = hash * 37 + spelling.GetHashCode(); } else { hash *= 37; } if (Readings != null) { foreach (string readings in Readings) hash = hash * 37 + readings.GetHashCode(); } else { hash *= 37; } foreach (string definition in Definitions) hash = hash * 37 + definition.GetHashCode(); foreach (string wordClass in WordClasses) hash = hash * 37 + wordClass.GetHashCode(); return hash; } } }
30.84
139
0.573714
[ "Apache-2.0" ]
rampaa/JL
JL.Core/Dicts/CustomWordDict/CustomWordEntry.cs
2,315
C#
using System; using Org.BouncyCastle.Asn1.X509; namespace Org.BouncyCastle.Asn1.Cmp { public class CmpCertificate : Asn1Encodable, IAsn1Choice { private readonly X509CertificateStructure x509v3PKCert; private readonly AttributeCertificate x509v2AttrCert; /** * Note: the addition of attribute certificates is a BC extension. */ public CmpCertificate(AttributeCertificate x509v2AttrCert) { this.x509v2AttrCert = x509v2AttrCert; } public CmpCertificate(X509CertificateStructure x509v3PKCert) { if (x509v3PKCert.Version != 3) throw new ArgumentException(@"only version 3 certificates allowed", "x509v3PKCert"); this.x509v3PKCert = x509v3PKCert; } public static CmpCertificate GetInstance(object obj) { if (obj is CmpCertificate) return (CmpCertificate)obj; if (obj is Asn1Sequence) return new CmpCertificate(X509CertificateStructure.GetInstance(obj)); if (obj is Asn1TaggedObject) return new CmpCertificate(AttributeCertificate.GetInstance(((Asn1TaggedObject)obj).GetObject())); throw new ArgumentException("Invalid object: " + obj.GetType().Name, "obj"); } public virtual bool IsX509v3PKCert { get { return x509v3PKCert != null; } } public virtual X509CertificateStructure X509v3PKCert { get { return x509v3PKCert; } } public virtual AttributeCertificate X509v2AttrCert { get { return x509v2AttrCert; } } /** * <pre> * CMPCertificate ::= CHOICE { * x509v3PKCert Certificate * x509v2AttrCert [1] AttributeCertificate * } * </pre> * Note: the addition of attribute certificates is a BC extension. * * @return a basic ASN.1 object representation. */ public override Asn1Object ToAsn1Object() { if (x509v2AttrCert != null) { // explicit following CMP conventions return new DerTaggedObject(true, 1, x509v2AttrCert); } return x509v3PKCert.ToAsn1Object(); } } }
29.580247
113
0.579716
[ "MIT" ]
SchmooseSA/Schmoose-BouncyCastle
Crypto/asn1/cmp/CmpCertificate.cs
2,398
C#
using System; using System.IO; using System.Text; using System.Collections.Generic; using InvokeIR.Win32; namespace InvokeIR.PowerForensics.Ntfs { #region UsnJrnlClass public class UsnJrnl { #region Enums [FlagsAttribute] public enum USN_REASON : uint { DATA_OVERWRITE = 0x00000001, DATA_EXTEND = 0x00000002, DATA_TRUNCATION = 0x00000004, NAMED_DATA_OVERWRITE = 0x00000010, NAMED_DATA_EXTEND = 0x00000020, NAMED_DATA_TRUNCATION = 0x00000040, FILE_CREATE = 0x00000100, FILE_DELETE = 0x00000200, EA_CHANGE = 0x00000400, SECURITY_CHANGE = 0x00000800, RENAME_OLD_NAME = 0x00001000, RENAME_NEW_NAME = 0x00002000, INDEXABLE_CHANGE = 0x00004000, BASIC_INFO_CHANGE = 0x00008000, HARD_LINK_CHANGE = 0x00010000, COMPRESSION_CHANGE = 0x00020000, ENCRYPTION_CHANGE = 0x00040000, OBJECT_ID_CHANGE = 0x00080000, REPARSE_POINT_CHANGE = 0x00100000, STREAM_CHANGE = 0x00200000, CLOSE = 0x80000000 } [FlagsAttribute] public enum USN_SOURCE : uint { DATA_MANAGEMENT = 0x00000001, AUXILIARY_DATA = 0x00000002, REPLICATION_MANAGEMENT = 0x00000004 } #endregion Enums #region Properties private readonly static Version USN40Version = new Version(4, 0); public readonly string VolumePath; public readonly Version Version; public readonly ulong RecordNumber; public readonly ushort FileSequenceNumber; public readonly ulong ParentFileRecordNumber; public readonly ushort ParentFileSequenceNumber; public readonly ulong Usn; public readonly DateTime TimeStamp; public readonly USN_REASON Reason; public readonly USN_SOURCE SourceInfo; public readonly uint SecurityId; public readonly StandardInformation.ATTR_STDINFO_PERMISSION FileAttributes; public readonly string FileName; #endregion Properties #region Constructors internal UsnJrnl(byte[] bytes, string volume, ref int offset) { uint RecordLength = RecordLength = BitConverter.ToUInt32(bytes, (0x00 + offset)); VolumePath = volume; Version = new System.Version(BitConverter.ToUInt16(bytes, (0x04 + offset)), BitConverter.ToUInt16(bytes, (0x06 + offset))); RecordNumber = (BitConverter.ToUInt64(bytes, (0x08 + offset)) & 0x0000FFFFFFFFFFFF); FileSequenceNumber = ParentFileSequenceNumber = BitConverter.ToUInt16(bytes, (0x0E + offset)); ParentFileRecordNumber = (BitConverter.ToUInt64(bytes, (0x10 + offset)) & 0x0000FFFFFFFFFFFF); ParentFileSequenceNumber = BitConverter.ToUInt16(bytes, (0x16 + offset)); Usn = BitConverter.ToUInt64(bytes, (0x18 + offset)); TimeStamp = DateTime.FromFileTimeUtc(BitConverter.ToInt64(bytes, (0x20 + offset))); Reason = ((USN_REASON)BitConverter.ToUInt32(bytes, (0x28 + offset))); SourceInfo = ((USN_SOURCE)BitConverter.ToUInt32(bytes, (0x2C + offset))); SecurityId = BitConverter.ToUInt32(bytes, (0x30 + offset)); FileAttributes = ((StandardInformation.ATTR_STDINFO_PERMISSION)BitConverter.ToUInt32(bytes, (0x34 + offset))); ushort fileNameLength = BitConverter.ToUInt16(bytes, (0x38 + offset)); ushort fileNameOffset = BitConverter.ToUInt16(bytes, (0x3A + offset)); FileName = Encoding.Unicode.GetString(bytes, 0x3C + offset, fileNameLength); offset += (int)RecordLength; } #endregion Constructors #region StaticMethods public static UsnJrnl Get(string volume, ulong usn) { // Check for valid Volume name NativeMethods.getVolumeName(ref volume); // Set up FileStream to read volume IntPtr hVolume = NativeMethods.getHandle(volume); FileStream streamToRead = NativeMethods.getFileStream(hVolume); // Get VolumeBootRecord object for logical addressing VolumeBootRecord VBR = VolumeBootRecord.Get(streamToRead); // Get the $J Data attribute (contains UsnJrnl details NonResident J = UsnJrnl.GetJStream(UsnJrnl.GetFileRecord(volume)); // Determine the length of the initial sparse pages ulong SparseLength = (ulong)J.DataRun[0].ClusterLength * VBR.BytesPerCluster; // Subtract length of sparse data from desired usn offset ulong usnOffset = usn - SparseLength; // Iterate through each data run for (int i = 1; i < J.DataRun.Length; i++) { // Determine length of current DataRun ulong dataRunLength = (ulong)J.DataRun[i].ClusterLength * VBR.BytesPerCluster; // Check if usnOffset resides in current DataRun if (dataRunLength <= usnOffset) { // If not, subtract length of DataRun from usnOffset usnOffset -= dataRunLength; } // If usnOffset resides within DataRun, parse associated UsnJrnl Entry else { // Read DataRun from disk byte[] fragmentBytes = NativeMethods.readDrive(streamToRead, ((ulong)J.DataRun[i].StartCluster * VBR.BytesPerCluster), ((ulong)J.DataRun[i].ClusterLength * VBR.BytesPerCluster)); // Instatiate a byte array that is the size of a single cluster byte[] clusterBytes = new byte[VBR.BytesPerCluster]; // Iterate through the clusters in the DataRun for (long j = 0; j < J.DataRun[i].ClusterLength; j++) { // If usnOffset is not in current cluster, then subtract cluster size from offset and iterate if (VBR.BytesPerCluster <= usnOffset) { usnOffset -= VBR.BytesPerCluster; } // Else if usnOffset is in current cluster else { // Copy current cluster bytes to clusterBytes variable Array.Copy(fragmentBytes, ((long)j * VBR.BytesPerCluster), clusterBytes, 0, clusterBytes.Length); // Parse desired UsnJrnl entry from cluster int offset = (int)usnOffset; return new UsnJrnl(clusterBytes, volume, ref offset); } } } } return null; } public static UsnJrnl[] GetInstances(string volume) { // Check for valid Volume name NativeMethods.getVolumeName(ref volume); // Set up FileStream to read volume IntPtr hVolume = NativeMethods.getHandle(volume); FileStream streamToRead = NativeMethods.getFileStream(hVolume); // Get VolumeBootRecord object for logical addressing VolumeBootRecord VBR = VolumeBootRecord.Get(streamToRead); // Get the $J Data attribute (contains UsnJrnl details NonResident J = UsnJrnl.GetJStream(UsnJrnl.GetFileRecord(volume)); List<UsnJrnl> usnList = new List<UsnJrnl>(); for (int i = 0; i < J.DataRun.Length; i++) { if (!(J.DataRun[i].Sparse)) { long clusterCount = J.DataRun[i].ClusterLength; byte[] fragmentBytes = NativeMethods.readDrive(streamToRead, ((ulong)J.DataRun[i].StartCluster * VBR.BytesPerCluster), ((ulong)clusterCount * VBR.BytesPerCluster)); byte[] clusterBytes = new byte[VBR.BytesPerCluster]; for (long j = 0; j < clusterCount; j++) { Array.Copy(fragmentBytes, ((long)j * VBR.BytesPerCluster), clusterBytes, 0, clusterBytes.Length); int offset = 0; do { if (clusterBytes[offset] == 0) { break; } try { UsnJrnl usn = new UsnJrnl(clusterBytes, volume, ref offset); if (usn.Version > USN40Version) { break; } usnList.Add(usn); } catch { break; } } while (offset >= 0 && offset < clusterBytes.Length); } } } return usnList.ToArray(); } internal static FileRecord GetFileRecord(string volume) { string volLetter = volume.Split('\\')[3]; ulong index = IndexEntry.Get(volLetter + "\\$Extend\\$UsnJrnl").RecordNumber; return new FileRecord(FileRecord.GetRecordBytes(volume, (int)index), volume, true); } internal static NonResident GetJStream(FileRecord fileRecord) { foreach (Attr attr in fileRecord.Attribute) { if (attr.NameString == "$J") { return attr as NonResident; } } throw new Exception("No $J attribute found."); } internal static Data GetMaxStream(FileRecord fileRecord) { foreach (Attr attr in fileRecord.Attribute) { if (attr.NameString == "$Max") { return attr as Data; } } throw new Exception("No $MAX attribute found."); } #endregion StaticMethods #region InstanceMethods public FileRecord GetFileRecord() { FileRecord record = new FileRecord(FileRecord.GetRecordBytes(this.VolumePath, (int)this.RecordNumber), this.VolumePath); if (record.SequenceNumber == this.FileSequenceNumber) { return record; } else { throw new Exception("Desired FileRecord has been overwritten"); } } public FileRecord GetParentFileRecord() { FileRecord record = new FileRecord(FileRecord.GetRecordBytes(this.VolumePath, (int)this.ParentFileRecordNumber), this.VolumePath); if (record.SequenceNumber == this.ParentFileSequenceNumber) { return record; } else { throw new Exception("Desired FileRecord has been overwritten"); } } #endregion InstanceMethods } #endregion USNJrnlClass #region UsnJrnlDetailClass public class UsnJrnlDetail { #region Properties public ulong MaxSize; public ulong AllocationDelta; public ulong UsnId; public ulong LowestUsn; #endregion Properties #region Constructors internal UsnJrnlDetail(byte[] maxBytes) { MaxSize = BitConverter.ToUInt64(maxBytes, 0x00); AllocationDelta = BitConverter.ToUInt64(maxBytes, 0x08); UsnId = BitConverter.ToUInt64(maxBytes, 0x10); LowestUsn = BitConverter.ToUInt64(maxBytes, 0x18); } #endregion Constructors } #endregion UsnJrnlDetailClass }
37.70405
198
0.55102
[ "Apache-2.0" ]
0x0mar/PowerForensics_Source
Invoke-IR.PowerForensics/PowerForensics/FileSystems/NTFS/MetadataFiles/11 - $Extend/UsnJrnl.cs
12,105
C#
using System; using Foundation.StateMachine; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Foundation.Tests.StateMachine { [TestClass] public class StateTransitionTests { [TestMethod, ExpectedException(typeof(InvalidOperationException))] public void IsValid_throws_InvalidOperationException_if_InputValidator_is_null() { var transition = new StateTransition<string, string>(); transition.IsValid("test"); } } }
28.722222
89
0.692456
[ "Apache-2.0" ]
DavidMoore/Foundation
Tests/UnitTests/Foundation.Tests/StateMachine/StateTransitionTests.cs
517
C#
namespace ErrorsAndPatterns { public sealed class Ignore { private static readonly Ignore use = new Ignore(); public static Ignore Use() => Ignore.use; private Ignore() { } } }
20.666667
52
0.704301
[ "MIT" ]
JasonBock/ExceptionalDevelopment
Exceptions/ErrorsAndPatterns/Ignore.cs
188
C#
// // Copyright (c) Microsoft. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Microsoft.Azure.Commands.ApiManagement.ServiceManagement.Models { using System; using System.Text.RegularExpressions; public class PsApiManagementGatewayHostnameConfiguration : PsApiManagementArmResource { static readonly Regex GatewayHostnameConfigurationIdRegex = new Regex(@"(.*?)/providers/microsoft.apimanagement/service/(?<serviceName>[^/]+)/gateways/(?<gatewayId>[^/]+)/hostnameConfigurations/(?<hcId>[^/]+)", RegexOptions.IgnoreCase); public string Hostname { get; set; } public string CertificateResourceId { get; set; } public bool? NegotiateClientCertificate { get; set; } public string GatewayId { get; set; } public string GatewayHostnameConfigurationId { get; set; } public PsApiManagementGatewayHostnameConfiguration() { } public PsApiManagementGatewayHostnameConfiguration(string armResourceId) { this.Id = armResourceId; var match = GatewayHostnameConfigurationIdRegex.Match(Id); if (match.Success) { var gatewayIdRegexResult = match.Groups["gatewayId"]; var hcIdRegexResult = match.Groups["hcId"]; if (gatewayIdRegexResult != null && gatewayIdRegexResult.Success && hcIdRegexResult != null && hcIdRegexResult.Success) { this.GatewayId = gatewayIdRegexResult.Value; this.GatewayHostnameConfigurationId = hcIdRegexResult.Value; return; } } throw new ArgumentException($"ResourceId {armResourceId} is not a valid GatewayHostnameConfiguration Id."); } } }
41.736842
245
0.654897
[ "MIT" ]
3quanfeng/azure-powershell
src/ApiManagement/ApiManagement.ServiceManagement/Models/PsApiManagementGatewayHostnameConfiguration.cs
2,325
C#
using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using VueExample.Models; using VueExample.ServiceModels; namespace VueExample.Providers { public class DefectiveDieProvider { public string GetByDangerLevel(List<Defect> defectList, DangerLevel dangerLevel) { var dieIdList = defectList.Where(x => x.DangerLevelId == dangerLevel.DangerLevelId).Select(x => x.DieId).Distinct() .ToList(); var defectiveDiesList = new List<DefectiveDie>(); foreach (var dieId in dieIdList) defectiveDiesList.Add(new DefectiveDie {DieId = dieId, HexColor = dangerLevel.Color}); return JsonConvert.SerializeObject(defectiveDiesList); } public string GetBadByDefectType(List<Defect> defectList, DefectType defectType, DangerLevel dangerLevel) { var dieIdList = defectList.Where(x => x.DangerLevelId == dangerLevel.DangerLevelId && x.DefectTypeId == defectType.DefectTypeId) .Select(x => x.DieId).Distinct().ToList(); var defectiveDiesList = new List<DefectiveDie>(); foreach (var dieId in dieIdList) defectiveDiesList.Add(new DefectiveDie {DieId = dieId, HexColor = defectType.Color}); return JsonConvert.SerializeObject(defectiveDiesList); } } }
42.84375
140
0.670314
[ "MIT" ]
7is7/SVR2.0
Providers/DefectiveDieProvider.cs
1,371
C#
using MediatR; using PromotionSales.Api.Application.Common.EntitiesDto; namespace PromotionSales.Api.Application.PromotionApplication.Queries.GetByFilters; public sealed class GetPromotionByIdQuery : IRequest<PromotionDto> { public Guid Id { get; set; } }
26.3
83
0.813688
[ "MIT" ]
RandhHaven/PromotionSales
src/PromotionSales.Api.Application/PromotionApplication/Queries/GetByFilters/GetPromotionByIdQuery.cs
265
C#
// <auto-generated/> // Contents of: hl7.fhir.r3.core version: 3.0.2 using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Hl7.Fhir.Introspection; using Hl7.Fhir.Serialization; using Hl7.Fhir.Specification; using Hl7.Fhir.Utility; using Hl7.Fhir.Validation; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Hl7.Fhir.Model { /// <summary> /// EnrollmentResponse resource /// </summary> [Serializable] [DataContract] [FhirType("EnrollmentResponse", IsResource=true)] public partial class EnrollmentResponse : Hl7.Fhir.Model.DomainResource { /// <summary> /// FHIR Type Name /// </summary> public override string TypeName { get { return "EnrollmentResponse"; } } /// <summary> /// Business Identifier /// </summary> [FhirElement("identifier", Order=90)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Identifier> Identifier { get { if(_Identifier==null) _Identifier = new List<Hl7.Fhir.Model.Identifier>(); return _Identifier; } set { _Identifier = value; OnPropertyChanged("Identifier"); } } private List<Hl7.Fhir.Model.Identifier> _Identifier; /// <summary> /// active | cancelled | draft | entered-in-error /// </summary> [FhirElement("status", InSummary=true, Order=100)] [DataMember] public Code<Hl7.Fhir.Model.FinancialResourceStatusCodes> StatusElement { get { return _StatusElement; } set { _StatusElement = value; OnPropertyChanged("StatusElement"); } } private Code<Hl7.Fhir.Model.FinancialResourceStatusCodes> _StatusElement; /// <summary> /// active | cancelled | draft | entered-in-error /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [IgnoreDataMember] public Hl7.Fhir.Model.FinancialResourceStatusCodes? Status { get { return StatusElement != null ? StatusElement.Value : null; } set { if (value == null) StatusElement = null; else StatusElement = new Code<Hl7.Fhir.Model.FinancialResourceStatusCodes>(value); OnPropertyChanged("Status"); } } /// <summary> /// Claim reference /// </summary> [FhirElement("request", Order=110)] [CLSCompliant(false)] [References("EnrollmentRequest")] [DataMember] public Hl7.Fhir.Model.ResourceReference Request { get { return _Request; } set { _Request = value; OnPropertyChanged("Request"); } } private Hl7.Fhir.Model.ResourceReference _Request; /// <summary> /// complete | error | partial /// </summary> [FhirElement("outcome", Order=120)] [DataMember] public Hl7.Fhir.Model.CodeableConcept Outcome { get { return _Outcome; } set { _Outcome = value; OnPropertyChanged("Outcome"); } } private Hl7.Fhir.Model.CodeableConcept _Outcome; /// <summary> /// Disposition Message /// </summary> [FhirElement("disposition", Order=130)] [DataMember] public Hl7.Fhir.Model.FhirString DispositionElement { get { return _DispositionElement; } set { _DispositionElement = value; OnPropertyChanged("DispositionElement"); } } private Hl7.Fhir.Model.FhirString _DispositionElement; /// <summary> /// Disposition Message /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [IgnoreDataMember] public string Disposition { get { return DispositionElement != null ? DispositionElement.Value : null; } set { if (value == null) DispositionElement = null; else DispositionElement = new Hl7.Fhir.Model.FhirString(value); OnPropertyChanged("Disposition"); } } /// <summary> /// Creation date /// </summary> [FhirElement("created", Order=140)] [DataMember] public Hl7.Fhir.Model.FhirDateTime CreatedElement { get { return _CreatedElement; } set { _CreatedElement = value; OnPropertyChanged("CreatedElement"); } } private Hl7.Fhir.Model.FhirDateTime _CreatedElement; /// <summary> /// Creation date /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [IgnoreDataMember] public string Created { get { return CreatedElement != null ? CreatedElement.Value : null; } set { if (value == null) CreatedElement = null; else CreatedElement = new Hl7.Fhir.Model.FhirDateTime(value); OnPropertyChanged("Created"); } } /// <summary> /// Insurer /// </summary> [FhirElement("organization", Order=150)] [CLSCompliant(false)] [References("Organization")] [DataMember] public Hl7.Fhir.Model.ResourceReference Organization { get { return _Organization; } set { _Organization = value; OnPropertyChanged("Organization"); } } private Hl7.Fhir.Model.ResourceReference _Organization; /// <summary> /// Responsible practitioner /// </summary> [FhirElement("requestProvider", Order=160)] [CLSCompliant(false)] [References("Practitioner")] [DataMember] public Hl7.Fhir.Model.ResourceReference RequestProvider { get { return _RequestProvider; } set { _RequestProvider = value; OnPropertyChanged("RequestProvider"); } } private Hl7.Fhir.Model.ResourceReference _RequestProvider; /// <summary> /// Responsible organization /// </summary> [FhirElement("requestOrganization", Order=170)] [CLSCompliant(false)] [References("Organization")] [DataMember] public Hl7.Fhir.Model.ResourceReference RequestOrganization { get { return _RequestOrganization; } set { _RequestOrganization = value; OnPropertyChanged("RequestOrganization"); } } private Hl7.Fhir.Model.ResourceReference _RequestOrganization; public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as EnrollmentResponse; if (dest == null) { throw new ArgumentException("Can only copy to an object of the same type", "other"); } base.CopyTo(dest); if(Identifier != null) dest.Identifier = new List<Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy()); if(StatusElement != null) dest.StatusElement = (Code<Hl7.Fhir.Model.FinancialResourceStatusCodes>)StatusElement.DeepCopy(); if(Request != null) dest.Request = (Hl7.Fhir.Model.ResourceReference)Request.DeepCopy(); if(Outcome != null) dest.Outcome = (Hl7.Fhir.Model.CodeableConcept)Outcome.DeepCopy(); if(DispositionElement != null) dest.DispositionElement = (Hl7.Fhir.Model.FhirString)DispositionElement.DeepCopy(); if(CreatedElement != null) dest.CreatedElement = (Hl7.Fhir.Model.FhirDateTime)CreatedElement.DeepCopy(); if(Organization != null) dest.Organization = (Hl7.Fhir.Model.ResourceReference)Organization.DeepCopy(); if(RequestProvider != null) dest.RequestProvider = (Hl7.Fhir.Model.ResourceReference)RequestProvider.DeepCopy(); if(RequestOrganization != null) dest.RequestOrganization = (Hl7.Fhir.Model.ResourceReference)RequestOrganization.DeepCopy(); return dest; } public override IDeepCopyable DeepCopy() { return CopyTo(new EnrollmentResponse()); } public override bool Matches(IDeepComparable other) { var otherT = other as EnrollmentResponse; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(Identifier, otherT.Identifier)) return false; if( !DeepComparable.Matches(StatusElement, otherT.StatusElement)) return false; if( !DeepComparable.Matches(Request, otherT.Request)) return false; if( !DeepComparable.Matches(Outcome, otherT.Outcome)) return false; if( !DeepComparable.Matches(DispositionElement, otherT.DispositionElement)) return false; if( !DeepComparable.Matches(CreatedElement, otherT.CreatedElement)) return false; if( !DeepComparable.Matches(Organization, otherT.Organization)) return false; if( !DeepComparable.Matches(RequestProvider, otherT.RequestProvider)) return false; if( !DeepComparable.Matches(RequestOrganization, otherT.RequestOrganization)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as EnrollmentResponse; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(Identifier, otherT.Identifier)) return false; if( !DeepComparable.IsExactly(StatusElement, otherT.StatusElement)) return false; if( !DeepComparable.IsExactly(Request, otherT.Request)) return false; if( !DeepComparable.IsExactly(Outcome, otherT.Outcome)) return false; if( !DeepComparable.IsExactly(DispositionElement, otherT.DispositionElement)) return false; if( !DeepComparable.IsExactly(CreatedElement, otherT.CreatedElement)) return false; if( !DeepComparable.IsExactly(Organization, otherT.Organization)) return false; if( !DeepComparable.IsExactly(RequestProvider, otherT.RequestProvider)) return false; if( !DeepComparable.IsExactly(RequestOrganization, otherT.RequestOrganization)) return false; return true; } [IgnoreDataMember] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; foreach (var elem in Identifier) { if (elem != null) yield return elem; } if (StatusElement != null) yield return StatusElement; if (Request != null) yield return Request; if (Outcome != null) yield return Outcome; if (DispositionElement != null) yield return DispositionElement; if (CreatedElement != null) yield return CreatedElement; if (Organization != null) yield return Organization; if (RequestProvider != null) yield return RequestProvider; if (RequestOrganization != null) yield return RequestOrganization; } } [IgnoreDataMember] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; foreach (var elem in Identifier) { if (elem != null) yield return new ElementValue("identifier", elem); } if (StatusElement != null) yield return new ElementValue("status", StatusElement); if (Request != null) yield return new ElementValue("request", Request); if (Outcome != null) yield return new ElementValue("outcome", Outcome); if (DispositionElement != null) yield return new ElementValue("disposition", DispositionElement); if (CreatedElement != null) yield return new ElementValue("created", CreatedElement); if (Organization != null) yield return new ElementValue("organization", Organization); if (RequestProvider != null) yield return new ElementValue("requestProvider", RequestProvider); if (RequestOrganization != null) yield return new ElementValue("requestOrganization", RequestOrganization); } } } } // end of file
37.348837
130
0.689212
[ "MIT" ]
FirelyTeam/fhir-codegen
generated/CSharpFirely2_R3/Generated/EnrollmentResponse.cs
12,848
C#
//*********************************************************// // Copyright (c) Microsoft. All rights reserved. // // Apache 2.0 License // // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or // implied. See the License for the specific language governing // permissions and limitations under the License. // //*********************************************************// using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; using ShellConstants = Microsoft.VisualStudio.Shell.Interop.Constants; namespace Microsoft.VisualStudioTools.Project { internal abstract class ProjectDocumentsListener : IVsTrackProjectDocumentsEvents2, IDisposable { #region fields private uint eventsCookie; private IVsTrackProjectDocuments2 projectDocTracker; private ServiceProvider serviceProvider; private bool isDisposed; /// <summary> /// Defines an object that will be a mutex for this object for synchronizing thread calls. /// </summary> private static volatile object Mutex = new object(); #endregion #region ctors protected ProjectDocumentsListener(ServiceProvider serviceProviderParameter) { Utilities.ArgumentNotNull("serviceProviderParameter", serviceProviderParameter); this.serviceProvider = serviceProviderParameter; this.projectDocTracker = this.serviceProvider.GetService(typeof(SVsTrackProjectDocuments)) as IVsTrackProjectDocuments2; Utilities.CheckNotNull(this.projectDocTracker, "Could not get the IVsTrackProjectDocuments2 object from the services exposed by this project"); } #endregion #region properties protected uint EventsCookie { get { return this.eventsCookie; } } protected IVsTrackProjectDocuments2 ProjectDocumentTracker2 { get { return this.projectDocTracker; } } protected ServiceProvider ServiceProvider { get { return this.serviceProvider; } } #endregion #region IVsTrackProjectDocumentsEvents2 Members public virtual int OnAfterAddDirectoriesEx(int cProjects, int cDirectories, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgpszMkDocuments, VSADDDIRECTORYFLAGS[] rgFlags) { return VSConstants.E_NOTIMPL; } public virtual int OnAfterAddFilesEx(int cProjects, int cFiles, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgpszMkDocuments, VSADDFILEFLAGS[] rgFlags) { return VSConstants.E_NOTIMPL; } public virtual int OnAfterRemoveDirectories(int cProjects, int cDirectories, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgpszMkDocuments, VSREMOVEDIRECTORYFLAGS[] rgFlags) { return VSConstants.E_NOTIMPL; } public virtual int OnAfterRemoveFiles(int cProjects, int cFiles, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgpszMkDocuments, VSREMOVEFILEFLAGS[] rgFlags) { return VSConstants.E_NOTIMPL; } public virtual int OnAfterRenameDirectories(int cProjects, int cDirs, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgszMkOldNames, string[] rgszMkNewNames, VSRENAMEDIRECTORYFLAGS[] rgFlags) { return VSConstants.E_NOTIMPL; } public virtual int OnAfterRenameFiles(int cProjects, int cFiles, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgszMkOldNames, string[] rgszMkNewNames, VSRENAMEFILEFLAGS[] rgFlags) { return VSConstants.E_NOTIMPL; } public virtual int OnAfterSccStatusChanged(int cProjects, int cFiles, IVsProject[] rgpProjects, int[] rgFirstIndices, string[] rgpszMkDocuments, uint[] rgdwSccStatus) { return VSConstants.E_NOTIMPL; } public virtual int OnQueryAddDirectories(IVsProject pProject, int cDirectories, string[] rgpszMkDocuments, VSQUERYADDDIRECTORYFLAGS[] rgFlags, VSQUERYADDDIRECTORYRESULTS[] pSummaryResult, VSQUERYADDDIRECTORYRESULTS[] rgResults) { return VSConstants.E_NOTIMPL; } public virtual int OnQueryAddFiles(IVsProject pProject, int cFiles, string[] rgpszMkDocuments, VSQUERYADDFILEFLAGS[] rgFlags, VSQUERYADDFILERESULTS[] pSummaryResult, VSQUERYADDFILERESULTS[] rgResults) { return VSConstants.E_NOTIMPL; } public virtual int OnQueryRemoveDirectories(IVsProject pProject, int cDirectories, string[] rgpszMkDocuments, VSQUERYREMOVEDIRECTORYFLAGS[] rgFlags, VSQUERYREMOVEDIRECTORYRESULTS[] pSummaryResult, VSQUERYREMOVEDIRECTORYRESULTS[] rgResults) { return VSConstants.E_NOTIMPL; } public virtual int OnQueryRemoveFiles(IVsProject pProject, int cFiles, string[] rgpszMkDocuments, VSQUERYREMOVEFILEFLAGS[] rgFlags, VSQUERYREMOVEFILERESULTS[] pSummaryResult, VSQUERYREMOVEFILERESULTS[] rgResults) { return VSConstants.E_NOTIMPL; } public virtual int OnQueryRenameDirectories(IVsProject pProject, int cDirs, string[] rgszMkOldNames, string[] rgszMkNewNames, VSQUERYRENAMEDIRECTORYFLAGS[] rgFlags, VSQUERYRENAMEDIRECTORYRESULTS[] pSummaryResult, VSQUERYRENAMEDIRECTORYRESULTS[] rgResults) { return VSConstants.E_NOTIMPL; } public virtual int OnQueryRenameFiles(IVsProject pProject, int cFiles, string[] rgszMkOldNames, string[] rgszMkNewNames, VSQUERYRENAMEFILEFLAGS[] rgFlags, VSQUERYRENAMEFILERESULTS[] pSummaryResult, VSQUERYRENAMEFILERESULTS[] rgResults) { return VSConstants.E_NOTIMPL; } #endregion #region IDisposable Members /// <summary> /// The IDispose interface Dispose method for disposing the object determinastically. /// </summary> public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } #endregion #region methods public void Init() { if (this.ProjectDocumentTracker2 != null) { ErrorHandler.ThrowOnFailure(this.ProjectDocumentTracker2.AdviseTrackProjectDocumentsEvents(this, out this.eventsCookie)); } } /// <summary> /// The method that does the cleanup. /// </summary> /// <param name="disposing"></param> protected virtual void Dispose(bool disposing) { // Everybody can go here. if (!this.isDisposed) { // Synchronize calls to the Dispose simulteniously. lock (Mutex) { if (disposing && this.eventsCookie != (uint)ShellConstants.VSCOOKIE_NIL && this.ProjectDocumentTracker2 != null) { this.ProjectDocumentTracker2.UnadviseTrackProjectDocumentsEvents((uint)this.eventsCookie); this.eventsCookie = (uint)ShellConstants.VSCOOKIE_NIL; } this.isDisposed = true; } } } #endregion } }
45.707317
265
0.673959
[ "MIT" ]
Muraad/VisualRust
Microsoft.VisualStudio.Project/ProjectDocumentsListener.cs
7,496
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace RawTextureManager.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("RawTextureManager.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
43.703125
183
0.614945
[ "Unlicense" ]
libertyernie/RawTextureManager
Properties/Resources.Designer.cs
2,799
C#
using System.Threading; using System.Threading.Tasks; using MediatR; using Microshoppy.Warehouse.Repositories; namespace Microshoppy.Warehouse.CQRS.Command { public class DeleteWarehouseProductCommandHandler : Handler, IRequestHandler<DeleteWarehouseProductCommand, Unit> { public DeleteWarehouseProductCommandHandler(IWarehouseRepository repo) : base(repo) { } public Task<Unit> Handle(DeleteWarehouseProductCommand request, CancellationToken cancellationToken) { _repo.DeleteProduct(request.ProductId); return Task.FromResult(Unit.Value); } } }
27.190476
114
0.810858
[ "MIT" ]
micro-shoppy/warehouse
Microshoppy.Warehouse/src/CQRS/Command/DeleteWarehouseProductCommandHandler.cs
573
C#
 namespace MineCrypto { partial class AES { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AES)); this.button2 = new System.Windows.Forms.Button(); this.textBox4 = new System.Windows.Forms.TextBox(); this.textBox3 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.textBox1 = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.checkBox1 = new System.Windows.Forms.CheckBox(); this.button3 = new System.Windows.Forms.Button(); this.button4 = new System.Windows.Forms.Button(); this.checkBox2 = new System.Windows.Forms.CheckBox(); this.button5 = new System.Windows.Forms.Button(); this.SuspendLayout(); // // button2 // this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button2.Location = new System.Drawing.Point(46, 216); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(149, 42); this.button2.TabIndex = 15; this.button2.Text = "Decrypt"; this.button2.UseVisualStyleBackColor = true; this.button2.Click += new System.EventHandler(this.button2_Click); // // textBox4 // this.textBox4.Location = new System.Drawing.Point(107, 162); this.textBox4.Name = "textBox4"; this.textBox4.Size = new System.Drawing.Size(1124, 26); this.textBox4.TabIndex = 14; // // textBox3 // this.textBox3.Location = new System.Drawing.Point(107, 120); this.textBox3.Name = "textBox3"; this.textBox3.Size = new System.Drawing.Size(1124, 26); this.textBox3.TabIndex = 13; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(107, 73); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(1124, 26); this.textBox2.TabIndex = 12; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(107, 30); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(1124, 26); this.textBox1.TabIndex = 11; // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(12, 168); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(86, 20); this.label4.TabIndex = 7; this.label4.Text = "Decrypted:"; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(12, 123); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(85, 20); this.label3.TabIndex = 8; this.label3.Text = "Encrypted:"; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(12, 76); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(90, 20); this.label2.TabIndex = 9; this.label2.Text = "To Decrypt:"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 33); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(89, 20); this.label1.TabIndex = 10; this.label1.Text = "To Encrypt:"; // // button1 // this.button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button1.Location = new System.Drawing.Point(308, 216); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(146, 42); this.button1.TabIndex = 16; this.button1.Text = "Encrypt"; this.button1.UseVisualStyleBackColor = true; this.button1.Click += new System.EventHandler(this.button1_Click); // // checkBox1 // this.checkBox1.AutoSize = true; this.checkBox1.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.checkBox1.Location = new System.Drawing.Point(518, 225); this.checkBox1.Name = "checkBox1"; this.checkBox1.Size = new System.Drawing.Size(250, 24); this.checkBox1.TabIndex = 17; this.checkBox1.Text = "Add another layer of encryption"; this.checkBox1.UseVisualStyleBackColor = true; // // button3 // this.button3.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button3.Location = new System.Drawing.Point(436, 290); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(232, 42); this.button3.TabIndex = 18; this.button3.Text = "Press me First"; this.button3.UseVisualStyleBackColor = true; this.button3.Click += new System.EventHandler(this.button3_Click); // // button4 // this.button4.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button4.Font = new System.Drawing.Font("Microsoft Sans Serif", 8F); this.button4.Location = new System.Drawing.Point(35, 284); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(315, 48); this.button4.TabIndex = 19; this.button4.Text = "What Another Layer Means?"; this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.button4_Click); // // checkBox2 // this.checkBox2.AutoSize = true; this.checkBox2.Location = new System.Drawing.Point(797, 224); this.checkBox2.Name = "checkBox2"; this.checkBox2.Size = new System.Drawing.Size(394, 24); this.checkBox2.TabIndex = 20; this.checkBox2.Text = "make the original string a binary for extra protection"; this.checkBox2.UseVisualStyleBackColor = true; this.checkBox2.CheckedChanged += new System.EventHandler(this.checkBox2_CheckedChanged); // // button5 // this.button5.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button5.Location = new System.Drawing.Point(720, 290); this.button5.Name = "button5"; this.button5.Size = new System.Drawing.Size(237, 42); this.button5.TabIndex = 21; this.button5.Text = "Encrypt File"; this.button5.UseVisualStyleBackColor = true; this.button5.Click += new System.EventHandler(this.button5_Click); // // AES // this.AutoScaleDimensions = new System.Drawing.SizeF(9F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1243, 344); this.Controls.Add(this.button5); this.Controls.Add(this.checkBox2); this.Controls.Add(this.button4); this.Controls.Add(this.button3); this.Controls.Add(this.checkBox1); this.Controls.Add(this.button1); this.Controls.Add(this.button2); this.Controls.Add(this.textBox4); this.Controls.Add(this.textBox3); this.Controls.Add(this.textBox2); this.Controls.Add(this.textBox1); this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MaximumSize = new System.Drawing.Size(1265, 400); this.MinimumSize = new System.Drawing.Size(1265, 400); this.Name = "AES"; this.Text = "AES"; this.Load += new System.EventHandler(this.AES_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button button2; private System.Windows.Forms.TextBox textBox4; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button1; private System.Windows.Forms.CheckBox checkBox1; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button4; private System.Windows.Forms.CheckBox checkBox2; private System.Windows.Forms.Button button5; } }
45.157025
136
0.55765
[ "CC0-1.0" ]
MinegamesAdministrationTool-zz/CryptoPrivacy
MineCrypto/AESForm.Designer.cs
10,930
C#
using System.Collections.Generic; using System.IO; using System.Linq; using Jotunn.Entities; using Jotunn.Managers; using UnityEngine; namespace JotunnDoc.Docs { public class CharacterDoc : Doc { public CharacterDoc() : base("prefabs/character-list.md") { On.Player.OnSpawned += DocCharacters; } private void DocCharacters(On.Player.orig_OnSpawned orig, Player self) { orig(self); if (Generated) { return; } var imageDirectory = Path.Combine(DocumentationDirConfig.Value, "images/characters"); Directory.CreateDirectory(imageDirectory); Jotunn.Logger.LogInfo("Documenting characters"); AddHeader(1, "Character list"); AddText("All of the Character prefabs currently in the game."); AddText("This file is automatically generated from Valheim using the JotunnDoc mod found on our GitHub."); AddTableHeader("Name", "Components"); List<GameObject> allPrefabs = new List<GameObject>(); allPrefabs.AddRange(ZNetScene.instance.m_nonNetViewPrefabs); allPrefabs.AddRange(ZNetScene.instance.m_prefabs); foreach (GameObject obj in allPrefabs.Where(x => !CustomPrefab.IsCustomPrefab(x.name) && x.GetComponent<Character>() != null).OrderBy(x => x.name)) { string name = obj.name; if (RequestSprite(Path.Combine(imageDirectory, $"{name}.png"), obj, RenderManager.IsometricRotation)) { name += $"<br><img src=\"../../images/characters/{name}.png\">"; } string components = "<ul>"; foreach (Component comp in obj.GetComponents<Component>()) { components += "<li>" + comp.GetType().Name + "</li>"; } components += "</ul>"; AddTableRow( name, components ); } Save(); } } }
31.955224
159
0.545072
[ "MIT" ]
heinermann/Jotunn
JotunnDoc/Docs/CharacterDoc.cs
2,143
C#
using SS.Common.BuldingBlocks; using SS.Common.Exceptions; using SS.Organizations.Domain.Exceptions; using SS.Organizations.Domain.Roles; using System; using System.Collections.Generic; using System.Linq; namespace SS.Organizations.Domain.Rules { public class CanUserBeChangedRule : IBusinessRule { private readonly HashSet<User> _users; private readonly Guid _id; private readonly Role _role; public CanUserBeChangedRule(HashSet<User> users, Guid id, Role role) { _users = users; _id = id; _role = role; } public SSException Exception => new RoleException("You cannot change the user role to the same role",HttpErrorCodes.NotAllowed ,InternalErrorCodes.Userhasthesamerole); public bool isBroken() { var user = _users.FirstOrDefault(p => p.Id == _id); if(user.Role != _role) { return false; } return true; } } }
28.333333
175
0.62549
[ "MIT" ]
KamilKarpus/SecretStorage
src/SS.Organization.Domain/Rules/CanUserBeChangedRule.cs
1,022
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace UniversalWindowsExample { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; // For this application to work you will need a trial license. // The MyAppKeyPair.snk linked in the project is not present in the repository, // you should generate your own strong name key and keep it private. // // 1) You can generate a strong name key with the following command in the Visual Studio command prompt: // sn -k MyKeyPair.snk // // 2) The next step is to extract the public key file from the strong name key (which is a key pair): // sn -p MyKeyPair.snk MyPublicKey.snk // // 3) Display the public key token for the public key: // sn -t MyPublicKey.snk // // 4) Go to the project properties Singing tab, and check the "Sign the assembly" checkbox, // and choose the strong name key you created. // // 5) Register and get your trial license from https://www.woutware.com/SoftwareLicenses. // Enter your strong name key public key token that you got at step 3. WW.WWLicense.SetLicense("<license string>"); } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (e.PrelaunchActivated == false) { if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
42.206612
116
0.607793
[ "MIT" ]
snowmiqi/WW.Cad.NetStandard.Examples
UniversalWindowsExample/App.xaml.cs
5,109
C#
/* Copyright (c) Perpetual Intelligence L.L.C. All Rights Reserved. For license, terms, and data policies, go to: https://terms.perpetualintelligence.com */ using PerpetualIntelligence.Shared.Attributes; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; namespace PerpetualIntelligence.Protocols.Security.Certificates { /// <summary> /// The <see cref="X509Certificate2"/> store for OAuth and OpenID Connect protocols. /// </summary> /// <seealso cref="X509Certificate2"/> /// <seealso cref="StoreLocation"/> /// <seealso cref="StoreName"/> [WriteUnitTest] public class X509Store { /// <summary> /// The X.509 certificate store used by <see cref="StoreLocation.CurrentUser"/>. /// </summary> public static X509Store CurrentUser => new(StoreLocation.CurrentUser); /// <summary> /// The X.509 certificate store assigned to <see cref="StoreLocation.LocalMachine"/>. /// </summary> public static X509Store LocalMachine => new(StoreLocation.LocalMachine); /// <summary> /// Finds the <see cref="X509Certificate2"/> based in the specified <see cref="X509FindType"/>. /// </summary> /// <param name="storeName">The <see cref="StoreName"/>.</param> /// <param name="findType">The <see cref="X509FindType"/>.</param> /// <param name="findValue">The find value.</param> /// <param name="validOnly">The find value validity.</param> /// <returns></returns> public IEnumerable<X509Certificate2> Find(StoreName storeName, X509FindType findType, object findValue, bool validOnly = true) { using (System.Security.Cryptography.X509Certificates.X509Store store = new(storeName, Location)) { store.Open(OpenFlags.ReadOnly); X509Certificate2Collection certColl = store.Certificates.Find(findType, findValue, validOnly); return certColl.Cast<X509Certificate2>(); } } /// <summary> /// Initializes a new instance with the specified <see cref="StoreLocation"/>. /// </summary> /// <param name="location">The X.509 <see cref="StoreLocation"/>.</param> private X509Store(StoreLocation location) { Location = location; } private StoreLocation Location { get; } } }
37.969231
134
0.632901
[ "Apache-2.0" ]
perpetualintelligence/protocols
src/PerpetualIntelligence.Protocols/Security/Certificates/X509Store.cs
2,470
C#
using System; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Skimur.Data.ReadModel; using Skimur.Web.Services; using Skimur.Web.ViewModels.Subs; using Skimur.Messaging; using Skimur.Data.Commands; using Skimur.Web.Infrastructure; using Skimur.Web.ViewModels; using Skimur.Common.Utils; using Skimur.Data.Services; using Skimur.Settings; using Skimur.Data.Settings; namespace Skimur.Web.Controllers { public class SubsController : BaseController { private readonly IContextService _contextService; private readonly ISubDao _subDao; private readonly IMapper _mapper; private readonly ICommandBus _commandBus; private readonly IUserContext _userContext; private readonly IPostDao _postDao; private readonly IVoteDao _voteDao; private readonly ICommentDao _commentDao; private readonly IPermissionDao _permissionDao; private readonly ICommentNodeHierarchyBuilder _commentNodeHierarchyBuilder; private readonly ICommentTreeContextBuilder _commentTreeContextBuilder; private readonly IPostWrapper _postwrapper; private readonly ISubWrapper _subwrapper; private readonly ICommentWrapper _commentWrapper; private readonly IMembershipService _membershiipService; private readonly ISettingsProvider<SubSettings> _subSettings; private readonly ISubActivityDao _subActivityDao; private readonly IModerationDao _moderationDao; public SubsController(IContextService contextService, ISubDao subDao, IMapper mapper, ICommandBus commandBus, IUserContext userContext, IPostDao postDao, IVoteDao voteDao, ICommentDao commentDao, IPermissionDao permissionDao, ICommentNodeHierarchyBuilder commentNodeHierarchyBuilder, ICommentTreeContextBuilder commentTreeContextBuilder, IPostWrapper postWrapper, ISubWrapper subWrapper, ICommentWrapper commentWrapper, IMembershipService membershipService, ISettingsProvider<SubSettings> subSettings, ISubActivityDao subActivityDao, IModerationDao moderationDao) { _contextService = contextService; _subDao = subDao; _mapper = mapper; _commandBus = commandBus; _userContext = userContext; _postDao = postDao; _voteDao = voteDao; _commentDao = commentDao; _permissionDao = permissionDao; _commentNodeHierarchyBuilder = commentNodeHierarchyBuilder; _commentTreeContextBuilder = commentTreeContextBuilder; _postwrapper = postWrapper; _subwrapper = subWrapper; _commentWrapper = commentWrapper; _membershiipService = membershipService; _subSettings = subSettings; _subActivityDao = subActivityDao; _moderationDao = moderationDao; } public ActionResult Popular(string query, int? pageNumber, int? pageSize) { ViewBag.NavigationKey = "popular"; ViewBag.Query = query; if (pageNumber == null || pageNumber < 1) { pageNumber = 1; } if (pageSize == null) { pageSize = 24; } if (pageSize > 100) { pageSize = 100; } if (pageSize < 1) { pageSize = 1; } var subs = _subDao.GetAllSubs(query, sortBy: SubsSortBy.Subscribers, nsfw: _userContext.CurrentNsfw, skip: ((pageNumber - 1) * pageSize), take: pageSize); return View("List", new PagedList<SubWrapped>(_subwrapper.Wrap(subs, _userContext.CurrentUser), pageNumber.Value, pageSize.Value, subs.HasMore)); } [Authorize] public ActionResult Create() { var model = new CreateEditSubModel(); // admins can create default subs if (_userContext.CurrentUser.IsAdmin) { model.IsDefault = false; } model.InAll = true; return View(model); } [Authorize] [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(CreateEditSubModel model) { var response = _commandBus.Send<CreateSub, CreateSubResponse>(new CreateSub { CreatedByUserId = _userContext.CurrentUser.Id, Name = model.Name, Description = model.Description, SidebarText = model.SidebarText, SubmissionText = model.SubmissionText, Type = model.SubType, IsDefault = model.IsDefault, InAll = model.InAll, Nsfw = model.Nsfw }); if (!string.IsNullOrEmpty(response.Error)) { ModelState.AddModelError(string.Empty, response.Error); return View(model); } AddSuccessMessage("You sub has been succesfully created."); return Redirect("/"); } } }
33.490683
157
0.608494
[ "MIT" ]
skimurio/Skimur
src/Skimur.Web/Controllers/SubsController.cs
5,394
C#
using Guppy.DependencyInjection; using Guppy.Extensions.System.Collections; using Guppy.Extensions.System; using Guppy.Interfaces; using Microsoft.Xna.Framework; namespace Guppy.Lists { public class FrameableList<TFrameable> : FactoryServiceList<TFrameable>, IFrameable where TFrameable : class, IFrameable { #region Events public event Step OnPreDraw; public event Step OnDraw; public event Step OnPostDraw; public event Step OnPreUpdate; public event Step OnUpdate; public event Step OnPostUpdate; #endregion #region Lifecycle Methods protected override void PreInitialize(ServiceProvider provider) { base.PreInitialize(provider); this.OnDraw += this.Draw; this.OnUpdate += this.Update; } protected override void Release() { base.Release(); this.OnDraw -= this.Draw; this.OnUpdate -= this.Update; } protected override void PostRelease() { base.PostRelease(); #if DEBUG_VERBOSE this.OnPreDraw.LogInvocationList("OnPreDraw", this, 1); this.OnDraw.LogInvocationList("OnDraw", this, 1); this.OnPostDraw.LogInvocationList("OnPostDraw", this, 1); this.OnPreUpdate.LogInvocationList("OnPreUpdate", this, 1); this.OnUpdate.LogInvocationList("OnUpdate", this, 1); this.OnPostUpdate.LogInvocationList("OnPostUpdate", this, 1); #endif } #endregion #region Frame Methods public virtual void TryDraw(GameTime gameTime) { this.OnPreDraw?.Invoke(gameTime); this.OnDraw?.Invoke(gameTime); this.OnPostDraw?.Invoke(gameTime); } public virtual void TryUpdate(GameTime gameTime) { this.OnPreUpdate?.Invoke(gameTime); this.OnUpdate?.Invoke(gameTime); this.OnPostUpdate?.Invoke(gameTime); } protected virtual void Draw(GameTime gameTime) { foreach (TFrameable child in this) child.TryDraw(gameTime); } protected virtual void Update(GameTime gameTime) { foreach (TFrameable child in this) child.TryUpdate(gameTime); } #endregion } }
29.170732
87
0.604515
[ "MIT" ]
rettoph/Guppy
src/Guppy/Lists/FrameableList.cs
2,394
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // This C# code was generated by XmlSchemaClassGenerator version 1.0.0.0. namespace Models.XsdConvert.genericRailML { using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Xml.Serialization; [System.CodeDom.Compiler.GeneratedCodeAttribute("XmlSchemaClassGenerator", "1.0.0.0")] internal partial interface IAOrientation { /// <summary> /// <para>a direction, which allows for all direction attributes</para> /// </summary> System.Nullable<genericRailML.TLaxDirection> Dir { get; set; } } }
31.121212
90
0.545278
[ "Apache-2.0" ]
LightosLimited/RailML
v3.1/Models/XsdConvert/genericRailML/IAOrientation.cs
1,027
C#
#nullable enable using System.Threading; using System.Threading.Tasks; namespace System.Net { internal static class GraphExtensions { public static ValueTask<bool> IsRootedTreeAsync<TValue>( this IAsyncFuncService<TValue> vertex, bool allowSingleton, CancellationToken cancellationToken = default) { #region Check if the task is canceled if (cancellationToken.IsCancellationRequested) { return ValueTask.FromCanceled<bool>(cancellationToken); } #endregion // TODO: Check if the graph is a rooted tree return (vertex, allowSingleton) switch { _ => ValueTask.FromResult(true) }; } public static ValueTask<bool> IsLeafAsync<TValue>( this IAsyncFuncService<TValue> vertex, CancellationToken cancellationToken = default) => vertex.GetIsLinearAsync(cancellationToken); } }
26.74359
71
0.597315
[ "MIT" ]
andreise/func-service-tree-orchestra
src/Net.FuncServiceOrchestrator/Implementation/GraphExtensions.cs
1,045
C#
#region Copyright // <<<<<<< HEAD <<<<<<< HEAD ======= ======= >>>>>>> update form orginal repo // DotNetNuke® - https://www.dnnsoftware.com // Copyright (c) 2002-2018 // by DotNetNuke Corporation // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and // to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions // of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED // TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF // CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion <<<<<<< HEAD >>>>>>> Merges latest changes from release/9.4.x into development (#3178) ======= >>>>>>> update form orginal repo #region Usings using Telerik.Web.UI; #endregion namespace DotNetNuke.Web.UI.WebControls { public class DnnAjaxPanel : RadAjaxPanel { } }
38.121951
116
0.727447
[ "MIT" ]
DnnSoftwarePersian/Dnn.Platform
DNN Platform/DotNetNuke.Web.Deprecated/UI/WebControls/DnnAjaxPanel.cs
1,566
C#
using System.Windows.Controls; using TournamentAssistantShared.Models; namespace TournamentAssistantUI.UI.UserControls { /// <summary> /// Interaction logic for UserDialog.xaml /// </summary> public partial class PlayerDialog : UserControl { public Player Player { get; set; } public PlayerDialog(Player player) { Player = player; DataContext = this; InitializeComponent(); } } }
20.73913
51
0.616352
[ "MIT" ]
Auros/TournamentAssistant
TournamentAssistantUI/UI/UserControls/PlayerDialog.xaml.cs
479
C#
using System; using NetRuntimeSystem = System; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.ComponentModel; using System.Reflection; using System.Collections.Generic; using NetOffice; namespace NetOffice.PowerPointApi { ///<summary> /// DispatchInterface ProtectedViewWindows /// SupportByVersion PowerPoint, 14,15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff744887.aspx ///</summary> [SupportByVersionAttribute("PowerPoint", 14,15)] [EntityTypeAttribute(EntityType.IsDispatchInterface)] public class ProtectedViewWindows : Collection { #pragma warning disable #region Type Information private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(ProtectedViewWindows); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public ProtectedViewWindows(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ProtectedViewWindows(COMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ProtectedViewWindows(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ProtectedViewWindows(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ProtectedViewWindows(COMObject replacedObject) : base(replacedObject) { } [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ProtectedViewWindows() : base() { } /// <param name="progId">registered ProgID</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public ProtectedViewWindows(string progId) : base(progId) { } #endregion #region Properties /// <summary> /// SupportByVersion PowerPoint 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff746147.aspx /// </summary> [SupportByVersionAttribute("PowerPoint", 14,15)] public NetOffice.PowerPointApi.Application Application { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Application", paramsArray); NetOffice.PowerPointApi.Application newObject = Factory.CreateKnownObjectFromComProxy(this,returnItem,NetOffice.PowerPointApi.Application.LateBindingApiWrapperType) as NetOffice.PowerPointApi.Application; return newObject; } } /// <summary> /// SupportByVersion PowerPoint 14, 15 /// Get /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff746392.aspx /// Unknown COM Proxy /// </summary> [SupportByVersionAttribute("PowerPoint", 14,15)] public object Parent { get { object[] paramsArray = null; object returnItem = Invoker.PropertyGet(this, "Parent", paramsArray); COMObject newObject = Factory.CreateObjectFromComProxy(this,returnItem); return newObject; } } #endregion #region Methods /// <summary> /// SupportByVersion PowerPoint 14, 15 /// /// </summary> /// <param name="index">Int32 Index</param> [SupportByVersionAttribute("PowerPoint", 14,15)] [NetRuntimeSystem.Runtime.CompilerServices.IndexerName("Item")] public NetOffice.PowerPointApi.ProtectedViewWindow this[Int32 index] { get { object[] paramsArray = Invoker.ValidateParamsArray(index); object returnItem = Invoker.MethodReturn(this, "Item", paramsArray); NetOffice.PowerPointApi.ProtectedViewWindow newObject = Factory.CreateKnownObjectFromComProxy(this, returnItem,NetOffice.PowerPointApi.ProtectedViewWindow.LateBindingApiWrapperType) as NetOffice.PowerPointApi.ProtectedViewWindow; return newObject; } } /// <summary> /// SupportByVersion PowerPoint 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff745478.aspx /// </summary> /// <param name="fileName">string FileName</param> /// <param name="readPassword">optional string ReadPassword = </param> /// <param name="openAndRepair">optional NetOffice.OfficeApi.Enums.MsoTriState OpenAndRepair = 0</param> [SupportByVersionAttribute("PowerPoint", 14,15)] public NetOffice.PowerPointApi.ProtectedViewWindow Open(string fileName, object readPassword, object openAndRepair) { object[] paramsArray = Invoker.ValidateParamsArray(fileName, readPassword, openAndRepair); object returnItem = Invoker.MethodReturn(this, "Open", paramsArray); NetOffice.PowerPointApi.ProtectedViewWindow newObject = Factory.CreateKnownObjectFromComProxy(this, returnItem,NetOffice.PowerPointApi.ProtectedViewWindow.LateBindingApiWrapperType) as NetOffice.PowerPointApi.ProtectedViewWindow; return newObject; } /// <summary> /// SupportByVersion PowerPoint 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff745478.aspx /// </summary> /// <param name="fileName">string FileName</param> [CustomMethodAttribute] [SupportByVersionAttribute("PowerPoint", 14,15)] public NetOffice.PowerPointApi.ProtectedViewWindow Open(string fileName) { object[] paramsArray = Invoker.ValidateParamsArray(fileName); object returnItem = Invoker.MethodReturn(this, "Open", paramsArray); NetOffice.PowerPointApi.ProtectedViewWindow newObject = Factory.CreateKnownObjectFromComProxy(this, returnItem,NetOffice.PowerPointApi.ProtectedViewWindow.LateBindingApiWrapperType) as NetOffice.PowerPointApi.ProtectedViewWindow; return newObject; } /// <summary> /// SupportByVersion PowerPoint 14, 15 /// MSDN Online Documentation: http://msdn.microsoft.com/en-us/en-us/library/office/ff745478.aspx /// </summary> /// <param name="fileName">string FileName</param> /// <param name="readPassword">optional string ReadPassword = </param> [CustomMethodAttribute] [SupportByVersionAttribute("PowerPoint", 14,15)] public NetOffice.PowerPointApi.ProtectedViewWindow Open(string fileName, object readPassword) { object[] paramsArray = Invoker.ValidateParamsArray(fileName, readPassword); object returnItem = Invoker.MethodReturn(this, "Open", paramsArray); NetOffice.PowerPointApi.ProtectedViewWindow newObject = Factory.CreateKnownObjectFromComProxy(this, returnItem,NetOffice.PowerPointApi.ProtectedViewWindow.LateBindingApiWrapperType) as NetOffice.PowerPointApi.ProtectedViewWindow; return newObject; } #endregion #pragma warning restore } }
40.787129
234
0.722296
[ "MIT" ]
NetOffice/NetOffice
Source/PowerPoint/DispatchInterfaces/ProtectedViewWindows.cs
8,239
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.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http.Hosting; using Microsoft.TestCommon; using Newtonsoft.Json.Linq; namespace System.Web.Http { public class IncludeErrorDetailTest { public static TheoryDataSet ThrowingOnActionIncludesErrorDetailData { get { return new TheoryDataSet<bool, IncludeErrorDetailPolicy, bool?, bool>() { // isLocal, includeErrorDetail, customErrors, expectErrorDetail { true, IncludeErrorDetailPolicy.LocalOnly, true, true }, { false, IncludeErrorDetailPolicy.LocalOnly, true, false }, { true, IncludeErrorDetailPolicy.LocalOnly, false, true }, { false, IncludeErrorDetailPolicy.LocalOnly, false, false }, { true, IncludeErrorDetailPolicy.LocalOnly, null, true }, { false, IncludeErrorDetailPolicy.LocalOnly, null, false }, { true, IncludeErrorDetailPolicy.Always, true, true }, { false, IncludeErrorDetailPolicy.Always, true, true }, { true, IncludeErrorDetailPolicy.Always, false, true }, { false, IncludeErrorDetailPolicy.Always, false, true }, { true, IncludeErrorDetailPolicy.Always, null, true }, { false, IncludeErrorDetailPolicy.Always, null, true }, { true, IncludeErrorDetailPolicy.Never, true, false }, { false, IncludeErrorDetailPolicy.Never, true, false }, { true, IncludeErrorDetailPolicy.Never, false, false }, { false, IncludeErrorDetailPolicy.Never, false, false }, { true, IncludeErrorDetailPolicy.Never, null, false }, { false, IncludeErrorDetailPolicy.Never, null, false }, { true, IncludeErrorDetailPolicy.Default, true, false }, { false, IncludeErrorDetailPolicy.Default, true, false }, { true, IncludeErrorDetailPolicy.Default, false, true }, { false, IncludeErrorDetailPolicy.Default, false, true }, { true, IncludeErrorDetailPolicy.Default, null, true }, { false, IncludeErrorDetailPolicy.Default, null, false } }; } } [Theory] [PropertyData("ThrowingOnActionIncludesErrorDetailData")] public async Task ThrowingOnActionIncludesErrorDetail( bool isLocal, IncludeErrorDetailPolicy includeErrorDetail, bool? customErrors, bool expectErrorDetail ) { string controllerName = "Exception"; string requestUrl = String.Format( "{0}/{1}/{2}", "http://www.foo.com", controllerName, "ArgumentNull" ); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUrl); request.Properties[HttpPropertyKeys.IsLocalKey] = new Lazy<bool>(() => isLocal); if (customErrors != null) { request.Properties[HttpPropertyKeys.IncludeErrorDetailKey] = new Lazy<bool>( () => !(bool)customErrors ); } await ScenarioHelper.RunTestAsync( controllerName, "/{action}", request, async (response) => { if (expectErrorDetail) { await AssertResponseIncludesErrorDetailAsync(response); } else { await AssertResponseDoesNotIncludeErrorDetailAsync(response); } }, (config) => { config.IncludeErrorDetailPolicy = includeErrorDetail; } ); } private async Task AssertResponseIncludesErrorDetailAsync(HttpResponseMessage response) { Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); dynamic json = JToken.Parse(await response.Content.ReadAsStringAsync()); string result = json.ExceptionType; Assert.Equal(typeof(ArgumentNullException).FullName, result); } private async Task AssertResponseDoesNotIncludeErrorDetailAsync( HttpResponseMessage response ) { Assert.Equal(HttpStatusCode.InternalServerError, response.StatusCode); JObject json = JToken.Parse(await response.Content.ReadAsStringAsync()) as JObject; Assert.Single(json); string errorMessage = ((JValue)json["Message"]).ToString(); Assert.Equal("An error has occurred.", errorMessage); } } }
44.213675
111
0.566596
[ "Apache-2.0" ]
belav/AspNetWebStack
test/System.Web.Http.Integration.Test/ExceptionHandling/IncludeErrorDetailTest.cs
5,175
C#
// WARNING // // This file has been generated automatically by Visual Studio from the outlets and // actions declared in your storyboard file. // Manual changes to this file will not be maintained. // using Foundation; using System; using System.CodeDom.Compiler; using UIKit; namespace MetroMate { [Register ("StopSelCell")] partial class StopSelCell { [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UILabel lbl_stopname { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UIKit.UITextField txt_stopid { get; set; } [Action ("txt_stopidChanged:")] [GeneratedCode ("iOS Designer", "1.0")] partial void txt_stopidChanged (UIKit.UITextField sender); void ReleaseDesignerOutlets () { if (lbl_stopname != null) { lbl_stopname.Dispose (); lbl_stopname = null; } if (txt_stopid != null) { txt_stopid.Dispose (); txt_stopid = null; } } } }
25.857143
84
0.575506
[ "MIT" ]
luxwig/MetroMate
SubwayConnect/StopSelCell.designer.cs
1,086
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 cognito-idp-2016-04-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CognitoIdentityProvider.Model { /// <summary> /// Container for the parameters to the InitiateAuth operation. /// Initiates the authentication flow. /// </summary> public partial class InitiateAuthRequest : AmazonCognitoIdentityProviderRequest { private AnalyticsMetadataType _analyticsMetadata; private AuthFlowType _authFlow; private Dictionary<string, string> _authParameters = new Dictionary<string, string>(); private string _clientId; private Dictionary<string, string> _clientMetadata = new Dictionary<string, string>(); private UserContextDataType _userContextData; /// <summary> /// Gets and sets the property AnalyticsMetadata. /// <para> /// The Amazon Pinpoint analytics metadata for collecting metrics for <code>InitiateAuth</code> /// calls. /// </para> /// </summary> public AnalyticsMetadataType AnalyticsMetadata { get { return this._analyticsMetadata; } set { this._analyticsMetadata = value; } } // Check to see if AnalyticsMetadata property is set internal bool IsSetAnalyticsMetadata() { return this._analyticsMetadata != null; } /// <summary> /// Gets and sets the property AuthFlow. /// <para> /// The authentication flow for this call to execute. The API action will depend on this /// value. For example: /// </para> /// <ul> <li> /// <para> /// <code>REFRESH_TOKEN_AUTH</code> will take in a valid refresh token and return new /// tokens. /// </para> /// </li> <li> /// <para> /// <code>USER_SRP_AUTH</code> will take in <code>USERNAME</code> and <code>SRP_A</code> /// and return the SRP variables to be used for next challenge execution. /// </para> /// </li> <li> /// <para> /// <code>USER_PASSWORD_AUTH</code> will take in <code>USERNAME</code> and <code>PASSWORD</code> /// and return the next challenge or tokens. /// </para> /// </li> </ul> /// <para> /// Valid values include: /// </para> /// <ul> <li> /// <para> /// <code>USER_SRP_AUTH</code>: Authentication flow for the Secure Remote Password (SRP) /// protocol. /// </para> /// </li> <li> /// <para> /// <code>REFRESH_TOKEN_AUTH</code>/<code>REFRESH_TOKEN</code>: Authentication flow for /// refreshing the access token and ID token by supplying a valid refresh token. /// </para> /// </li> <li> /// <para> /// <code>CUSTOM_AUTH</code>: Custom authentication flow. /// </para> /// </li> <li> /// <para> /// <code>USER_PASSWORD_AUTH</code>: Non-SRP authentication flow; USERNAME and PASSWORD /// are passed directly. If a user migration Lambda trigger is set, this flow will invoke /// the user migration Lambda if the USERNAME is not found in the user pool. /// </para> /// </li> <li> /// <para> /// <code>ADMIN_USER_PASSWORD_AUTH</code>: Admin-based user password authentication. /// This replaces the <code>ADMIN_NO_SRP_AUTH</code> authentication flow. In this flow, /// Cognito receives the password in the request instead of using the SRP process to verify /// passwords. /// </para> /// </li> </ul> /// <para> /// <code>ADMIN_NO_SRP_AUTH</code> is not a valid value. /// </para> /// </summary> [AWSProperty(Required=true)] public AuthFlowType AuthFlow { get { return this._authFlow; } set { this._authFlow = value; } } // Check to see if AuthFlow property is set internal bool IsSetAuthFlow() { return this._authFlow != null; } /// <summary> /// Gets and sets the property AuthParameters. /// <para> /// The authentication parameters. These are inputs corresponding to the <code>AuthFlow</code> /// that you are invoking. The required values depend on the value of <code>AuthFlow</code>: /// </para> /// <ul> <li> /// <para> /// For <code>USER_SRP_AUTH</code>: <code>USERNAME</code> (required), <code>SRP_A</code> /// (required), <code>SECRET_HASH</code> (required if the app client is configured with /// a client secret), <code>DEVICE_KEY</code> /// </para> /// </li> <li> /// <para> /// For <code>REFRESH_TOKEN_AUTH/REFRESH_TOKEN</code>: <code>REFRESH_TOKEN</code> (required), /// <code>SECRET_HASH</code> (required if the app client is configured with a client secret), /// <code>DEVICE_KEY</code> /// </para> /// </li> <li> /// <para> /// For <code>CUSTOM_AUTH</code>: <code>USERNAME</code> (required), <code>SECRET_HASH</code> /// (if app client is configured with client secret), <code>DEVICE_KEY</code> /// </para> /// </li> </ul> /// </summary> public Dictionary<string, string> AuthParameters { get { return this._authParameters; } set { this._authParameters = value; } } // Check to see if AuthParameters property is set internal bool IsSetAuthParameters() { return this._authParameters != null && this._authParameters.Count > 0; } /// <summary> /// Gets and sets the property ClientId. /// <para> /// The app client ID. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=128)] public string ClientId { get { return this._clientId; } set { this._clientId = value; } } // Check to see if ClientId property is set internal bool IsSetClientId() { return this._clientId != null; } /// <summary> /// Gets and sets the property ClientMetadata. /// <para> /// A map of custom key-value pairs that you can provide as input for certain custom workflows /// that this action triggers. /// </para> /// /// <para> /// You create custom workflows by assigning AWS Lambda functions to user pool triggers. /// When you use the InitiateAuth API action, Amazon Cognito invokes the AWS Lambda functions /// that are specified for various triggers. The ClientMetadata value is passed as input /// to the functions for only the following triggers: /// </para> /// <ul> <li> /// <para> /// Pre signup /// </para> /// </li> <li> /// <para> /// Pre authentication /// </para> /// </li> <li> /// <para> /// User migration /// </para> /// </li> </ul> /// <para> /// When Amazon Cognito invokes the functions for these triggers, it passes a JSON payload, /// which the function receives as input. This payload contains a <code>validationData</code> /// attribute, which provides the data that you assigned to the ClientMetadata parameter /// in your InitiateAuth request. In your function code in AWS Lambda, you can process /// the <code>validationData</code> value to enhance your workflow for your specific needs. /// </para> /// /// <para> /// When you use the InitiateAuth API action, Amazon Cognito also invokes the functions /// for the following triggers, but it does not provide the ClientMetadata value as input: /// </para> /// <ul> <li> /// <para> /// Post authentication /// </para> /// </li> <li> /// <para> /// Custom message /// </para> /// </li> <li> /// <para> /// Pre token generation /// </para> /// </li> <li> /// <para> /// Create auth challenge /// </para> /// </li> <li> /// <para> /// Define auth challenge /// </para> /// </li> <li> /// <para> /// Verify auth challenge /// </para> /// </li> </ul> /// <para> /// For more information, see <a href="https://docs.aws.amazon.com/cognito/latest/developerguide/cognito-user-identity-pools-working-with-aws-lambda-triggers.html">Customizing /// User Pool Workflows with Lambda Triggers</a> in the <i>Amazon Cognito Developer Guide</i>. /// </para> /// <note> /// <para> /// Take the following limitations into consideration when you use the ClientMetadata /// parameter: /// </para> /// <ul> <li> /// <para> /// Amazon Cognito does not store the ClientMetadata value. This data is available only /// to AWS Lambda triggers that are assigned to a user pool to support custom workflows. /// If your user pool configuration does not include triggers, the ClientMetadata parameter /// serves no purpose. /// </para> /// </li> <li> /// <para> /// Amazon Cognito does not validate the ClientMetadata value. /// </para> /// </li> <li> /// <para> /// Amazon Cognito does not encrypt the the ClientMetadata value, so don't use it to provide /// sensitive information. /// </para> /// </li> </ul> </note> /// </summary> public Dictionary<string, string> ClientMetadata { get { return this._clientMetadata; } set { this._clientMetadata = value; } } // Check to see if ClientMetadata property is set internal bool IsSetClientMetadata() { return this._clientMetadata != null && this._clientMetadata.Count > 0; } /// <summary> /// Gets and sets the property UserContextData. /// <para> /// Contextual data such as the user's device fingerprint, IP address, or location used /// for evaluating the risk of an unexpected event by Amazon Cognito advanced security. /// </para> /// </summary> public UserContextDataType UserContextData { get { return this._userContextData; } set { this._userContextData = value; } } // Check to see if UserContextData property is set internal bool IsSetUserContextData() { return this._userContextData != null; } } }
37.893891
183
0.563258
[ "Apache-2.0" ]
Melvinerall/aws-sdk-net
sdk/src/Services/CognitoIdentityProvider/Generated/Model/InitiateAuthRequest.cs
11,785
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Balrond3PersonMovements { public class Balrond3personCameraCollision : MonoBehaviour { private Vector3 dollyDir; private Vector3 dollyDirAdjusted; private Balrond3pCameraFollow follow; private Balrond3pMainCamera cam; void Awake() { follow = transform.parent.parent.GetComponent<Balrond3pCameraFollow>(); cam = transform.parent.GetComponent<Balrond3pMainCamera>(); dollyDir = transform.parent.localPosition; } // Update is called once per frame void FixedUpdate() { Vector3 desiredCameraPos = transform.parent.TransformPoint(dollyDir * follow.maxDistance); RaycastHit hit; if (Physics.Linecast(transform.parent.localPosition, desiredCameraPos, out hit)) { if (transform.localPosition.z <= follow.minDistance && !hit.transform.name.Equals(follow.target.transform.gameObject.name) && !hit.transform.gameObject.name.Equals(transform.gameObject.name) && !hit.transform.gameObject.name.Equals(cam.transform.gameObject.name)) { transform.localPosition += new Vector3(0, 0, follow.smooth * Time.deltaTime); } } else { if (-follow.maxDistance < transform.localPosition.z) { transform.localPosition -= new Vector3(0, 0, follow.smooth * Time.deltaTime); } } } } }
36.727273
279
0.615718
[ "MIT" ]
HoBeenH/Second-Popol
Assets/LanFang/Scrips/Balrond3Pcontroller/Balrond3personCameraCollision.cs
1,618
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\MethodRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The type CalendarAllowedCalendarSharingRolesRequestBuilder. /// </summary> public partial class CalendarAllowedCalendarSharingRolesRequestBuilder : BaseFunctionMethodRequestBuilder<ICalendarAllowedCalendarSharingRolesRequest>, ICalendarAllowedCalendarSharingRolesRequestBuilder { /// <summary> /// Constructs a new <see cref="CalendarAllowedCalendarSharingRolesRequestBuilder"/>. /// </summary> /// <param name="requestUrl">The URL for the request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="User">A User parameter for the OData method call.</param> public CalendarAllowedCalendarSharingRolesRequestBuilder( string requestUrl, IBaseClient client, string User) : base(requestUrl, client) { this.SetParameter("user", User, false); } /// <summary> /// A method used by the base class to construct a request class instance. /// </summary> /// <param name="functionUrl">The request URL to </param> /// <param name="options">The query and header options for the request.</param> /// <returns>An instance of a specific request class.</returns> protected override ICalendarAllowedCalendarSharingRolesRequest CreateRequest(string functionUrl, IEnumerable<Option> options) { var request = new CalendarAllowedCalendarSharingRolesRequest(functionUrl, this.Client, options); return request; } } }
44.56
206
0.631059
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/CalendarAllowedCalendarSharingRolesRequestBuilder.cs
2,228
C#
using System; using System.Collections.Generic; using System.Linq; using LinqToDB; using NUnit.Framework; namespace Tests.Linq { using Model; using VisualBasic; [TestFixture] public class VisualBasicTests : TestBase { [Test] public void CompareString([DataSources] string context) { using (var db = GetDataContext(context)) AreEqual( from p in db.Person where p.FirstName == "John" select p, CompilerServices.CompareString(db)); } [Test] public void CompareString1([IncludeDataSources(TestProvName.AllSQLite)] string context) { using (var db = GetDataContext(context)) { var query = (IQueryable<Person>)CompilerServices.CompareString(db); var str = query.ToString(); TestContext.WriteLine(str); Assert.That(str, Does.Not.Contain("CASE")); } } [Test] public void ParameterName([DataSources(TestProvName.AllSapHana)] string context) { using (var db = GetDataContext(context)) AreEqual( from p in Parent where p.ParentID == 1 select p, VisualBasicCommon.ParamenterName(db)); } [Test] public void SearchCondition1([DataSources(TestProvName.AllAccess)] string context) { using (var db = GetDataContext(context)) AreEqual( from t in Types where !t.BoolValue && (t.SmallIntValue == 5 || t.SmallIntValue == 7 || (t.SmallIntValue | 2) == 10) select t, VisualBasicCommon.SearchCondition1(db)); } [Test] public void SearchCondition2([NorthwindDataContext] string context) { using (var db = new NorthwindDB(context)) { var dd = GetNorthwindAsList(context); AreEqual( from cust in dd.Customer where cust.Orders.Count > 0 && cust.CompanyName.StartsWith("H") select cust.CustomerID, VisualBasicCommon.SearchCondition2(db)); } } [Test] public void SearchCondition3([NorthwindDataContext] string context) { using (var db = new NorthwindDB(context)) { var cQuery = from order in db.Order where order.OrderDate == new DateTime(1997, 11, 14) select order.OrderID; var cSharpResults = cQuery.ToList(); var vbResults = (VisualBasicCommon.SearchCondition3(db)).ToList(); AreEqual( cSharpResults, vbResults); } } [Test] public void SearchCondition4([NorthwindDataContext] string context) { using (var db = new NorthwindDB(context)) { var cQuery = from order in db.Order where order.OrderDate == new DateTime(1997, 11, 14) select order.OrderID; var cSharpResults = cQuery.ToList(); var vbResults = (VisualBasicCommon.SearchCondition4(db)).ToList(); AreEqual( cSharpResults, vbResults); } } [ActiveIssue(649)] [Test] public void Issue649Test1([DataSources] string context) { using (var db = GetDataContext(context)) using (db.CreateLocalTable<VBTests.Activity649>()) using (db.CreateLocalTable<VBTests.Person649>()) { var result = VBTests.Issue649Test1(db); } } [Test] public void Issue649Test2([DataSources] string context) { using (var db = GetDataContext(context)) using (db.CreateLocalTable<VBTests.Activity649>()) using (db.CreateLocalTable<VBTests.Person649>()) { var result = VBTests.Issue649Test2(db); } } [Test] public void Issue649Test3([DataSources] string context) { using (var db = GetDataContext(context)) using (db.CreateLocalTable<VBTests.Activity649>()) using (db.CreateLocalTable<VBTests.Person649>()) { var result = VBTests.Issue649Test3(db); } } [ActiveIssue(649)] [Test] public void Issue649Test4([DataSources] string context) { using (var db = GetDataContext(context)) { db.InlineParameters = true; var q1 = db.Child.GroupBy(c => new { c.ParentID, c.ChildID }, (c, g) => new { Child = c, Grouped = g }).Select(data => new { ParentID = data.Child.ParentID, ChildID = data.Child.ChildID, LastChild = data.Grouped.Max(f => f.ChildID) }); var str = q1.ToString(); } } #region issue 2746 [Test] public void Issue2746([DataSources] string context) { using (var db = GetDataContext(context)) { VBTests.Issue2746Test(db, "1"); } } #endregion } }
23.71123
105
0.636446
[ "MIT" ]
williamlee1982/linq2db
Tests/Linq/Linq/VisualBasicTests.cs
4,250
C#
using System.Threading.Tasks; using MSFramework.Common; using MSFramework.DependencyInjection; using Template.Application.DTO; namespace Template.Application.Query { public interface IProductQuery : IScopeDependency { Task<ProductOut> GetByNameAsync(string name); Task<PagedResult<ProductOut>> PagedQueryAsync(string keyword, int page, int limit); } }
25.714286
85
0.811111
[ "MIT" ]
jonechenug/MSFramework
template/Content/src/Template.Application/Query/IProductQuery.cs
360
C#
//------------------------------------------------------------------------------ // <auto-generated> // Ce code a été généré par un outil. // Version du runtime :4.0.30319.42000 // // Les modifications apportées à ce fichier peuvent provoquer un comportement incorrect et seront perdues si // le code est régénéré. // </auto-generated> //------------------------------------------------------------------------------ namespace SignToolGUI.Properties { using System; /// <summary> /// Une classe de ressource fortement typée destinée, entre autres, à la consultation des chaînes localisées. /// </summary> // Cette classe a été générée automatiquement par la classe StronglyTypedResourceBuilder // à l'aide d'un outil, tel que ResGen ou Visual Studio. // Pour ajouter ou supprimer un membre, modifiez votre fichier .ResX, puis réexécutez ResGen // avec l'option /str ou régénérez votre projet VS. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Retourne l'instance ResourceManager mise en cache utilisée par cette classe. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SignToolGUI.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Remplace la propriété CurrentUICulture du thread actuel pour toutes /// les recherches de ressources à l'aide de cette classe de ressource fortement typée. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Recherche une ressource localisée de type System.Drawing.Icon semblable à (Icône). /// </summary> internal static System.Drawing.Icon certificate_icone_6120 { get { object obj = ResourceManager.GetObject("certificate_icone_6120", resourceCulture); return ((System.Drawing.Icon)(obj)); } } /// <summary> /// Recherche une ressource localisée de type System.Byte[]. /// </summary> internal static byte[] signtool { get { object obj = ResourceManager.GetObject("signtool", resourceCulture); return ((byte[])(obj)); } } } }
43.988095
177
0.605954
[ "MIT" ]
nicelife90/SignToolGUI
Properties/Resources.Designer.cs
3,733
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> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("DataModels")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Release")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("DataModels")] [assembly: System.Reflection.AssemblyTitleAttribute("DataModels")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
40.916667
80
0.647658
[ "MIT" ]
ShashangkaShekhar/LibrarySystem-Core2.1-Angular6
LibrarySystem/DataModels/obj/Release/netstandard2.0/DataModels.AssemblyInfo.cs
982
C#
//****************************************************************************************************** // InterprocessReaderWriterLock.cs - Gbtc // // Copyright © 2012, Grid Protection Alliance. All Rights Reserved. // // Licensed to the Grid Protection Alliance (GPA) under one or more contributor license agreements. See // the NOTICE file distributed with this work for additional information regarding copyright ownership. // The GPA licenses this file to you under the MIT License (MIT), 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.opensource.org/licenses/MIT // // Unless agreed to in writing, the subject software distributed under the License is distributed on an // "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. Refer to the // License for the specific language governing permissions and limitations. // // Code Modification History: // ---------------------------------------------------------------------------------------------------- // 03/21/2011 - J. Ritchie Carroll // Generated original version of source code. // 12/14/2012 - Starlynn Danyelle Gilliam // Modified Header. // //****************************************************************************************************** using System; using System.Threading; namespace GSF.Threading { /// <summary> /// Represents an inter-process reader/writer lock using <see cref="Semaphore"/> and <see cref="Mutex"/> native locking mechanisms. /// </summary> public class InterprocessReaderWriterLock : IDisposable { #region [ Members ] // Constants /// <summary> /// Default maximum concurrent locks allowed for <see cref="InterprocessReaderWriterLock"/>. /// </summary> public const int DefaultMaximumConcurrentLocks = 10; // Fields private Mutex m_semaphoreLock; // Mutex used to synchronize access to Semaphore private Semaphore m_concurrencyLock; // Semaphore used for reader/writer lock on consumer object private readonly int m_maximumConcurrentLocks; // Maximum number of concurrent locks before waiting private bool m_disposed; #endregion #region [ Constructors ] /// <summary> /// Creates a new instance of the <see cref="InterprocessReaderWriterLock"/> associated with the specified /// <paramref name="name"/> that identifies a source object needing concurrency locking. /// </summary> /// <param name="name">Identifying name of source object needing concurrency locking (e.g., a path and file name).</param> public InterprocessReaderWriterLock(string name) : this(name, DefaultMaximumConcurrentLocks) { } /// <summary> /// Creates a new instance of the <see cref="InterprocessReaderWriterLock"/> associated with the specified /// <paramref name="name"/> that identifies a source object needing concurrency locking. /// </summary> /// <param name="name">Identifying name of source object needing concurrency locking (e.g., a path and file name).</param> /// <param name="maximumConcurrentLocks">Maximum concurrent reader locks to allow.</param> /// <remarks> /// If more reader locks are requested than the <paramref name="maximumConcurrentLocks"/>, excess reader locks will simply /// wait until a lock is available (i.e., one of the existing reads completes). /// </remarks> public InterprocessReaderWriterLock(string name, int maximumConcurrentLocks) { m_maximumConcurrentLocks = maximumConcurrentLocks; m_semaphoreLock = InterprocessLock.GetNamedMutex(name); m_concurrencyLock = InterprocessLock.GetNamedSemaphore(name, m_maximumConcurrentLocks); } /// <summary> /// Releases the unmanaged resources before the <see cref="InterprocessReaderWriterLock"/> object is reclaimed by <see cref="GC"/>. /// </summary> ~InterprocessReaderWriterLock() => Dispose(false); #endregion #region [ Properties ] /// <summary> /// Gets the maximum concurrent reader locks allowed. /// </summary> public int MaximumConcurrentLocks => m_maximumConcurrentLocks; #endregion #region [ Methods ] /// <summary> /// Releases all the resources used by the <see cref="InterprocessReaderWriterLock"/> object. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases the unmanaged resources used by the <see cref="InterprocessReaderWriterLock"/> object and optionally releases the managed resources. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (m_disposed) return; try { if (!disposing) return; if (!(m_concurrencyLock is null)) { m_concurrencyLock.Close(); m_concurrencyLock = null; } if (!(m_semaphoreLock is null)) { m_semaphoreLock.Close(); m_semaphoreLock = null; } } finally { m_disposed = true; // Prevent duplicate dispose. } } /// <summary> /// Tries to enter the lock in read mode. /// </summary> /// <remarks> /// Upon successful acquisition of a read lock, use the <c>finally</c> block of a <c>try/finally</c> statement to call <see cref="ExitReadLock"/>. /// One <see cref="ExitReadLock"/> should be called for each <see cref="EnterReadLock"/> or <see cref="TryEnterReadLock"/>. /// </remarks> public void EnterReadLock() => TryEnterReadLock(Timeout.Infinite); /// <summary> /// Tries to enter the lock in write mode. /// </summary> /// <remarks> /// Upon successful acquisition of a write lock, use the <c>finally</c> block of a <c>try/finally</c> statement to call <see cref="ExitWriteLock"/>. /// One <see cref="ExitWriteLock"/> should be called for each <see cref="EnterWriteLock"/> or <see cref="TryEnterWriteLock"/>. /// </remarks> public void EnterWriteLock() => TryEnterWriteLock(Timeout.Infinite); /// <summary> /// Exits read mode and returns the prior read lock count. /// </summary> /// <remarks> /// Upon successful acquisition of a read lock, use the <c>finally</c> block of a <c>try/finally</c> statement to call <see cref="ExitReadLock"/>. /// One <see cref="ExitReadLock"/> should be called for each <see cref="EnterReadLock"/> or <see cref="TryEnterReadLock"/>. /// </remarks> public int ExitReadLock() => m_concurrencyLock.Release(); // Release the semaphore lock and restore the slot /// <summary> /// Exits write mode. /// </summary> /// <remarks> /// Upon successful acquisition of a write lock, use the <c>finally</c> block of a <c>try/finally</c> statement to call <see cref="ExitWriteLock"/>. /// One <see cref="ExitWriteLock"/> should be called for each <see cref="EnterWriteLock"/> or <see cref="TryEnterWriteLock"/>. /// </remarks> public void ExitWriteLock() => m_semaphoreLock.ReleaseMutex(); // Release semaphore synchronization mutex lock /// <summary> /// Tries to enter the lock in read mode, with an optional time-out. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or -1 (<see cref="Timeout.Infinite"/>) to wait indefinitely.</param> /// <returns><c>true</c> if the calling thread entered read mode, otherwise, <c>false</c>.</returns> /// <remarks> /// <para> /// Upon successful acquisition of a read lock, use the <c>finally</c> block of a <c>try/finally</c> statement to call <see cref="ExitReadLock"/>. /// One <see cref="ExitReadLock"/> should be called for each <see cref="EnterReadLock"/> or <see cref="TryEnterReadLock"/>. /// </para> /// <para> /// Note that this function may wait as long as 2 * <paramref name="millisecondsTimeout"/> since the function first waits for synchronous access /// to the semaphore, then waits again on an available semaphore slot. /// </para> /// </remarks> public bool TryEnterReadLock(int millisecondsTimeout) { bool success; try { // Wait for system level mutex lock to synchronize access to semaphore if (!m_semaphoreLock.WaitOne(millisecondsTimeout)) return false; } catch (AbandonedMutexException) { // Abnormal application terminations can leave a mutex abandoned, in // this case we now own the mutex so we just ignore the exception } try { // Wait for a semaphore slot to become available success = m_concurrencyLock.WaitOne(millisecondsTimeout); } finally { // Release mutex so others can access the semaphore m_semaphoreLock.ReleaseMutex(); } return success; } /// <summary> /// Tries to enter the lock in write mode, with an optional time-out. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or -1 (<see cref="Timeout.Infinite"/>) to wait indefinitely.</param> /// <returns><c>true</c> if the calling thread entered write mode, otherwise, <c>false</c>.</returns> /// <remarks> /// <para> /// Upon successful acquisition of a write lock, use the <c>finally</c> block of a <c>try/finally</c> statement to call <see cref="ExitWriteLock"/>. /// One <see cref="ExitWriteLock"/> should be called for each <see cref="EnterWriteLock"/> or <see cref="TryEnterWriteLock"/>. /// </para> /// <para> /// Note that this function may wait as long as 2 * <paramref name="millisecondsTimeout"/> since the function first waits for synchronous access /// to the semaphore, then waits again on an available semaphore slot. /// </para> /// </remarks> public bool TryEnterWriteLock(int millisecondsTimeout) { bool success = false; try { // Wait for system level mutex lock to synchronize access to semaphore if (!m_semaphoreLock.WaitOne(millisecondsTimeout)) return false; } catch (AbandonedMutexException) { // Abnormal application terminations can leave a mutex abandoned, in // this case we now own the mutex so we just ignore the exception } try { // At this point no other threads can acquire read or write access since we own the mutex. // Other threads may be busy reading, so we wait until all semaphore slots become available. // The only way to get a semaphore slot count is to execute a successful wait and release. long startTime = DateTime.UtcNow.Ticks; success = m_concurrencyLock.WaitOne(millisecondsTimeout); if (success) { int count = m_concurrencyLock.Release(); int adjustedTimeout = millisecondsTimeout; // After a successful wait and release the returned semaphore slot count will be -1 of the // actual count since we owned one slot after a successful wait. while (success && count != m_maximumConcurrentLocks - 1) { // Sleep to allow any remaining reads to complete Thread.Sleep(1); // Continue to adjust remaining time to accommodate user specified millisecond timeout if (millisecondsTimeout > 0) adjustedTimeout = millisecondsTimeout - (int)Ticks.ToMilliseconds(DateTime.UtcNow.Ticks - startTime); if (adjustedTimeout < 0) adjustedTimeout = 0; success = m_concurrencyLock.WaitOne(adjustedTimeout); if (success) count = m_concurrencyLock.Release(); } } } finally { // If lock failed, release mutex so others can access the semaphore if (!success) m_semaphoreLock.ReleaseMutex(); } // Successfully entering write lock leaves state of semaphore locking mutex "owned", it is critical that // consumer call ExitWriteLock upon completion of write action to release mutex regardless of whether // their code succeeds or fails, that is, consumer should use the finally clause of a "try/finally" // expression to ExitWriteLock. return success; } #endregion } }
44.967742
156
0.579914
[ "MIT" ]
GridProtectionAlliance/gsf
Source/Libraries/GSF.Core/Threading/InterprocessReaderWriterLock.cs
13,943
C#
namespace Bbt.Campaign.Public.Dtos.CampaignRule { public class CampaignRuleInsertFormDto { public List<ParameterDto> BusinessLineList { get; set; } public List<ParameterDto> JoinTypeList { get; set; } public List<ParameterDto> BranchList { get; set; } public List<ParameterDto> CustomerTypeList { get; set; } public List<ParameterDto> CampaignStartTermList { get; set; } } }
35.666667
69
0.684579
[ "MIT" ]
evrenarifoglu69/bbt.loyalty
src/Bbt.Campaign.Api/Bbt.Campaign.Public/Dtos/CampaignRule/CampaignRuleInsertFormDto.cs
430
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// PosDeviceInfoVO Data Structure. /// </summary> [Serializable] public class PosDeviceInfoVO : AopObject { /// <summary> /// 设备对应的软件方公司名称,比如:美味不用等;银盒子;二维火;云纵;雅座;辰森; /// </summary> [XmlElement("decive_software_name")] public string DeciveSoftwareName { get; set; } /// <summary> /// 设备安装的应用数 /// </summary> [XmlElement("device_app_cnt")] public string DeviceAppCnt { get; set; } /// <summary> /// 设备安装的应用列表对应的流量,单位KB /// </summary> [XmlElement("device_app_flow")] public string DeviceAppFlow { get; set; } /// <summary> /// 设备安装的应用列表 /// </summary> [XmlElement("device_app_list")] public string DeviceAppList { get; set; } /// <summary> /// 设备出厂公司;比如:商米;新大陆;荣焱; /// </summary> [XmlElement("device_company_name")] public string DeviceCompanyName { get; set; } /// <summary> /// 设备总使用流量,单位KB /// </summary> [XmlElement("device_flow")] public string DeviceFlow { get; set; } /// <summary> /// pos机设备ip值 /// </summary> [XmlElement("device_ip")] public string DeviceIp { get; set; } /// <summary> /// pos机设备MAC地址 /// </summary> [XmlElement("device_mac")] public string DeviceMac { get; set; } /// <summary> /// 设备运行的操作系统版本 /// </summary> [XmlElement("device_os_version")] public string DeviceOsVersion { get; set; } /// <summary> /// pos机设备状态值,枚举值为:已出厂(1),已入仓(2),已出售(3),已报单(4),已发货(5),已收货(6),已激活(7)、已绑定(8)、运行中(9)、设备失联(10)、已解绑(11) /// </summary> [XmlElement("device_status")] public string DeviceStatus { get; set; } /// <summary> /// pos机设备类型,枚举值为: 旗舰(FLAG_SHIP),高端(HIGH_END),标准(STANDARD),手持(IN_HAND) /// </summary> [XmlElement("device_type")] public string DeviceType { get; set; } /// <summary> /// 设备型号,如荣焱P10CC、商米D1、荣焱P10S、商米P1、荣焱HD01、商米V1、商米M1、荣焱P8K、商米T1、商米T2lite、荣焱P8G、商米T1、商米T2Lite等 /// </summary> [XmlElement("device_version")] public string DeviceVersion { get; set; } /// <summary> /// 设备激活时间 /// </summary> [XmlElement("gmt_activate")] public string GmtActivate { get; set; } /// <summary> /// 最后登录时间:设备处于登陆状态的最后时间 /// </summary> [XmlElement("gmt_login")] public string GmtLogin { get; set; } /// <summary> /// 设备解绑时间 /// </summary> [XmlElement("gmt_production")] public string GmtProduction { get; set; } /// <summary> /// 最后发送信息时间:设备最后发送信息的时间,发给服务端的最后时间 /// </summary> [XmlElement("gmt_send")] public string GmtSend { get; set; } /// <summary> /// 设备出厂时间 /// </summary> [XmlElement("gmt_unbundling")] public string GmtUnbundling { get; set; } /// <summary> /// 最后更新时间:设备上软件的最后更新时间 /// </summary> [XmlElement("gmt_update")] public string GmtUpdate { get; set; } /// <summary> /// 数据回流设备对应的ISV名称 /// </summary> [XmlElement("isv_name")] public string IsvName { get; set; } /// <summary> /// 数据回流设备对应的ISV_PID /// </summary> [XmlElement("isv_pid")] public string IsvPid { get; set; } /// <summary> /// 口碑门店id,激活设备才有口碑门店id /// </summary> [XmlElement("shop_id")] public string ShopId { get; set; } /// <summary> /// 设备id,唯一标识设备的ID,SN号 /// </summary> [XmlElement("sn_no")] public string SnNo { get; set; } } }
28.075862
107
0.497666
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Domain/PosDeviceInfoVO.cs
4,813
C#
using System.Collections.Generic; using System.Linq; using Autodesk.Revit.DB; using HLApps.Revit.Utils; // A node in a BoundsOctree // Copyright 2014 Nition, BSD licence (see LICENCE file). http://nition.co namespace HLApps.Revit.Geometry.Octree { public delegate bool Filter<T>(T gelm); public class BoundsOctreeNode<T> { // Centre of this node public XYZ Center { get; private set; } // Length of this node if it has a looseness of 1.0 public float BaseLength { get; private set; } // Looseness value for this node float looseness; // Minimum size for a node in this octree float minSize; // Actual length of sides, taking the looseness value into account float adjLength; // Bounding box that represents this node HLBoundingBoxXYZ bounds = default(HLBoundingBoxXYZ); // Objects in this node readonly List<OctreeObject> objects = new List<OctreeObject>(); // Child nodes, if any BoundsOctreeNode<T>[] children = null; // Bounds of potential children to this node. These are actual size (with looseness taken into account), not base size HLBoundingBoxXYZ[] childBounds; // If there are already numObjectsAllowed in a node, we split it into children // A generally good number seems to be something around 8-15 const int numObjectsAllowed = 8; // An object in the octree class OctreeObject { public T Obj; public HLBoundingBoxXYZ Bounds; } /// <summary> /// Constructor. /// </summary> /// <param name="baseLengthVal">Length of this node, not taking looseness into account.</param> /// <param name="minSizeVal">Minimum size of nodes in this octree.</param> /// <param name="loosenessVal">Multiplier for baseLengthVal to get the actual size.</param> /// <param name="centerVal">Centre position of this node.</param> public BoundsOctreeNode(float baseLengthVal, float minSizeVal, float loosenessVal, XYZ centerVal) { SetValues(baseLengthVal, minSizeVal, loosenessVal, centerVal); } // #### PUBLIC METHODS #### /// <summary> /// Add an object. /// </summary> /// <param name="obj">Object to add.</param> /// <param name="objBounds">3D bounding box around the object.</param> /// <returns>True if the object fits entirely within this node.</returns> public bool Add(T obj, HLBoundingBoxXYZ objBounds) { if (!Encapsulates(bounds, objBounds)) { return false; } SubAdd(obj, objBounds); return true; } /// <summary> /// Remove an object. Makes the assumption that the object only exists once in the tree. /// </summary> /// <param name="obj">Object to remove.</param> /// <returns>True if the object was removed successfully.</returns> public bool Remove(T obj) { bool removed = false; for (int i = 0; i < objects.Count; i++) { if (objects[i].Obj.Equals(obj)) { removed = objects.Remove(objects[i]); break; } } if (!removed && children != null) { for (int i = 0; i < 8; i++) { removed = children[i].Remove(obj); if (removed) break; } } if (removed && children != null) { // Check if we should merge nodes now that we've removed an item if (ShouldMerge()) { Merge(); } } return removed; } /// <summary> /// Check if the specified bounds intersect with anything in the tree. See also: GetColliding. /// </summary> /// <param name="checkBounds">Bounds to check.</param> /// <returns>True if there was a collision.</returns> public bool IsColliding(ref HLBoundingBoxXYZ checkBounds, Filter<T> flt) { // Are the input bounds at least partially in this node? if (!GeoUtils.DoBoxesIntersect(bounds, checkBounds, 0)) { return false; } // Check against any objects in this node for (int i = 0; i < objects.Count; i++) { var obj = objects[i]; if ((flt == null || flt.Invoke(obj.Obj)) && GeoUtils.DoBoxesIntersect(objects[i].Bounds, checkBounds, 0)) { return true; } } // Check children if (children != null) { for (int i = 0; i < 8; i++) { if (children[i].IsColliding(ref checkBounds, flt)) { return true; } } } return false; } /// <summary> /// Check if the specified bounds intersect with anything in the tree. See also: GetColliding. /// </summary> /// <param name="checkBounds">Bounds to check.</param> /// <returns>True if there was a collision.</returns> public bool IsColliding(ref Line checkBounds, Filter<T> flt) { // Are the input bounds at least partially in this node? if (!bounds.IntersectRay(checkBounds)) { return false; } // Check against any objects in this node for (int i = 0; i < objects.Count; i++) { var obj = objects[i]; if ((flt == null || flt.Invoke(obj.Obj)) && obj.Bounds.IntersectRay(checkBounds)) { return true; } } // Check children if (children != null) { for (int i = 0; i < 8; i++) { if (children[i].IsColliding(ref checkBounds, flt)) { return true; } } } return false; } /// <summary> /// Returns an array of objects that intersect with the specified bounds, if any. Otherwise returns an empty array. See also: IsColliding. /// </summary> /// <param name="checkBounds">Bounds to check. Passing by ref as it improve performance with structs.</param> /// <param name="result">List result.</param> /// <returns>Objects that intersect with the specified bounds.</returns> public void GetColliding(ref HLBoundingBoxXYZ checkBounds, List<T> result, Filter<T> flt) { // Are the input bounds at least partially in this node? if (!bounds.Intersects(checkBounds)) { return; } // Check against any objects in this node for (int i = 0; i < objects.Count; i++) { if (objects[i].Bounds.Intersects(checkBounds)) { result.Add(objects[i].Obj); } } // Check children if (children != null) { for (int i = 0; i < 8; i++) { children[i].GetColliding(ref checkBounds, result, flt); } } } /// <summary> /// Returns an array of objects that intersect with the specified bounds, if any. Otherwise returns an empty array. See also: IsColliding. /// </summary> /// <param name="checkBounds">Bounds to check. Passing by ref as it improve performance with structs.</param> /// <param name="result">List result.</param> /// <returns>Objects that intersect with the specified bounds.</returns> public void GetColliding(ref Line checkBounds, List<T> result, Filter<T> flt) { // Are the input bounds at least partially in this node? if (!bounds.IntersectRay(checkBounds)) { return; } // Check against any objects in this node for (int i = 0; i < objects.Count; i++) { if (objects[i].Bounds.IntersectRay(checkBounds)) { result.Add(objects[i].Obj); } } // Check children if (children != null) { for (int i = 0; i < 8; i++) { children[i].GetColliding(ref checkBounds, result, flt); } } } /// <summary> /// Set the 8 children of this octree. /// </summary> /// <param name="childOctrees">The 8 new child nodes.</param> public void SetChildren(BoundsOctreeNode<T>[] childOctrees) { if (childOctrees.Length != 8) { //Debug.LogError("Child octree array must be length 8. Was length: " + childOctrees.Length); return; } children = childOctrees; } /* /// <summary> /// Draws node boundaries visually for debugging. /// Must be called from OnDrawGizmos externally. See also: DrawAllObjects. /// </summary> /// <param name="depth">Used for recurcive calls to this method.</param> public void DrawAllBounds(float depth = 0) { float tintVal = depth / 7; // Will eventually get values > 1. Color rounds to 1 automatically Gizmos.color = new Color(tintVal, 0, 1.0f - tintVal); Bounds thisBounds = new HLBoundingBoxXYZ(Center, new Vector3(adjLength, adjLength, adjLength)); Gizmos.DrawWireCube(thisBounds.center, thisBounds.size); if (children != null) { depth++; for (int i = 0; i < 8; i++) { children[i].DrawAllBounds(depth); } } Gizmos.color = Color.white; } /// <summary> /// Draws the bounds of all objects in the tree visually for debugging. /// Must be called from OnDrawGizmos externally. See also: DrawAllBounds. /// </summary> public void DrawAllObjects() { float tintVal = BaseLength / 20; Gizmos.color = new Color(0, 1.0f - tintVal, tintVal, 0.25f); foreach (OctreeObject obj in objects) { Gizmos.DrawCube(obj.Bounds.center, obj.Bounds.size); } if (children != null) { for (int i = 0; i < 8; i++) { children[i].DrawAllObjects(); } } Gizmos.color = Color.white; } */ /// <summary> /// We can shrink the octree if: /// - This node is >= double minLength in length /// - All objects in the root node are within one octant /// - This node doesn't have children, or does but 7/8 children are empty /// We can also shrink it if there are no objects left at all! /// </summary> /// <param name="minLength">Minimum dimensions of a node in this octree.</param> /// <returns>The new root, or the existing one if we didn't shrink.</returns> public BoundsOctreeNode<T> ShrinkIfPossible(float minLength) { if (BaseLength < (2 * minLength)) { return this; } if (objects.Count == 0 && children.Length == 0) { return this; } // Check objects in root int bestFit = -1; for (int i = 0; i < objects.Count; i++) { OctreeObject curObj = objects[i]; int newBestFit = BestFitChild(curObj.Bounds); if (i == 0 || newBestFit == bestFit) { // In same octant as the other(s). Does it fit completely inside that octant? if (Encapsulates(childBounds[newBestFit], curObj.Bounds)) { if (bestFit < 0) { bestFit = newBestFit; } } else { // Nope, so we can't reduce. Otherwise we continue return this; } } else { return this; // Can't reduce - objects fit in different octants } } // Check objects in children if there are any if (children != null) { bool childHadContent = false; for (int i = 0; i < children.Length; i++) { if (children[i].HasAnyObjects()) { if (childHadContent) { return this; // Can't shrink - another child had content already } if (bestFit >= 0 && bestFit != i) { return this; // Can't reduce - objects in root are in a different octant to objects in child } childHadContent = true; bestFit = i; } } } // Can reduce if (children == null) { // We don't have any children, so just shrink this node to the new size // We already know that everything will still fit in it SetValues(BaseLength / 2, minSize, looseness, childBounds[bestFit].MidPoint); return this; } // We have children. Use the appropriate child as the new root node return children[bestFit]; } /* /// <summary> /// Get the total amount of objects in this node and all its children, grandchildren etc. Useful for debugging. /// </summary> /// <param name="startingNum">Used by recursive calls to add to the previous total.</param> /// <returns>Total objects in this node and its children, grandchildren etc.</returns> public int GetTotalObjects(int startingNum = 0) { int totalObjects = startingNum + objects.Count; if (children != null) { for (int i = 0; i < 8; i++) { totalObjects += children[i].GetTotalObjects(); } } return totalObjects; } */ // #### PRIVATE METHODS #### /// <summary> /// Set values for this node. /// </summary> /// <param name="baseLengthVal">Length of this node, not taking looseness into account.</param> /// <param name="minSizeVal">Minimum size of nodes in this octree.</param> /// <param name="loosenessVal">Multiplier for baseLengthVal to get the actual size.</param> /// <param name="centerVal">Centre position of this node.</param> void SetValues(float baseLengthVal, float minSizeVal, float loosenessVal, XYZ centerVal) { BaseLength = baseLengthVal; minSize = minSizeVal; looseness = loosenessVal; Center = centerVal; adjLength = looseness * baseLengthVal; // Create the bounding box. var size = new XYZ(adjLength, adjLength, adjLength); bounds = new HLBoundingBoxXYZ(Center, size); float quarter = BaseLength / 4f; float childActualLength = (BaseLength / 2) * looseness; var childActualSize = new XYZ(childActualLength, childActualLength, childActualLength); childBounds = new HLBoundingBoxXYZ[8]; childBounds[0] = new HLBoundingBoxXYZ(Center + new XYZ(-quarter, quarter, -quarter), childActualSize); childBounds[1] = new HLBoundingBoxXYZ(Center + new XYZ(quarter, quarter, -quarter), childActualSize); childBounds[2] = new HLBoundingBoxXYZ(Center + new XYZ(-quarter, quarter, quarter), childActualSize); childBounds[3] = new HLBoundingBoxXYZ(Center + new XYZ(quarter, quarter, quarter), childActualSize); childBounds[4] = new HLBoundingBoxXYZ(Center + new XYZ(-quarter, -quarter, -quarter), childActualSize); childBounds[5] = new HLBoundingBoxXYZ(Center + new XYZ(quarter, -quarter, -quarter), childActualSize); childBounds[6] = new HLBoundingBoxXYZ(Center + new XYZ(-quarter, -quarter, quarter), childActualSize); childBounds[7] = new HLBoundingBoxXYZ(Center + new XYZ(quarter, -quarter, quarter), childActualSize); } /// <summary> /// Private counterpart to the public Add method. /// </summary> /// <param name="obj">Object to add.</param> /// <param name="objBounds">3D bounding box around the object.</param> void SubAdd(T obj, HLBoundingBoxXYZ objBounds) { // We know it fits at this level if we've got this far // Just add if few objects are here, or children would be below min size if (objects.Count < numObjectsAllowed || (BaseLength / 2) < minSize) { OctreeObject newObj = new OctreeObject { Obj = obj, Bounds = objBounds }; //Debug.Log("ADD " + obj.name + " to depth " + depth); objects.Add(newObj); } else { // Fits at this level, but we can go deeper. Would it fit there? // Create the 8 children int bestFitChild; if (children == null) { Split(); if (children == null) { // Debug.Log("Child creation failed for an unknown reason. Early exit."); return; } // Now that we have the new children, see if this node's existing objects would fit there for (int i = objects.Count - 1; i >= 0; i--) { OctreeObject existingObj = objects[i]; // Find which child the object is closest to based on where the // object's center is located in relation to the octree's center. bestFitChild = BestFitChild(existingObj.Bounds); // Does it fit? if (Encapsulates(children[bestFitChild].bounds, existingObj.Bounds)) { children[bestFitChild].SubAdd(existingObj.Obj, existingObj.Bounds); // Go a level deeper objects.Remove(existingObj); // Remove from here } } } // Now handle the new object we're adding now bestFitChild = BestFitChild(objBounds); if (Encapsulates(children[bestFitChild].bounds, objBounds)) { children[bestFitChild].SubAdd(obj, objBounds); } else { OctreeObject newObj = new OctreeObject { Obj = obj, Bounds = objBounds }; //Debug.Log("ADD " + obj.name + " to depth " + depth); objects.Add(newObj); } } } /// <summary> /// Splits the octree into eight children. /// </summary> void Split() { float quarter = BaseLength / 4f; float newLength = BaseLength / 2; children = new BoundsOctreeNode<T>[8]; children[0] = new BoundsOctreeNode<T>(newLength, minSize, looseness, Center + new XYZ(-quarter, quarter, -quarter)); children[1] = new BoundsOctreeNode<T>(newLength, minSize, looseness, Center + new XYZ(quarter, quarter, -quarter)); children[2] = new BoundsOctreeNode<T>(newLength, minSize, looseness, Center + new XYZ(-quarter, quarter, quarter)); children[3] = new BoundsOctreeNode<T>(newLength, minSize, looseness, Center + new XYZ(quarter, quarter, quarter)); children[4] = new BoundsOctreeNode<T>(newLength, minSize, looseness, Center + new XYZ(-quarter, -quarter, -quarter)); children[5] = new BoundsOctreeNode<T>(newLength, minSize, looseness, Center + new XYZ(quarter, -quarter, -quarter)); children[6] = new BoundsOctreeNode<T>(newLength, minSize, looseness, Center + new XYZ(-quarter, -quarter, quarter)); children[7] = new BoundsOctreeNode<T>(newLength, minSize, looseness, Center + new XYZ(quarter, -quarter, quarter)); } /// <summary> /// Merge all children into this node - the opposite of Split. /// Note: We only have to check one level down since a merge will never happen if the children already have children, /// since THAT won't happen unless there are already too many objects to merge. /// </summary> void Merge() { // Note: We know children != null or we wouldn't be merging for (int i = 0; i < 8; i++) { BoundsOctreeNode<T> curChild = children[i]; int numObjects = curChild.objects.Count; for (int j = numObjects - 1; j >= 0; j--) { OctreeObject curObj = curChild.objects[j]; objects.Add(curObj); } } // Remove the child nodes (and the objects in them - they've been added elsewhere now) children = null; } /// <summary> /// Checks if outerBounds encapsulates innerBounds. /// </summary> /// <param name="outerBounds">Outer bounds.</param> /// <param name="innerBounds">Inner bounds.</param> /// <returns>True if innerBounds is fully encapsulated by outerBounds.</returns> static bool Encapsulates(HLBoundingBoxXYZ outerBounds, HLBoundingBoxXYZ innerBounds) { return outerBounds.Contains(innerBounds.Min) && outerBounds.Contains(innerBounds.Max); } /// <summary> /// Find which child node this object would be most likely to fit in. /// </summary> /// <param name="objBounds">The object's bounds.</param> /// <returns>One of the eight child octants.</returns> int BestFitChild(HLBoundingBoxXYZ objBounds) { return (objBounds.MidPoint.X <= Center.X ? 0 : 1) + (objBounds.MidPoint.Y >= Center.Y ? 0 : 4) + (objBounds.MidPoint.Z <= Center.Z ? 0 : 2); } /// <summary> /// Checks if there are few enough objects in this node and its children that the children should all be merged into this. /// </summary> /// <returns>True there are less or the same abount of objects in this and its children than numObjectsAllowed.</returns> bool ShouldMerge() { int totalObjects = objects.Count; if (children != null) { foreach (BoundsOctreeNode<T> child in children) { if (child.children != null) { // If any of the *children* have children, there are definitely too many to merge, // or the child woudl have been merged already return false; } totalObjects += child.objects.Count; } } return totalObjects <= numObjectsAllowed; } /// <summary> /// Checks if this node or anything below it has something in it. /// </summary> /// <returns>True if this node or any of its children, grandchildren etc have something in them</returns> bool HasAnyObjects() { if (objects.Count > 0) return true; if (children != null) { for (int i = 0; i < 8; i++) { if (children[i].HasAnyObjects()) return true; } } return false; } } }
39.798722
152
0.512162
[ "MIT" ]
menome/BuildingGraph-Client-Revit
BuildingGraph.Integration.Revit/Geometry/Octree/BoundsOctreeNode.cs
24,916
C#
using MG_Library; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Hwatu.MonoGameComponents.Drawables { public class OutlineImage : Sprite2D { public OutlineImage(Game game) : base(game, null) { } protected override void LoadContent() { base.LoadContent(); Texture = new Texture2D(Game.GraphicsDevice, 50, 81); Color[] data = new Color[50 * 81]; for (int i = 0; i < data.Length; ++i) data[i] = Color.Yellow; Texture.SetData(data); Width = Texture.Width; Height = Texture.Height; Origin = new Vector2(Width / 2, Height / 2); Alpha = 0.5f; } public void Draw(Vector2 scale) { SpriteBatch.Draw(Texture, Position, SourceRect, Color.White * Alpha, Rotation, Origin, scale, SpriteEffects.None, 0.0f); } } }
30.125
73
0.561203
[ "MIT" ]
ALee1303/GoStop
Hwatu/MonoGameComponents/Drawables/SpriteImage/OutlineImage.cs
966
C#
using System; using System.Collections.Generic; using NHapi.Base.Log; using NHapi.Model.V27.Group; using NHapi.Model.V27.Segment; using NHapi.Model.V27.Datatype; using NHapi.Base; using NHapi.Base.Parser; using NHapi.Base.Model; namespace NHapi.Model.V27.Message { ///<summary> /// Represents a RPI_I04 message structure (see chapter 11.3.4). This structure contains the /// following elements: ///<ol> ///<li>0: MSH (Message Header) </li> ///<li>1: SFT (Software Segment) optional repeating</li> ///<li>2: UAC (User Authentication Credential Segment) optional </li> ///<li>3: MSA (Message Acknowledgment) </li> ///<li>4: RPI_I04_PROVIDER (a Group object) repeating</li> ///<li>5: PID (Patient Identification) </li> ///<li>6: NK1 (Next of Kin / Associated Parties) optional repeating</li> ///<li>7: RPI_I04_GUARANTOR_INSURANCE (a Group object) optional </li> ///<li>8: NTE (Notes and Comments) optional repeating</li> ///</ol> ///</summary> [Serializable] public class RPI_I04 : AbstractMessage { ///<summary> /// Creates a new RPI_I04 Group with custom IModelClassFactory. ///</summary> public RPI_I04(IModelClassFactory factory) : base(factory){ init(factory); } ///<summary> /// Creates a new RPI_I04 Group with DefaultModelClassFactory. ///</summary> public RPI_I04() : base(new DefaultModelClassFactory()) { init(new DefaultModelClassFactory()); } ///<summary> /// initalize method for RPI_I04. This does the segment setup for the message. ///</summary> private void init(IModelClassFactory factory) { try { this.add(typeof(MSH), true, false); this.add(typeof(SFT), false, true); this.add(typeof(UAC), false, false); this.add(typeof(MSA), true, false); this.add(typeof(RPI_I04_PROVIDER), true, true); this.add(typeof(PID), true, false); this.add(typeof(NK1), false, true); this.add(typeof(RPI_I04_GUARANTOR_INSURANCE), false, false); this.add(typeof(NTE), false, true); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating RPI_I04 - this is probably a bug in the source code generator.", e); } } public override string Version { get{ return Constants.VERSION; } } ///<summary> /// Returns MSH (Message Header) - creates it if necessary ///</summary> public MSH MSH { get{ MSH ret = null; try { ret = (MSH)this.GetStructure("MSH"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of SFT (Software Segment) - creates it if necessary ///</summary> public SFT GetSFT() { SFT ret = null; try { ret = (SFT)this.GetStructure("SFT"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of SFT /// * (Software Segment) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public SFT GetSFT(int rep) { return (SFT)this.GetStructure("SFT", rep); } /** * Returns the number of existing repetitions of SFT */ public int SFTRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("SFT").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the SFT results */ public IEnumerable<SFT> SFTs { get { for (int rep = 0; rep < SFTRepetitionsUsed; rep++) { yield return (SFT)this.GetStructure("SFT", rep); } } } ///<summary> ///Adds a new SFT ///</summary> public SFT AddSFT() { return this.AddStructure("SFT") as SFT; } ///<summary> ///Removes the given SFT ///</summary> public void RemoveSFT(SFT toRemove) { this.RemoveStructure("SFT", toRemove); } ///<summary> ///Removes the SFT at the given index ///</summary> public void RemoveSFTAt(int index) { this.RemoveRepetition("SFT", index); } ///<summary> /// Returns UAC (User Authentication Credential Segment) - creates it if necessary ///</summary> public UAC UAC { get{ UAC ret = null; try { ret = (UAC)this.GetStructure("UAC"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns MSA (Message Acknowledgment) - creates it if necessary ///</summary> public MSA MSA { get{ MSA ret = null; try { ret = (MSA)this.GetStructure("MSA"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of RPI_I04_PROVIDER (a Group object) - creates it if necessary ///</summary> public RPI_I04_PROVIDER GetPROVIDER() { RPI_I04_PROVIDER ret = null; try { ret = (RPI_I04_PROVIDER)this.GetStructure("PROVIDER"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of RPI_I04_PROVIDER /// * (a Group object) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public RPI_I04_PROVIDER GetPROVIDER(int rep) { return (RPI_I04_PROVIDER)this.GetStructure("PROVIDER", rep); } /** * Returns the number of existing repetitions of RPI_I04_PROVIDER */ public int PROVIDERRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("PROVIDER").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the RPI_I04_PROVIDER results */ public IEnumerable<RPI_I04_PROVIDER> PROVIDERs { get { for (int rep = 0; rep < PROVIDERRepetitionsUsed; rep++) { yield return (RPI_I04_PROVIDER)this.GetStructure("PROVIDER", rep); } } } ///<summary> ///Adds a new RPI_I04_PROVIDER ///</summary> public RPI_I04_PROVIDER AddPROVIDER() { return this.AddStructure("PROVIDER") as RPI_I04_PROVIDER; } ///<summary> ///Removes the given RPI_I04_PROVIDER ///</summary> public void RemovePROVIDER(RPI_I04_PROVIDER toRemove) { this.RemoveStructure("PROVIDER", toRemove); } ///<summary> ///Removes the RPI_I04_PROVIDER at the given index ///</summary> public void RemovePROVIDERAt(int index) { this.RemoveRepetition("PROVIDER", index); } ///<summary> /// Returns PID (Patient Identification) - creates it if necessary ///</summary> public PID PID { get{ PID ret = null; try { ret = (PID)this.GetStructure("PID"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of NK1 (Next of Kin / Associated Parties) - creates it if necessary ///</summary> public NK1 GetNK1() { NK1 ret = null; try { ret = (NK1)this.GetStructure("NK1"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of NK1 /// * (Next of Kin / Associated Parties) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public NK1 GetNK1(int rep) { return (NK1)this.GetStructure("NK1", rep); } /** * Returns the number of existing repetitions of NK1 */ public int NK1RepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("NK1").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the NK1 results */ public IEnumerable<NK1> NK1s { get { for (int rep = 0; rep < NK1RepetitionsUsed; rep++) { yield return (NK1)this.GetStructure("NK1", rep); } } } ///<summary> ///Adds a new NK1 ///</summary> public NK1 AddNK1() { return this.AddStructure("NK1") as NK1; } ///<summary> ///Removes the given NK1 ///</summary> public void RemoveNK1(NK1 toRemove) { this.RemoveStructure("NK1", toRemove); } ///<summary> ///Removes the NK1 at the given index ///</summary> public void RemoveNK1At(int index) { this.RemoveRepetition("NK1", index); } ///<summary> /// Returns RPI_I04_GUARANTOR_INSURANCE (a Group object) - creates it if necessary ///</summary> public RPI_I04_GUARANTOR_INSURANCE GUARANTOR_INSURANCE { get{ RPI_I04_GUARANTOR_INSURANCE ret = null; try { ret = (RPI_I04_GUARANTOR_INSURANCE)this.GetStructure("GUARANTOR_INSURANCE"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of NTE (Notes and Comments) - creates it if necessary ///</summary> public NTE GetNTE() { NTE ret = null; try { ret = (NTE)this.GetStructure("NTE"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of NTE /// * (Notes and Comments) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public NTE GetNTE(int rep) { return (NTE)this.GetStructure("NTE", rep); } /** * Returns the number of existing repetitions of NTE */ public int NTERepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("NTE").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the NTE results */ public IEnumerable<NTE> NTEs { get { for (int rep = 0; rep < NTERepetitionsUsed; rep++) { yield return (NTE)this.GetStructure("NTE", rep); } } } ///<summary> ///Adds a new NTE ///</summary> public NTE AddNTE() { return this.AddStructure("NTE") as NTE; } ///<summary> ///Removes the given NTE ///</summary> public void RemoveNTE(NTE toRemove) { this.RemoveStructure("NTE", toRemove); } ///<summary> ///Removes the NTE at the given index ///</summary> public void RemoveNTEAt(int index) { this.RemoveRepetition("NTE", index); } } }
27.023404
145
0.65672
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AMCN41R/nHapi
src/NHapi.Model.V27/Message/RPI_I04.cs
12,701
C#
using System.Threading.Tasks; using SpotifyAPI.Web; namespace Spiralfy.Core.Interfaces { public interface ISpiralfyPlayer { public Task Play(); public Task Play(IPlayableItem item); public Task PlayShuffle(SimplePlaylist playlist); public Task Pause(); public Task<bool> PlayPause(); public Task<bool> IsPlaying(); public Task<IPlayableItem> GetCurrentlyPlaying(); public Task Next(); public Task Previous(); public Task<FullPlaylist> GetCurrentPlaylist(); } }
27.75
57
0.661261
[ "MIT" ]
DanteDeRuwe/spiralfy
controls/Spiralfy.Core/Interfaces/ISpiralfyPlayer.cs
557
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.Collections.Generic; using System.Data; using System.Data.Common; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Net.Http.Headers; using System.Runtime.CompilerServices; using System.Security; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.Data.Common; using Microsoft.Data.ProviderBase; using Microsoft.Identity.Client; using SysTx = System.Transactions; namespace Microsoft.Data.SqlClient { internal class SessionStateRecord { internal bool _recoverable; internal UInt32 _version; internal Int32 _dataLength; internal byte[] _data; } internal class SessionData { internal const int _maxNumberOfSessionStates = 256; internal UInt32 _tdsVersion; internal bool _encrypted; internal string _database; internal SqlCollation _collation; internal string _language; internal string _initialDatabase; internal SqlCollation _initialCollation; internal string _initialLanguage; internal byte _unrecoverableStatesCount = 0; internal Dictionary<string, Tuple<string, string>> _resolvedAliases; #if DEBUG internal bool _debugReconnectDataApplied; #endif internal SessionStateRecord[] _delta = new SessionStateRecord[_maxNumberOfSessionStates]; internal bool _deltaDirty = false; internal byte[][] _initialState = new byte[_maxNumberOfSessionStates][]; public SessionData(SessionData recoveryData) { _initialDatabase = recoveryData._initialDatabase; _initialCollation = recoveryData._initialCollation; _initialLanguage = recoveryData._initialLanguage; _resolvedAliases = recoveryData._resolvedAliases; for (int i = 0; i < _maxNumberOfSessionStates; i++) { if (recoveryData._initialState[i] != null) { _initialState[i] = (byte[])recoveryData._initialState[i].Clone(); } } } public SessionData() { _resolvedAliases = new Dictionary<string, Tuple<string, string>>(2); } public void Reset() { _database = null; _collation = null; _language = null; if (_deltaDirty) { _delta = new SessionStateRecord[_maxNumberOfSessionStates]; _deltaDirty = false; } _unrecoverableStatesCount = 0; } [Conditional("DEBUG")] public void AssertUnrecoverableStateCountIsCorrect() { byte unrecoverableCount = 0; foreach (var state in _delta) { if (state != null && !state._recoverable) unrecoverableCount++; } Debug.Assert(unrecoverableCount == _unrecoverableStatesCount, "Unrecoverable count does not match"); } } sealed internal class SqlInternalConnectionTds : SqlInternalConnection, IDisposable { // Connection re-route limit internal const int _maxNumberOfRedirectRoute = 10; // CONNECTION AND STATE VARIABLES private readonly SqlConnectionPoolGroupProviderInfo _poolGroupProviderInfo; // will only be null when called for ChangePassword, or creating SSE User Instance private TdsParser _parser; private SqlLoginAck _loginAck; private SqlCredential _credential; private FederatedAuthenticationFeatureExtensionData? _fedAuthFeatureExtensionData; // Connection Resiliency private bool _sessionRecoveryRequested; internal bool _sessionRecoveryAcknowledged; internal SessionData _currentSessionData; // internal for use from TdsParser only, other should use CurrentSessionData property that will fix database and language private SessionData _recoverySessionData; // Federated Authentication // Response obtained from the server for FEDAUTHREQUIRED prelogin option. internal bool _fedAuthRequired; internal bool _federatedAuthenticationRequested; internal bool _federatedAuthenticationAcknowledged; internal bool _federatedAuthenticationInfoRequested; // Keep this distinct from _federatedAuthenticationRequested, since some fedauth library types may not need more info internal bool _federatedAuthenticationInfoReceived; // The Federated Authentication returned by TryGetFedAuthTokenLocked or GetFedAuthToken. SqlFedAuthToken _fedAuthToken = null; internal byte[] _accessTokenInBytes; private readonly ActiveDirectoryAuthenticationTimeoutRetryHelper _activeDirectoryAuthTimeoutRetryHelper; private readonly SqlAuthenticationProviderManager _sqlAuthenticationProviderManager; // Certificate auth calbacks. ServerCertificateValidationCallback _serverCallback; ClientCertificateRetrievalCallback _clientCallback; SqlClientOriginalNetworkAddressInfo _originalNetworkAddressInfo; internal bool _cleanSQLDNSCaching = false; private bool _serverSupportsDNSCaching = false; /// <summary> /// Returns buffer time allowed before access token expiry to continue using the access token. /// </summary> private int accessTokenExpirationBufferTime { get { return (ConnectionOptions.ConnectTimeout == ADP.InfiniteConnectionTimeout || ConnectionOptions.ConnectTimeout >= ADP.MaxBufferAccessTokenExpiry) ? ADP.MaxBufferAccessTokenExpiry : ConnectionOptions.ConnectTimeout; } } /// <summary> /// Get or set if SQLDNSCaching FeatureExtAck is supported by the server. /// </summary> internal bool IsSQLDNSCachingSupported { get { return _serverSupportsDNSCaching; } set { _serverSupportsDNSCaching = value; } } private bool _SQLDNSRetryEnabled = false; /// <summary> /// Get or set if we need retrying with IP received from FeatureExtAck. /// </summary> internal bool IsSQLDNSRetryEnabled { get { return _SQLDNSRetryEnabled; } set { _SQLDNSRetryEnabled = value; } } private bool DNSCachingBeforeRedirect = false; /// <summary> /// Get or set if the control ring send redirect token and SQLDNSCaching FeatureExtAck with true /// </summary> internal bool IsDNSCachingBeforeRedirectSupported { get { return DNSCachingBeforeRedirect; } set { DNSCachingBeforeRedirect = value; } } internal SQLDNSInfo pendingSQLDNSObject = null; // TCE flags internal byte _tceVersionSupported; // The pool that this connection is associated with, if at all it is. private DbConnectionPool _dbConnectionPool; // This is used to preserve the authentication context object if we decide to cache it for subsequent connections in the same pool. // This will finally end up in _dbConnectionPool.AuthenticationContexts, but only after 1 successful login to SQL Server using this context. // This variable is to persist the context after we have generated it, but before we have successfully completed the login with this new context. // If this connection attempt ended up re-using the existing context and not create a new one, this will be null (since the context is not new). private DbConnectionPoolAuthenticationContext _newDbConnectionPoolAuthenticationContext; // The key of the authentication context, built from information found in the FedAuthInfoToken. private DbConnectionPoolAuthenticationContextKey _dbConnectionPoolAuthenticationContextKey; #if DEBUG // This is a test hook to enable testing of the retry paths for MSAL get access token. // Sample code to enable: // // Type type = typeof(SqlConnection).Assembly.GetType("Microsoft.Data.SqlClient.SQLInternalConnectionTds"); // System.Reflection.FieldInfo field = type.GetField("_forceMsalRetry", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static); // if (field != null) { // field.SetValue(null, true); // } // internal static bool _forceMsalRetry = false; // This is a test hook to simulate a token expiring within the next 45 minutes. private static bool _forceExpiryLocked = false; // This is a test hook to simulate a token expiring within the next 10 minutes. private static bool _forceExpiryUnLocked = false; #endif //DEBUG // The timespan defining the amount of time the authentication context needs to be valid for at-least, to re-use the cached context, // without making an attempt to refresh it. IF the context is expiring within the next 45 mins, then try to take a lock and refresh // the context, if the lock is acquired. private static readonly TimeSpan _dbAuthenticationContextLockedRefreshTimeSpan = new TimeSpan(hours: 0, minutes: 45, seconds: 00); // The timespan defining the minimum amount of time the authentication context needs to be valid for re-using the cached context. // If the context is expiring within the next 10 mins, then create a new context, irrespective of if another thread is trying to do the same. private static readonly TimeSpan _dbAuthenticationContextUnLockedRefreshTimeSpan = new TimeSpan(hours: 0, minutes: 10, seconds: 00); private readonly TimeoutTimer _timeout; private static HashSet<int> transientErrors = new HashSet<int>(); internal SessionData CurrentSessionData { get { if (_currentSessionData != null) { _currentSessionData._database = CurrentDatabase; _currentSessionData._language = _currentLanguage; } return _currentSessionData; } } // FOR POOLING private bool _fConnectionOpen = false; // FOR CONNECTION RESET MANAGEMENT private bool _fResetConnection; private string _originalDatabase; private string _currentFailoverPartner; // only set by ENV change from server private string _originalLanguage; private string _currentLanguage; private int _currentPacketSize; private int _asyncCommandCount; // number of async Begins minus number of async Ends. // FOR SSE private string _instanceName = String.Empty; // FOR NOTIFICATIONS private DbConnectionPoolIdentity _identity; // Used to lookup info for notification matching Start(). // FOR SYNCHRONIZATION IN TdsParser // How to use these locks: // 1. Whenever writing to the connection (with the exception of Cancellation) the _parserLock MUST be taken // 2. _parserLock will also be taken during close (to prevent closing in the middle of a write) // 3. Whenever you have the _parserLock and are calling a method that would cause the connection to close if it failed (with the exception of any writing method), you MUST set ThreadHasParserLockForClose to true // * This is to prevent the connection deadlocking with itself (since you already have the _parserLock, and Closing the connection will attempt to re-take that lock) // * It is safe to set ThreadHasParserLockForClose to true when writing as well, but it is unneccesary // * If you have a method that takes _parserLock, it is a good idea check ThreadHasParserLockForClose first (if you don't expect _parserLock to be taken by something higher on the stack, then you should at least assert that it is false) // 4. ThreadHasParserLockForClose is thread-specific - this means that you must set it to false before returning a Task, and set it back to true in the continuation // 5. ThreadHasParserLockForClose should only be modified if you currently own the _parserLock // 6. Reading ThreadHasParserLockForClose is thread-safe internal class SyncAsyncLock { SemaphoreSlim semaphore = new SemaphoreSlim(1); internal void Wait(bool canReleaseFromAnyThread) { Monitor.Enter(semaphore); // semaphore is used as lock object, no relation to SemaphoreSlim.Wait/Release methods if (canReleaseFromAnyThread || semaphore.CurrentCount == 0) { semaphore.Wait(); if (canReleaseFromAnyThread) { Monitor.Exit(semaphore); } else { semaphore.Release(); } } } internal void Wait(bool canReleaseFromAnyThread, int timeout, ref bool lockTaken) { lockTaken = false; bool hasMonitor = false; try { Monitor.TryEnter(semaphore, timeout, ref hasMonitor); // semaphore is used as lock object, no relation to SemaphoreSlim.Wait/Release methods if (hasMonitor) { if ((canReleaseFromAnyThread) || (semaphore.CurrentCount == 0)) { if (semaphore.Wait(timeout)) { if (canReleaseFromAnyThread) { Monitor.Exit(semaphore); hasMonitor = false; } else { semaphore.Release(); } lockTaken = true; } } else { lockTaken = true; } } } finally { if ((!lockTaken) && (hasMonitor)) { Monitor.Exit(semaphore); } } } internal void Release() { if (semaphore.CurrentCount == 0) { // semaphore methods were used for locking semaphore.Release(); } else { Monitor.Exit(semaphore); } } internal bool CanBeReleasedFromAnyThread { get { return semaphore.CurrentCount == 0; } } // Necessary but not sufficient condition for thread to have lock (since sempahore may be obtained by any thread) internal bool ThreadMayHaveLock() { return Monitor.IsEntered(semaphore) || semaphore.CurrentCount == 0; } } internal SyncAsyncLock _parserLock = new SyncAsyncLock(); private int _threadIdOwningParserLock = -1; private SqlConnectionTimeoutErrorInternal timeoutErrorInternal; internal SqlConnectionTimeoutErrorInternal TimeoutErrorInternal { get { return timeoutErrorInternal; } } // OTHER STATE VARIABLES AND REFERENCES internal Guid _clientConnectionId = Guid.Empty; // Routing information (ROR) RoutingInfo _routingInfo = null; private Guid _originalClientConnectionId = Guid.Empty; private string _routingDestination = null; static SqlInternalConnectionTds() { populateTransientErrors(); } // although the new password is generally not used it must be passed to the c'tor // the new Login7 packet will always write out the new password (or a length of zero and no bytes if not present) // internal SqlInternalConnectionTds( DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, object providerInfo, string newPassword, SecureString newSecurePassword, bool redirectedUserInstance, SqlConnectionString userConnectionOptions = null, // NOTE: userConnectionOptions may be different to connectionOptions if the connection string has been expanded (see SqlConnectionString.Expand) SessionData reconnectSessionData = null, ServerCertificateValidationCallback serverCallback = null, ClientCertificateRetrievalCallback clientCallback = null, DbConnectionPool pool = null, string accessToken = null, SqlClientOriginalNetworkAddressInfo originalNetworkAddressInfo = null, bool applyTransientFaultHandling = false) : base(connectionOptions) { #if DEBUG if (reconnectSessionData != null) { reconnectSessionData._debugReconnectDataApplied = true; } try { // use this to help validate this object is only created after the following permission has been previously demanded in the current codepath if (userConnectionOptions != null) { // As mentioned above, userConnectionOptions may be different to connectionOptions, so we need to demand on the correct connection string userConnectionOptions.DemandPermission(); } else { connectionOptions.DemandPermission(); } } catch (System.Security.SecurityException) { System.Diagnostics.Debug.Assert(false, "unexpected SecurityException for current codepath"); throw; } #endif Debug.Assert(reconnectSessionData == null || connectionOptions.ConnectRetryCount > 0, "Reconnect data supplied with CR turned off"); _dbConnectionPool = pool; if (connectionOptions.ConnectRetryCount > 0) { _recoverySessionData = reconnectSessionData; if (reconnectSessionData == null) { _currentSessionData = new SessionData(); } else { _currentSessionData = new SessionData(_recoverySessionData); _originalDatabase = _recoverySessionData._initialDatabase; _originalLanguage = _recoverySessionData._initialLanguage; } } if (connectionOptions.UserInstance && InOutOfProcHelper.InProc) { throw SQL.UserInstanceNotAvailableInProc(); } if (accessToken != null) { _accessTokenInBytes = System.Text.Encoding.Unicode.GetBytes(accessToken); } _activeDirectoryAuthTimeoutRetryHelper = new ActiveDirectoryAuthenticationTimeoutRetryHelper(); _sqlAuthenticationProviderManager = SqlAuthenticationProviderManager.Instance; _serverCallback = serverCallback; _clientCallback = clientCallback; _originalNetworkAddressInfo = originalNetworkAddressInfo; _identity = identity; Debug.Assert(newSecurePassword != null || newPassword != null, "cannot have both new secure change password and string based change password to be null"); Debug.Assert(credential == null || (String.IsNullOrEmpty(connectionOptions.UserID) && String.IsNullOrEmpty(connectionOptions.Password)), "cannot mix the new secure password system and the connection string based password"); Debug.Assert(credential == null || !connectionOptions.IntegratedSecurity, "Cannot use SqlCredential and Integrated Security"); Debug.Assert(credential == null || !connectionOptions.ContextConnection, "Cannot use SqlCredential with context connection"); _poolGroupProviderInfo = (SqlConnectionPoolGroupProviderInfo)providerInfo; _fResetConnection = connectionOptions.ConnectionReset; if (_fResetConnection && _recoverySessionData == null) { _originalDatabase = connectionOptions.InitialCatalog; _originalLanguage = connectionOptions.CurrentLanguage; } timeoutErrorInternal = new SqlConnectionTimeoutErrorInternal(); _credential = credential; _parserLock.Wait(canReleaseFromAnyThread: false); ThreadHasParserLockForClose = true; // In case of error, let ourselves know that we already own the parser lock RuntimeHelpers.PrepareConstrainedRegions(); try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); try { tdsReliabilitySection.Start(); #else { #endif //DEBUG _timeout = TimeoutTimer.StartSecondsTimeout(connectionOptions.ConnectTimeout); // If transient fault handling is enabled then we can retry the login upto the ConnectRetryCount. int connectionEstablishCount = applyTransientFaultHandling ? connectionOptions.ConnectRetryCount + 1 : 1; int transientRetryIntervalInMilliSeconds = connectionOptions.ConnectRetryInterval * 1000; // Max value of transientRetryInterval is 60*1000 ms. The max value allowed for ConnectRetryInterval is 60 for (int i = 0; i < connectionEstablishCount; i++) { try { OpenLoginEnlist(_timeout, connectionOptions, credential, newPassword, newSecurePassword, redirectedUserInstance); break; } catch (SqlException sqlex) { if (i + 1 == connectionEstablishCount || !applyTransientFaultHandling || _timeout.IsExpired || _timeout.MillisecondsRemaining < transientRetryIntervalInMilliSeconds || !IsTransientError(sqlex)) { throw; } else { Thread.Sleep(transientRetryIntervalInMilliSeconds); } } } } #if DEBUG finally { tdsReliabilitySection.Stop(); } #endif //DEBUG } catch (System.OutOfMemoryException) { DoomThisConnection(); throw; } catch (System.StackOverflowException) { DoomThisConnection(); throw; } catch (System.Threading.ThreadAbortException) { DoomThisConnection(); throw; } finally { ThreadHasParserLockForClose = false; _parserLock.Release(); } SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.ctor|ADV> {0}, constructed new TDS internal connection", ObjectID); } // The erros in the transient error set are contained in // https://azure.microsoft.com/en-us/documentation/articles/sql-database-develop-error-messages/#transient-faults-connection-loss-and-other-temporary-errors private static void populateTransientErrors() { // SQL Error Code: 4060 // Cannot open database "%.*ls" requested by the login. The login failed. transientErrors.Add(4060); // SQL Error Code: 10928 // Resource ID: %d. The %s limit for the database is %d and has been reached. transientErrors.Add(10928); // SQL Error Code: 10929 // Resource ID: %d. The %s minimum guarantee is %d, maximum limit is %d and the current usage for the database is %d. // However, the server is currently too busy to support requests greater than %d for this database. transientErrors.Add(10929); // SQL Error Code: 40197 // You will receive this error, when the service is down due to software or hardware upgrades, hardware failures, // or any other failover problems. The error code (%d) embedded within the message of error 40197 provides // additional information about the kind of failure or failover that occurred. Some examples of the error codes are // embedded within the message of error 40197 are 40020, 40143, 40166, and 40540. transientErrors.Add(40197); transientErrors.Add(40020); transientErrors.Add(40143); transientErrors.Add(40166); // The service has encountered an error processing your request. Please try again. transientErrors.Add(40540); // The service is currently busy. Retry the request after 10 seconds. Incident ID: %ls. Code: %d. transientErrors.Add(40501); // Database '%.*ls' on server '%.*ls' is not currently available. Please retry the connection later. // If the problem persists, contact customer support, and provide them the session tracing ID of '%.*ls'. transientErrors.Add(40613); // Do federation errors deserve to be here ? // Note: Federation errors 10053 and 10054 might also deserve inclusion in your retry logic. //transientErrors.Add(10053); //transientErrors.Add(10054); } // Returns true if the Sql error is a transient. private bool IsTransientError(SqlException exc) { if (exc == null) { return false; } foreach (SqlError error in exc.Errors) { if (transientErrors.Contains(error.Number)) { // When server timeouts, connection is doomed. Reset here to allow reconnect. UnDoomThisConnection(); return true; } } return false; } internal Guid ClientConnectionId { get { return _clientConnectionId; } } internal Guid OriginalClientConnectionId { get { return _originalClientConnectionId; } } internal string RoutingDestination { get { return _routingDestination; } } internal RoutingInfo RoutingInfo { get { return _routingInfo; } } override internal SqlInternalTransaction CurrentTransaction { get { return _parser.CurrentTransaction; } } override internal SqlInternalTransaction AvailableInternalTransaction { get { return _parser._fResetConnection ? null : CurrentTransaction; } } override internal SqlInternalTransaction PendingTransaction { get { return _parser.PendingTransaction; } } internal DbConnectionPoolIdentity Identity { get { return _identity; } } internal string InstanceName { get { return _instanceName; } } override internal bool IsLockedForBulkCopy { get { return (!Parser.MARSOn && Parser._physicalStateObj.BcpLock); } } override protected internal bool IsNonPoolableTransactionRoot { get { return IsTransactionRoot && (!IsKatmaiOrNewer || null == Pool); } } override internal bool IsShiloh { get { return _loginAck.isVersion8; } } override internal bool IsYukonOrNewer { get { return _parser.IsYukonOrNewer; } } override internal bool IsKatmaiOrNewer { get { return _parser.IsKatmaiOrNewer; } } internal int PacketSize { get { return _currentPacketSize; } } internal TdsParser Parser { get { return _parser; } } internal string ServerProvidedFailOverPartner { get { return _currentFailoverPartner; } } internal SqlConnectionPoolGroupProviderInfo PoolGroupProviderInfo { get { return _poolGroupProviderInfo; } } override protected bool ReadyToPrepareTransaction { get { // TODO: probably need to use a different method, but that's a different bug bool result = (null == FindLiveReader(null)); // can't prepare with a live data reader... return result; } } override public string ServerVersion { get { return (string.Format("{0:00}.{1:00}.{2:0000}", _loginAck.majorVersion, (short)_loginAck.minorVersion, _loginAck.buildNum)); } } public int ServerProcessId { get { return Parser._physicalStateObj._spid; } } /// <summary> /// Get boolean that specifies whether an enlisted transaction can be unbound from /// the connection when that transaction completes. /// </summary> /// <value> /// This override always returns false. /// </value> /// <remarks> /// The SqlInternalConnectionTds.CheckEnlistedTransactionBinding method handles implicit unbinding for disposed transactions. /// </remarks> protected override bool UnbindOnTransactionCompletion { get { return false; } } /// <summary> /// Validates if federated authentication is used, Access Token used by this connection is active for the value of 'accessTokenExpirationBufferTime'. /// </summary> internal override bool IsAccessTokenExpired => _federatedAuthenticationInfoRequested && DateTime.FromFileTimeUtc(_fedAuthToken.expirationFileTime) < DateTime.UtcNow.AddSeconds(accessTokenExpirationBufferTime); //////////////////////////////////////////////////////////////////////////////////////// // GENERAL METHODS //////////////////////////////////////////////////////////////////////////////////////// [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // copied from Triaged.cs override protected void ChangeDatabaseInternal(string database) { // MDAC 73598 - add brackets around database database = SqlConnection.FixupDatabaseTransactionName(database); System.Threading.Tasks.Task executeTask = _parser.TdsExecuteSQLBatch("use " + database, ConnectionOptions.ConnectTimeout, null, _parser._physicalStateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); _parser.Run(RunBehavior.UntilDone, null, null, null, _parser._physicalStateObj); } override public void Dispose() { SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.Dispose|ADV> {0} disposing", ObjectID); try { TdsParser parser = Interlocked.Exchange(ref _parser, null); // guard against multiple concurrent dispose calls -- Delegated Transactions might cause this. Debug.Assert(parser != null && _fConnectionOpen || parser == null && !_fConnectionOpen, "Unexpected state on dispose"); if (null != parser) { parser.Disconnect(); } } finally { // UNDONE: MDAC 77928 // close will always close, even if exception is thrown // remember to null out any object references _loginAck = null; _fConnectionOpen = false; // mark internal connection as closed } base.Dispose(); } override internal void ValidateConnectionForExecute(SqlCommand command) { TdsParser parser = _parser; if ((parser == null) || (parser.State == TdsParserState.Broken) || (parser.State == TdsParserState.Closed)) { throw ADP.ClosedConnectionError(); } else { SqlDataReader reader = null; if (parser.MARSOn) { if (null != command) { // command can't have datareader already associated with it reader = FindLiveReader(command); } } else { // single execution/datareader per connection if (_asyncCommandCount > 0) { throw SQL.MARSUnsupportedOnConnection(); } reader = FindLiveReader(null); } if (null != reader) { // if MARS is on, then a datareader associated with the command exists // or if MARS is off, then a datareader exists throw ADP.OpenReaderExists(parser.MARSOn); // MDAC 66411 } else if (!parser.MARSOn && parser._physicalStateObj._pendingData) { parser.DrainData(parser._physicalStateObj); } Debug.Assert(!parser._physicalStateObj._pendingData, "Should not have a busy physicalStateObject at this point!"); parser.RollbackOrphanedAPITransactions(); } } /// <summary> /// Validate the enlisted transaction state, taking into consideration the ambient transaction and transaction unbinding mode. /// If there is no enlisted transaction, this method is a nop. /// </summary> /// <remarks> /// <para> /// This method must be called while holding a lock on the SqlInternalConnection instance, /// to ensure we don't accidentally execute after the transaction has completed on a different thread, /// causing us to unwittingly execute in auto-commit mode. /// </para> /// /// <para> /// When using Explicit transaction unbinding, /// verify that the enlisted transaction is active and equal to the current ambient transaction. /// </para> /// /// <para> /// When using Implicit transaction unbinding, /// verify that the enlisted transaction is active. /// If it is not active, and the transaction object has been diposed, unbind from the transaction. /// If it is not active and not disposed, throw an exception. /// </para> /// </remarks> internal void CheckEnlistedTransactionBinding() { // If we are enlisted in a transaction, check that transaction is active. // When using explicit transaction unbinding, also verify that the enlisted transaction is the current transaction. SysTx.Transaction enlistedTransaction = EnlistedTransaction; if (enlistedTransaction != null) { bool requireExplicitTransactionUnbind = ConnectionOptions.TransactionBinding == SqlConnectionString.TransactionBindingEnum.ExplicitUnbind; if (requireExplicitTransactionUnbind) { SysTx.Transaction currentTransaction = SysTx.Transaction.Current; if (SysTx.TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status || !enlistedTransaction.Equals(currentTransaction)) { throw ADP.TransactionConnectionMismatch(); } } else // implicit transaction unbind { if (SysTx.TransactionStatus.Active != enlistedTransaction.TransactionInformation.Status) { if (EnlistedTransactionDisposed) { DetachTransaction(enlistedTransaction, true); } else { throw ADP.TransactionCompletedButNotDisposed(); } } } } } internal override bool IsConnectionAlive(bool throwOnException) { bool isAlive = false; #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); try { tdsReliabilitySection.Start(); #endif //DEBUG isAlive = _parser._physicalStateObj.IsConnectionAlive(throwOnException); #if DEBUG } finally { tdsReliabilitySection.Stop(); } #endif //DEBUG return isAlive; } //////////////////////////////////////////////////////////////////////////////////////// // POOLING METHODS //////////////////////////////////////////////////////////////////////////////////////// override protected void Activate(SysTx.Transaction transaction) { FailoverPermissionDemand(); // Demand for unspecified failover pooled connections // When we're required to automatically enlist in transactions and // there is one we enlist in it. On the other hand, if there isn't a // transaction and we are currently enlisted in one, then we // unenlist from it. // // Regardless of whether we're required to automatically enlist, // when there is not a current transaction, we cannot leave the // connection enlisted in a transaction. if (null != transaction) { if (ConnectionOptions.Enlist) { Enlist(transaction); } } else { Enlist(null); } } override protected void InternalDeactivate() { // When we're deactivated, the user must have called End on all // the async commands, or we don't know that we're in a state that // we can recover from. We doom the connection in this case, to // prevent odd cases when we go to the wire. if (0 != _asyncCommandCount) { DoomThisConnection(); } // If we're deactivating with a delegated transaction, we // should not be cleaning up the parser just yet, that will // cause our transaction to be rolled back and the connection // to be reset. We'll get called again once the delegated // transaction is completed and we can do it all then. if (!IsNonPoolableTransactionRoot) { Debug.Assert(null != _parser || IsConnectionDoomed, "Deactivating a disposed connection?"); if (_parser != null) { _parser.Deactivate(IsConnectionDoomed); if (!IsConnectionDoomed) { ResetConnection(); } } } } [SuppressMessage("Microsoft.Globalization", "CA1303:DoNotPassLiteralsAsLocalizedParameters")] // copied from Triaged.cs private void ResetConnection() { // For implicit pooled connections, if connection reset behavior is specified, // reset the database and language properties back to default. It is important // to do this on activate so that the hashtable is correct before SqlConnection // obtains a clone. Debug.Assert(!HasLocalTransactionFromAPI, "Upon ResetConnection SqlInternalConnectionTds has a currently ongoing local transaction."); Debug.Assert(!_parser._physicalStateObj._pendingData, "Upon ResetConnection SqlInternalConnectionTds has pending data."); if (_fResetConnection) { // Ensure we are either going against shiloh, or we are not enlisted in a // distributed transaction - otherwise don't reset! if (IsShiloh) { // Prepare the parser for the connection reset - the next time a trip // to the server is made. _parser.PrepareResetConnection(IsTransactionRoot && !IsNonPoolableTransactionRoot); } else if (!IsEnlistedInTransaction) { // If not Shiloh, we are going against Sphinx. On Sphinx, we // may only reset if not enlisted in a distributed transaction. try { // execute sp System.Threading.Tasks.Task executeTask = _parser.TdsExecuteSQLBatch("sp_reset_connection", 30, null, _parser._physicalStateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); _parser.Run(RunBehavior.UntilDone, null, null, null, _parser._physicalStateObj); } catch (Exception e) { // UNDONE - should not be catching all exceptions!!! if (!ADP.IsCatchableExceptionType(e)) { throw; } DoomThisConnection(); ADP.TraceExceptionWithoutRethrow(e); } } // Reset hashtable values, since calling reset will not send us env_changes. CurrentDatabase = _originalDatabase; _currentLanguage = _originalLanguage; } } internal void DecrementAsyncCount() { Debug.Assert(_asyncCommandCount > 0); Interlocked.Decrement(ref _asyncCommandCount); } internal void IncrementAsyncCount() { Interlocked.Increment(ref _asyncCommandCount); } //////////////////////////////////////////////////////////////////////////////////////// // LOCAL TRANSACTION METHODS //////////////////////////////////////////////////////////////////////////////////////// override internal void DisconnectTransaction(SqlInternalTransaction internalTransaction) { TdsParser parser = Parser; if (null != parser) { parser.DisconnectTransaction(internalTransaction); } } internal void ExecuteTransaction(TransactionRequest transactionRequest, string name, IsolationLevel iso) { ExecuteTransaction(transactionRequest, name, iso, null, false); } override internal void ExecuteTransaction(TransactionRequest transactionRequest, string name, IsolationLevel iso, SqlInternalTransaction internalTransaction, bool isDelegateControlRequest) { if (IsConnectionDoomed) { // doomed means we can't do anything else... if (transactionRequest == TransactionRequest.Rollback || transactionRequest == TransactionRequest.IfRollback) { return; } throw SQL.ConnectionDoomed(); } if (transactionRequest == TransactionRequest.Commit || transactionRequest == TransactionRequest.Rollback || transactionRequest == TransactionRequest.IfRollback) { if (!Parser.MARSOn && Parser._physicalStateObj.BcpLock) { throw SQL.ConnectionLockedForBcpEvent(); } } string transactionName = (null == name) ? String.Empty : name; if (!_parser.IsYukonOrNewer) { ExecuteTransactionPreYukon(transactionRequest, transactionName, iso, internalTransaction); } else { ExecuteTransactionYukon(transactionRequest, transactionName, iso, internalTransaction, isDelegateControlRequest); } } // This function will not handle idle connection resiliency, as older servers will not support it internal void ExecuteTransactionPreYukon( TransactionRequest transactionRequest, string transactionName, IsolationLevel iso, SqlInternalTransaction internalTransaction) { StringBuilder sqlBatch = new StringBuilder(); switch (iso) { case IsolationLevel.Unspecified: break; case IsolationLevel.ReadCommitted: sqlBatch.Append(TdsEnums.TRANS_READ_COMMITTED); sqlBatch.Append(";"); break; case IsolationLevel.ReadUncommitted: sqlBatch.Append(TdsEnums.TRANS_READ_UNCOMMITTED); sqlBatch.Append(";"); break; case IsolationLevel.RepeatableRead: sqlBatch.Append(TdsEnums.TRANS_REPEATABLE_READ); sqlBatch.Append(";"); break; case IsolationLevel.Serializable: sqlBatch.Append(TdsEnums.TRANS_SERIALIZABLE); sqlBatch.Append(";"); break; case IsolationLevel.Snapshot: throw SQL.SnapshotNotSupported(IsolationLevel.Snapshot); case IsolationLevel.Chaos: throw SQL.NotSupportedIsolationLevel(iso); default: throw ADP.InvalidIsolationLevel(iso); } if (!ADP.IsEmpty(transactionName)) { transactionName = " " + SqlConnection.FixupDatabaseTransactionName(transactionName); } switch (transactionRequest) { case TransactionRequest.Begin: sqlBatch.Append(TdsEnums.TRANS_BEGIN); sqlBatch.Append(transactionName); break; case TransactionRequest.Promote: Debug.Assert(false, "Promote called with transaction name or on pre-Yukon!"); break; case TransactionRequest.Commit: sqlBatch.Append(TdsEnums.TRANS_COMMIT); sqlBatch.Append(transactionName); break; case TransactionRequest.Rollback: sqlBatch.Append(TdsEnums.TRANS_ROLLBACK); sqlBatch.Append(transactionName); break; case TransactionRequest.IfRollback: sqlBatch.Append(TdsEnums.TRANS_IF_ROLLBACK); sqlBatch.Append(transactionName); break; case TransactionRequest.Save: sqlBatch.Append(TdsEnums.TRANS_SAVE); sqlBatch.Append(transactionName); break; default: Debug.Fail("Unknown transaction type"); break; } System.Threading.Tasks.Task executeTask = _parser.TdsExecuteSQLBatch(sqlBatch.ToString(), ConnectionOptions.ConnectTimeout, null, _parser._physicalStateObj, sync: true); Debug.Assert(executeTask == null, "Shouldn't get a task when doing sync writes"); _parser.Run(RunBehavior.UntilDone, null, null, null, _parser._physicalStateObj); // Prior to Yukon, we didn't have any transaction tokens to manage, // or any feedback to know when one was created, so we just presume // that successful execution of the request caused the transaction // to be created, and we set that on the parser. if (TransactionRequest.Begin == transactionRequest) { Debug.Assert(null != internalTransaction, "Begin Transaction request without internal transaction"); _parser.CurrentTransaction = internalTransaction; } } internal void ExecuteTransactionYukon( TransactionRequest transactionRequest, string transactionName, IsolationLevel iso, SqlInternalTransaction internalTransaction, bool isDelegateControlRequest) { TdsEnums.TransactionManagerRequestType requestType = TdsEnums.TransactionManagerRequestType.Begin; TdsEnums.TransactionManagerIsolationLevel isoLevel = TdsEnums.TransactionManagerIsolationLevel.ReadCommitted; switch (iso) { case IsolationLevel.Unspecified: isoLevel = TdsEnums.TransactionManagerIsolationLevel.Unspecified; break; case IsolationLevel.ReadCommitted: isoLevel = TdsEnums.TransactionManagerIsolationLevel.ReadCommitted; break; case IsolationLevel.ReadUncommitted: isoLevel = TdsEnums.TransactionManagerIsolationLevel.ReadUncommitted; break; case IsolationLevel.RepeatableRead: isoLevel = TdsEnums.TransactionManagerIsolationLevel.RepeatableRead; break; case IsolationLevel.Serializable: isoLevel = TdsEnums.TransactionManagerIsolationLevel.Serializable; break; case IsolationLevel.Snapshot: isoLevel = TdsEnums.TransactionManagerIsolationLevel.Snapshot; break; case IsolationLevel.Chaos: throw SQL.NotSupportedIsolationLevel(iso); default: throw ADP.InvalidIsolationLevel(iso); } TdsParserStateObject stateObj = _parser._physicalStateObj; TdsParser parser = _parser; bool mustPutSession = false; bool releaseConnectionLock = false; Debug.Assert(!ThreadHasParserLockForClose || _parserLock.ThreadMayHaveLock(), "Thread claims to have parser lock, but lock is not taken"); if (!ThreadHasParserLockForClose) { _parserLock.Wait(canReleaseFromAnyThread: false); ThreadHasParserLockForClose = true; // In case of error, let the connection know that we already own the parser lock releaseConnectionLock = true; } try { switch (transactionRequest) { case TransactionRequest.Begin: requestType = TdsEnums.TransactionManagerRequestType.Begin; break; case TransactionRequest.Promote: requestType = TdsEnums.TransactionManagerRequestType.Promote; break; case TransactionRequest.Commit: requestType = TdsEnums.TransactionManagerRequestType.Commit; break; case TransactionRequest.IfRollback: // Map IfRollback to Rollback since with Yukon and beyond we should never need // the if since the server will inform us when transactions have completed // as a result of an error on the server. case TransactionRequest.Rollback: requestType = TdsEnums.TransactionManagerRequestType.Rollback; break; case TransactionRequest.Save: requestType = TdsEnums.TransactionManagerRequestType.Save; break; default: Debug.Fail("Unknown transaction type"); break; } // only restore if connection lock has been taken within the function if (internalTransaction != null && internalTransaction.RestoreBrokenConnection && releaseConnectionLock) { Task reconnectTask = internalTransaction.Parent.Connection.ValidateAndReconnect(() => { ThreadHasParserLockForClose = false; _parserLock.Release(); releaseConnectionLock = false; }, ADP.InfiniteConnectionTimeout); if (reconnectTask != null) { AsyncHelper.WaitForCompletion(reconnectTask, ADP.InfiniteConnectionTimeout); // there is no specific timeout for BeginTransaction, uses ConnectTimeout internalTransaction.ConnectionHasBeenRestored = true; return; } } // SQLBUDT #20010853 - Promote, Commit and Rollback requests for // delegated transactions often happen while there is an open result // set, so we need to handle them by using a different MARS session, // otherwise we'll write on the physical state objects while someone // else is using it. When we don't have MARS enabled, we need to // lock the physical state object to syncronize it's use at least // until we increment the open results count. Once it's been // incremented the delegated transaction requests will fail, so they // won't stomp on anything. // // We need to keep this lock through the duration of the TM reqeuest // so that we won't hijack a different request's data stream and a // different request won't hijack ours, so we have a lock here on // an object that the ExecTMReq will also lock, but since we're on // the same thread, the lock is a no-op. if (null != internalTransaction && internalTransaction.IsDelegated) { if (_parser.MARSOn) { stateObj = _parser.GetSession(this); mustPutSession = true; } else if (internalTransaction.OpenResultsCount != 0) { throw SQL.CannotCompleteDelegatedTransactionWithOpenResults(this, _parser.MARSOn); } } // SQLBU #406778 - _parser may be nulled out during TdsExecuteTrannsactionManagerRequest. // Only use local variable after this call. _parser.TdsExecuteTransactionManagerRequest(null, requestType, transactionName, isoLevel, ConnectionOptions.ConnectTimeout, internalTransaction, stateObj, isDelegateControlRequest); } finally { if (mustPutSession) { parser.PutSession(stateObj); } if (releaseConnectionLock) { ThreadHasParserLockForClose = false; _parserLock.Release(); } } } //////////////////////////////////////////////////////////////////////////////////////// // DISTRIBUTED TRANSACTION METHODS //////////////////////////////////////////////////////////////////////////////////////// override internal void DelegatedTransactionEnded() { // TODO: I don't like the way that this works, but I don't want to rototill the entire pooler to avoid this call. base.DelegatedTransactionEnded(); } override protected byte[] GetDTCAddress() { byte[] dtcAddress = _parser.GetDTCAddress(ConnectionOptions.ConnectTimeout, _parser.GetSession(this)); Debug.Assert(null != dtcAddress, "null dtcAddress?"); return dtcAddress; } override protected void PropagateTransactionCookie(byte[] cookie) { _parser.PropagateDistributedTransaction(cookie, ConnectionOptions.ConnectTimeout, _parser._physicalStateObj); } //////////////////////////////////////////////////////////////////////////////////////// // LOGIN-RELATED METHODS //////////////////////////////////////////////////////////////////////////////////////// private void CompleteLogin(bool enlistOK) { _parser.Run(RunBehavior.UntilDone, null, null, null, _parser._physicalStateObj); if (_routingInfo == null) { // ROR should not affect state of connection recovery if (_federatedAuthenticationRequested && !_federatedAuthenticationAcknowledged) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.CompleteLogin|ERR> {0}, Server did not acknowledge the federated authentication request", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthNotAcknowledged); } if (_federatedAuthenticationInfoRequested && !_federatedAuthenticationInfoReceived) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.CompleteLogin|ERR> {0}, Server never sent the requested federated authentication info", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthInfoNotReceived); } if (!_sessionRecoveryAcknowledged) { _currentSessionData = null; if (_recoverySessionData != null) { throw SQL.CR_NoCRAckAtReconnection(this); } } if (_currentSessionData != null && _recoverySessionData == null) { _currentSessionData._initialDatabase = CurrentDatabase; _currentSessionData._initialCollation = _currentSessionData._collation; _currentSessionData._initialLanguage = _currentLanguage; } bool isEncrypted = (_parser.EncryptionOptions & EncryptionOptions.OPTIONS_MASK) == EncryptionOptions.ON; if (_recoverySessionData != null) { if (_recoverySessionData._encrypted != isEncrypted) { throw SQL.CR_EncryptionChanged(this); } } if (_currentSessionData != null) { _currentSessionData._encrypted = isEncrypted; } _recoverySessionData = null; } Debug.Assert(SniContext.Snix_Login == Parser._physicalStateObj.SniContext, $"SniContext should be Snix_Login; actual Value: {Parser._physicalStateObj.SniContext}"); _parser._physicalStateObj.SniContext = SniContext.Snix_EnableMars; _parser.EnableMars(); _fConnectionOpen = true; // mark connection as open SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.CompleteLogin|ADV> Post-Login Phase: Server connection obtained."); // for non-pooled connections, enlist in a distributed transaction // if present - and user specified to enlist if (enlistOK && ConnectionOptions.Enlist) { _parser._physicalStateObj.SniContext = SniContext.Snix_AutoEnlist; SysTx.Transaction tx = ADP.GetCurrentTransaction(); Enlist(tx); } _parser._physicalStateObj.SniContext = SniContext.Snix_Login; } private void Login(ServerInfo server, TimeoutTimer timeout, string newPassword, SecureString newSecurePassword) { // create a new login record SqlLogin login = new SqlLogin(); // gather all the settings the user set in the connection string or // properties and do the login CurrentDatabase = server.ResolvedDatabaseName; _currentPacketSize = ConnectionOptions.PacketSize; _currentLanguage = ConnectionOptions.CurrentLanguage; int timeoutInSeconds = 0; // If a timeout tick value is specified, compute the timeout based // upon the amount of time left in seconds. if (!timeout.IsInfinite) { long t = timeout.MillisecondsRemaining / 1000; if (t == 0 && LocalAppContextSwitches.UseMinimumLoginTimeout) { // Take 1 as the minimum value, since 0 is treated as an infinite timeout t = 1; } if ((long)Int32.MaxValue > t) { timeoutInSeconds = (int)t; } } login.authentication = ConnectionOptions.Authentication; login.timeout = timeoutInSeconds; login.userInstance = ConnectionOptions.UserInstance; login.hostName = ConnectionOptions.ObtainWorkstationId(); login.userName = ConnectionOptions.UserID; login.password = ConnectionOptions.Password; login.applicationName = ConnectionOptions.ApplicationName; login.language = _currentLanguage; if (!login.userInstance) { // Do not send attachdbfilename or database to SSE primary instance login.database = CurrentDatabase; ; login.attachDBFilename = ConnectionOptions.AttachDBFilename; } // VSTS#795621 - Ensure ServerName is Sent During TdsLogin To Enable Sql Azure Connectivity. // Using server.UserServerName (versus ConnectionOptions.DataSource) since TdsLogin requires // serverName to always be non-null. login.serverName = server.UserServerName; login.useReplication = ConnectionOptions.Replication; login.useSSPI = ConnectionOptions.IntegratedSecurity // Treat AD Integrated like Windows integrated when against a non-FedAuth endpoint || (ConnectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated && !_fedAuthRequired); login.packetSize = _currentPacketSize; login.newPassword = newPassword; login.readOnlyIntent = ConnectionOptions.ApplicationIntent == ApplicationIntent.ReadOnly; login.credential = _credential; if (newSecurePassword != null) { login.newSecurePassword = newSecurePassword; } TdsEnums.FeatureExtension requestedFeatures = TdsEnums.FeatureExtension.None; if (ConnectionOptions.ConnectRetryCount > 0) { requestedFeatures |= TdsEnums.FeatureExtension.SessionRecovery; _sessionRecoveryRequested = true; } // If the workflow being used is Active Directory Password/Integrated/Interactive/Service Principal/Device Code Flow and server's prelogin response // for FEDAUTHREQUIRED option indicates Federated Authentication is required, we have to insert FedAuth Feature Extension // in Login7, indicating the intent to use Active Directory Authentication for SQL Server. if (ConnectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryPassword || ConnectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryInteractive || ConnectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryServicePrincipal || ConnectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow // Since AD Integrated may be acting like Windows integrated, additionally check _fedAuthRequired || (ConnectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated && _fedAuthRequired)) { requestedFeatures |= TdsEnums.FeatureExtension.FedAuth; _federatedAuthenticationInfoRequested = true; _fedAuthFeatureExtensionData = new FederatedAuthenticationFeatureExtensionData { libraryType = TdsEnums.FedAuthLibrary.MSAL, authentication = ConnectionOptions.Authentication, fedAuthRequiredPreLoginResponse = _fedAuthRequired }; } if (_accessTokenInBytes != null) { requestedFeatures |= TdsEnums.FeatureExtension.FedAuth; _fedAuthFeatureExtensionData = new FederatedAuthenticationFeatureExtensionData { libraryType = TdsEnums.FedAuthLibrary.SecurityToken, fedAuthRequiredPreLoginResponse = _fedAuthRequired, accessToken = _accessTokenInBytes }; // No need any further info from the server for token based authentication. So set _federatedAuthenticationRequested to true _federatedAuthenticationRequested = true; } // The TCE, DATACLASSIFICATION and GLOBALTRANSACTIONS, UTF8 support feature are implicitly requested requestedFeatures |= TdsEnums.FeatureExtension.Tce | TdsEnums.FeatureExtension.DataClassification | TdsEnums.FeatureExtension.GlobalTransactions; requestedFeatures |= TdsEnums.FeatureExtension.UTF8Support; // The AzureSQLSupport feature is implicitly set for ReadOnly login if (ConnectionOptions.ApplicationIntent == ApplicationIntent.ReadOnly) { requestedFeatures |= TdsEnums.FeatureExtension.AzureSQLSupport; } // The SQLDNSCaching feature is implicitly set requestedFeatures |= TdsEnums.FeatureExtension.SQLDNSCaching; _parser.TdsLogin(login, requestedFeatures, _recoverySessionData, _fedAuthFeatureExtensionData, _originalNetworkAddressInfo); } private void LoginFailure() { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.LoginFailure|RES|CPOOL> {0}", ObjectID); // If the parser was allocated and we failed, then we must have failed on // either the Connect or Login, either way we should call Disconnect. // Disconnect can be called if the connection is already closed - becomes // no-op, so no issues there. if (_parser != null) { _parser.Disconnect(); } // TODO: Need a performance counter for Failed Connections } private void OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, string newPassword, SecureString newSecurePassword, bool redirectedUserInstance) { bool useFailoverPartner; // should we use primary or secondary first ServerInfo dataSource = new ServerInfo(connectionOptions); string failoverPartner; if (null != PoolGroupProviderInfo) { useFailoverPartner = PoolGroupProviderInfo.UseFailoverPartner; failoverPartner = PoolGroupProviderInfo.FailoverPartner; } else { // Only ChangePassword or SSE User Instance comes through this code path. useFailoverPartner = false; failoverPartner = ConnectionOptions.FailoverPartner; } timeoutErrorInternal.SetInternalSourceType(useFailoverPartner ? SqlConnectionInternalSourceType.Failover : SqlConnectionInternalSourceType.Principle); bool hasFailoverPartner = !ADP.IsEmpty(failoverPartner); // Open the connection and Login try { timeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.PreLoginBegin); if (hasFailoverPartner) { timeoutErrorInternal.SetFailoverScenario(true); // this is a failover scenario LoginWithFailover( useFailoverPartner, dataSource, failoverPartner, newPassword, newSecurePassword, redirectedUserInstance, connectionOptions, credential, timeout); } else { timeoutErrorInternal.SetFailoverScenario(false); // not a failover scenario LoginNoFailover(dataSource, newPassword, newSecurePassword, redirectedUserInstance, connectionOptions, credential, timeout); } if (!IsAzureSQLConnection) { // If not a connection to Azure SQL, Readonly with FailoverPartner is not supported if (ConnectionOptions.ApplicationIntent == ApplicationIntent.ReadOnly) { if (!String.IsNullOrEmpty(ConnectionOptions.FailoverPartner)) { throw SQL.ROR_FailoverNotSupportedConnString(); } if (null != ServerProvidedFailOverPartner) { throw SQL.ROR_FailoverNotSupportedServer(this); } } } timeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.PostLogin); } catch (Exception e) { // UNDONE - should not be catching all exceptions!!! if (ADP.IsCatchableExceptionType(e)) { LoginFailure(); } throw; } timeoutErrorInternal.SetAllCompleteMarker(); #if DEBUG _parser._physicalStateObj.InvalidateDebugOnlyCopyOfSniContext(); #endif } // Is the given Sql error one that should prevent retrying // to connect. private bool IsDoNotRetryConnectError(SqlException exc) { return (TdsEnums.LOGON_FAILED == exc.Number) // actual logon failed, i.e. bad password || (TdsEnums.PASSWORD_EXPIRED == exc.Number) // actual logon failed, i.e. password isExpired || (TdsEnums.IMPERSONATION_FAILED == exc.Number) // Insuficient privelege for named pipe, among others || exc._doNotReconnect; // Exception explicitly supressed reconnection attempts } // Attempt to login to a host that does not have a failover partner // // Will repeatedly attempt to connect, but back off between each attempt so as not to clog the network. // Back off period increases for first few failures: 100ms, 200ms, 400ms, 800ms, then 1000ms for subsequent attempts // // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // DEVNOTE: The logic in this method is paralleled by the logic in LoginWithFailover. // Changes to either one should be examined to see if they need to be reflected in the other // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! private void LoginNoFailover(ServerInfo serverInfo, string newPassword, SecureString newSecurePassword, bool redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) { Debug.Assert(object.ReferenceEquals(connectionOptions, this.ConnectionOptions), "ConnectionOptions argument and property must be the same"); // consider removing the argument int routingAttempts = 0; ServerInfo originalServerInfo = serverInfo; // serverInfo may end up pointing to new object due to routing, original object is used to set CurrentDatasource SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.LoginNoFailover|ADV> {0}, host={1}", ObjectID, serverInfo.UserServerName); int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. ResolveExtendedServerName(serverInfo, !redirectedUserInstance, connectionOptions); Boolean disableTnir = ShouldDisableTnir(connectionOptions); long timeoutUnitInterval = 0; Boolean isParallel = connectionOptions.MultiSubnetFailover || (connectionOptions.TransparentNetworkIPResolution && !disableTnir); if (isParallel) { float failoverTimeoutStep = connectionOptions.MultiSubnetFailover ? ADP.FailoverTimeoutStep : ADP.FailoverTimeoutStepForTnir; // Determine unit interval if (timeout.IsInfinite) { timeoutUnitInterval = checked((long)(failoverTimeoutStep * (1000L * ADP.DefaultConnectionTimeout))); } else { timeoutUnitInterval = checked((long)(failoverTimeoutStep * timeout.MillisecondsRemaining)); } } // Only three ways out of this loop: // 1) Successfully connected // 2) Parser threw exception while main timer was expired // 3) Parser threw logon failure-related exception // 4) Parser threw exception in post-initial connect code, // such as pre-login handshake or during actual logon. (parser state != Closed) // // Of these methods, only #1 exits normally. This preserves the call stack on the exception // back into the parser for the error cases. int attemptNumber = 0; TimeoutTimer intervalTimer = null; TimeoutTimer attemptOneLoginTimeout = timeout; while (true) { Boolean isFirstTransparentAttempt = connectionOptions.TransparentNetworkIPResolution && !disableTnir && attemptNumber == 1; if (isParallel) { int multiplier = ++attemptNumber; if (connectionOptions.TransparentNetworkIPResolution) { // While connecting using TNIR the timeout multiplier should be increased to allow steps of 1,2,4 instead of 1,2,3. // This will allow half the time out for the last connection attempt in case of Tnir. multiplier = 1 << (attemptNumber - 1); } // Set timeout for this attempt, but don't exceed original timer long nextTimeoutInterval = checked(timeoutUnitInterval * multiplier); long milliseconds = timeout.MillisecondsRemaining; // If it is the first attempt at TNIR connection, then allow at least 500 ms for timeout. With the current failover step of 0.125 // and Connection Time of < 4000 ms, the first attempt can be lower than 500 ms. if (isFirstTransparentAttempt) { nextTimeoutInterval = Math.Max(ADP.MinimumTimeoutForTnirMs, nextTimeoutInterval); } if (nextTimeoutInterval > milliseconds) { nextTimeoutInterval = milliseconds; } intervalTimer = TimeoutTimer.StartMillisecondsTimeout(nextTimeoutInterval); } // Re-allocate parser each time to make sure state is known // RFC 50002652 - if parser was created by previous attempt, dispose it to properly close the socket, if created if (_parser != null) _parser.Disconnect(); _parser = new TdsParser(ConnectionOptions.MARS, ConnectionOptions.Asynchronous); Debug.Assert(SniContext.Undefined == Parser._physicalStateObj.SniContext, String.Format((IFormatProvider)null, "SniContext should be Undefined; actual Value: {0}", Parser._physicalStateObj.SniContext)); try { // UNDONE: ITEM12001110 (DB Mirroring Reconnect) Old behavior of not truly honoring timeout presevered // for non-failover, non-MSF scenarios to avoid breaking changes as part of a QFE. Consider fixing timeout // handling in next full release and removing ignoreSniOpenTimeout parameter. if (isParallel) { attemptOneLoginTimeout = intervalTimer; } AttemptOneLogin(serverInfo, newPassword, newSecurePassword, !isParallel, // ignore timeout for SniOpen call unless MSF , and TNIR attemptOneLoginTimeout, isFirstTransparentAttempt: isFirstTransparentAttempt, disableTnir: disableTnir); if (connectionOptions.MultiSubnetFailover && null != ServerProvidedFailOverPartner) { // connection succeeded: trigger exception if server sends failover partner and MultiSubnetFailover is used. throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: true, internalConnection: this); } if (_routingInfo != null) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.LoginNoFailover> Routed to {0}", serverInfo.ExtendedServerName); if (routingAttempts > _maxNumberOfRedirectRoute) { throw SQL.ROR_RecursiveRoutingNotSupported(this); } if (timeout.IsExpired) { throw SQL.ROR_TimeoutAfterRoutingInfo(this); } serverInfo = new ServerInfo(ConnectionOptions, _routingInfo, serverInfo.ResolvedServerName); timeoutErrorInternal.SetInternalSourceType(SqlConnectionInternalSourceType.RoutingDestination); _originalClientConnectionId = _clientConnectionId; _routingDestination = serverInfo.UserServerName; // restore properties that could be changed by the environment tokens _currentPacketSize = ConnectionOptions.PacketSize; _currentLanguage = _originalLanguage = ConnectionOptions.CurrentLanguage; CurrentDatabase = _originalDatabase = ConnectionOptions.InitialCatalog; _currentFailoverPartner = null; _instanceName = String.Empty; routingAttempts++; continue; // repeat the loop, but skip code reserved for failed connections (after the catch) } else { break; // leave the while loop -- we've successfully connected } } catch (SqlException sqlex) { if (AttemptRetryADAuthWithTimeoutError(sqlex, connectionOptions, timeout)) { continue; } if (null == _parser || TdsParserState.Closed != _parser.State || IsDoNotRetryConnectError(sqlex) || timeout.IsExpired) { // no more time to try again throw; // Caller will call LoginFailure() } // Check sleep interval to make sure we won't exceed the timeout // Do this in the catch block so we can re-throw the current exception if (timeout.MillisecondsRemaining <= sleepInterval) { throw; } // TODO: Stash parser away somewhere so we can examine it's state during debugging } // We only get here when we failed to connect, but are going to re-try // Switch to failover logic if the server provided a partner if (null != ServerProvidedFailOverPartner) { if (connectionOptions.MultiSubnetFailover) { // connection failed: do not allow failover to server-provided failover partner if MultiSubnetFailover is set throw SQL.MultiSubnetFailoverWithFailoverPartner(serverProvidedFailoverPartner: true, internalConnection: this); } Debug.Assert(ConnectionOptions.ApplicationIntent != ApplicationIntent.ReadOnly, "FAILOVER+AppIntent=RO: Should already fail (at LOGSHIPNODE in OnEnvChange)"); timeoutErrorInternal.ResetAndRestartPhase(); timeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.PreLoginBegin); timeoutErrorInternal.SetInternalSourceType(SqlConnectionInternalSourceType.Failover); timeoutErrorInternal.SetFailoverScenario(true); // this is a failover scenario LoginWithFailover( true, // start by using failover partner, since we already failed to connect to the primary serverInfo, ServerProvidedFailOverPartner, newPassword, newSecurePassword, redirectedUserInstance, connectionOptions, credential, timeout); return; // LoginWithFailover successfully connected and handled entire connection setup } // Sleep for a bit to prevent clogging the network with requests, // then update sleep interval for next iteration (max 1 second interval) SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.LoginNoFailover|ADV> {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; } _activeDirectoryAuthTimeoutRetryHelper.State = ActiveDirectoryAuthenticationTimeoutRetryState.HasLoggedIn; if (null != PoolGroupProviderInfo) { // We must wait for CompleteLogin to finish for to have the // env change from the server to know its designated failover // partner; save this information in _currentFailoverPartner. PoolGroupProviderInfo.FailoverCheck(this, false, connectionOptions, ServerProvidedFailOverPartner); } CurrentDataSource = originalServerInfo.UserServerName; } private bool ShouldDisableTnir(SqlConnectionString connectionOptions) { Boolean isAzureEndPoint = ADP.IsAzureSqlServerEndpoint(connectionOptions.DataSource); Boolean isFedAuthEnabled = this._accessTokenInBytes != null || connectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryPassword || connectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated || connectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryInteractive || connectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryServicePrincipal || connectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow; // Check if the user had explicitly specified the TNIR option in the connection string or the connection string builder. // If the user has specified the option in the connection string explicitly, then we shouldn't disable TNIR. bool isTnirExplicitlySpecifiedInConnectionOptions = connectionOptions.Parsetable[SqlConnectionString.KEY.TransparentNetworkIPResolution] != null; return isTnirExplicitlySpecifiedInConnectionOptions ? false : (isAzureEndPoint || isFedAuthEnabled); } // With possible MFA support in all AD auth providers, the duration for acquiring a token can be unpredictable. // If a timeout error (client or server) happened, we silently retry if a cached token exists from a previous auth attempt (see GetFedAuthToken) private bool AttemptRetryADAuthWithTimeoutError(SqlException sqlex, SqlConnectionString connectionOptions, TimeoutTimer timeout) { if (!_activeDirectoryAuthTimeoutRetryHelper.CanRetryWithSqlException(sqlex)) { return false; } // Reset client-side timeout. timeout.Reset(); // When server timeout, the auth context key was already created. Clean it up here. _dbConnectionPoolAuthenticationContextKey = null; // When server timeouts, connection is doomed. Reset here to allow reconnect. UnDoomThisConnection(); // Change retry state so it only retries once for timeout error. _activeDirectoryAuthTimeoutRetryHelper.State = ActiveDirectoryAuthenticationTimeoutRetryState.Retrying; return true; } // Attempt to login to a host that has a failover partner // // Connection & timeout sequence is // First target, timeout = interval * 1 // second target, timeout = interval * 1 // sleep for 100ms // First target, timeout = interval * 2 // Second target, timeout = interval * 2 // sleep for 200ms // First Target, timeout = interval * 3 // etc. // // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // DEVNOTE: The logic in this method is paralleled by the logic in LoginNoFailover. // Changes to either one should be examined to see if they need to be reflected in the other // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! private void LoginWithFailover( bool useFailoverHost, ServerInfo primaryServerInfo, string failoverHost, string newPassword, SecureString newSecurePassword, bool redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout ) { Debug.Assert(!connectionOptions.MultiSubnetFailover, "MultiSubnetFailover should not be set if failover partner is used"); SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.LoginWithFailover|ADV> {0}, useFailover={1}[bool], primary={2}, failover={3}", ObjectID, useFailoverHost, primaryServerInfo.UserServerName, failoverHost ?? "null"); int sleepInterval = 100; //milliseconds to sleep (back off) between attempts. long timeoutUnitInterval; string protocol = ConnectionOptions.NetworkLibrary; ServerInfo failoverServerInfo = new ServerInfo(connectionOptions, failoverHost); ResolveExtendedServerName(primaryServerInfo, !redirectedUserInstance, connectionOptions); if (null == ServerProvidedFailOverPartner) {// No point in resolving the failover partner when we're going to override it below // Don't resolve aliases if failover == primary // UNDONE: WHY? Previous code in TdsParser.Connect did this, but the reason is not clear ResolveExtendedServerName(failoverServerInfo, !redirectedUserInstance && failoverHost != primaryServerInfo.UserServerName, connectionOptions); } // Determine unit interval if (timeout.IsInfinite) { timeoutUnitInterval = checked((long)(ADP.FailoverTimeoutStep * ADP.TimerFromSeconds(ADP.DefaultConnectionTimeout))); } else { timeoutUnitInterval = checked((long)(ADP.FailoverTimeoutStep * timeout.MillisecondsRemaining)); } // Initialize loop variables bool failoverDemandDone = false; // have we demanded for partner information yet (as necessary)? int attemptNumber = 0; // Only three ways out of this loop: // 1) Successfully connected // 2) Parser threw exception while main timer was expired // 3) Parser threw logon failure-related exception (LOGON_FAILED, PASSWORD_EXPIRED, etc) // // Of these methods, only #1 exits normally. This preserves the call stack on the exception // back into the parser for the error cases. while (true) { // Set timeout for this attempt, but don't exceed original timer long nextTimeoutInterval = checked(timeoutUnitInterval * ((attemptNumber / 2) + 1)); long milliseconds = timeout.MillisecondsRemaining; if (nextTimeoutInterval > milliseconds) { nextTimeoutInterval = milliseconds; } TimeoutTimer intervalTimer = TimeoutTimer.StartMillisecondsTimeout(nextTimeoutInterval); // Re-allocate parser each time to make sure state is known // RFC 50002652 - if parser was created by previous attempt, dispose it to properly close the socket, if created if (_parser != null) _parser.Disconnect(); _parser = new TdsParser(ConnectionOptions.MARS, ConnectionOptions.Asynchronous); Debug.Assert(SniContext.Undefined == Parser._physicalStateObj.SniContext, String.Format((IFormatProvider)null, "SniContext should be Undefined; actual Value: {0}", Parser._physicalStateObj.SniContext)); ServerInfo currentServerInfo; if (useFailoverHost) { if (!failoverDemandDone) { FailoverPermissionDemand(); failoverDemandDone = true; } // Primary server may give us a different failover partner than the connection string indicates. Update it if (null != ServerProvidedFailOverPartner && failoverServerInfo.ResolvedServerName != ServerProvidedFailOverPartner) { SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.LoginWithFailover|ADV> {0}, new failover partner={1}", ObjectID, ServerProvidedFailOverPartner); failoverServerInfo.SetDerivedNames(protocol, ServerProvidedFailOverPartner); } currentServerInfo = failoverServerInfo; timeoutErrorInternal.SetInternalSourceType(SqlConnectionInternalSourceType.Failover); } else { currentServerInfo = primaryServerInfo; timeoutErrorInternal.SetInternalSourceType(SqlConnectionInternalSourceType.Principle); } try { // Attempt login. Use timerInterval for attempt timeout unless infinite timeout was requested. AttemptOneLogin( currentServerInfo, newPassword, newSecurePassword, false, // Use timeout in SniOpen intervalTimer, withFailover: true ); int routingAttempts = 0; while (_routingInfo != null) { if (routingAttempts > _maxNumberOfRedirectRoute) { throw SQL.ROR_RecursiveRoutingNotSupported(this); } routingAttempts++; SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.LoginWithFailover> Routed to {0}", _routingInfo.ServerName); if (_parser != null) _parser.Disconnect(); _parser = new TdsParser(ConnectionOptions.MARS, ConnectionOptions.Asynchronous); Debug.Assert(SniContext.Undefined == Parser._physicalStateObj.SniContext, $"SniContext should be Undefined; actual Value: {Parser._physicalStateObj.SniContext}"); currentServerInfo = new ServerInfo(ConnectionOptions, _routingInfo, currentServerInfo.ResolvedServerName); timeoutErrorInternal.SetInternalSourceType(SqlConnectionInternalSourceType.RoutingDestination); _originalClientConnectionId = _clientConnectionId; _routingDestination = currentServerInfo.UserServerName; // restore properties that could be changed by the environment tokens _currentPacketSize = ConnectionOptions.PacketSize; _currentLanguage = _originalLanguage = ConnectionOptions.CurrentLanguage; CurrentDatabase = _originalDatabase = ConnectionOptions.InitialCatalog; _currentFailoverPartner = null; _instanceName = String.Empty; AttemptOneLogin( currentServerInfo, newPassword, newSecurePassword, false, // Use timeout in SniOpen intervalTimer, withFailover: true ); } break; // leave the while loop -- we've successfully connected } catch (SqlException sqlex) { if (AttemptRetryADAuthWithTimeoutError(sqlex, connectionOptions, timeout)) { continue; } if (IsDoNotRetryConnectError(sqlex) || timeout.IsExpired) { // no more time to try again throw; // Caller will call LoginFailure() } if (!ADP.IsAzureSqlServerEndpoint(connectionOptions.DataSource) && IsConnectionDoomed) { throw; } if (1 == attemptNumber % 2) { // Check sleep interval to make sure we won't exceed the original timeout // Do this in the catch block so we can re-throw the current exception if (timeout.MillisecondsRemaining <= sleepInterval) { throw; } } // TODO: Stash parser away somewhere so we can examine it's state during debugging } // We only get here when we failed to connect, but are going to re-try // After trying to connect to both servers fails, sleep for a bit to prevent clogging // the network with requests, then update sleep interval for next iteration (max 1 second interval) if (1 == attemptNumber % 2) { SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.LoginWithFailover|ADV> {0}, sleeping {1}[milisec]", ObjectID, sleepInterval); Thread.Sleep(sleepInterval); sleepInterval = (sleepInterval < 500) ? sleepInterval * 2 : 1000; } // Update attempt number and target host attemptNumber++; useFailoverHost = !useFailoverHost; } // If we get here, connection/login succeeded! Just a few more checks & record-keeping _activeDirectoryAuthTimeoutRetryHelper.State = ActiveDirectoryAuthenticationTimeoutRetryState.HasLoggedIn; // if connected to failover host, but said host doesn't have DbMirroring set up, throw an error if (useFailoverHost && null == ServerProvidedFailOverPartner) { throw SQL.InvalidPartnerConfiguration(failoverHost, CurrentDatabase); } if (null != PoolGroupProviderInfo) { // We must wait for CompleteLogin to finish for to have the // env change from the server to know its designated failover // partner; save this information in _currentFailoverPartner. PoolGroupProviderInfo.FailoverCheck(this, useFailoverHost, connectionOptions, ServerProvidedFailOverPartner); } CurrentDataSource = (useFailoverHost ? failoverHost : primaryServerInfo.UserServerName); } private void ResolveExtendedServerName(ServerInfo serverInfo, bool aliasLookup, SqlConnectionString options) { if (serverInfo.ExtendedServerName == null) { string host = serverInfo.UserServerName; string protocol = serverInfo.UserProtocol; if (aliasLookup) { // We skip this for UserInstances... // Perform registry lookup to see if host is an alias. It will appropriately set host and protocol, if an Alias. // Check if it was already resolved, during CR reconnection _currentSessionData values will be copied from // _reconnectSessonData of the previous connection if (_currentSessionData != null && !string.IsNullOrEmpty(host)) { Tuple<string, string> hostPortPair; if (_currentSessionData._resolvedAliases.TryGetValue(host, out hostPortPair)) { host = hostPortPair.Item1; protocol = hostPortPair.Item2; } else { TdsParserStaticMethods.AliasRegistryLookup(ref host, ref protocol); _currentSessionData._resolvedAliases.Add(serverInfo.UserServerName, new Tuple<string, string>(host, protocol)); } } else { TdsParserStaticMethods.AliasRegistryLookup(ref host, ref protocol); } //TODO: fix local host enforcement with datadirectory and failover if (options.EnforceLocalHost) { // verify LocalHost for |DataDirectory| usage SqlConnectionString.VerifyLocalHostAndFixup(ref host, true, true /*fix-up to "."*/); } } serverInfo.SetDerivedNames(protocol, host); } } // Common code path for making one attempt to establish a connection and log in to server. private void AttemptOneLogin(ServerInfo serverInfo, string newPassword, SecureString newSecurePassword, bool ignoreSniOpenTimeout, TimeoutTimer timeout, bool withFailover = false, bool isFirstTransparentAttempt = true, bool disableTnir = false) { SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.AttemptOneLogin|ADV> {0}, timout={1}[msec], server={2}", ObjectID, timeout.MillisecondsRemaining, serverInfo.ExtendedServerName); _routingInfo = null; // forget routing information _parser._physicalStateObj.SniContext = SniContext.Snix_Connect; _parser.Connect(serverInfo, this, ignoreSniOpenTimeout, timeout.LegacyTimerExpire, ConnectionOptions.Encrypt, ConnectionOptions.TrustServerCertificate, ConnectionOptions.IntegratedSecurity, withFailover, isFirstTransparentAttempt, ConnectionOptions.Authentication, ConnectionOptions.Certificate, _serverCallback, _clientCallback, _originalNetworkAddressInfo != null, disableTnir); timeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.ConsumePreLoginHandshake); timeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.LoginBegin); _parser._physicalStateObj.SniContext = SniContext.Snix_Login; this.Login(serverInfo, timeout, newPassword, newSecurePassword); timeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.ProcessConnectionAuth); timeoutErrorInternal.SetAndBeginPhase(SqlConnectionTimeoutErrorPhase.PostLogin); CompleteLogin(!ConnectionOptions.Pooling); timeoutErrorInternal.EndPhase(SqlConnectionTimeoutErrorPhase.PostLogin); } internal void FailoverPermissionDemand() { if (null != PoolGroupProviderInfo) { PoolGroupProviderInfo.FailoverPermissionDemand(); } } //////////////////////////////////////////////////////////////////////////////////////// // PREPARED COMMAND METHODS //////////////////////////////////////////////////////////////////////////////////////// protected override object ObtainAdditionalLocksForClose() { bool obtainParserLock = !ThreadHasParserLockForClose; Debug.Assert(obtainParserLock || _parserLock.ThreadMayHaveLock(), "Thread claims to have lock, but lock is not taken"); if (obtainParserLock) { _parserLock.Wait(canReleaseFromAnyThread: false); ThreadHasParserLockForClose = true; } return obtainParserLock; } protected override void ReleaseAdditionalLocksForClose(object lockToken) { Debug.Assert(lockToken is bool, "Lock token should be boolean"); if ((bool)lockToken) { ThreadHasParserLockForClose = false; _parserLock.Release(); } } // called by SqlConnection.RepairConnection which is a relatevly expensive way of repair inner connection // prior to execution of request, used from EnlistTransaction, EnlistDistributedTransaction and ChangeDatabase internal bool GetSessionAndReconnectIfNeeded(SqlConnection parent, int timeout = 0) { Debug.Assert(!ThreadHasParserLockForClose, "Cannot call this method if caller has parser lock"); if (ThreadHasParserLockForClose) { return false; // we cannot restore if we cannot release lock } _parserLock.Wait(canReleaseFromAnyThread: false); ThreadHasParserLockForClose = true; // In case of error, let the connection know that we already own the parser lock bool releaseConnectionLock = true; try { RuntimeHelpers.PrepareConstrainedRegions(); try { #if DEBUG TdsParser.ReliabilitySection tdsReliabilitySection = new TdsParser.ReliabilitySection(); RuntimeHelpers.PrepareConstrainedRegions(); try { tdsReliabilitySection.Start(); #endif //DEBUG Task reconnectTask = parent.ValidateAndReconnect(() => { ThreadHasParserLockForClose = false; _parserLock.Release(); releaseConnectionLock = false; }, timeout); if (reconnectTask != null) { AsyncHelper.WaitForCompletion(reconnectTask, timeout); return true; } return false; #if DEBUG } finally { tdsReliabilitySection.Stop(); } #endif //DEBUG } catch (System.OutOfMemoryException) { DoomThisConnection(); throw; } catch (System.StackOverflowException) { DoomThisConnection(); throw; } catch (System.Threading.ThreadAbortException) { DoomThisConnection(); throw; } } finally { if (releaseConnectionLock) { ThreadHasParserLockForClose = false; _parserLock.Release(); } } } //////////////////////////////////////////////////////////////////////////////////////// // PARSER CALLBACKS //////////////////////////////////////////////////////////////////////////////////////// internal void BreakConnection() { SqlConnection connection = Connection; SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.BreakConnection|RES|CPOOL> {0}, Breaking connection.", ObjectID); DoomThisConnection(); // Mark connection as unusable, so it will be destroyed if (null != connection) { connection.Close(); } } internal bool IgnoreEnvChange { // true if we are only draining environment change tokens, used by TdsParser get { return _routingInfo != null; // connection was routed, ignore rest of env change } } internal void OnEnvChange(SqlEnvChange rec) { Debug.Assert(!IgnoreEnvChange, "This function should not be called if IgnoreEnvChange is set!"); switch (rec.type) { case TdsEnums.ENV_DATABASE: // If connection is not open and recovery is not in progresss, store the server value as the original. if (!_fConnectionOpen && _recoverySessionData == null) { _originalDatabase = rec.newValue; } CurrentDatabase = rec.newValue; break; case TdsEnums.ENV_LANG: // If connection is not open and recovery is not in progresss, store the server value as the original. if (!_fConnectionOpen && _recoverySessionData == null) { _originalLanguage = rec.newValue; } _currentLanguage = rec.newValue; // TODO: finish this. break; case TdsEnums.ENV_PACKETSIZE: _currentPacketSize = Int32.Parse(rec.newValue, CultureInfo.InvariantCulture); break; case TdsEnums.ENV_COLLATION: if (_currentSessionData != null) { _currentSessionData._collation = rec.newCollation; } break; case TdsEnums.ENV_CHARSET: case TdsEnums.ENV_LOCALEID: case TdsEnums.ENV_COMPFLAGS: case TdsEnums.ENV_BEGINTRAN: case TdsEnums.ENV_COMMITTRAN: case TdsEnums.ENV_ROLLBACKTRAN: case TdsEnums.ENV_ENLISTDTC: case TdsEnums.ENV_DEFECTDTC: // only used on parser break; case TdsEnums.ENV_LOGSHIPNODE: _currentFailoverPartner = rec.newValue; break; case TdsEnums.ENV_PROMOTETRANSACTION: PromotedDTCToken = rec.newBinValue; break; case TdsEnums.ENV_TRANSACTIONENDED: break; case TdsEnums.ENV_TRANSACTIONMANAGERADDRESS: // For now we skip these Yukon only env change notifications break; case TdsEnums.ENV_SPRESETCONNECTIONACK: // connection is being reset if (_currentSessionData != null) { _currentSessionData.Reset(); } break; case TdsEnums.ENV_USERINSTANCE: _instanceName = rec.newValue; break; case TdsEnums.ENV_ROUTING: SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.OnEnvChange|ADV> {0}, Received routing info", ObjectID); if (string.IsNullOrEmpty(rec.newRoutingInfo.ServerName) || rec.newRoutingInfo.Protocol != 0 || rec.newRoutingInfo.Port == 0) { throw SQL.ROR_InvalidRoutingInfo(this); } _routingInfo = rec.newRoutingInfo; break; default: Debug.Fail("Missed token in EnvChange!"); break; } } internal void OnLoginAck(SqlLoginAck rec) { _loginAck = rec; // UNDONE: throw an error if this is not 7.0 or 7.1[5]. if (_recoverySessionData != null) { if (_recoverySessionData._tdsVersion != rec.tdsVersion) { throw SQL.CR_TDSVersionNotPreserved(this); } } if (_currentSessionData != null) { _currentSessionData._tdsVersion = rec.tdsVersion; } } /// <summary> /// Generates (if appropriate) and sends a Federated Authentication Access token to the server, using the Federated Authentication Info. /// </summary> /// <param name="fedAuthInfo">Federated Authentication Info.</param> internal void OnFedAuthInfo(SqlFedAuthInfo fedAuthInfo) { Debug.Assert((ConnectionOptions.HasUserIdKeyword && ConnectionOptions.HasPasswordKeyword) || _credential != null || ConnectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryInteractive || ConnectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow || (ConnectionOptions.Authentication == SqlAuthenticationMethod.ActiveDirectoryIntegrated && _fedAuthRequired), "Credentials aren't provided for calling MSAL"); Debug.Assert(fedAuthInfo != null, "info should not be null."); Debug.Assert(_dbConnectionPoolAuthenticationContextKey == null, "_dbConnectionPoolAuthenticationContextKey should be null."); SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFedAuthInfo> {0}, Generating federated authentication token", ObjectID); DbConnectionPoolAuthenticationContext dbConnectionPoolAuthenticationContext = null; // We want to refresh the token without taking a lock on the context, allowed when the access token is expiring within the next 10 mins. bool attemptRefreshTokenUnLocked = false; // We want to refresh the token, if taking the lock on the authentication context is successful. bool attemptRefreshTokenLocked = false; if (_dbConnectionPool != null) { Debug.Assert(_dbConnectionPool.AuthenticationContexts != null); // Construct the dbAuthenticationContextKey with information from FedAuthInfo and store for later use, when inserting in to the token cache. _dbConnectionPoolAuthenticationContextKey = new DbConnectionPoolAuthenticationContextKey(fedAuthInfo.stsurl, fedAuthInfo.spn); // Try to retrieve the authentication context from the pool, if one does exist for this key. if (_dbConnectionPool.AuthenticationContexts.TryGetValue(_dbConnectionPoolAuthenticationContextKey, out dbConnectionPoolAuthenticationContext)) { Debug.Assert(dbConnectionPoolAuthenticationContext != null, "dbConnectionPoolAuthenticationContext should not be null."); // The timespan between UTCNow and the token expiry. TimeSpan contextValidity = dbConnectionPoolAuthenticationContext.ExpirationTime.Subtract(DateTime.UtcNow); // If the authentication context is expiring within next 10 minutes, lets just re-create a token for this connection attempt. // And on successful login, try to update the cache with the new token. if (contextValidity <= _dbAuthenticationContextUnLockedRefreshTimeSpan) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFedAuthInfo> {0}, " + "The expiration time is less than 10 mins, so trying to get new access token regardless of if an other thread is also trying to update it." + "The expiration time is {1}. Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); attemptRefreshTokenUnLocked = true; } #if DEBUG // Checking if any failpoints are enabled. else if (_forceExpiryUnLocked) { attemptRefreshTokenUnLocked = true; } else if (_forceExpiryLocked) { attemptRefreshTokenLocked = TryGetFedAuthTokenLocked(fedAuthInfo, dbConnectionPoolAuthenticationContext, out _fedAuthToken); } #endif // If the token is expiring within the next 45 mins, try to fetch a new token, if there is no thread already doing it. // If a thread is already doing the refresh, just use the existing token in the cache and proceed. else if (contextValidity <= _dbAuthenticationContextLockedRefreshTimeSpan) { SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.OnFedAuthInfo|ADV> {0}, " + "The authentication context needs a refresh.The expiration time is {1}. " + "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); // Call the function which tries to acquire a lock over the authentication context before trying to update. // If the lock could not be obtained, it will return false, without attempting to fetch a new token. attemptRefreshTokenLocked = TryGetFedAuthTokenLocked(fedAuthInfo, dbConnectionPoolAuthenticationContext, out _fedAuthToken); // If TryGetFedAuthTokenLocked returns true, it means lock was obtained and _fedAuthToken should not be null. // If there was an exception in retrieving the new token, TryGetFedAuthTokenLocked should have thrown, so we won't be here. Debug.Assert(!attemptRefreshTokenLocked || _fedAuthToken != null, "Either Lock should not have been obtained or _fedAuthToken should not be null."); Debug.Assert(!attemptRefreshTokenLocked || _newDbConnectionPoolAuthenticationContext != null, "Either Lock should not have been obtained or _newDbConnectionPoolAuthenticationContext should not be null."); // Indicate in Bid Trace that we are successful with the update. if (attemptRefreshTokenLocked) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFedAuthInfo> {0}, The attempt to get a new access token succeeded under the locked mode.", ObjectID); } } SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.OnFedAuthInfo> {0}, Found an authentication context in the cache that does not need a refresh at this time. Re-using the cached token.", ObjectID); } } // dbConnectionPoolAuthenticationContext will be null if either this is the first connection attempt in the pool or pooling is disabled. if (dbConnectionPoolAuthenticationContext == null || attemptRefreshTokenUnLocked) { // Get the Federated Authentication Token. _fedAuthToken = GetFedAuthToken(fedAuthInfo); Debug.Assert(_fedAuthToken != null, "_fedAuthToken should not be null."); if (_dbConnectionPool != null) { // GetFedAuthToken should have updated _newDbConnectionPoolAuthenticationContext. Debug.Assert(_newDbConnectionPoolAuthenticationContext != null, "_newDbConnectionPoolAuthenticationContext should not be null."); } } else if (!attemptRefreshTokenLocked) { Debug.Assert(dbConnectionPoolAuthenticationContext != null, "dbConnectionPoolAuthenticationContext should not be null."); Debug.Assert(_fedAuthToken == null, "_fedAuthToken should be null in this case."); Debug.Assert(_newDbConnectionPoolAuthenticationContext == null, "_newDbConnectionPoolAuthenticationContext should be null."); _fedAuthToken = new SqlFedAuthToken(); // If the code flow is here, then we are re-using the context from the cache for this connection attempt and not // generating a new access token on this thread. _fedAuthToken.accessToken = dbConnectionPoolAuthenticationContext.AccessToken; _fedAuthToken.expirationFileTime = dbConnectionPoolAuthenticationContext.ExpirationTime.ToFileTime(); } Debug.Assert(_fedAuthToken != null && _fedAuthToken.accessToken != null, "_fedAuthToken and _fedAuthToken.accessToken cannot be null."); _parser.SendFedAuthToken(_fedAuthToken); } /// <summary> /// Tries to acquire a lock on the authentication context. If successful in acquiring the lock, gets a new token and assigns it in the out parameter. Else returns false. /// </summary> /// <param name="fedAuthInfo">Federated Authentication Info</param> /// <param name="dbConnectionPoolAuthenticationContext">Authentication Context cached in the connection pool.</param> /// <param name="fedAuthToken">Out parameter, carrying the token if we acquired a lock and got the token.</param> /// <returns></returns> internal bool TryGetFedAuthTokenLocked(SqlFedAuthInfo fedAuthInfo, DbConnectionPoolAuthenticationContext dbConnectionPoolAuthenticationContext, out SqlFedAuthToken fedAuthToken) { Debug.Assert(fedAuthInfo != null, "fedAuthInfo should not be null."); Debug.Assert(dbConnectionPoolAuthenticationContext != null, "dbConnectionPoolAuthenticationContext should not be null."); fedAuthToken = null; // Variable which indicates if we did indeed manage to acquire the lock on the authentication context, to try update it. bool authenticationContextLocked = false; // Prepare CER to ensure the lock on authentication context is released. RuntimeHelpers.PrepareConstrainedRegions(); try { // Try to obtain a lock on the context. If acquired, this thread got the opportunity to update. // Else some other thread is already updating it, so just proceed forward with the existing token in the cache. if (dbConnectionPoolAuthenticationContext.LockToUpdate()) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.TryGetFedAuthTokenLocked> {0}, " + "Acquired the lock to update the authentication context.The expiration time is {1}. " + "Current Time is {2}.", ObjectID, dbConnectionPoolAuthenticationContext.ExpirationTime.ToLongTimeString(), DateTime.UtcNow.ToLongTimeString()); authenticationContextLocked = true; } else { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.TryGetFedAuthTokenLocked> {0}, Refreshing the context is already in progress by another thread.", ObjectID); } if (authenticationContextLocked) { // Get the Federated Authentication Token. fedAuthToken = GetFedAuthToken(fedAuthInfo); Debug.Assert(fedAuthToken != null, "fedAuthToken should not be null."); } } finally { if (authenticationContextLocked) { // Release the lock we took on the authentication context, even if we have not yet updated the cache with the new context. Login process can fail at several places after this step and so there is no guarantee that the new context will make it to the cache. So we shouldn't miss resetting the flag. With the reset, at-least another thread may have a chance to update it. dbConnectionPoolAuthenticationContext.ReleaseLockToUpdate(); } } return authenticationContextLocked; } /// <summary> /// Get the Federated Authentication Token. /// </summary> /// <param name="fedAuthInfo">Information obtained from server as Federated Authentication Info.</param> /// <returns>SqlFedAuthToken</returns> internal SqlFedAuthToken GetFedAuthToken(SqlFedAuthInfo fedAuthInfo) { Debug.Assert(fedAuthInfo != null, "fedAuthInfo should not be null."); // No:of milliseconds to sleep for the inital back off. int sleepInterval = 100; // No:of attempts, for tracing purposes, if we underwent retries. int numberOfAttempts = 0; // Object that will be returned to the caller, containing all required data about the token. SqlFedAuthToken fedAuthToken = new SqlFedAuthToken(); // Username to use in error messages. string username = null; var authProvider = _sqlAuthenticationProviderManager.GetProvider(ConnectionOptions.Authentication); if (authProvider == null) throw SQL.CannotFindAuthProvider(ConnectionOptions.Authentication.ToString()); // retry getting access token once if MsalException.error_code is unknown_error. // extra logic to deal with HTTP 429 (Retry after). while (numberOfAttempts <= 1 && sleepInterval <= _timeout.MillisecondsRemaining) { numberOfAttempts++; try { var authParamsBuilder = new SqlAuthenticationParameters.Builder( authenticationMethod: ConnectionOptions.Authentication, resource: fedAuthInfo.spn, authority: fedAuthInfo.stsurl, serverName: ConnectionOptions.DataSource, databaseName: ConnectionOptions.InitialCatalog) .WithConnectionId(_clientConnectionId); switch (ConnectionOptions.Authentication) { case SqlAuthenticationMethod.ActiveDirectoryIntegrated: username = TdsEnums.NTAUTHORITYANONYMOUSLOGON; if (_activeDirectoryAuthTimeoutRetryHelper.State == ActiveDirectoryAuthenticationTimeoutRetryState.Retrying) { fedAuthToken = _activeDirectoryAuthTimeoutRetryHelper.CachedToken; } else { Task.Run(() => fedAuthToken = authProvider.AcquireTokenAsync(authParamsBuilder).Result.ToSqlFedAuthToken()).Wait(); _activeDirectoryAuthTimeoutRetryHelper.CachedToken = fedAuthToken; } break; case SqlAuthenticationMethod.ActiveDirectoryInteractive: case SqlAuthenticationMethod.ActiveDirectoryDeviceCodeFlow: if (_activeDirectoryAuthTimeoutRetryHelper.State == ActiveDirectoryAuthenticationTimeoutRetryState.Retrying) { fedAuthToken = _activeDirectoryAuthTimeoutRetryHelper.CachedToken; } else { authParamsBuilder.WithUserId(ConnectionOptions.UserID); Task.Run(() => fedAuthToken = authProvider.AcquireTokenAsync(authParamsBuilder).Result.ToSqlFedAuthToken()).Wait(); _activeDirectoryAuthTimeoutRetryHelper.CachedToken = fedAuthToken; } break; case SqlAuthenticationMethod.ActiveDirectoryPassword: case SqlAuthenticationMethod.ActiveDirectoryServicePrincipal: if (_activeDirectoryAuthTimeoutRetryHelper.State == ActiveDirectoryAuthenticationTimeoutRetryState.Retrying) { fedAuthToken = _activeDirectoryAuthTimeoutRetryHelper.CachedToken; } else { if (_credential != null) { username = _credential.UserId; authParamsBuilder.WithUserId(username).WithPassword(_credential.Password); Task.Run(() => fedAuthToken = authProvider.AcquireTokenAsync(authParamsBuilder).Result.ToSqlFedAuthToken()).Wait(); } else { username = ConnectionOptions.UserID; authParamsBuilder.WithUserId(username).WithPassword(ConnectionOptions.Password); Task.Run(() => fedAuthToken = authProvider.AcquireTokenAsync(authParamsBuilder).Result.ToSqlFedAuthToken()).Wait(); } _activeDirectoryAuthTimeoutRetryHelper.CachedToken = fedAuthToken; } break; default: throw SQL.UnsupportedAuthenticationSpecified(ConnectionOptions.Authentication); } Debug.Assert(fedAuthToken.accessToken != null, "AccessToken should not be null."); #if DEBUG if (_forceMsalRetry) { // 3399614468 is 0xCAA20004L just for testing. throw new MsalServiceException(MsalError.UnknownError, "Force retry in GetFedAuthToken"); } #endif // Break out of the retry loop in successful case. break; } // Deal with Msal service exceptions first, retry if 429 received. catch (MsalServiceException serviceException) { if (429 == serviceException.StatusCode) { RetryConditionHeaderValue retryAfter = serviceException.Headers.RetryAfter; if (retryAfter.Delta.HasValue) { sleepInterval = retryAfter.Delta.Value.Milliseconds; } else if (retryAfter.Date.HasValue) { sleepInterval = Convert.ToInt32(retryAfter.Date.Value.Offset.TotalMilliseconds); } // if there's enough time to retry before timeout, then retry, otherwise break out the retry loop. if (sleepInterval < _timeout.MillisecondsRemaining) { Thread.Sleep(sleepInterval); } else { break; } } } // Deal with normal MsalExceptions. catch (MsalException msalException) { if (MsalError.UnknownError != msalException.ErrorCode || _timeout.IsExpired || _timeout.MillisecondsRemaining <= sleepInterval) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.GetFedAuthToken.MSALException error:> {0}", msalException.ErrorCode); // Error[0] SqlErrorCollection sqlErs = new SqlErrorCollection(); sqlErs.Add(new SqlError(0, (byte)0x00, (byte)TdsEnums.MIN_ERROR_CLASS, ConnectionOptions.DataSource, StringsHelper.GetString(Strings.SQL_MSALFailure, username, ConnectionOptions.Authentication.ToString("G")), ActiveDirectoryAuthentication.MSALGetAccessTokenFunctionName, 0)); // Error[1] string errorMessage1 = StringsHelper.GetString(Strings.SQL_MSALInnerException, msalException.ErrorCode); sqlErs.Add(new SqlError(0, (byte)0x00, (byte)TdsEnums.MIN_ERROR_CLASS, ConnectionOptions.DataSource, errorMessage1, ActiveDirectoryAuthentication.MSALGetAccessTokenFunctionName, 0)); // Error[2] if (!string.IsNullOrEmpty(msalException.Message)) { sqlErs.Add(new SqlError(0, (byte)0x00, (byte)TdsEnums.MIN_ERROR_CLASS, ConnectionOptions.DataSource, msalException.Message, ActiveDirectoryAuthentication.MSALGetAccessTokenFunctionName, 0)); } SqlException exc = SqlException.CreateException(sqlErs, "", this); throw exc; } SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.GetFedAuthToken|ADV> {0}, sleeping {1}[Milliseconds]", ObjectID, sleepInterval); SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.GetFedAuthToken|ADV> {0}, remaining {1}[Milliseconds]", ObjectID, _timeout.MillisecondsRemaining); Thread.Sleep(sleepInterval); sleepInterval *= 2; } } Debug.Assert(fedAuthToken != null, "fedAuthToken should not be null."); Debug.Assert(fedAuthToken.accessToken != null && fedAuthToken.accessToken.Length > 0, "fedAuthToken.accessToken should not be null or empty."); // Store the newly generated token in _newDbConnectionPoolAuthenticationContext, only if using pooling. if (_dbConnectionPool != null) { DateTime expirationTime = DateTime.FromFileTimeUtc(fedAuthToken.expirationFileTime); _newDbConnectionPoolAuthenticationContext = new DbConnectionPoolAuthenticationContext(fedAuthToken.accessToken, expirationTime); } SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.GetFedAuthToken> {0}, Finished generating federated authentication token.", ObjectID); return fedAuthToken; } internal void OnFeatureExtAck(int featureId, byte[] data) { if (_routingInfo != null) { if (TdsEnums.FEATUREEXT_SQLDNSCACHING != featureId) { return; } } switch (featureId) { case TdsEnums.FEATUREEXT_SRECOVERY: { // Session recovery not requested if (!_sessionRecoveryRequested) { throw SQL.ParsingErrorFeatureId(ParsingErrorState.UnrequestedFeatureAckReceived, featureId); } _sessionRecoveryAcknowledged = true; #if DEBUG foreach (var s in _currentSessionData._delta) { Debug.Assert(s == null, "Delta should be null at this point"); } #endif Debug.Assert(_currentSessionData._unrecoverableStatesCount == 0, "Unrecoverable states count should be 0"); int i = 0; while (i < data.Length) { byte stateId = data[i]; i++; int len; byte bLen = data[i]; i++; if (bLen == 0xFF) { len = BitConverter.ToInt32(data, i); i += 4; } else { len = bLen; } byte[] stateData = new byte[len]; Buffer.BlockCopy(data, i, stateData, 0, len); i += len; if (_recoverySessionData == null) { _currentSessionData._initialState[stateId] = stateData; } else { _currentSessionData._delta[stateId] = new SessionStateRecord { _data = stateData, _dataLength = len, _recoverable = true, _version = 0 }; _currentSessionData._deltaDirty = true; } } break; } case TdsEnums.FEATUREEXT_FEDAUTH: { SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ADV> {0}, Received feature extension acknowledgement for federated authentication", ObjectID); if (!_federatedAuthenticationRequested) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ERR> {0}, Did not request federated authentication", ObjectID); throw SQL.ParsingErrorFeatureId(ParsingErrorState.UnrequestedFeatureAckReceived, featureId); } Debug.Assert(_fedAuthFeatureExtensionData != null, "_fedAuthFeatureExtensionData must not be null when _federatedAuthenticationRequested == true"); switch (_fedAuthFeatureExtensionData.Value.libraryType) { case TdsEnums.FedAuthLibrary.MSAL: case TdsEnums.FedAuthLibrary.SecurityToken: // The server shouldn't have sent any additional data with the ack (like a nonce) if (data.Length != 0) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ERR> {0}, Federated authentication feature extension ack for MSAL and Security Token includes extra data", ObjectID); throw SQL.ParsingError(ParsingErrorState.FedAuthFeatureAckContainsExtraData); } break; default: Debug.Fail("Unknown _fedAuthLibrary type"); SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ERR> {0}, Attempting to use unknown federated authentication library", ObjectID); throw SQL.ParsingErrorLibraryType(ParsingErrorState.FedAuthFeatureAckUnknownLibraryType, (int)_fedAuthFeatureExtensionData.Value.libraryType); } _federatedAuthenticationAcknowledged = true; // If a new authentication context was used as part of this login attempt, try to update the new context in the cache, i.e.dbConnectionPool.AuthenticationContexts. // ChooseAuthenticationContextToUpdate will take care that only the context which has more validity will remain in the cache, based on the Update logic. if (_newDbConnectionPoolAuthenticationContext != null) { Debug.Assert(_dbConnectionPool != null, "_dbConnectionPool should not be null when _newDbConnectionPoolAuthenticationContext != null."); DbConnectionPoolAuthenticationContext newAuthenticationContextInCacheAfterAddOrUpdate = _dbConnectionPool.AuthenticationContexts.AddOrUpdate(_dbConnectionPoolAuthenticationContextKey, _newDbConnectionPoolAuthenticationContext, (key, oldValue) => DbConnectionPoolAuthenticationContext.ChooseAuthenticationContextToUpdate(oldValue, _newDbConnectionPoolAuthenticationContext)); Debug.Assert(newAuthenticationContextInCacheAfterAddOrUpdate != null, "newAuthenticationContextInCacheAfterAddOrUpdate should not be null."); #if DEBUG // For debug purposes, assert and trace if we ended up updating the cache with the new one or some other thread's context won the expiration race. if (newAuthenticationContextInCacheAfterAddOrUpdate == _newDbConnectionPoolAuthenticationContext) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ERR> {0}, Updated the new dbAuthenticationContext in the _dbConnectionPool.AuthenticationContexts.", ObjectID); } else { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ERR> {0}, AddOrUpdate attempted on _dbConnectionPool.AuthenticationContexts, but it did not update the new value.", ObjectID); } #endif } break; } case TdsEnums.FEATUREEXT_TCE: { SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ADV> {0}, Received feature extension acknowledgement for TCE", ObjectID); if (data.Length < 1) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ERR> {0}, Unknown version number for TCE", ObjectID); throw SQL.ParsingError(ParsingErrorState.TceUnknownVersion); } byte supportedTceVersion = data[0]; if (0 == supportedTceVersion || supportedTceVersion > TdsEnums.MAX_SUPPORTED_TCE_VERSION) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ERR> {0}, Invalid version number for TCE", ObjectID); throw SQL.ParsingErrorValue(ParsingErrorState.TceInvalidVersion, supportedTceVersion); } _tceVersionSupported = supportedTceVersion; Debug.Assert(_tceVersionSupported <= TdsEnums.MAX_SUPPORTED_TCE_VERSION, "Client support TCE version 2"); _parser.IsColumnEncryptionSupported = true; _parser.TceVersionSupported = _tceVersionSupported; if (data.Length > 1) { _parser.EnclaveType = Encoding.Unicode.GetString(data, 2, (data.Length - 2)); } break; } case TdsEnums.FEATUREEXT_GLOBALTRANSACTIONS: { SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ADV> {0}, Received feature extension acknowledgement for GlobalTransactions", ObjectID); if (data.Length < 1) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ERR> {0}, Unknown version number for GlobalTransactions", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } IsGlobalTransaction = true; if (1 == data[0]) { IsGlobalTransactionsEnabledForServer = true; } break; } case TdsEnums.FEATUREEXT_AZURESQLSUPPORT: { SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ADV> {0}, Received feature extension acknowledgement for AzureSQLSupport", ObjectID); if (data.Length < 1) { throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } IsAzureSQLConnection = true; // Bit 0 for RO/FP support if ((data[0] & 1) == 1 && SqlClientEventSource.Log.IsTraceEnabled()) { SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ADV> {0}, FailoverPartner enabled with Readonly intent for AzureSQL DB", ObjectID); } break; } case TdsEnums.FEATUREEXT_DATACLASSIFICATION: { SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ADV> {0}, Received feature extension acknowledgement for DATACLASSIFICATION", ObjectID); if (data.Length < 1) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ERR> {0}, Unknown token for DATACLASSIFICATION", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte supportedDataClassificationVersion = data[0]; if ((0 == supportedDataClassificationVersion) || (supportedDataClassificationVersion > TdsEnums.DATA_CLASSIFICATION_VERSION_MAX_SUPPORTED)) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ERR> {0}, Invalid version number for DATACLASSIFICATION", ObjectID); throw SQL.ParsingErrorValue(ParsingErrorState.DataClassificationInvalidVersion, supportedDataClassificationVersion); } if (data.Length != 2) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ERR> {0}, Unknown token for DATACLASSIFICATION", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } byte enabled = data[1]; _parser.DataClassificationVersion = (enabled == 0) ? TdsEnums.DATA_CLASSIFICATION_NOT_ENABLED : supportedDataClassificationVersion; break; } case TdsEnums.FEATUREEXT_UTF8SUPPORT: { SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ADV> {0}, Received feature extension acknowledgement for UTF8 support", ObjectID); if (data.Length < 1) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ERR> {0}, Unknown value for UTF8 support", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } break; } case TdsEnums.FEATUREEXT_SQLDNSCACHING: { SqlClientEventSource.Log.AdvancedTraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ADV> {0}, Received feature extension acknowledgement for SQLDNSCACHING", ObjectID); if (data.Length < 1) { SqlClientEventSource.Log.TraceEvent("<sc.SqlInternalConnectionTds.OnFeatureExtAck|ERR> {0}, Unknown token for SQLDNSCACHING", ObjectID); throw SQL.ParsingError(ParsingErrorState.CorruptedTdsStream); } if (1 == data[0]) { IsSQLDNSCachingSupported = true; _cleanSQLDNSCaching = false; if (_routingInfo != null) { IsDNSCachingBeforeRedirectSupported = true; } } else { // we receive the IsSupported whose value is 0 IsSQLDNSCachingSupported = false; _cleanSQLDNSCaching = true; } // need to add more steps for phrase 2 // get IPv4 + IPv6 + Port number // not put them in the DNS cache at this point but need to store them somewhere // generate pendingSQLDNSObject and turn on IsSQLDNSRetryEnabled flag break; } default: { // Unknown feature ack throw SQL.ParsingErrorFeatureId(ParsingErrorState.UnknownFeatureAck, featureId); } } } //////////////////////////////////////////////////////////////////////////////////////// // Helper methods for Locks //////////////////////////////////////////////////////////////////////////////////////// // Indicates if the current thread claims to hold the parser lock internal bool ThreadHasParserLockForClose { get { return _threadIdOwningParserLock == Thread.CurrentThread.ManagedThreadId; } set { Debug.Assert(_parserLock.ThreadMayHaveLock(), "Should not modify ThreadHasParserLockForClose without taking the lock first"); Debug.Assert(_threadIdOwningParserLock == -1 || _threadIdOwningParserLock == Thread.CurrentThread.ManagedThreadId, "Another thread already claims to own the parser lock"); if (value) { // If setting to true, then the thread owning the lock is the current thread _threadIdOwningParserLock = Thread.CurrentThread.ManagedThreadId; } else if (_threadIdOwningParserLock == Thread.CurrentThread.ManagedThreadId) { // If setting to false and currently owns the lock, then no-one owns the lock _threadIdOwningParserLock = -1; } // else This thread didn't own the parser lock and doesn't claim to own it, so do nothing } } internal override bool TryReplaceConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource<DbConnectionInternal> retry, DbConnectionOptions userOptions) { return base.TryOpenConnectionInternal(outerConnection, connectionFactory, retry, userOptions); } } internal sealed class ServerInfo { internal string ExtendedServerName { get; private set; } // the resolved servername with protocol internal string ResolvedServerName { get; private set; } // the resolved servername only internal string ResolvedDatabaseName { get; private set; } // name of target database after resolution internal string UserProtocol { get; private set; } // the user specified protocol // The original user-supplied server name from the connection string. // If connection string has no Data Source, the value is set to string.Empty. // In case of routing, will be changed to routing destination internal string UserServerName { get { return m_userServerName; } private set { m_userServerName = value; } } private string m_userServerName; internal readonly string PreRoutingServerName; // Initialize server info from connection options, internal ServerInfo(SqlConnectionString userOptions) : this(userOptions, userOptions.DataSource) { } // Initialize server info from connection options, but override DataSource with given server name internal ServerInfo(SqlConnectionString userOptions, string serverName) { //----------------- // Preconditions Debug.Assert(null != userOptions); //----------------- //Method body Debug.Assert(serverName != null, "server name should never be null"); UserServerName = (serverName ?? string.Empty); // ensure user server name is not null UserProtocol = userOptions.NetworkLibrary; ResolvedDatabaseName = userOptions.InitialCatalog; PreRoutingServerName = null; } // Initialize server info from connection options, but override DataSource with given server name internal ServerInfo(SqlConnectionString userOptions, RoutingInfo routing, string preRoutingServerName) { //----------------- // Preconditions Debug.Assert(null != userOptions && null != routing); //----------------- //Method body Debug.Assert(routing.ServerName != null, "server name should never be null"); if (routing == null || routing.ServerName == null) { UserServerName = string.Empty; // ensure user server name is not null } else { UserServerName = string.Format(CultureInfo.InvariantCulture, "{0},{1}", routing.ServerName, routing.Port); } PreRoutingServerName = preRoutingServerName; UserProtocol = TdsEnums.TCP; SetDerivedNames(UserProtocol, UserServerName); ResolvedDatabaseName = userOptions.InitialCatalog; } internal void SetDerivedNames(string protocol, string serverName) { // The following concatenates the specified netlib network protocol to the host string, if netlib is not null // and the flag is on. This allows the user to specify the network protocol for the connection - but only // when using the Dbnetlib dll. If the protocol is not specified, the netlib will // try all protocols in the order listed in the Client Network Utility. Connect will // then fail if all protocols fail. if (!ADP.IsEmpty(protocol)) { ExtendedServerName = protocol + ":" + serverName; } else { ExtendedServerName = serverName; } ResolvedServerName = serverName; } } }
48.274605
389
0.565303
[ "MIT" ]
smurfpandey/SqlClient
src/Microsoft.Data.SqlClient/netfx/src/Microsoft/Data/SqlClient/SqlInternalConnectionTds.cs
158,920
C#
using Microsoft.Azure.Cosmos; using System; namespace Connecterra.StateTracking.Persistent.Connection { public interface IDbClient { CosmosClient GetClient(); Container GetLeaseContainer(); Container GetEventContainer(); Container GetViewContainer(); Container GetSnapshotContainer(); } public class CosmosDbClient : IDbClient { private readonly IConfigurationLocator _configuration; public CosmosDbClient(IConfigurationLocator configuration) { _configuration = configuration; } public CosmosClient GetClient() => new CosmosClient(_configuration.EndpointUrl, _configuration.AuthorizationKey); public Container GetLeaseContainer() => GetClient().GetContainer(_configuration.DatabaseId, _configuration.LeaseContainerId); public Container GetEventContainer() => GetClient().GetContainer(_configuration.DatabaseId, _configuration.EventContainerId); public Container GetViewContainer() => GetClient().GetContainer(_configuration.DatabaseId, _configuration.ViewContainerId); public Container GetSnapshotContainer() => GetClient().GetContainer(_configuration.DatabaseId, _configuration.SnapshotContainerId); } }
42
121
0.717358
[ "MIT" ]
ASMaharana/AI.Connecterra.StateTracking
src/Connecterra.StateTracking.Persistent/Connection/CosmosDbClient.cs
1,302
C#
// Copyright (c) Jeremy W. Kuhne. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using WInterop.Storage.Native; namespace WInterop.Storage { /// <summary> /// Callback for [IO_APC_ROUTINE]. Defined in wdm.h. /// </summary> public delegate void AsyncProcedureCall( IntPtr apcContext, ref IO_STATUS_BLOCK ioStatusBlock, uint reserved); }
29.3125
101
0.69936
[ "MIT" ]
JeremyKuhne/WInterop
src/WInterop.Desktop/Storage/AsyncProcedureCall.cs
471
C#
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; namespace SharpDX.DirectWrite { public partial class LocalizedStrings { /// <summary> /// Get the locale name from the language. /// </summary> /// <param name="index">Zero-based index of the locale name to be retrieved. </param> /// <returns>The locale name from the language </returns> /// <unmanaged>HRESULT IDWriteLocalizedStrings::GetLocaleName([None] int index,[Out, Buffer] wchar_t* localeName,[None] int size)</unmanaged> public string GetLocaleName(int index) { unsafe { int localNameLength; GetLocaleNameLength(index, out localNameLength); char* localName = stackalloc char[localNameLength+1]; GetLocaleName(index, new IntPtr(localName), localNameLength+1); return new string(localName, 0, localNameLength); } } /// <summary> /// Get the string from the language/string pair. /// </summary> /// <param name="index">Zero-based index of the string from the language/string pair to be retrieved. </param> /// <returns>The locale name from the language </returns> /// <unmanaged>HRESULT IDWriteLocalizedStrings::GetLocaleName([None] int index,[Out, Buffer] wchar_t* localeName,[None] int size)</unmanaged> public string GetString(int index) { unsafe { int stringNameLength; GetStringLength(index, out stringNameLength); char* stringName = stackalloc char[stringNameLength + 1]; GetString(index, new IntPtr(stringName), stringNameLength+1); return new string(stringName, 0, stringNameLength); } } } }
47.5
149
0.660102
[ "MIT" ]
Altair7610/SharpDX
Source/SharpDX.Direct2D1/DirectWrite/LocalizedStrings.cs
2,945
C#
//Problem URL: https://www.hackerrank.com/challenges/arrays-ds/problem static int[] reverseArray(int[] a) { for(int i = 0; i < Math.Floor(a.Length / 2d); i++){ int temp = a[i]; a[i] = a[a.Length - i - 1]; a[a.Length - i - 1] = temp; } return a; }
25.818182
70
0.53169
[ "Unlicense" ]
DKLynch/HackerRank-Challenges
Data Structures/Arrays/Arrays - DS (Reverse Array)/reverseArray.cs
284
C#
using System.Configuration; namespace Stove.Demo.ConsoleApp { public static class ConnectionStringHelper { /// <summary> /// Gets connection string from given connection string or name. /// </summary> public static string GetConnectionString(string nameOrConnectionString) { ConnectionStringSettings connStrSection = ConfigurationManager.ConnectionStrings[nameOrConnectionString]; if (connStrSection != null) { return connStrSection.ConnectionString; } return nameOrConnectionString; } } }
28.772727
117
0.635071
[ "MIT" ]
eraydin/Stove
test/Stove.Demo.ConsoleApp/ConnectionStringHelper.cs
635
C#
using System; namespace MLD.Library.Helper { /// <summary> /// 判断数据类型 /// </summary> public static class Vilidate { /// <summary> /// 判断数据是否是日期类型 /// </summary> /// <param name="date">待判断的数据</param> /// <returns>判断后的bool值</returns> public static bool IsDate(string date) { var dt = new DateTime(); bool flag = DateTime.TryParse(date, out dt); return flag; } /// <summary> /// 检查字符串是否为空 /// </summary> /// <param name="target">待检查的字符串</param> /// <returns>如果为null返回false,反之tr返回ue</returns> public static bool IsNull(this string target) { if (string.IsNullOrWhiteSpace(target)) return true; return false; } } }
24
56
0.50119
[ "Apache-2.0" ]
huahuajjh/mld
MLD/MLD/MLD.Library/Helper/Vilidate.cs
950
C#
using System; using FluentAssertions; using Xunit; namespace Bogus.Tests { public class StrictModeTests : SeededTest { [Fact] public void should_throw_exception_on_incomplete_rules() { var testOrders = new Faker<Examples.Order>() .StrictMode(true) .RuleFor(o => o.Quantity, f => f.Random.Number(2, 5)); testOrders.Invoking(faker => faker.Generate()) .Should().Throw<ValidationException>(); } [Fact] public void should_not_throw_exception_on_complete_rule_set() { var testOrders = new Faker<Examples.Order>() .StrictMode(true) .RuleFor(o => o.Quantity, f => f.Random.Number(2, 5)) .RuleFor(o => o.Item, f => f.Lorem.Sentence()) .RuleFor(o => o.OrderId, f => f.Random.Number()); testOrders.Invoking(faker => faker.Generate()) .Should().NotThrow<ValidationException>(); } [Fact] public void cannot_use_rules_with_strictmode() { var faker = new Faker<Examples.Order>() .Rules((f, o) => { o.Quantity = f.Random.Number(1, 4); o.Item = f.Commerce.Product(); o.OrderId = 25; }) .StrictMode(true); Action act = () => faker.AssertConfigurationIsValid(); act.Should().Throw<ValidationException>(); var faker2 = new Faker<Examples.Order>() .StrictMode(true) .Rules((f, o) => { o.Quantity = f.Random.Number(1, 4); o.Item = f.Commerce.Product(); o.OrderId = 25; }); Action act2 = () => faker2.AssertConfigurationIsValid(); act2.Should().Throw<ValidationException>(); } [Fact] public void cannot_use_rules_with_strictmode_inside_rulesets() { const string myset = "myset"; var faker = new Faker<Examples.Order>() .RuleSet(myset, set => { set.Rules((f, o) => { o.Quantity = f.Random.Number(1, 4); o.Item = f.Commerce.Product(); o.OrderId = 25; }); set.StrictMode(true); }); Action act = () => faker.AssertConfigurationIsValid(); act.Should().Throw<ValidationException>(); var faker2 = new Faker<Examples.Order>() .RuleSet(myset, set => { set.StrictMode(true); set.Rules((f, o) => { o.Quantity = f.Random.Number(1, 4); o.Item = f.Commerce.Product(); o.OrderId = 25; }); }); Action act2 = () => faker2.AssertConfigurationIsValid(); act2.Should().Throw<ValidationException>(); } } }
30.918367
68
0.481848
[ "BSD-3-Clause" ]
GillCleeren/Bogus
Source/Bogus.Tests/StrictModeTests.cs
3,030
C#
namespace InteriorDesign.Data.Common.Repositories { using System.Linq; using System.Threading.Tasks; using InteriorDesign.Data.Common.Models; public interface IDeletableEntityRepository<TEntity> : IRepository<TEntity> where TEntity : class, IDeletableEntity { IQueryable<TEntity> AllWithDeleted(); IQueryable<TEntity> AllAsNoTrackingWithDeleted(); Task<TEntity> GetByIdWithDeletedAsync(params object[] id); void HardDelete(TEntity entity); void Undelete(TEntity entity); } }
25.181818
79
0.709386
[ "MIT" ]
vanya-ant/InteriorDesign
InteriorDesign/Data/InteriorDesign.Data.Common/Repositories/IDeletableEntityRepository.cs
556
C#
namespace UglyToad.PdfPig.Parser { using System; using System.Collections.Generic; using Annotations; using Content; using Core; using Filters; using Geometry; using Graphics; using Logging; using Parts; using Tokenization.Scanner; using Tokens; using Util; internal class PageFactory : IPageFactory { private readonly IPdfTokenScanner pdfScanner; private readonly IResourceStore resourceStore; private readonly IFilterProvider filterProvider; private readonly IPageContentParser pageContentParser; private readonly ILog log; public PageFactory(IPdfTokenScanner pdfScanner, IResourceStore resourceStore, IFilterProvider filterProvider, IPageContentParser pageContentParser, ILog log) { this.resourceStore = resourceStore; this.filterProvider = filterProvider; this.pageContentParser = pageContentParser; this.log = log; this.pdfScanner = pdfScanner; } public Page Create(int number, DictionaryToken dictionary, PageTreeMembers pageTreeMembers, bool clipPaths) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary)); } var type = dictionary.GetNameOrDefault(NameToken.Type); if (type != null && !type.Equals(NameToken.Page)) { log?.Error($"Page {number} had its type specified as {type} rather than 'Page'."); } var rotation = new PageRotationDegrees(pageTreeMembers.Rotation); if (dictionary.TryGet(NameToken.Rotate, pdfScanner, out NumericToken rotateToken)) { rotation = new PageRotationDegrees(rotateToken.Int); } MediaBox mediaBox = GetMediaBox(number, dictionary, pageTreeMembers); CropBox cropBox = GetCropBox(dictionary, pageTreeMembers, mediaBox); var stackDepth = 0; while (pageTreeMembers.ParentResources.Count > 0) { var resource = pageTreeMembers.ParentResources.Dequeue(); resourceStore.LoadResourceDictionary(resource); stackDepth++; } if (dictionary.TryGet(NameToken.Resources, pdfScanner, out DictionaryToken resources)) { resourceStore.LoadResourceDictionary(resources); stackDepth++; } UserSpaceUnit userSpaceUnit = GetUserSpaceUnits(dictionary); PageContent content = default(PageContent); if (!dictionary.TryGet(NameToken.Contents, out var contents)) { // ignored for now, is it possible? check the spec... } else if (DirectObjectFinder.TryGet<ArrayToken>(contents, pdfScanner, out var array)) { var bytes = new List<byte>(); for (var i = 0; i < array.Data.Count; i++) { var item = array.Data[i]; if (!(item is IndirectReferenceToken obj)) { throw new PdfDocumentFormatException($"The contents contained something which was not an indirect reference: {item}."); } var contentStream = DirectObjectFinder.Get<StreamToken>(obj, pdfScanner); if (contentStream == null) { throw new InvalidOperationException($"Could not find the contents for object {obj}."); } bytes.AddRange(contentStream.Decode(filterProvider)); if (i < array.Data.Count - 1) { bytes.Add((byte)'\n'); } } content = GetContent(number, bytes, cropBox, userSpaceUnit, rotation, clipPaths); } else { var contentStream = DirectObjectFinder.Get<StreamToken>(contents, pdfScanner); if (contentStream == null) { throw new InvalidOperationException("Failed to parse the content for the page: " + number); } var bytes = contentStream.Decode(filterProvider); content = GetContent(number, bytes, cropBox, userSpaceUnit, rotation, clipPaths); } var page = new Page(number, dictionary, mediaBox, cropBox, rotation, content, new AnnotationProvider(pdfScanner, dictionary), pdfScanner); for (var i = 0; i < stackDepth; i++) { resourceStore.UnloadResourceDictionary(); } return page; } private PageContent GetContent(int pageNumber, IReadOnlyList<byte> contentBytes, CropBox cropBox, UserSpaceUnit userSpaceUnit, PageRotationDegrees rotation, bool clipPaths) { var operations = pageContentParser.Parse(pageNumber, new ByteArrayInputBytes(contentBytes), log); var context = new ContentStreamProcessor(cropBox.Bounds, resourceStore, userSpaceUnit, rotation, pdfScanner, pageContentParser, filterProvider, log, clipPaths); return context.Process(pageNumber, operations); } private static UserSpaceUnit GetUserSpaceUnits(DictionaryToken dictionary) { var spaceUnits = UserSpaceUnit.Default; if (dictionary.TryGet(NameToken.UserUnit, out var userUnitBase) && userUnitBase is NumericToken userUnitNumber) { spaceUnits = new UserSpaceUnit(userUnitNumber.Int); } return spaceUnits; } private CropBox GetCropBox(DictionaryToken dictionary, PageTreeMembers pageTreeMembers, MediaBox mediaBox) { CropBox cropBox; if (dictionary.TryGet(NameToken.CropBox, out var cropBoxObject) && DirectObjectFinder.TryGet(cropBoxObject, pdfScanner, out ArrayToken cropBoxArray)) { if (cropBoxArray.Length != 4) { log.Error($"The CropBox was the wrong length in the dictionary: {dictionary}. Array was: {cropBoxArray}. Using MediaBox."); cropBox = new CropBox(mediaBox.Bounds); return cropBox; } cropBox = new CropBox(cropBoxArray.ToIntRectangle(pdfScanner)); } else { cropBox = pageTreeMembers.GetCropBox() ?? new CropBox(mediaBox.Bounds); } return cropBox; } private MediaBox GetMediaBox(int number, DictionaryToken dictionary, PageTreeMembers pageTreeMembers) { MediaBox mediaBox; if (dictionary.TryGet(NameToken.MediaBox, out var mediaboxObject) && DirectObjectFinder.TryGet(mediaboxObject, pdfScanner, out ArrayToken mediaboxArray)) { if (mediaboxArray.Length != 4) { log.Error($"The MediaBox was the wrong length in the dictionary: {dictionary}. Array was: {mediaboxArray}. Defaulting to US Letter."); mediaBox = MediaBox.Letter; return mediaBox; } mediaBox = new MediaBox(mediaboxArray.ToIntRectangle(pdfScanner)); } else { mediaBox = pageTreeMembers.MediaBox; if (mediaBox == null) { log.Error($"The MediaBox was the wrong missing for page {number}. Using US Letter."); // PDFBox defaults to US Letter. mediaBox = MediaBox.Letter; } } return mediaBox; } } }
36.116071
154
0.562052
[ "Apache-2.0" ]
mcjt/PdfPig
src/UglyToad.PdfPig/Parser/PageFactory.cs
8,092
C#