content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using NUnit.Framework; using Kayak; using System.Threading; using Kayak.Tests.Net; using Kayak.Tests; using System.Diagnostics; namespace Kayak.Tests.Net { // TODO // - closes connection if no OnConnection listeners // - raises OnClose after being closed. class ServerTests { ManualResetEventSlim wh; IServer server; IDisposable stopListening; public IPEndPoint LocalEP(int port) { return new IPEndPoint(IPAddress.Loopback, port); } [SetUp] public void SetUp() { wh = new ManualResetEventSlim(); var schedulerDelegate = new SchedulerDelegate(); schedulerDelegate.OnStoppedAction = () => wh.Set(); var scheduler = new DefaultKayakScheduler(schedulerDelegate); schedulerDelegate.OnExceptionAction = e => { Debug.WriteLine("Error on scheduler"); e.DebugStackTrace(); scheduler.Stop(); }; var serverDelegate = new ServerDelegate(); server = new DefaultKayakServer(serverDelegate, scheduler); } [TearDown] public void TearDown() { if (stopListening != null) stopListening.Dispose(); wh.Dispose(); server.Dispose(); } [Test] public void Listen_after_listen_throws_exception() { Exception e = null; var ep = LocalEP(Config.Port); server.Listen(ep); try { stopListening = server.Listen(LocalEP(Config.Port)); } catch (Exception ex) { e = ex; } Assert.That(e, Is.Not.Null); Assert.That(e.GetType(), Is.EqualTo(typeof(InvalidOperationException))); Assert.That(e.Message, Is.EqualTo("The server was already listening.")); } } }
26.9625
85
0.540566
[ "MIT" ]
kayakhttp/kayak
Kayak.Tests/Net/ServerTests.cs
2,159
C#
๏ปฟnamespace FoodRecipes.Test.Controllers { using Microsoft.AspNetCore.Mvc.Testing; using System.Threading.Tasks; using Xunit; public class HomeControllerSystemTest : IClassFixture<WebApplicationFactory<Startup>> { private readonly WebApplicationFactory<Startup> factory; public HomeControllerSystemTest(WebApplicationFactory<Startup> factory) => this.factory = factory; [Fact] public async Task IndexShouldReturnCorrectStatusCode() { // Arrange var client = this.factory.CreateClient(); // Act var result = await client.GetAsync("/"); // Arrange Assert.True(result.IsSuccessStatusCode); } } }
26.892857
89
0.634794
[ "MIT" ]
MihailMilenkov/Food.Recipes.ASP.Net
FoodRecipes.Test/Controllers/HomeControllerSystemTest.cs
755
C#
๏ปฟusing leetcodeinterviewquestions.Trees_and_Graphs; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace UnitTests.Trees_and_Graphs { public class NumberOfIslandsTest { private NumberOfIslands solution; [SetUp] public void Setup() { solution = new NumberOfIslands(); } [Test] public void Test1() { var inputStr = @"11110 11010 11000 00000"; var input = inputStr.Split(Environment.NewLine).Select(str => str.ToCharArray()).ToArray(); var result = solution.NumIslands(input); Assert.AreEqual(1, result); } [Test] public void Test2() { var inputStr = @"11000 11000 00100 00011"; var input = inputStr.Split(Environment.NewLine).Select(str => str.ToCharArray()).ToArray(); var result = solution.NumIslands(input); Assert.AreEqual(3, result); } } }
23.545455
103
0.598456
[ "MIT" ]
YLiohenki/leetcodeinterviewquestions
UnitTests/Trees and Graphs/NumberOfIslands.cs
1,038
C#
๏ปฟusing DarkSoulsII.DebugView.Core; namespace DarkSoulsII.DebugView.Model.Events { public class MapObjectBonfire : IReadable<MapObjectBonfire>, IFixedSize { public const byte KindledMask = 1; public const byte AscentionLevelMask = 254; public ushort Id { get; set; } public bool Kindled { get; set; } public byte AscentionLevel { get; set; } public int Size { get { return 16; } } public MapObjectBonfire Read(IPointerFactory pointerFactory, IReader reader, int address, bool relative = false) { Id = reader.ReadUInt16(address + 0x0000, relative); var bonfireStatus = reader.ReadByte(address + 0x0002, relative); Kindled = (bonfireStatus & KindledMask) > 0; AscentionLevel = (byte) ((bonfireStatus & AscentionLevelMask) >> 1); // 0004 ParamEntry return this; } } }
28.939394
120
0.609424
[ "MIT" ]
Atvaark/DarkSoulsII.DebugView
DarkSoulsII.DebugView.Model/Events/MapObjectBonfire.cs
957
C#
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using Gallio.Common.Collections; using Gallio.Tests; using MbUnit.Framework; using Gallio.Model.Filters; namespace Gallio.Tests.Model.Filters { [TestFixture] [TestsOn(typeof(FilterRule<object>))] public class FilterRuleTest : BaseTestWithMocks { [Test] [ExpectedException(typeof(ArgumentNullException))] public void Constructor_WhenArgumentIsNull_Throws() { new FilterRule<object>(FilterRuleType.Inclusion, null); } [Test] public void Constructor_WhenInvoked_InitializesProperties() { var filter = new AnyFilter<object>(); var filterRule = new FilterRule<object>(FilterRuleType.Exclusion, filter); Assert.AreEqual(FilterRuleType.Exclusion, filterRule.RuleType); Assert.AreEqual(filter, filterRule.Filter); } } }
34.847826
87
0.683094
[ "ECL-2.0", "Apache-2.0" ]
Gallio/mbunit-v3
src/Gallio/Gallio.Tests/Model/Filters/FilterRuleTest.cs
1,603
C#
๏ปฟusing System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AgentDetails")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("AgentDetails")] [assembly: AssemblyCopyright("Copyright ยฉ Microsoft 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("fa6461c0-8773-4e78-9384-3ab7e81b7529")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.243243
84
0.74841
[ "MIT" ]
harlandgomez/woc
src/AgentDetails/Properties/AssemblyInfo.cs
1,418
C#
using System.Diagnostics; using System.Net; using Microsoft.AspNetCore.Http; using HotChocolate.AspNetCore.Instrumentation; using HotChocolate.AspNetCore.Serialization; using HotChocolate.Language; using HttpRequestDelegate = Microsoft.AspNetCore.Http.RequestDelegate; namespace HotChocolate.AspNetCore; public sealed class HttpGetMiddleware : MiddlewareBase { private static readonly OperationType[] _onlyQueries = { OperationType.Query }; private readonly IHttpRequestParser _requestParser; private readonly IServerDiagnosticEvents _diagnosticEvents; public HttpGetMiddleware( HttpRequestDelegate next, IRequestExecutorResolver executorResolver, IHttpResultSerializer resultSerializer, IHttpRequestParser requestParser, IServerDiagnosticEvents diagnosticEvents, NameString schemaName) : base(next, executorResolver, resultSerializer, schemaName) { _requestParser = requestParser ?? throw new ArgumentNullException(nameof(requestParser)); _diagnosticEvents = diagnosticEvents ?? throw new ArgumentNullException(nameof(diagnosticEvents)); } public async Task InvokeAsync(HttpContext context) { if (HttpMethods.IsGet(context.Request.Method) && (context.GetGraphQLServerOptions()?.EnableGetRequests ?? true)) { if (!IsDefaultSchema) { context.Items[WellKnownContextData.SchemaName] = SchemaName.Value; } using (_diagnosticEvents.ExecuteHttpRequest(context, HttpRequestKind.HttpGet)) { await HandleRequestAsync(context); } } else { // if the request is not a get request or if the content type is not correct // we will just invoke the next middleware and do nothing. await NextAsync(context); } } private async Task HandleRequestAsync(HttpContext context) { // first we need to get the request executor to be able to execute requests. IRequestExecutor requestExecutor = await GetExecutorAsync(context.RequestAborted); IHttpRequestInterceptor requestInterceptor = requestExecutor.GetRequestInterceptor(); IErrorHandler errorHandler = requestExecutor.GetErrorHandler(); context.Items[WellKnownContextData.RequestExecutor] = requestExecutor; HttpStatusCode? statusCode = null; IExecutionResult? result; // next we parse the GraphQL request. GraphQLRequest request; using (_diagnosticEvents.ParseHttpRequest(context)) { try { request = _requestParser.ReadParamsRequest(context.Request.Query); } catch (GraphQLRequestException ex) { // A GraphQL request exception is thrown if the HTTP request body couldn't be // parsed. In this case we will return HTTP status code 400 and return a // GraphQL error result. statusCode = HttpStatusCode.BadRequest; IReadOnlyList<IError> errors = errorHandler.Handle(ex.Errors); result = QueryResultBuilder.CreateError(errors); _diagnosticEvents.ParserErrors(context, errors); goto HANDLE_RESULT; } catch (Exception ex) { statusCode = HttpStatusCode.InternalServerError; IError error = errorHandler.CreateUnexpectedError(ex).Build(); result = QueryResultBuilder.CreateError(error); _diagnosticEvents.HttpRequestError(context, error); goto HANDLE_RESULT; } } // after successfully parsing the request we now will attempt to execute the request. try { GraphQLServerOptions? options = context.GetGraphQLServerOptions(); result = await ExecuteSingleAsync( context, requestExecutor, requestInterceptor, _diagnosticEvents, request, options is null or { AllowedGetOperations: AllowedGetOperations.Query } ? _onlyQueries : null); } catch (GraphQLException ex) { // This allows extensions to throw GraphQL exceptions in the GraphQL interceptor. statusCode = null; // we let the serializer determine the status code. result = QueryResultBuilder.CreateError(ex.Errors); } catch (Exception ex) { statusCode = HttpStatusCode.InternalServerError; IError error = errorHandler.CreateUnexpectedError(ex).Build(); result = QueryResultBuilder.CreateError(error); } HANDLE_RESULT: IDisposable? formatScope = null; try { // if cancellation is requested we will not try to attempt to write the result to the // response stream. if (context.RequestAborted.IsCancellationRequested) { return; } // in any case we will have a valid GraphQL result at this point that can be written // to the HTTP response stream. Debug.Assert(result is not null, "No GraphQL result was created."); if (result is IQueryResult queryResult) { formatScope = _diagnosticEvents.FormatHttpResponse(context, queryResult); } await WriteResultAsync(context.Response, result, statusCode, context.RequestAborted); } finally { // we must dispose the diagnostic scope first. formatScope?.Dispose(); // query results use pooled memory an need to be disposed after we have // used them. if (result is IAsyncDisposable asyncDisposable) { await asyncDisposable.DisposeAsync(); } if (result is not null) { await result.DisposeAsync(); } } } }
37.527273
97
0.619186
[ "MIT" ]
ChilliCream/prometheus
src/HotChocolate/AspNetCore/src/AspNetCore/HttpGetMiddleware.cs
6,192
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Graphics.Printing { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] #endif public partial class PrintTaskCompletedEventArgs { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ || __MACOS__ [global::Uno.NotImplemented] public global::Windows.Graphics.Printing.PrintTaskCompletion Completion { get { throw new global::System.NotImplementedException("The member PrintTaskCompletion PrintTaskCompletedEventArgs.Completion is not implemented in Uno."); } } #endif // Forced skipping of method Windows.Graphics.Printing.PrintTaskCompletedEventArgs.Completion.get } }
32.826087
153
0.762914
[ "Apache-2.0" ]
AlexTrepanier/Uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Graphics.Printing/PrintTaskCompletedEventArgs.cs
755
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 Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc.Razor.Internal; using Microsoft.Extensions.FileProviders; using Moq; namespace Microsoft.AspNetCore.Mvc.RazorPages { public class TestRazorProjectFileSystem : FileProviderRazorProjectFileSystem { public TestRazorProjectFileSystem(IFileProvider fileProvider, IHostingEnvironment hostingEnvironment) :base(GetAccessor(fileProvider), hostingEnvironment) { } private static IRazorViewEngineFileProviderAccessor GetAccessor(IFileProvider fileProvider) { var fileProviderAccessor = new Mock<IRazorViewEngineFileProviderAccessor>(); fileProviderAccessor.SetupGet(f => f.FileProvider) .Returns(fileProvider); return fileProviderAccessor.Object; } } }
35.928571
111
0.734592
[ "Apache-2.0" ]
Kartikexp/MvcDotnet
test/Microsoft.AspNetCore.Mvc.RazorPages.Test/TestRazorProjectFileSystem.cs
1,008
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 firehose-2015-08-04.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.KinesisFirehose { /// <summary> /// Configuration for accessing Amazon KinesisFirehose service /// </summary> public partial class AmazonKinesisFirehoseConfig : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.7.0.50"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonKinesisFirehoseConfig() { this.AuthenticationServiceName = "firehose"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "firehose"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2015-08-04"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
26.325
106
0.591168
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/KinesisFirehose/Generated/AmazonKinesisFirehoseConfig.cs
2,106
C#
๏ปฟusing System.Security.Claims; using System.Threading.Tasks; using Emeraude.Infrastructure.Identity.Services; using Microsoft.AspNetCore.Authentication; namespace Emeraude.Infrastructure.Identity.ExternalProviders; /// <summary> /// Provides external provider authenticator for registration and consuming external authentication services. /// </summary> public interface IExternalProviderAuthenticator { /// <summary> /// Client id. /// </summary> string ClientId { get; set; } /// <summary> /// Client secret. /// </summary> string ClientSecret { get; set; } /// <summary> /// Gets the external provider name. /// </summary> public string Name { get; } /// <summary> /// Gets external user stored in the claims principal of the request. /// </summary> /// <param name="principal"></param> /// <returns></returns> Task<IExternalUser> GetExternalUserAsync(ClaimsPrincipal principal); /// <summary> /// Gets external user based on the provider name and its provided access token. /// </summary> /// <param name="provider"></param> /// <param name="accessToken"></param> /// <returns></returns> Task<IExternalUser> GetExternalUserAsync(string provider, string accessToken); /// <summary> /// Register authenticator into the authentication settings. /// </summary> /// <param name="builder"></param> void RegisterAuthenticator(AuthenticationBuilder builder); }
30.895833
109
0.675657
[ "Apache-2.0" ]
emeraudeframework/emeraude
src/Emeraude.Infrastructure.Identity/ExternalProviders/IExternalProviderAuthenticator.cs
1,485
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; using Json.Pointer; namespace Json.Schema { /// <summary> /// Handles `allOf`. /// </summary> [Applicator] [SchemaPriority(20)] [SchemaKeyword(Name)] [SchemaDraft(Draft.Draft6)] [SchemaDraft(Draft.Draft7)] [SchemaDraft(Draft.Draft201909)] [SchemaDraft(Draft.Draft202012)] [Vocabulary(Vocabularies.Applicator201909Id)] [Vocabulary(Vocabularies.Applicator202012Id)] [JsonConverter(typeof(AllOfKeywordJsonConverter))] public class AllOfKeyword : IJsonSchemaKeyword, IRefResolvable, ISchemaCollector, IEquatable<AllOfKeyword> { internal const string Name = "allOf"; /// <summary> /// The keywords schema collection. /// </summary> public IReadOnlyList<JsonSchema> Schemas { get; } /// <summary> /// Creates a new <see cref="AllOfKeyword"/>. /// </summary> /// <param name="values">The set of schemas.</param> public AllOfKeyword(params JsonSchema[] values) { Schemas = values.ToList() ?? throw new ArgumentNullException(nameof(values)); } /// <summary> /// Creates a new <see cref="AllOfKeyword"/>. /// </summary> /// <param name="values">The set of schemas.</param> public AllOfKeyword(IEnumerable<JsonSchema> values) { Schemas = values.ToList() ?? throw new ArgumentNullException(nameof(values)); } /// <summary> /// Provides validation for the keyword. /// </summary> /// <param name="context">Contextual details for the validation process.</param> public void Validate(ValidationContext context) { context.EnterKeyword(Name); var overallResult = true; for (var i = 0; i < Schemas.Count; i++) { context.Log(() => $"Processing {Name}[{i}]..."); var schema = Schemas[i]; var subContext = ValidationContext.From(context, subschemaLocation: context.SchemaLocation.Combine(PointerSegment.Create($"{i}"))); schema.ValidateSubschema(subContext); overallResult &= subContext.IsValid; context.Log(() => $"{Name}[{i}] {subContext.IsValid.GetValidityString()}."); if (!overallResult && context.ApplyOptimizations) break; context.NestedContexts.Add(subContext); } context.ConsolidateAnnotations(); context.IsValid = overallResult; context.ExitKeyword(Name, context.IsValid); } IRefResolvable? IRefResolvable.ResolvePointerSegment(string? value) { if (!int.TryParse(value, out var index)) return null; if (index < 0 || Schemas.Count <= index) return null; return Schemas[index]; } void IRefResolvable.RegisterSubschemas(SchemaRegistry registry, Uri currentUri) { foreach (var schema in Schemas) { schema.RegisterSubschemas(registry, currentUri); } } /// <summary>Indicates whether the current object is equal to another object of the same type.</summary> /// <param name="other">An object to compare with this object.</param> /// <returns>true if the current object is equal to the <paramref name="other">other</paramref> parameter; otherwise, false.</returns> public bool Equals(AllOfKeyword? other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Schemas.ContentsEqual(other.Schemas); } /// <summary>Determines whether the specified object is equal to the current object.</summary> /// <param name="obj">The object to compare with the current object.</param> /// <returns>true if the specified object is equal to the current object; otherwise, false.</returns> public override bool Equals(object obj) { return Equals(obj as AllOfKeyword); } /// <summary>Serves as the default hash function.</summary> /// <returns>A hash code for the current object.</returns> public override int GetHashCode() { return Schemas.GetUnorderedCollectionHashCode(); } } internal class AllOfKeywordJsonConverter : JsonConverter<AllOfKeyword> { public override AllOfKeyword Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.StartArray) { var schemas = JsonSerializer.Deserialize<List<JsonSchema>>(ref reader, options); return new AllOfKeyword(schemas); } var schema = JsonSerializer.Deserialize<JsonSchema>(ref reader, options); return new AllOfKeyword(schema); } public override void Write(Utf8JsonWriter writer, AllOfKeyword value, JsonSerializerOptions options) { writer.WritePropertyName(AllOfKeyword.Name); writer.WriteStartArray(); foreach (var schema in value.Schemas) { JsonSerializer.Serialize(writer, schema, options); } writer.WriteEndArray(); } } }
33.156028
136
0.717005
[ "MIT" ]
ConnectionMaster/json-everything
JsonSchema/AllOfKeyword.cs
4,677
C#
๏ปฟusing Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Routing; namespace Microsoft.AspNetCore.Builder { public static class EndpointRoutingApplicationBuilderExtensions { public static IApplicationBuilder UseEndpointsWithFallbackRoute(this IApplicationBuilder app) { return app.UseEndpoints(endpoints => { endpoints.MapControllers() ;//.RequireAuthorization("ApiScope"); // TODO: is this the best place for this line of code? Shouldn't it be moved somewhere to do with authorization? endpoints.MapFallBack(); }); } } }
34.157895
166
0.662558
[ "Apache-2.0" ]
EnergeticApps/Energetic.WebApis.Extensions
Routing/EndpointRoutingApplicationBuilderExtensions.cs
651
C#
๏ปฟusing System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using FsCheck.MsTest.Examples.ClassesToTest; namespace FsCheck.MsTest.Examples { [TestClass] public class SampleTests { [TestMethod] public void RevRev() { Prop.ForAll<int[]>(xs => xs.Reverse().Reverse().SequenceEqual(xs)) .QuickCheckThrowOnFailure(); } [TestMethod, ExpectedException(typeof(Exception))] public void RevId() { Prop.ForAll<int[]>(xs => xs.Reverse().SequenceEqual(xs)) .VerboseCheckThrowOnFailure(); } [TestMethod, ExpectedException(typeof(Exception))] public void Insert() { Prop.ForAll<int, int[]>((x, xs) => xs.Insert(x).IsOrdered() .When(xs.IsOrdered())) .QuickCheckThrowOnFailure(); } [TestMethod] public void DivByZero() { Prop.ForAll<int>(a => new Func<bool>(() => 1 / a == 1 / a).When(a != 0)) .QuickCheckThrowOnFailure(); } [TestMethod, ExpectedException(typeof(Exception))] public void InsertTrivial() { Prop.ForAll<int, int[]>((x, xs) => xs.Insert(x).IsOrdered() .When(xs.IsOrdered()) .Classify(xs.Count() == 0, "trivial")) .QuickCheckThrowOnFailure(); } [TestMethod, ExpectedException(typeof(Exception))] public void InsertClassify() { Prop.ForAll<int, int[]>((x, xs) => xs.Insert(x).IsOrdered() .When(xs.IsOrdered()) .Classify(new[] { x }.Concat(xs).IsOrdered(), "at-head") .Classify(xs.Concat(new int[] { x }).IsOrdered(), "at-tail")) .QuickCheckThrowOnFailure(); } [TestMethod, ExpectedException(typeof(Exception))] public void InsertCollect() { Prop.ForAll<int, int[]>((x, xs) => xs.Insert(x).IsOrdered() .When(xs.IsOrdered()) .Collect("length " + xs.Count().ToString())) .QuickCheckThrowOnFailure(); } [TestMethod, ExpectedException(typeof(Exception))] public void InsertCombined() { Prop.ForAll<int, int[]>((x, xs) => xs.Insert(x).IsOrdered() .When(xs.IsOrdered()) .Classify(new[] { x }.Concat(xs).IsOrdered(), "at-head") .Classify(xs.Concat(new int[] { x }).IsOrdered(), "at-tail") .Collect("length " + xs.Count().ToString())) .QuickCheckThrowOnFailure(); } [TestMethod, ExpectedException(typeof(Exception))] public void ComplexProp() { Prop.ForAll<int, int>((m, n) => { var result = m + n; return ( result >= m).Label("result > #1") .And( result >= n).Label("result > #2") .And( result < m + n).Label("result not sum"); }).QuickCheckThrowOnFailure(); } [TestMethod, ExpectedException(typeof(Exception))] public void Label() { Prop.ForAll<int>(x => false.Label("Always false") .And(Math.Abs(x) - x == 0)) .QuickCheckThrowOnFailure(); } } }
34.413462
84
0.481419
[ "BSD-3-Clause" ]
Andrea/FsCheck
examples/FsCheck.MsTest.Examples/SampleTests.cs
3,581
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerDeadState : PlayerState { public PlayerDeadState(Player player, PlayerStateMachine stateMachine, PlayerData playerData, string animBoolName) : base(player, stateMachine, playerData, animBoolName) { } }
28.454545
173
0.795527
[ "MIT" ]
SchoolHours/paint-jam-2021
Assets/Scripts/Player/States/SubStates/PlayerDeadState.cs
313
C#
๏ปฟusing System; using System.Collections.Generic; using System.Text; namespace Beer.DaAPI.Core.Notifications { public interface INotificationTriggerSource { IEnumerable<NotifcationTrigger> GetTriggers(); void ClearTriggers(); } }
20
55
0.723077
[ "MIT" ]
just-the-benno/Beer
src/DaAPI/Service/Beer.DaAPI.Service.Core/Notifications/INotificationTriggerSource.cs
262
C#
using System.Collections.Generic; using GraphQL.Types; using GreenHouse.GraphQL.schemas.models; namespace GreenHouse.GraphQL.queries { public class RootQuery : ObjectGraphType { public RootQuery(IEnumerable<ISchemaGroup> queries) { Name = "Query"; foreach (var query in queries) query.SetGroup(this); } } }
24.466667
64
0.66485
[ "MIT" ]
GagiuFilip1/GreenHouse.WebApi
GreenHouse.WebApi/GraphQL/queries/RootQuery.cs
367
C#
๏ปฟ#region MIT // // Gorgon. // Copyright (C) 2018 Michael Winsor // // 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 // 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. // // Created: August 11, 2018 7:58:40 PM // #endregion using System; using Newtonsoft.Json; using DX = SharpDX; namespace Gorgon.IO { /// <summary> /// A converter used to convert a size to and from a string. /// </summary> internal class JsonSize2FConverter : JsonConverter { /// <summary>Writes the JSON representation of the object.</summary> /// <param name="writer">The <see cref="T:Newtonsoft.Json.JsonWriter" /> to write to.</param> /// <param name="value">The value.</param> /// <param name="serializer">The calling serializer.</param> public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { var v2 = (DX.Size2F)value; writer.WriteStartObject(); writer.WritePropertyName("w"); writer.WriteValue(v2.Width); writer.WritePropertyName("h"); writer.WriteValue(v2.Height); writer.WriteEndObject(); } /// <summary>Reads the JSON representation of the object.</summary> /// <param name="reader">The <see cref="T:Newtonsoft.Json.JsonReader" /> to read from.</param> /// <param name="objectType">Type of the object.</param> /// <param name="existingValue">The existing value of object being read.</param> /// <param name="serializer">The calling serializer.</param> /// <returns>The object value.</returns> public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if ((reader.TokenType != JsonToken.StartObject) || (!reader.Read())) { return DX.Size2F.Zero; } float w = (float)(reader.ReadAsDouble() ?? 0); if (!reader.Read()) { return new DX.Size2F(w, 0); } float h = (float)(reader.ReadAsDouble() ?? 0); reader.Read(); return new DX.Size2F(w, h); } /// <summary> /// Determines whether this instance can convert the specified object type. /// </summary> /// <param name="objectType">Type of the object.</param> /// <returns> /// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>. /// </returns> public override bool CanConvert(Type objectType) => (objectType == typeof(DX.Size2F)); } }
39.788889
124
0.631388
[ "MIT" ]
Tape-Worm/Gorgon
Gorgon/Gorgon.Renderers/IO.Gorgon2D/Codecs/_Internal/JsonSize2FConverter.cs
3,583
C#
๏ปฟ/* * Created by SharpDevelop. * User: Administrator * Date: 2006-12-16 * Time: 3:11 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; namespace NChardet { /// <summary> /// Description of EUCJPStatistics. /// </summary> public class EUCJPStatistics : EUCStatistics { static float[] _mFirstByteFreq ; static float _mFirstByteStdDev; static float _mFirstByteMean; static float _mFirstByteWeight; static float[] _mSecondByteFreq; static float _mSecondByteStdDev; static float _mSecondByteMean; static float _mSecondByteWeight; public override float[] mFirstByteFreq() { return _mFirstByteFreq; } public override float mFirstByteStdDev() { return _mFirstByteStdDev; } public override float mFirstByteMean() { return _mFirstByteMean; } public override float mFirstByteWeight() { return _mFirstByteWeight; } public override float[] mSecondByteFreq() { return _mSecondByteFreq; } public override float mSecondByteStdDev() { return _mSecondByteStdDev; } public override float mSecondByteMean() { return _mSecondByteMean; } public override float mSecondByteWeight() { return _mSecondByteWeight; } public EUCJPStatistics() { _mFirstByteFreq = new float[] { 0.364808f, // FreqH[a1] 0.000000f, // FreqH[a2] 0.000000f, // FreqH[a3] 0.145325f, // FreqH[a4] 0.304891f, // FreqH[a5] 0.000000f, // FreqH[a6] 0.000000f, // FreqH[a7] 0.000000f, // FreqH[a8] 0.000000f, // FreqH[a9] 0.000000f, // FreqH[aa] 0.000000f, // FreqH[ab] 0.000000f, // FreqH[ac] 0.000000f, // FreqH[ad] 0.000000f, // FreqH[ae] 0.000000f, // FreqH[af] 0.001835f, // FreqH[b0] 0.010771f, // FreqH[b1] 0.006462f, // FreqH[b2] 0.001157f, // FreqH[b3] 0.002114f, // FreqH[b4] 0.003231f, // FreqH[b5] 0.001356f, // FreqH[b6] 0.007420f, // FreqH[b7] 0.004189f, // FreqH[b8] 0.003231f, // FreqH[b9] 0.003032f, // FreqH[ba] 0.033190f, // FreqH[bb] 0.006303f, // FreqH[bc] 0.006064f, // FreqH[bd] 0.009973f, // FreqH[be] 0.002354f, // FreqH[bf] 0.003670f, // FreqH[c0] 0.009135f, // FreqH[c1] 0.001675f, // FreqH[c2] 0.002792f, // FreqH[c3] 0.002194f, // FreqH[c4] 0.014720f, // FreqH[c5] 0.011928f, // FreqH[c6] 0.000878f, // FreqH[c7] 0.013124f, // FreqH[c8] 0.001077f, // FreqH[c9] 0.009295f, // FreqH[ca] 0.003471f, // FreqH[cb] 0.002872f, // FreqH[cc] 0.002433f, // FreqH[cd] 0.000957f, // FreqH[ce] 0.001636f, // FreqH[cf] 0.000000f, // FreqH[d0] 0.000000f, // FreqH[d1] 0.000000f, // FreqH[d2] 0.000000f, // FreqH[d3] 0.000000f, // FreqH[d4] 0.000000f, // FreqH[d5] 0.000000f, // FreqH[d6] 0.000000f, // FreqH[d7] 0.000000f, // FreqH[d8] 0.000000f, // FreqH[d9] 0.000000f, // FreqH[da] 0.000000f, // FreqH[db] 0.000000f, // FreqH[dc] 0.000000f, // FreqH[dd] 0.000080f, // FreqH[de] 0.000279f, // FreqH[df] 0.000000f, // FreqH[e0] 0.000000f, // FreqH[e1] 0.000000f, // FreqH[e2] 0.000000f, // FreqH[e3] 0.000000f, // FreqH[e4] 0.000000f, // FreqH[e5] 0.000000f, // FreqH[e6] 0.000000f, // FreqH[e7] 0.000000f, // FreqH[e8] 0.000000f, // FreqH[e9] 0.000000f, // FreqH[ea] 0.000000f, // FreqH[eb] 0.000000f, // FreqH[ec] 0.000000f, // FreqH[ed] 0.000000f, // FreqH[ee] 0.000000f, // FreqH[ef] 0.000000f, // FreqH[f0] 0.000000f, // FreqH[f1] 0.000000f, // FreqH[f2] 0.000000f, // FreqH[f3] 0.000000f, // FreqH[f4] 0.000000f, // FreqH[f5] 0.000000f, // FreqH[f6] 0.000000f, // FreqH[f7] 0.000000f, // FreqH[f8] 0.000000f, // FreqH[f9] 0.000000f, // FreqH[fa] 0.000000f, // FreqH[fb] 0.000000f, // FreqH[fc] 0.000080f, // FreqH[fd] 0.000000f // FreqH[fe] }; _mFirstByteStdDev = 0.050407f; // Lead Byte StdDev _mFirstByteMean = 0.010638f; // Lead Byte Mean _mFirstByteWeight = 0.640871f; // Lead Byte Weight _mSecondByteFreq = new float[] { 0.002473f, // FreqL[a1] 0.039134f, // FreqL[a2] 0.152745f, // FreqL[a3] 0.009694f, // FreqL[a4] 0.000359f, // FreqL[a5] 0.022180f, // FreqL[a6] 0.000758f, // FreqL[a7] 0.004308f, // FreqL[a8] 0.000160f, // FreqL[a9] 0.002513f, // FreqL[aa] 0.003072f, // FreqL[ab] 0.001316f, // FreqL[ac] 0.003830f, // FreqL[ad] 0.001037f, // FreqL[ae] 0.003590f, // FreqL[af] 0.000957f, // FreqL[b0] 0.000160f, // FreqL[b1] 0.000239f, // FreqL[b2] 0.006462f, // FreqL[b3] 0.001596f, // FreqL[b4] 0.031554f, // FreqL[b5] 0.001316f, // FreqL[b6] 0.002194f, // FreqL[b7] 0.016555f, // FreqL[b8] 0.003271f, // FreqL[b9] 0.000678f, // FreqL[ba] 0.000598f, // FreqL[bb] 0.206438f, // FreqL[bc] 0.000718f, // FreqL[bd] 0.001077f, // FreqL[be] 0.003710f, // FreqL[bf] 0.001356f, // FreqL[c0] 0.001356f, // FreqL[c1] 0.000439f, // FreqL[c2] 0.004388f, // FreqL[c3] 0.005704f, // FreqL[c4] 0.000878f, // FreqL[c5] 0.010172f, // FreqL[c6] 0.007061f, // FreqL[c7] 0.014680f, // FreqL[c8] 0.000638f, // FreqL[c9] 0.025730f, // FreqL[ca] 0.002792f, // FreqL[cb] 0.000718f, // FreqL[cc] 0.001795f, // FreqL[cd] 0.091551f, // FreqL[ce] 0.000758f, // FreqL[cf] 0.003909f, // FreqL[d0] 0.000558f, // FreqL[d1] 0.031195f, // FreqL[d2] 0.007061f, // FreqL[d3] 0.001316f, // FreqL[d4] 0.022579f, // FreqL[d5] 0.006981f, // FreqL[d6] 0.007260f, // FreqL[d7] 0.001117f, // FreqL[d8] 0.000239f, // FreqL[d9] 0.012127f, // FreqL[da] 0.000878f, // FreqL[db] 0.003790f, // FreqL[dc] 0.001077f, // FreqL[dd] 0.000758f, // FreqL[de] 0.002114f, // FreqL[df] 0.002234f, // FreqL[e0] 0.000678f, // FreqL[e1] 0.002992f, // FreqL[e2] 0.003311f, // FreqL[e3] 0.023416f, // FreqL[e4] 0.001237f, // FreqL[e5] 0.002753f, // FreqL[e6] 0.005146f, // FreqL[e7] 0.002194f, // FreqL[e8] 0.007021f, // FreqL[e9] 0.008497f, // FreqL[ea] 0.013763f, // FreqL[eb] 0.011768f, // FreqL[ec] 0.006303f, // FreqL[ed] 0.001915f, // FreqL[ee] 0.000638f, // FreqL[ef] 0.008776f, // FreqL[f0] 0.000918f, // FreqL[f1] 0.003431f, // FreqL[f2] 0.057603f, // FreqL[f3] 0.000439f, // FreqL[f4] 0.000439f, // FreqL[f5] 0.000758f, // FreqL[f6] 0.002872f, // FreqL[f7] 0.001675f, // FreqL[f8] 0.011050f, // FreqL[f9] 0.000000f, // FreqL[fa] 0.000279f, // FreqL[fb] 0.012127f, // FreqL[fc] 0.000718f, // FreqL[fd] 0.007380f // FreqL[fe] }; _mSecondByteStdDev = 0.028247f; // Trail Byte StdDev _mSecondByteMean = 0.010638f; // Trail Byte Mean _mSecondByteWeight = 0.359129f; // Trial Byte Weight } } }
39.588477
82
0.418087
[ "BSD-2-Clause" ]
thinksea/NChardet
EUCJPStatistics.cs
9,622
C#
๏ปฟusing System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using SRPApp.Classes; using GRA.SRP.ControlRooms; using GRA.SRP.Core.Utilities; using GRA.SRP.DAL; using GRA.SRP.Utilities.CoreClasses; namespace GRA.SRP.ControlRoom.Modules.Setup { public partial class SurveyClone : BaseControlRoomPage { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { SetPageRibbon(StandardModuleRibbons.SetupRibbon()); SID.Text = Session["SID"] == null ? "" : Session["SID"].ToString(); if (SID.Text == "") Response.Redirect("SurveyList.aspx"); var s = Survey.FetchObject(int.Parse(SID.Text)); lblSurvey.Text = string.Format("{0} - {1}", s.Name, s.LongName); } MasterPage.RequiredPermission = 5200; MasterPage.IsSecure = true; MasterPage.PageTitle = string.Format("{0}", "Survey/Test Clone"); } protected void btnCancel_Click(object sender, ImageClickEventArgs e) { Response.Redirect("SurveyList.aspx"); } protected void btnClone_Click(object sender, ImageClickEventArgs e) { var so = Survey.FetchObject(int.Parse(SID.Text)); var sn = Survey.FetchObject(int.Parse(SID.Text)); sn.SID = 0; sn.Name = txtNewName.Text; sn.Status = 1; sn.Insert(); var ds1 = SurveyQuestion.GetAll(so.SID); foreach (DataRow r1 in ds1.Tables[0].Rows) { var QID = Convert.ToInt32(r1["QID"]); var q = SurveyQuestion.FetchObject(QID); q.SID = sn.SID; q.QID = 0; q.Insert(); var ds2 = SQChoices.GetAll(QID); foreach (DataRow r2 in ds2.Tables[0].Rows) { var SQCID = Convert.ToInt32(r2["SQCID"]); var c = SQChoices.FetchObject(SQCID); c.SQCID = 0; c.QID = q.QID; c.Insert(); } var ds3 = SQMatrixLines.GetAll(QID); foreach (DataRow r3 in ds3.Tables[0].Rows) { var SQMLID = Convert.ToInt32(r3["SQMLID"]); var l = SQMatrixLines.FetchObject(SQMLID); l.SQMLID = 0; l.QID = q.QID; l.Insert(); } } Session["SID"] = sn.SID; Response.Redirect("SurveyList.aspx"); Response.Redirect("SurveyAddEdit.aspx"); } } }
33.47619
83
0.515292
[ "MIT" ]
iafb/greatreadingadventure
SRP/ControlRoom/Modules/Setup/SurveyClone.aspx.cs
2,814
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Telerik.Data.Core; using Telerik.UI.Xaml.Controls.Grid.Primitives; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; namespace Telerik.UI.Xaml.Controls.Grid.Commands { internal class ColumnHeaderActionCommand : DataGridCommand { private const string SortKey = "Sort"; private const string FilterKey = "Filter"; private const string GroupKey = "Group"; public override bool CanExecute(object parameter) { var context = parameter as ColumnHeaderActionContext; if(context == null) { return false; } var key = context.Key; bool isActionAllowed = false; if(key.Equals(ColumnHeaderActionCommand.FilterKey)) { isActionAllowed = context.ColumnHeader.Column.CanUserFilter && context.ColumnHeader.Owner.UserFilterMode != DataGridUserFilterMode.Disabled; } else if(key.Equals(ColumnHeaderActionCommand.SortKey)) { isActionAllowed = context.ColumnHeader.Column.CanUserSort && context.ColumnHeader.Owner.UserSortMode != DataGridUserSortMode.None; } else if(key.Equals(ColumnHeaderActionCommand.GroupKey)) { isActionAllowed = context.ColumnHeader.Column.CanUserGroup && context.ColumnHeader.Owner.UserGroupMode != DataGridUserGroupMode.Disabled; } return isActionAllowed; } private Dictionary<DataGridColumn, GroupDescriptorBase> appliedGroupDescriptors = new Dictionary<DataGridColumn, GroupDescriptorBase>(); public override void Execute(object parameter) { var context = parameter as ColumnHeaderActionContext; if (context == null) { return; } this.Owner.ContentFlyout.Hide(DataGridFlyoutId.ColumnHeader); if (context.Key.Equals(ColumnHeaderActionCommand.FilterKey)) { this.Owner.ExecuteFilter(context.ColumnHeader); } else if (context.Key.Equals(ColumnHeaderActionCommand.SortKey)) { context.ColumnHeader.Column.ToggleSort(this.Owner.UserSortMode == DataGridUserSortMode.Multiple); } else if (context.Key.Equals(ColumnHeaderActionCommand.GroupKey)) { var column = context.ColumnHeader.Column; if (column.CanGroupBy) { var descriptor = column.GetGroupDescriptor(); this.Owner.GroupDescriptors.Add(descriptor); } else { var typedColumn = column as DataGridTypedColumn; if (typedColumn != null) { var descriptor = this.Owner.GroupDescriptors.OfType<PropertyGroupDescriptor>().Where(d => d.PropertyName == typedColumn.PropertyName).FirstOrDefault(); if (descriptor != null) { this.Owner.GroupDescriptors.Remove(descriptor); } } } } } } }
36.510638
175
0.583333
[ "Apache-2.0" ]
JackWangCUMT/UI-For-UWP
Controls/Grid/Grid.UWP/View/Services/Commands/ColumnHeader/ColumnHeaderActionCommand.cs
3,434
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; namespace BlazorWorker.Core { /// <summary> /// Options for initializing the worker. /// </summary> public class WorkerInitOptions { /// <summary> /// Creates a new instance of WorkerInitOptions /// </summary> public WorkerInitOptions() { DependentAssemblyFilenames = new string[] { }; #if NETSTANDARD21 DeployPrefix = "_framework/_bin"; WasmRoot = "_framework/wasm"; #endif #if NET5 DeployPrefix = "_framework"; WasmRoot = "_framework"; #endif #if DEBUG Debug = true; #endif } /// <summary> /// Specifies the location of binaries /// </summary> public string DeployPrefix { get; } /// <summary> /// Specifieds the location of the wasm binary /// </summary> public string WasmRoot { get; } /// <summary> /// Outputs additional debug information to the console /// </summary> public bool Debug { get; set; } /// <summary> /// Specifies a list of assembly files names (dlls) that should be loaded when initializing the worker. /// </summary> public string[] DependentAssemblyFilenames { get; set; } /// <summary> /// Mono-wasm-annotated endpoint for sending messages to the worker. Experts only. /// </summary> public string MessageEndPoint { get; set; } /// <summary> /// Mono-wasm-annotated endpoint for instanciating the worker. Experts only. /// </summary> public string InitEndPoint { get; set; } /// <summary> /// Unique blazor identifier for handling callbacks. As referenced by JSInvokableAttribute. Experts only. /// </summary> public string CallbackMethod { get; set; } /// <summary> /// If set to true, deducts the name of the assembly containing the service using the service type assembly name + dll extension as file name, and adds it as a dependency. /// </summary> public bool UseConventionalServiceAssembly { get; set; } /// <summary> /// Mono-wasm-annotated endpoint for doing callbacks on self invocations from the worker. Experts only. /// </summary> public string EndInvokeCallBackEndpoint { get; set; } public WorkerInitOptions MergeWith(WorkerInitOptions initOptions) { return new WorkerInitOptions { CallbackMethod = initOptions.CallbackMethod ?? this.CallbackMethod, DependentAssemblyFilenames = this.DependentAssemblyFilenames .Concat(initOptions.DependentAssemblyFilenames) .Distinct() .ToArray(), UseConventionalServiceAssembly = initOptions.UseConventionalServiceAssembly, MessageEndPoint = initOptions.MessageEndPoint ?? this.MessageEndPoint, InitEndPoint = initOptions.InitEndPoint ?? this.InitEndPoint, EndInvokeCallBackEndpoint = initOptions.EndInvokeCallBackEndpoint ?? this.EndInvokeCallBackEndpoint }; } } /// <summary> /// Contains convenience extensions for <see cref="WorkerInitOptions"/> /// </summary> public static class WorkerInitOptionsExtensions { /// <summary> /// Adds the specified assembly filesnames as dependencies /// </summary> /// <param name="source"></param> /// <param name="dependentAssemblyFilenames"></param> /// <returns></returns> public static WorkerInitOptions AddAssemblies(this WorkerInitOptions source, params string[] dependentAssemblyFilenames) { source.DependentAssemblyFilenames = source.DependentAssemblyFilenames.Concat(dependentAssemblyFilenames).ToArray(); return source; } /// <summary> /// Deducts the name of the assembly containing the service using the the service type assembly name with dll extension as file name, and adds it as a dependency. /// </summary> /// <param name="source"></param> /// <returns></returns> public static WorkerInitOptions AddConventionalAssemblyOfService(this WorkerInitOptions source) { source.UseConventionalServiceAssembly = true; return source; } /// <summary> /// Deducts the name of the assembly containing the specified <typeparamref name="T"/> using the assembly name with dll extension as file name, and adds it as a dependency. /// </summary> /// <param name="source"></param> /// <returns></returns> public static WorkerInitOptions AddAssemblyOf<T>(this WorkerInitOptions source) { return source.AddAssemblyOfType(typeof(T)); } /// <summary> /// Deducts the name of the assembly containing the specified <paramref name="type"/> using the assembly name with dll extension as file name, and adds it as a dependency. /// </summary> /// <param name="source"></param> /// <param name="type"></param> /// <returns></returns> public static WorkerInitOptions AddAssemblyOfType(this WorkerInitOptions source, Type type) { source.AddAssemblies($"{type.Assembly.GetName().Name}.dll"); return source; } /// <summary> /// Registers the neccessary dependencies for injecting or instanciating <see cref="System.Net.Http.HttpClient"/> in the background service. /// </summary> /// <param name="source"></param> /// <returns></returns> /// <remarks>When this method has been called, <see cref="System.Net.Http.HttpClient"/> can be used inside the service either by instanciating it or by injection into the constructor.</remarks> public static WorkerInitOptions AddHttpClient(this WorkerInitOptions source) { #if NETSTANDARD21 source.AddAssemblies("System.Net.Http.dll", "System.Net.Http.WebAssemblyHttpHandler.dll"); #endif #if NET5 source.AddAssemblies( "System.Net.Http.dll", "System.Security.Cryptography.X509Certificates.dll", "System.Net.Primitives.dll", "System.Net.Requests.dll", "System.Net.Security.dll", "System.Net.dll", "System.Diagnostics.Tracing.dll"); #endif return source; } } }
38.439306
201
0.61188
[ "MIT" ]
Tewr/BlazorWorker
src/BlazorWorker.WorkerCore/InitOptions.cs
6,652
C#
๏ปฟ#region Copyright notice and license // Copyright 2019 The gRPC Authors // // 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. #endregion namespace Grpc.AspNetCore.FunctionalTests.Infrastructure { internal static class TestConstants { public const string ServerCallHandlerTestName = "SERVER Grpc.AspNetCore.Server.ServerCallHandler"; } }
33.269231
106
0.753757
[ "Apache-2.0" ]
Alibesharat/grpc-dotnet
test/FunctionalTests/Infrastructure/TestConstants.cs
867
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration { using static Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Extensions; /// <summary> /// Low-level API implementation for the KubernetesConfiguration service. /// </summary> public partial class KubernetesConfiguration { /// <summary> /// List all the available operations the KubernetesConfiguration resource provider supports. /// </summary> /// <param name="onOk">a delegate that is called when the remote service returns 200 (OK).</param> /// <param name="onDefault">a delegate that is called when the remote service returns default (any response code not handled /// elsewhere).</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <param name="sender">an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync pipeline to use to make the request.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> public async global::System.Threading.Tasks.Task OperationsList(global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IResourceProviderOperationList>, global::System.Threading.Tasks.Task> onOk, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IErrorResponse>, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) { var apiVersion = @"2021-03-01"; // Constant Parameters using( NoSynchronizationContext ) { // construct URL var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( "https://management.azure.com/providers/Microsoft.KubernetesConfiguration/operations" + "?" + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // generate request object var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get, _url); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // make the call await this.OperationsList_Call(request,onOk,onDefault,eventListener,sender); } } /// <summary> /// List all the available operations the KubernetesConfiguration resource provider supports. /// </summary> /// <param name="viaIdentity"></param> /// <param name="onOk">a delegate that is called when the remote service returns 200 (OK).</param> /// <param name="onDefault">a delegate that is called when the remote service returns default (any response code not handled /// elsewhere).</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <param name="sender">an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync pipeline to use to make the request.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> public async global::System.Threading.Tasks.Task OperationsListViaIdentity(global::System.String viaIdentity, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IResourceProviderOperationList>, global::System.Threading.Tasks.Task> onOk, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IErrorResponse>, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) { var apiVersion = @"2021-03-01"; // Constant Parameters using( NoSynchronizationContext ) { // verify that Identity format is an exact match for uri var _match = new global::System.Text.RegularExpressions.Regex("^/providers/Microsoft.KubernetesConfiguration/operations$").Match(viaIdentity); if (!_match.Success) { throw new global::System.Exception("Invalid identity for URI '/providers/Microsoft.KubernetesConfiguration/operations'"); } // replace URI parameters with values from identity // construct URL var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( "https://management.azure.com/providers/Microsoft.KubernetesConfiguration/operations" + "?" + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // generate request object var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get, _url); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // make the call await this.OperationsList_Call(request,onOk,onDefault,eventListener,sender); } } /// <summary>Actual wire call for <see cref="OperationsList" /> method.</summary> /// <param name="request">the prepared HttpRequestMessage to send.</param> /// <param name="onOk">a delegate that is called when the remote service returns 200 (OK).</param> /// <param name="onDefault">a delegate that is called when the remote service returns default (any response code not handled /// elsewhere).</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <param name="sender">an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync pipeline to use to make the request.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> internal async global::System.Threading.Tasks.Task OperationsList_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IResourceProviderOperationList>, global::System.Threading.Tasks.Task> onOk, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IErrorResponse>, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) { using( NoSynchronizationContext ) { global::System.Net.Http.HttpResponseMessage _response = null; try { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } _response = await sender.SendAsync(request, eventListener); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } var _contentType = _response.Content.Headers.ContentType?.MediaType; switch ( _response.StatusCode ) { case global::System.Net.HttpStatusCode.OK: { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ResourceProviderOperationList.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); break; } default: { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); break; } } } finally { // finally statements await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Finally, request, _response); _response?.Dispose(); request?.Dispose(); } } } /// <summary> /// Validation method for <see cref="OperationsList" /> method. Call this like the actual call, but you will get validation /// events back. /// </summary> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> internal async global::System.Threading.Tasks.Task OperationsList_Validate(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener) { using( NoSynchronizationContext ) { } } /// <summary>Create a new Kubernetes Source Control Configuration.</summary> /// <param name="subscriptionId">The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)</param> /// <param name="resourceGroupName">The name of the resource group.</param> /// <param name="clusterRp">The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes /// (for OnPrem K8S clusters).</param> /// <param name="clusterResourceName">The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or /// connectedClusters (for OnPrem K8S clusters).</param> /// <param name="clusterName">The name of the kubernetes cluster.</param> /// <param name="sourceControlConfigurationName">Name of the Source Control Configuration.</param> /// <param name="body">Properties necessary to Create KubernetesConfiguration.</param> /// <param name="onOk">a delegate that is called when the remote service returns 200 (OK).</param> /// <param name="onCreated">a delegate that is called when the remote service returns 201 (Created).</param> /// <param name="onDefault">a delegate that is called when the remote service returns default (any response code not handled /// elsewhere).</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <param name="sender">an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync pipeline to use to make the request.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> public async global::System.Threading.Tasks.Task SourceControlConfigurationsCreateOrUpdate(string subscriptionId, string resourceGroupName, string clusterRp, string clusterResourceName, string clusterName, string sourceControlConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ISourceControlConfiguration body, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ISourceControlConfiguration>, global::System.Threading.Tasks.Task> onOk, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ISourceControlConfiguration>, global::System.Threading.Tasks.Task> onCreated, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IErrorResponse>, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) { var apiVersion = @"2021-03-01"; // Constant Parameters using( NoSynchronizationContext ) { // construct URL var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( "https://management.azure.com/subscriptions/" + global::System.Uri.EscapeDataString(subscriptionId) + "/resourceGroups/" + global::System.Uri.EscapeDataString(resourceGroupName) + "/providers/" + global::System.Uri.EscapeDataString(clusterRp) + "/" + global::System.Uri.EscapeDataString(clusterResourceName) + "/" + global::System.Uri.EscapeDataString(clusterName) + "/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/" + global::System.Uri.EscapeDataString(sourceControlConfigurationName) + "?" + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // generate request object var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Put, _url); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // set body content request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // make the call await this.SourceControlConfigurationsCreateOrUpdate_Call(request,onOk,onCreated,onDefault,eventListener,sender); } } /// <summary>Create a new Kubernetes Source Control Configuration.</summary> /// <param name="viaIdentity"></param> /// <param name="body">Properties necessary to Create KubernetesConfiguration.</param> /// <param name="onOk">a delegate that is called when the remote service returns 200 (OK).</param> /// <param name="onCreated">a delegate that is called when the remote service returns 201 (Created).</param> /// <param name="onDefault">a delegate that is called when the remote service returns default (any response code not handled /// elsewhere).</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <param name="sender">an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync pipeline to use to make the request.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> public async global::System.Threading.Tasks.Task SourceControlConfigurationsCreateOrUpdateViaIdentity(global::System.String viaIdentity, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ISourceControlConfiguration body, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ISourceControlConfiguration>, global::System.Threading.Tasks.Task> onOk, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ISourceControlConfiguration>, global::System.Threading.Tasks.Task> onCreated, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IErrorResponse>, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) { var apiVersion = @"2021-03-01"; // Constant Parameters using( NoSynchronizationContext ) { // verify that Identity format is an exact match for uri var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?<subscriptionId>[^/]+)/resourceGroups/(?<resourceGroupName>[^/]+)/providers/(?<clusterRp>[^/]+)/(?<clusterResourceName>[^/]+)/(?<clusterName>[^/]+)/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/(?<sourceControlConfigurationName>[^/]+)$").Match(viaIdentity); if (!_match.Success) { throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'"); } // replace URI parameters with values from identity var subscriptionId = _match.Groups["subscriptionId"].Value; var resourceGroupName = _match.Groups["resourceGroupName"].Value; var clusterRp = _match.Groups["clusterRp"].Value; var clusterResourceName = _match.Groups["clusterResourceName"].Value; var clusterName = _match.Groups["clusterName"].Value; var sourceControlConfigurationName = _match.Groups["sourceControlConfigurationName"].Value; // construct URL var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( "https://management.azure.com/subscriptions/" + subscriptionId + "/resourceGroups/" + resourceGroupName + "/providers/" + clusterRp + "/" + clusterResourceName + "/" + clusterName + "/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/" + sourceControlConfigurationName + "?" + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // generate request object var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Put, _url); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // set body content request.Content = new global::System.Net.Http.StringContent(null != body ? body.ToJson(null).ToString() : @"{}", global::System.Text.Encoding.UTF8); request.Content.Headers.ContentType = global::System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json"); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BodyContentSet, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // make the call await this.SourceControlConfigurationsCreateOrUpdate_Call(request,onOk,onCreated,onDefault,eventListener,sender); } } /// <summary> /// Actual wire call for <see cref="SourceControlConfigurationsCreateOrUpdate" /> method. /// </summary> /// <param name="request">the prepared HttpRequestMessage to send.</param> /// <param name="onOk">a delegate that is called when the remote service returns 200 (OK).</param> /// <param name="onCreated">a delegate that is called when the remote service returns 201 (Created).</param> /// <param name="onDefault">a delegate that is called when the remote service returns default (any response code not handled /// elsewhere).</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <param name="sender">an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync pipeline to use to make the request.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> internal async global::System.Threading.Tasks.Task SourceControlConfigurationsCreateOrUpdate_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ISourceControlConfiguration>, global::System.Threading.Tasks.Task> onOk, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ISourceControlConfiguration>, global::System.Threading.Tasks.Task> onCreated, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IErrorResponse>, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) { using( NoSynchronizationContext ) { global::System.Net.Http.HttpResponseMessage _response = null; try { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } _response = await sender.SendAsync(request, eventListener); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } var _contentType = _response.Content.Headers.ContentType?.MediaType; switch ( _response.StatusCode ) { case global::System.Net.HttpStatusCode.OK: { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.SourceControlConfiguration.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); break; } case global::System.Net.HttpStatusCode.Created: { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } await onCreated(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.SourceControlConfiguration.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); break; } default: { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); break; } } } finally { // finally statements await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Finally, request, _response); _response?.Dispose(); request?.Dispose(); } } } /// <summary> /// Validation method for <see cref="SourceControlConfigurationsCreateOrUpdate" /> method. Call this like the actual call, /// but you will get validation events back. /// </summary> /// <param name="subscriptionId">The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)</param> /// <param name="resourceGroupName">The name of the resource group.</param> /// <param name="clusterRp">The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes /// (for OnPrem K8S clusters).</param> /// <param name="clusterResourceName">The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or /// connectedClusters (for OnPrem K8S clusters).</param> /// <param name="clusterName">The name of the kubernetes cluster.</param> /// <param name="sourceControlConfigurationName">Name of the Source Control Configuration.</param> /// <param name="body">Properties necessary to Create KubernetesConfiguration.</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> internal async global::System.Threading.Tasks.Task SourceControlConfigurationsCreateOrUpdate_Validate(string subscriptionId, string resourceGroupName, string clusterRp, string clusterResourceName, string clusterName, string sourceControlConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ISourceControlConfiguration body, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener) { using( NoSynchronizationContext ) { await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); await eventListener.AssertNotNull(nameof(clusterRp),clusterRp); await eventListener.AssertEnum(nameof(clusterRp),clusterRp,@"Microsoft.ContainerService", @"Microsoft.Kubernetes"); await eventListener.AssertNotNull(nameof(clusterResourceName),clusterResourceName); await eventListener.AssertEnum(nameof(clusterResourceName),clusterResourceName,@"managedClusters", @"connectedClusters"); await eventListener.AssertNotNull(nameof(clusterName),clusterName); await eventListener.AssertNotNull(nameof(sourceControlConfigurationName),sourceControlConfigurationName); await eventListener.AssertNotNull(nameof(body), body); await eventListener.AssertObjectIsValid(nameof(body), body); } } /// <summary> /// This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source /// repo. /// </summary> /// <param name="subscriptionId">The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)</param> /// <param name="resourceGroupName">The name of the resource group.</param> /// <param name="clusterRp">The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes /// (for OnPrem K8S clusters).</param> /// <param name="clusterResourceName">The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or /// connectedClusters (for OnPrem K8S clusters).</param> /// <param name="clusterName">The name of the kubernetes cluster.</param> /// <param name="sourceControlConfigurationName">Name of the Source Control Configuration.</param> /// <param name="onOk">a delegate that is called when the remote service returns 200 (OK).</param> /// <param name="onNoContent">a delegate that is called when the remote service returns 204 (NoContent).</param> /// <param name="onDefault">a delegate that is called when the remote service returns default (any response code not handled /// elsewhere).</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <param name="sender">an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync pipeline to use to make the request.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> public async global::System.Threading.Tasks.Task SourceControlConfigurationsDelete(string subscriptionId, string resourceGroupName, string clusterRp, string clusterResourceName, string clusterName, string sourceControlConfigurationName, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task> onOk, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task> onNoContent, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IErrorResponse>, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) { var apiVersion = @"2021-03-01"; // Constant Parameters using( NoSynchronizationContext ) { // construct URL var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( "https://management.azure.com/subscriptions/" + global::System.Uri.EscapeDataString(subscriptionId) + "/resourceGroups/" + global::System.Uri.EscapeDataString(resourceGroupName) + "/providers/" + global::System.Uri.EscapeDataString(clusterRp) + "/" + global::System.Uri.EscapeDataString(clusterResourceName) + "/" + global::System.Uri.EscapeDataString(clusterName) + "/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/" + global::System.Uri.EscapeDataString(sourceControlConfigurationName) + "?" + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // generate request object var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Delete, _url); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // make the call await this.SourceControlConfigurationsDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); } } /// <summary> /// This will delete the YAML file used to set up the Source control configuration, thus stopping future sync from the source /// repo. /// </summary> /// <param name="viaIdentity"></param> /// <param name="onOk">a delegate that is called when the remote service returns 200 (OK).</param> /// <param name="onNoContent">a delegate that is called when the remote service returns 204 (NoContent).</param> /// <param name="onDefault">a delegate that is called when the remote service returns default (any response code not handled /// elsewhere).</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <param name="sender">an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync pipeline to use to make the request.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> public async global::System.Threading.Tasks.Task SourceControlConfigurationsDeleteViaIdentity(global::System.String viaIdentity, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task> onOk, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task> onNoContent, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IErrorResponse>, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) { var apiVersion = @"2021-03-01"; // Constant Parameters using( NoSynchronizationContext ) { // verify that Identity format is an exact match for uri var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?<subscriptionId>[^/]+)/resourceGroups/(?<resourceGroupName>[^/]+)/providers/(?<clusterRp>[^/]+)/(?<clusterResourceName>[^/]+)/(?<clusterName>[^/]+)/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/(?<sourceControlConfigurationName>[^/]+)$").Match(viaIdentity); if (!_match.Success) { throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'"); } // replace URI parameters with values from identity var subscriptionId = _match.Groups["subscriptionId"].Value; var resourceGroupName = _match.Groups["resourceGroupName"].Value; var clusterRp = _match.Groups["clusterRp"].Value; var clusterResourceName = _match.Groups["clusterResourceName"].Value; var clusterName = _match.Groups["clusterName"].Value; var sourceControlConfigurationName = _match.Groups["sourceControlConfigurationName"].Value; // construct URL var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( "https://management.azure.com/subscriptions/" + subscriptionId + "/resourceGroups/" + resourceGroupName + "/providers/" + clusterRp + "/" + clusterResourceName + "/" + clusterName + "/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/" + sourceControlConfigurationName + "?" + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // generate request object var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Delete, _url); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // make the call await this.SourceControlConfigurationsDelete_Call(request,onOk,onNoContent,onDefault,eventListener,sender); } } /// <summary>Actual wire call for <see cref="SourceControlConfigurationsDelete" /> method.</summary> /// <param name="request">the prepared HttpRequestMessage to send.</param> /// <param name="onOk">a delegate that is called when the remote service returns 200 (OK).</param> /// <param name="onNoContent">a delegate that is called when the remote service returns 204 (NoContent).</param> /// <param name="onDefault">a delegate that is called when the remote service returns default (any response code not handled /// elsewhere).</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <param name="sender">an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync pipeline to use to make the request.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> internal async global::System.Threading.Tasks.Task SourceControlConfigurationsDelete_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task> onOk, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task> onNoContent, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IErrorResponse>, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) { using( NoSynchronizationContext ) { global::System.Net.Http.HttpResponseMessage _response = null; try { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } _response = await sender.SendAsync(request, eventListener); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } // this operation supports x-ms-long-running-operation var _originalUri = request.RequestUri.AbsoluteUri; // declared final-state-via: default var _finalUri = _response.GetFirstHeader(@"Location"); var asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); var location = _response.GetFirstHeader(@"Location"); while (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) { // get the delay before polling. (default to 30 seconds if not present) int delay = (int)(_response.Headers.RetryAfter?.Delta?.TotalSeconds ?? 30); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.DelayBeforePolling, $"Delaying {delay} seconds before polling.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } // start the delay timer (we'll await later...) var waiting = global::System.Threading.Tasks.Task.Delay(delay * 1000, eventListener.Token ); // while we wait, let's grab the headers and get ready to poll. if (!System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Azure-AsyncOperation"))) { asyncOperation = _response.GetFirstHeader(@"Azure-AsyncOperation"); } if (!global::System.String.IsNullOrEmpty(_response.GetFirstHeader(@"Location"))) { location = _response.GetFirstHeader(@"Location"); } var _uri = global::System.String.IsNullOrEmpty(asyncOperation) ? global::System.String.IsNullOrEmpty(location) ? _originalUri : location : asyncOperation; request = request.CloneAndDispose(new global::System.Uri(_uri), Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get); // and let's look at the current response body and see if we have some information we can give back to the listener var content = await _response.Content.ReadAsStringAsync(); await waiting; // check for cancellation if( eventListener.Token.IsCancellationRequested ) { return; } await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Polling, $"Polling {_uri}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } // drop the old response _response?.Dispose(); // make the polling call _response = await sender.SendAsync(request, eventListener); // if we got back an OK, take a peek inside and see if it's done if( _response.StatusCode == global::System.Net.HttpStatusCode.OK) { try { if( Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(await _response.Content.ReadAsStringAsync()) is Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonObject json) { var state = json.Property("properties")?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString>("provisioningState") ?? json.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonString>("status"); if( state is null ) { // the body doesn't contain any information that has the state of the LRO // we're going to just get out, and let the consumer have the result break; } await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Polling, $"Polled {_uri} provisioning state {state}.", _response); if( eventListener.Token.IsCancellationRequested ) { return; } switch( state?.ToString()?.ToLower() ) { case "succeeded": case "failed": case "canceled": // we're done polling. break; default: // need to keep polling! _response.StatusCode = global::System.Net.HttpStatusCode.Created; continue; } } } catch { // if we run into a problem peeking into the result, // we really don't want to do anything special. } } // check for terminal status code if (_response.StatusCode == global::System.Net.HttpStatusCode.Created || _response.StatusCode == global::System.Net.HttpStatusCode.Accepted ) { continue; } // we are done polling, do a request on final target? if (!string.IsNullOrWhiteSpace(_finalUri)) { // create a new request with the final uri request = request.CloneAndDispose(new global::System.Uri(_finalUri), Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get); // drop the old response _response?.Dispose(); // make the final call _response = await sender.SendAsync(request, eventListener); break; } } var _contentType = _response.Content.Headers.ContentType?.MediaType; switch ( _response.StatusCode ) { case global::System.Net.HttpStatusCode.OK: { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } await onOk(_response); break; } case global::System.Net.HttpStatusCode.NoContent: { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } await onNoContent(_response); break; } default: { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); break; } } } finally { // finally statements await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Finally, request, _response); _response?.Dispose(); request?.Dispose(); } } } /// <summary> /// Validation method for <see cref="SourceControlConfigurationsDelete" /> method. Call this like the actual call, but you /// will get validation events back. /// </summary> /// <param name="subscriptionId">The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)</param> /// <param name="resourceGroupName">The name of the resource group.</param> /// <param name="clusterRp">The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes /// (for OnPrem K8S clusters).</param> /// <param name="clusterResourceName">The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or /// connectedClusters (for OnPrem K8S clusters).</param> /// <param name="clusterName">The name of the kubernetes cluster.</param> /// <param name="sourceControlConfigurationName">Name of the Source Control Configuration.</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> internal async global::System.Threading.Tasks.Task SourceControlConfigurationsDelete_Validate(string subscriptionId, string resourceGroupName, string clusterRp, string clusterResourceName, string clusterName, string sourceControlConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener) { using( NoSynchronizationContext ) { await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); await eventListener.AssertNotNull(nameof(clusterRp),clusterRp); await eventListener.AssertEnum(nameof(clusterRp),clusterRp,@"Microsoft.ContainerService", @"Microsoft.Kubernetes"); await eventListener.AssertNotNull(nameof(clusterResourceName),clusterResourceName); await eventListener.AssertEnum(nameof(clusterResourceName),clusterResourceName,@"managedClusters", @"connectedClusters"); await eventListener.AssertNotNull(nameof(clusterName),clusterName); await eventListener.AssertNotNull(nameof(sourceControlConfigurationName),sourceControlConfigurationName); } } /// <summary>Gets details of the Source Control Configuration.</summary> /// <param name="subscriptionId">The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)</param> /// <param name="resourceGroupName">The name of the resource group.</param> /// <param name="clusterRp">The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes /// (for OnPrem K8S clusters).</param> /// <param name="clusterResourceName">The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or /// connectedClusters (for OnPrem K8S clusters).</param> /// <param name="clusterName">The name of the kubernetes cluster.</param> /// <param name="sourceControlConfigurationName">Name of the Source Control Configuration.</param> /// <param name="onOk">a delegate that is called when the remote service returns 200 (OK).</param> /// <param name="onDefault">a delegate that is called when the remote service returns default (any response code not handled /// elsewhere).</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <param name="sender">an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync pipeline to use to make the request.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> public async global::System.Threading.Tasks.Task SourceControlConfigurationsGet(string subscriptionId, string resourceGroupName, string clusterRp, string clusterResourceName, string clusterName, string sourceControlConfigurationName, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ISourceControlConfiguration>, global::System.Threading.Tasks.Task> onOk, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IErrorResponse>, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) { var apiVersion = @"2021-03-01"; // Constant Parameters using( NoSynchronizationContext ) { // construct URL var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( "https://management.azure.com/subscriptions/" + global::System.Uri.EscapeDataString(subscriptionId) + "/resourceGroups/" + global::System.Uri.EscapeDataString(resourceGroupName) + "/providers/" + global::System.Uri.EscapeDataString(clusterRp) + "/" + global::System.Uri.EscapeDataString(clusterResourceName) + "/" + global::System.Uri.EscapeDataString(clusterName) + "/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/" + global::System.Uri.EscapeDataString(sourceControlConfigurationName) + "?" + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // generate request object var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get, _url); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // make the call await this.SourceControlConfigurationsGet_Call(request,onOk,onDefault,eventListener,sender); } } /// <summary>Gets details of the Source Control Configuration.</summary> /// <param name="viaIdentity"></param> /// <param name="onOk">a delegate that is called when the remote service returns 200 (OK).</param> /// <param name="onDefault">a delegate that is called when the remote service returns default (any response code not handled /// elsewhere).</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <param name="sender">an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync pipeline to use to make the request.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> public async global::System.Threading.Tasks.Task SourceControlConfigurationsGetViaIdentity(global::System.String viaIdentity, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ISourceControlConfiguration>, global::System.Threading.Tasks.Task> onOk, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IErrorResponse>, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) { var apiVersion = @"2021-03-01"; // Constant Parameters using( NoSynchronizationContext ) { // verify that Identity format is an exact match for uri var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?<subscriptionId>[^/]+)/resourceGroups/(?<resourceGroupName>[^/]+)/providers/(?<clusterRp>[^/]+)/(?<clusterResourceName>[^/]+)/(?<clusterName>[^/]+)/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/(?<sourceControlConfigurationName>[^/]+)$").Match(viaIdentity); if (!_match.Success) { throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/{sourceControlConfigurationName}'"); } // replace URI parameters with values from identity var subscriptionId = _match.Groups["subscriptionId"].Value; var resourceGroupName = _match.Groups["resourceGroupName"].Value; var clusterRp = _match.Groups["clusterRp"].Value; var clusterResourceName = _match.Groups["clusterResourceName"].Value; var clusterName = _match.Groups["clusterName"].Value; var sourceControlConfigurationName = _match.Groups["sourceControlConfigurationName"].Value; // construct URL var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( "https://management.azure.com/subscriptions/" + subscriptionId + "/resourceGroups/" + resourceGroupName + "/providers/" + clusterRp + "/" + clusterResourceName + "/" + clusterName + "/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations/" + sourceControlConfigurationName + "?" + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // generate request object var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get, _url); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // make the call await this.SourceControlConfigurationsGet_Call(request,onOk,onDefault,eventListener,sender); } } /// <summary>Actual wire call for <see cref="SourceControlConfigurationsGet" /> method.</summary> /// <param name="request">the prepared HttpRequestMessage to send.</param> /// <param name="onOk">a delegate that is called when the remote service returns 200 (OK).</param> /// <param name="onDefault">a delegate that is called when the remote service returns default (any response code not handled /// elsewhere).</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <param name="sender">an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync pipeline to use to make the request.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> internal async global::System.Threading.Tasks.Task SourceControlConfigurationsGet_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ISourceControlConfiguration>, global::System.Threading.Tasks.Task> onOk, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IErrorResponse>, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) { using( NoSynchronizationContext ) { global::System.Net.Http.HttpResponseMessage _response = null; try { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } _response = await sender.SendAsync(request, eventListener); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } var _contentType = _response.Content.Headers.ContentType?.MediaType; switch ( _response.StatusCode ) { case global::System.Net.HttpStatusCode.OK: { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.SourceControlConfiguration.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); break; } default: { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); break; } } } finally { // finally statements await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Finally, request, _response); _response?.Dispose(); request?.Dispose(); } } } /// <summary> /// Validation method for <see cref="SourceControlConfigurationsGet" /> method. Call this like the actual call, but you will /// get validation events back. /// </summary> /// <param name="subscriptionId">The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)</param> /// <param name="resourceGroupName">The name of the resource group.</param> /// <param name="clusterRp">The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes /// (for OnPrem K8S clusters).</param> /// <param name="clusterResourceName">The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or /// connectedClusters (for OnPrem K8S clusters).</param> /// <param name="clusterName">The name of the kubernetes cluster.</param> /// <param name="sourceControlConfigurationName">Name of the Source Control Configuration.</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> internal async global::System.Threading.Tasks.Task SourceControlConfigurationsGet_Validate(string subscriptionId, string resourceGroupName, string clusterRp, string clusterResourceName, string clusterName, string sourceControlConfigurationName, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener) { using( NoSynchronizationContext ) { await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); await eventListener.AssertNotNull(nameof(clusterRp),clusterRp); await eventListener.AssertEnum(nameof(clusterRp),clusterRp,@"Microsoft.ContainerService", @"Microsoft.Kubernetes"); await eventListener.AssertNotNull(nameof(clusterResourceName),clusterResourceName); await eventListener.AssertEnum(nameof(clusterResourceName),clusterResourceName,@"managedClusters", @"connectedClusters"); await eventListener.AssertNotNull(nameof(clusterName),clusterName); await eventListener.AssertNotNull(nameof(sourceControlConfigurationName),sourceControlConfigurationName); } } /// <summary>List all Source Control Configurations.</summary> /// <param name="subscriptionId">The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)</param> /// <param name="resourceGroupName">The name of the resource group.</param> /// <param name="clusterRp">The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes /// (for OnPrem K8S clusters).</param> /// <param name="clusterResourceName">The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or /// connectedClusters (for OnPrem K8S clusters).</param> /// <param name="clusterName">The name of the kubernetes cluster.</param> /// <param name="onOk">a delegate that is called when the remote service returns 200 (OK).</param> /// <param name="onDefault">a delegate that is called when the remote service returns default (any response code not handled /// elsewhere).</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <param name="sender">an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync pipeline to use to make the request.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> public async global::System.Threading.Tasks.Task SourceControlConfigurationsList(string subscriptionId, string resourceGroupName, string clusterRp, string clusterResourceName, string clusterName, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ISourceControlConfigurationList>, global::System.Threading.Tasks.Task> onOk, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IErrorResponse>, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) { var apiVersion = @"2021-03-01"; // Constant Parameters using( NoSynchronizationContext ) { // construct URL var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( "https://management.azure.com/subscriptions/" + global::System.Uri.EscapeDataString(subscriptionId) + "/resourceGroups/" + global::System.Uri.EscapeDataString(resourceGroupName) + "/providers/" + global::System.Uri.EscapeDataString(clusterRp) + "/" + global::System.Uri.EscapeDataString(clusterResourceName) + "/" + global::System.Uri.EscapeDataString(clusterName) + "/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations" + "?" + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // generate request object var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get, _url); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // make the call await this.SourceControlConfigurationsList_Call(request,onOk,onDefault,eventListener,sender); } } /// <summary>List all Source Control Configurations.</summary> /// <param name="viaIdentity"></param> /// <param name="onOk">a delegate that is called when the remote service returns 200 (OK).</param> /// <param name="onDefault">a delegate that is called when the remote service returns default (any response code not handled /// elsewhere).</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <param name="sender">an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync pipeline to use to make the request.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> public async global::System.Threading.Tasks.Task SourceControlConfigurationsListViaIdentity(global::System.String viaIdentity, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ISourceControlConfigurationList>, global::System.Threading.Tasks.Task> onOk, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IErrorResponse>, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) { var apiVersion = @"2021-03-01"; // Constant Parameters using( NoSynchronizationContext ) { // verify that Identity format is an exact match for uri var _match = new global::System.Text.RegularExpressions.Regex("^/subscriptions/(?<subscriptionId>[^/]+)/resourceGroups/(?<resourceGroupName>[^/]+)/providers/(?<clusterRp>[^/]+)/(?<clusterResourceName>[^/]+)/(?<clusterName>[^/]+)/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations$").Match(viaIdentity); if (!_match.Success) { throw new global::System.Exception("Invalid identity for URI '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{clusterRp}/{clusterResourceName}/{clusterName}/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations'"); } // replace URI parameters with values from identity var subscriptionId = _match.Groups["subscriptionId"].Value; var resourceGroupName = _match.Groups["resourceGroupName"].Value; var clusterRp = _match.Groups["clusterRp"].Value; var clusterResourceName = _match.Groups["clusterResourceName"].Value; var clusterName = _match.Groups["clusterName"].Value; // construct URL var _url = new global::System.Uri(global::System.Text.RegularExpressions.Regex.Replace( "https://management.azure.com/subscriptions/" + subscriptionId + "/resourceGroups/" + resourceGroupName + "/providers/" + clusterRp + "/" + clusterResourceName + "/" + clusterName + "/providers/Microsoft.KubernetesConfiguration/sourceControlConfigurations" + "?" + "api-version=" + global::System.Uri.EscapeDataString(apiVersion) ,"\\?&*$|&*$|(\\?)&+|(&)&+","$1$2")); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.URLCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // generate request object var request = new global::System.Net.Http.HttpRequestMessage(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Method.Get, _url); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.RequestCreated, _url); if( eventListener.Token.IsCancellationRequested ) { return; } await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.HeaderParametersAdded, _url); if( eventListener.Token.IsCancellationRequested ) { return; } // make the call await this.SourceControlConfigurationsList_Call(request,onOk,onDefault,eventListener,sender); } } /// <summary>Actual wire call for <see cref="SourceControlConfigurationsList" /> method.</summary> /// <param name="request">the prepared HttpRequestMessage to send.</param> /// <param name="onOk">a delegate that is called when the remote service returns 200 (OK).</param> /// <param name="onDefault">a delegate that is called when the remote service returns default (any response code not handled /// elsewhere).</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <param name="sender">an instance of an Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync pipeline to use to make the request.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> internal async global::System.Threading.Tasks.Task SourceControlConfigurationsList_Call(global::System.Net.Http.HttpRequestMessage request, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ISourceControlConfigurationList>, global::System.Threading.Tasks.Task> onOk, global::System.Func<global::System.Net.Http.HttpResponseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.IErrorResponse>, global::System.Threading.Tasks.Task> onDefault, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.ISendAsync sender) { using( NoSynchronizationContext ) { global::System.Net.Http.HttpResponseMessage _response = null; try { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeCall, request); if( eventListener.Token.IsCancellationRequested ) { return; } _response = await sender.SendAsync(request, eventListener); await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.ResponseCreated, _response); if( eventListener.Token.IsCancellationRequested ) { return; } var _contentType = _response.Content.Headers.ContentType?.MediaType; switch ( _response.StatusCode ) { case global::System.Net.HttpStatusCode.OK: { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } await onOk(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.SourceControlConfigurationList.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); break; } default: { await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.BeforeResponseDispatch, _response); if( eventListener.Token.IsCancellationRequested ) { return; } await onDefault(_response,_response.Content.ReadAsStringAsync().ContinueWith( body => Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Models.Api20210301.ErrorResponse.FromJson(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Json.JsonNode.Parse(body.Result)) )); break; } } } finally { // finally statements await eventListener.Signal(Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.Events.Finally, request, _response); _response?.Dispose(); request?.Dispose(); } } } /// <summary> /// Validation method for <see cref="SourceControlConfigurationsList" /> method. Call this like the actual call, but you will /// get validation events back. /// </summary> /// <param name="subscriptionId">The Azure subscription ID. This is a GUID-formatted string (e.g. 00000000-0000-0000-0000-000000000000)</param> /// <param name="resourceGroupName">The name of the resource group.</param> /// <param name="clusterRp">The Kubernetes cluster RP - either Microsoft.ContainerService (for AKS clusters) or Microsoft.Kubernetes /// (for OnPrem K8S clusters).</param> /// <param name="clusterResourceName">The Kubernetes cluster resource name - either managedClusters (for AKS clusters) or /// connectedClusters (for OnPrem K8S clusters).</param> /// <param name="clusterName">The name of the kubernetes cluster.</param> /// <param name="eventListener">an <see cref="Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener" /> instance that will receive events.</param> /// <returns> /// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the response is completed. /// </returns> internal async global::System.Threading.Tasks.Task SourceControlConfigurationsList_Validate(string subscriptionId, string resourceGroupName, string clusterRp, string clusterResourceName, string clusterName, Microsoft.Azure.PowerShell.Cmdlets.KubernetesConfiguration.Runtime.IEventListener eventListener) { using( NoSynchronizationContext ) { await eventListener.AssertNotNull(nameof(subscriptionId),subscriptionId); await eventListener.AssertNotNull(nameof(resourceGroupName),resourceGroupName); await eventListener.AssertNotNull(nameof(clusterRp),clusterRp); await eventListener.AssertEnum(nameof(clusterRp),clusterRp,@"Microsoft.ContainerService", @"Microsoft.Kubernetes"); await eventListener.AssertNotNull(nameof(clusterResourceName),clusterResourceName); await eventListener.AssertEnum(nameof(clusterResourceName),clusterResourceName,@"managedClusters", @"connectedClusters"); await eventListener.AssertNotNull(nameof(clusterName),clusterName); } } } }
87.779453
1,301
0.662304
[ "MIT" ]
BurgerZ/azure-powershell
src/KubernetesConfiguration/generated/api/KubernetesConfiguration.cs
92,074
C#
#if NET_2_0 // Book.cs using System; using System.ComponentModel; using System.Security.Permissions; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace Samples.AspNet.CS.Controls { [ AspNetHostingPermission(SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Minimal), AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal), DefaultProperty("Title"), ToolboxData("<{0}:Book runat=\"server\"> </{0}:Book>") ] public class Book : WebControl { private Author authorValue; private String initialAuthorString; [ Bindable(true), Category("Appearance"), DefaultValue(""), Description("The name of the author."), DesignerSerializationVisibility( DesignerSerializationVisibility.Content), PersistenceMode(PersistenceMode.InnerProperty), ] public virtual Author Author { get { if (authorValue == null) { authorValue = new Author(); } return authorValue; } } [ Bindable(true), Category("Appearance"), DefaultValue(BookType.NotDefined), Description("Fiction or Not"), ] public virtual BookType BookType { get { object t = ViewState["BookType"]; return (t == null) ? BookType.NotDefined : (BookType)t; } set { ViewState["BookType"] = value; } } [ Bindable(true), Category("Appearance"), DefaultValue(""), Description("The symbol for the currency."), Localizable(true) ] public virtual string CurrencySymbol { get { string s = (string)ViewState["CurrencySymbol"]; return (s == null) ? String.Empty : s; } set { ViewState["CurrencySymbol"] = value; } } [ Bindable(true), Category("Appearance"), DefaultValue("0.00"), Description("The price of the book."), Localizable(true) ] public virtual Decimal Price { get { object price = ViewState["Price"]; return (price == null) ? Decimal.Zero : (Decimal)price; } set { ViewState["Price"] = value; } } [ Bindable(true), Category("Appearance"), DefaultValue(""), Description("The title of the book."), Localizable(true) ] public virtual string Title { get { string s = (string)ViewState["Title"]; return (s == null) ? String.Empty : s; } set { ViewState["Title"] = value; } } protected override void RenderContents(HtmlTextWriter writer) { writer.RenderBeginTag(HtmlTextWriterTag.Table); writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.WriteEncodedText(Title); writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.WriteEncodedText(Author.ToString()); writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.WriteEncodedText(BookType.ToString()); writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderBeginTag(HtmlTextWriterTag.Tr); writer.RenderBeginTag(HtmlTextWriterTag.Td); writer.Write(CurrencySymbol); writer.Write("&nbsp;"); writer.Write(String.Format("{0:F2}", Price)); writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderEndTag(); } protected override void LoadViewState(object savedState) { base.LoadViewState(savedState); Author auth = (Author)ViewState["Author"]; if (auth != null) { authorValue = auth; } } protected override object SaveViewState() { if (authorValue != null) { String currentAuthorString = authorValue.ToString(); if (!(currentAuthorString.Equals(initialAuthorString))) { ViewState["Author"] = authorValue; } } return base.SaveViewState(); } protected override void TrackViewState() { if (authorValue != null) { initialAuthorString = authorValue.ToString(); } base.TrackViewState(); } } } #endif
27.071066
72
0.511907
[ "MIT" ]
zlxy/Genesis-3D
Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/System.Web/Test/mainsoft/NunitWeb/NunitWeb/Tests/Book.cs
5,333
C#
๏ปฟusing System; using System.Drawing; using Gwen.Input; namespace Gwen.Control { /// <summary> /// Horizontal scrollbar. /// </summary> public class HorizontalScrollBar : ScrollBar { /// <summary> /// Bar size (in pixels). /// </summary> public override int BarSize { get { return m_Bar.Width; } set { m_Bar.Width = value; } } /// <summary> /// Bar position (in pixels). /// </summary> public override int BarPos { get { return m_Bar.X - Height; } } /// <summary> /// Indicates whether the bar is horizontal. /// </summary> public override bool IsHorizontal { get { return true; } } /// <summary> /// Button size (in pixels). /// </summary> public override int ButtonSize { get { return Height; } } /// <summary> /// Initializes a new instance of the <see cref="HorizontalScrollBar"/> class. /// </summary> /// <param name="parent">Parent control.</param> public HorizontalScrollBar(Base parent) : base(parent) { m_Bar.IsHorizontal = true; m_ScrollButton[0].SetDirectionLeft(); m_ScrollButton[0].Clicked += NudgeLeft; m_ScrollButton[1].SetDirectionRight(); m_ScrollButton[1].Clicked += NudgeRight; m_Bar.Dragged += OnBarMoved; } /// <summary> /// Lays out the control's interior according to alignment, padding, dock etc. /// </summary> /// <param name="skin">Skin to use.</param> protected override void Layout(Skin.Base skin) { base.Layout(skin); m_ScrollButton[0].Width = Height; m_ScrollButton[0].Dock = Pos.Left; m_ScrollButton[1].Width = Height; m_ScrollButton[1].Dock = Pos.Right; m_Bar.Height = ButtonSize; m_Bar.Padding = new Padding(ButtonSize, 0, ButtonSize, 0); float barWidth = (m_ViewableContentSize / m_ContentSize) * (Width - (ButtonSize * 2)); if (barWidth < ButtonSize * 0.5f) barWidth = (int)(ButtonSize * 0.5f); m_Bar.Width = (int)(barWidth); m_Bar.IsHidden = Width - (ButtonSize * 2) <= barWidth; //Based on our last scroll amount, produce a position for the bar if (!m_Bar.IsHeld) { SetScrollAmount(ScrollAmount, true); } } public void NudgeLeft(Base control, EventArgs args) { if (!IsDisabled) SetScrollAmount(ScrollAmount - NudgeAmount, true); } public void NudgeRight(Base control, EventArgs args) { if (!IsDisabled) SetScrollAmount(ScrollAmount + NudgeAmount, true); } public override void ScrollToLeft() { SetScrollAmount(0, true); } public override void ScrollToRight() { SetScrollAmount(1, true); } public override float NudgeAmount { get { if (m_Depressed) return m_ViewableContentSize / m_ContentSize; else return base.NudgeAmount; } set { base.NudgeAmount = value; } } /// <summary> /// Handler invoked on mouse click (left) event. /// </summary> /// <param name="x">X coordinate.</param> /// <param name="y">Y coordinate.</param> /// <param name="down">If set to <c>true</c> mouse button is down.</param> protected override void OnMouseClickedLeft(int x, int y, bool down) { base.OnMouseClickedLeft(x, y, down); if (down) { m_Depressed = true; InputHandler.MouseFocus = this; } else { Point clickPos = CanvasPosToLocal(new Point(x, y)); if (clickPos.X < m_Bar.X) NudgeLeft(this, EventArgs.Empty); else if (clickPos.X > m_Bar.X + m_Bar.Width) NudgeRight(this, EventArgs.Empty); m_Depressed = false; InputHandler.MouseFocus = null; } } protected override float CalculateScrolledAmount() { return (float)(m_Bar.X - ButtonSize) / (Width - m_Bar.Width - (ButtonSize * 2)); } /// <summary> /// Sets the scroll amount (0-1). /// </summary> /// <param name="value">Scroll amount.</param> /// <param name="forceUpdate">Determines whether the control should be updated.</param> /// <returns> /// True if control state changed. /// </returns> public override bool SetScrollAmount(float value, bool forceUpdate = false) { value = Util.Clamp(value, 0, 1); if (!base.SetScrollAmount(value, forceUpdate)) return false; if (forceUpdate) { int newX = (int)(ButtonSize + (value * ((Width - m_Bar.Width) - (ButtonSize * 2)))); m_Bar.MoveTo(newX, m_Bar.Y); } return true; } /// <summary> /// Handler for the BarMoved event. /// </summary> /// <param name="control">Event source.</param> protected override void OnBarMoved(Base control, EventArgs args) { if (m_Bar.IsHeld) { SetScrollAmount(CalculateScrolledAmount(), false); base.OnBarMoved(control, args); } else InvalidateParent(); } } }
28.990244
100
0.504122
[ "MIT" ]
BreyerW/Sharp.Engine
Gwen/Control/HorizontalScrollBar.cs
5,945
C#
๏ปฟusing UnityEngine; namespace YooAsset { internal class YooAssetDriver : MonoBehaviour { void Update() { YooAssets.InternalUpdate(); } } }
15.583333
49
0.566845
[ "MIT" ]
zhangfeitao/YooAsset
Assets/YooAsset/Runtime/YooAssetDriver.cs
189
C#
๏ปฟ//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by \generate-code.bat. // // Changes to this file will be lost when the code is regenerated. // The build server regenerates the code before each build and a pre-build // step will regenerate the code on each local build. // // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. // Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // </auto-generated> //------------------------------------------------------------------------------ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; namespace UnitsNet.NumberExtensions.NumberToLuminousFlux { /// <summary> /// A number to LuminousFlux Extensions /// </summary> public static class NumberToLuminousFluxExtensions { /// <inheritdoc cref="LuminousFlux.FromLumens(UnitsNet.QuantityValue)" /> public static LuminousFlux Lumens<T>(this T value) => LuminousFlux.FromLumens(Convert.ToDouble(value)); } }
40.971429
125
0.624826
[ "MIT" ]
DInozemtsev/UnitsNet
UnitsNet.NumberExtensions/GeneratedCode/NumberToLuminousFluxExtensions.g.cs
1,436
C#
๏ปฟ/************************************************* Copyright (c) 2021 Undersoft System.Instant.Sqlset.SqlDbSchema.cs @project: Undersoft.Vegas.Sdk @stage: Development @author: Dariusz Hanc @date: (05.06.2021) @licence MIT *************************************************/ namespace System.Instant.Sqlset { using System.Collections.Generic; using System.Data.SqlClient; /// <summary> /// Defines the <see cref="DataDbSchema" />. /// </summary> public class DataDbSchema { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="DataDbSchema"/> class. /// </summary> /// <param name="sqlDbConnection">The sqlDbConnection<see cref="SqlConnection"/>.</param> public DataDbSchema(SqlConnection sqlDbConnection) { DataDbTables = new DbTables(); DbConfig = new DbConfig(sqlDbConnection.ConnectionString); } /// <summary> /// Initializes a new instance of the <see cref="DataDbSchema"/> class. /// </summary> /// <param name="dbConnectionString">The dbConnectionString<see cref="string"/>.</param> public DataDbSchema(string dbConnectionString) { DataDbTables = new DbTables(); DbConfig = new DbConfig(dbConnectionString); SqlDbConnection = new SqlConnection(dbConnectionString); } #endregion #region Properties /// <summary> /// Gets or sets the DataDbTables. /// </summary> public DbTables DataDbTables { get; set; } /// <summary> /// Gets or sets the DbConfig. /// </summary> public DbConfig DbConfig { get; set; } /// <summary> /// Gets or sets the DbName. /// </summary> public string DbName { get; set; } /// <summary> /// Gets or sets the DbTables. /// </summary> public List<DbTable> DbTables { get { return DataDbTables.List; } set { DataDbTables.List = value; } } /// <summary> /// Gets or sets the SqlDbConnection. /// </summary> public SqlConnection SqlDbConnection { get; set; } #endregion } /// <summary> /// Defines the <see cref="DbConfig" />. /// </summary> public class DbConfig { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="DbConfig"/> class. /// </summary> public DbConfig() { } /// <summary> /// Initializes a new instance of the <see cref="DbConfig"/> class. /// </summary> /// <param name="_User">The _User<see cref="string"/>.</param> /// <param name="_Password">The _Password<see cref="string"/>.</param> /// <param name="_Source">The _Source<see cref="string"/>.</param> /// <param name="_Catalog">The _Catalog<see cref="string"/>.</param> /// <param name="_Provider">The _Provider<see cref="string"/>.</param> public DbConfig(string _User, string _Password, string _Source, string _Catalog, string _Provider = "SQLNCLI11") { User = _User; Password = _Password; Provider = _Provider; Source = _Source; Album = _Catalog; DbConnectionString = string.Format("Provider={0};Data Source = {1}; Persist Security Info=True;Password={2};User ID = {3}; Initial Album = {4}", Provider, Source, Password, User, Album); } /// <summary> /// Initializes a new instance of the <see cref="DbConfig"/> class. /// </summary> /// <param name="dbConnectionString">The dbConnectionString<see cref="string"/>.</param> public DbConfig(string dbConnectionString) { DbConnectionString = dbConnectionString; } #endregion #region Properties /// <summary> /// Gets or sets the Album. /// </summary> public string Album { get; set; } /// <summary> /// Gets or sets the DbConnectionString. /// </summary> public string DbConnectionString { get; set; } /// <summary> /// Gets or sets the Password. /// </summary> public string Password { get; set; } /// <summary> /// Gets or sets the Provider. /// </summary> public string Provider { get; set; } /// <summary> /// Gets or sets the Source. /// </summary> public string Source { get; set; } /// <summary> /// Gets or sets the User. /// </summary> public string User { get; set; } #endregion } /// <summary> /// Defines the <see cref="DbHand" />. /// </summary> public static class DbHand { #region Properties /// <summary> /// Gets or sets the Schema. /// </summary> public static DataDbSchema Schema { get; set; } /// <summary> /// Gets or sets the Temp. /// </summary> public static DataDbSchema Temp { get; set; } #endregion } }
29.689266
198
0.533968
[ "MIT" ]
undersoft-org/NET.Undersoft.Sdk.Devel
NET.Undersoft.Vegas.Sdk/Undersoft.System.Instant.Sqlset/Schema/SqlDbSchema.cs
5,257
C#
๏ปฟ// // RedundantObjectOrCollectionInitializerIssue.cs // // Author: // Mansheng Yang <lightyang0@gmail.com> // // Copyright (c) 2012 Mansheng Yang <lightyang0@gmail.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System.Collections.Generic; namespace ICSharpCode.NRefactory.CSharp.Refactoring { [IssueDescription ("Redundant empty object or collection initializer", Description = "Redundant empty object or collection initializer.", Category = IssueCategories.Redundancies, Severity = Severity.Suggestion, IssueMarker = IssueMarker.GrayOut)] public class RedundantObjectOrCollectionInitializerIssue : ICodeIssueProvider { public IEnumerable<CodeIssue> GetIssues (BaseRefactoringContext context) { return new GatherVisitor (context).GetIssues (); } class GatherVisitor : GatherVisitorBase { public GatherVisitor (BaseRefactoringContext ctx) : base (ctx) { } public override void VisitObjectCreateExpression (ObjectCreateExpression objectCreateExpression) { base.VisitObjectCreateExpression (objectCreateExpression); if (objectCreateExpression.Initializer.IsNull || objectCreateExpression.Initializer.Elements.Count > 0) return; AddIssue (objectCreateExpression.Initializer, ctx.TranslateString ("Remove redundant empty initializer"), script => { var expr = (ObjectCreateExpression)objectCreateExpression.Clone (); expr.Initializer = ArrayInitializerExpression.Null; script.Replace (objectCreateExpression, expr); }); } } } }
39.333333
109
0.755778
[ "MIT" ]
4lab/ILSpy
NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeIssues/RedundantObjectOrCollectionInitializerIssue.cs
2,598
C#
๏ปฟ/* * Copyright 2014 Splunk, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"): you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ namespace Splunk.ModularInputs { using System; /// <summary> /// The <see cref="EventElement"/> class represents an event element /// for XML event streaming. /// </summary> public struct EventElement { /// <summary> /// Event data. /// </summary> public string Data { get; set; } /// <summary> /// The event source. /// </summary> public string Source { get; set; } /// <summary> /// The source type. /// </summary> public string SourceType { get; set; } /// <summary> /// The index. /// </summary> public string Index { get; set; } /// <summary> /// The host. /// </summary> public string Host { get; set; } /// <summary> /// The timestamp of the event. /// </summary> /// <remarks> /// If this property is null, Splunk will generate a timestamp /// according to current time, or in case of "unbroken" event, the /// timestamp supplied earlier for the event will be used. /// </remarks> public DateTime? Time { get; set; } /// <summary> /// A value indicating whether the event stream has /// completed a set of events and can be flushed. /// </summary> public bool Done { get; set; } /// <summary> /// A value indicating whether the element contains /// only a part of an event or multiple events. /// </summary> /// <remarks> /// If this property is false, the element represents a single, /// whole event. /// </remarks> public bool Unbroken { get; set; } /// <summary> /// The name of the stanza of the input this event belongs to. /// </summary> public string Stanza { get; set; } } }
29.72619
76
0.568682
[ "Apache-2.0" ]
glennblock/splunk-sdk-csharp-pcl
src/Splunk.ModularInputs/Splunk.safe/ModularInputs/EventElement.cs
2,499
C#
๏ปฟusing System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // ะžะฑั‰ะธะต ัะฒะตะดะตะฝะธั ะพะฑ ัั‚ะพะน ัะฑะพั€ะบะต ะฟั€ะตะดะพัั‚ะฐะฒะปััŽั‚ัั ัะปะตะดัƒัŽั‰ะธะผ ะฝะฐะฑะพั€ะพะผ // ะฝะฐะฑะพั€ะฐ ะฐั‚ั€ะธะฑัƒั‚ะพะฒ. ะ˜ะทะผะตะฝะธั‚ะต ะทะฝะฐั‡ะตะฝะธั ัั‚ะธั… ะฐั‚ั€ะธะฑัƒั‚ะพะฒ, ั‡ั‚ะพะฑั‹ ะธะทะผะตะฝะธั‚ัŒ ัะฒะตะดะตะฝะธั, // ัะฒัะทะฐะฝะฝั‹ะต ัะพ ัะฑะพั€ะบะพะน. [assembly: AssemblyTitle("Eoam.Task8.EmailFinder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Eoam.Task8.EmailFinder")] [assembly: AssemblyCopyright("Copyright ยฉ 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ะฃัั‚ะฐะฝะพะฒะบะฐ ะทะฝะฐั‡ะตะฝะธั False ะดะปั ะฟะฐั€ะฐะผะตั‚ั€ะฐ ComVisible ะดะตะปะฐะตั‚ ั‚ะธะฟั‹ ะฒ ัั‚ะพะน ัะฑะพั€ะบะต ะฝะตะฒะธะดะธะผั‹ะผะธ // ะดะปั ะบะพะผะฟะพะฝะตะฝั‚ะพะฒ COM. ะ•ัะปะธ ะฝะตะพะฑั…ะพะดะธะผะพ ะพะฑั€ะฐั‚ะธั‚ัŒัั ะบ ั‚ะธะฟัƒ ะฒ ัั‚ะพะน ัะฑะพั€ะบะต ั‡ะตั€ะตะท // COM, ะทะฐะดะฐะนั‚ะต ะฐั‚ั€ะธะฑัƒั‚ัƒ ComVisible ะทะฝะฐั‡ะตะฝะธะต TRUE ะดะปั ัั‚ะพะณะพ ั‚ะธะฟะฐ. [assembly: ComVisible(false)] // ะกะปะตะดัƒัŽั‰ะธะน GUID ัะปัƒะถะธั‚ ะดะปั ะธะดะตะฝั‚ะธั„ะธะบะฐั†ะธะธ ะฑะธะฑะปะธะพั‚ะตะบะธ ั‚ะธะฟะพะฒ, ะตัะปะธ ัั‚ะพั‚ ะฟั€ะพะตะบั‚ ะฑัƒะดะตั‚ ะฒะธะดะธะผั‹ะผ ะดะปั COM [assembly: Guid("b387fe48-bfe6-4b67-8480-967ffb3bce02")] // ะกะฒะตะดะตะฝะธั ะพ ะฒะตั€ัะธะธ ัะฑะพั€ะบะธ ัะพัั‚ะพัั‚ ะธะท ัะปะตะดัƒัŽั‰ะธั… ั‡ะตั‚ั‹ั€ะตั… ะทะฝะฐั‡ะตะฝะธะน: // // ะžัะฝะพะฒะฝะพะน ะฝะพะผะตั€ ะฒะตั€ัะธะธ // ะ”ะพะฟะพะปะฝะธั‚ะตะปัŒะฝั‹ะน ะฝะพะผะตั€ ะฒะตั€ัะธะธ // ะะพะผะตั€ ัะฑะพั€ะบะธ // ะ ะตะดะฐะบั†ะธั // // ะœะพะถะฝะพ ะทะฐะดะฐั‚ัŒ ะฒัะต ะทะฝะฐั‡ะตะฝะธั ะธะปะธ ะฟั€ะธะฝัั‚ัŒ ะฝะพะผะตั€ ัะฑะพั€ะบะธ ะธ ะฝะพะผะตั€ ั€ะตะดะฐะบั†ะธะธ ะฟะพ ัƒะผะพะปั‡ะฐะฝะธัŽ. // ะธัะฟะพะปัŒะทัƒั "*", ะบะฐะบ ะฟะพะบะฐะทะฐะฝะพ ะฝะธะถะต: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.108108
99
0.76434
[ "MIT" ]
NurAliia/XT-2018Q4
Epam.Task8/Eoam.Task8.EmailFinder/Properties/AssemblyInfo.cs
2,027
C#
๏ปฟ#region License /* * File: Program.cs * * The MIT License * * Copyright ยฉ 2017 - 2020 AVSP Ltd * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion License using System; using System.Diagnostics; using AVSP.ConsoleSupport; using VsIdeBuild.VsBuilderLibrary; namespace VsIdeBuild { internal class Program { private static int Run(SimpleArguments arguments) { VsBuilderOptions options = new VsBuilderOptions(); // parse command line arguments into options SimpleArgumentsReader.ArgumentsToObject(arguments, options); if (options.Solution == null || options.Solution.Length == 0) { Console.Error.WriteLine(@"ERROR: solution must be specified with -solution c:\path\to\solution.sln"); return 1; } VsBuilder builder = new VsBuilder(); int result = builder.Run(options); if ((result != 0) || builder.Results.Failed) { Console.Error.WriteLine("ERROR: some builds failed, check output"); return 1; } Console.WriteLine("Success: all okay"); return 0; } // STAThread needed for COM [STAThread] private static int Main(string[] args) { return ConsoleHelper.RunProgram(args, Run); } } }
32.918919
117
0.66133
[ "Unlicense" ]
ninjaoxygen/VsIdeBuild
Program.cs
2,439
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using Grasshopper.Kernel; using Grasshopper.Kernel.Types; using Grasshopper.Kernel.Parameters; using Rhino.Geometry; using Parametric_FEM_Toolbox.UIWidgets; using Parametric_FEM_Toolbox.HelperLibraries; using Parametric_FEM_Toolbox.Utilities; using System.Runtime.InteropServices; using Parametric_FEM_Toolbox.GUI; namespace Parametric_FEM_Toolbox.Deprecated { public class Component_RFNodalLoad_GUI_OBSOLETE : GH_SwitcherComponent { // Declare class variables outside the method "SolveInstance" so their values persist // when the method is called again. /// <summary> /// Each implementation of GH_Component must provide a public /// constructor without any arguments. /// Category represents the Tab in which the component will appear, /// Subcategory the panel. If you use non-existing tab or panel names, /// new tabs/panels will automatically be created. /// </summary> public Component_RFNodalLoad_GUI_OBSOLETE() : base("RF Nodal Load", "RFNodLoad", "Creates a RFNodalLoad object to define new data or modify existing data " + "in the RFEM model.", "B+G Toolbox", "RFEM") { } // Define Keywords to search for this Component more easily in Grasshopper public override IEnumerable<string> Keywords => new string[] {"rf", "rfnodalload", "load", "nodal"}; /// <summary> /// Registers all the input parameters for this component. /// </summary> protected override void RegisterInputParams(GH_Component.GH_InputParamManager pManager) { // Use the pManager object to register your input parameters. pManager.AddPointParameter("Location", "Loc", "Load Application point.", GH_ParamAccess.item); pManager[0].Optional = true; pManager.AddIntegerParameter("Load Case", "LC", "Load Case to assign the load to.", GH_ParamAccess.item); pManager[1].Optional = true; pManager.AddVectorParameter("Force [kN]", "F", "Load Force [kN]", GH_ParamAccess.item); pManager[2].Optional = true; pManager.AddVectorParameter("Moment [kNm]", "M", "Load Moment [kN]", GH_ParamAccess.item); pManager[3].Optional = true; pManager.AddIntegerParameter("Load Number", "No", "Optional index number to assign to the RFEM object.", GH_ParamAccess.item); pManager[4].Optional = true; pManager.AddTextParameter("Comment", "Comment", "Comment.", GH_ParamAccess.item); pManager[5].Optional = true; // you can use the pManager instance to access them by index: // pManager[0].Optional = true; } /// <summary> /// Registers all the output parameters for this component. /// </summary> protected override void RegisterOutputParams(GH_Component.GH_OutputParamManager pManager) { // Use the pManager object to register your output parameters. // Output parameters do not have default values, but they too must have the correct access type. pManager.RegisterParam(new Param_RFEM(), "Nodal Load", "NodLoad", "Output RFNodalLoad.", GH_ParamAccess.item); // Sometimes you want to hide a specific parameter from the Rhino preview. // You can use the HideParameter() method as a quick way: // pManager.HideParameter(0); } protected override void RegisterEvaluationUnits(EvaluationUnitManager mngr) { EvaluationUnit evaluationUnit = new EvaluationUnit("Assemble Nodal Support", "NodSup", "Creates a RFSupportP object to define new data or modify existing data " + "in the RFEM model."); mngr.RegisterUnit(evaluationUnit); evaluationUnit.RegisterInputParam(new Param_String(), "Node List", "NodeList", "Node List", GH_ParamAccess.item); evaluationUnit.RegisterInputParam(new Param_String(), "Node List", "NodeList", "Node List", GH_ParamAccess.item); evaluationUnit.Inputs[0].Parameter.Optional = true; //evaluationUnit.RegisterInputParam(new Param_String(), "LoadDefinitionType", "Def", UtilLibrary.DescriptionRFTypes(typeof(LoadDefinitionType)), GH_ParamAccess.item); evaluationUnit.Inputs[1].Parameter.Optional = true; evaluationUnit.RegisterInputParam(new Param_RFEM(), "Nodal Load", "NodLoad", "Load object from the RFEM model to modify", GH_ParamAccess.item); evaluationUnit.Inputs[2].Parameter.Optional = true; evaluationUnit.RegisterInputParam(new Param_Boolean(), "Modify", "Modify", "Modify node?", GH_ParamAccess.item); evaluationUnit.Inputs[3].Parameter.Optional = true; evaluationUnit.RegisterInputParam(new Param_Boolean(), "Delete", "Delete", "Delete node?", GH_ParamAccess.item); evaluationUnit.Inputs[4].Parameter.Optional = true; GH_ExtendableMenu gH_ExtendableMenu = new GH_ExtendableMenu(0, "advanced"); gH_ExtendableMenu.Name = "Advanced"; gH_ExtendableMenu.Collapse(); evaluationUnit.AddMenu(gH_ExtendableMenu); for (int i = 0; i < 2; i++) { gH_ExtendableMenu.RegisterInputPlug(evaluationUnit.Inputs[i]); } GH_ExtendableMenu gH_ExtendableMenu2 = new GH_ExtendableMenu(1, "modify"); gH_ExtendableMenu2.Name = "Modify"; gH_ExtendableMenu2.Collapse(); evaluationUnit.AddMenu(gH_ExtendableMenu2); for (int i = 2; i < 2+3; i++) { gH_ExtendableMenu2.RegisterInputPlug(evaluationUnit.Inputs[i]); } } /// <summary> /// This is the method that actually does the work. /// </summary> /// <param name="DA">The DA object can be used to retrieve data from input parameters and /// to store data in output parameters.</param> protected override void SolveInstance(IGH_DataAccess DA, EvaluationUnit unit) { ////var line = new LineCurve(); //var point = new Point3d(); //var noIndex = 0; //var loadCase = 0; //var comment = ""; //var rfNodalLoad = new RFNodalLoad(); //var inRFEM = new GH_RFEM(); //var mod = false; //var del = false; //var force = new Vector3d(); //var moment = new Vector3d(); //var nodeList = ""; //var definition = ""; ////int newNo = 0; //if (DA.GetData(8, ref inRFEM)) //{ // rfNodalLoad = new RFNodalLoad((RFNodalLoad)inRFEM.Value); //}else if ((DA.GetData(0, ref point)) && (DA.GetData(1, ref loadCase))) //{ // var inPoints = new List<Point3d>(); // inPoints.Add(point); // rfNodalLoad = new RFNodalLoad(new NodalLoad(), inPoints, loadCase); // rfNodalLoad.LoadDefType = LoadDefinitionType.ByComponentsType; //} //else //{ // return; //} //if (DA.GetData(9, ref mod)) //{ // rfNodalLoad.ToModify = mod; //} //if (DA.GetData(10, ref del)) //{ // rfNodalLoad.ToDelete = del; //} //if (DA.GetData(4, ref noIndex)) //{ // rfNodalLoad.No = noIndex; //} //if (DA.GetData(5, ref comment)) //{ // rfNodalLoad.Comment = comment; //} //if (DA.GetData(2, ref force)) //{ // rfNodalLoad.Force = force; //} //if (DA.GetData(3, ref moment)) //{ // rfNodalLoad.Moment = moment; //} //// Add warning in case of null forces //if ((rfNodalLoad.Force.Length == 0.0) && (rfNodalLoad.Moment.Length == 0)) //{ // AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Null forces will result in an error in RFEM"); //} //if (DA.GetData(6, ref nodeList)) //{ // rfNodalLoad.NodeList = nodeList; //} //if (DA.GetData(7, ref definition)) //{ // Enum.TryParse(definition, out LoadDefinitionType myDef); // rfNodalLoad.LoadDefType = myDef; //} //DA.SetData(0, rfNodalLoad); } /// <summary> /// The Exposure property controls where in the panel a component icon /// will appear. There are seven possible locations (primary to septenary), /// each of which can be combined with the GH_Exposure.obscure flag, which /// ensures the component will only be visible on panel dropdowns. /// </summary> public override GH_Exposure Exposure { get { return GH_Exposure.hidden; } } /// <summary> /// Provides an Icon for every component that will be visible in the User Interface. /// Icons need to be 24x24 pixels. /// </summary> protected override System.Drawing.Bitmap Icon { get { // You can add image files to your project resources and access them like this: //return Resources.IconForThisComponent; return Properties.Resources.Assemble_NodalLoad; } } /// <summary> /// Each component must have a unique Guid to identify it. /// It is vital this Guid doesn't change otherwise old ghx files /// that use the old ID will partially fail during loading. /// </summary> public override Guid ComponentGuid { get { return new Guid("1798fa54-7920-4a8a-a3ba-caff0fbc7061"); } } } }
43.87931
178
0.586149
[ "Apache-2.0" ]
Sonderwoods/Parametric-FEM-Toolbox
Parametric_FEM_Toolbox/Parametric_FEM_Toolbox/Deprecated/Component_RFNodalLoad_GUI_OBSOLETE.cs
10,182
C#
๏ปฟusing System; using System.Collections.ObjectModel; using System.Threading.Tasks; using BlissXamarinApp.Interfaces; using BlissXamarinApp.Models; using BlissXamarinApp.Utils; using Xamarin.Forms; namespace BlissXamarinApp.ViewModels { public class MainViewModel : BaseViewModel { private readonly IBlissApiService _blissXamarinApiService; private string _searchTerm; public string SearchTerm { get => _searchTerm; set { SetProperty(ref _searchTerm, value); SearchCommand.ChangeCanExecute(); SearchCommandClear(_searchTerm); } } public ObservableCollection<Question> Questions { get; set; } private ObservableCollection<Question> QuestionsAll { get; } public Command ShareCommand { get; } public Command SearchCommand { get; } public Command<Question> ShowQuestionCommand { get; } public Command ForceRefreshCommand { get; } public Command LoadMoreCommand { get; } public MainViewModel(IBlissApiService blissXamarinApiService) { try { Title = "Bliss Test"; _blissXamarinApiService = blissXamarinApiService; Questions = new ObservableCollection<Question>(); QuestionsAll = new ObservableCollection<Question>(); SearchCommand = new Command(ExecuteSearchCommand); ShareCommand = new Command(ExecuteShareCommand); ForceRefreshCommand = new Command(ExecuteForceRefreshCommand); LoadMoreCommand = new Command(ExecuteLoadMoreCommand); ShowQuestionCommand = new Command<Question>(ExecuteShowQuestionCommand); } catch (Exception e) { } } private async void ExecuteShareCommand() { Questions.Clear(); await PushAsync<ShareViewModel>(""); } private async void ExecuteForceRefreshCommand() { Questions.Clear(); await LoadAsync(); } private async void ExecuteLoadMoreCommand() { await LoadAsync(); } private async void ExecuteShowQuestionCommand(Question question) { Questions.Clear(); await PushAsync<QuestionViewModel>(question); } private void SearchCommandClear(string searchTerm) { Questions.Clear(); if (QuestionsAll.Count > 0 && string.IsNullOrEmpty(searchTerm)) { Questions = QuestionsAll; OnPropertyChanged(nameof(Questions)); } } private async void ExecuteSearchCommand() { try { IsBusy = true; IsEmpty = false; var questions = await _blissXamarinApiService.GetQuestionsByFilterAsync(Questions.Count, SearchTerm); if (questions != null && questions.Count > 0) { IsEmpty = false; foreach (var question in questions) { Questions.Add(question); } OnPropertyChanged(nameof(Questions)); } else IsEmpty = true; } catch (Exception e) { IsEmpty = true; } finally { IsBusy = false; } } public override async Task LoadAsync() { try { IsEmpty = false; if (Util.CheckConnectivity()) { IsBusy = true; var questions = await _blissXamarinApiService.GetQuestionsAsync(Questions.Count); if (questions != null && questions.Count > 0) { foreach (var question in questions) { Questions.Add(question); QuestionsAll.Add(question); } OnPropertyChanged(nameof(Questions)); } else IsEmpty = true; } } catch (Exception e) { IsEmpty = true; } finally { IsBusy = false; } } } }
29.23125
117
0.496258
[ "MIT" ]
ejastre/BlissXamarinApp
BlissXamarinApp/BlissXamarinApp/ViewModels/MainViewModel.cs
4,679
C#
using ASTRA.EMSG.Business.Entities.Mapping; using ASTRA.EMSG.Common.Enums; namespace ASTRA.EMSG.Business.Entities.Common { [TableShortName("TUI")] public class TestUserInfo : Entity { public const string IntegrationTestUserName = "Test"; public virtual string UserName { get; set; } public virtual string Mandator { get; set; } public virtual Rolle Rolle { get; set; } public override string ToString() { return string.Format("UserName: {0}, Mandator: {1}, Rolle: {2}", UserName, Mandator, Rolle); } } }
30.9
104
0.61165
[ "BSD-3-Clause" ]
astra-emsg/ASTRA.EMSG
Master/ASTRA.EMSG.Business/Entities/Common/TestUserInfo.cs
618
C#
๏ปฟusing System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Security.Claims; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using HelseID.Common.Crypto; using HelseID.Common.Extensions; using IdentityModel; using Microsoft.IdentityModel.Tokens; namespace HelseID.Common.Jwt { public class JwtGenerator { public enum SigningMethod { None, X509SecurityKey, RsaSecurityKey, X509EnterpriseSecurityKey }; public static List<string> ValidAudiences = new List<string> { "https://localhost:44366/connect/token", "https://helseid-sts.utvikling.nhn.no", "https://helseid-sts.test.nhn.no", "https://helseid-sts.utvikling.nhn.no" }; private const double DefaultExpiryInHours = 10; /// <summary> /// /// </summary> /// <param name="clientId"></param> /// <param name="tokenEndpoint"></param> /// <param name="signingMethod">Indicate which method to use when signing the Jwt Token</param> /// <param name="securityKey"></param> /// <param name="securityAlgorithm"></param> public static string Generate(string clientId, string tokenEndpoint, SigningMethod signingMethod, SecurityKey securityKey, string securityAlgorithm) { if (clientId.IsNullOrEmpty()) throw new ArgumentException("clientId can not be empty or null"); if (tokenEndpoint.IsNullOrEmpty()) throw new ArgumentException("The token endpoint address can not be empty or null"); if (securityKey ==null) throw new ArgumentException("The security key can not be null"); if (securityAlgorithm.IsNullOrEmpty()) throw new ArgumentException("The security algorithm can not be empty or null"); return GenerateJwt(clientId, tokenEndpoint, null, signingMethod, securityKey, securityAlgorithm); } /// <summary> /// Generates a new JWT /// </summary> /// <param name="clientId">The OAuth/OIDC client ID</param> /// <param name="audience">The Authorization Server (STS)</param> /// <param name="expiryDate">If value is null, the default expiry date is used (10 hrs)</param> /// <param name="signingMethod"></param> /// <param name="securityKey"></param> /// <param name="securityAlgorithm"></param> /// <returns></returns> private static string GenerateJwt(string clientId, string audience, DateTime? expiryDate, SigningMethod signingMethod, SecurityKey securityKey, string securityAlgorithm) //SigningMethod signingMethod, SigningCredentials signingCredentials = null) { var signingCredentials = new SigningCredentials(securityKey, securityAlgorithm); var jwt = CreateJwtSecurityToken(clientId, audience + "", expiryDate, signingCredentials); if (signingMethod == SigningMethod.X509EnterpriseSecurityKey) UpdateJwtHeader(securityKey, jwt); var tokenHandler = new JwtSecurityTokenHandler(); return tokenHandler.WriteToken(jwt); } public static void UpdateJwtHeader(SecurityKey key, JwtSecurityToken token) { if (key is X509SecurityKey x509Key) { var thumbprint = Base64Url.Encode(x509Key.Certificate.GetCertHash()); var x5c = GenerateX5c(x509Key.Certificate); var pubKey = x509Key.PublicKey as RSA; var parameters = pubKey.ExportParameters(false); var exponent = Base64Url.Encode(parameters.Exponent); var modulus = Base64Url.Encode(parameters.Modulus); token.Header.Add("x5c", x5c); token.Header.Add("kty", pubKey.SignatureAlgorithm); token.Header.Add("use", "sig"); token.Header.Add("x5t", thumbprint); token.Header.Add("e", exponent); token.Header.Add("n", modulus); } if (key is RsaSecurityKey rsaKey) { var parameters = rsaKey.Rsa?.ExportParameters(false) ?? rsaKey.Parameters; var exponent = Base64Url.Encode(parameters.Exponent); var modulus = Base64Url.Encode(parameters.Modulus); token.Header.Add("kty", "RSA"); token.Header.Add("use", "sig"); token.Header.Add("e", exponent); token.Header.Add("n", modulus); } } private static List<string> GenerateX5c(X509Certificate2 certificate) { var x5c = new List<string>(); var chain = GetCertificateChain(certificate); if (chain != null) { foreach (var cert in chain.ChainElements) { var x509base64 = Convert.ToBase64String(cert.Certificate.RawData); x5c.Add(x509base64); } } return x5c; } private static X509Chain GetCertificateChain(X509Certificate2 cert) { X509Chain certificateChain = X509Chain.Create(); certificateChain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; certificateChain.Build(cert); return certificateChain; } private static JwtSecurityToken CreateJwtSecurityToken(string clientId, string audience, DateTime? expiryDate, SigningCredentials signingCredentials) { var exp = new DateTimeOffset(expiryDate ?? DateTime.Now.AddHours(DefaultExpiryInHours)); var claims = new List<Claim> { new Claim(JwtClaimTypes.Subject, clientId), new Claim(JwtClaimTypes.IssuedAt, exp.ToUnixTimeSeconds().ToString()), new Claim(JwtClaimTypes.JwtId, Guid.NewGuid().ToString("N")) }; var token = new JwtSecurityToken(clientId, audience, claims, DateTime.Now, DateTime.Now.AddHours(10), signingCredentials); return token; } public static SecurityToken ValidateToken(string token, string validIssuer, string validAudience) { var publicKey = RSAKeyGenerator.GetPublicKeyAsXml(); var test = RSA.Create(); test.FromXmlString(publicKey); var securityKey = new RsaSecurityKey(test.ExportParameters(false)); var handler = new JwtSecurityTokenHandler(); var validationParams = new TokenValidationParameters { RequireSignedTokens = true, IssuerSigningKey = securityKey, ValidAudience = validAudience, ValidIssuer = validIssuer }; var claimsPrincipal = handler.ValidateToken(token, validationParams, out var validatedToken); return validatedToken; } } }
41.609467
254
0.616468
[ "MIT" ]
uringeller/HelseID.Samples
HelseId.Common/Jwt/JwtGenerator.cs
7,034
C#
๏ปฟusing System; using System.Collections.Generic; using System.Text; namespace Tensorflow.Keras.Losses { public abstract class Loss { } }
13.636364
33
0.72
[ "Apache-2.0" ]
mahedee/TensorFlow.NET
src/TensorFlowNET.Keras/Losses/Loss.cs
152
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using ISAAR.MSolve.PreProcessor.Interfaces; using System.IO; using System.Globalization; using System.Diagnostics; namespace ISAAR.MSolve.PreProcessor.Stochastic { public class LognormalPCFileStochasticCoefficientsProvider : IStochasticMaterialCoefficientsProvider, IPCCoefficientsProvider { private readonly StochasticCoefficientsMemoizer memoizer; private readonly int orderM, orderP; private readonly double[][,] evp; private readonly int[,] evpPos; private readonly double[] eigs; private readonly double[] translations; private readonly double mean; private readonly double meanGaussian; private readonly double covariance; private readonly double covarianceGaussian; private readonly double[] stochasticDomain; private readonly int[] varianceAxes = new int[] { 0, 1, 2 }; private readonly IPolynomialChaosCoefficients calculator; private static NumberFormatInfo ni = null; public int OrderM { get { return orderM; } } public int OrderP { get { return orderP; } } public int CurrentOrder { get; set; } public int ExpansionOrder { get { return calculator.PsiSize - 1; } } public int NoOfMatrices { get { return calculator.PsiSize - 1; } } public double[] RandomVariables { get; set; } public IPolynomialChaosCoefficients Calculator { get { return calculator; } } public LognormalPCFileStochasticCoefficientsProvider(string fileName, int noOfVariables, int orderM, int orderP, char separator, double[] stochasticDomain, string decimalSeparator = ".") { this.orderM = orderM; this.orderP = orderP; this.calculator = new PolynomialChaosCoefficientsCalculator(orderM, orderP, false); CultureInfo ci = System.Globalization.CultureInfo.InstalledUICulture; ni = (System.Globalization.NumberFormatInfo)ci.NumberFormat.Clone(); ni.NumberDecimalSeparator = decimalSeparator; this.stochasticDomain = stochasticDomain; int noOfCoords = stochasticDomain.Length; eigs = new double[noOfVariables]; evpPos = new int[noOfVariables, 3]; evp = new double[noOfCoords][,]; translations = new double[noOfCoords]; for (int i = 0; i < noOfCoords; i++) { translations[i] = stochasticDomain[i] / 2; evp[i] = new double[noOfVariables, 3]; } string[] lines = File.ReadAllLines(fileName); string[] values; for (int i = 0; i < noOfVariables; i++) { for (int j = 0; j < noOfCoords; j++) { values = lines[i + j * noOfVariables].Split(separator); evp[j][i, 0] = double.Parse(values[0], ni); evp[j][i, 1] = double.Parse(values[1], ni); evp[j][i, 2] = double.Parse(values[2], ni); } values = lines[i + noOfCoords * noOfVariables].Split(separator); evpPos[i, 0] = int.Parse(values[0], ni); evpPos[i, 1] = int.Parse(values[1], ni); evpPos[i, 2] = int.Parse(values[2], ni); values = lines[i + (noOfCoords + 1) * noOfVariables].Split(separator); eigs[i] = double.Parse(values[0], ni); } values = lines[(noOfCoords + 2) * noOfVariables].Split(separator); //mean = double.Parse(values[0], ni); values = lines[(noOfCoords + 2) * noOfVariables + 1].Split(separator); //covariance = double.Parse(values[0], ni); mean = 1; covariance = 0.8; //covarianceGaussian = covariance; meanGaussian = 0; covarianceGaussian = Math.Sqrt(Math.Log(Math.Pow(covariance / mean, 2) + 1, Math.E)); //meanGaussian = Math.Log(mean, Math.E) - 0.5 * Math.Pow(covarianceGaussian, 2); //covarianceGaussian = Math.Log(Math.Sqrt(Math.Pow(covariance / mean, 2) + 1), Math.E); //meanGaussian = Math.Log(mean, Math.E) - 0.5 * covarianceGaussian; } public LognormalPCFileStochasticCoefficientsProvider(string fileName, int noOfVariables, int orderM, int orderP, char separator, double[] stochasticDomain, int[] varianceAxes, string decimalSeparator = ".") : this(fileName, noOfVariables, orderM, orderP, separator, stochasticDomain, decimalSeparator) { this.varianceAxes = varianceAxes; } public LognormalPCFileStochasticCoefficientsProvider(string fileName, int noOfVariables, int orderM, int orderP, char separator, double[] stochasticDomain, StochasticCoefficientsMemoizer memoizer, string decimalSeparator = ".") : this(fileName, noOfVariables, orderM, orderP, separator, stochasticDomain, decimalSeparator) { this.memoizer = memoizer; } private double GetBasisCoefficientInternal(double[] coordinates, int order) { if (order == -1) return 1; double f = 1; if (memoizer == null || memoizer.Exists(coordinates, order) == false) { f = covarianceGaussian * Math.Sqrt(eigs[order]); for (int i = 0; i < varianceAxes.Length; i++) { int index = evpPos[order, varianceAxes[i]]; double w = evp[i][index - 1, 0]; double l = evp[i][index - 1, 1]; double a = evp[i][index - 1, 2]; double x = coordinates[varianceAxes[i]] - translations[varianceAxes[i]]; f *= index % 2 == 0 ? a * Math.Sin(w * x) : a * Math.Cos(w * x); } if (memoizer != null) memoizer.SetCoefficient(coordinates, order, f); } else f = memoizer.GetCoefficient(coordinates, order); f += meanGaussian; return f; } private double GetCoefficientInternal(double meanValue, double[] coordinates, int o) { Debug.WriteLine("Order: " + o.ToString()); if (o < 0) return meanValue; int order = o + 1; double l_n = meanValue; for (int i = 0; i < calculator.PsiBasis[order].Length; i++) if (calculator.PsiBasis[order][i] > 0) l_n *= Math.Pow(GetBasisCoefficientInternal(coordinates, i), calculator.PsiBasis[order][i]); return l_n / calculator.PsiSquareNorm[order]; } #region IStochasticCoefficientsProvider Members double IStochasticCoefficientsProvider.GetCoefficient(double meanValue, double[] coordinates) { return GetCoefficientInternal(meanValue, coordinates, CurrentOrder); } #endregion #region IStochasticMaterialCoefficientsProvider Members double IStochasticMaterialCoefficientsProvider.GetCoefficient(double meanValue, double[] coordinates) { // Possibly erroneous. Check with Giovanis. double result = 0; for (int i = 0; i < RandomVariables.Length; i++) result += RandomVariables[i] * GetCoefficientInternal(meanValue, coordinates, i); return Math.Exp(result) - mean; } #endregion } }
44.611765
235
0.592695
[ "Apache-2.0" ]
Ambros21/MSolve
ISAAR.MSolve.PreProcessor/Stochastic/LognormalPCFileStochasticCoefficientsProvider.cs
7,586
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; namespace TreeGP { public class Constants { /// <summary>Maximum log on the machine.</summary> public const double LogMax = 7.09782712893383996732E2; /// <summary>Square root of 2: sqrt(2).</summary> public const double Sqrt2 = 1.4142135623730950488016887; /// <summary>Square root of twice number pi: sqrt(2*ฯ€).</summary> public const double Sqrt2PI = 2.50662827463100050242E0; /// <summary>Log of number pi: log(pi).</summary> public const double LogPI = 1.14472988584940017414; } }
27.208333
73
0.664625
[ "MIT" ]
chen0040/cs-tree-genetic-programming
cs-tree-genetic-programming/Constants.cs
656
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Game.Items.Weapons { abstract class Weapon : Item { public int Damage { get; protected set; } } }
17.571429
49
0.703252
[ "MIT" ]
Rinkton/console_game-forest_demon
NewRpgGame/Game/Items/Weapons/Weapon.cs
248
C#
๏ปฟusing System; using DynamicData.Tests.Domain; using FluentAssertions; using Xunit; namespace DynamicData.Tests { public class EnumerableExFixtures { private readonly Person _person1 = new Person("One", 1); private readonly Person _person2 = new Person("Two", 2); private readonly Person _person3 = new Person("Three", 3); [Fact] public void CanConvertToObservableChangeSetList() { var source = new[] {_person1, _person2, _person3}; var changeSet = source.AsObservableChangeSet(x => x.Age) .AsObservableCache(); changeSet.Items.ShouldBeEquivalentTo(source); } [Fact] public void CanConvertToObservableChangeSetCache() { var source = new[] {_person1, _person2, _person3}; var changeSet = source.AsObservableChangeSet() .AsObservableList(); changeSet.Items.ShouldBeEquivalentTo(source); } [Theory] [InlineData(true)] [InlineData(false)] public void RespectsCompleteConfigurationForList(bool shouldComplete) { var completed = false; var source = new[] {_person1, _person2, _person3}; using (source.AsObservableChangeSet(shouldComplete) .Subscribe(_ => { }, () => completed = true)) { Assert.Equal(completed, shouldComplete); } } [Theory] [InlineData(true)] [InlineData(false)] public void RespectsCompleteConfigurationForCache(bool shouldComplete) { var completed = false; var source = new[] {_person1, _person2, _person3}; using (source.AsObservableChangeSet(x => x.Age, shouldComplete) .Subscribe(_ => { }, () => completed = true)) { Assert.Equal(completed, shouldComplete); } } } }
32.833333
78
0.57665
[ "MIT" ]
CaseNewmark/DynamicData
src/DynamicData.Tests/EnumerableExFixtures.cs
1,972
C#
๏ปฟusing EddiDataDefinitions; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EddiEvents { public class ShipSoldEvent : Event { public const string NAME = "Ship sold"; public const string DESCRIPTION = "Triggered when you sell a ship"; public const string SAMPLE = "{\"timestamp\":\"2016-06-10T14:32:03Z\",\"event\":\"ShipyardSell\",\"ShipType\":\"Adder\",\"SellShipID\":1,\"ShipPrice\":25000}"; public static Dictionary<string, string> VARIABLES = new Dictionary<string, string>(); static ShipSoldEvent() { VARIABLES.Add("shipid", "The ID of the ship that was sold"); VARIABLES.Add("ship", "The ship that was sold"); VARIABLES.Add("price", "The price for which the ship was sold"); } [JsonProperty("shipid")] public int? shipid { get; private set; } [JsonProperty("ship")] public string ship { get; private set; } [JsonIgnore] public Ship Ship { get; private set; } [JsonProperty("price")] public long price { get; private set; } public ShipSoldEvent(DateTime timestamp, Ship ship, long price) : base(timestamp, NAME) { this.Ship = ship; this.ship = (ship == null ? null : ship.model); this.shipid = (ship == null ? (int?)null : ship.LocalId); this.price = price; } } }
32.978261
167
0.603823
[ "Apache-2.0" ]
draconas1/EDDIWithMissionTrack
Events/ShipSoldEvent.cs
1,519
C#
using System; using System.Net.Http; using System.Collections.Generic; using System.Threading.Tasks; using System.Text; using Microsoft.AspNetCore.Components.WebAssembly.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Fullstack.Client { public class Program { public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add<App>("app"); builder.Services.AddTransient(sp => new HttpClient { BaseAddress = new Uri(builder.HostEnvironment.BaseAddress) }); await builder.Build().RunAsync(); } } }
28.653846
127
0.716779
[ "MIT" ]
hubity/PostManager-dotnet
Client/Program.cs
745
C#
๏ปฟusing System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using ThScoreFileConverter.Models; using ThScoreFileConverter.Models.Th13; using IClearData = ThScoreFileConverter.Models.Th13.IClearData< ThScoreFileConverter.Models.Th13.CharaWithTotal, ThScoreFileConverter.Models.Th13.LevelPractice, ThScoreFileConverter.Models.Th13.LevelPractice, ThScoreFileConverter.Models.Th13.LevelPracticeWithTotal, ThScoreFileConverter.Models.Th13.StagePractice, ThScoreFileConverter.Models.Th10.IScoreData<ThScoreFileConverter.Models.Th13.StageProgress>>; using IPractice = ThScoreFileConverter.Models.Th10.IPractice; namespace ThScoreFileConverterTests.Models.Th13 { [TestClass] public class PracticeReplacerTests { internal static IReadOnlyDictionary<CharaWithTotal, IClearData> ClearDataDictionary { get; } = new[] { ClearDataTests.MockClearData().Object }.ToDictionary(clearData => clearData.Chara); private static Mock<INumberFormatter> MockNumberFormatter() { var mock = new Mock<INumberFormatter>(); _ = mock.Setup(formatter => formatter.FormatNumber(It.IsAny<It.IsValueType>())) .Returns((object value) => "invoked: " + value.ToString()); return mock; } [TestMethod] public void PracticeReplacerTest() { var formatterMock = MockNumberFormatter(); var replacer = new PracticeReplacer(ClearDataDictionary, formatterMock.Object); Assert.IsNotNull(replacer); } [TestMethod] public void PracticeReplacerTestEmpty() { var dictionary = ImmutableDictionary<CharaWithTotal, IClearData>.Empty; var formatterMock = MockNumberFormatter(); var replacer = new PracticeReplacer(dictionary, formatterMock.Object); Assert.IsNotNull(replacer); } [TestMethod] public void ReplaceTest() { var formatterMock = MockNumberFormatter(); var replacer = new PracticeReplacer(ClearDataDictionary, formatterMock.Object); Assert.AreEqual("invoked: 1234360", replacer.Replace("%T13PRACHMR3")); } [TestMethod] public void ReplaceTestLevelExtra() { var formatterMock = MockNumberFormatter(); var replacer = new PracticeReplacer(ClearDataDictionary, formatterMock.Object); Assert.AreEqual("%T13PRACXMR3", replacer.Replace("%T13PRACXMR3")); } [TestMethod] public void ReplaceTestLevelOverDrive() { var formatterMock = MockNumberFormatter(); var replacer = new PracticeReplacer(ClearDataDictionary, formatterMock.Object); Assert.AreEqual("%T13PRACDMR3", replacer.Replace("%T13PRACDMR3")); } [TestMethod] public void ReplaceTestStageExtra() { var formatterMock = MockNumberFormatter(); var replacer = new PracticeReplacer(ClearDataDictionary, formatterMock.Object); Assert.AreEqual("%T13PRACHMRX", replacer.Replace("%T13PRACHMRX")); } [TestMethod] public void ReplaceTestStageOverDrive() { var formatterMock = MockNumberFormatter(); var replacer = new PracticeReplacer(ClearDataDictionary, formatterMock.Object); Assert.AreEqual("%T13PRACHMRD", replacer.Replace("%T13PRACHMRD")); } [TestMethod] public void ReplaceTestEmpty() { var dictionary = ImmutableDictionary<CharaWithTotal, IClearData>.Empty; var formatterMock = MockNumberFormatter(); var replacer = new PracticeReplacer(dictionary, formatterMock.Object); Assert.AreEqual("invoked: 0", replacer.Replace("%T13PRACHMR3")); } [TestMethod] public void ReplaceTestEmptyPractices() { var dictionary = new[] { Mock.Of<IClearData>( m => (m.Chara == CharaWithTotal.Marisa) && (m.Practices == ImmutableDictionary<(LevelPractice, StagePractice), IPractice>.Empty)) }.ToDictionary(clearData => clearData.Chara); var formatterMock = MockNumberFormatter(); var replacer = new PracticeReplacer(dictionary, formatterMock.Object); Assert.AreEqual("invoked: 0", replacer.Replace("%T13PRACHMR3")); } [TestMethod] public void ReplaceTestInvalidFormat() { var formatterMock = MockNumberFormatter(); var replacer = new PracticeReplacer(ClearDataDictionary, formatterMock.Object); Assert.AreEqual("%T13XXXXHMR3", replacer.Replace("%T13XXXXHMR3")); } [TestMethod] public void ReplaceTestInvalidLevel() { var formatterMock = MockNumberFormatter(); var replacer = new PracticeReplacer(ClearDataDictionary, formatterMock.Object); Assert.AreEqual("%T13PRACYMR3", replacer.Replace("%T13PRACYMR3")); } [TestMethod] public void ReplaceTestInvalidChara() { var formatterMock = MockNumberFormatter(); var replacer = new PracticeReplacer(ClearDataDictionary, formatterMock.Object); Assert.AreEqual("%T13PRACHXX3", replacer.Replace("%T13PRACHXX3")); } [TestMethod] public void ReplaceTestInvalidStage() { var formatterMock = MockNumberFormatter(); var replacer = new PracticeReplacer(ClearDataDictionary, formatterMock.Object); Assert.AreEqual("%T13PRACHMRY", replacer.Replace("%T13PRACHMRY")); } } }
39.673469
114
0.647977
[ "BSD-2-Clause" ]
armadillo-winX/ThScoreFileConverter
ThScoreFileConverterTests/Models/Th13/PracticeReplacerTests.cs
5,834
C#
๏ปฟusing static System.Console; namespace Debugging { class Program { static double Add(double a, double b) { return a + b; // deliberate bug! } static void Main(string[] args) { double a = 4.5; // or use var double b = 2.5; double answer = Add(a, b); WriteLine($"{a} + {b} = {answer}"); ReadLine(); // wait for user to press ENTER } } }
20.142857
50
0.51773
[ "MIT" ]
PacktPublishing/CSharp-8.0-and-.NET-Core-3.0-Modern-Cross-Platform-Development-Third-Edition
Chapter04/Debugging/Program.cs
425
C#
๏ปฟusing System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("RethinkDb.Newtonsoft")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RethinkDb.Newtonsoft")] [assembly: AssemblyCopyright("Copyright ยฉ 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("45266f00-0e2e-463e-8497-18d115afe669")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.9.1.0")] [assembly: AssemblyFileVersion("0.9.1.0")]
34.560976
84
0.744531
[ "Apache-2.0" ]
karlgrz/rethinkdb-net
rethinkdb-net-newtonsoft/Properties/AssemblyInfo.cs
1,420
C#
๏ปฟusing System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Threading; using TXTCommunication.Fischertechnik.Txt.Command; using TXTCommunication.Fischertechnik.Txt.Response; using TXTCommunication.Utils; namespace TXTCommunication.Fischertechnik.Txt { /// <summary> /// This class manages the TCP/IP communication between the TXT and us. /// </summary> class TxtCommunication : IDisposable { public bool Connected { get; private set; } private bool _requestedStop; private readonly IDictionary<string, string> _controllerNameCache; private Socket _socket; public TxtInterface TxtInterface { get; private set; } // We do all the network communication in one thread with this queue private readonly TaskQueue _networkingTaskQueue; public TxtCommunication(TxtInterface txtInterface) { TxtInterface = txtInterface; _networkingTaskQueue = new TaskQueue("TXT Communication"); _controllerNameCache = new ConcurrentDictionary<string, string>(); } public void OpenConnection() { if (Connected) { throw new InvalidOperationException("Already connected!"); } _requestedStop = false; Exception exception = null; _networkingTaskQueue.DoWorkInQueue(() => { try { var ipEndPoint = new IPEndPoint(IPAddress.Parse(TxtInterface.Ip), TxtInterface.ControllerIpPort); _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { SendTimeout = TxtInterface.TcpTimeout, ReceiveTimeout = TxtInterface.TcpTimeout }; _socket.Connect(ipEndPoint); Connected = _socket.Connected; } catch (Exception e) { Console.WriteLine(e.Message); exception = e; Connected = false; } }, true); if (exception != null) { Connected = false; throw exception; } } public void CloseConnection() { if (!Connected) { throw new InvalidOperationException("Not connected!"); } _requestedStop = true; Exception exception = null; _networkingTaskQueue.DoWorkInQueue(() => { try { _socket.Shutdown(SocketShutdown.Both); _socket.Close(); Connected = false; } catch (SocketException e) { Console.WriteLine(e.Message); exception = e; Connected = false; } }, true); if (exception != null) { Connected = false; throw exception; } } public void SendCommand(CommandBase command, ResponseBase response) { Exception exception = null; _networkingTaskQueue.DoWorkInQueue(() => { try { // Send the command _socket.Send(command.GetByteArray()); var responseBytes = new byte[response.GetResponseLength()]; // Receive the response Receive(_socket, responseBytes, responseBytes.Length); uint responseId = BitConverter.ToUInt32(responseBytes, 0); if (responseId != response.ResponseId) { // Set an exception when the received response id is not the same as the expected response id // The exception is thrown at the end exception = new InvalidOperationException( $"The response id ({responseId}) is not the same response id ({response.ResponseId}) as expected"); } else { // Set the values of the given response object response.FromByteArray(responseBytes); } } catch (Exception ex) { Console.WriteLine(ex.Message); exception = ex; } }, true); if (exception != null) { if (!(exception is InvalidOperationException)) { Connected = false; } throw exception; } } private int Receive(Socket socket, byte[] buffer, int count) { // Wait until enough bytes are received while (socket.Available < count && !_requestedStop) { Thread.Sleep(5); } return socket.Receive(buffer, 0, count, SocketFlags.None); } public string RequestControllerName(string address) { // If we cached the address already: return the controller name if (_controllerNameCache.ContainsKey(address)) { return _controllerNameCache[address]; } try { // Connect to the interface var ipEndPoint = new IPEndPoint(IPAddress.Parse(address), TxtInterface.ControllerIpPort); var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) { SendTimeout = 1000, ReceiveTimeout = 1000 }; socket.Connect(ipEndPoint); // Send the command socket.Send(new CommandQueryStatus().GetByteArray()); var response = new ResponseQueryStatus(); var responseBytes = new byte[response.GetResponseLength()]; // Receive the response Receive(socket, responseBytes, responseBytes.Length); // Close the socket socket.Shutdown(SocketShutdown.Both); socket.Close(); socket.Dispose(); // Process the response response.FromByteArray(responseBytes); _controllerNameCache.Add(address, response.GetControllerName()); return response.GetControllerName(); } catch (Exception) { return string.Empty; } } public bool IsValidInterface(string address) { return !string.IsNullOrEmpty(RequestControllerName(address)); } public void Dispose() { // Close the connection before disposing the task queue if (Connected) { CloseConnection(); } ((IDisposable) _networkingTaskQueue).Dispose(); ((IDisposable) _socket).Dispose(); } } }
30.481781
131
0.496879
[ "MIT" ]
Bennik2000/FtApp
FtApp/FtApp/Fischertechnik/Txt/TxtCommunication.cs
7,531
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * 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 the OpenSimulator Project 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 DEVELOPERS ``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 CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using log4net; using Mono.Addins; using NDesk.Options; using Nini.Config; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Framework.Monitoring; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using GridRegion = OpenSim.Services.Interfaces.GridRegion; namespace OpenSim.Region.CoreModules.World.Objects.Commands { /// <summary> /// A module that holds commands for manipulating objects in the scene. /// </summary> [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule", Id = "RegionCommandsModule")] public class RegionCommandsModule : INonSharedRegionModule { private Scene m_scene; private ICommandConsole m_console; public string Name { get { return "Region Commands Module"; } } public Type ReplaceableInterface { get { return null; } } public void Initialise(IConfigSource source) { // m_log.DebugFormat("[REGION COMMANDS MODULE]: INITIALIZED MODULE"); } public void PostInitialise() { // m_log.DebugFormat("[REGION COMMANDS MODULE]: POST INITIALIZED MODULE"); } public void Close() { // m_log.DebugFormat("[REGION COMMANDS MODULE]: CLOSED MODULE"); } public void AddRegion(Scene scene) { // m_log.DebugFormat("[REGION COMMANDS MODULE]: REGION {0} ADDED", scene.RegionInfo.RegionName); m_scene = scene; m_console = MainConsole.Instance; m_console.Commands.AddCommand( "Regions", false, "show scene", "show scene", "Show live information for the currently selected scene (fps, prims, etc.).", HandleShowScene); m_console.Commands.AddCommand( "Regions", false, "show region", "show region", "Show control information for the currently selected region (host name, max physical prim size, etc).", "A synonym for \"region get\"", HandleShowRegion); m_console.Commands.AddCommand( "Regions", false, "region get", "region get", "Show control information for the currently selected region (host name, max physical prim size, etc).", "Some parameters can be set with the \"region set\" command.\n" + "Others must be changed via a viewer (usually via the region/estate dialog box).", HandleShowRegion); m_console.Commands.AddCommand( "Regions", false, "region set", "region set", "Set control information for the currently selected region.", "Currently, the following parameters can be set:\n" + "agent-limit <int> - Current root agent limit. This is persisted over restart.\n" + "max-agent-limit <int> - Maximum root agent limit. agent-limit cannot exceed this." + " This is not persisted over restart - to set it every time you must add a MaxAgents entry to your regions file.", HandleRegionSet); m_console.Commands.AddCommand("Regions", false, "show neighbours", "show neighbours", "Shows the local region neighbours", HandleShowNeighboursCommand); m_console.Commands.AddCommand("Regions", false, "show regionsinview", "show regionsinview", "Shows regions that can be seen from a region", HandleShowRegionsInViewCommand); } public void RemoveRegion(Scene scene) { // m_log.DebugFormat("[REGION COMMANDS MODULE]: REGION {0} REMOVED", scene.RegionInfo.RegionName); } public void RegionLoaded(Scene scene) { // m_log.DebugFormat("[REGION COMMANDS MODULE]: REGION {0} LOADED", scene.RegionInfo.RegionName); } private void HandleShowRegion(string module, string[] cmd) { if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_scene)) return; RegionInfo ri = m_scene.RegionInfo; RegionSettings rs = ri.RegionSettings; StringBuilder sb = new StringBuilder(); sb.AppendFormat("Region information for {0}\n", m_scene.Name); ConsoleDisplayList dispList = new ConsoleDisplayList(); dispList.AddRow("Region ID", ri.RegionID); dispList.AddRow("Region handle", ri.RegionHandle); dispList.AddRow("Region location", string.Format("{0},{1}", ri.RegionLocX, ri.RegionLocY)); dispList.AddRow("Region size", string.Format("{0}x{1}", ri.RegionSizeX, ri.RegionSizeY)); //dispList.AddRow("Region type", ri.RegionType); dispList.AddRow("Maturity", rs.Maturity); dispList.AddRow("Region address", ri.ServerURI); dispList.AddRow("From region file", ri.RegionFile); dispList.AddRow("External endpoint", ri.ExternalEndPoint); dispList.AddRow("Internal endpoint", ri.InternalEndPoint); dispList.AddRow("Access level", ri.AccessLevel); dispList.AddRow("Agent limit", rs.AgentLimit); dispList.AddRow("Max agent limit", ri.AgentCapacity); dispList.AddRow("Linkset capacity", ri.LinksetCapacity <= 0 ? "not set" : ri.LinksetCapacity.ToString()); dispList.AddRow("Prim capacity", ri.ObjectCapacity); dispList.AddRow("Prim bonus", rs.ObjectBonus); dispList.AddRow("Max prims per user", ri.MaxPrimsPerUser < 0 ? "n/a" : ri.MaxPrimsPerUser.ToString()); dispList.AddRow("Clamp prim size", ri.ClampPrimSize); dispList.AddRow("Non physical prim min size", ri.NonphysPrimMin <= 0 ? "not set" : string.Format("{0} m", ri.NonphysPrimMin)); dispList.AddRow("Non physical prim max size", ri.NonphysPrimMax <= 0 ? "not set" : string.Format("{0} m", ri.NonphysPrimMax)); dispList.AddRow("Physical prim min size", ri.PhysPrimMin <= 0 ? "not set" : string.Format("{0} m", ri.PhysPrimMin)); dispList.AddRow("Physical prim max size", ri.PhysPrimMax <= 0 ? "not set" : string.Format("{0} m", ri.PhysPrimMax)); dispList.AddRow("Allow Damage", rs.AllowDamage); dispList.AddRow("Allow Land join/divide", rs.AllowLandJoinDivide); dispList.AddRow("Allow land resell", rs.AllowLandResell); dispList.AddRow("Block fly", rs.BlockFly); dispList.AddRow("Block show in search", rs.BlockShowInSearch); dispList.AddRow("Block terraform", rs.BlockTerraform); dispList.AddRow("Covenant UUID", rs.Covenant); dispList.AddRow("Convenant change Unix time", rs.CovenantChangedDateTime); dispList.AddRow("Disable collisions", rs.DisableCollisions); dispList.AddRow("Disable physics", rs.DisablePhysics); dispList.AddRow("Disable scripts", rs.DisableScripts); dispList.AddRow("Restrict pushing", rs.RestrictPushing); dispList.AddRow("Fixed sun", rs.FixedSun); dispList.AddRow("Sun position", rs.SunPosition); dispList.AddRow("Sun vector", rs.SunVector); dispList.AddRow("Use estate sun", rs.UseEstateSun); dispList.AddRow("Telehub UUID", rs.TelehubObject); dispList.AddRow("Terrain lower limit", string.Format("{0} m", rs.TerrainLowerLimit)); dispList.AddRow("Terrain raise limit", string.Format("{0} m", rs.TerrainRaiseLimit)); dispList.AddRow("Water height", string.Format("{0} m", rs.WaterHeight)); dispList.AddRow("Maptile static file", ri.MaptileStaticFile); dispList.AddRow("Maptile static UUID", ri.MaptileStaticUUID); dispList.AddRow("Last map refresh", ri.lastMapRefresh); dispList.AddRow("Last map UUID", ri.lastMapUUID); dispList.AddToStringBuilder(sb); MainConsole.Instance.Output(sb.ToString()); } private void HandleRegionSet(string module, string[] args) { if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_scene)) return; if (args.Length != 4) { MainConsole.Instance.OutputFormat("Usage: region set <param> <value>"); return; } string param = args[2]; string rawValue = args[3]; if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_scene)) return; RegionInfo ri = m_scene.RegionInfo; RegionSettings rs = ri.RegionSettings; if (param == "agent-limit") { int newValue; if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, rawValue, out newValue)) return; if (newValue > ri.AgentCapacity) { MainConsole.Instance.OutputFormat( "Cannot set {0} to {1} in {2} as max-agent-limit is {3}", "agent-limit", newValue, m_scene.Name, ri.AgentCapacity); } else { rs.AgentLimit = newValue; MainConsole.Instance.OutputFormat( "{0} set to {1} in {2}", "agent-limit", newValue, m_scene.Name); } rs.Save(); } else if (param == "max-agent-limit") { int newValue; if (!ConsoleUtil.TryParseConsoleNaturalInt(MainConsole.Instance, rawValue, out newValue)) return; ri.AgentCapacity = newValue; MainConsole.Instance.OutputFormat( "{0} set to {1} in {2}", "max-agent-limit", newValue, m_scene.Name); if (ri.AgentCapacity < rs.AgentLimit) { rs.AgentLimit = ri.AgentCapacity; MainConsole.Instance.OutputFormat( "Reducing {0} to {1} in {2}", "agent-limit", rs.AgentLimit, m_scene.Name); } rs.Save(); } } private void HandleShowScene(string module, string[] cmd) { if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_scene)) return; SimStatsReporter r = m_scene.StatsReporter; float[] stats = r.LastReportedSimStats; float timeDilation = stats[0]; float simFps = stats[1]; float physicsFps = stats[2]; float agentUpdates = stats[3]; float rootAgents = stats[4]; float childAgents = stats[5]; float totalPrims = stats[6]; float activePrims = stats[7]; float totalFrameTime = stats[8]; // float netFrameTime = stats.StatsBlock[9].StatValue; // Ignored - not used by OpenSimulator float physicsFrameTime = stats[10]; float otherFrameTime = stats[12]; // float imageFrameTime = stats.StatsBlock[11].StatValue; // Ignored float inPacketsPerSecond = stats[13]; float outPacketsPerSecond = stats[14]; float unackedBytes = stats[15]; // float agentFrameTime = stats.StatsBlock[16].StatValue; // Not really used float pendingDownloads = stats[17]; float pendingUploads = stats[18]; float activeScripts = stats[19]; float scriptLinesPerSecond = stats[23]; StringBuilder sb = new StringBuilder(); sb.AppendFormat("Scene statistics for {0}\n", m_scene.RegionInfo.RegionName); ConsoleDisplayList dispList = new ConsoleDisplayList(); dispList.AddRow("Time Dilation", timeDilation); dispList.AddRow("Sim FPS", simFps); dispList.AddRow("Physics FPS", physicsFps); dispList.AddRow("Avatars", rootAgents); dispList.AddRow("Child agents", childAgents); dispList.AddRow("Total prims", totalPrims); dispList.AddRow("Scripts", activeScripts); dispList.AddRow("Script lines processed per second", scriptLinesPerSecond); dispList.AddRow("Physics enabled prims", activePrims); dispList.AddRow("Total frame time", totalFrameTime); dispList.AddRow("Physics frame time", physicsFrameTime); dispList.AddRow("Other frame time", otherFrameTime); dispList.AddRow("Agent Updates per second", agentUpdates); dispList.AddRow("Packets processed from clients per second", inPacketsPerSecond); dispList.AddRow("Packets sent to clients per second", outPacketsPerSecond); dispList.AddRow("Bytes unacknowledged by clients", unackedBytes); dispList.AddRow("Pending asset downloads to clients", pendingDownloads); dispList.AddRow("Pending asset uploads from clients", pendingUploads); dispList.AddToStringBuilder(sb); MainConsole.Instance.Output(sb.ToString()); } public void HandleShowNeighboursCommand(string module, string[] cmdparams) { if(m_scene == null) return; if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_scene)) return; System.Text.StringBuilder caps = new System.Text.StringBuilder(); RegionInfo sr = m_scene.RegionInfo; caps.AppendFormat("*** Neighbours of {0} ({1}) ***\n", sr.RegionName, sr.RegionID); List<GridRegion> regions = m_scene.GridService.GetNeighbours(sr.ScopeID, sr.RegionID); foreach (GridRegion r in regions) caps.AppendFormat(" {0} @ {1}-{2}\n", r.RegionName, Util.WorldToRegionLoc((uint)r.RegionLocX), Util.WorldToRegionLoc((uint)r.RegionLocY)); MainConsole.Instance.Output(caps.ToString()); } public void HandleShowRegionsInViewCommand(string module, string[] cmdparams) { if(m_scene == null) return; if (!(MainConsole.Instance.ConsoleScene == null || MainConsole.Instance.ConsoleScene == m_scene)) return; System.Text.StringBuilder caps = new System.Text.StringBuilder(); int maxview = (int)m_scene.MaxRegionViewDistance; RegionInfo sr = m_scene.RegionInfo; caps.AppendFormat("*** Regions that can be seen from {0} ({1}) (MaxRegionViewDistance {2}m) ***\n", sr.RegionName, sr.RegionID, maxview); int startX = (int)sr.WorldLocX; int endX = startX + (int)sr.RegionSizeX; int startY = (int)sr.WorldLocY; int endY = startY + (int)sr.RegionSizeY; startX -= maxview; if(startX < 0 ) startX = 0; startY -= maxview; if(startY < 0) startY = 0; endX += maxview; endY += maxview; List<GridRegion> regions = m_scene.GridService.GetRegionRange(sr.ScopeID, startX, endX, startY, endY); foreach (GridRegion r in regions) { if(r.RegionHandle == sr.RegionHandle) continue; caps.AppendFormat(" {0} @ {1}-{2}\n", r.RegionName, Util.WorldToRegionLoc((uint)r.RegionLocX), Util.WorldToRegionLoc((uint)r.RegionLocY)); } MainConsole.Instance.Output(caps.ToString()); } } }
46.986807
161
0.603324
[ "BSD-3-Clause" ]
SignpostMarv/opensim
OpenSim/Region/CoreModules/World/Region/RegionCommandsModule.cs
17,808
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace StarterProject.Web.Api { public class Startup { public Startup(IHostingEnvironment env) { var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } public IConfigurationRoot Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // Add framework services. services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); app.UseMvc(); } } }
32.673913
109
0.669993
[ "MIT" ]
LHGames-2017/AtLeastYouTried
LHGames/Startup.cs
1,505
C#
๏ปฟusing Firk.Core; namespace Movselex.Core.Models { public interface IMovselexAppConfig : IAppConfig { string MpcExePath { get; } int ScreenNo { get; } bool IsFullScreen { get; } } }
19.818182
52
0.619266
[ "MIT" ]
finalstream/Movselex
Movselex.Core/Models/IMovselexAppConfig.cs
220
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System.Collections; using System.ComponentModel; using System.Diagnostics; namespace System.Windows.Forms { /// <summary> /// A collection of listview groups. /// </summary> [ListBindable(false)] public class ListViewGroupCollection : IList { private readonly ListView _listView; private ArrayList _list; internal ListViewGroupCollection(ListView listView) { _listView = listView; } public int Count => List.Count; object ICollection.SyncRoot => this; bool ICollection.IsSynchronized => true; bool IList.IsFixedSize => false; bool IList.IsReadOnly => false; private ArrayList List => _list ?? (_list = new ArrayList()); public ListViewGroup this[int index] { get => (ListViewGroup)List[index]; set { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (List.Contains(value)) { return; } CheckListViewItems(value); value.ListView = _listView; List[index] = value; } } public ListViewGroup this[string key] { get { if (_list == null) { return null; } for (int i = 0; i < _list.Count; i++) { if (string.Equals(key, this[i].Name, StringComparison.CurrentCulture)) { return this[i]; } } return null; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (_list == null) { // nothing to do return; } int index = -1; for (int i = 0; i < _list.Count; i++) { if (string.Equals(key, this[i].Name, StringComparison.CurrentCulture)) { index = i; break; } } if (index != -1) { _list[index] = value; } } } object IList.this[int index] { get => this[index]; set { if (value is ListViewGroup group) { this[index] = group; } } } public int Add(ListViewGroup group) { if (group == null) { throw new ArgumentNullException(nameof(group)); } if (Contains(group)) { return -1; } CheckListViewItems(group); group.ListView = _listView; int index = List.Add(group); if (_listView.IsHandleCreated) { _listView.InsertGroupInListView(List.Count, group); MoveGroupItems(group); } return index; } public ListViewGroup Add(string key, string headerText) { ListViewGroup group = new ListViewGroup(key, headerText); Add(group); return group; } int IList.Add(object value) { if (!(value is ListViewGroup group)) { throw new ArgumentException(SR.ListViewGroupCollectionBadListViewGroup, nameof(value)); } return Add(group); } public void AddRange(ListViewGroup[] groups) { if (groups == null) { throw new ArgumentNullException(nameof(groups)); } for (int i = 0; i < groups.Length; i++) { Add(groups[i]); } } public void AddRange(ListViewGroupCollection groups) { if (groups == null) { throw new ArgumentNullException(nameof(groups)); } for (int i = 0; i < groups.Count; i++) { Add(groups[i]); } } private void CheckListViewItems(ListViewGroup group) { for (int i = 0; i < group.Items.Count; i++) { ListViewItem item = group.Items[i]; if (item.ListView != null && item.ListView != _listView) { throw new ArgumentException(string.Format(SR.OnlyOneControl, item.Text)); } } } public void Clear() { if (_listView.IsHandleCreated) { for (int i = 0; i < Count; i++) { _listView.RemoveGroupFromListView(this[i]); } } // Dissociate groups from the ListView for (int i = 0; i < Count; i++) { this[i].ListView = null; } List.Clear(); // we have to tell the listView that there are no more groups // so the list view knows to remove items from the default group _listView.UpdateGroupView(); } public bool Contains(ListViewGroup value) => List.Contains(value); bool IList.Contains(object value) { if (!(value is ListViewGroup group)) { return false; } return Contains(group); } public void CopyTo(Array array, int index) => List.CopyTo(array, index); public IEnumerator GetEnumerator() => List.GetEnumerator(); public int IndexOf(ListViewGroup value) => List.IndexOf(value); int IList.IndexOf(object value) { if (!(value is ListViewGroup group)) { return -1; } return IndexOf((ListViewGroup)value); } public void Insert(int index, ListViewGroup group) { if (group == null) { throw new ArgumentNullException(nameof(group)); } if (Contains(group)) { return; } CheckListViewItems(group); group.ListView = _listView; List.Insert(index, group); if (_listView.IsHandleCreated) { _listView.InsertGroupInListView(index, group); MoveGroupItems(group); } } void IList.Insert(int index, object value) { if (value is ListViewGroup group) { Insert(index, group); } } private void MoveGroupItems(ListViewGroup group) { Debug.Assert(_listView.IsHandleCreated, "MoveGroupItems pre-condition: listView handle must be created"); foreach (ListViewItem item in group.Items) { if (item.ListView == _listView) { item.UpdateStateToListView(item.Index); } } } public void Remove(ListViewGroup group) { group.ListView = null; List.Remove(group); if (_listView.IsHandleCreated) { _listView.RemoveGroupFromListView(group); } } void IList.Remove(object value) { if (value is ListViewGroup group) { Remove(group); } } public void RemoveAt(int index) => Remove(this[index]); } }
25.990536
117
0.451632
[ "MIT" ]
GrabYourPitchforks/winforms
src/System.Windows.Forms/src/System/Windows/Forms/ListViewGroupCollection.cs
8,239
C#
๏ปฟusing System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using WDE.Common.Database; using WDE.Common.Services.MessageBox; using WDE.MVVM.Observable; using WDE.SmartScriptEditor.Data; using WDE.SmartScriptEditor.Models.Helpers; namespace WDE.SmartScriptEditor.Models { public abstract class SmartScriptBase { protected readonly ISmartFactory smartFactory; protected readonly ISmartDataManager smartDataManager; protected readonly IMessageBoxService messageBoxService; public readonly ObservableCollection<SmartEvent> Events; private readonly SmartSelectionHelper selectionHelper; public abstract SmartScriptType SourceType { get; } public event Action? ScriptSelectedChanged; public event Action<SmartEvent?, SmartAction?, EventChangedMask>? EventChanged; public ObservableCollection<object> AllSmartObjectsFlat { get; } public ObservableCollection<SmartAction> AllActions { get; } public ObservableCollection<GlobalVariable> GlobalVariables { get; } = new(); ~SmartScriptBase() { selectionHelper.Dispose(); } public SmartGenericJsonData GetEventData(SmartEvent e) => smartDataManager.GetRawData(SmartType.SmartEvent, e.Id); public SmartGenericJsonData? TryGetEventData(SmartEvent e) => smartDataManager.Contains(SmartType.SmartEvent, e.Id) ? smartDataManager.GetRawData(SmartType.SmartEvent, e.Id) : null; public SmartGenericJsonData? TryGetSourceData(SmartSource s) => smartDataManager.Contains(SmartType.SmartSource, s.Id) ? smartDataManager.GetRawData(SmartType.SmartSource, s.Id) : null; public SmartGenericJsonData? TryGetTargetData(SmartTarget t) => smartDataManager.Contains(SmartType.SmartTarget, t.Id) ? smartDataManager.GetRawData(SmartType.SmartTarget, t.Id) : null; public SmartScriptBase(ISmartFactory smartFactory, ISmartDataManager smartDataManager, IMessageBoxService messageBoxService) { this.smartFactory = smartFactory; this.smartDataManager = smartDataManager; this.messageBoxService = messageBoxService; Events = new ObservableCollection<SmartEvent>(); selectionHelper = new SmartSelectionHelper(this); selectionHelper.ScriptSelectedChanged += CallScriptSelectedChanged; selectionHelper.EventChanged += (e, a, mask) => { RenumerateEvents(); EventChanged?.Invoke(e, a, mask); }; AllSmartObjectsFlat = selectionHelper.AllSmartObjectsFlat; AllActions = selectionHelper.AllActions; Events.ToStream(false) .Subscribe((e) => { if (e.Type == CollectionEventType.Add) e.Item.Parent = this; }); GlobalVariables.ToStream(true).Subscribe(e => { GlobalVariableChanged(null, null); if (e.Type == CollectionEventType.Add) e.Item.PropertyChanged += GlobalVariableChanged; else e.Item.PropertyChanged -= GlobalVariableChanged; }); } private void GlobalVariableChanged(object? sender, PropertyChangedEventArgs? _) { foreach (var e in Events) e.InvalidateReadable(); } private void RenumerateEvents() { int index = 1; foreach (var e in Events) { e.LineId = index; if (e.Actions.Count == 0) { index++; } else { int indent = 0; foreach (var a in e.Actions) { if (a.ActionFlags.HasFlag(ActionFlags.DecreaseIndent) && indent > 0) indent--; a.Indent = indent; if (a.ActionFlags.HasFlag(ActionFlags.IncreaseIndent)) indent++; a.LineId = index; index++; } } } } private void CallScriptSelectedChanged() { ScriptSelectedChanged?.Invoke(); } public List<SmartEvent> InsertFromClipboard(int index, IEnumerable<ISmartScriptLine> lines, IEnumerable<IConditionLine>? conditions) { List<SmartEvent> newEvents = new(); SmartEvent? currentEvent = null; var prevIndex = 0; var conds = ParseConditions(conditions); foreach (ISmartScriptLine line in lines) { if (currentEvent == null || prevIndex != line.Id) { prevIndex = line.Id; currentEvent = SafeEventFactory(line); if (currentEvent == null) continue; currentEvent.Parent = this; Events.Insert(index++, currentEvent); newEvents.Add(currentEvent); if (conds.TryGetValue(prevIndex, out var conditionList)) foreach (var cond in conditionList) currentEvent.Conditions.Add(cond); } if (line.ActionType != -1) { SmartAction? action = SafeActionFactory(line); if (action != null) { action.Comment = line.Comment.Contains(" // ") ? line.Comment.Substring(line.Comment.IndexOf(" // ") + 4).Trim() : ""; currentEvent.AddAction(action); } } } return newEvents; } public Dictionary<int, List<SmartCondition>> ParseConditions(IEnumerable<IConditionLine>? conditions) { Dictionary<int, List<SmartCondition>> conds = new(); if (conditions != null) { Dictionary<int, int> prevElseGroupPerLine = new(); foreach (IConditionLine line in conditions) { SmartCondition? condition = SafeConditionFactory(line); if (condition == null) continue; if (!conds.ContainsKey(line.SourceGroup - 1)) conds[line.SourceGroup - 1] = new List<SmartCondition>(); if (!prevElseGroupPerLine.TryGetValue(line.SourceGroup - 1, out var prevElseGroup)) prevElseGroup = prevElseGroupPerLine[line.SourceGroup - 1] = 0; if (prevElseGroup != line.ElseGroup && conds[line.SourceGroup - 1].Count > 0) { var or = SafeConditionFactory(-1); if (or != null) conds[line.SourceGroup - 1].Add(or); prevElseGroupPerLine[line.SourceGroup - 1] = line.ElseGroup; } conds[line.SourceGroup - 1].Add(condition); } } return conds; } public void SafeUpdateSource(SmartSource source, int targetId) { try { smartFactory.UpdateSource(source, targetId); } catch (Exception) { messageBoxService.ShowDialog(new MessageBoxFactory<bool>() .SetIcon(MessageBoxIcon.Error) .SetTitle("Unknown source") .SetMainInstruction($"Source {targetId} unknown, this may lead to invalid script opened!!") .Build()); } } public SmartAction? SafeActionFactory(int actionId, SmartSource source, SmartTarget target) { try { return smartFactory.ActionFactory(actionId, source, target); } catch (Exception) { messageBoxService.ShowDialog(new MessageBoxFactory<bool>() .SetIcon(MessageBoxIcon.Warning) .SetTitle("Unknown action") .SetMainInstruction($"Action {actionId} unknown, skipping action") .Build()); } return null; } public SmartAction? SafeActionFactory(ISmartScriptLine line) { try { return smartFactory.ActionFactory(line); } catch (Exception e) { messageBoxService.ShowDialog(new MessageBoxFactory<bool>() .SetIcon(MessageBoxIcon.Warning) .SetTitle("Unknown action") .SetMainInstruction("Skipping action: " + e.Message) .Build()); } return null; } public SmartCondition? SafeConditionFactory(IConditionLine line) { try { return smartFactory.ConditionFactory(line); } catch (Exception) { messageBoxService.ShowDialog(new MessageBoxFactory<bool>() .SetIcon(MessageBoxIcon.Warning) .SetTitle("Unknown condition") .SetMainInstruction($"Condition {line.ConditionType} unknown, skipping condition") .Build()); } return null; } public SmartCondition? SafeConditionFactory(int id) { try { return smartFactory.ConditionFactory(id); } catch (Exception) { messageBoxService.ShowDialog(new MessageBoxFactory<bool>() .SetIcon(MessageBoxIcon.Warning) .SetTitle("Unknown condition") .SetMainInstruction($"Condition {id} unknown, skipping condition") .Build()); } return null; } public SmartEvent? SafeEventFactory(ISmartScriptLine line) { try { return smartFactory.EventFactory(line); } catch (Exception) { messageBoxService.ShowDialog(new MessageBoxFactory<bool>() .SetIcon(MessageBoxIcon.Warning) .SetTitle("Unknown event") .SetMainInstruction($"Event {line.EventType} unknown, skipping event") .Build()); } return null; } public event Action BulkEditingStarted = delegate { }; public event Action<string> BulkEditingFinished = delegate { }; public IDisposable BulkEdit(string name) { return new BulkEditing(this, name); } private class BulkEditing : IDisposable { private readonly string name; private readonly SmartScriptBase smartScript; public BulkEditing(SmartScriptBase smartScript, string name) { this.smartScript = smartScript; this.name = name; this.smartScript.BulkEditingStarted.Invoke(); } public void Dispose() { smartScript.BulkEditingFinished.Invoke(name); } } } }
36.228916
140
0.516545
[ "Unlicense" ]
T1ti/WoWDatabaseEditor
WDE.SmartScriptEditor/Models/SmartScriptBase.cs
12,030
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Northwind.Dal.Abstract; using Northwind.Entities; namespace Northwind.Dal.Abstract.ICategory { public interface ICategoryDal { List<Category> GetAll(); } }
18.75
42
0.75
[ "MIT" ]
erhankiyakk/Northwind_ASP.NET
Northwind.Dal/Abstract/ICategory/ICategoryDal.cs
302
C#
๏ปฟusing System; using System.Collections.Generic; using System.Data; using System.Data.Common; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; using NewLife; using NewLife.Collections; using NewLife.Data; namespace XCode.DataAccessLayer { internal class PostgreSQL : RemoteDb { #region ๅฑžๆ€ง /// <summary>่ฟ”ๅ›žๆ•ฐๆฎๅบ“็ฑปๅž‹ใ€‚</summary> public override DatabaseType Type => DatabaseType.PostgreSQL; private static DbProviderFactory _Factory; /// <summary>ๅทฅๅŽ‚</summary> public override DbProviderFactory Factory { get { if (_Factory == null) { lock (typeof(PostgreSQL)) { if (_Factory == null) _Factory = GetProviderFactory("Npgsql.dll", "Npgsql.NpgsqlFactory"); } } return _Factory; } } const String Server_Key = "Server"; protected override void OnSetConnectionString(ConnectionStringBuilder builder) { base.OnSetConnectionString(builder); var key = builder[Server_Key]; if (key.EqualIgnoreCase(".", "localhost")) { //builder[Server_Key] = "127.0.0.1"; builder[Server_Key] = IPAddress.Loopback.ToString(); } //if (builder.TryGetValue("Database", out var db) && db != db.ToLower()) builder["Database"] = db.ToLower(); } #endregion #region ๆ–นๆณ• /// <summary>ๅˆ›ๅปบๆ•ฐๆฎๅบ“ไผš่ฏ</summary> /// <returns></returns> protected override IDbSession OnCreateSession() => new PostgreSQLSession(this); /// <summary>ๅˆ›ๅปบๅ…ƒๆ•ฐๆฎๅฏน่ฑก</summary> /// <returns></returns> protected override IMetaData OnCreateMetaData() => new PostgreSQLMetaData(); public override Boolean Support(String providerName) { providerName = providerName.ToLower(); if (providerName.Contains("postgresql.data.postgresqlclient")) return true; if (providerName.Contains("postgresql")) return true; if (providerName.Contains("npgsql")) return true; return false; } #endregion #region ๆ•ฐๆฎๅบ“็‰นๆ€ง protected override String ReservedWordsStr { get { return "ACCESSIBLE,ADD,ALL,ALTER,ANALYZE,AND,AS,ASC,ASENSITIVE,BEFORE,BETWEEN,BIGINT,BINARY,BLOB,BOTH,BY,CALL,CASCADE,CASE,CHANGE,CHAR,CHARACTER,CHECK,COLLATE,COLUMN,CONDITION,CONNECTION,CONSTRAINT,CONTINUE,CONTRIBUTORS,CONVERT,CREATE,CROSS,CURRENT_DATE,CURRENT_TIME,CURRENT_TIMESTAMP,CURRENT_USER,CURSOR,DATABASE,DATABASES,DAY_HOUR,DAY_MICROSECOND,DAY_MINUTE,DAY_SECOND,DEC,DECIMAL,DECLARE,DEFAULT,DELAYED,DELETE,DESC,DESCRIBE,DETERMINISTIC,DISTINCT,DISTINCTROW,DIV,DOUBLE,DROP,DUAL,EACH,ELSE,ELSEIF,ENCLOSED,ESCAPED,EXISTS,EXIT,EXPLAIN,FALSE,FETCH,FLOAT,FLOAT4,FLOAT8,FOR,FORCE,FOREIGN,FROM,FULLTEXT,GRANT,GROUP,HAVING,HIGH_PRIORITY,HOUR_MICROSECOND,HOUR_MINUTE,HOUR_SECOND,IF,IGNORE,IN,INDEX,INFILE,INNER,INOUT,INSENSITIVE,INSERT,INT,INT1,INT2,INT3,INT4,INT8,INTEGER,INTERVAL,INTO,IS,ITERATE,JOIN,KEY,KEYS,KILL,LEADING,LEAVE,LEFT,LIKE,LIMIT,LINEAR,LINES,LOAD,LOCALTIME,LOCALTIMESTAMP,LOCK,LONG,LONGBLOB,LONGTEXT,LOOP,LOW_PRIORITY,MATCH,MEDIUMBLOB,MEDIUMINT,MEDIUMTEXT,MIDDLEINT,MINUTE_MICROSECOND,MINUTE_SECOND,MOD,MODIFIES,NATURAL,NOT,NO_WRITE_TO_BINLOG,NULL,NUMERIC,ON,OPTIMIZE,OPTION,OPTIONALLY,OR,ORDER,OUT,OUTER,OUTFILE,PRECISION,PRIMARY,PROCEDURE,PURGE,RANGE,READ,READS,READ_ONLY,READ_WRITE,REAL,REFERENCES,REGEXP,RELEASE,RENAME,REPEAT,REPLACE,REQUIRE,RESTRICT,RETURN,REVOKE,RIGHT,RLIKE,SCHEMA,SCHEMAS,SECOND_MICROSECOND,SELECT,SENSITIVE,SEPARATOR,SET,SHOW,SMALLINT,SPATIAL,SPECIFIC,SQL,SQLEXCEPTION,SQLSTATE,SQLWARNING,SQL_BIG_RESULT,SQL_CALC_FOUND_ROWS,SQL_SMALL_RESULT,SSL,STARTING,STRAIGHT_JOIN,TABLE,TERMINATED,THEN,TINYBLOB,TINYINT,TINYTEXT,TO,TRAILING,TRIGGER,TRUE,UNDO,UNION,UNIQUE,UNLOCK,UNSIGNED,UPDATE,UPGRADE,USAGE,USE,USING,UTC_DATE,UTC_TIME,UTC_TIMESTAMP,VALUES,VARBINARY,VARCHAR,VARCHARACTER,VARYING,WHEN,WHERE,WHILE,WITH,WRITE,X509,XOR,YEAR_MONTH,ZEROFILL,Offset" + "LOG,User,Role,Admin,Rank,Member"; } } /// <summary>ๆ ผๅผๅŒ–ๅ…ณ้”ฎๅญ—</summary> /// <param name="keyWord">ๅ…ณ้”ฎๅญ—</param> /// <returns></returns> public override String FormatKeyWord(String keyWord) { //if (String.IsNullOrEmpty(keyWord)) throw new ArgumentNullException("keyWord"); if (String.IsNullOrEmpty(keyWord)) return keyWord; if (keyWord.StartsWith("\"") && keyWord.EndsWith("\"")) return keyWord; return $"\"{keyWord}\""; } /// <summary>ๆ ผๅผๅŒ–ๆ•ฐๆฎไธบSQLๆ•ฐๆฎ</summary> /// <param name="field">ๅญ—ๆฎต</param> /// <param name="value">ๆ•ฐๅ€ผ</param> /// <returns></returns> public override String FormatValue(IDataColumn field, Object value) { if (field.DataType == typeof(String)) { if (value == null) return field.Nullable ? "null" : "''"; //ไบ‘้ฃžๆ‰ฌ๏ผš่ฟ™้‡Œๆณจ้‡Šๆމ๏ผŒๅบ”่ฏฅ่ฟ”ๅ›ž``่€Œไธๆ˜ฏnullๅญ—็ฌฆ //if (String.IsNullOrEmpty(value.ToString()) && field.Nullable) return "null"; return "'" + value + "'"; } else if (field.DataType == typeof(Boolean)) { return (Boolean)value ? "true" : "false"; } return base.FormatValue(field, value); } /// <summary>้•ฟๆ–‡ๆœฌ้•ฟๅบฆ</summary> public override Int32 LongTextLength => 4000; protected internal override String ParamPrefix => "$"; /// <summary>็ณป็ปŸๆ•ฐๆฎๅบ“ๅ</summary> public override String SystemDatabaseName => "postgres"; /// <summary>ๅญ—็ฌฆไธฒ็›ธๅŠ </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns></returns> public override String StringConcat(String left, String right) => (!String.IsNullOrEmpty(left) ? left : "''") + "||" + (!String.IsNullOrEmpty(right) ? right : "''"); /// <summary> /// ๆ ผๅผๅŒ–ๆ•ฐๆฎๅบ“ๅ็งฐ๏ผŒ่กจๅ็งฐ๏ผŒๅญ—ๆฎตๅ็งฐ ๅขžๅŠ ๅŒๅผ•ๅท๏ผˆ""๏ผ‰ /// PGSQL ้ป˜่ฎคๆƒ…ๅ†ตไธ‹ๅˆ›ๅปบๅบ“่กจๆ—ถ่‡ชๅŠจ่ฝฌไธบๅฐๅ†™๏ผŒๅขžๅŠ ๅผ•ๅทๅผบๅˆถๅŒบๅˆ†ๅคงๅฐๅ†™ /// ไปฅ่งฃๅ†ณๆ•ฐๆฎๅบ“ๅˆ›ๅปบๆŸฅ่ฏขๆ—ถๅคงๅฐๅ†™้—ฎ้ข˜ /// </summary> /// <param name="name"></param> /// <returns></returns> public override String FormatName(String name) { name = base.FormatName(name); if (name.StartsWith("\"") || name.EndsWith("\"")) return name; return $"\"{name}\""; } #endregion #region ๅˆ†้กต /// <summary>ๅทฒ้‡ๅ†™ใ€‚่Žทๅ–ๅˆ†้กต</summary> /// <param name="sql">SQL่ฏญๅฅ</param> /// <param name="startRowIndex">ๅผ€ๅง‹่กŒ๏ผŒ0่กจ็คบ็ฌฌไธ€่กŒ</param> /// <param name="maximumRows">ๆœ€ๅคง่ฟ”ๅ›ž่กŒๆ•ฐ๏ผŒ0่กจ็คบๆ‰€ๆœ‰่กŒ</param> /// <param name="keyColumn">ไธป้”ฎๅˆ—ใ€‚็”จไบŽnot inๅˆ†้กต</param> /// <returns></returns> public override String PageSplit(String sql, Int64 startRowIndex, Int64 maximumRows, String keyColumn) => PageSplitByOffsetLimit(sql, startRowIndex, maximumRows); /// <summary>ๆž„้€ ๅˆ†้กตSQL</summary> /// <param name="builder">ๆŸฅ่ฏข็”Ÿๆˆๅ™จ</param> /// <param name="startRowIndex">ๅผ€ๅง‹่กŒ๏ผŒ0่กจ็คบ็ฌฌไธ€่กŒ</param> /// <param name="maximumRows">ๆœ€ๅคง่ฟ”ๅ›ž่กŒๆ•ฐ๏ผŒ0่กจ็คบๆ‰€ๆœ‰่กŒ</param> /// <returns>ๅˆ†้กตSQL</returns> public override SelectBuilder PageSplit(SelectBuilder builder, Int64 startRowIndex, Int64 maximumRows) => PageSplitByOffsetLimit(builder, startRowIndex, maximumRows); /// <summary>ๅทฒ้‡ๅ†™ใ€‚่Žทๅ–ๅˆ†้กต</summary> /// <param name="sql">SQL่ฏญๅฅ</param> /// <param name="startRowIndex">ๅผ€ๅง‹่กŒ๏ผŒ0่กจ็คบ็ฌฌไธ€่กŒ</param> /// <param name="maximumRows">ๆœ€ๅคง่ฟ”ๅ›ž่กŒๆ•ฐ๏ผŒ0่กจ็คบๆ‰€ๆœ‰่กŒ</param> /// <returns></returns> public static String PageSplitByOffsetLimit(String sql, Int64 startRowIndex, Int64 maximumRows) { // ไปŽ็ฌฌไธ€่กŒๅผ€ๅง‹๏ผŒไธ้œ€่ฆๅˆ†้กต if (startRowIndex <= 0) { if (maximumRows < 1) return sql; return $"{sql} limit {maximumRows}"; } if (maximumRows < 1) throw new NotSupportedException("ไธๆ”ฏๆŒๅ–็ฌฌๅ‡ ๆกๆ•ฐๆฎไน‹ๅŽ็š„ๆ‰€ๆœ‰ๆ•ฐๆฎ๏ผ"); return $"{sql} offset {startRowIndex} limit {maximumRows}"; } /// <summary>ๆž„้€ ๅˆ†้กตSQL</summary> /// <param name="builder">ๆŸฅ่ฏข็”Ÿๆˆๅ™จ</param> /// <param name="startRowIndex">ๅผ€ๅง‹่กŒ๏ผŒ0่กจ็คบ็ฌฌไธ€่กŒ</param> /// <param name="maximumRows">ๆœ€ๅคง่ฟ”ๅ›ž่กŒๆ•ฐ๏ผŒ0่กจ็คบๆ‰€ๆœ‰่กŒ</param> /// <returns>ๅˆ†้กตSQL</returns> public static SelectBuilder PageSplitByOffsetLimit(SelectBuilder builder, Int64 startRowIndex, Int64 maximumRows) { // ไปŽ็ฌฌไธ€่กŒๅผ€ๅง‹๏ผŒไธ้œ€่ฆๅˆ†้กต if (startRowIndex <= 0) { if (maximumRows > 0) builder.Limit = $"limit {maximumRows}"; return builder; } if (maximumRows < 1) throw new NotSupportedException("ไธๆ”ฏๆŒๅ–็ฌฌๅ‡ ๆกๆ•ฐๆฎไน‹ๅŽ็š„ๆ‰€ๆœ‰ๆ•ฐๆฎ๏ผ"); builder.Limit = $"offset {startRowIndex} limit {maximumRows}"; return builder; } #endregion } /// <summary>PostgreSQLๆ•ฐๆฎๅบ“</summary> internal class PostgreSQLSession : RemoteDbSession { #region ๆž„้€ ๅ‡ฝๆ•ฐ public PostgreSQLSession(IDatabase db) : base(db) { } #endregion #region ๅŸบๆœฌๆ–นๆณ• ๆŸฅ่ฏข/ๆ‰ง่กŒ /// <summary>ๆ‰ง่กŒๆ’ๅ…ฅ่ฏญๅฅๅนถ่ฟ”ๅ›žๆ–ฐๅขž่กŒ็š„่‡ชๅŠจ็ผ–ๅท</summary> /// <param name="sql">SQL่ฏญๅฅ</param> /// <param name="type">ๅ‘ฝไปค็ฑปๅž‹๏ผŒ้ป˜่ฎคSQLๆ–‡ๆœฌ</param> /// <param name="ps">ๅ‘ฝไปคๅ‚ๆ•ฐ</param> /// <returns>ๆ–ฐๅขž่กŒ็š„่‡ชๅŠจ็ผ–ๅท</returns> public override Int64 InsertAndGetIdentity(String sql, CommandType type = CommandType.Text, params IDataParameter[] ps) { sql += " RETURNING id"; return base.InsertAndGetIdentity(sql, type, ps); } public override Task<Int64> InsertAndGetIdentityAsync(String sql, CommandType type = CommandType.Text, params IDataParameter[] ps) { sql += " RETURNING id"; return base.InsertAndGetIdentityAsync(sql, type, ps); } #endregion #region ๆ‰น้‡ๆ“ไฝœ /* insert into stat (siteid,statdate,`count`,cost,createtime,updatetime) values (1,'2018-08-11 09:34:00',1,123,now(),now()), (2,'2018-08-11 09:34:00',1,456,now(),now()), (3,'2018-08-11 09:34:00',1,789,now(),now()), (2,'2018-08-11 09:34:00',1,456,now(),now()) on duplicate key update `count`=`count`+values(`count`),cost=cost+values(cost), updatetime=values(updatetime); */ private String GetBatchSql(String action, IDataTable table, IDataColumn[] columns, ICollection<String> updateColumns, ICollection<String> addColumns, IEnumerable<IExtend> list) { var sb = Pool.StringBuilder.Get(); var db = Database as DbBase; // ๅญ—ๆฎตๅˆ—่กจ if (columns == null) columns = table.Columns.ToArray(); BuildInsert(sb, db, action, table, columns); // ๅ€ผๅˆ—่กจ sb.Append(" Values"); BuildBatchValues(sb, db, action, table, columns, list); // ้‡ๅค้”ฎๆ‰ง่กŒupdate BuildDuplicateKey(sb, db, columns, updateColumns, addColumns); return sb.Put(true); } public override Int32 Insert(IDataTable table, IDataColumn[] columns, IEnumerable<IExtend> list) { var sql = GetBatchSql("Insert Into", table, columns, null, null, list); return Execute(sql); } public override Int32 Upsert(IDataTable table, IDataColumn[] columns, ICollection<String> updateColumns, ICollection<String> addColumns, IEnumerable<IExtend> list) { var sql = GetBatchSql("Insert Into", table, columns, updateColumns, addColumns, list); return Execute(sql); } #endregion } /// <summary>PostgreSQLๅ…ƒๆ•ฐๆฎ</summary> internal class PostgreSQLMetaData : RemoteDbMetaData { public PostgreSQLMetaData() => Types = _DataTypes; #region ๆ•ฐๆฎ็ฑปๅž‹ protected override List<KeyValuePair<Type, Type>> FieldTypeMaps { get { if (_FieldTypeMaps == null) { var list = base.FieldTypeMaps; if (!list.Any(e => e.Key == typeof(Byte) && e.Value == typeof(Boolean))) list.Add(new KeyValuePair<Type, Type>(typeof(Byte), typeof(Boolean))); } return base.FieldTypeMaps; } } /// <summary>ๆ•ฐๆฎ็ฑปๅž‹ๆ˜ ๅฐ„</summary> private static readonly Dictionary<Type, String[]> _DataTypes = new() { { typeof(Byte[]), new String[] { "bytea" } }, { typeof(Boolean), new String[] { "boolean" } }, { typeof(Int16), new String[] { "smallint" } }, { typeof(Int32), new String[] { "integer" } }, { typeof(Int64), new String[] { "bigint" } }, { typeof(Single), new String[] { "float" } }, { typeof(Double), new String[] { "float8", "double precision" } }, { typeof(Decimal), new String[] { "decimal" } }, { typeof(DateTime), new String[] { "timestamp", "timestamp without time zone", "date" } }, { typeof(String), new String[] { "varchar({0})", "character varying", "text" } }, }; #endregion protected override void FixTable(IDataTable table, DataRow dr, IDictionary<String, DataTable> data) { // ๆณจ้‡Š if (TryGetDataRowValue(dr, "TABLE_COMMENT", out String comment)) table.Description = comment; base.FixTable(table, dr, data); } protected override void FixField(IDataColumn field, DataRow dr) { // ไฟฎๆญฃๅŽŸๅง‹็ฑปๅž‹ if (TryGetDataRowValue(dr, "COLUMN_TYPE", out String rawType)) field.RawType = rawType; // ไฟฎๆญฃ่‡ชๅขžๅญ—ๆฎต if (TryGetDataRowValue(dr, "EXTRA", out String extra) && extra == "auto_increment") field.Identity = true; // ไฟฎๆญฃไธป้”ฎ if (TryGetDataRowValue(dr, "COLUMN_KEY", out String key)) field.PrimaryKey = key == "PRI"; // ๆณจ้‡Š if (TryGetDataRowValue(dr, "COLUMN_COMMENT", out String comment)) field.Description = comment; // ๅธƒๅฐ”็ฑปๅž‹ if (field.RawType == "enum") { // PostgreSQLไธญๆฒกๆœ‰ๅธƒๅฐ”ๅž‹๏ผŒ่ฟ™้‡Œๅค„็†YNๆžšไธพไฝœไธบๅธƒๅฐ”ๅž‹ if (field.RawType is "enum('N','Y')" or "enum('Y','N')") { field.DataType = typeof(Boolean); //// ๅค„็†้ป˜่ฎคๅ€ผ //if (!String.IsNullOrEmpty(field.Default)) //{ // if (field.Default == "Y") // field.Default = "true"; // else if (field.Default == "N") // field.Default = "false"; //} return; } } base.FixField(field, dr); } public override String FieldClause(IDataColumn field, Boolean onlyDefine) { if (field.Identity) return $"{field.Name} serial NOT NULL"; var sql = base.FieldClause(field, onlyDefine); //// ๅŠ ไธŠๆณจ้‡Š //if (!String.IsNullOrEmpty(field.Description)) sql = $"{sql} COMMENT '{field.Description}'"; return sql; } protected override String GetFieldConstraints(IDataColumn field, Boolean onlyDefine) { String str = null; if (!field.Nullable) str = " NOT NULL"; if (field.Identity) str = " serial NOT NULL"; // ้ป˜่ฎคๅ€ผ if (!field.Nullable && !field.Identity) { str += GetDefault(field, onlyDefine); } return str; } #region ๆžถๆž„ๅฎšไน‰ //public override object SetSchema(DDLSchema schema, params object[] values) //{ // if (schema == DDLSchema.DatabaseExist) // { // IDbSession session = Database.CreateSession(); // DataTable dt = GetSchema(_.Databases, new String[] { values != null && values.Length > 0 ? (String)values[0] : session.DatabaseName }); // if (dt == null || dt.Rows == null || dt.Rows.Count <= 0) return false; // return true; // } // return base.SetSchema(schema, values); //} protected override Boolean DatabaseExist(String databaseName) { //return base.DatabaseExist(databaseName); var session = Database.CreateSession(); //var dt = GetSchema(_.Databases, new String[] { databaseName.ToLower() }); var dt = GetSchema(_.Databases, new String[] { databaseName }); return dt != null && dt.Rows != null && dt.Rows.Count > 0; } //public override string CreateDatabaseSQL(string dbname, string file) //{ // return String.Format("Create Database Binary {0}", FormatKeyWord(dbname)); //} public override String DropDatabaseSQL(String dbname) => $"Drop Database If Exists {Database.FormatName(dbname)}"; public override String CreateTableSQL(IDataTable table) { var fs = new List<IDataColumn>(table.Columns); var sb = new StringBuilder(32 + fs.Count * 20); sb.AppendFormat("Create Table {0}(", FormatName(table)); for (var i = 0; i < fs.Count; i++) { sb.AppendLine(); sb.Append('\t'); sb.Append(FieldClause(fs[i], true)); if (i < fs.Count - 1) sb.Append(','); } if (table.PrimaryKeys.Length > 0) sb.AppendFormat(",\r\n\tPrimary Key ({0})", table.PrimaryKeys.Join(",", FormatName)); sb.AppendLine(); sb.Append(')'); return sb.ToString(); } public override String AddTableDescriptionSQL(IDataTable table) => $"Comment On Table {FormatName(table)} is '{table.Description}'"; public override String DropTableDescriptionSQL(IDataTable table) => $"Comment On Table {FormatName(table)} is ''"; public override String AddColumnDescriptionSQL(IDataColumn field) => $"Comment On Column {FormatName(field.Table)}.{FormatName(field)} is '{field.Description}'"; public override String DropColumnDescriptionSQL(IDataColumn field) => $"Comment On Column {FormatName(field.Table)}.{FormatName(field)} is ''"; #endregion #region ่พ…ๅŠฉๅ‡ฝๆ•ฐ #endregion } }
42.133038
1,807
0.569572
[ "MIT" ]
qaz734913414/X
XCode/DataAccessLayer/Database/PostgreSQL.cs
19,998
C#
//--------------------------------------------------------------------- // <copyright file="GlobalSuppressions.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //--------------------------------------------------------------------- // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. // // To add a suppression to this file, right-click the message in the // Error List, point to "Suppress Message(s)", and click // "In Project Suppression File". // You do not need to add suppressions to this file manually. #region code generated resource members [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControlsRes.#GetString(System.String,System.Boolean&)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControlsRes.#GetObject(System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControlsRes.#Resources")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Error.#ArgumentNull(System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Error.#ArgumentOutOfRange(System.String)")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Error.#NotImplemented()")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Error.#NotSupported()")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#EntityDataSource_Description")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#EntityDataSource_DisplayName")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_AutoGenerateOrderByClause")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_AutoGenerateWhereClause")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_AutoPage")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_AutoSort")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_ContextCreated")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_ContextCreating")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_ContextDisposing")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_Deleting")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_EnableDelete")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_EnableInsert")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_EnableUpdate")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_GroupBy")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_Inserted")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_Inserting")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_Selected")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_Selecting")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_StoreOriginalValuesInViewState")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_Updated")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_Updating")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_Deleted")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_QueryCreated")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_Include")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_ContextTypeName")] [assembly: System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope = "member", Target = "System.Web.UI.WebControls.Strings.#PropertyDescription_EnableFlattening")] #endregion
155.509804
235
0.799647
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/fx/src/DataWebControls/GlobalSuppressions.cs
7,931
C#
๏ปฟnamespace UnravelTravel.Services.Data.Contracts { using System.Collections.Generic; using System.Threading.Tasks; using UnravelTravel.Models.ViewModels.Countries; public interface ICountriesService { Task<IEnumerable<CountryViewModel>> GetAllAsync(); } }
22.307692
58
0.737931
[ "MIT" ]
EmORz/Simple_Example_Projects
UnravelTravel-master/src/Services/UnravelTravel.Services.Data/Contracts/ICountriesService.cs
292
C#
๏ปฟusing UnityEngine; public static class MeshGenerator { public static MeshData GenerateTerrainMesh(float[,] heightMap, float heightMultiplier, AnimationCurve meshHeightCurve, int levelOfDetail) { int width = heightMap.GetLength(0); int height = heightMap.GetLength(1); float topLeftX = (width - 1) / -2f; float topLeftZ = (height - 1) / 2f; int meshSimplificationIncrement = levelOfDetail == 0 ? 1 : levelOfDetail * 2; int verticesPerLine = (width - 1) / meshSimplificationIncrement + 1; MeshData meshData = new MeshData(verticesPerLine, verticesPerLine); int vertexIndex = 0; for (int y = 0; y < height; y += meshSimplificationIncrement) { for (int x = 0; x < width; x += meshSimplificationIncrement) { meshData.vertices[vertexIndex] = new Vector3(topLeftX + x, meshHeightCurve.Evaluate(heightMap[x, y]) * heightMultiplier, topLeftZ - y); meshData.uvs[vertexIndex] = new Vector2(x / (float)width, y / (float)height); if (x < width - 1 && y < height - 1) { meshData.AddTriangle(vertexIndex, vertexIndex + verticesPerLine + 1, vertexIndex + verticesPerLine); meshData.AddTriangle(vertexIndex + verticesPerLine + 1, vertexIndex, vertexIndex + 1); } vertexIndex++; } } return meshData; } } public class MeshData { public Vector3[] vertices; public int[] triangles; public Vector2[] uvs; int triangleIndex; public MeshData(int mapWidth, int mapHeight) { vertices = new Vector3[mapWidth * mapHeight]; triangles = new int[(mapWidth - 1) * (mapHeight - 1) * 6]; uvs = new Vector2[mapWidth * mapHeight]; } public void AddTriangle(int a, int b, int c) { triangles[triangleIndex] = a; triangles[triangleIndex + 1] = b; triangles[triangleIndex + 2] = c; triangleIndex += 3; } public Mesh CreateMesh() { Mesh mesh = new Mesh(); mesh.vertices = vertices; mesh.triangles = triangles; mesh.uv = uvs; mesh.RecalculateNormals(); return mesh; } }
32.056338
151
0.592267
[ "MIT" ]
pwroff/landmass-generetor
Assets/Scripts/MeshGenerator.cs
2,278
C#
๏ปฟusing System.Collections.Generic; using System.Text.Json.Serialization; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// AlipayTradePayModel Data Structure. /// </summary> public class AlipayTradePayModel : AlipayObject { /// <summary> /// ๆ”ฏไป˜ๆจกๅผ็ฑปๅž‹,่‹ฅๅ€ผไธบENJOY_PAY_V2่กจ็คบๅฝ“ๅ‰ไบคๆ˜“ๅ…่ฎธ่ตฐๅ…ˆไบซๅŽไป˜2.0ๅžซ่ต„ /// </summary> [JsonPropertyName("advance_payment_type")] public string AdvancePaymentType { get; set; } /// <summary> /// ไปฃๆ‰ฃไธšๅŠก้œ€่ฆไผ ๅ…ฅๅ่ฎฎ็›ธๅ…ณไฟกๆฏ /// </summary> [JsonPropertyName("agreement_params")] public AgreementParams AgreementParams { get; set; } /// <summary> /// ๆ”ฏไป˜ๅฎ็š„ๅบ—้“บ็ผ–ๅท /// </summary> [JsonPropertyName("alipay_store_id")] public string AlipayStoreId { get; set; } /// <summary> /// ๆ”ฏไป˜ๆŽˆๆƒ็ ๏ผŒ25~30ๅผ€ๅคด็š„้•ฟๅบฆไธบ16~24ไฝ็š„ๆ•ฐๅญ—๏ผŒๅฎž้™…ๅญ—็ฌฆไธฒ้•ฟๅบฆไปฅๅผ€ๅ‘่€…่Žทๅ–็š„ไป˜ๆฌพ็ ้•ฟๅบฆไธบๅ‡† /// </summary> [JsonPropertyName("auth_code")] public string AuthCode { get; set; } /// <summary> /// ้ข„ๆŽˆๆƒ็กฎ่ฎคๆจกๅผ๏ผŒๆŽˆๆƒ่ฝฌไบคๆ˜“่ฏทๆฑ‚ไธญไผ ๅ…ฅ๏ผŒ้€‚็”จไบŽ้ข„ๆŽˆๆƒ่ฝฌไบคๆ˜“ไธšๅŠกไฝฟ็”จ๏ผŒ็›ฎๅ‰ๅชๆ”ฏๆŒPRE_AUTH(้ข„ๆŽˆๆƒไบงๅ“็ ) COMPLETE๏ผš่ฝฌไบคๆ˜“ๆ”ฏไป˜ๅฎŒๆˆ็ป“ๆŸ้ข„ๆŽˆๆƒ๏ผŒ่งฃๅ†ปๅ‰ฉไฝ™้‡‘้ข; NOT_COMPLETE๏ผš่ฝฌไบคๆ˜“ๆ”ฏไป˜ๅฎŒๆˆไธ็ป“ๆŸ้ข„ๆŽˆๆƒ๏ผŒไธ่งฃๅ†ปๅ‰ฉไฝ™้‡‘้ข /// </summary> [JsonPropertyName("auth_confirm_mode")] public string AuthConfirmMode { get; set; } /// <summary> /// ้ข„ๆŽˆๆƒๅท๏ผŒ้ข„ๆŽˆๆƒ่ฝฌไบคๆ˜“่ฏทๆฑ‚ไธญไผ ๅ…ฅ๏ผŒ้€‚็”จไบŽ้ข„ๆŽˆๆƒ่ฝฌไบคๆ˜“ไธšๅŠกไฝฟ็”จ๏ผŒ็›ฎๅ‰ๅชๆ”ฏๆŒFUND_TRADE_FAST_PAY๏ผˆ่ต„้‡‘่ฎขๅ•ๅณๆ—ถๅˆฐๅธไบคๆ˜“๏ผ‰ใ€ๅขƒๅค–้ข„ๆŽˆๆƒไบงๅ“๏ผˆOVERSEAS_AUTH_PAY๏ผ‰ไธคไธชไบงๅ“ใ€‚ /// </summary> [JsonPropertyName("auth_no")] public string AuthNo { get; set; } /// <summary> /// ่ฎขๅ•ๆ่ฟฐ /// </summary> [JsonPropertyName("body")] public string Body { get; set; } /// <summary> /// ๅ•†ๆˆทไผ ๅ…ฅไธšๅŠกไฟกๆฏ๏ผŒๅ…ทไฝ“ๅ€ผ่ฆๅ’Œๆ”ฏไป˜ๅฎ็บฆๅฎš๏ผŒๅบ”็”จไบŽๅฎ‰ๅ…จ๏ผŒ่ฅ้”€็ญ‰ๅ‚ๆ•ฐ็›ดไผ ๅœบๆ™ฏ๏ผŒๆ ผๅผไธบjsonๆ ผๅผ /// </summary> [JsonPropertyName("business_params")] public BusinessParams BusinessParams { get; set; } /// <summary> /// ไนฐๅฎถ็š„ๆ”ฏไป˜ๅฎ็”จๆˆท id๏ผŒๅฆ‚ๆžœไธบ็ฉบ๏ผŒไผšไปŽไผ ๅ…ฅ็š„็ ๅ€ผไฟกๆฏไธญ่Žทๅ–ไนฐๅฎถ ID /// </summary> [JsonPropertyName("buyer_id")] public string BuyerId { get; set; } /// <summary> /// ็ฆ็”จๆ”ฏไป˜ๆธ ้“,ๅคšไธชๆธ ้“ไปฅ้€—ๅทๅˆ†ๅ‰ฒ๏ผŒๅฆ‚ๅŒๆ—ถ็ฆ็”จไฟก็”จๆ”ฏไป˜็ฑปๅž‹ๅ’Œ็งฏๅˆ†๏ผŒๅˆ™disable_pay_channels="credit_group,point" /// </summary> [JsonPropertyName("disable_pay_channels")] public string DisablePayChannels { get; set; } /// <summary> /// ๅ‚ไธŽไผ˜ๆƒ ่ฎก็ฎ—็š„้‡‘้ข๏ผŒๅ•ไฝไธบๅ…ƒ๏ผŒ็ฒพ็กฎๅˆฐๅฐๆ•ฐ็‚นๅŽไธคไฝ๏ผŒๅ–ๅ€ผ่Œƒๅ›ด[0.01,100000000]ใ€‚ ๅฆ‚ๆžœ่ฏฅๅ€ผๆœชไผ ๅ…ฅ๏ผŒไฝ†ไผ ๅ…ฅไบ†ใ€่ฎขๅ•ๆ€ป้‡‘้ขใ€‘ๅ’Œใ€ไธๅฏๆ‰“ๆŠ˜้‡‘้ขใ€‘๏ผŒๅˆ™่ฏฅๅ€ผ้ป˜่ฎคไธบใ€่ฎขๅ•ๆ€ป้‡‘้ขใ€‘-ใ€ไธๅฏๆ‰“ๆŠ˜้‡‘้ขใ€‘ /// </summary> [JsonPropertyName("discountable_amount")] public string DiscountableAmount { get; set; } /// <summary> /// ๅค–้ƒจๆŒ‡ๅฎšไนฐๅฎถ /// </summary> [JsonPropertyName("ext_user_info")] public ExtUserInfo ExtUserInfo { get; set; } /// <summary> /// ไธšๅŠกๆ‰ฉๅฑ•ๅ‚ๆ•ฐ /// </summary> [JsonPropertyName("extend_params")] public ExtendParams ExtendParams { get; set; } /// <summary> /// ่ฎขๅ•ๅŒ…ๅซ็š„ๅ•†ๅ“ๅˆ—่กจไฟกๆฏ๏ผŒjsonๆ ผๅผ๏ผŒๅ…ถๅฎƒ่ฏดๆ˜Ž่ฏฆ่งๅ•†ๅ“ๆ˜Ž็ป†่ฏดๆ˜Ž /// </summary> [JsonPropertyName("goods_detail")] public List<GoodsDetail> GoodsDetail { get; set; } /// <summary> /// ๆ˜ฏๅฆๅผ‚ๆญฅๆ”ฏไป˜๏ผŒไผ ๅ…ฅtrueๆ—ถ๏ผŒ่กจๆ˜ŽๆœฌๆฌกๆœŸๆœ›่ตฐๅผ‚ๆญฅๆ”ฏไป˜๏ผŒไผšๅ…ˆๅฐ†ๆ”ฏไป˜่ฏทๆฑ‚ๅ—็†ไธ‹ๆฅ๏ผŒๅ†ๅผ‚ๆญฅๆŽจ่ฟ›ใ€‚ๅ•†ๆˆทๅฏไปฅ้€š่ฟ‡ไบคๆ˜“็š„ๅผ‚ๆญฅ้€š็Ÿฅๆˆ–่€…่ฝฎ่ฏขไบคๆ˜“็š„็Šถๆ€ๆฅ็กฎๅฎšๆœ€็ปˆ็š„ไบคๆ˜“็ป“ๆžœ /// </summary> [JsonPropertyName("is_async_pay")] public bool IsAsyncPay { get; set; } /// <summary> /// ๅ•†ๆˆท็š„ๅŽŸๅง‹่ฎขๅ•ๅท /// </summary> [JsonPropertyName("merchant_order_no")] public string MerchantOrderNo { get; set; } /// <summary> /// ๅ•†ๆˆทๆ“ไฝœๅ‘˜็ผ–ๅท /// </summary> [JsonPropertyName("operator_id")] public string OperatorId { get; set; } /// <summary> /// ๅ•†ๆˆท่ฎขๅ•ๅท,64ไธชๅญ—็ฌฆไปฅๅ†…ใ€ๅฏๅŒ…ๅซๅญ—ๆฏใ€ๆ•ฐๅญ—ใ€ไธ‹ๅˆ’็บฟ๏ผ›้œ€ไฟ่ฏๅœจๅ•†ๆˆท็ซฏไธ้‡ๅค /// </summary> [JsonPropertyName("out_trade_no")] public string OutTradeNo { get; set; } /// <summary> /// ้”€ๅ”ฎไบงๅ“็  /// </summary> [JsonPropertyName("product_code")] public string ProductCode { get; set; } /// <summary> /// ไผ˜ๆƒ ๆ˜Ž็ป†ๅ‚ๆ•ฐ๏ผŒ้€š่ฟ‡ๆญคๅฑžๆ€ง่กฅๅ……่ฅ้”€ๅ‚ๆ•ฐ /// </summary> [JsonPropertyName("promo_params")] public PromoParam PromoParams { get; set; } /// <summary> /// ่ฟ”ๅ›žๆŸฅ่ฏข้€‰้กน๏ผŒๅ•†ๆˆท้€š่ฟ‡ไธŠ้€่ฏฅๅ‚ๆ•ฐๆฅๅฎšๅˆถๅŒๆญฅ้œ€่ฆ้ขๅค–่ฟ”ๅ›ž็š„ไฟกๆฏๅญ—ๆฎต๏ผŒๆ•ฐ็ป„ๆ ผๅผใ€‚ๅฆ‚๏ผš["fund_bill_list","voucher_detail_list","discount_goods_detail"] /// </summary> [JsonPropertyName("query_options")] public List<string> QueryOptions { get; set; } /// <summary> /// ๆ”ถๅ•ๆœบๆž„(ไพ‹ๅฆ‚้“ถ่กŒ๏ผ‰็š„ๆ ‡่ฏ†๏ผŒๅกซๅ†™่ฏฅๆœบๆž„ๅœจๆ”ฏไป˜ๅฎ็š„pidใ€‚ๅชๅœจๆœบๆž„้—ด่”ๅœบๆ™ฏไธ‹ไผ ้€’่ฏฅๅ€ผใ€‚ /// </summary> [JsonPropertyName("request_org_pid")] public string RequestOrgPid { get; set; } /// <summary> /// ๆ่ฟฐๅˆ†่ดฆไฟกๆฏ๏ผŒjsonๆ ผๅผ๏ผŒๅ…ถๅฎƒ่ฏดๆ˜Ž่ฏฆ่งๅˆ†่ดฆ่ฏดๆ˜Ž /// </summary> [JsonPropertyName("royalty_info")] public RoyaltyInfo RoyaltyInfo { get; set; } /// <summary> /// ๆ”ฏไป˜ๅœบๆ™ฏ ๆก็ ๆ”ฏไป˜๏ผŒๅ–ๅ€ผ๏ผšbar_code ๅฃฐๆณขๆ”ฏไป˜๏ผŒๅ–ๅ€ผ๏ผšwave_code /// </summary> [JsonPropertyName("scene")] public string Scene { get; set; } /// <summary> /// ๅฆ‚ๆžœ่ฏฅๅ€ผไธบ็ฉบ๏ผŒๅˆ™้ป˜่ฎคไธบๅ•†ๆˆท็ญพ็บฆ่ดฆๅทๅฏนๅบ”็š„ๆ”ฏไป˜ๅฎ็”จๆˆทID /// </summary> [JsonPropertyName("seller_id")] public string SellerId { get; set; } /// <summary> /// ๅ•†ๆˆทๆŒ‡ๅฎš็š„็ป“็ฎ—ๅธ็ง๏ผŒๆ”ฏๆŒ่‹ฑ้•‘๏ผšGBPใ€ๆธฏๅธ๏ผšHKDใ€็พŽๅ…ƒ๏ผšUSDใ€ๆ–ฐๅŠ ๅกๅ…ƒ๏ผšSGDใ€ๆ—ฅๅ…ƒ๏ผšJPYใ€ๅŠ ๆ‹ฟๅคงๅ…ƒ๏ผšCADใ€ๆพณๅ…ƒ๏ผšAUDใ€ๆฌงๅ…ƒ๏ผšEURใ€ๆ–ฐ่ฅฟๅ…ฐๅ…ƒ๏ผšNZDใ€้Ÿฉๅ…ƒ๏ผšKRWใ€ๆณฐ้“ข๏ผšTHBใ€็‘žๅฃซๆณ•้ƒŽ๏ผšCHFใ€็‘žๅ…ธๅ…‹ๆœ—๏ผšSEKใ€ไธน้บฆๅ…‹ๆœ—๏ผšDKKใ€ๆŒชๅจๅ…‹ๆœ—๏ผšNOKใ€้ฉฌๆฅ่ฅฟไบšๆž—ๅ‰็‰น๏ผšMYRใ€ๅฐๅฐผๅขๆฏ”๏ผšIDRใ€่ฒๅพ‹ๅฎพๆฏ”็ดข๏ผšPHPใ€ๆฏ›้‡Œๆฑ‚ๆ–ฏๅขๆฏ”๏ผšMURใ€ไปฅ่‰ฒๅˆ—ๆ–ฐ่ฐขๅ…‹ๅฐ”๏ผšILSใ€ๆ–ฏ้‡Œๅ…ฐๅกๅขๆฏ”๏ผšLKRใ€ไฟ„็ฝ—ๆ–ฏๅขๅธƒ๏ผšRUBใ€้˜ฟ่”้…‹่ฟชๆ‹‰ๅง†๏ผšAEDใ€ๆทๅ…‹ๅ…‹ๆœ—๏ผšCZKใ€ๅ—้žๅ…ฐ็‰น๏ผšZARใ€ไบบๆฐ‘ๅธ๏ผšCNY /// </summary> [JsonPropertyName("settle_currency")] public string SettleCurrency { get; set; } /// <summary> /// ๆ่ฟฐ็ป“็ฎ—ไฟกๆฏ๏ผŒjsonๆ ผๅผ๏ผŒ่ฏฆ่ง็ป“็ฎ—ๅ‚ๆ•ฐ่ฏดๆ˜Ž /// </summary> [JsonPropertyName("settle_info")] public SettleInfo SettleInfo { get; set; } /// <summary> /// ๅ•†ๆˆท้—จๅบ—็ผ–ๅท /// </summary> [JsonPropertyName("store_id")] public string StoreId { get; set; } /// <summary> /// ้—ด่ฟžๅ—็†ๅ•†ๆˆทไฟกๆฏไฝ“๏ผŒๅฝ“ๅ‰ๅชๅฏน็‰นๆฎŠ้“ถ่กŒๆœบๆž„็‰นๅฎšๅœบๆ™ฏไธ‹ไฝฟ็”จๆญคๅญ—ๆฎต /// </summary> [JsonPropertyName("sub_merchant")] public SubMerchant SubMerchant { get; set; } /// <summary> /// ๅ•†ๅ“ๆ ‡้ข˜/ไบคๆ˜“ๆ ‡้ข˜/่ฎขๅ•ๆ ‡้ข˜/่ฎขๅ•ๅ…ณ้”ฎๅญ—็ญ‰ใ€‚ ๆณจๆ„๏ผšไธๅฏไฝฟ็”จ็‰นๆฎŠๅญ—็ฌฆ๏ผŒๅฆ‚ /๏ผŒ=๏ผŒ& ็ญ‰ใ€‚ /// </summary> [JsonPropertyName("subject")] public string Subject { get; set; } /// <summary> /// ๅ•†ๆˆทๆœบๅ…ท็ปˆ็ซฏ็ผ–ๅท /// </summary> [JsonPropertyName("terminal_id")] public string TerminalId { get; set; } /// <summary> /// ๅ•†ๆˆทไผ ๅ…ฅ็ปˆ็ซฏ่ฎพๅค‡็›ธๅ…ณไฟกๆฏ๏ผŒๅ…ทไฝ“ๅ€ผ่ฆๅ’Œๆ”ฏไป˜ๅฎ็บฆๅฎš /// </summary> [JsonPropertyName("terminal_params")] public string TerminalParams { get; set; } /// <summary> /// ่ฏฅ็ฌ”่ฎขๅ•ๅ…่ฎธ็š„ๆœ€ๆ™šไป˜ๆฌพๆ—ถ้—ด๏ผŒ้€พๆœŸๅฐ†ๅ…ณ้—ญไบคๆ˜“ใ€‚ๅ–ๅ€ผ่Œƒๅ›ด๏ผš1m๏ฝž15dใ€‚m-ๅˆ†้’Ÿ๏ผŒh-ๅฐๆ—ถ๏ผŒd-ๅคฉ๏ผŒ1c-ๅฝ“ๅคฉ๏ผˆ1c-ๅฝ“ๅคฉ็š„ๆƒ…ๅ†ตไธ‹๏ผŒๆ— ่ฎบไบคๆ˜“ไฝ•ๆ—ถๅˆ›ๅปบ๏ผŒ้ƒฝๅœจ0็‚นๅ…ณ้—ญ๏ผ‰ใ€‚ ่ฏฅๅ‚ๆ•ฐๆ•ฐๅ€ผไธๆŽฅๅ—ๅฐๆ•ฐ็‚น๏ผŒ ๅฆ‚ 1.5h๏ผŒๅฏ่ฝฌๆขไธบ 90m /// </summary> [JsonPropertyName("timeout_express")] public string TimeoutExpress { get; set; } /// <summary> /// ่ฎขๅ•ๆ€ป้‡‘้ข๏ผŒๅ•ไฝไธบๅ…ƒ๏ผŒ็ฒพ็กฎๅˆฐๅฐๆ•ฐ็‚นๅŽไธคไฝ๏ผŒๅ–ๅ€ผ่Œƒๅ›ด[0.01,100000000] ๅฆ‚ๆžœๅŒๆ—ถไผ ๅ…ฅใ€ๅฏๆ‰“ๆŠ˜้‡‘้ขใ€‘ๅ’Œใ€ไธๅฏๆ‰“ๆŠ˜้‡‘้ขใ€‘๏ผŒ่ฏฅๅ‚ๆ•ฐๅฏไปฅไธ็”จไผ ๅ…ฅ๏ผ› ๅฆ‚ๆžœๅŒๆ—ถไผ ๅ…ฅไบ†ใ€ๅฏๆ‰“ๆŠ˜้‡‘้ขใ€‘๏ผŒใ€ไธๅฏๆ‰“ๆŠ˜้‡‘้ขใ€‘๏ผŒใ€่ฎขๅ•ๆ€ป้‡‘้ขใ€‘ไธ‰่€…๏ผŒๅˆ™ๅฟ…้กปๆปก่ถณๅฆ‚ไธ‹ๆกไปถ๏ผšใ€่ฎขๅ•ๆ€ป้‡‘้ขใ€‘=ใ€ๅฏๆ‰“ๆŠ˜้‡‘้ขใ€‘+ใ€ไธๅฏๆ‰“ๆŠ˜้‡‘้ขใ€‘ /// </summary> [JsonPropertyName("total_amount")] public string TotalAmount { get; set; } /// <summary> /// ๆ ‡ไปทๅธ็ง, total_amount ๅฏนๅบ”็š„ๅธ็งๅ•ไฝใ€‚ๆ”ฏๆŒ่‹ฑ้•‘๏ผšGBPใ€ๆธฏๅธ๏ผšHKDใ€็พŽๅ…ƒ๏ผšUSDใ€ๆ–ฐๅŠ ๅกๅ…ƒ๏ผšSGDใ€ๆ—ฅๅ…ƒ๏ผšJPYใ€ๅŠ ๆ‹ฟๅคงๅ…ƒ๏ผšCADใ€ๆพณๅ…ƒ๏ผšAUDใ€ๆฌงๅ…ƒ๏ผšEURใ€ๆ–ฐ่ฅฟๅ…ฐๅ…ƒ๏ผšNZDใ€้Ÿฉๅ…ƒ๏ผšKRWใ€ๆณฐ้“ข๏ผšTHBใ€็‘žๅฃซๆณ•้ƒŽ๏ผšCHFใ€็‘žๅ…ธๅ…‹ๆœ—๏ผšSEKใ€ไธน้บฆๅ…‹ๆœ—๏ผšDKKใ€ๆŒชๅจๅ…‹ๆœ—๏ผšNOKใ€้ฉฌๆฅ่ฅฟไบšๆž—ๅ‰็‰น๏ผšMYRใ€ๅฐๅฐผๅขๆฏ”๏ผšIDRใ€่ฒๅพ‹ๅฎพๆฏ”็ดข๏ผšPHPใ€ๆฏ›้‡Œๆฑ‚ๆ–ฏๅขๆฏ”๏ผšMURใ€ไปฅ่‰ฒๅˆ—ๆ–ฐ่ฐขๅ…‹ๅฐ”๏ผšILSใ€ๆ–ฏ้‡Œๅ…ฐๅกๅขๆฏ”๏ผšLKRใ€ไฟ„็ฝ—ๆ–ฏๅขๅธƒ๏ผšRUBใ€้˜ฟ่”้…‹่ฟชๆ‹‰ๅง†๏ผšAEDใ€ๆทๅ…‹ๅ…‹ๆœ—๏ผšCZKใ€ๅ—้žๅ…ฐ็‰น๏ผšZARใ€ไบบๆฐ‘ๅธ๏ผšCNY /// </summary> [JsonPropertyName("trans_currency")] public string TransCurrency { get; set; } /// <summary> /// ไธๅ‚ไธŽไผ˜ๆƒ ่ฎก็ฎ—็š„้‡‘้ข๏ผŒๅ•ไฝไธบๅ…ƒ๏ผŒ็ฒพ็กฎๅˆฐๅฐๆ•ฐ็‚นๅŽไธคไฝ๏ผŒๅ–ๅ€ผ่Œƒๅ›ด[0.01,100000000]ใ€‚ๅฆ‚ๆžœ่ฏฅๅ€ผๆœชไผ ๅ…ฅ๏ผŒไฝ†ไผ ๅ…ฅไบ†ใ€่ฎขๅ•ๆ€ป้‡‘้ขใ€‘ๅ’Œใ€ๅฏๆ‰“ๆŠ˜้‡‘้ขใ€‘๏ผŒๅˆ™่ฏฅๅ€ผ้ป˜่ฎคไธบใ€่ฎขๅ•ๆ€ป้‡‘้ขใ€‘-ใ€ๅฏๆ‰“ๆŠ˜้‡‘้ขใ€‘ /// </summary> [JsonPropertyName("undiscountable_amount")] public string UndiscountableAmount { get; set; } } }
34.171053
272
0.584007
[ "MIT" ]
LuohuaRain/payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/AlipayTradePayModel.cs
10,753
C#
๏ปฟ#nullable enable using Lidgren.Network; using Robust.Shared.Network; namespace Content.Shared.Preferences { /// <summary> /// The client sends this to delete a character profile. /// </summary> public class MsgDeleteCharacter : NetMessage { #region REQUIRED public const MsgGroups GROUP = MsgGroups.Command; public const string NAME = nameof(MsgDeleteCharacter); public MsgDeleteCharacter(INetChannel channel) : base(NAME, GROUP) { } #endregion public int Slot; public override void ReadFromBuffer(NetIncomingMessage buffer) { Slot = buffer.ReadInt32(); } public override void WriteToBuffer(NetOutgoingMessage buffer) { buffer.Write(Slot); } } }
23.470588
78
0.636591
[ "MIT" ]
GalacticChimp/space-station-14
Content.Shared/Preferences/MsgDeleteCharacter.cs
800
C#
using Xunit; using DotNetCoreKoans.Engine; namespace DotNetCoreKoans.Koans { public class AboutAsserts : Koan { //We shall contemplate truth by testing reality, via asserts. [Step(1)] public void AssertTruth() { Assert.True(true); //This should be true } //Enlightenment may be more easily achieved with appropriate messages [Step(2)] public void AssertTruthWithMessage() { Assert.True(true, "This should be true -- Please fix this"); } //To understand reality, we must compare our expectations against reality [Step(3)] public void AssertEquality() { var expectedValue = 2; var actualValue = 1 + 1; Assert.True(expectedValue == actualValue); } //Some ways of asserting equality are better than others [Step(4)] public void ABetterWayOfAssertingEquality() { var expectedValue = 2; var actualValue = 1 + 1; Assert.Equal(expectedValue, actualValue); } //Sometimes we will ask you to fill in the values [Step(5)] public void FillInValues() { Assert.Equal(2, 1 + 1); } } }
26.958333
81
0.564142
[ "MIT" ]
icole/DotNetCoreKoans
Koans/AboutAsserts.cs
1,294
C#
๏ปฟusing Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Options; using Microsoft.TeamFoundation.SourceControl.WebApi; using Microsoft.TeamFoundation.Build.WebApi; using Microsoft.VisualStudio.Services.Common; using Microsoft.VisualStudio.Services.WebApi; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PipelineCacher.Server.Controllers { [ApiController] [Route("api/[controller]")] public class BuildController : ControllerBase { private readonly PipelineCacherConfig pipelineCacherConfig; public BuildController(IOptions<PipelineCacherConfig> pipelineCacherConfig) { this.pipelineCacherConfig = pipelineCacherConfig.Value; } [HttpGet] public async Task<string> Get() { var collectionUri = "https://dev.azure.com/carlintveld"; VssConnection connection = new VssConnection(new Uri(collectionUri), new VssBasicCredential(String.Empty, pipelineCacherConfig.AzureDevOpsPAT)); var client = connection.GetClient<BuildHttpClient>(); // https://dev.azure.com/carlintveld/lucas-demo/_build?definitionId=28 var definition = await client.GetDefinitionAsync("lucas-demo", 28); // https://dev.azure.com/{organization}/{project}/_apis/build/builds/{buildId}?api-version=6.0 var builds = await client.GetBuildsAsync("lucas-demo", new int[] { 28 }); //var build = await client.GetBuildAsync("lucas-demo", builds[0].); return builds[0].SourceVersion; } } }
39.902439
156
0.692543
[ "MIT" ]
cveld/PipelineCacher
PipelineCacher/Server/Controllers/BuildController.cs
1,638
C#
//----------------------------------------------------------------------- // <copyright file="ISupportsPrefabSerialization.cs" company="Sirenix IVS"> // Copyright (c) 2018 Sirenix IVS // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> //----------------------------------------------------------------------- namespace OdinSerializer { /// <summary> /// Indicates that an Odin-serialized Unity object supports prefab serialization. /// </summary> public interface ISupportsPrefabSerialization { /// <summary> /// Gets or sets the serialization data of the object. /// </summary> SerializationData SerializationData { get; set; } } }
41.333333
86
0.605645
[ "MIT" ]
coding2233/UnityGameFramework
Libraries/OdinSerializer/Unity Integration/SerializedUnityObjects/ISupportsPrefabSerialization.cs
1,240
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CDS.Core.Client.DataAccessLayer.DB { using System; using System.Collections.Generic; public partial class VW_OrderInventoryHistory { public long Id { get; set; } public long EntityId { get; set; } public long SupplierId { get; set; } public string Code { get; set; } public string Name { get; set; } public string SupplierCode { get; set; } public string SupplierName { get; set; } public byte CostCategoryId { get; set; } public decimal TotalOnHand { get; set; } public decimal TotalOnOrder { get; set; } public decimal TotalOnHold { get; set; } public decimal UnitCost { get; set; } public decimal UnitAverage { get; set; } public string Category { get; set; } public string LocationMain { get; set; } public decimal MinStockLevel { get; set; } public decimal MaxStockLevel { get; set; } public decimal MinimumOrderLevel { get; set; } public decimal MaximumOrderLevel { get; set; } public decimal PackSize { get; set; } public decimal WarehousingCost { get; set; } public byte OrderLeadTime { get; set; } public decimal SafetyStock { get; set; } public decimal UnitPrice { get; set; } public decimal UnitReplacementCost { get; set; } public string StockType { get; set; } public decimal d00Month { get; set; } public decimal d01Month { get; set; } public decimal d02Month { get; set; } public decimal d03Month { get; set; } public decimal d04Month { get; set; } public decimal d05Month { get; set; } public decimal d06Month { get; set; } public decimal d07Month { get; set; } public decimal d08Month { get; set; } public decimal d09Month { get; set; } public decimal d10Month { get; set; } public decimal d11Month { get; set; } public decimal d12Month { get; set; } public decimal d13Month { get; set; } public decimal d14Month { get; set; } public decimal d15Month { get; set; } public decimal d16Month { get; set; } public decimal d17Month { get; set; } public decimal d18Month { get; set; } public decimal d19Month { get; set; } public decimal d20Month { get; set; } public decimal d21Month { get; set; } public decimal d22Month { get; set; } public decimal d23Month { get; set; } public decimal d24Month { get; set; } public decimal d25Month { get; set; } public decimal d26Month { get; set; } public decimal d27Month { get; set; } public decimal d28Month { get; set; } public decimal d29Month { get; set; } public decimal d30Month { get; set; } public decimal d31Month { get; set; } public decimal d32Month { get; set; } public decimal d33Month { get; set; } public decimal d34Month { get; set; } public decimal d35Month { get; set; } public decimal d36Month { get; set; } public decimal d37Month { get; set; } public decimal d38Month { get; set; } public decimal d39Month { get; set; } public decimal d40Month { get; set; } public decimal d41Month { get; set; } public decimal d42Month { get; set; } public decimal d43Month { get; set; } public decimal d44Month { get; set; } public decimal d45Month { get; set; } public decimal d46Month { get; set; } public decimal d47Month { get; set; } public decimal d48Month { get; set; } } }
43.574468
84
0.58252
[ "Apache-2.0" ]
RetroRabbit/CDS-Core
CDS.Core.Client.DataAccessLayer/DB/Readonly/VW_OrderInventoryHistory.cs
4,096
C#
๏ปฟ using DotNetNuke.Entities.Modules; public class NZSolutionSettingsBase : ModuleSettingsBase { }
14.142857
56
0.818182
[ "MIT" ]
EL-BID/Nexso
VS2013_PROJECT/NZPortalWeb/DesktopModules/Nexso/NZSolution/NZSolutionModuleSettingsBase.cs
101
C#
// Copyright (c) 2021 homuler // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. using System.Collections.Generic; using UnityEngine; namespace Mediapipe.Unity { public class CuboidListAnnotation : ListAnnotation<CuboidAnnotation> { [SerializeField] private Color _pointColor = Color.green; [SerializeField] private Color _lineColor = Color.red; [SerializeField, Range(0, 1)] private float _lineWidth = 1.0f; [SerializeField] private float _arrowCapScale = 2.0f; [SerializeField] private float _arrowLengthScale = 1.0f; [SerializeField, Range(0, 1)] private float _arrowWidth = 1.0f; private void OnValidate() { ApplyPointColor(_pointColor); ApplyLineColor(_lineColor); ApplyLineWidth(_lineWidth); ApplyArrowCapScale(_arrowCapScale); ApplyArrowLengthScale(_arrowLengthScale); ApplyArrowWidth(_arrowWidth); } public void SetPointColor(Color pointColor) { _pointColor = pointColor; ApplyPointColor(pointColor); } public void SetLineColor(Color lineColor) { _lineColor = lineColor; ApplyLineColor(lineColor); } public void SetLineWidth(float lineWidth) { _lineWidth = lineWidth; ApplyLineWidth(lineWidth); } public void SetArrowCapScale(float arrowCapScale) { _arrowCapScale = arrowCapScale; ApplyArrowCapScale(arrowCapScale); } public void SetArrowLengthScale(float arrowLengthScale) { _arrowLengthScale = arrowLengthScale; ApplyArrowLengthScale(arrowLengthScale); } public void SetArrowWidth(float arrowWidth) { _arrowWidth = arrowWidth; ApplyArrowWidth(arrowWidth); } public void Draw(IList<ObjectAnnotation> targets, Vector2 focalLength, Vector2 principalPoint, float scale, bool visualizeZ = true) { if (ActivateFor(targets)) { CallActionForAll(targets, (annotation, target) => { if (annotation != null) { annotation.Draw(target, focalLength, principalPoint, scale, visualizeZ); } }); } } public void Draw(FrameAnnotation target, Vector2 focalLength, Vector2 principalPoint, float scale, bool visualizeZ = true) { Draw(target?.Annotations, focalLength, principalPoint, scale, visualizeZ); } protected override CuboidAnnotation InstantiateChild(bool isActive = true) { var annotation = base.InstantiateChild(isActive); annotation.SetPointColor(_pointColor); annotation.SetLineColor(_lineColor); annotation.SetLineWidth(_lineWidth); annotation.SetArrowCapScale(_arrowCapScale); annotation.SetArrowLengthScale(_arrowLengthScale); annotation.SetArrowWidth(_arrowWidth); return annotation; } private void ApplyPointColor(Color pointColor) { foreach (var cuboid in children) { if (cuboid != null) { cuboid.SetPointColor(pointColor); } } } private void ApplyLineColor(Color lineColor) { foreach (var cuboid in children) { if (cuboid != null) { cuboid.SetLineColor(lineColor); } } } private void ApplyLineWidth(float lineWidth) { foreach (var cuboid in children) { if (cuboid != null) { cuboid.SetLineWidth(lineWidth); } } } private void ApplyArrowCapScale(float arrowCapScale) { foreach (var cuboid in children) { if (cuboid != null) { cuboid.SetArrowCapScale(arrowCapScale); } } } private void ApplyArrowLengthScale(float arrowLengthScale) { foreach (var cuboid in children) { if (cuboid != null) { cuboid.SetArrowLengthScale(arrowLengthScale); } } } private void ApplyArrowWidth(float arrowWidth) { foreach (var cuboid in children) { if (cuboid != null) { cuboid.SetArrowWidth(arrowWidth); } } } } }
27.840278
135
0.671988
[ "MIT" ]
62-26Nonny/MuscleLand
Packages/com.github.homuler.mediapipe/Runtime/Scripts/Unity/Annotation/CuboidListAnnotation.cs
4,009
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Get a route point's holiday service settings. /// The response is either a GroupRoutePointHolidayServiceGetResponse20 or an ErrorResponse. /// <see cref="GroupRoutePointHolidayServiceGetResponse20"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""a27224a048c30ff69eab9209dec841cc:703""}]")] public class GroupRoutePointHolidayServiceGetRequest20 : BroadWorksConnector.Ocip.Models.C.OCIRequest { private string _serviceUserId; [XmlElement(ElementName = "serviceUserId", IsNullable = false, Namespace = "")] [Group(@"a27224a048c30ff69eab9209dec841cc:703")] [MinLength(1)] [MaxLength(161)] public string ServiceUserId { get => _serviceUserId; set { ServiceUserIdSpecified = true; _serviceUserId = value; } } [XmlIgnore] protected bool ServiceUserIdSpecified { get; set; } } }
31.162791
129
0.65597
[ "MIT" ]
JTOne123/broadworks-connector-net
BroadworksConnector/Ocip/Models/GroupRoutePointHolidayServiceGetRequest20.cs
1,340
C#
๏ปฟusing System; using System.Collections.Generic; using System.IO; using System.Security.Cryptography; using System.Text; namespace ASF.Internal.Security { public static class RSA { //encoded OID sequence for PKCS #1 rsaEncryption szOID_RSA_RSA = "1.2.840.113549.1.1.1" private static byte[] SeqOID = { 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00 }; private static byte[] Seq = new byte[15]; /// <summary> /// ็ญพๅ /// </summary> /// <param name="content">็ญพๅๅ†…ๅฎน</param> /// <param name="privateKey">็ง้’ฅ</param> /// <param name="encoding">็ผ–็ ็ฑปๅž‹</param> /// <param name="hashAlgorithm">ๅŠ ๅฏ†ๆ–นๅผ</param> /// <returns>ๅŠ ๅฏ†ๅฏ†ๆ–‡</returns> public static string Sign(string content, string privateKey, Encoding encoding, HashAlgorithmName hashAlgorithm) { var rsa = System.Security.Cryptography.RSA.Create(); rsa.ImportParameters(DecodePkcsPrivateKey(privateKey)); var contentBytes = encoding.GetBytes(content); var cipherBytes = rsa.SignData(contentBytes, hashAlgorithm, RSASignaturePadding.Pkcs1); return Convert.ToBase64String(cipherBytes); } /// <summary> /// ้ชŒ่ฏ็ญพๅ /// </summary> /// <param name="content">้ชŒ่ฏ็ญพๅๅ†…ๅฎน</param> /// <param name="publicKey">ๅ…ฌ้’ฅ</param> /// <param name="sign">็ญพๅๅฏ†ๆ–‡</param> /// <param name="encoding">็ผ–็ ็ฑปๅž‹</param> /// <param name="hashAlgorithm">ๅŠ ๅฏ†ๆ–นๅผ</param> /// <returns>ๅŠ ๅฏ†ๅฏ†ๆ–‡</returns> public static bool CheckSign(string content, string publicKey, string sign, Encoding encoding, HashAlgorithmName hashAlgorithm) { var rsa = System.Security.Cryptography.RSA.Create(); rsa.ImportParameters(DecodePkcsPublicKey(publicKey)); var contentBytes = encoding.GetBytes(content); var signBytes = Convert.FromBase64String(sign); return rsa.VerifyData(contentBytes, signBytes, hashAlgorithm, RSASignaturePadding.Pkcs1); } /// <summary> /// ่งฃๅฏ† /// </summary> /// <param name="cipher">ๅฏ†ๆ–‡</param> /// <param name="privateKey">็ง้’ฅ</param> /// <param name="encoding">็ผ–็ </param> /// <returns>ๆ˜Žๆ–‡</returns> public static string Decrypt(string cipher, string privateKey, Encoding encoding) { var rsa = System.Security.Cryptography.RSA.Create(); rsa.ImportParameters(DecodePkcsPrivateKey(privateKey)); var cipherBytes = System.Convert.FromBase64String(cipher); var plainTextBytes = rsa.Decrypt(cipherBytes, RSAEncryptionPadding.Pkcs1); return encoding.GetString(plainTextBytes); } /// <summary> /// ๅŠ ๅฏ† /// </summary> /// <param name="plainText ">ๆ˜Žๆ–‡</param> /// <param name="publicKey">ๅ…ฌ้’ฅ</param> /// <param name="encoding">็ผ–็ </param> /// <returns>ๅฏ†ๆ–‡</returns> public static string Encrypt(string plainText, string publicKey, Encoding encoding) { var rsa = System.Security.Cryptography.RSA.Create(); rsa.ImportParameters(DecodePkcsPublicKey(publicKey)); var plainTextBytes = Encoding.UTF8.GetBytes(plainText); var cipherBytes = rsa.Encrypt(plainTextBytes, RSAEncryptionPadding.Pkcs1); return Convert.ToBase64String(cipherBytes); } public static RSAParameters DecodePkcsPublicKey(string publicKey) { if (string.IsNullOrEmpty(publicKey)) throw new ArgumentNullException("publicKey", "This arg cann't be empty."); publicKey = publicKey.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "").Replace("\n", "").Replace("\r", ""); var publicKeyData = Convert.FromBase64String(publicKey); //็”ŸๆˆRSAๅ‚ๆ•ฐ var rsaParams = new RSAParameters(); // --------- Set up stream to read the asn.1 encoded SubjectPublicKeyInfo blob ----- using (BinaryReader binr = new BinaryReader(new MemoryStream(publicKeyData))) { byte bt = 0; ushort twobytes = 0; twobytes = binr.ReadUInt16(); if (twobytes == 0x8130)//data read as little endian order (actual data order for Sequence is 30 81) binr.ReadByte(); //advance 1 byte else if (twobytes == 0x8230) binr.ReadInt16(); //advance 2 bytes else throw new ArgumentException("PemToXmlPublicKey Conversion failed"); Seq = binr.ReadBytes(15); //read the Sequence OID if (!CompareBytearrays(Seq, SeqOID)) //make sure Sequence for OID is correct throw new ArgumentException("PemToXmlPublicKey Conversion failed"); twobytes = binr.ReadUInt16(); if (twobytes == 0x8103) //data read as little endian order (actual data order for Bit String is 03 81) binr.ReadByte(); //advance 1 byte else if (twobytes == 0x8203) binr.ReadInt16(); //advance 2 bytes else throw new ArgumentException("PemToXmlPublicKey Conversion failed"); bt = binr.ReadByte(); if (bt != 0x00) //expect null byte next throw new ArgumentException("PemToXmlPublicKey Conversion failed"); twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) binr.ReadByte(); //advance 1 byte else if (twobytes == 0x8230) binr.ReadInt16(); //advance 2 bytes else throw new ArgumentException("PemToXmlPublicKey Conversion failed"); twobytes = binr.ReadUInt16(); byte lowbyte = 0x00; byte highbyte = 0x00; if (twobytes == 0x8102) //data read as little endian order (actual data order for Integer is 02 81) lowbyte = binr.ReadByte(); // read next bytes which is bytes in modulus else if (twobytes == 0x8202) { highbyte = binr.ReadByte(); //advance 2 bytes lowbyte = binr.ReadByte(); } else throw new ArgumentException("PemToXmlPublicKey Conversion failed"); byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; //reverse byte order since asn.1 key uses big endian order int modsize = BitConverter.ToInt32(modint, 0); int firstbyte = binr.PeekChar(); if (firstbyte == 0x00) { //if first byte (highest order) of modulus is zero, don't include it binr.ReadByte(); //skip this null byte modsize -= 1; //reduce modulus buffer size by 1 } byte[] modulus = binr.ReadBytes(modsize); //read the modulus bytes if (binr.ReadByte() != 0x02) //expect an Integer for the exponent data throw new ArgumentException("PemToXmlPublicKey Conversion failed"); int expbytes = (int)binr.ReadByte(); // should only need one byte for actual exponent data (for all useful values) byte[] exponent = binr.ReadBytes(expbytes); // ------- create RSACryptoServiceProvider instance and initialize with public key ----- rsaParams.Modulus = modulus; rsaParams.Exponent = exponent; } return rsaParams; } public static RSAParameters DecodePkcsPrivateKey(string privateKey) { if (string.IsNullOrEmpty(privateKey)) { throw new ArgumentNullException("pemFileConent", "This arg cann't be empty."); } try { privateKey = privateKey.Replace("-----BEGIN RSA PRIVATE KEY-----", "").Replace("-----END RSA PRIVATE KEY-----", "").Replace("\n", "").Replace("\r", ""); var privateKeyData = Convert.FromBase64String(privateKey); //่งฃๆžPkcs่ฏไนฆ PKCSType type = GetPrivateKeyType(privateKeyData.Length); if (type == PKCSType.PKCS_8_1024 || type == PKCSType.PKCS_8_2048) { //Pkcs#8็ง˜้’ฅ้œ€่ฆ็‰นๆฎŠๅค„็† privateKeyData = DecodePkcs8PrivateKey(privateKeyData); } var rsaParams = new RSAParameters(); byte bt = 0; ushort twobytes = 0; //่ฝฌๆขไธบไบŒ่ฟ›ๅˆถๅ€ผ using (var binr = new BinaryReader(new MemoryStream(privateKeyData))) { twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) binr.ReadByte(); else if (twobytes == 0x8230) binr.ReadInt16(); else throw new ArgumentException("Unexpected value read )"); twobytes = binr.ReadUInt16(); if (twobytes != 0x0102) throw new ArgumentException("Unexpected version"); bt = binr.ReadByte(); if (bt != 0x00) throw new ArgumentException("Unexpected value read "); //่ฝฌๆขXML rsaParams.Modulus = binr.ReadBytes(GetIntegerSize(binr)); rsaParams.Exponent = binr.ReadBytes(GetIntegerSize(binr)); rsaParams.D = binr.ReadBytes(GetIntegerSize(binr)); rsaParams.P = binr.ReadBytes(GetIntegerSize(binr)); rsaParams.Q = binr.ReadBytes(GetIntegerSize(binr)); rsaParams.DP = binr.ReadBytes(GetIntegerSize(binr)); rsaParams.DQ = binr.ReadBytes(GetIntegerSize(binr)); rsaParams.InverseQ = binr.ReadBytes(GetIntegerSize(binr)); } return rsaParams; } catch (Exception ex) { throw new ArgumentException("ๆญค็ง้’ฅ่ฏไนฆๆ— ๆ•ˆ", ex); } } /// <summary> /// Pkcs#8 ่ฏไนฆ่งฃๅฏ† /// </summary> /// <param name="privateKeyData"></param> /// <returns></returns> private static byte[] DecodePkcs8PrivateKey(byte[] privateKeyData) { byte bt = 0; ushort twobytes = 0; MemoryStream mem = new MemoryStream(privateKeyData); int lenstream = (int)mem.Length; using (var binr = new BinaryReader(mem)) { twobytes = binr.ReadUInt16(); if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) binr.ReadByte(); //advance 1 byte else if (twobytes == 0x8230) binr.ReadInt16(); //advance 2 bytes else throw new Exception("Unexpected value read"); bt = binr.ReadByte(); if (bt != 0x02) throw new Exception("Unexpected version"); twobytes = binr.ReadUInt16(); if (twobytes != 0x0001) throw new Exception("Unexpected value read"); Seq = binr.ReadBytes(15); //read the Sequence OID if (!CompareBytearrays(Seq, SeqOID)) //make sure Sequence for OID is correct throw new Exception("Unexpected value read"); bt = binr.ReadByte(); if (bt != 0x04) //expect an Octet string throw new Exception("Unexpected value read"); bt = binr.ReadByte(); //read next byte, or next 2 bytes is 0x81 or 0x82; otherwise bt is the byte count if (bt == 0x81) binr.ReadByte(); else if (bt == 0x82) binr.ReadUInt16(); //------ at this stage, the remaining sequence should be the RSA private key return binr.ReadBytes((int)(lenstream - mem.Position)); } } /// <summary> /// ่Žทๅ–Integer็š„ๅคงๅฐ /// </summary> /// <param name="binr"></param> /// <returns></returns> private static int GetIntegerSize(BinaryReader binr) { byte bt = 0; byte lowbyte = 0x00; byte highbyte = 0x00; int count = 0; bt = binr.ReadByte(); if (bt != 0x02) return 0; bt = binr.ReadByte(); if (bt == 0x81) count = binr.ReadByte(); else if (bt == 0x82) { highbyte = binr.ReadByte(); lowbyte = binr.ReadByte(); byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; count = BitConverter.ToInt32(modint, 0); } else { count = bt; } while (binr.ReadByte() == 0x00) { count -= 1; } binr.BaseStream.Seek(-1, SeekOrigin.Current); return count; } private static bool CompareBytearrays(byte[] a, byte[] b) { if (a.Length != b.Length) return false; int i = 0; foreach (byte c in a) { if (c != b[i]) return false; i++; } return true; } /// <summary> /// ่Žทๅ–็ง้’ฅ็š„็ฑปๅž‹ /// </summary> /// <param name="privateKeyLength"></param> /// <returns></returns> private static PKCSType GetPrivateKeyType(int privateKeyLength) { if (privateKeyLength >= 630 && privateKeyLength <= 640) return PKCSType.PKCS_8_1024; if (privateKeyLength >= 600 && privateKeyLength <= 610) return PKCSType.PKCS_1_1024; if (privateKeyLength >= 1210 && privateKeyLength <= 1220) return PKCSType.PKCS_8_2048; if (privateKeyLength >= 1190 && privateKeyLength <= 1199) return PKCSType.PKCS_1_2048; else throw new ArgumentException("ๆญค็ง้’ฅ่ฏไนฆๆ ‡ๅ‡†ไธๆ”ฏๆŒ"); } } public enum PKCSType { PKCS_1_1024, PKCS_1_2048, PKCS_8_1024, PKCS_8_2048, } }
41.548747
168
0.523599
[ "MIT" ]
AClumsy/ASF
src/ASF.Core/Internal/Security/RSA.cs
15,170
C#
๏ปฟusing CourseTracker.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace CourseTrackerApi { public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); Database.SetInitializer<CourseTrackerContext>(new CourseTrackerInitializer()); } } }
29.035714
90
0.726937
[ "MIT" ]
MichaelGustavsson/8440-20486
Mod13/CourseTrackerApi/Global.asax.cs
815
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. 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 TencentCloud.Monitor.V20180724.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class DataPoint : AbstractModel { /// <summary> /// ๅฎžไพ‹ๅฏน่ฑก็ปดๅบฆ็ป„ๅˆ /// </summary> [JsonProperty("Dimensions")] public Dimension[] Dimensions{ get; set; } /// <summary> /// ๆ—ถ้—ดๆˆณๆ•ฐ็ป„๏ผŒ่กจ็คบ้‚ฃไบ›ๆ—ถ้—ด็‚นๆœ‰ๆ•ฐๆฎ๏ผŒ็ผบๅคฑ็š„ๆ—ถ้—ดๆˆณ๏ผŒๆฒกๆœ‰ๆ•ฐๆฎ็‚น๏ผŒๅฏไปฅ็†่งฃไธบๆމ็‚นไบ† /// </summary> [JsonProperty("Timestamps")] public float?[] Timestamps{ get; set; } /// <summary> /// ็›‘ๆŽงๅ€ผๆ•ฐ็ป„๏ผŒ่ฏฅๆ•ฐ็ป„ๅ’ŒTimestampsไธ€ไธ€ๅฏนๅบ” /// </summary> [JsonProperty("Values")] public float?[] Values{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamArrayObj(map, prefix + "Dimensions.", this.Dimensions); this.SetParamArraySimple(map, prefix + "Timestamps.", this.Timestamps); this.SetParamArraySimple(map, prefix + "Values.", this.Values); } } }
31.051724
83
0.629095
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Monitor/V20180724/Models/DataPoint.cs
1,921
C#
๏ปฟnamespace Xtrimmer.SqlDatabaseBuilder { internal class NVarChar : VariableCharacterSet { internal NVarChar() { } internal NVarChar(int n) { if (n == -1) { isMax = true; } else { N = n; } } protected override string TypeValue => "nvarchar"; protected override int MaxN => 4000; public override int Size => isMax ? MAX_SIZE : (2 * n) + 2; } }
20.68
67
0.45648
[ "Apache-2.0" ]
Xtrimmer/SqlDatabaseBuilder
src/SqlDatabaseBuilder/DataTypes/CharacterSet/NVarChar.cs
519
C#
using System; namespace LINE_Webhook.Areas.HelpPage.ModelDescriptions { /// <summary> /// Use this attribute to change the name of the <see cref="ModelDescription"/> generated for a type. /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, AllowMultiple = false, Inherited = false)] public sealed class ModelNameAttribute : Attribute { public ModelNameAttribute(string name) { Name = name; } public string Name { get; private set; } } }
31.277778
136
0.667851
[ "MIT" ]
Jutha1234/linebotTest
LINE-Webhook/Areas/HelpPage/ModelDescriptions/ModelNameAttribute.cs
563
C#
#pragma checksum "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\Books1\Create.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "1d0a25611d6bde0d2e2de31299f5787e9c5c836e" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Books1_Create), @"mvc.1.0.view", @"/Views/Books1/Create.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\_ViewImports.cshtml" using BookStore3; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\_ViewImports.cshtml" using BookStore3.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"1d0a25611d6bde0d2e2de31299f5787e9c5c836e", @"/Views/Books1/Create.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"b446c1f233e0cf277ca7694d68c2b1289de69aba", @"/Views/_ViewImports.cshtml")] public class Views_Books1_Create : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<BookStore3.Models.Book> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("text-danger"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("control-label"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-control"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Create", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("\r\n"); #nullable restore #line 3 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\Books1\Create.cshtml" ViewData["Title"] = "Create"; #line default #line hidden #nullable disable WriteLiteral("\r\n<h1>Create</h1>\r\n\r\n<h4>Book</h4>\r\n<hr />\r\n<div class=\"row\">\r\n <div class=\"col-md-4\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "1d0a25611d6bde0d2e2de31299f5787e9c5c836e5930", async() => { WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("div", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "1d0a25611d6bde0d2e2de31299f5787e9c5c836e6200", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationSummaryTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper); #nullable restore #line 14 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\Books1\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary = global::Microsoft.AspNetCore.Mvc.Rendering.ValidationSummary.ModelOnly; #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-summary", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationSummaryTagHelper.ValidationSummary, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "1d0a25611d6bde0d2e2de31299f5787e9c5c836e7922", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 16 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\Books1\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Title); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "1d0a25611d6bde0d2e2de31299f5787e9c5c836e9512", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 17 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\Books1\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Title); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "1d0a25611d6bde0d2e2de31299f5787e9c5c836e11096", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #nullable restore #line 18 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\Books1\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Title); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "1d0a25611d6bde0d2e2de31299f5787e9c5c836e12821", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 21 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\Books1\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Genre); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "1d0a25611d6bde0d2e2de31299f5787e9c5c836e14412", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 22 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\Books1\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Genre); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "1d0a25611d6bde0d2e2de31299f5787e9c5c836e15997", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #nullable restore #line 23 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\Books1\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Genre); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "1d0a25611d6bde0d2e2de31299f5787e9c5c836e17722", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 26 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\Books1\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Price); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "1d0a25611d6bde0d2e2de31299f5787e9c5c836e19313", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 27 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\Books1\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Price); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "1d0a25611d6bde0d2e2de31299f5787e9c5c836e20898", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #nullable restore #line 28 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\Books1\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Price); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("label", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "1d0a25611d6bde0d2e2de31299f5787e9c5c836e22623", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.LabelTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper); #nullable restore #line 31 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\Books1\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.PublishDate); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_LabelTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "1d0a25611d6bde0d2e2de31299f5787e9c5c836e24220", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 32 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\Books1\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.PublishDate); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("span", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "1d0a25611d6bde0d2e2de31299f5787e9c5c836e25811", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.ValidationMessageTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper); #nullable restore #line 33 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\Books1\Create.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.PublishDate); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-validation-for", __Microsoft_AspNetCore_Mvc_TagHelpers_ValidationMessageTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n <div class=\"form-group\">\r\n <input type=\"submit\" value=\"Create\" class=\"btn btn-primary\" />\r\n </div>\r\n "); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n</div>\r\n\r\n<div>\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "1d0a25611d6bde0d2e2de31299f5787e9c5c836e28858", async() => { WriteLiteral("Back to List"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_4.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n</div>\r\n\r\n"); DefineSection("Scripts", async() => { WriteLiteral("\r\n"); #nullable restore #line 47 "C:\Users\seda3\source\repos\BookStore3\BookStore3\Views\Books1\Create.cshtml" await Html.RenderPartialAsync("_ValidationScriptsPartial"); #line default #line hidden #nullable disable } ); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<BookStore3.Models.Book> Html { get; private set; } } } #pragma warning restore 1591
72.912736
351
0.736148
[ "MIT" ]
AkarSeda/BookStore3
BookStore3/obj/Debug/net5.0/Razor/Views/Books1/Create.cshtml.g.cs
30,915
C#
๏ปฟusing System; namespace NullArgumentExceptions.Classes; public class MyClassDotNet6 { private readonly string paramName; public MyClassDotNet6(string paramName) { ArgumentNullException.ThrowIfNull(paramName); this.paramName = paramName; } public static string MyMethod(string paramName) { ArgumentNullException.ThrowIfNull(paramName); return paramName; } }
20.095238
53
0.708531
[ "MIT" ]
DamirsCorner/20211224-dotnet-null-argument-exceptions
NullArgumentExceptions/Classes/MyClassDotNet6.cs
424
C#
๏ปฟusing System.Net; using System.Threading.Tasks; using NUnit.Framework; using SnelStart.B2B.V2.Client.Operations; namespace SnelStart.B2B.V2.Client.IntegrationTest { public abstract class CrudTest<T> where T : IIdentifierModel { protected abstract Task<T> CreateNewModelAsync(); protected abstract ICrudOperations<T> CrudSubject { get; } [Test] public async Task DeleteAsync() { var createResponse = await SetupCreatedAsync(); var deleteResponse = await CrudSubject.DeleteAsync(createResponse.Result.Id); var getByIdResponse = await CrudSubject.GetByIdAsync(createResponse.Result.Id); Assert.AreEqual(HttpStatusCode.OK, deleteResponse.HttpStatusCode); Assert.AreEqual(HttpStatusCode.NotFound, getByIdResponse.HttpStatusCode); } [Test] public async Task GetByIdAsync() { var createResponse = await SetupCreatedAsync(); try { var getByIdResponse = await CrudSubject.GetByIdAsync(createResponse.Result.Id); Assert.AreEqual(HttpStatusCode.OK, getByIdResponse.HttpStatusCode); } finally { await CrudSubject.DeleteAsync(createResponse.Result.Id); } } [Test] public async Task UpdateAsync() { var createResponse = await SetupCreatedAsync(); var createdModel = createResponse.Result; try { var updateResponse = await CrudSubject.UpdateAsync(createdModel); Assert.AreEqual(HttpStatusCode.OK, updateResponse.HttpStatusCode); } finally { await CrudSubject.DeleteAsync(createdModel.Id); } } private async Task<Response<T>> SetupCreatedAsync() { var dto = await CreateNewModelAsync(); var createResponse = await CrudSubject.CreateAsync(dto); if (createResponse.HttpStatusCode != HttpStatusCode.Created) { Assert.Inconclusive($"dto not created Status {createResponse.HttpStatusCode}, Response:\r\n{createResponse.ResponseBody}"); } return createResponse; } } }
32.361111
139
0.608155
[ "MIT" ]
BeyondDefinition/B2B.client.v2.net
SnelStart.B2B.V2.Client.IntegrationTest/CrudTest.cs
2,332
C#
๏ปฟusing Kadmium_sACN.MulticastAddressProvider; using Kadmium_Udp; using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Text; namespace Kadmium_sACN.SacnReceiver { public class MulticastSacnReceiverIPV4 : MulticastSacnReceiver { internal MulticastSacnReceiverIPV4(IUdpWrapper udpWrapper, ISacnMulticastAddressProvider multicastAddressProvider) : base(udpWrapper, multicastAddressProvider) { } public MulticastSacnReceiverIPV4() : base(new UdpWrapper(), new SacnMulticastAddressProviderIPV4()) { } public override void Listen(IPAddress ipAddress) { if (ipAddress.AddressFamily != AddressFamily.InterNetwork) { throw new ArgumentException("The given IP Address was not an IPv4 Address"); } ListenInternal(ipAddress); } } }
26.16129
161
0.789149
[ "MIT" ]
iKadmium/kadmium-sacn
Kadmium-sACN/SacnReceiver/MulticastSacnReceiverIPV4.cs
813
C#
๏ปฟusing System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("AttachmentsSampleSystem.Core")] [assembly: ComVisible(false)]
31.2
58
0.801282
[ "MIT" ]
Luxoft/BSSFramework.Attachments
src/_AttachmentsSampleSystem/AttachmentsSampleSystem.Core/Properties/AssemblyInfo.cs
154
C#
using System; namespace Senai.Tsushi.MVC.ViewModel { public class ProdutoViewModel : BaseViewModel { public string Descricao {get; set;} public float Preco {get; set;} public string Categoria {get; set;} } }
22.181818
49
0.651639
[ "MIT" ]
matheusamaralima/Tsushi
ViewModel/ProdutoViewModel.cs
244
C#
๏ปฟusing System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Newster.Services")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Newster.Services")] [assembly: AssemblyCopyright("Copyright ยฉ 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e61dca2c-1662-42aa-9035-c7134dab182b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.916667
84
0.748718
[ "MIT" ]
vladislav-karamfilov/TelerikAcademy
Hybrid Mobile Applications Projects/Newster/Newster.Services/Properties/AssemblyInfo.cs
1,368
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; namespace Baseline { public static class StringExtensions { /// <summary> /// If the path is rooted, just returns the path. Otherwise, /// combines root & path /// </summary> /// <param name="path"></param> /// <param name="root"></param> /// <returns></returns> public static string CombineToPath(this string path, string root) { if (Path.IsPathRooted(path)) return path; return Path.Combine(root, path); } public static void IfNotNull(this string? target, Action<string> continuation) { if (target != null) { continuation(target); } } public static string ToFullPath(this string path) { return Path.GetFullPath(path); } /// <summary> /// Retrieve the parent directory of a directory or file /// Shortcut to Path.GetDirectoryName(path) /// </summary> /// <param name="path"></param> /// <returns></returns> public static string? ParentDirectory(this string path) { return Path.GetDirectoryName(path.TrimEnd(Path.DirectorySeparatorChar)); } /// <summary> /// Equivalent of FileSystem.Combine( [Union of path, parts] ) /// </summary> /// <param name="path"></param> /// <param name="parts"></param> /// <returns></returns> public static string AppendPath(this string path, params string[] parts) { var list = new List<string>{ path }; list.AddRange(parts); return FileSystem.Combine(list.ToArray()); } public static string PathRelativeTo(this string path, string root) { var pathParts = path.getPathParts(); var rootParts = root.getPathParts(); var length = pathParts.Count > rootParts.Count ? rootParts.Count : pathParts.Count; for (int i = 0; i < length; i++) { if (pathParts.First() == rootParts.First()) { pathParts.RemoveAt(0); rootParts.RemoveAt(0); } else { break; } } for (int i = 0; i < rootParts.Count; i++) { pathParts.Insert(0, ".."); } return pathParts.Count > 0 ? FileSystem.Combine(pathParts.ToArray()) : string.Empty; } public static bool IsEmpty([NotNullWhen(false)] this string? stringValue) { return string.IsNullOrEmpty(stringValue); } public static bool IsNotEmpty([NotNullWhen(true)] this string? stringValue) { return !string.IsNullOrEmpty(stringValue); } public static void IsNotEmpty([NotNullWhen(true)] this string? stringValue, Action<string> action) { if (stringValue.IsNotEmpty()) action(stringValue); } public static bool ToBool(this string stringValue) { if (string.IsNullOrEmpty(stringValue)) return false; return bool.Parse(stringValue); } public static string ToFormat(this string stringFormat, params object[] args) { return String.Format(stringFormat, args); } /// <summary> /// Performs a case-insensitive comparison of strings /// </summary> public static bool EqualsIgnoreCase(this string thisString, string otherString) { return thisString.Equals(otherString, StringComparison.CurrentCultureIgnoreCase); } /// <summary> /// Converts the string to Title Case /// </summary> public static string Capitalize(this string stringValue) { #if NET451 return CultureInfo.CurrentCulture.TextInfo.ToTitleCase(stringValue); #else StringBuilder result = new StringBuilder(stringValue); result[0] = char.ToUpper(result[0]); for (int i = 1; i < result.Length; ++i) { if (char.IsWhiteSpace(result[i - 1]) && !char.IsWhiteSpace(result[i])) result[i] = char.ToUpper(result[i]); } return result.ToString(); #endif } /// <summary> /// Formats a multi-line string for display on the web /// </summary> /// <param name="plainText"></param> public static string ConvertCRLFToBreaks(this string plainText) { return new Regex("(\r\n|\n)").Replace(plainText, "<br/>"); } /// <summary> /// Returns a DateTime value parsed from the <paramref name="dateTimeValue"/> parameter. /// </summary> /// <param name="dateTimeValue">A valid, parseable DateTime value</param> /// <returns>The parsed DateTime value</returns> public static DateTime ToDateTime(this string dateTimeValue) { return DateTime.Parse(dateTimeValue); } public static string ToGmtFormattedDate(this DateTime date) { return date.ToString("yyyy'-'MM'-'dd hh':'mm':'ss tt 'GMT'"); } public static string[] ToDelimitedArray(this string content) { return content.ToDelimitedArray(','); } public static string[] ToDelimitedArray(this string content, char delimiter) { string[] array = content.Split(delimiter); for (int i = 0; i < array.Length; i++) { array[i] = array[i].Trim(); } return array; } public static bool IsValidNumber(this string number) { return IsValidNumber(number, CultureInfo.CurrentCulture); } public static bool IsValidNumber(this string number, CultureInfo culture) { string _validNumberPattern = @"^-?(?:\d+|\d{1,3}(?:" + culture.NumberFormat.NumberGroupSeparator + @"\d{3})+)?(?:\" + culture.NumberFormat.NumberDecimalSeparator + @"\d+)?$"; return new Regex(_validNumberPattern, RegexOptions.ECMAScript).IsMatch(number); } public static IList<string> getPathParts(this string path) { return path.Split(new[] {Path.DirectorySeparatorChar}, StringSplitOptions.RemoveEmptyEntries).ToList(); } public static string? DirectoryPath(this string path) { return Path.GetDirectoryName(path); } /// <summary> /// Reads text and returns an enumerable of strings for each line /// </summary> /// <param name="text"></param> /// <returns></returns> public static IEnumerable<string> ReadLines(this string text) { var reader = new StringReader(text); string? line; while ((line = reader.ReadLine()) != null) { yield return line; } } /// <summary> /// Reads text and calls back for each line of text /// </summary> /// <param name="text"></param> /// <returns></returns> public static void ReadLines(this string text, Action<string> callback) { var reader = new StringReader(text); string? line; while ((line = reader.ReadLine()) != null) { callback(line); } } /// <summary> /// Just uses MD5 to create a repeatable hash /// </summary> /// <param name="text"></param> /// <returns></returns> public static string ToHash(this string text) { return MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(text)).Select(b => b.ToString("x2")).Join(""); } /// <summary> /// Splits a camel cased string into seperate words delimitted by a space /// </summary> /// <param name="str"></param> /// <returns></returns> public static string SplitCamelCase(this string str) { return Regex.Replace(Regex.Replace(str, @"(\P{Ll})(\P{Ll}\p{Ll})", "$1 $2"), @"(\p{Ll})(\P{Ll})", "$1 $2"); } /// <summary> /// Splits a pascal cased string into seperate words delimitted by a space /// </summary> /// <param name="str"></param> /// <returns></returns> public static string SplitPascalCase(this string str) { return SplitCamelCase(str); } public static string ToCamelCase(this string s) { if (string.IsNullOrEmpty(s) || !char.IsUpper(s[0])) { return s; } char[] chars = s.ToCharArray(); for (int i = 0; i < chars.Length; i++) { if (i == 1 && !char.IsUpper(chars[i])) { break; } bool hasNext = (i + 1 < chars.Length); if (i > 0 && hasNext && !char.IsUpper(chars[i + 1])) { break; } chars[i] = char.ToLowerInvariant(chars[i]); } return new string(chars); } public static TEnum ToEnum<TEnum>(this string text) where TEnum : struct { var enumType = typeof (TEnum); if(!enumType.GetTypeInfo().IsEnum) throw new ArgumentException("{0} is not an Enum".ToFormat(enumType.Name)); return (TEnum) Enum.Parse(enumType, text, true); } /// <summary> /// Wraps a string with parantheses. Originally used to file escape file names when making command line calls /// </summary> /// <param name="file"></param> /// <returns></returns> public static string FileEscape(this string file) { return "\"{0}\"".ToFormat(file); } /// <summary> /// Replace only the first instance of the "search" string with the value /// of "replace" /// </summary> /// <param name="text"></param> /// <param name="search"></param> /// <param name="replace"></param> /// <returns></returns> public static string ReplaceFirst(this string text, string search, string replace) { int pos = text.IndexOf(search); if (pos < 0) { return text; } return text.Substring(0, pos) + replace + text.Substring(pos + search.Length); } /// <summary> /// string.Contains() with finer grained case sensitivity settings /// </summary> /// <param name="source"></param> /// <param name="value"></param> /// <param name="comparison"></param> /// <returns></returns> public static bool Contains(this string source, string value, StringComparison comparison) { return source.IndexOf(value, comparison) >= 0; } /// <summary> /// string.Contains() with OrdinalIgnoreCase semantics /// </summary> /// <param name="source"></param> /// <param name="value"></param> /// <returns></returns> public static bool ContainsIgnoreCase(this string source, string value) { return source.Contains(value, StringComparison.OrdinalIgnoreCase); } } }
32.673025
121
0.532316
[ "Apache-2.0" ]
JasperFx/Baseline
src/Baseline/StringExtensions.cs
11,991
C#
๏ปฟ// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Practices.DataPipeline.Logging { using Microsoft.Practices.DataPipeline.Logging.NLog; /// <summary> /// Generic pluggable logger factory for retrieving configured /// logging objects /// </summary> public abstract class LoggerFactory { #region "Singleton Implementation" private static ILogFactory _loggerFactory = null; private static object _lockObj = new object(); protected static ILogFactory _factory { get { if (_loggerFactory == null) { lock (_lockObj) { if (_loggerFactory == null) { _loggerFactory = new NLoggerFactory(); } } } return _loggerFactory; } } #endregion public static void Register(ILogFactory factory) { lock (_lockObj) { _loggerFactory = factory; } } public static void Initialize() { if (_loggerFactory != null) _loggerFactory.Initialize(); } public static ILogger GetLogger<T>() { return _factory.Create(typeof(T).Name); } public static ILogger GetLogger() { return _factory.Create(); } public static ILogger GetLogger(string logName) { return _factory.Create(logName); } } public interface ILogFactory { ILogger Create(); ILogger Create(string name); void Initialize(); } }
24.727273
101
0.511555
[ "MIT" ]
averyspa/data-pipeline
src/Implementation/Shared/Core/Logging/LoggerFactory.cs
1,906
C#
using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = Intrinio.Client.SwaggerDateConverter; namespace Intrinio.Model { /// <summary> /// A stock price adjustment for a security on a given day, most frequently representing a split and/or dividend. /// </summary> [DataContract] public partial class StockPriceAdjustment : IEquatable<StockPriceAdjustment>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="StockPriceAdjustment" /> class. /// </summary> /// <param name="Date">The date on which the adjustment occurred. The adjustment should be applied to all stock prices before this date..</param> /// <param name="Factor">The factor by which to multiply stock prices before this date, in order to calculate historically-adjusted stock prices..</param> /// <param name="Dividend">The dividend amount, if a dividend was paid..</param> /// <param name="DividendCurrency">The currency of the dividend, if known..</param> /// <param name="SplitRatio">The ratio of the stock split, if a stock split occurred..</param> /// <param name="Security">The Security of the stock price.</param> public StockPriceAdjustment(DateTime? Date = default(DateTime?), decimal? Factor = default(decimal?), decimal? Dividend = default(decimal?), string DividendCurrency = default(string), decimal? SplitRatio = default(decimal?), SecuritySummary Security = default(SecuritySummary)) { this.Date = Date; this.Factor = Factor; this.Dividend = Dividend; this.DividendCurrency = DividendCurrency; this.SplitRatio = SplitRatio; this.Security = Security; } /// <summary> /// The date on which the adjustment occurred. The adjustment should be applied to all stock prices before this date. /// </summary> /// <value>The date on which the adjustment occurred. The adjustment should be applied to all stock prices before this date.</value> [DataMember(Name="date", EmitDefaultValue=false)] [JsonConverter(typeof(SwaggerDateConverter))] public DateTime? Date { get; set; } /// <summary> /// The factor by which to multiply stock prices before this date, in order to calculate historically-adjusted stock prices. /// </summary> /// <value>The factor by which to multiply stock prices before this date, in order to calculate historically-adjusted stock prices.</value> [DataMember(Name="factor", EmitDefaultValue=false)] public decimal? Factor { get; set; } /// <summary> /// The dividend amount, if a dividend was paid. /// </summary> /// <value>The dividend amount, if a dividend was paid.</value> [DataMember(Name="dividend", EmitDefaultValue=false)] public decimal? Dividend { get; set; } /// <summary> /// The currency of the dividend, if known. /// </summary> /// <value>The currency of the dividend, if known.</value> [DataMember(Name="dividend_currency", EmitDefaultValue=false)] public string DividendCurrency { get; set; } /// <summary> /// The ratio of the stock split, if a stock split occurred. /// </summary> /// <value>The ratio of the stock split, if a stock split occurred.</value> [DataMember(Name="split_ratio", EmitDefaultValue=false)] public decimal? SplitRatio { get; set; } /// <summary> /// The Security of the stock price /// </summary> /// <value>The Security of the stock price</value> [DataMember(Name="security", EmitDefaultValue=false)] public SecuritySummary Security { 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 StockPriceAdjustment {\n"); sb.Append(" Date: ").Append(Date).Append("\n"); sb.Append(" Factor: ").Append(Factor).Append("\n"); sb.Append(" Dividend: ").Append(Dividend).Append("\n"); sb.Append(" DividendCurrency: ").Append(DividendCurrency).Append("\n"); sb.Append(" SplitRatio: ").Append(SplitRatio).Append("\n"); sb.Append(" Security: ").Append(Security).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 string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as StockPriceAdjustment); } /// <summary> /// Returns true if StockPriceAdjustment instances are equal /// </summary> /// <param name="input">Instance of StockPriceAdjustment to be compared</param> /// <returns>Boolean</returns> public bool Equals(StockPriceAdjustment input) { if (input == null) return false; return ( this.Date == input.Date || (this.Date != null && this.Date.Equals(input.Date)) ) && ( this.Factor == input.Factor || (this.Factor != null && this.Factor.Equals(input.Factor)) ) && ( this.Dividend == input.Dividend || (this.Dividend != null && this.Dividend.Equals(input.Dividend)) ) && ( this.DividendCurrency == input.DividendCurrency || (this.DividendCurrency != null && this.DividendCurrency.Equals(input.DividendCurrency)) ) && ( this.SplitRatio == input.SplitRatio || (this.SplitRatio != null && this.SplitRatio.Equals(input.SplitRatio)) ) && ( this.Security == input.Security || (this.Security != null && this.Security.Equals(input.Security)) ); } /// <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.Date != null) hashCode = hashCode * 59 + this.Date.GetHashCode(); if (this.Factor != null) hashCode = hashCode * 59 + this.Factor.GetHashCode(); if (this.Dividend != null) hashCode = hashCode * 59 + this.Dividend.GetHashCode(); if (this.DividendCurrency != null) hashCode = hashCode * 59 + this.DividendCurrency.GetHashCode(); if (this.SplitRatio != null) hashCode = hashCode * 59 + this.SplitRatio.GetHashCode(); if (this.Security != null) hashCode = hashCode * 59 + this.Security.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
43.45098
286
0.558664
[ "MIT" ]
KolesnichenkoDS/intrinio-netcore
Intrinio/Model/StockPriceAdjustment.cs
8,864
C#
๏ปฟ// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Linq; using osu.Framework.Audio; using osu.Framework.Audio.Track; using osu.Framework.Graphics.Textures; using osu.Framework.Graphics.Video; using osu.Framework.IO.Stores; using osu.Framework.Logging; using osu.Game.Beatmaps.Formats; using osu.Game.IO; using osu.Game.Skinning; using osu.Game.Storyboards; namespace osu.Game.Beatmaps { public partial class BeatmapManager { protected class BeatmapManagerWorkingBeatmap : WorkingBeatmap { private readonly IResourceStore<byte[]> store; public BeatmapManagerWorkingBeatmap(IResourceStore<byte[]> store, TextureStore textureStore, BeatmapInfo beatmapInfo, AudioManager audioManager) : base(beatmapInfo, audioManager) { this.store = store; this.textureStore = textureStore; } protected override IBeatmap GetBeatmap() { try { using (var stream = new LineBufferedReader(store.GetStream(getPathForFile(BeatmapInfo.Path)))) return Decoder.GetDecoder<Beatmap>(stream).Decode(stream); } catch { return null; } } private string getPathForFile(string filename) => BeatmapSetInfo.Files.FirstOrDefault(f => string.Equals(f.Filename, filename, StringComparison.InvariantCultureIgnoreCase))?.FileInfo.StoragePath; private TextureStore textureStore; private ITrackStore trackStore; protected override bool BackgroundStillValid(Texture b) => false; // bypass lazy logic. we want to return a new background each time for refcounting purposes. protected override Texture GetBackground() { if (Metadata?.BackgroundFile == null) return null; try { return textureStore.Get(getPathForFile(Metadata.BackgroundFile)); } catch { return null; } } protected override VideoSprite GetVideo() { if (Metadata?.VideoFile == null) return null; try { return new VideoSprite(textureStore.GetStream(getPathForFile(Metadata.VideoFile))); } catch { return null; } } protected override Track GetTrack() { try { return (trackStore ??= AudioManager.GetTrackStore(store)).Get(getPathForFile(Metadata.AudioFile)); } catch { return null; } } public override void RecycleTrack() { base.RecycleTrack(); trackStore?.Dispose(); trackStore = null; } public override void TransferTo(WorkingBeatmap other) { base.TransferTo(other); if (other is BeatmapManagerWorkingBeatmap owb && textureStore != null && BeatmapInfo.BackgroundEquals(other.BeatmapInfo)) owb.textureStore = textureStore; } protected override Waveform GetWaveform() { try { var trackData = store.GetStream(getPathForFile(Metadata.AudioFile)); return trackData == null ? null : new Waveform(trackData); } catch { return null; } } protected override Storyboard GetStoryboard() { Storyboard storyboard; try { using (var stream = new LineBufferedReader(store.GetStream(getPathForFile(BeatmapInfo.Path)))) { var decoder = Decoder.GetDecoder<Storyboard>(stream); // todo: support loading from both set-wide storyboard *and* beatmap specific. if (BeatmapSetInfo?.StoryboardFile == null) storyboard = decoder.Decode(stream); else { using (var secondaryStream = new LineBufferedReader(store.GetStream(getPathForFile(BeatmapSetInfo.StoryboardFile)))) storyboard = decoder.Decode(stream, secondaryStream); } } } catch (Exception e) { Logger.Error(e, "Storyboard failed to load"); storyboard = new Storyboard(); } storyboard.BeatmapInfo = BeatmapInfo; return storyboard; } protected override ISkin GetSkin() { try { return new LegacyBeatmapSkin(BeatmapInfo, store, AudioManager); } catch (Exception e) { Logger.Error(e, "Skin failed to load"); return null; } } } } }
34.229412
208
0.486853
[ "MIT" ]
Luxiono/osu
osu.Game/Beatmaps/BeatmapManager_WorkingBeatmap.cs
5,652
C#
๏ปฟ//------------------------------------------------------------------------------ // <่‡ชๅ‹•็”ข็”Ÿ็š„> // ้€™ๆฎต็จ‹ๅผ็ขผๆ˜ฏ็”ฑๅทฅๅ…ท็”ข็”Ÿ็š„ใ€‚ // // ่ฎŠๆ›ด้€™ๅ€‹ๆช”ๆกˆๅฏ่ƒฝๆœƒๅฐŽ่‡ดไธๆญฃ็ขบ็š„่กŒ็‚บ๏ผŒ่€Œไธ”ๅฆ‚ๆžœๅทฒ้‡ๆ–ฐ็”ข็”Ÿ // ็จ‹ๅผ็ขผ๏ผŒๅ‰‡ๆœƒ้บๅคฑ่ฎŠๆ›ดใ€‚ // </่‡ชๅ‹•็”ข็”Ÿ็š„> //------------------------------------------------------------------------------ namespace Questionnaire1029.SystemAdmin { public partial class Detail { /// <summary> /// btnSurvey ๆŽงๅˆถ้ …ใ€‚ /// </summary> /// <remarks> /// ่‡ชๅ‹•็”ข็”Ÿ็š„ๆฌ„ไฝใ€‚ /// ่‹ฅ่ฆไฟฎๆ”น๏ผŒ่ซ‹ๅฐ‡ๆฌ„ไฝๅฎฃๅ‘Šๅพž่จญ่จˆๅทฅๅ…ทๆช”ๆกˆ็งปๅˆฐ็จ‹ๅผ็ขผๅพŒ็ฝฎๆช”ๆกˆใ€‚ /// </remarks> protected global::System.Web.UI.WebControls.Button btnSurvey; /// <summary> /// btnQa ๆŽงๅˆถ้ …ใ€‚ /// </summary> /// <remarks> /// ่‡ชๅ‹•็”ข็”Ÿ็š„ๆฌ„ไฝใ€‚ /// ่‹ฅ่ฆไฟฎๆ”น๏ผŒ่ซ‹ๅฐ‡ๆฌ„ไฝๅฎฃๅ‘Šๅพž่จญ่จˆๅทฅๅ…ทๆช”ๆกˆ็งปๅˆฐ็จ‹ๅผ็ขผๅพŒ็ฝฎๆช”ๆกˆใ€‚ /// </remarks> protected global::System.Web.UI.WebControls.Button btnQa; /// <summary> /// btnData ๆŽงๅˆถ้ …ใ€‚ /// </summary> /// <remarks> /// ่‡ชๅ‹•็”ข็”Ÿ็š„ๆฌ„ไฝใ€‚ /// ่‹ฅ่ฆไฟฎๆ”น๏ผŒ่ซ‹ๅฐ‡ๆฌ„ไฝๅฎฃๅ‘Šๅพž่จญ่จˆๅทฅๅ…ทๆช”ๆกˆ็งปๅˆฐ็จ‹ๅผ็ขผๅพŒ็ฝฎๆช”ๆกˆใ€‚ /// </remarks> protected global::System.Web.UI.WebControls.Button btnData; /// <summary> /// btnCount ๆŽงๅˆถ้ …ใ€‚ /// </summary> /// <remarks> /// ่‡ชๅ‹•็”ข็”Ÿ็š„ๆฌ„ไฝใ€‚ /// ่‹ฅ่ฆไฟฎๆ”น๏ผŒ่ซ‹ๅฐ‡ๆฌ„ไฝๅฎฃๅ‘Šๅพž่จญ่จˆๅทฅๅ…ทๆช”ๆกˆ็งปๅˆฐ็จ‹ๅผ็ขผๅพŒ็ฝฎๆช”ๆกˆใ€‚ /// </remarks> protected global::System.Web.UI.WebControls.Button btnCount; /// <summary> /// IFRAME1 ๆŽงๅˆถ้ …ใ€‚ /// </summary> /// <remarks> /// ่‡ชๅ‹•็”ข็”Ÿ็š„ๆฌ„ไฝใ€‚ /// ่‹ฅ่ฆไฟฎๆ”น๏ผŒ่ซ‹ๅฐ‡ๆฌ„ไฝๅฎฃๅ‘Šๅพž่จญ่จˆๅทฅๅ…ทๆช”ๆกˆ็งปๅˆฐ็จ‹ๅผ็ขผๅพŒ็ฝฎๆช”ๆกˆใ€‚ /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlIframe IFRAME1; } }
25.269841
81
0.458543
[ "MIT" ]
thousandtw/Questionnaire
Questionnaire1029/Questionnaire1029/SystemAdmin/Detail.aspx.designer.cs
2,116
C#
๏ปฟusing System; namespace DomainBlocks.Serialization { public interface IEventPersistenceData<out TRawData> { Guid EventId { get; } string EventName { get; } string ContentType { get; } TRawData EventData { get; } TRawData EventMetadata { get; } } }
23.153846
56
0.624585
[ "MIT" ]
JohnCgp/domain-blocks
src/DomainBlocks.Serialization/IEventPersistenceData.cs
303
C#
๏ปฟnamespace ASPCore.Angular.EntityFrameworkCore.Seed.Host { public class InitialHostDbBuilder { private readonly AngularDbContext _context; public InitialHostDbBuilder(AngularDbContext context) { _context = context; } public void Create() { new DefaultEditionCreator(_context).Create(); new DefaultLanguagesCreator(_context).Create(); new HostRoleAndUserCreator(_context).Create(); new DefaultSettingsCreator(_context).Create(); _context.SaveChanges(); } } }
26.130435
61
0.62396
[ "MIT" ]
nhungsky/KBook
aspnet-core/src/ASPCore.Angular.EntityFrameworkCore/EntityFrameworkCore/Seed/Host/InitialHostDbBuilder.cs
603
C#
๏ปฟusing MTGAHelper.Lib.IoC; using MTGAHelper.Lib.OutputLogParser.EventsSchedule; using MTGAHelper.Lib.OutputLogParser.InMatchTracking; using MTGAHelper.Lib.OutputLogParser.InMatchTracking.GameEvents; using MTGAHelper.Lib.OutputLogParser.Models.GRE.ClientToMatch; using MTGAHelper.Lib.OutputLogParser.OutputLogProgress; using MTGAHelper.Lib.OutputLogParser.Readers; using MTGAHelper.Lib.OutputLogParser.Readers.GreMessageType; using MTGAHelper.Lib.OutputLogParser.Readers.MTGAProLogger; using MTGAHelper.Lib.OutputLogParser.Readers.UnityCrossThreadLogger; using SimpleInjector; namespace MTGAHelper.Lib.OutputLogParser.IoC { public static class SimpleInjectorRegistrations { public static Container RegisterServicesLibOutputLogParser(this Container container) { container.RegisterSingleton<IEventTypeCache, SimpleEventCache>(); container.RegisterSingleton<AutoMapperEventNameToTypeConverter>(); container.RegisterSingleton<DeckListConverter>(); container.RegisterSingleton<CourseDeckCardsConverter>(); container.RegisterSingleton<EventSetDeckToCardsConverter>(); container.Collection.Append<AutoMapper.Profile, MapperProfileLibCardConvert>(Lifestyle.Singleton); container.Collection.Append<AutoMapper.Profile, MapperProfileLibOutputLogParser>(Lifestyle.Singleton); container.Register<ReaderMtgaOutputLog>(); //container.Register<ReaderMtgaOutputLogGre>(); container.Register<ReaderDetailedLogs>(); container.Register<ReaderMessageSummarized>(); container.Register<ReaderAccountsClient>(); container.Register<ReaderAccountsAccountClient>(); container.Register<ReaderMtgaOutputLogUnityCrossThreadLogger>(); container.Register<ReaderMtgaProLogger>(); container.Collection.Register<IMessageReaderUnityCrossThreadLogger>(typeof(IMessageReaderUnityCrossThreadLogger).Assembly); container.Collection.Register<IMessageReaderMtgaProLogger>(typeof(IMessageReaderMtgaProLogger).Assembly); container.Collection.Register<IMessageReaderRequestToServer>(typeof(IMessageReaderRequestToServer).Assembly); container.Register<AuthenticateResponseConverter>(); // === GreMessageType readers === // container.Register<DieRollResultsRespConverter>(); container.Register<GameStateMessageConverter>(); container.Register<GreConnectRespConverter>(); container.Register<GroupReqConverter>(); container.Register<IntermissionReqConverter>(); container.Register<MulliganReqConverter>(); container.Register<QueuedGameStateMessageConverter>(); container.Register<SelectNReqConverter>(); container.Register<SubmitDeckReqConverter>(); // === ClientToMatch readers === // container.Register<ClientToMatchConverter<PayloadSubmitDeckResp>>(); container.Register<ClientToMatchConverter<PayloadEnterSideboardingReq>>(); container.Register<LogSplitter>(); container.Register<MtgaOutputLogResultsPreparer>(); container.Register<OutputLogMessagesBatcher>(); container.Register<ZipDeflator>(); return container; } public static Container RegisterFileLoaders(this Container container) { container.RegisterFileLoadersShared(); container.RegisterSingleton<IPossibleDateFormats, DateFormatsFromFile>(); return container; } public static Container RegisterServicesTracker(this Container container) { container.Register<InGameTracker2>(); container.Register<InGameTrackerState2>(); container.Register<GameEventFactory>(); container.RegisterSingleton<DraftPicksCalculator>(); return container; } } }
48
135
0.721888
[ "MIT" ]
DuncanmaMSFT/MTGAHelper-Windows-Client
MTGAHelper.Lib.OutputLogParser/IoC/SimpleInjectorRegistrations.cs
3,986
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SMSPortalCross { public class Messages { public const int LOGGER_FILE_CREATE = 101; public const int WEBSERVICE_ADD_TO_QUEUE = 201; public const int WEBSERVICE_PROCESS_SCHEDULE_QUEUE = 202; public const int GSM_HANDLER_QUEUE_MAKER = 303; public const int GSM_HANDLER_ADD_QUEUE_PHONE = 304; public const int GSM_HANDLER_PUSH_BY_SCHEDULE = 305; public const int HANDLER_RUN_SERVICE = 401; public const int CONNECTOR_MAIN = 501; public const int CONNECTOR_TIMER_EVENT = 502; public const int CONNECTOR_GET_QUEUE_ITEM = 503; public const int CONNECTOR_SEND = 504; public const int CONNECTOR_ON_SEND = 505; public const int SCHEDULE_CONSOL = 601; } }
22.372093
65
0.659044
[ "MIT" ]
eabasir/sms-portal
SMSPortalCross/Messages.cs
964
C#
๏ปฟ// Dragon6 API Copyright DragonFruit Network <inbox@dragonfruit.network> // Licensed under Apache-2. Refer to the LICENSE file for more info using System; namespace DragonFruit.Six.Api.Exceptions { public class UbisoftErrorException : Exception { public UbisoftErrorException() : base("A Ubisoft server has disallowed this request, probably due to the Ubi-AppId header. Please check and try again") { } } }
28.625
132
0.700873
[ "Apache-2.0" ]
dragonfruitnetwork/Dragon6-API
DragonFruit.Six.Api/Exceptions/UbisoftErrorException.cs
460
C#
๏ปฟusing Basket.API.Entities; using System.Threading.Tasks; namespace Basket.API.Repositories.IRepository { public interface IBasketRepository { Task<ShoppingCart> GetBasket(string userName); Task<ShoppingCart> UpdateBasket(ShoppingCart basket); Task DeleteBasket(string userName); } }
24.692308
61
0.732087
[ "MIT" ]
dwivedi-ankita/AspnetMicroservices
src/Services/Basket/Basket.API/Repositories/IRepository/IBasketRepository.cs
323
C#
๏ปฟusing System; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace systemDaemon { public class DaemonService : IHostedService, IDisposable { private readonly ILogger _logger; private readonly IOptions<DaemonConfig> _config; public DaemonService(ILogger<DaemonService> logger, IOptions<DaemonConfig> config) { _logger = logger; _config = config; } public Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("Starting daemon: " + _config.Value.DaemonName); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { _logger.LogInformation("Stopping daemon."); return Task.CompletedTask; } public void Dispose() { _logger.LogInformation("Disposing...."); } } }
27.552632
90
0.64852
[ "Apache-2.0" ]
Kcils360/systemDaemon
systemDaemon/lib/daemon/DaemonService.cs
1,049
C#
๏ปฟusing System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("DayOfWeekInBulgarianConsoleClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DayOfWeekInBulgarianConsoleClient")] [assembly: AssemblyCopyright("Copyright ยฉ 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d732615b-cb22-455d-9bf7-d1c63b4b9940")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.891892
84
0.752606
[ "MIT" ]
vladislav-karamfilov/TelerikAcademy
Web Services Projects/Homework-WindowsCommunicationFoundation/DayOfWeekInBulgarianConsoleClient/Properties/AssemblyInfo.cs
1,442
C#
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace Couchbase.Linq.QueryGeneration.MethodCallTranslators { class StringTrimMethodCallTranslator : IMethodCallTranslator { private static readonly MethodInfo[] SupportedMethodsStatic = { typeof (string).GetMethod("Trim", Type.EmptyTypes), typeof (string).GetMethod("Trim", new[] { typeof (char[]) }), typeof (string).GetMethod("TrimStart"), typeof (string).GetMethod("TrimEnd") }; public IEnumerable<MethodInfo> SupportMethods { get { return SupportedMethodsStatic; } } public Expression Translate(MethodCallExpression methodCallExpression, N1QlExpressionTreeVisitor expressionTreeVisitor) { if (methodCallExpression == null) { throw new ArgumentNullException("methodCallExpression"); } var expression = expressionTreeVisitor.Expression; expression.Append(methodCallExpression.Method.Name == "TrimStart" ? "LTRIM(" : methodCallExpression.Method.Name == "TrimEnd" ? "RTRIM(" : "TRIM("); expressionTreeVisitor.VisitExpression(methodCallExpression.Object); if (methodCallExpression.Arguments.Count > 0) { if (methodCallExpression.Arguments[0].Type != typeof (char[])) { throw new NotSupportedException("String Trim Operations Expect Character Array Parameters"); } try { var lambda = Expression.Lambda<Func<char[]>>(methodCallExpression.Arguments[0]).Compile(); var chars = lambda.Invoke(); if ((chars != null) && (chars.Length > 0)) { expression.Append(", "); expressionTreeVisitor.VisitExpression(Expression.Constant(new String(chars), typeof (string))); } } catch (NotSupportedException ex) { throw; } catch (Exception ex) { throw new NotSupportedException("Unable To Parse Trim Character Set. Dynamic Expressions Are Not Supported", ex); } } expression.Append(")"); return methodCallExpression; } } }
34.285714
134
0.557576
[ "Apache-2.0" ]
amccool/Linq2Couchbase
Src/Couchbase.Linq/QueryGeneration/MethodCallTranslators/StringTrimMethodCallTranslator.cs
2,642
C#
namespace EmailHeaderInspector.Models { public class IPGeolocationResult { [ValidIPAddress] public string ip { get; set; } public string city { get; set; } public string state { get; set; } public string country { get; set; } public string asn { get; set; } } }
21.307692
37
0.685921
[ "MIT" ]
eragonriddle/emailheaderinspector
Models/IPGeolocationResult.cs
277
C#
๏ปฟ/** *โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” *โ”‚ใ€€ๆ ่ฟฐ๏ผšๆ•ฐๆฎๅบ“่ฟžๆŽฅ้€‰้กน *โ”‚ใ€€ไฝœ ่€…๏ผšyilezhu *โ”‚ใ€€็‰ˆ ๆœฌ๏ผš1.0 *โ”‚ใ€€ๅˆ›ๅปบๆ—ถ้—ด๏ผš2018/12/16 22:08:46 *โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ *โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” *โ”‚ใ€€ๅ‘ฝๅ็ฉบ้—ด๏ผš Czar.Cms.Core.Options *โ”‚ใ€€็ฑป ๅ๏ผš DbOpion *โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ */ namespace Czar.Cms.Core.Options { public class DbOption { /// <summary> /// ๆ•ฐๆฎๅบ“่ฟžๆŽฅๅญ—็ฌฆไธฒ /// </summary> public string ConnectionString { get; set; } /// <summary> /// ๆ•ฐๆฎๅบ“็ฑปๅž‹ /// </summary> public string DbType { get; set; } } }
33.857143
69
0.227848
[ "MIT" ]
RookieBoy666/Czar.Cms-master
src/Czar.Cms.Core/Options/DbOption.cs
1,570
C#
๏ปฟ/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ using NPOI.POIFS.Properties; namespace TestCases.POIFS.Storage { public class LocalProperty : NPOI.POIFS.Properties.Property { /** * Constructor TestProperty * * @param name name of the property */ public LocalProperty(string name) : base() { Name = name; } /** * do nothing */ public override void PreWrite() { } /** * @return false */ public override bool IsDirectory { get { return false; } } } }
29.188679
75
0.575953
[ "Apache-2.0" ]
0xAAE/npoi
testcases/main/POIFS/Storage/LocalProperty.cs
1,549
C#
๏ปฟusing System.Collections.Generic; namespace Nomad.DotNet.Model { public class TaskDiff : ApiObject<TaskDiff> { public string Type { get; set; } public string Name { get; set; } public IList<FieldDiff> Fields { get; set; } = new List<FieldDiff>(); public IList<ObjectDiff> Objects { get; set; } = new List<ObjectDiff>(); public IList<string> Annotations { get; set; } = new List<string>(); } }
34.307692
80
0.627803
[ "MIT" ]
pedrostc/nomad-dotnet-sdk
src/Nomad.DotNet/Model/TaskDiff.cs
448
C#
using NetWork.Utilities; using ProtoBuf; using System; using System.Collections.Generic; using System.ComponentModel; namespace Package { [ForRecv(768), ForSend(768), ProtoContract(Name = "RoleAttrChangedNty")] [Serializable] public class RoleAttrChangedNty : IExtensible { [ProtoContract(Name = "AttrPair")] [Serializable] public class AttrPair : IExtensible { private int _attrType; private long _attrValue; private IExtension extensionObject; [ProtoMember(1, IsRequired = true, Name = "attrType", DataFormat = DataFormat.TwosComplement)] public int attrType { get { return this._attrType; } set { this._attrType = value; } } [ProtoMember(2, IsRequired = true, Name = "attrValue", DataFormat = DataFormat.TwosComplement)] public long attrValue { get { return this._attrValue; } set { this._attrValue = value; } } IExtension IExtensible.GetExtensionObject(bool createIfMissing) { return Extensible.GetExtensionObject(ref this.extensionObject, createIfMissing); } } public static readonly short OP = 768; private GameObjectType.ENUM _type; private long _id; private readonly List<RoleAttrChangedNty.AttrPair> _attrs = new List<RoleAttrChangedNty.AttrPair>(); private IExtension extensionObject; [ProtoMember(1, IsRequired = false, Name = "type", DataFormat = DataFormat.TwosComplement), DefaultValue(GameObjectType.ENUM.Role)] public GameObjectType.ENUM type { get { return this._type; } set { this._type = value; } } [ProtoMember(2, IsRequired = false, Name = "id", DataFormat = DataFormat.TwosComplement), DefaultValue(0L)] public long id { get { return this._id; } set { this._id = value; } } [ProtoMember(3, Name = "attrs", DataFormat = DataFormat.Default)] public List<RoleAttrChangedNty.AttrPair> attrs { get { return this._attrs; } } IExtension IExtensible.GetExtensionObject(bool createIfMissing) { return Extensible.GetExtensionObject(ref this.extensionObject, createIfMissing); } } }
20.245283
133
0.687791
[ "MIT" ]
corefan/tianqi_src
src/Package/RoleAttrChangedNty.cs
2,146
C#
๏ปฟusing System; namespace L03.VariationsNoRepetition { internal class Program { private static int K; private static string[] Input; private static string[] Variations; private static bool[] IsUsed; static void Main(string[] args) { Input = Console.ReadLine().Split(); K = int.Parse(Console.ReadLine()); Variations = new string[K]; IsUsed = new bool[Input.Length]; Variate(0); } private static void Variate(int index) { if (index >= Variations.Length) { Console.WriteLine(string.Join(" ", Variations)); return; } for (int i = 0; i < Input.Length; i++) { if (!IsUsed[i]) { IsUsed[i] = true; Variations[index] = Input[i]; Variate(index + 1); IsUsed[i] = false; } } } } }
24.581395
64
0.441816
[ "MIT" ]
vassdeniss/software-university-courses
csharp-algorithms-fundamentals/02.CombinatorialProblems/L03.VariationsNoRepetition/Program.cs
1,059
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Schema; using System.Xml.Serialization; namespace Workday.PerformanceManagement { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Question_CategoryObjectIDType : INotifyPropertyChanged { private string typeField; private string valueField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlAttribute(Form = XmlSchemaForm.Qualified)] public string type { get { return this.typeField; } set { this.typeField = value; this.RaisePropertyChanged("type"); } } [XmlText] public string Value { get { return this.valueField; } set { this.valueField = value; this.RaisePropertyChanged("Value"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
20.868852
136
0.729772
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.PerformanceManagement/Question_CategoryObjectIDType.cs
1,273
C#