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
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using Microsoft.ApplicationInsights.Channel; using Microsoft.ApplicationInsights.DataContracts; using Microsoft.ApplicationInsights.Extensibility.Implementation; using Microsoft.Azure.WebJobs.Host; using Microsoft.Azure.WebJobs.Logging; using Microsoft.Azure.WebJobs.Script.Rpc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.WebJobs.Script.Tests; using Newtonsoft.Json.Linq; using Xunit; namespace Microsoft.Azure.WebJobs.Script.Tests.ApplicationInsights { public abstract class ApplicationInsightsEndToEndTestsBase<TTestFixture> : IClassFixture<TTestFixture> where TTestFixture : ApplicationInsightsTestFixture, new() { private ApplicationInsightsTestFixture _fixture; public ApplicationInsightsEndToEndTestsBase(ApplicationInsightsTestFixture fixture) { _fixture = fixture; } [Fact] public async Task Validate_Manual() { string functionName = "Scenarios"; int invocationCount = 5; List<string> functionTraces = new List<string>(); // We want to invoke this multiple times specifically to make sure Node invocationIds // are correctly being set. Invoke them all first, then come back and validate all. for (int i = 0; i < invocationCount; i++) { string functionTrace = $"Function trace: {Guid.NewGuid().ToString()}"; functionTraces.Add(functionTrace); JObject input = new JObject() { { "scenario", "appInsights" }, { "container", "not-used" }, { "value", functionTrace } }; await _fixture.TestHost.BeginFunctionAsync(functionName, input); } // Now validate each function invocation. foreach (string functionTrace in functionTraces) { await WaitForFunctionTrace(functionName, functionTrace); string invocationId = ValidateEndToEndTest(functionName, functionTrace, true); // TODO: Remove this check when metrics are supported in Node: // https://github.com/Azure/azure-functions-host/issues/2189 if (this is ApplicationInsightsCSharpEndToEndTests) { // Do some additional metric validation MetricTelemetry metric = _fixture.Channel.Telemetries .OfType<MetricTelemetry>() .Where(t => GetInvocationId(t) == invocationId) .Single(); ValidateMetric(metric, invocationId, functionName); } } } [Fact(Skip = "HTTP logging not currently supported")] public async Task Validate_Http_Success() { await RunHttpTest("HttpTrigger-Scenarios", "appInsights-Success", HttpStatusCode.OK, true); } [Fact(Skip = "HTTP logging not currently supported")] public async Task Validate_Http_Failure() { await RunHttpTest("HttpTrigger-Scenarios", "appInsights-Failure", HttpStatusCode.Conflict, true); } [Fact(Skip = "HTTP logging not currently supported")] public async Task Validate_Http_Throw() { await RunHttpTest("HttpTrigger-Scenarios", "appInsights-Throw", HttpStatusCode.InternalServerError, false); } private async Task RunHttpTest(string functionName, string scenario, HttpStatusCode expectedStatusCode, bool functionSuccess) { HttpRequestMessage request = new HttpRequestMessage { RequestUri = new Uri($"https://localhost/api/{functionName}"), Method = HttpMethod.Post, }; string functionTrace = $"Function trace: {Guid.NewGuid().ToString()}"; JObject input = new JObject() { { "scenario", scenario }, { "container", "not-used" }, { "value", functionTrace }, }; request.Content = new StringContent(input.ToString()); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); request.Content.Headers.ContentLength = input.ToString().Length; HttpResponseMessage response = await _fixture.HttpClient.SendAsync(request); Assert.Equal(expectedStatusCode, response.StatusCode); string invocationId = ValidateEndToEndTest(functionName, functionTrace, functionSuccess); // Perform some additional validation on HTTP properties RequestTelemetry requestTelemetry = _fixture.Channel.Telemetries .OfType<RequestTelemetry>() .Where(t => GetInvocationId(t) == invocationId) .Single(); Assert.Equal(((int)expectedStatusCode).ToString(), requestTelemetry.ResponseCode); Assert.Equal("POST", requestTelemetry.Properties["HttpMethod"]); Assert.Equal(request.RequestUri, requestTelemetry.Url); Assert.Equal(functionSuccess, requestTelemetry.Success); } private string ValidateEndToEndTest(string functionName, string functionTrace, bool functionSuccess) { // Look for the trace that matches the GUID we passed in. That's how we'll find the // function's invocation id. TraceTelemetry trace = _fixture.Channel.Telemetries .OfType<TraceTelemetry>() .Where(t => t.Message.Contains(functionTrace)) .Single(); // functions need to log JSON that contains the invocationId and trace JObject logPayload = JObject.Parse(trace.Message); string logInvocationId = logPayload["invocationId"].ToString(); string invocationId = trace.Properties[LogConstants.InvocationIdKey]; // make sure they match Assert.Equal(logInvocationId, invocationId); // Find the Info traces. TraceTelemetry[] traces = _fixture.Channel.Telemetries .OfType<TraceTelemetry>() .Where(t => GetInvocationId(t) == invocationId) .Where(t => !t.Message.StartsWith("Exception")) // we'll verify the exception message separately .Where(t => t.Properties[LogConstants.CategoryNameKey] == LogCategories.CreateFunctionCategory(functionName)) .OrderBy(t => t.Message) .ToArray(); string expectedMessage = functionSuccess ? $"Executed 'Functions.{functionName}' (Succeeded, Id=" : $"Executed 'Functions.{functionName}' (Failed, Id="; SeverityLevel expectedLevel = functionSuccess ? SeverityLevel.Information : SeverityLevel.Error; ValidateTrace(traces[0], expectedMessage + invocationId, LogCategories.CreateFunctionCategory(functionName), functionName, invocationId, expectedLevel); ValidateTrace(traces[1], $"Executing 'Functions.{functionName}' (Reason='This function was programmatically called via the host APIs.', Id=" + invocationId, LogCategories.CreateFunctionCategory(functionName), functionName, invocationId); if (!functionSuccess) { TraceTelemetry errorTrace = _fixture.Channel.Telemetries .OfType<TraceTelemetry>() .Where(t => GetInvocationId(t) == invocationId) .Where(t => t.Message.Contains("Exception while")) .Single(); ValidateTrace(errorTrace, $"Exception while executing function: Functions.{functionName}.", LogCategories.CreateFunctionCategory(functionName), functionName, invocationId, SeverityLevel.Error); ExceptionTelemetry exception = _fixture.Channel.Telemetries .OfType<ExceptionTelemetry>() .Single(t => GetInvocationId(t) == invocationId); ValidateException(exception, invocationId, functionName, LogCategories.Results); } RequestTelemetry requestTelemetry = _fixture.Channel.Telemetries .OfType<RequestTelemetry>() .Where(t => GetInvocationId(t) == invocationId) .Single(); ValidateRequest(requestTelemetry, invocationId, functionName, "req", functionSuccess); return invocationId; } private async Task WaitForFunctionTrace(string functionName, string functionTrace) { // watch for the specific user log, then make sure the request telemetry has flushed, which // indicates all logging is done for this function invocation await TestHelpers.Await(() => { bool done = false; TraceTelemetry logTrace = _fixture.Channel.Telemetries.OfType<TraceTelemetry>().SingleOrDefault(p => p.Message.Contains(functionTrace) && p.Properties[LogConstants.CategoryNameKey] == LogCategories.CreateFunctionUserCategory(functionName)); if (logTrace != null) { string invocationId = logTrace.Properties[LogConstants.InvocationIdKey]; RequestTelemetry request = _fixture.Channel.Telemetries.OfType<RequestTelemetry>().SingleOrDefault(p => GetInvocationId(p) == invocationId); done = request != null; } return done; }, userMessageCallback: _fixture.TestHost.GetLog); } private void ValidateException(ExceptionTelemetry telemetry, string expectedOperationId, string expectedOperationName, string expectedCategory) { Assert.IsType<FunctionInvocationException>(telemetry.Exception); ValidateTelemetry(telemetry, expectedOperationId, expectedOperationName, expectedCategory, SeverityLevel.Error); } [Fact] public async Task Validate_HostLogs() { // Validate the host startup traces. Order by message string as the requests may come in // slightly out-of-order or on different threads TraceTelemetry[] traces = null; await TestHelpers.Await(() => { traces = _fixture.Channel.Telemetries .OfType<TraceTelemetry>() .Where(t => t.Properties[LogConstants.CategoryNameKey].ToString().StartsWith("Host.")) .OrderBy(t => t.Message) .ToArray(); // When these two messages are logged, we know we've completed initialization. return traces .Where(t => t.Message.Contains("Host lock lease acquired by instance ID") || t.Message.Contains("Job host started")) .Count() == 2; }, userMessageCallback: () => string.Join(Environment.NewLine, _fixture.Channel.Telemetries.OfType<TraceTelemetry>().Select(t => t.Message))); // Excluding Node buffer deprecation warning for now // TODO: Remove this once the issue https://github.com/Azure/azure-functions-nodejs-worker/issues/98 is resolved // We may have any number of "Host Status" calls as we wait for startup. Let's ignore them. traces = traces.Where(t => !t.Message.Contains("[DEP0005]") && !t.Message.StartsWith("Host Status") ).ToArray(); int expectedCount = 12; Assert.True(traces.Length == expectedCount, $"Expected {expectedCount} messages, but found {traces.Length}. Actual logs:{Environment.NewLine}{string.Join(Environment.NewLine, traces.Select(t => t.Message))}"); int idx = 0; ValidateTrace(traces[idx++], "2 functions loaded", LogCategories.Startup); ValidateTrace(traces[idx++], "A function whitelist has been specified", LogCategories.Startup); ValidateTrace(traces[idx++], "Found the following functions:\r\n", LogCategories.Startup); ValidateTrace(traces[idx++], "Generating 2 job function(s)", LogCategories.Startup); ValidateTrace(traces[idx++], "Host initialization: ConsecutiveErrors=0, StartupCount=1", LogCategories.Startup); ValidateTrace(traces[idx++], "Host initialized (", LogCategories.Startup); ValidateTrace(traces[idx++], "Host lock lease acquired by instance ID", ScriptConstants.LogCategoryHostGeneral); ValidateTrace(traces[idx++], "Host started (", LogCategories.Startup); ValidateTrace(traces[idx++], "Initializing Host", LogCategories.Startup); ValidateTrace(traces[idx++], "Job host started", LogCategories.Startup); ValidateTrace(traces[idx++], "Loading functions metadata", LogCategories.Startup); ValidateTrace(traces[idx++], "Starting Host (HostId=", LogCategories.Startup); } [Fact] public void Validate_BeginScope() { TestTelemetryChannel channel = new TestTelemetryChannel(); IHost host = new HostBuilder() .ConfigureAppConfiguration(c => { c.AddInMemoryCollection(new Dictionary<string, string> { { "APPINSIGHTS_INSTRUMENTATIONKEY", "some_key" }, }); }) .ConfigureDefaultTestWebScriptHost(b => { b.Services.AddSingleton<ITelemetryChannel>(_ => channel); }) .Build(); ILoggerFactory loggerFactory = host.Services.GetService<ILoggerFactory>(); // Create a logger and try out the configured factory. We need to pretend that it is coming from a // function, so set the function name and the category appropriately. ILogger logger = loggerFactory.CreateLogger(LogCategories.CreateFunctionCategory("Test")); using (logger.BeginScope(new Dictionary<string, object> { [ScriptConstants.LogPropertyFunctionNameKey] = "Test" })) { // Now log as if from within a function. // Test that both dictionaries and structured logs work as state // and that nesting works as expected. using (logger.BeginScope("{customKey1}", "customValue1")) { logger.LogInformation("1"); using (logger.BeginScope(new Dictionary<string, object> { ["customKey2"] = "customValue2" })) { logger.LogInformation("2"); } logger.LogInformation("3"); } using (logger.BeginScope("should not throw")) { logger.LogInformation("4"); } } TraceTelemetry[] traces = channel.Telemetries.OfType<TraceTelemetry>().OrderBy(t => t.Message).ToArray(); Assert.Equal(4, traces.Length); // Every telemetry will have {originalFormat}, Category, Level, but we validate those elsewhere. // We're only interested in the custom properties. Assert.Equal("1", traces[0].Message); Assert.Equal(4, traces[0].Properties.Count); Assert.Equal("customValue1", traces[0].Properties["prop__customKey1"]); Assert.Equal("2", traces[1].Message); Assert.Equal(5, traces[1].Properties.Count); Assert.Equal("customValue1", traces[1].Properties["prop__customKey1"]); Assert.Equal("customValue2", traces[1].Properties["prop__customKey2"]); Assert.Equal("3", traces[2].Message); Assert.Equal(4, traces[2].Properties.Count); Assert.Equal("customValue1", traces[2].Properties["prop__customKey1"]); Assert.Equal("4", traces[3].Message); Assert.Equal(3, traces[3].Properties.Count); } private static void ValidateMetric(MetricTelemetry telemetry, string expectedOperationId, string expectedOperationName) { ValidateTelemetry(telemetry, expectedOperationId, expectedOperationName, LogCategories.CreateFunctionUserCategory(expectedOperationName), SeverityLevel.Information); Assert.Equal("TestMetric", telemetry.Name); Assert.Equal(1234, telemetry.Sum); Assert.Equal(50, telemetry.Count); Assert.Equal(10.4, telemetry.Min); Assert.Equal(23, telemetry.Max); Assert.Equal("100", telemetry.Properties[$"{LogConstants.CustomPropertyPrefix}MyCustomMetricProperty"]); ValidateSdkVersion(telemetry); } protected static void ValidateTrace(TraceTelemetry telemetry, string expectedMessageContains, string expectedCategory, string expectedOperationName = null, string expectedOperationId = null, SeverityLevel expectedLevel = SeverityLevel.Information) { Assert.Contains(expectedMessageContains, telemetry.Message); Assert.Equal(expectedLevel, telemetry.SeverityLevel); Assert.Equal(expectedCategory, telemetry.Properties[LogConstants.CategoryNameKey]); if (expectedCategory.StartsWith("Function.")) { ValidateTelemetry(telemetry, expectedOperationId, expectedOperationName, expectedCategory, expectedLevel); } else { Assert.Null(telemetry.Context.Operation.Name); Assert.Null(telemetry.Context.Operation.Id); } ValidateSdkVersion(telemetry); } private static void ValidateTelemetry(ITelemetry telemetry, string expectedInvocationId, string expectedOperationName, string expectedCategory, SeverityLevel expectedLevel) { Assert.Equal(expectedInvocationId, ((ISupportProperties)telemetry).Properties[LogConstants.InvocationIdKey]); Assert.Equal(expectedOperationName, telemetry.Context.Operation.Name); ISupportProperties properties = (ISupportProperties)telemetry; Assert.Equal(expectedCategory, properties.Properties[LogConstants.CategoryNameKey]); Assert.Equal(expectedLevel.ToString(), properties.Properties[LogConstants.LogLevelKey]); } private static void ValidateRequest(RequestTelemetry telemetry, string expectedInvocationId, string expectedOperationName, string inputParamName, bool success) { SeverityLevel expectedLevel = success ? SeverityLevel.Information : SeverityLevel.Error; ValidateTelemetry(telemetry, expectedInvocationId, expectedOperationName, LogCategories.Results, expectedLevel); Assert.NotNull(telemetry.Id); Assert.NotNull(telemetry.Duration); Assert.Equal(success, telemetry.Success); AssertHasKey(telemetry.Properties, "FullName", $"Functions.{expectedOperationName}"); AssertHasKey(telemetry.Properties, "TriggerReason", "This function was programmatically called via the host APIs."); ValidateSdkVersion(telemetry); } private static void AssertHasKey(IDictionary<string, string> dict, string keyName, string expectedValue = null) { if (!dict.TryGetValue(keyName, out string actualValue)) { string msg = $"Missing key '{keyName}'. Keys = " + string.Join(", ", dict.Keys); Assert.True(false, msg); } if (expectedValue != null) { Assert.Equal(expectedValue, actualValue); } } private static void ValidateSdkVersion(ITelemetry telemetry) { Assert.StartsWith("azurefunctions: ", telemetry.Context.GetInternalContext().SdkVersion); } private static string GetInvocationId(ISupportProperties telemetry) { telemetry.Properties.TryGetValue(LogConstants.InvocationIdKey, out string id); return id; } } }
47.565217
256
0.624555
[ "MIT" ]
alrod/azure-webjobs-sdk-script
test/WebJobs.Script.Tests.Integration/ApplicationInsights/ApplicationInsightsEndToEndTestsBase.cs
20,788
C#
using FluentValidation; using MediatR; using Microsoft.ApplicationInsights.Extensibility; using Microsoft.AspNetCore.Http; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using PingDong.Azure.FunctionApp; using PingDong.Http; using PingDong.Newmoon.Venues.Services.Commands; using PingDong.Newmoon.Venues.Settings; using System.Net.Http; using System.Threading.Tasks; namespace PingDong.Newmoon.Venues.Endpoints { public class VenueClose : HttpCommandTrigger { private readonly IOptionsMonitor<AppSettings> _settings; public VenueClose( TelemetryConfiguration telemetryConfiguration , IMediator mediator , IHttpContextAccessor accessor , IHttpRequestHelper requestHelper , ILogger<VenueClose> logger , IValidatorFactory validatorFactory , IOptionsMonitor<AppSettings> settings ) : base(telemetryConfiguration, accessor, requestHelper , mediator, logger, validatorFactory) { _settings = settings; } [FunctionName("Venue_Close")] public async Task<HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = "venue/{venueId}/close")] HttpRequest request , ExecutionContext context , string venueId) { return await ProcessAsync<VenueCloseCommand>(context, request, supportIdempotencyCheck: _settings.CurrentValue.SupportIdempotencyCheck).ConfigureAwait(false); } } }
35.521739
170
0.713586
[ "MIT" ]
pingdong/newmoon.places
src/Venues.FunctionApp/RESTful/Mutation/VenueClose.cs
1,634
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.Http.Features; namespace Microsoft.AspNetCore.Http { public static class HttpContextServerVariableExtensions { /// <summary> /// Gets the value of a server variable for the current request. /// </summary> /// <param name="context">The http context for the request.</param> /// <param name="variableName">The name of the variable.</param> /// <returns> /// <c>null</c> if the server does not support the <see cref="IServerVariablesFeature"/> feature. /// May return null or empty if the variable does not exist or is not set. /// </returns> public static string? GetServerVariable(this HttpContext context, string variableName) { var feature = context.Features.Get<IServerVariablesFeature>(); if (feature == null) { return null; } return feature[variableName]; } } }
35.875
111
0.626307
[ "Apache-2.0" ]
DavidKlempfner/aspnetcore
src/Http/Http.Extensions/src/HttpContextServerVariableExtensions.cs
1,148
C#
namespace HBGaragem.Areas.HelpPage.ModelDescriptions { public class CollectionModelDescription : ModelDescription { public ModelDescription ElementDescription { get; set; } } }
28
64
0.75
[ "MIT" ]
rudimarboeno/Hbsis-aula
HBGaragem/HBGaragem/Areas/HelpPage/ModelDescriptions/CollectionModelDescription.cs
196
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace CodingMilitia.PlayBall.GroupManagement.Infrastructure.Data.Migrations { public partial class AdjustmentsAfterEnablingNullableReferenceTypes : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Groups_Users_CreatorId", schema: "public", table: "Groups"); migrationBuilder.DropForeignKey( name: "FK_Players_Groups_GroupId", schema: "public", table: "Players"); migrationBuilder.AlterColumn<string>( name: "Name", schema: "public", table: "Users", nullable: false, oldClrType: typeof(string), oldType: "text", oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Name", schema: "public", table: "Players", nullable: false, oldClrType: typeof(string), oldType: "text", oldNullable: true); migrationBuilder.AlterColumn<long>( name: "GroupId", schema: "public", table: "Players", nullable: false, oldClrType: typeof(long), oldType: "bigint", oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Name", schema: "public", table: "Groups", nullable: false, oldClrType: typeof(string), oldType: "text", oldNullable: true); migrationBuilder.AlterColumn<string>( name: "CreatorId", schema: "public", table: "Groups", nullable: false, oldClrType: typeof(string), oldType: "text", oldNullable: true); migrationBuilder.AddForeignKey( name: "FK_Groups_Users_CreatorId", schema: "public", table: "Groups", column: "CreatorId", principalSchema: "public", principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.AddForeignKey( name: "FK_Players_Groups_GroupId", schema: "public", table: "Players", column: "GroupId", principalSchema: "public", principalTable: "Groups", principalColumn: "Id", onDelete: ReferentialAction.Cascade); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Groups_Users_CreatorId", schema: "public", table: "Groups"); migrationBuilder.DropForeignKey( name: "FK_Players_Groups_GroupId", schema: "public", table: "Players"); migrationBuilder.AlterColumn<string>( name: "Name", schema: "public", table: "Users", type: "text", nullable: true, oldClrType: typeof(string)); migrationBuilder.AlterColumn<string>( name: "Name", schema: "public", table: "Players", type: "text", nullable: true, oldClrType: typeof(string)); migrationBuilder.AlterColumn<long>( name: "GroupId", schema: "public", table: "Players", type: "bigint", nullable: true, oldClrType: typeof(long)); migrationBuilder.AlterColumn<string>( name: "Name", schema: "public", table: "Groups", type: "text", nullable: true, oldClrType: typeof(string)); migrationBuilder.AlterColumn<string>( name: "CreatorId", schema: "public", table: "Groups", type: "text", nullable: true, oldClrType: typeof(string)); migrationBuilder.AddForeignKey( name: "FK_Groups_Users_CreatorId", schema: "public", table: "Groups", column: "CreatorId", principalSchema: "public", principalTable: "Users", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_Players_Groups_GroupId", schema: "public", table: "Players", column: "GroupId", principalSchema: "public", principalTable: "Groups", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
33.597484
83
0.475852
[ "MIT" ]
AspNetCoreFromZeroToOverkill/GroupManagement
src/CodingMilitia.PlayBall.GroupManagement.Infrastructure/Data/Migrations/20200118130702_AdjustmentsAfterEnablingNullableReferenceTypes.cs
5,344
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V6301 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="UKCT_MT130401UK03.DispensingEndorsement", Namespace="urn:hl7-org:v3")] [System.Xml.Serialization.XmlRootAttribute("UKCT_MT130401UK03.DispensingEndorsement", Namespace="urn:hl7-org:v3")] public partial class UKCT_MT130401UK03DispensingEndorsement { private CV codeField; private ST textField; private CV valueField; private string typeField; private string classCodeField; private string moodCodeField; private string[] typeIDField; private string[] realmCodeField; private string nullFlavorField; private static System.Xml.Serialization.XmlSerializer serializer; public UKCT_MT130401UK03DispensingEndorsement() { this.typeField = "Observation"; this.classCodeField = "OBS"; this.moodCodeField = "EVN"; } public CV code { get { return this.codeField; } set { this.codeField = value; } } public ST text { get { return this.textField; } set { this.textField = value; } } public CV value { get { return this.valueField; } set { this.valueField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string type { get { return this.typeField; } set { this.typeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string classCode { get { return this.classCodeField; } set { this.classCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string moodCode { get { return this.moodCodeField; } set { this.moodCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string[] typeID { get { return this.typeIDField; } set { this.typeIDField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string[] realmCode { get { return this.realmCodeField; } set { this.realmCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string nullFlavor { get { return this.nullFlavorField; } set { this.nullFlavorField = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(UKCT_MT130401UK03DispensingEndorsement)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current UKCT_MT130401UK03DispensingEndorsement object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an UKCT_MT130401UK03DispensingEndorsement object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output UKCT_MT130401UK03DispensingEndorsement object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out UKCT_MT130401UK03DispensingEndorsement obj, out System.Exception exception) { exception = null; obj = default(UKCT_MT130401UK03DispensingEndorsement); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out UKCT_MT130401UK03DispensingEndorsement obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static UKCT_MT130401UK03DispensingEndorsement Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((UKCT_MT130401UK03DispensingEndorsement)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current UKCT_MT130401UK03DispensingEndorsement object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an UKCT_MT130401UK03DispensingEndorsement object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output UKCT_MT130401UK03DispensingEndorsement object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out UKCT_MT130401UK03DispensingEndorsement obj, out System.Exception exception) { exception = null; obj = default(UKCT_MT130401UK03DispensingEndorsement); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out UKCT_MT130401UK03DispensingEndorsement obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static UKCT_MT130401UK03DispensingEndorsement LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this UKCT_MT130401UK03DispensingEndorsement object /// </summary> public virtual UKCT_MT130401UK03DispensingEndorsement Clone() { return ((UKCT_MT130401UK03DispensingEndorsement)(this.MemberwiseClone())); } #endregion } }
39.890365
1,358
0.568418
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V6301/Generated/UKCT_MT130401UK03DispensingEndorsement.cs
12,007
C#
namespace SoftUni.Models { using System; using System.Collections.Generic; public partial class Address { public Address() { Employees = new HashSet<Employee>(); } public int AddressId { get; set; } public string AddressText { get; set; } public int? TownId { get; set; } public virtual Town Town { get; set; } public virtual ICollection<Employee> Employees { get; set; } } }
22.666667
68
0.577731
[ "MIT" ]
HostVanyaD/SoftUni
Entity Framework Core/03.Entity-Framework-Introduction-Exercises/SoftUni/Models/Address.cs
478
C#
using System.Collections.Generic; namespace WebSignalR.Common.DTO { public class UserDto : DtoBase { public UserDto() { Privileges = new List<PrivilegeDto>(); } public string Name { get; set; } public bool IsAdmin { get; set; } public List<PrivilegeDto> Privileges { get; set; } } }
16.944444
52
0.678689
[ "Apache-2.0" ]
OleksandrKulchytskyi/Agile
Server/WebSignalR/WebSignalR.Common/DTO/UserDto.cs
307
C#
using System; using System.Linq; using Moq; using Xunit; namespace Binance.Tests { public class SymbolTest { [Fact] public void Throws() { const SymbolStatus status = SymbolStatus.Trading; var baseAsset = Asset.BTC; var quoteAsset = Asset.USDT; var quantityRange = new InclusiveRange(0.01m, 10.0m, 0.01m); var priceRange = new InclusiveRange(0.01m, 100.0m, 0.01m); const decimal minNotionalValue = 0.001m; const bool isIcebergAllowed = true; const bool quoteOrderQtyMarketAllowed = true; var orderTypes = new [] { OrderType.Limit, OrderType.Market }; Assert.Throws<ArgumentNullException>("baseAsset", () => new Symbol(status, null, quoteAsset, quantityRange, priceRange, minNotionalValue, isIcebergAllowed, orderTypes, quoteOrderQtyMarketAllowed)); Assert.Throws<ArgumentNullException>("quoteAsset", () => new Symbol(status, baseAsset, null, quantityRange, priceRange, minNotionalValue, isIcebergAllowed, orderTypes, quoteOrderQtyMarketAllowed)); Assert.Throws<ArgumentNullException>("quantity", () => new Symbol(status, baseAsset, quoteAsset, null, priceRange, minNotionalValue, isIcebergAllowed, orderTypes, quoteOrderQtyMarketAllowed)); Assert.Throws<ArgumentNullException>("price", () => new Symbol(status, baseAsset, quoteAsset, quantityRange, null, minNotionalValue, isIcebergAllowed, orderTypes, quoteOrderQtyMarketAllowed)); Assert.Throws<ArgumentNullException>("orderTypes", () => new Symbol(status, baseAsset, quoteAsset, quantityRange, priceRange, minNotionalValue, isIcebergAllowed, null, quoteOrderQtyMarketAllowed)); } [Fact] public void ImplicitOperators() { var symbol1 = Symbol.BTC_USDT; var symbol2 = new Symbol(symbol1.Status, symbol1.BaseAsset, symbol1.QuoteAsset, symbol1.Quantity, symbol1.Price, symbol1.NotionalMinimumValue, symbol1.IsIcebergAllowed, symbol1.OrderTypes, symbol1.QuoteOrderQtyMarketAllowed); var symbol3 = Symbol.XRP_USDT; Assert.True(symbol1 == symbol2); Assert.True(symbol1 != symbol3); Assert.True(symbol1 == symbol1.ToString()); Assert.True(symbol1 == symbol2.ToString()); Assert.True(symbol1 != symbol3.ToString()); var baseAsset = new Asset("TEST", 8); var quoteAsset = Asset.BTC; var quantityRange = new InclusiveRange(0.01m, 10.0m, 0.01m); var priceRange = new InclusiveRange(0.01m, 100.0m, 0.01m); const decimal minNotionalValue = 0.001m; const bool isIcebergAllowed = true; const bool quoteOrderQtyMarketAllowed = true; var orderTypes = new[] { OrderType.Limit, OrderType.Market }; var newSymbol = new Symbol(SymbolStatus.Trading, baseAsset, quoteAsset, quantityRange, priceRange, minNotionalValue, isIcebergAllowed, orderTypes, quoteOrderQtyMarketAllowed); Assert.True(newSymbol == baseAsset.Symbol + quoteAsset.Symbol); } [Fact] public void Properties() { const SymbolStatus status = SymbolStatus.Trading; var baseAsset = Asset.BTC; var quoteAsset = Asset.USDT; var quantityRange = new InclusiveRange(0.01m, 10.0m, 0.01m); var priceRange = new InclusiveRange(0.01m, 100.0m, 0.01m); const decimal minNotionalValue = 0.001m; const bool isIcebergAllowed = true; const bool quoteOrderQtyMarketAllowed = true; var orderTypes = new [] { OrderType.Limit, OrderType.Market }; var symbol = new Symbol(status, baseAsset, quoteAsset, quantityRange, priceRange, minNotionalValue, isIcebergAllowed, orderTypes, quoteOrderQtyMarketAllowed); Assert.Equal(status, symbol.Status); Assert.Equal(baseAsset, symbol.BaseAsset); Assert.Equal(quoteAsset, symbol.QuoteAsset); Assert.Equal(quantityRange, symbol.Quantity); Assert.Equal(priceRange, symbol.Price); Assert.Equal(minNotionalValue, symbol.NotionalMinimumValue); Assert.Equal(orderTypes, symbol.OrderTypes); } [Fact] public void IsValid() { const SymbolStatus status = SymbolStatus.Trading; var quoteAsset = Asset.USDT; var quantityRange = new InclusiveRange(0.01m, 10.0m, 0.01m); var priceRange = new InclusiveRange(0.01m, 100.0m, 0.01m); const decimal minNotionalValue = 0.001m; const bool isIcebergAllowed = true; const bool quoteOrderQtyMarketAllowed = true; var orderTypes = new [] { OrderType.Limit, OrderType.Market }; var validSymbol = Symbol.BTC_USDT; var invalidSymbol = new Symbol(status, new Asset("...", 0), quoteAsset, quantityRange, priceRange, minNotionalValue, isIcebergAllowed, orderTypes, quoteOrderQtyMarketAllowed); Assert.True(Symbol.IsValid(validSymbol)); Assert.False(Symbol.IsValid(invalidSymbol)); } [Fact] public void IsSupported() { var symbol = Symbol.BTC_USDT; Assert.Contains(OrderType.Limit, symbol.OrderTypes); Assert.True(symbol.IsSupported(OrderType.Limit)); } [Fact] public void IsOrderTypeSupported() { var symbol = Symbol.BTC_USDT; var order = new LimitOrder(new Mock<IBinanceApiUser>().Object); Assert.Contains(OrderType.Limit, symbol.OrderTypes); Assert.True(symbol.IsOrderTypeSupported(order)); } [Fact] public void IsPriceQuantityValid() { var symbol = Symbol.BTC_USDT; var user = new Mock<IBinanceApiUser>().Object; //const decimal price = 10000; //const decimal quantity = 1; Assert.Equal(8, symbol.BaseAsset.Precision); Assert.Equal(8, symbol.QuoteAsset.Precision); /* TODO Assert.True(symbol.IsPriceQuantityValid(price, quantity)); Assert.False(symbol.IsPriceQuantityValid(price, 0.000000001m)); Assert.False(symbol.IsPriceQuantityValid(0.000000001m, quantity)); Assert.False(symbol.IsPriceQuantityValid(price, symbol.Quantity.Maximum + symbol.Quantity.Increment)); Assert.False(symbol.IsPriceQuantityValid(symbol.Price.Minimum - symbol.Price.Increment, quantity)); Assert.True(symbol.IsPriceQuantityValid(price, symbol.NotionalMinimumValue / price)); Assert.False(symbol.IsPriceQuantityValid(price, symbol.NotionalMinimumValue / price - symbol.Quantity.Increment)); var order = new LimitOrder(user) { Price = price, Quantity = quantity }; Assert.True(symbol.IsPriceQuantityValid(order)); order.Price = price; order.Quantity = 0.000000001m; Assert.False(symbol.IsPriceQuantityValid(order)); order.Price = 0.000000001m; order.Quantity = quantity; Assert.False(symbol.IsPriceQuantityValid(order)); order.Price = price; order.Quantity = symbol.Quantity.Maximum + symbol.Quantity.Increment; Assert.False(symbol.IsPriceQuantityValid(order)); order.Price = symbol.Price.Minimum - symbol.Price.Increment; order.Quantity = quantity; Assert.False(symbol.IsPriceQuantityValid(order)); order.Price = price; order.Quantity = symbol.NotionalMinimumValue / price; Assert.True(symbol.IsPriceQuantityValid(order)); order.Price = price; order.Quantity = symbol.NotionalMinimumValue / price - symbol.Quantity.Increment; Assert.False(symbol.IsPriceQuantityValid(order)); */ } [Fact] public void IsValidOrder() { var symbol = Symbol.BTC_USDT; var user = new Mock<IBinanceApiUser>().Object; //const decimal price = 10000; //const decimal quantity = 1; Assert.Equal(8, symbol.BaseAsset.Precision); Assert.Equal(8, symbol.QuoteAsset.Precision); /* TODO var order = new LimitOrder(user); Assert.False(symbol.IsValid(order)); order.Price = price; Assert.False(symbol.IsValid(order)); order.Quantity = quantity; Assert.False(symbol.IsValid(order)); order.Symbol = symbol; Assert.True(symbol.IsValid(order)); var takeProfitLimitOrder = new TakeProfitLimitOrder(user) { Symbol = symbol, Price = price, Quantity = quantity }; if (symbol.OrderTypes.Contains(OrderType.TakeProfitLimit)) { Assert.True(symbol.IsValid(takeProfitLimitOrder)); } else { Assert.False(symbol.IsValid(takeProfitLimitOrder)); } order.Price = price; order.Quantity = 0.000000001m; Assert.False(symbol.IsValid(order)); order.Price = 0.000000001m; order.Quantity = quantity; Assert.False(symbol.IsValid(order)); order.Price = price; order.Quantity = symbol.Quantity.Maximum + symbol.Quantity.Increment; Assert.False(symbol.IsValid(order)); order.Price = symbol.Price.Minimum - symbol.Price.Increment; order.Quantity = quantity; Assert.False(symbol.IsValid(order)); order.Price = price; order.Quantity = symbol.NotionalMinimumValue / price; Assert.True(symbol.IsValid(order)); order.Price = price; order.Quantity = symbol.NotionalMinimumValue / price - symbol.Quantity.Increment; Assert.False(symbol.IsValid(order)); */ } [Fact] public void ValidateOrderType() { var symbol = Symbol.BTC_USDT; var user = new Mock<IBinanceApiUser>().Object; Assert.Contains(OrderType.Limit, symbol.OrderTypes); symbol.Validate(OrderType.Limit); var order = new LimitOrder(new Mock<IBinanceApiUser>().Object); symbol.ValidateOrderType(order); var takeProfitLimitOrder = new TakeProfitLimitOrder(user); if (symbol.OrderTypes.Contains(OrderType.TakeProfitLimit)) { symbol.ValidateOrderType(takeProfitLimitOrder); } else { Assert.Throws<ArgumentException>(nameof(takeProfitLimitOrder.Type), () => symbol.ValidateOrderType(takeProfitLimitOrder)); } } [Fact] public void ValidatePriceQuantity() { var symbol = Symbol.BTC_USDT; var user = new Mock<IBinanceApiUser>().Object; //const decimal price = 10000; //const decimal quantity = 1; Assert.Equal(8, symbol.BaseAsset.Precision); Assert.Equal(8, symbol.QuoteAsset.Precision); /* TODO symbol.ValidatePriceQuantity(price, quantity); Assert.Throws<ArgumentOutOfRangeException>("quantity", () => symbol.ValidatePriceQuantity(price, 0.000000001m)); Assert.Throws<ArgumentOutOfRangeException>("price", () => symbol.ValidatePriceQuantity(0.000000001m, quantity)); Assert.Throws<ArgumentOutOfRangeException>("quantity", () => symbol.ValidatePriceQuantity(price, symbol.Quantity.Maximum + symbol.Quantity.Increment)); Assert.Throws<ArgumentOutOfRangeException>("price", () => symbol.ValidatePriceQuantity(symbol.Price.Minimum - symbol.Price.Increment, quantity)); symbol.IsPriceQuantityValid(price, symbol.NotionalMinimumValue / price); Assert.Throws<ArgumentOutOfRangeException>("notionalValue", () => symbol.ValidatePriceQuantity(price, symbol.NotionalMinimumValue / price - symbol.Quantity.Increment)); var order = new LimitOrder(user) { Price = price, Quantity = quantity }; symbol.ValidatePriceQuantity(order); order.Price = price; order.Quantity = 0.000000001m; Assert.Throws<ArgumentOutOfRangeException>(nameof(order.Quantity), () => symbol.ValidatePriceQuantity(order)); order.Price = 0.000000001m; order.Quantity = quantity; Assert.Throws<ArgumentOutOfRangeException>(nameof(order.Price), () => symbol.ValidatePriceQuantity(order)); order.Price = price; order.Quantity = symbol.Quantity.Maximum + symbol.Quantity.Increment; Assert.Throws<ArgumentOutOfRangeException>(nameof(order.Quantity), () => symbol.ValidatePriceQuantity(order)); order.Price = symbol.Price.Minimum - symbol.Price.Increment; order.Quantity = quantity; Assert.Throws<ArgumentOutOfRangeException>(nameof(order.Price), () => symbol.ValidatePriceQuantity(order)); order.Price = price; order.Quantity = symbol.NotionalMinimumValue / price; symbol.ValidatePriceQuantity(order); order.Price = price; order.Quantity = symbol.NotionalMinimumValue / price - symbol.Quantity.Increment; Assert.Throws<ArgumentOutOfRangeException>("notionalValue", () => symbol.ValidatePriceQuantity(order)); */ } [Fact] public void Validate() { var symbol = Symbol.BTC_USDT; var user = new Mock<IBinanceApiUser>().Object; //const decimal price = 10000; //const decimal quantity = 1; Assert.Equal(8, symbol.BaseAsset.Precision); Assert.Equal(8, symbol.QuoteAsset.Precision); /* TODO var order = new LimitOrder(user); Assert.Throws<ArgumentException>("Symbol", () => symbol.Validate(order)); order.Symbol = symbol; Assert.Throws<ArgumentOutOfRangeException>(nameof(order.Quantity), () => symbol.Validate(order)); order.Quantity = quantity; Assert.Throws<ArgumentOutOfRangeException>(nameof(order.Price), () => symbol.Validate(order)); order.Price = price; symbol.Validate(order); order.Price = price; order.Quantity = 0.000000001m; Assert.Throws<ArgumentOutOfRangeException>(nameof(order.Quantity), () => symbol.Validate(order)); order.Price = 0.000000001m; order.Quantity = quantity; Assert.Throws<ArgumentOutOfRangeException>(nameof(order.Price), () => symbol.Validate(order)); order.Price = price; order.Quantity = symbol.Quantity.Maximum + symbol.Quantity.Increment; Assert.Throws<ArgumentOutOfRangeException>(nameof(order.Quantity), () => symbol.Validate(order)); order.Price = symbol.Price.Minimum - symbol.Price.Increment; order.Quantity = quantity; Assert.Throws<ArgumentOutOfRangeException>(nameof(order.Price), () => symbol.Validate(order)); order.Price = price; order.Quantity = symbol.NotionalMinimumValue / price; symbol.Validate(order); order.Price = price; order.Quantity = symbol.NotionalMinimumValue / price - symbol.Quantity.Increment; Assert.Throws<ArgumentOutOfRangeException>("notionalValue", () => symbol.Validate(order)); */ } } }
41.734908
237
0.619269
[ "MIT" ]
meeron/Binance
test/Binance.Tests/SymbolTest.cs
15,903
C#
using Dotmim.Sync.Builders; using Dotmim.Sync.Enumerations; using Dotmim.Sync.SqlServer; using Dotmim.Sync.Tests.Core; using Dotmim.Sync.Tests.Misc; using Dotmim.Sync.Tests.Models; using Dotmim.Sync.Tests.Serializers; using Dotmim.Sync.Web.Client; using Dotmim.Sync.Web.Server; using Microsoft.AspNetCore.Http; using Microsoft.Data.SqlClient; using Microsoft.EntityFrameworkCore; #if NET5_0 || NETCOREAPP3_1 using MySqlConnector; #elif NETCOREAPP2_1 using MySql.Data.MySqlClient; #endif using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace Dotmim.Sync.Tests { //[TestCaseOrderer("Dotmim.Sync.Tests.Misc.PriorityOrderer", "Dotmim.Sync.Tests")] public abstract class HttpFilterTests : IClassFixture<HelperProvider>, IDisposable { private Stopwatch stopwatch; /// <summary> /// Gets the sync filtered tables involved in the tests /// </summary> public abstract SyncSetup FilterSetup { get; } /// <summary> /// Gets the filter parameter value /// </summary> public abstract SyncParameters FilterParameters { get; } /// <summary> /// Gets the clients type we want to tests /// </summary> public abstract List<ProviderType> ClientsType { get; } /// <summary> /// Gets the server type we want to test /// </summary> public abstract ProviderType ServerType { get; } /// <summary> /// Gets if fiddler is in use /// </summary> public abstract bool UseFiddler { get; } /// <summary> /// Service Uri provided by kestrell when starts /// </summary> public string ServiceUri { get; private set; } /// <summary> /// Gets the Web Server Orchestrator used for the tests /// </summary> public WebServerOrchestrator WebServerOrchestrator { get; } /// <summary> /// Get the server rows count /// </summary> public abstract int GetServerDatabaseRowsCount((string DatabaseName, ProviderType ProviderType, CoreProvider Provider) t); /// <summary> /// Create a provider /// </summary> public abstract CoreProvider CreateProvider(ProviderType providerType, string dbName); /// <summary> /// Create database, seed it, with or without schema /// </summary> /// <param name="t"></param> /// <param name="useSeeding"></param> /// <param name="useFallbackSchema"></param> public abstract Task EnsureDatabaseSchemaAndSeedAsync((string DatabaseName, ProviderType ProviderType, CoreProvider Provider) t, bool useSeeding = false, bool useFallbackSchema = false); // abstract fixture used to run the tests protected readonly HelperProvider fixture; // Current test running private ITest test; private KestrellTestServer kestrell; /// <summary> /// Gets the remote orchestrator and its database name /// </summary> public (string DatabaseName, ProviderType ProviderType, CoreProvider Provider) Server { get; private set; } /// <summary> /// Gets the dictionary of all local orchestrators with database name as key /// </summary> public List<(string DatabaseName, ProviderType ProviderType, CoreProvider Provider)> Clients { get; set; } /// <summary> /// Gets a bool indicating if we should generate the schema for tables /// </summary> public bool UseFallbackSchema => ServerType == ProviderType.Sql; /// <summary> /// Create an empty database /// </summary> public abstract Task CreateDatabaseAsync(ProviderType providerType, string dbName, bool recreateDb = true); public ITestOutputHelper Output { get; } /// <summary> /// For each test, Create a server database and some clients databases, depending on ProviderType provided in concrete class /// </summary> public HttpFilterTests(HelperProvider fixture, ITestOutputHelper output) { // Getting the test running this.Output = output; var type = output.GetType(); var testMember = type.GetField("test", BindingFlags.Instance | BindingFlags.NonPublic); this.test = (ITest)testMember.GetValue(output); this.stopwatch = Stopwatch.StartNew(); this.fixture = fixture; // Since we are creating a lot of databases // each database will have its own pool // Droping database will not clear the pool associated // So clear the pools on every start of a new test SqlConnection.ClearAllPools(); MySqlConnection.ClearAllPools(); // get the server provider (and db created) without seed var serverDatabaseName = HelperDatabase.GetRandomName("httpfilt_sv_"); // create remote orchestrator var serverProvider = this.CreateProvider(this.ServerType, serverDatabaseName); // create web remote orchestrator this.WebServerOrchestrator = new WebServerOrchestrator(serverProvider, new SyncOptions(), new SyncSetup(), new WebServerOptions()); // public property this.Server = (serverDatabaseName, this.ServerType, serverProvider); // Create a kestrell server this.kestrell = new KestrellTestServer(this.WebServerOrchestrator, this.UseFiddler); // start server and get uri this.ServiceUri = this.kestrell.Run(); // Get all clients providers Clients = new List<(string DatabaseName, ProviderType ProviderType, CoreProvider Provider)>(this.ClientsType.Count); // Generate Client database foreach (var clientType in this.ClientsType) { var dbCliName = HelperDatabase.GetRandomName("httpfilt_cli_"); var localProvider = this.CreateProvider(clientType, dbCliName); this.Clients.Add((dbCliName, clientType, localProvider)); } } /// <summary> /// Drop all databases used for the tests /// </summary> public void Dispose() { HelperDatabase.DropDatabase(this.ServerType, Server.DatabaseName); foreach (var client in Clients) HelperDatabase.DropDatabase(client.ProviderType, client.DatabaseName); this.stopwatch.Stop(); var str = $"{test.TestCase.DisplayName} : {this.stopwatch.Elapsed.Minutes}:{this.stopwatch.Elapsed.Seconds}.{this.stopwatch.Elapsed.Milliseconds}"; Console.WriteLine(str); Debug.WriteLine(str); } [Fact] public virtual async Task SchemaIsCreated() { // create a server db without seed await this.EnsureDatabaseSchemaAndSeedAsync(Server, false, UseFallbackSchema); // create empty client databases foreach (var client in this.Clients) await this.CreateDatabaseAsync(client.ProviderType, client.DatabaseName, true); // configure server orchestrator this.WebServerOrchestrator.Setup = this.FilterSetup; // Execute a sync on all clients and check results foreach (var client in Clients) { var agent = new SyncAgent(client.Provider, new WebClientOrchestrator(this.ServiceUri)); var s = await agent.SynchronizeAsync(); Assert.Equal(0, s.TotalChangesDownloaded); Assert.Equal(0, s.TotalChangesUploaded); } } [Theory] [ClassData(typeof(SyncOptionsData))] public virtual async Task RowsCount(SyncOptions options) { // create a server db and seed it await this.EnsureDatabaseSchemaAndSeedAsync(this.Server, true, UseFallbackSchema); // create empty client databases foreach (var client in this.Clients) await this.CreateDatabaseAsync(client.ProviderType, client.DatabaseName, true); // Get count of rows var rowsCount = this.GetServerDatabaseRowsCount(this.Server); // configure server orchestrator this.WebServerOrchestrator.Setup = this.FilterSetup; // Execute a sync on all clients and check results foreach (var client in this.Clients) { var agent = new SyncAgent(client.Provider, new WebClientOrchestrator(this.ServiceUri), options); agent.Parameters.AddRange(this.FilterParameters); var s = await agent.SynchronizeAsync(); Assert.Equal(rowsCount, s.TotalChangesDownloaded); Assert.Equal(0, s.TotalChangesUploaded); } } /// <summary> /// Insert two rows on server, should be correctly sync on all clients /// </summary> [Theory] [ClassData(typeof(SyncOptionsData))] public async Task Insert_TwoTables_FromServer(SyncOptions options) { // create a server schema and seed await this.EnsureDatabaseSchemaAndSeedAsync(this.Server, true, UseFallbackSchema); // create empty client databases foreach (var client in this.Clients) await this.CreateDatabaseAsync(client.ProviderType, client.DatabaseName, true); // Get count of rows var rowsCount = this.GetServerDatabaseRowsCount(this.Server); // configure server orchestrator this.WebServerOrchestrator.Setup = this.FilterSetup; // Execute a sync on all clients to initialize client and server schema foreach (var client in Clients) { // create agent with filtered tables and parameter var agent = new SyncAgent(client.Provider, new WebClientOrchestrator(this.ServiceUri), options); agent.Parameters.AddRange(this.FilterParameters); var s = await agent.SynchronizeAsync(); Assert.Equal(rowsCount, s.TotalChangesDownloaded); Assert.Equal(0, s.TotalChangesUploaded); Assert.Equal(0, s.TotalResolvedConflicts); } // Create a new address & customer address on server using (var serverDbCtx = new AdventureWorksContext(this.Server)) { var addressLine1 = HelperDatabase.GetRandomName().ToUpperInvariant().Substring(0, 10); var newAddress = new Address { AddressLine1 = addressLine1 }; serverDbCtx.Address.Add(newAddress); await serverDbCtx.SaveChangesAsync(); var newCustomerAddress = new CustomerAddress { AddressId = newAddress.AddressId, CustomerId = AdventureWorksContext.CustomerIdForFilter, AddressType = "OTH" }; serverDbCtx.CustomerAddress.Add(newCustomerAddress); await serverDbCtx.SaveChangesAsync(); } // Execute a sync on all clients and check results foreach (var client in Clients) { // create agent with filtered tables and parameter var agent = new SyncAgent(client.Provider, new WebClientOrchestrator(this.ServiceUri), options); agent.Parameters.AddRange(this.FilterParameters); var s = await agent.SynchronizeAsync(); Assert.Equal(2, s.TotalChangesDownloaded); Assert.Equal(0, s.TotalChangesUploaded); Assert.Equal(0, s.TotalResolvedConflicts); } } /// <summary> /// Insert four rows on each client, should be sync on server and clients /// </summary> [Theory] [ClassData(typeof(SyncOptionsData))] public async Task Insert_TwoTables_FromClient(SyncOptions options) { // create a server schema and seed await this.EnsureDatabaseSchemaAndSeedAsync(this.Server, true, UseFallbackSchema); // create empty client databases foreach (var client in this.Clients) await this.CreateDatabaseAsync(client.ProviderType, client.DatabaseName, true); // Get count of rows var rowsCount = this.GetServerDatabaseRowsCount(this.Server); // configure server orchestrator this.WebServerOrchestrator.Setup = this.FilterSetup; // Execute a sync on all clients to initialize client and server schema foreach (var client in Clients) { // create agent with filtered tables and parameter var agent = new SyncAgent(client.Provider, new WebClientOrchestrator(this.ServiceUri), options); agent.Parameters.AddRange(this.FilterParameters); var s = await agent.SynchronizeAsync(); Assert.Equal(rowsCount, s.TotalChangesDownloaded); Assert.Equal(0, s.TotalChangesUploaded); Assert.Equal(0, s.TotalResolvedConflicts); } // Insert 4 lines on each client foreach (var client in Clients) { var soh = new SalesOrderHeader { SalesOrderNumber = $"SO-99999", RevisionNumber = 1, Status = 5, OnlineOrderFlag = true, PurchaseOrderNumber = "PO348186287", AccountNumber = "10-4020-000609", CustomerId = AdventureWorksContext.CustomerIdForFilter, ShipToAddressId = 4, BillToAddressId = 5, ShipMethod = "CAR TRANSPORTATION", SubTotal = 6530.35M, TaxAmt = 70.4279M, Freight = 22.0087M, TotalDue = 6530.35M + 70.4279M + 22.0087M }; using var ctx = new AdventureWorksContext(client, this.UseFallbackSchema); var productId = ctx.Product.First().ProductId; var sod1 = new SalesOrderDetail { OrderQty = 1, ProductId = productId, UnitPrice = 3578.2700M }; var sod2 = new SalesOrderDetail { OrderQty = 2, ProductId = productId, UnitPrice = 44.5400M }; var sod3 = new SalesOrderDetail { OrderQty = 2, ProductId = productId, UnitPrice = 1431.5000M }; soh.SalesOrderDetail.Add(sod1); soh.SalesOrderDetail.Add(sod2); soh.SalesOrderDetail.Add(sod3); ctx.SalesOrderHeader.Add(soh); await ctx.SaveChangesAsync(); } // Sync all clients // First client will upload 4 lines and will download nothing // Second client will upload 4 lines and will download 8 lines // thrid client will upload 4 lines and will download 12 lines int download = 0; foreach (var client in Clients) { // create agent with filtered tables and parameter var agent = new SyncAgent(client.Provider, new WebClientOrchestrator(this.ServiceUri), options); agent.Parameters.AddRange(this.FilterParameters); var s = await agent.SynchronizeAsync(); //Assert.Equal(download, s.TotalChangesDownloaded); Assert.Equal(4, s.TotalChangesUploaded); //Assert.Equal(0, s.TotalSyncConflicts); download += 4; } // Now sync again to be sure all clients have all lines foreach (var client in Clients) { // create agent with filtered tables and parameter var agent = new SyncAgent(client.Provider, new WebClientOrchestrator(this.ServiceUri), options); agent.Parameters.AddRange(this.FilterParameters); await agent.SynchronizeAsync(); } } /// <summary> /// Insert one row in two tables on server, should be correctly sync on all clients /// </summary> [Fact] public async Task Snapshot_Initialize() { // create a server schema with seeding await this.EnsureDatabaseSchemaAndSeedAsync(this.Server, true, UseFallbackSchema); // create empty client databases foreach (var client in this.Clients) await this.CreateDatabaseAsync(client.ProviderType, client.DatabaseName, true); // snapshot directory var snapshotDirctory = HelperDatabase.GetRandomName(); var directory = Path.Combine(Environment.CurrentDirectory, snapshotDirctory); // ---------------------------------- // Setting correct options for sync agent to be able to reach snapshot // ---------------------------------- var options = new SyncOptions { SnapshotsDirectory = directory, BatchSize = 200 }; // ---------------------------------- // Create a snapshot // ---------------------------------- var remoteOrchestrator = new RemoteOrchestrator(Server.Provider, options, this.FilterSetup); await remoteOrchestrator.CreateSnapshotAsync(this.FilterParameters); // ---------------------------------- // Add rows on server AFTER snapshot // ---------------------------------- // Create a new address & customer address on server using (var serverDbCtx = new AdventureWorksContext(this.Server)) { var addressLine1 = HelperDatabase.GetRandomName().ToUpperInvariant().Substring(0, 10); var newAddress = new Address { AddressLine1 = addressLine1 }; serverDbCtx.Address.Add(newAddress); await serverDbCtx.SaveChangesAsync(); var newCustomerAddress = new CustomerAddress { AddressId = newAddress.AddressId, CustomerId = AdventureWorksContext.CustomerIdForFilter, AddressType = "OTH" }; serverDbCtx.CustomerAddress.Add(newCustomerAddress); await serverDbCtx.SaveChangesAsync(); } // Get count of rows var rowsCount = this.GetServerDatabaseRowsCount(this.Server); // configure server orchestrator this.WebServerOrchestrator.Setup = this.FilterSetup; this.WebServerOrchestrator.Options.SnapshotsDirectory = directory; this.WebServerOrchestrator.Options.BatchSize = 200; // Execute a sync on all clients and check results foreach (var client in Clients) { // create agent with filtered tables and parameter var agent = new SyncAgent(client.Provider, new WebClientOrchestrator(this.ServiceUri), options); agent.Parameters.AddRange(this.FilterParameters); var snapshotApplying = 0; var snapshotApplied = 0; agent.LocalOrchestrator.OnSnapshotApplying(saa => snapshotApplying++); agent.LocalOrchestrator.OnSnapshotApplied(saa => snapshotApplied++); var s = await agent.SynchronizeAsync(); Assert.Equal(rowsCount, s.TotalChangesDownloaded); Assert.Equal(0, s.TotalChangesUploaded); Assert.Equal(0, s.TotalResolvedConflicts); Assert.Equal(1, snapshotApplying); Assert.Equal(1, snapshotApplied); } } /// <summary> /// Insert two rows on server, should be correctly sync on all clients /// </summary> [Theory] [ClassData(typeof(SyncOptionsData))] public async Task CustomSeriazlizer_MessagePack(SyncOptions options) { // create a server schema and seed await this.EnsureDatabaseSchemaAndSeedAsync(this.Server, true, UseFallbackSchema); // create empty client databases foreach (var client in this.Clients) await this.CreateDatabaseAsync(client.ProviderType, client.DatabaseName, true); // Get count of rows var rowsCount = this.GetServerDatabaseRowsCount(this.Server); // configure server orchestrator this.WebServerOrchestrator.Setup = this.FilterSetup; this.WebServerOrchestrator.Options.SerializerFactory = new CustomMessagePackSerializerFactory(); // add custom serializer options.SerializerFactory = new CustomMessagePackSerializerFactory(); // Execute a sync on all clients to initialize client and server schema foreach (var client in Clients) { // create agent with filtered tables and parameter and serializer message pack var webClientOrchestrator = new WebClientOrchestrator(this.ServiceUri); var agent = new SyncAgent(client.Provider, webClientOrchestrator, options); agent.Parameters.AddRange(this.FilterParameters); var s = await agent.SynchronizeAsync(); Assert.Equal(rowsCount, s.TotalChangesDownloaded); Assert.Equal(0, s.TotalChangesUploaded); Assert.Equal(0, s.TotalResolvedConflicts); } // Create a new address & customer address on server using (var serverDbCtx = new AdventureWorksContext(this.Server)) { var addressLine1 = HelperDatabase.GetRandomName().ToUpperInvariant().Substring(0, 10); var newAddress = new Address { AddressLine1 = addressLine1 }; serverDbCtx.Address.Add(newAddress); await serverDbCtx.SaveChangesAsync(); var newCustomerAddress = new CustomerAddress { AddressId = newAddress.AddressId, CustomerId = AdventureWorksContext.CustomerIdForFilter, AddressType = "OTH" }; serverDbCtx.CustomerAddress.Add(newCustomerAddress); await serverDbCtx.SaveChangesAsync(); } // Execute a sync on all clients and check results foreach (var client in Clients) { // create agent with filtered tables and parameter and serializer message pack var webClientOrchestrator = new WebClientOrchestrator(this.ServiceUri); var agent = new SyncAgent(client.Provider, webClientOrchestrator, options); agent.Parameters.AddRange(this.FilterParameters); var s = await agent.SynchronizeAsync(); Assert.Equal(2, s.TotalChangesDownloaded); Assert.Equal(0, s.TotalChangesUploaded); Assert.Equal(0, s.TotalResolvedConflicts); } } /// <summary> /// Insert one row in two tables on server, should be correctly sync on all clients /// </summary> [Fact] public async Task Snapshot_ShouldNot_Delete_Folders() { // create a server schema with seeding await this.EnsureDatabaseSchemaAndSeedAsync(this.Server, true, UseFallbackSchema); // create empty client databases foreach (var client in this.Clients) await this.CreateDatabaseAsync(client.ProviderType, client.DatabaseName, true); // ---------------------------------- // Setting correct options for sync agent to be able to reach snapshot // ---------------------------------- var snapshotDirctory = HelperDatabase.GetRandomName(); var directory = Path.Combine(Environment.CurrentDirectory, snapshotDirctory); var serverOptions = new SyncOptions { SnapshotsDirectory = directory, BatchDirectory = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "srv"), BatchSize = 200 }; var clientOptions = new SyncOptions { BatchDirectory = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "cli"), BatchSize = 200 }; // ---------------------------------- // Create a snapshot // ---------------------------------- var remoteOrchestrator = new RemoteOrchestrator(Server.Provider, serverOptions, this.FilterSetup); // getting snapshot directory names var (rootDirectory, nameDirectory) = await remoteOrchestrator.GetSnapshotDirectoryAsync(this.FilterParameters).ConfigureAwait(false); Assert.False(Directory.Exists(rootDirectory)); Assert.False(Directory.Exists(Path.Combine(rootDirectory, nameDirectory))); await remoteOrchestrator.CreateSnapshotAsync(this.FilterParameters); Assert.True(Directory.Exists(rootDirectory)); Assert.True(Directory.Exists(Path.Combine(rootDirectory, nameDirectory))); // ---------------------------------- // Add rows on server AFTER snapshot // ---------------------------------- // Create a new address & customer address on server using (var serverDbCtx = new AdventureWorksContext(this.Server)) { var addressLine1 = HelperDatabase.GetRandomName().ToUpperInvariant().Substring(0, 10); var newAddress = new Address { AddressLine1 = addressLine1 }; serverDbCtx.Address.Add(newAddress); await serverDbCtx.SaveChangesAsync(); var newCustomerAddress = new CustomerAddress { AddressId = newAddress.AddressId, CustomerId = AdventureWorksContext.CustomerIdForFilter, AddressType = "OTH" }; serverDbCtx.CustomerAddress.Add(newCustomerAddress); await serverDbCtx.SaveChangesAsync(); } // Get count of rows var rowsCount = this.GetServerDatabaseRowsCount(this.Server); // configure server orchestrator this.WebServerOrchestrator.Setup = this.FilterSetup; this.WebServerOrchestrator.Options.SnapshotsDirectory = serverOptions.SnapshotsDirectory; this.WebServerOrchestrator.Options.BatchSize = serverOptions.BatchSize; this.WebServerOrchestrator.Options.BatchDirectory = serverOptions.BatchDirectory; // Execute a sync on all clients and check results foreach (var client in Clients) { // create agent with filtered tables and parameter var agent = new SyncAgent(client.Provider, new WebClientOrchestrator(this.ServiceUri), clientOptions); agent.Parameters.AddRange(this.FilterParameters); var s = await agent.SynchronizeAsync(); Assert.True(Directory.Exists(rootDirectory)); Assert.True(Directory.Exists(Path.Combine(rootDirectory, nameDirectory))); var serverFiles = Directory.GetFiles(serverOptions.BatchDirectory, "*", SearchOption.AllDirectories); var clientFiles = Directory.GetFiles(clientOptions.BatchDirectory, "*", SearchOption.AllDirectories); Assert.Empty(serverFiles); Assert.Empty(clientFiles); } } /// <summary> /// Insert one row in two tables on server, should be correctly sync on all clients /// </summary> [Fact] public async Task Snapshot_Initialize_With_CustomSeriazlizer_MessagePack() { // create a server schema with seeding await this.EnsureDatabaseSchemaAndSeedAsync(this.Server, true, UseFallbackSchema); // create empty client databases foreach (var client in this.Clients) await this.CreateDatabaseAsync(client.ProviderType, client.DatabaseName, true); // snapshot directory var snapshotDirctory = HelperDatabase.GetRandomName(); var directory = Path.Combine(Environment.CurrentDirectory, snapshotDirctory); // ---------------------------------- // Setting correct options for sync agent to be able to reach snapshot // ---------------------------------- var options = new SyncOptions { SnapshotsDirectory = directory, BatchSize = 200, SerializerFactory = new CustomMessagePackSerializerFactory() }; // ---------------------------------- // Create a snapshot // ---------------------------------- var remoteOrchestrator = new RemoteOrchestrator(Server.Provider, options, this.FilterSetup); await remoteOrchestrator.CreateSnapshotAsync(this.FilterParameters); // ---------------------------------- // Add rows on server AFTER snapshot // ---------------------------------- // Create a new address & customer address on server using (var serverDbCtx = new AdventureWorksContext(this.Server)) { var addressLine1 = HelperDatabase.GetRandomName().ToUpperInvariant().Substring(0, 10); var newAddress = new Address { AddressLine1 = addressLine1 }; serverDbCtx.Address.Add(newAddress); await serverDbCtx.SaveChangesAsync(); var newCustomerAddress = new CustomerAddress { AddressId = newAddress.AddressId, CustomerId = AdventureWorksContext.CustomerIdForFilter, AddressType = "OTH" }; serverDbCtx.CustomerAddress.Add(newCustomerAddress); await serverDbCtx.SaveChangesAsync(); } // Get count of rows var rowsCount = this.GetServerDatabaseRowsCount(this.Server); // configure server orchestrator this.WebServerOrchestrator.Setup = this.FilterSetup; this.WebServerOrchestrator.Options.SnapshotsDirectory = directory; this.WebServerOrchestrator.Options.BatchSize = 200; this.WebServerOrchestrator.Options.SerializerFactory = new CustomMessagePackSerializerFactory(); // Execute a sync on all clients and check results foreach (var client in Clients) { // create agent with filtered tables and parameter var agent = new SyncAgent(client.Provider, new WebClientOrchestrator(this.ServiceUri), options); agent.Parameters.AddRange(this.FilterParameters); var snapshotApplying = 0; var snapshotApplied = 0; agent.LocalOrchestrator.OnSnapshotApplying(saa => snapshotApplying++); agent.LocalOrchestrator.OnSnapshotApplied(saa => snapshotApplied++); var s = await agent.SynchronizeAsync(); Assert.Equal(rowsCount, s.TotalChangesDownloaded); Assert.Equal(0, s.TotalChangesUploaded); Assert.Equal(0, s.TotalResolvedConflicts); Assert.Equal(1, snapshotApplying); Assert.Equal(1, snapshotApplied); } } } }
40.989822
159
0.593209
[ "MIT" ]
Mimetis/Dotmim.Sync
Tests/Dotmim.Sync.Tests/HttpFilterTests.cs
32,220
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the devicefarm-2015-06-23.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.DeviceFarm.Model { /// <summary> /// Container for the parameters to the ListJobs operation. /// Gets information about jobs for a given test run. /// </summary> public partial class ListJobsRequest : AmazonDeviceFarmRequest { private string _arn; private string _nextToken; /// <summary> /// Gets and sets the property Arn. /// <para> /// The run's Amazon Resource Name (ARN). /// </para> /// </summary> public string Arn { get { return this._arn; } set { this._arn = value; } } // Check to see if Arn property is set internal bool IsSetArn() { return this._arn != null; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// An identifier that was returned from the previous call to this operation, which can /// be used to return the next set of items in the list. /// </para> /// </summary> public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } } }
29.25974
108
0.61296
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/DeviceFarm/Generated/Model/ListJobsRequest.cs
2,253
C#
/******************************************************************************* * Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.CloudFormation; using Amazon.CloudFormation.Model; namespace Amazon.PowerShell.Cmdlets.CFN { /// <summary> /// Updates the stack set, and associated stack instances in the specified accounts and /// regions. /// /// /// <para> /// Even if the stack set operation created by updating the stack set fails (completely /// or partially, below or above a specified failure tolerance), the stack set is updated /// with your changes. Subsequent <a>CreateStackInstances</a> calls on the specified stack /// set use the updated stack set. /// </para> /// </summary> [Cmdlet("Update", "CFNStackSet", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)] [OutputType("System.String")] [AWSCmdlet("Calls the AWS CloudFormation UpdateStackSet API operation.", Operation = new[] {"UpdateStackSet"}, SelectReturnType = typeof(Amazon.CloudFormation.Model.UpdateStackSetResponse))] [AWSCmdletOutput("System.String or Amazon.CloudFormation.Model.UpdateStackSetResponse", "This cmdlet returns a System.String object.", "The service call response (type Amazon.CloudFormation.Model.UpdateStackSetResponse) can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class UpdateCFNStackSetCmdlet : AmazonCloudFormationClientCmdlet, IExecutor { #region Parameter Account /// <summary> /// <para> /// <para>[Self-managed permissions] The accounts in which to update associated stack instances. /// If you specify accounts, you must also specify the regions in which to update stack /// set instances.</para><para>To update <i>all</i> the stack instances associated with this stack set, do not specify /// the <code>Accounts</code> or <code>Regions</code> properties.</para><para>If the stack set update includes changes to the template (that is, if the <code>TemplateBody</code> /// or <code>TemplateURL</code> properties are specified), or the <code>Parameters</code> /// property, AWS CloudFormation marks all stack instances with a status of <code>OUTDATED</code> /// prior to updating the stack instances in the specified accounts and regions. If the /// stack set update does not include changes to the template or parameters, AWS CloudFormation /// updates the stack instances in the specified accounts and regions, while leaving all /// other stack instances with their existing stack instance status. </para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("Accounts")] public System.String[] Account { get; set; } #endregion #region Parameter DeploymentTargets_Account /// <summary> /// <para> /// <para>The names of one or more AWS accounts for which you want to deploy stack set updates.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("DeploymentTargets_Accounts")] public System.String[] DeploymentTargets_Account { get; set; } #endregion #region Parameter AdministrationRoleARN /// <summary> /// <para> /// <para>The Amazon Resource Number (ARN) of the IAM role to use to update this stack set.</para><para>Specify an IAM role only if you are using customized administrator roles to control /// which users or groups can manage specific stack sets within the same administrator /// account. For more information, see <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-prereqs.html">Granting /// Permissions for Stack Set Operations</a> in the <i>AWS CloudFormation User Guide</i>.</para><para>If you specified a customized administrator role when you created the stack set, you /// must specify a customized administrator role, even if it is the same customized administrator /// role used with this stack set previously.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String AdministrationRoleARN { get; set; } #endregion #region Parameter Capability /// <summary> /// <para> /// <para>In some cases, you must explicitly acknowledge that your stack template contains certain /// capabilities in order for AWS CloudFormation to update the stack set and its associated /// stack instances.</para><ul><li><para><code>CAPABILITY_IAM</code> and <code>CAPABILITY_NAMED_IAM</code></para><para>Some stack templates might include resources that can affect permissions in your AWS /// account; for example, by creating new AWS Identity and Access Management (IAM) users. /// For those stacks sets, you must explicitly acknowledge this by specifying one of these /// capabilities.</para><para>The following IAM resources require you to specify either the <code>CAPABILITY_IAM</code> /// or <code>CAPABILITY_NAMED_IAM</code> capability.</para><ul><li><para>If you have IAM resources, you can specify either capability. </para></li><li><para>If you have IAM resources with custom names, you <i>must</i> specify <code>CAPABILITY_NAMED_IAM</code>. /// </para></li><li><para>If you don't specify either of these capabilities, AWS CloudFormation returns an <code>InsufficientCapabilities</code> /// error.</para></li></ul><para>If your stack template contains these resources, we recommend that you review all /// permissions associated with them and edit their permissions if necessary.</para><ul><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-accesskey.html"> /// AWS::IAM::AccessKey</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-group.html"> /// AWS::IAM::Group</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-instanceprofile.html"> /// AWS::IAM::InstanceProfile</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-policy.html"> /// AWS::IAM::Policy</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-iam-role.html"> /// AWS::IAM::Role</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-user.html"> /// AWS::IAM::User</a></para></li><li><para><a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-iam-addusertogroup.html"> /// AWS::IAM::UserToGroupAddition</a></para></li></ul><para>For more information, see <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-iam-template.html#capabilities">Acknowledging /// IAM Resources in AWS CloudFormation Templates</a>.</para></li><li><para><code>CAPABILITY_AUTO_EXPAND</code></para><para>Some templates contain macros. If your stack template contains one or more macros, /// and you choose to update a stack directly from the processed template, without first /// reviewing the resulting changes in a change set, you must acknowledge this capability. /// For more information, see <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-macros.html">Using /// AWS CloudFormation Macros to Perform Custom Processing on Templates</a>.</para><important><para>Stack sets do not currently support macros in stack templates. (This includes the /// <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/create-reusable-transform-function-snippets-and-add-to-your-template-with-aws-include-transform.html">AWS::Include</a> /// and <a href="http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/transform-aws-serverless.html">AWS::Serverless</a> /// transforms, which are macros hosted by AWS CloudFormation.) Even if you specify this /// capability, if you include a macro in your template the stack set operation will fail.</para></important></li></ul> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("Capabilities")] public System.String[] Capability { get; set; } #endregion #region Parameter Description /// <summary> /// <para> /// <para>A brief description of updates that you are making.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String Description { get; set; } #endregion #region Parameter AutoDeployment_Enabled /// <summary> /// <para> /// <para>If set to <code>true</code>, StackSets automatically deploys additional stack instances /// to AWS Organizations accounts that are added to a target organization or organizational /// unit (OU) in the specified Regions. If an account is removed from a target organization /// or OU, StackSets deletes stack instances from the account in the specified Regions.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.Boolean? AutoDeployment_Enabled { get; set; } #endregion #region Parameter ExecutionRoleName /// <summary> /// <para> /// <para>The name of the IAM execution role to use to update the stack set. If you do not specify /// an execution role, AWS CloudFormation uses the <code>AWSCloudFormationStackSetExecutionRole</code> /// role for the stack set operation.</para><para>Specify an IAM role only if you are using customized execution roles to control which /// stack resources users and groups can include in their stack sets. </para><para> If you specify a customized execution role, AWS CloudFormation uses that role to /// update the stack. If you do not specify a customized execution role, AWS CloudFormation /// performs the update using the role previously associated with the stack set, so long /// as you have permissions to perform operations on the stack set.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String ExecutionRoleName { get; set; } #endregion #region Parameter OperationId /// <summary> /// <para> /// <para>The unique ID for this stack set operation. </para><para>The operation ID also functions as an idempotency token, to ensure that AWS CloudFormation /// performs the stack set operation only once, even if you retry the request multiple /// times. You might retry stack set operation requests to ensure that AWS CloudFormation /// successfully received them.</para><para>If you don't specify an operation ID, AWS CloudFormation generates one automatically.</para><para>Repeating this stack set operation with a new operation ID retries all stack instances /// whose status is <code>OUTDATED</code>. </para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String OperationId { get; set; } #endregion #region Parameter OperationPreference /// <summary> /// <para> /// <para>Preferences for how AWS CloudFormation performs this stack set operation.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("OperationPreferences")] public Amazon.CloudFormation.Model.StackSetOperationPreferences OperationPreference { get; set; } #endregion #region Parameter DeploymentTargets_OrganizationalUnitId /// <summary> /// <para> /// <para>The organization root ID or organizational unit (OUs) IDs to which StackSets deploys.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("DeploymentTargets_OrganizationalUnitIds")] public System.String[] DeploymentTargets_OrganizationalUnitId { get; set; } #endregion #region Parameter Parameter /// <summary> /// <para> /// <para>A list of input parameters for the stack set template. </para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("Parameters")] public Amazon.CloudFormation.Model.Parameter[] Parameter { get; set; } #endregion #region Parameter PermissionModel /// <summary> /// <para> /// <para>Describes how the IAM roles required for stack set operations are created. You cannot /// modify <code>PermissionModel</code> if there are stack instances associated with your /// stack set.</para><ul><li><para>With <code>self-managed</code> permissions, you must create the administrator and /// execution roles required to deploy to target accounts. For more information, see <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-prereqs-self-managed.html">Grant /// Self-Managed Stack Set Permissions</a>.</para></li><li><para>With <code>service-managed</code> permissions, StackSets automatically creates the /// IAM roles required to deploy to accounts managed by AWS Organizations. For more information, /// see <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stacksets-prereqs-service-managed.html">Grant /// Service-Managed Stack Set Permissions</a>.</para></li></ul> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [AWSConstantClassSource("Amazon.CloudFormation.PermissionModels")] public Amazon.CloudFormation.PermissionModels PermissionModel { get; set; } #endregion #region Parameter StackRegion /// <summary> /// <para> /// <para>The regions in which to update associated stack instances. If you specify regions, /// you must also specify accounts in which to update stack set instances.</para><para>To update <i>all</i> the stack instances associated with this stack set, do not specify /// the <code>Accounts</code> or <code>Regions</code> properties.</para><para>If the stack set update includes changes to the template (that is, if the <code>TemplateBody</code> /// or <code>TemplateURL</code> properties are specified), or the <code>Parameters</code> /// property, AWS CloudFormation marks all stack instances with a status of <code>OUTDATED</code> /// prior to updating the stack instances in the specified accounts and regions. If the /// stack set update does not include changes to the template or parameters, AWS CloudFormation /// updates the stack instances in the specified accounts and regions, while leaving all /// other stack instances with their existing stack instance status. </para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String[] StackRegion { get; set; } #endregion #region Parameter AutoDeployment_RetainStacksOnAccountRemoval /// <summary> /// <para> /// <para>If set to <code>true</code>, stack resources are retained when an account is removed /// from a target organization or OU. If set to <code>false</code>, stack resources are /// deleted. Specify only if <code>Enabled</code> is set to <code>True</code>.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.Boolean? AutoDeployment_RetainStacksOnAccountRemoval { get; set; } #endregion #region Parameter StackSetName /// <summary> /// <para> /// <para>The name or unique ID of the stack set that you want to update.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String StackSetName { get; set; } #endregion #region Parameter Tag /// <summary> /// <para> /// <para>The key-value pairs to associate with this stack set and the stacks created from it. /// AWS CloudFormation also propagates these tags to supported resources that are created /// in the stacks. You can specify a maximum number of 50 tags.</para><para>If you specify tags for this parameter, those tags replace any list of tags that are /// currently associated with this stack set. This means:</para><ul><li><para>If you don't specify this parameter, AWS CloudFormation doesn't modify the stack's /// tags. </para></li><li><para>If you specify <i>any</i> tags using this parameter, you must specify <i>all</i> the /// tags that you want associated with this stack set, even tags you've specifed before /// (for example, when creating the stack set or during a previous update of the stack /// set.). Any tags that you don't include in the updated list of tags are removed from /// the stack set, and therefore from the stacks and resources as well. </para></li><li><para>If you specify an empty value, AWS CloudFormation removes all currently associated /// tags.</para></li></ul><para>If you specify new tags as part of an <code>UpdateStackSet</code> action, AWS CloudFormation /// checks to see if you have the required IAM permission to tag resources. If you omit /// tags that are currently associated with the stack set from the list of tags you specify, /// AWS CloudFormation assumes that you want to remove those tags from the stack set, /// and checks to see if you have permission to untag resources. If you don't have the /// necessary permission(s), the entire <code>UpdateStackSet</code> action fails with /// an <code>access denied</code> error, and the stack set is not updated.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] [Alias("Tags")] public Amazon.CloudFormation.Model.Tag[] Tag { get; set; } #endregion #region Parameter TemplateBody /// <summary> /// <para> /// <para>The structure that contains the template body, with a minimum length of 1 byte and /// a maximum length of 51,200 bytes. For more information, see <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html">Template /// Anatomy</a> in the AWS CloudFormation User Guide.</para><para>Conditional: You must specify only one of the following parameters: <code>TemplateBody</code> /// or <code>TemplateURL</code>—or set <code>UsePreviousTemplate</code> to true.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String TemplateBody { get; set; } #endregion #region Parameter TemplateURL /// <summary> /// <para> /// <para>The location of the file that contains the template body. The URL must point to a /// template (maximum size: 460,800 bytes) that is located in an Amazon S3 bucket. For /// more information, see <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/template-anatomy.html">Template /// Anatomy</a> in the AWS CloudFormation User Guide.</para><para>Conditional: You must specify only one of the following parameters: <code>TemplateBody</code> /// or <code>TemplateURL</code>—or set <code>UsePreviousTemplate</code> to true. </para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String TemplateURL { get; set; } #endregion #region Parameter UsePreviousTemplate /// <summary> /// <para> /// <para>Use the existing template that's associated with the stack set that you're updating.</para><para>Conditional: You must specify only one of the following parameters: <code>TemplateBody</code> /// or <code>TemplateURL</code>—or set <code>UsePreviousTemplate</code> to true. </para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.Boolean? UsePreviousTemplate { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The default value is 'OperationId'. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.CloudFormation.Model.UpdateStackSetResponse). /// Specifying the name of a property of type Amazon.CloudFormation.Model.UpdateStackSetResponse will result in that property being returned. /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "OperationId"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the StackSetName parameter. /// The -PassThru parameter is deprecated, use -Select '^StackSetName' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^StackSetName' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.StackSetName), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Update-CFNStackSet (UpdateStackSet)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.CloudFormation.Model.UpdateStackSetResponse, UpdateCFNStackSetCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.StackSetName; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute if (this.Account != null) { context.Account = new List<System.String>(this.Account); } context.AdministrationRoleARN = this.AdministrationRoleARN; context.AutoDeployment_Enabled = this.AutoDeployment_Enabled; context.AutoDeployment_RetainStacksOnAccountRemoval = this.AutoDeployment_RetainStacksOnAccountRemoval; if (this.Capability != null) { context.Capability = new List<System.String>(this.Capability); } if (this.DeploymentTargets_Account != null) { context.DeploymentTargets_Account = new List<System.String>(this.DeploymentTargets_Account); } if (this.DeploymentTargets_OrganizationalUnitId != null) { context.DeploymentTargets_OrganizationalUnitId = new List<System.String>(this.DeploymentTargets_OrganizationalUnitId); } context.Description = this.Description; context.ExecutionRoleName = this.ExecutionRoleName; context.OperationId = this.OperationId; context.OperationPreference = this.OperationPreference; if (this.Parameter != null) { context.Parameter = new List<Amazon.CloudFormation.Model.Parameter>(this.Parameter); } context.PermissionModel = this.PermissionModel; if (this.StackRegion != null) { context.StackRegion = new List<System.String>(this.StackRegion); } context.StackSetName = this.StackSetName; #if MODULAR if (this.StackSetName == null && ParameterWasBound(nameof(this.StackSetName))) { WriteWarning("You are passing $null as a value for parameter StackSetName which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif if (this.Tag != null) { context.Tag = new List<Amazon.CloudFormation.Model.Tag>(this.Tag); } context.TemplateBody = this.TemplateBody; context.TemplateURL = this.TemplateURL; context.UsePreviousTemplate = this.UsePreviousTemplate; // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.CloudFormation.Model.UpdateStackSetRequest(); if (cmdletContext.Account != null) { request.Accounts = cmdletContext.Account; } if (cmdletContext.AdministrationRoleARN != null) { request.AdministrationRoleARN = cmdletContext.AdministrationRoleARN; } // populate AutoDeployment var requestAutoDeploymentIsNull = true; request.AutoDeployment = new Amazon.CloudFormation.Model.AutoDeployment(); System.Boolean? requestAutoDeployment_autoDeployment_Enabled = null; if (cmdletContext.AutoDeployment_Enabled != null) { requestAutoDeployment_autoDeployment_Enabled = cmdletContext.AutoDeployment_Enabled.Value; } if (requestAutoDeployment_autoDeployment_Enabled != null) { request.AutoDeployment.Enabled = requestAutoDeployment_autoDeployment_Enabled.Value; requestAutoDeploymentIsNull = false; } System.Boolean? requestAutoDeployment_autoDeployment_RetainStacksOnAccountRemoval = null; if (cmdletContext.AutoDeployment_RetainStacksOnAccountRemoval != null) { requestAutoDeployment_autoDeployment_RetainStacksOnAccountRemoval = cmdletContext.AutoDeployment_RetainStacksOnAccountRemoval.Value; } if (requestAutoDeployment_autoDeployment_RetainStacksOnAccountRemoval != null) { request.AutoDeployment.RetainStacksOnAccountRemoval = requestAutoDeployment_autoDeployment_RetainStacksOnAccountRemoval.Value; requestAutoDeploymentIsNull = false; } // determine if request.AutoDeployment should be set to null if (requestAutoDeploymentIsNull) { request.AutoDeployment = null; } if (cmdletContext.Capability != null) { request.Capabilities = cmdletContext.Capability; } // populate DeploymentTargets var requestDeploymentTargetsIsNull = true; request.DeploymentTargets = new Amazon.CloudFormation.Model.DeploymentTargets(); List<System.String> requestDeploymentTargets_deploymentTargets_Account = null; if (cmdletContext.DeploymentTargets_Account != null) { requestDeploymentTargets_deploymentTargets_Account = cmdletContext.DeploymentTargets_Account; } if (requestDeploymentTargets_deploymentTargets_Account != null) { request.DeploymentTargets.Accounts = requestDeploymentTargets_deploymentTargets_Account; requestDeploymentTargetsIsNull = false; } List<System.String> requestDeploymentTargets_deploymentTargets_OrganizationalUnitId = null; if (cmdletContext.DeploymentTargets_OrganizationalUnitId != null) { requestDeploymentTargets_deploymentTargets_OrganizationalUnitId = cmdletContext.DeploymentTargets_OrganizationalUnitId; } if (requestDeploymentTargets_deploymentTargets_OrganizationalUnitId != null) { request.DeploymentTargets.OrganizationalUnitIds = requestDeploymentTargets_deploymentTargets_OrganizationalUnitId; requestDeploymentTargetsIsNull = false; } // determine if request.DeploymentTargets should be set to null if (requestDeploymentTargetsIsNull) { request.DeploymentTargets = null; } if (cmdletContext.Description != null) { request.Description = cmdletContext.Description; } if (cmdletContext.ExecutionRoleName != null) { request.ExecutionRoleName = cmdletContext.ExecutionRoleName; } if (cmdletContext.OperationId != null) { request.OperationId = cmdletContext.OperationId; } if (cmdletContext.OperationPreference != null) { request.OperationPreferences = cmdletContext.OperationPreference; } if (cmdletContext.Parameter != null) { request.Parameters = cmdletContext.Parameter; } if (cmdletContext.PermissionModel != null) { request.PermissionModel = cmdletContext.PermissionModel; } if (cmdletContext.StackRegion != null) { request.Regions = cmdletContext.StackRegion; } if (cmdletContext.StackSetName != null) { request.StackSetName = cmdletContext.StackSetName; } if (cmdletContext.Tag != null) { request.Tags = cmdletContext.Tag; } if (cmdletContext.TemplateBody != null) { request.TemplateBody = cmdletContext.TemplateBody; } if (cmdletContext.TemplateURL != null) { request.TemplateURL = cmdletContext.TemplateURL; } if (cmdletContext.UsePreviousTemplate != null) { request.UsePreviousTemplate = cmdletContext.UsePreviousTemplate.Value; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.CloudFormation.Model.UpdateStackSetResponse CallAWSServiceOperation(IAmazonCloudFormation client, Amazon.CloudFormation.Model.UpdateStackSetRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS CloudFormation", "UpdateStackSet"); try { #if DESKTOP return client.UpdateStackSet(request); #elif CORECLR return client.UpdateStackSetAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public List<System.String> Account { get; set; } public System.String AdministrationRoleARN { get; set; } public System.Boolean? AutoDeployment_Enabled { get; set; } public System.Boolean? AutoDeployment_RetainStacksOnAccountRemoval { get; set; } public List<System.String> Capability { get; set; } public List<System.String> DeploymentTargets_Account { get; set; } public List<System.String> DeploymentTargets_OrganizationalUnitId { get; set; } public System.String Description { get; set; } public System.String ExecutionRoleName { get; set; } public System.String OperationId { get; set; } public Amazon.CloudFormation.Model.StackSetOperationPreferences OperationPreference { get; set; } public List<Amazon.CloudFormation.Model.Parameter> Parameter { get; set; } public Amazon.CloudFormation.PermissionModels PermissionModel { get; set; } public List<System.String> StackRegion { get; set; } public System.String StackSetName { get; set; } public List<Amazon.CloudFormation.Model.Tag> Tag { get; set; } public System.String TemplateBody { get; set; } public System.String TemplateURL { get; set; } public System.Boolean? UsePreviousTemplate { get; set; } public System.Func<Amazon.CloudFormation.Model.UpdateStackSetResponse, UpdateCFNStackSetCmdlet, object> Select { get; set; } = (response, cmdlet) => response.OperationId; } } }
57.08432
283
0.645935
[ "Apache-2.0" ]
JekzVadaria/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/CloudFormation/Basic/Update-CFNStackSet-Cmdlet.cs
38,595
C#
/* * THIS FILE WAS GENERATED BY PLOTLY.BLAZOR.GENERATOR */ using System.Text.Json.Serialization; using System.Runtime.Serialization; #pragma warning disable 1591 namespace Plotly.Blazor.LayoutLib.LegendLib { /// <summary> /// Determines the behavior on legend item double-click. <c>toggle</c> toggles /// the visibility of the item clicked on the graph. <c>toggleothers</c> makes /// the clicked item the sole visible item on the graph. <c>false</c> disables /// legend item double-click interactions. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Plotly.Blazor.Generator", "1.0.0.0")] [JsonConverter(typeof(EnumConverter))] public enum ItemDoubleClickEnum { [EnumMember(Value=@"toggleothers")] ToggleOthers = 0, [EnumMember(Value=@"toggle")] Toggle, [EnumMember(Value=@"False")] False } }
32.464286
86
0.662266
[ "MIT" ]
ScriptBox99/Plotly.Blazor
Plotly.Blazor/LayoutLib/LegendLib/ItemDoubleClickEnum.cs
909
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.DataMigration.Latest.Inputs { /// <summary> /// Types of validations to run after the migration /// </summary> public sealed class MigrationValidationOptionsArgs : Pulumi.ResourceArgs { /// <summary> /// Allows to perform a checksum based data integrity validation between source and target for the selected database / tables . /// </summary> [Input("enableDataIntegrityValidation")] public Input<bool>? EnableDataIntegrityValidation { get; set; } /// <summary> /// Allows to perform a quick and intelligent query analysis by retrieving queries from the source database and executes them in the target. The result will have execution statistics for executions in source and target databases for the extracted queries. /// </summary> [Input("enableQueryAnalysisValidation")] public Input<bool>? EnableQueryAnalysisValidation { get; set; } /// <summary> /// Allows to compare the schema information between source and target. /// </summary> [Input("enableSchemaValidation")] public Input<bool>? EnableSchemaValidation { get; set; } public MigrationValidationOptionsArgs() { } } }
38.512195
263
0.685244
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/DataMigration/Latest/Inputs/MigrationValidationOptionsArgs.cs
1,579
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Reflection; using BTDB.Buffer; using BTDB.FieldHandler; using BTDB.IL; using BTDB.KVDBLayer; using BTDB.StreamLayer; namespace BTDB.ODBLayer { internal class RelationBuilder<T> { readonly RelationInfo _relationInfo; public RelationBuilder(RelationInfo relationInfo) { _relationInfo = relationInfo; } public Func<IObjectDBTransaction, T> Build(string relationName, Type relationDBManipulatorType) { var interfaceType = typeof(T); var classImpl = ILBuilder.Instance.NewType("Relation" + relationName, relationDBManipulatorType, new[] { interfaceType }); var constructorMethod = classImpl.DefineConstructor(new[] { typeof(IObjectDBTransaction), typeof(RelationInfo) }); var il = constructorMethod.Generator; // super.ctor(transaction, relationInfo); il.Ldarg(0).Ldarg(1).Ldarg(2).Call(relationDBManipulatorType.GetConstructor(new[] { typeof(IObjectDBTransaction), typeof(RelationInfo) })) .Ret(); GenerateApartFieldsProperties(classImpl, interfaceType); var methods = RelationInfo.GetMethods(interfaceType); foreach (var method in methods) { if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_")) continue; var reqMethod = classImpl.DefineMethod("_R_" + method.Name, method.ReturnType, method.GetParameters().Select(pi => pi.ParameterType).ToArray(), MethodAttributes.Virtual | MethodAttributes.Public); if (method.Name.StartsWith("RemoveBy")) { if (method.Name == "RemoveByIdPartial") BuildRemoveByIdPartialMethod(method, reqMethod, relationDBManipulatorType); else BuildRemoveByMethod(method, reqMethod, relationDBManipulatorType); } else if (method.Name.StartsWith("FindBy")) { BuildFindByMethod(method, reqMethod, relationDBManipulatorType); } else if (method.Name == "Contains") { BuildContainsMethod(method, reqMethod, relationDBManipulatorType); } else if (method.Name == "ListById") //list by primary key { BuildListByIdMethod(method, reqMethod); } else if (method.Name.StartsWith("ListBy", StringComparison.Ordinal)) //ListBy{Name}(tenantId, .., AdvancedEnumeratorParam) { BuildListByMethod(method, reqMethod); } else if (method.Name == "Insert") { BuildInsertMethod(method, reqMethod, relationDBManipulatorType); } else { BuildManipulatorCallWithSameParameters(method, reqMethod, relationDBManipulatorType); } reqMethod.Generator.Ret(); classImpl.DefineMethodOverride(reqMethod, method); } var classImplType = classImpl.CreateType(); return BuildRelationCreatorInstance<T>(classImplType, relationName, _relationInfo); } void BuildContainsMethod(MethodInfo method, IILMethod reqMethod, Type relationDBManipulatorType) { var writerLoc = reqMethod.Generator.DeclareLocal(typeof(ByteBufferWriter)); reqMethod.Generator.Newobj(() => new ByteBufferWriter()); reqMethod.Generator.Stloc(writerLoc); //ByteBufferWriter.WriteVUInt32(RelationInfo.Id); WriteIdIl(reqMethod.Generator, il => il.Ldloc(writerLoc), (int)_relationInfo.Id); var primaryKeyFields = _relationInfo.ClientRelationVersionInfo.GetPrimaryKeyFields(); var count = SaveMethodParameters(reqMethod.Generator, "Contains", method.GetParameters(), method.GetParameters().Length, _relationInfo.ApartFields, primaryKeyFields, writerLoc); if (count != primaryKeyFields.Count) throw new BTDBException($"Number of parameters in Contains does not match primary key count {primaryKeyFields.Count}."); //call manipulator.Contains reqMethod.Generator .Ldarg(0); //manipulator //call byteBuffer.data var dataGetter = typeof(ByteBufferWriter).GetProperty("Data").GetGetMethod(true); reqMethod.Generator.Ldloc(writerLoc).Callvirt(dataGetter); reqMethod.Generator.Callvirt(relationDBManipulatorType.GetMethod("Contains")); } void BuildFindByMethod(MethodInfo method, IILMethod reqMethod, Type relationDBManipulatorType) { var writerLoc = reqMethod.Generator.DeclareLocal(typeof(ByteBufferWriter)); reqMethod.Generator.Newobj(() => new ByteBufferWriter()); reqMethod.Generator.Stloc(writerLoc); Action<IILGen> pushWriter = il => il.Ldloc(writerLoc); if (method.Name == "FindById" || method.Name == "FindByIdOrDefault") { CreateMethodFindById(reqMethod.Generator, relationDBManipulatorType, method.Name, method.GetParameters(), method.ReturnType, _relationInfo.ApartFields, pushWriter, writerLoc); } else { CreateMethodFindBy(reqMethod.Generator, relationDBManipulatorType, method.Name, method.GetParameters(), method.ReturnType, _relationInfo.ApartFields, pushWriter, writerLoc); } } void BuildRemoveByMethod(MethodInfo method, IILMethod reqMethod, Type relationDBManipulatorType) { var methodParameters = method.GetParameters(); var isPrefixBased = method.ReturnType == typeof(int); //returns number of removed items var writerLoc = reqMethod.Generator.DeclareLocal(typeof(ByteBufferWriter)); reqMethod.Generator.Newobj(() => new ByteBufferWriter()); reqMethod.Generator.Stloc(writerLoc); Action<IILGen> pushWriter = il => il.Ldloc(writerLoc); if (isPrefixBased) WriteShortPrefixIl(reqMethod.Generator, pushWriter, _relationInfo.Prefix); else //ByteBufferWriter.WriteVUInt32(RelationInfo.Id); WriteIdIl(reqMethod.Generator, pushWriter, (int)_relationInfo.Id); var primaryKeyFields = _relationInfo.ClientRelationVersionInfo.GetPrimaryKeyFields(); var count = SaveMethodParameters(reqMethod.Generator, method.Name, methodParameters, methodParameters.Length, _relationInfo.ApartFields, primaryKeyFields, writerLoc); if (!isPrefixBased && count != primaryKeyFields.Count) throw new BTDBException($"Number of parameters in {method.Name} does not match primary key count {primaryKeyFields.Count}."); //call manipulator.RemoveBy_ reqMethod.Generator .Ldarg(0); //manipulator //call byteBuffer.data var dataGetter = typeof(ByteBufferWriter).GetProperty("Data").GetGetMethod(true); reqMethod.Generator.Ldloc(writerLoc).Callvirt(dataGetter); if (isPrefixBased) { if (AllKeyPrefixesAreSame(_relationInfo.ClientRelationVersionInfo, count) && !_relationInfo.NeedImplementFreeContent()) reqMethod.Generator.Callvirt(relationDBManipulatorType.GetMethod("RemoveByKeyPrefixWithoutIterate")); else reqMethod.Generator.Callvirt(relationDBManipulatorType.GetMethod("RemoveByPrimaryKeyPrefix")); } else { reqMethod.Generator.LdcI4(ShouldThrowWhenKeyNotFound(method.Name, method.ReturnType) ? 1 : 0); reqMethod.Generator.Callvirt(relationDBManipulatorType.GetMethod("RemoveById")); if (method.ReturnType == typeof(void)) reqMethod.Generator.Pop(); } } void BuildRemoveByIdPartialMethod(MethodInfo method, IILMethod reqMethod, Type relationDbManipulatorType) { var methodParameters = method.GetParameters(); var isPrefixBased = method.ReturnType == typeof(int); //returns number of removed items if (!isPrefixBased || methodParameters.Length == 0 || methodParameters[methodParameters.Length - 1].ParameterType != typeof(int) || methodParameters[methodParameters.Length - 1].Name.IndexOf("max", StringComparison.InvariantCultureIgnoreCase) == -1) { throw new BTDBException("Invalid shape of RemoveByIdPartial."); } var il = reqMethod.Generator; var writerLoc = il.DeclareLocal(typeof(ByteBufferWriter)); il .Newobj(() => new ByteBufferWriter()) .Stloc(writerLoc); WriteShortPrefixIl(il, ilg => ilg.Ldloc(writerLoc), _relationInfo.Prefix); var primaryKeyFields = _relationInfo.ClientRelationVersionInfo.GetPrimaryKeyFields(); SaveMethodParameters(il, method.Name, methodParameters, methodParameters.Length - 1, _relationInfo.ApartFields, primaryKeyFields, writerLoc); var dataGetter = typeof(ByteBufferWriter).GetProperty("Data").GetGetMethod(true); il .Ldarg(0) //manipulator .Ldloc(writerLoc).Callvirt(dataGetter) //call byteBuffer.Data .Ldarg((ushort)methodParameters.Length) .Callvirt(relationDbManipulatorType.GetMethod("RemoveByPrimaryKeyPrefixPartial")); } static bool AllKeyPrefixesAreSame(RelationVersionInfo relationInfo, ushort count) { foreach (var sk in relationInfo.SecondaryKeys) { var skFields = sk.Value; var idx = 0; foreach (var field in skFields.Fields) { if (!field.IsFromPrimaryKey) return false; if (field.Index != idx) return false; if (++idx == count) break; } } return true; } void BuildListByIdMethod(MethodInfo method, IILMethod reqMethod) { var parameters = method.GetParameters(); var advEnumParamOrder = (ushort)parameters.Length; var advEnumParam = parameters[advEnumParamOrder - 1].ParameterType; var advEnumParamType = advEnumParam.GenericTypeArguments[0]; var emptyBufferLoc = reqMethod.Generator.DeclareLocal(typeof(ByteBuffer)); var prefixParamCount = parameters.Length - 1; var primaryKeyFields = _relationInfo.ClientRelationVersionInfo.GetPrimaryKeyFields(); var field = primaryKeyFields.Skip(_relationInfo.ApartFields.Count + prefixParamCount).First(); ValidateAdvancedEnumParameter(field, advEnumParamType, method.Name); reqMethod.Generator .Ldarg(0); SavePKListPrefixBytes(reqMethod.Generator, method.Name, parameters, _relationInfo.ApartFields); reqMethod.Generator .LdcI4(prefixParamCount + _relationInfo.ApartFields.Count) .Ldarg(advEnumParamOrder).Ldfld(advEnumParam.GetField("Order")) .Ldarg(advEnumParamOrder).Ldfld(advEnumParam.GetField("StartProposition")); FillBufferWhenNotIgnoredKeyPropositionIl(advEnumParamOrder, field, emptyBufferLoc, advEnumParam.GetField("Start"), reqMethod.Generator); reqMethod.Generator .Ldarg(advEnumParamOrder).Ldfld(advEnumParam.GetField("EndProposition")); FillBufferWhenNotIgnoredKeyPropositionIl(advEnumParamOrder, field, emptyBufferLoc, advEnumParam.GetField("End"), reqMethod.Generator); if (typeof(IEnumerator<>).MakeGenericType(_relationInfo.ClientType).IsAssignableFrom(method.ReturnType)) { //return new RelationAdvancedEnumerator<T>(relationManipulator, // prefixBytes, prefixFieldCount, // order, // startKeyProposition, startKeyBytes, // endKeyProposition, endKeyBytes, secondaryKeyIndex); var enumType = typeof(RelationAdvancedEnumerator<>).MakeGenericType(_relationInfo.ClientType); var advancedEnumeratorCtor = enumType.GetConstructors()[0]; reqMethod.Generator.Newobj(advancedEnumeratorCtor); } else if (typeof(IOrderedDictionaryEnumerator<,>).MakeGenericType(advEnumParamType, _relationInfo.ClientType) .IsAssignableFrom(method.ReturnType)) { reqMethod.Generator .LdcI4(1); //init key reader //return new RelationAdvancedOrderedEnumerator<T>(relationManipulator, // prefixBytes, prefixFieldCount, // order, // startKeyProposition, startKeyBytes, // endKeyProposition, endKeyBytes, secondaryKeyIndex, initKeyReader); var enumType = typeof(RelationAdvancedOrderedEnumerator<,>).MakeGenericType(advEnumParamType, _relationInfo.ClientType); var advancedEnumeratorCtor = enumType.GetConstructors()[0]; reqMethod.Generator.Newobj(advancedEnumeratorCtor); } else { throw new BTDBException("Invalid method " + method.Name); } } void BuildListByMethod(MethodInfo method, IILMethod reqMethod) { var parameters = method.GetParameters(); var advEnumParamOrder = (ushort)parameters.Length; var advEnumParam = parameters[advEnumParamOrder - 1].ParameterType; var advEnumParamType = advEnumParam.GenericTypeArguments[0]; var emptyBufferLoc = reqMethod.Generator.DeclareLocal(typeof(ByteBuffer)); var secondaryKeyIndex = _relationInfo.ClientRelationVersionInfo.GetSecondaryKeyIndex(method.Name.Substring(6)); var prefixParamCount = parameters.Length - 1; var skFields = _relationInfo.ClientRelationVersionInfo.GetSecondaryKeyFields(secondaryKeyIndex); var field = skFields.Skip(_relationInfo.ApartFields.Count + prefixParamCount).First(); ValidateAdvancedEnumParameter(field, advEnumParamType, method.Name); reqMethod.Generator .Ldarg(0); SaveListPrefixBytes(secondaryKeyIndex, reqMethod.Generator, method.Name, parameters, _relationInfo.ApartFields); reqMethod.Generator .LdcI4(prefixParamCount + _relationInfo.ApartFields.Count) .Ldarg(advEnumParamOrder).Ldfld(advEnumParam.GetField("Order")) .Ldarg(advEnumParamOrder).Ldfld(advEnumParam.GetField("StartProposition")); FillBufferWhenNotIgnoredKeyPropositionIl(advEnumParamOrder, field, emptyBufferLoc, advEnumParam.GetField("Start"), reqMethod.Generator); reqMethod.Generator .Ldarg(advEnumParamOrder).Ldfld(advEnumParam.GetField("EndProposition")); FillBufferWhenNotIgnoredKeyPropositionIl(advEnumParamOrder, field, emptyBufferLoc, advEnumParam.GetField("End"), reqMethod.Generator); reqMethod.Generator .LdcI4((int)secondaryKeyIndex); if (typeof(IEnumerator<>).MakeGenericType(_relationInfo.ClientType).IsAssignableFrom(method.ReturnType)) { //return new RelationAdvancedSecondaryKeyEnumerator<T>(relationManipulator, // prefixBytes, prefixFieldCount, // order, // startKeyProposition, startKeyBytes, // endKeyProposition, endKeyBytes, secondaryKeyIndex); var enumType = typeof(RelationAdvancedSecondaryKeyEnumerator<>).MakeGenericType(_relationInfo.ClientType); var advancedEnumeratorCtor = enumType.GetConstructors()[0]; reqMethod.Generator.Newobj(advancedEnumeratorCtor); } else if (typeof(IOrderedDictionaryEnumerator<,>).MakeGenericType(advEnumParamType, _relationInfo.ClientType) .IsAssignableFrom(method.ReturnType)) { //return new RelationAdvancedOrderedSecondaryKeyEnumerator<T>(relationManipulator, // prefixBytes, prefixFieldCount, // order, // startKeyProposition, startKeyBytes, // endKeyProposition, endKeyBytes, secondaryKeyIndex); var enumType = typeof(RelationAdvancedOrderedSecondaryKeyEnumerator<,>).MakeGenericType(advEnumParamType, _relationInfo.ClientType); var advancedEnumeratorCtor = enumType.GetConstructors()[0]; reqMethod.Generator.Newobj(advancedEnumeratorCtor); } else { throw new BTDBException("Invalid method " + method.Name); } } void ValidateAdvancedEnumParameter(TableFieldInfo field, Type advEnumParamType, string methodName) { if (!field.Handler.IsCompatibleWith(advEnumParamType, FieldHandlerOptions.Orderable)) { throw new BTDBException($"Parameter type mismatch in {methodName} (expected '{field.Handler.HandledType().ToSimpleName()}' but '{advEnumParamType.ToSimpleName()}' found)."); } } static void BuildInsertMethod(MethodInfo method, IILMethod reqMethod, Type relationDBManipulatorType) { var methodInfo = relationDBManipulatorType.GetMethod(method.Name); bool returningBoolVariant; var returnType = method.ReturnType; if (returnType == typeof(void)) returningBoolVariant = false; else if (returnType == typeof(bool)) returningBoolVariant = true; else throw new BTDBException("Method Insert should be defined with void or bool return type."); var methodParams = method.GetParameters(); CheckParameterCount(method.Name, 1, methodParams.Length); CheckParameterType(method.Name, 0, methodInfo.GetParameters()[0].ParameterType, methodParams[0].ParameterType); reqMethod.Generator .Ldarg(0) //this .Ldarg(1) .Callvirt(methodInfo); if (!returningBoolVariant) { var returnedTrueLabel = reqMethod.Generator.DefineLabel("returnedTrueLabel"); reqMethod.Generator .Brtrue(returnedTrueLabel) .Ldstr("Trying to insert duplicate key.") .Newobj(() => new BTDBException(null)) .Throw() .Mark(returnedTrueLabel); } } static void BuildManipulatorCallWithSameParameters(MethodInfo method, IILMethod reqMethod, Type relationDBManipulatorType) { var methodParams = method.GetParameters(); int paramCount = methodParams.Length; var methodInfo = relationDBManipulatorType.GetMethod(method.Name); if (methodInfo == null) throw new BTDBException($"Method {method} is not supported."); CheckReturnType(method.Name, methodInfo.ReturnType, method.ReturnType); var calledMethodParams = methodInfo.GetParameters(); CheckParameterCount(method.Name, calledMethodParams.Length, methodParams.Length); for (int i = 0; i < methodParams.Length; i++) { CheckParameterType(method.Name, i, calledMethodParams[i].ParameterType, methodParams[i].ParameterType); } for (ushort i = 0; i <= paramCount; i++) reqMethod.Generator.Ldarg(i); reqMethod.Generator.Callvirt(methodInfo); } static void CheckParameterType(string name, int parIdx, Type expectedType, Type actualType) { if (expectedType != actualType) throw new BTDBException($"Method {name} expects {parIdx}th parameter of type {expectedType.Name}."); } static void CheckParameterCount(string name, int expectedParameterCount, int actualParameterCount) { if (expectedParameterCount != actualParameterCount) throw new BTDBException($"Method {name} expects {expectedParameterCount} parameters count."); } static void CheckReturnType(string name, Type expectedReturnType, Type returnType) { if (returnType != expectedReturnType) throw new BTDBException($"Method {name} should be defined with {expectedReturnType.Name} return type."); } static Func<IObjectDBTransaction, T1> BuildRelationCreatorInstance<T1>(Type classImplType, string relationName, RelationInfo relationInfo) { var methodBuilder = ILBuilder.Instance.NewMethod("RelationFactory" + relationName, typeof(Func<IObjectDBTransaction, T1>), typeof(RelationInfo)); var ilGenerator = methodBuilder.Generator; ilGenerator .Ldarg(1) .Ldarg(0) .Newobj(classImplType.GetConstructor(new[] { typeof(IObjectDBTransaction), typeof(RelationInfo) })) .Castclass(typeof(T1)) .Ret(); return (Func<IObjectDBTransaction, T1>)methodBuilder.Create(relationInfo); } void CreateMethodFindById(IILGen ilGenerator, Type relationDBManipulatorType, string methodName, ParameterInfo[] methodParameters, Type methodReturnType, IDictionary<string, MethodInfo> apartFields, Action<IILGen> pushWriter, IILLocal writerLoc) { var isPrefixBased = ReturnsEnumerableOfClientType(methodReturnType, _relationInfo.ClientType); if (isPrefixBased) WriteShortPrefixIl(ilGenerator, pushWriter, _relationInfo.Prefix); else //ByteBufferWriter.WriteVUInt32(RelationInfo.Id); WriteIdIl(ilGenerator, pushWriter, (int)_relationInfo.Id); var primaryKeyFields = _relationInfo.ClientRelationVersionInfo.GetPrimaryKeyFields(); var count = SaveMethodParameters(ilGenerator, methodName, methodParameters, methodParameters.Length, apartFields, primaryKeyFields, writerLoc); if (!isPrefixBased && count != primaryKeyFields.Count) throw new BTDBException( $"Number of parameters in {methodName} does not match primary key count {primaryKeyFields.Count}."); //call manipulator.FindBy_ ilGenerator .Ldarg(0); //manipulator //call byteBuffer.data var dataGetter = typeof(ByteBufferWriter).GetProperty("Data").GetGetMethod(true); ilGenerator.Ldloc(writerLoc).Call(dataGetter); if (isPrefixBased) { ilGenerator.Callvirt(relationDBManipulatorType.GetMethod("FindByPrimaryKeyPrefix")); } else { ilGenerator.LdcI4(ShouldThrowWhenKeyNotFound(methodName, methodReturnType) ? 1 : 0); ilGenerator.Callvirt(relationDBManipulatorType.GetMethod("FindByIdOrDefault")); if (methodReturnType == typeof(void)) ilGenerator.Pop(); } } void CreateMethodFindBy(IILGen ilGenerator, Type relationDBManipulatorType, string methodName, ParameterInfo[] methodParameters, Type methodReturnType, IDictionary<string, MethodInfo> apartFields, Action<IILGen> pushWriter, IILLocal writerLoc) { bool allowDefault = false; var skName = methodName.Substring(6); if (skName.EndsWith("OrDefault")) { skName = skName.Substring(0, skName.Length - 9); allowDefault = true; } WriteShortPrefixIl(ilGenerator, pushWriter, ObjectDB.AllRelationsSKPrefix); var skIndex = _relationInfo.ClientRelationVersionInfo.GetSecondaryKeyIndex(skName); //ByteBuffered.WriteVUInt32(RelationInfo.Id); WriteIdIl(ilGenerator, pushWriter, (int)_relationInfo.Id); //ByteBuffered.WriteVUInt32(skIndex); WriteIdIl(ilGenerator, pushWriter, (int)skIndex); var secondaryKeyFields = _relationInfo.ClientRelationVersionInfo.GetSecondaryKeyFields(skIndex); SaveMethodParameters(ilGenerator, methodName, methodParameters, methodParameters.Length, apartFields, secondaryKeyFields, writerLoc); //call public T FindBySecondaryKeyOrDefault(uint secondaryKeyIndex, uint prefixParametersCount, ByteBuffer secKeyBytes, bool throwWhenNotFound) ilGenerator.Ldarg(0); //manipulator ilGenerator.LdcI4((int)skIndex); ilGenerator.LdcI4(methodParameters.Length + apartFields.Count); //call byteBuffer.data var dataGetter = typeof(ByteBufferWriter).GetProperty("Data").GetGetMethod(true); ilGenerator.Ldloc(writerLoc).Callvirt(dataGetter); if (ReturnsEnumerableOfClientType(methodReturnType, _relationInfo.ClientType)) { ilGenerator.Callvirt(relationDBManipulatorType.GetMethod("FindBySecondaryKey")); } else { ilGenerator.LdcI4(allowDefault ? 0 : 1); //? should throw ilGenerator.Callvirt(relationDBManipulatorType.GetMethod("FindBySecondaryKeyOrDefault")); } } static bool ReturnsEnumerableOfClientType(Type methodReturnType, Type clientType) { return methodReturnType.IsGenericType && methodReturnType.GetGenericTypeDefinition() == typeof(IEnumerator<>) && methodReturnType.GetGenericArguments()[0] == clientType; } static ushort SaveMethodParameters(IILGen ilGenerator, string methodName, ParameterInfo[] methodParameters, int paramCount, IDictionary<string, MethodInfo> apartFields, IEnumerable<TableFieldInfo> fields, IILLocal writerLoc) { ushort usedApartFieldsCount = 0; ushort idx = 0; foreach (var field in fields) { MethodInfo fieldGetter; if (apartFields.TryGetValue(field.Name, out fieldGetter)) { usedApartFieldsCount++; SaveKeyFieldFromApartField(ilGenerator, field, fieldGetter, writerLoc); continue; } if (idx == paramCount) { break; } var par = methodParameters[idx++]; if (string.Compare(field.Name, par.Name.ToLower(), StringComparison.OrdinalIgnoreCase) != 0) { throw new BTDBException($"Parameter and key mismatch in {methodName}, {field.Name}!={par.Name}."); } if (!field.Handler.IsCompatibleWith(par.ParameterType, FieldHandlerOptions.Orderable)) { throw new BTDBException($"Parameter type mismatch in {methodName} (expected '{field.Handler.HandledType().ToSimpleName()}' but '{par.ParameterType.ToSimpleName()}' found)."); } SaveKeyFieldFromArgument(ilGenerator, field, idx, par.ParameterType, writerLoc); } if (usedApartFieldsCount != apartFields.Count) { throw new BTDBException($"Apart fields must be part of prefix in {methodName}."); } return (ushort)(idx + usedApartFieldsCount); } static bool ShouldThrowWhenKeyNotFound(string methodName, Type methodReturnType) { if (methodName.StartsWith("RemoveBy")) return methodReturnType == typeof(void); if (methodName == "FindByIdOrDefault") return false; return true; } internal static void FillBufferWhenNotIgnoredKeyPropositionIl(ushort advEnumParamOrder, TableFieldInfo field, IILLocal emptyBufferLoc, FieldInfo instField, IILGen ilGenerator) { //stack contains KeyProposition var ignoreLabel = ilGenerator.DefineLabel(instField + "_ignore"); var doneLabel = ilGenerator.DefineLabel(instField + "_done"); var writerLoc = ilGenerator.DeclareLocal(typeof(AbstractBufferedWriter)); ilGenerator .Dup() .LdcI4((int)KeyProposition.Ignored) .BeqS(ignoreLabel) .Newobj(() => new ByteBufferWriter()) .Stloc(writerLoc); field.Handler.SpecializeSaveForType(instField.FieldType).Save(ilGenerator, il => il.Ldloc(writerLoc), il => il.Ldarg(advEnumParamOrder).Ldfld(instField)); var dataGetter = typeof(ByteBufferWriter).GetProperty("Data").GetGetMethod(true); ilGenerator.Ldloc(writerLoc).Castclass(typeof(ByteBufferWriter)).Callvirt(dataGetter); ilGenerator .Br(doneLabel) .Mark(ignoreLabel) .Ldloc(emptyBufferLoc) .Mark(doneLabel); } void SaveListPrefixBytes(uint secondaryKeyIndex, IILGen ilGenerator, string methodName, ParameterInfo[] methodParameters, IDictionary<string, MethodInfo> apartFields) { var writerLoc = ilGenerator.DeclareLocal(typeof(ByteBufferWriter)); ilGenerator .Newobj(() => new ByteBufferWriter()) .Stloc(writerLoc); Action<IILGen> pushWriter = il => il.Ldloc(writerLoc); WriteShortPrefixIl(ilGenerator, pushWriter, ObjectDB.AllRelationsSKPrefix); //ByteBuffered.WriteVUInt32(RelationInfo.Id); WriteIdIl(ilGenerator, pushWriter, (int)_relationInfo.Id); //ByteBuffered.WriteVUInt32(skIndex); WriteIdIl(ilGenerator, pushWriter, (int)secondaryKeyIndex); var secondaryKeyFields = _relationInfo.ClientRelationVersionInfo.GetSecondaryKeyFields(secondaryKeyIndex); var paramCount = methodParameters.Length - 1; //last param is key proposition SaveMethodParameters(ilGenerator, methodName, methodParameters, paramCount, apartFields, secondaryKeyFields, writerLoc); var dataGetter = typeof(ByteBufferWriter).GetProperty("Data").GetGetMethod(true); ilGenerator.Ldloc(writerLoc).Callvirt(dataGetter); } void SavePKListPrefixBytes(IILGen ilGenerator, string methodName, ParameterInfo[] methodParameters, IDictionary<string, MethodInfo> apartFields) { var writerLoc = ilGenerator.DeclareLocal(typeof(ByteBufferWriter)); ilGenerator .Newobj(() => new ByteBufferWriter()) .Stloc(writerLoc); Action<IILGen> pushWriter = il => il.Ldloc(writerLoc); WriteShortPrefixIl(ilGenerator, pushWriter, _relationInfo.Prefix); var keyFields = _relationInfo.ClientRelationVersionInfo.GetPrimaryKeyFields(); var paramCount = methodParameters.Length - 1; //last param is key proposition SaveMethodParameters(ilGenerator, methodName, methodParameters, paramCount, apartFields, keyFields, writerLoc); var dataGetter = typeof(ByteBufferWriter).GetProperty("Data").GetGetMethod(true); ilGenerator.Ldloc(writerLoc).Callvirt(dataGetter); } void GenerateApartFieldsProperties(IILDynamicType classImpl, Type interfaceType) { var apartFields = new Dictionary<string, IILField>(); var initializedFields = new Dictionary<string, IILField>(); var methods = RelationInfo.GetMethods(interfaceType); var properties = RelationInfo.GetProperties(interfaceType).ToArray(); foreach (var method in methods) { var name = method.Name; if (!name.StartsWith("get_") && !name.StartsWith("set_")) continue; IILField field; IILField initCheckField; var propName = RelationInfo.GetPersistentName(method.Name.Substring(4), properties); if (!_relationInfo.ApartFields.ContainsKey(propName)) throw new BTDBException($"Invalid property name {propName}."); if (!apartFields.TryGetValue(propName, out field)) { field = classImpl.DefineField("_" + propName, method.ReturnType, FieldAttributes.Private); apartFields[propName] = field; initCheckField = classImpl.DefineField("_initialized_" + propName, typeof(bool), FieldAttributes.Private); initializedFields[propName] = initCheckField; } else { initCheckField = initializedFields[propName]; } var reqMethod = classImpl.DefineMethod(method.Name, method.ReturnType, method.GetParameters().Select(pi => pi.ParameterType).ToArray(), MethodAttributes.Virtual | MethodAttributes.Public); if (name.StartsWith("set_")) { reqMethod.Generator.Ldarg(0).Ldarg(1).Stfld(field) .Ldarg(0).LdcI4(1).Stfld(initCheckField) .Ret(); } else { var initializedLabel = reqMethod.Generator.DefineLabel("initialized"); reqMethod.Generator .Ldarg(0).Ldfld(initCheckField) .Brtrue(initializedLabel) .Ldstr($"Cannot use uninitialized apart field {propName}") .Newobj(() => new BTDBException(null)) .Throw() .Mark(initializedLabel) .Ldarg(0).Ldfld(field).Ret(); } classImpl.DefineMethodOverride(reqMethod, method); } } static void SaveKeyFieldFromArgument(IILGen ilGenerator, TableFieldInfo field, ushort parameterId, Type parameterType, IILLocal writerLoc) { field.Handler.SpecializeSaveForType(parameterType).Save(ilGenerator, il => il.Ldloc(writerLoc), il => il.Ldarg(parameterId)); } static void SaveKeyFieldFromApartField(IILGen ilGenerator, TableFieldInfo field, MethodInfo fieldGetter, IILLocal writerLoc) { field.Handler.SpecializeSaveForType(fieldGetter.ReturnType).Save(ilGenerator, il => il.Ldloc(writerLoc), il => il.Ldarg(0).Callvirt(fieldGetter)); } static void WriteIdIl(IILGen ilGenerator, Action<IILGen> pushWriter, int id) { var bytes = new byte[PackUnpack.LengthVUInt((uint)id)]; int o = 0; PackUnpack.PackVUInt(bytes, ref o, (uint)id); WriteShortPrefixIl(ilGenerator, pushWriter, bytes); } static void WriteShortPrefixIl(IILGen ilGenerator, Action<IILGen> pushWriter, byte[] prefix) { foreach (byte b in prefix) ilGenerator .Do(pushWriter) .LdcI4(b) .Call(() => default(AbstractBufferedWriter).WriteUInt8(0)); } } }
50.713693
194
0.613293
[ "MIT" ]
Juzic/BTDB
BTDB/ODBLayer/RelationBuilder.cs
36,666
C#
using ESFA.DC.ILR.Model.Interface; using ESFA.DC.ILR.ValidationService.Interface; using ESFA.DC.ILR.ValidationService.Rules.Constants; using ESFA.DC.ILR.ValidationService.Rules.LearningDelivery.AFinType; using ESFA.DC.ILR.ValidationService.Utility; using Moq; using System; using System.Collections.Generic; using Xunit; namespace ESFA.DC.ILR.ValidationService.Rules.Tests.LearningDelivery.AFinType { /// <summary> /// from version 1.1 validation spread sheet /// </summary> public class AFinType_09RuleTests { /// <summary> /// New rule with null message handler throws. /// </summary> [Fact] public void NewRuleWithNullMessageHandlerThrows() { Assert.Throws<ArgumentNullException>(() => new AFinType_09Rule(null)); } /// <summary> /// Rule name 1, matches a literal. /// </summary> [Fact] public void RuleName1() { // arrange var sut = NewRule(); // act var result = sut.RuleName; // assert Assert.Equal("AFinType_09", result); } /// <summary> /// Rule name 2, matches the constant. /// </summary> [Fact] public void RuleName2() { // arrange var sut = NewRule(); // act var result = sut.RuleName; // assert Assert.Equal(AFinType_09Rule.Name, result); } /// <summary> /// Rule name 3 test, account for potential false positives. /// </summary> [Fact] public void RuleName3() { // arrange var sut = NewRule(); // act var result = sut.RuleName; // assert Assert.NotEqual("SomeOtherRuleName_07", result); } /// <summary> /// Validate with null learner throws. /// </summary> [Fact] public void ValidateWithNullLearnerThrows() { // arrange var sut = NewRule(); // act/assert Assert.Throws<ArgumentNullException>(() => sut.Validate(null)); } /// <summary> /// Condition met with null learning delivery returns true. /// </summary> [Fact] public void ConditionMetWithNullLearningDeliveryReturnsTrue() { // arrange var sut = NewRule(); // act var result = sut.ConditionMet(null); // assert Assert.True(result); } /// <summary> /// Condition met with learning delivery and null prog type returns false. /// </summary> [Fact] public void ConditionMetWithLearningDeliveryNullProgTypeReturnsFalse() { // arrange var sut = NewRule(); var mockDelivery = new Mock<ILearningDelivery>(MockBehavior.Strict); mockDelivery .SetupGet(x => x.AppFinRecords) .Returns((IReadOnlyCollection<IAppFinRecord>)null); // act var result = sut.ConditionMet(mockDelivery.Object); // assert Assert.False(result); mockDelivery.VerifyAll(); } /// <summary> /// Condition met with learning delivery and empty apprenticeship financial records returns false. /// </summary> [Fact] public void ConditionMetWithLearningDeliveryAndEmptyApprenticeshipFinancialRecordsReturnsFalse() { // arrange var sut = NewRule(); var mockDelivery = new Mock<ILearningDelivery>(MockBehavior.Strict); mockDelivery .SetupGet(x => x.AppFinRecords) .Returns(Collection.EmptyAndReadOnly<IAppFinRecord>()); // act var result = sut.ConditionMet(mockDelivery.Object); // assert Assert.False(result); mockDelivery.VerifyAll(); } /// <summary> /// Condition met with learning delivery and apprenticeship financial record returns true. /// </summary> [Fact] public void ConditionMetWithLearningDeliveryAndApprenticeshipFinancialRecordReturnsTrue() { // arrange var sut = NewRule(); var mockDelivery = new Mock<ILearningDelivery>(MockBehavior.Strict); var appFinRecords = Collection.Empty<IAppFinRecord>(); appFinRecords.Add(new Mock<IAppFinRecord>().Object); mockDelivery .SetupGet(x => x.AppFinRecords) .Returns(appFinRecords.AsSafeReadOnlyList()); // act var result = sut.ConditionMet(mockDelivery.Object); // assert Assert.True(result); mockDelivery.VerifyAll(); } /// <summary> /// Determines whether [is apprenticeship returns expectation] [for the specified type of funding]. /// </summary> /// <param name="forTypeOfFunding">The type of funding.</param> /// <param name="expectation">if set to <c>true</c> [expectation].</param> [Theory] [InlineData(TypeOfFunding.AdultSkills, false)] [InlineData(TypeOfFunding.Age16To19ExcludingApprenticeships, false)] [InlineData(TypeOfFunding.ApprenticeshipsFrom1May2017, true)] [InlineData(TypeOfFunding.CommunityLearning, false)] [InlineData(TypeOfFunding.EuropeanSocialFund, false)] [InlineData(TypeOfFunding.NotFundedByESFA, false)] [InlineData(TypeOfFunding.Other16To19, false)] [InlineData(TypeOfFunding.OtherAdult, false)] public void IsApprenticeshipReturnsExpectation(int forTypeOfFunding, bool expectation) { // arrange var sut = NewRule(); var mockDelivery = new Mock<ILearningDelivery>(MockBehavior.Strict); mockDelivery .SetupGet(x => x.FundModel) .Returns(forTypeOfFunding); // act var result = sut.IsApprenticeship(mockDelivery.Object); // assert Assert.Equal(expectation, result); mockDelivery.VerifyAll(); } /// <summary> /// Determines whether [is in training returns expectation] [for the specified type of funding and the aim]. /// </summary> /// <param name="forTypeOfFunding">For type of funding.</param> /// <param name="andProgrammeType">and the Programme Type.</param> /// <param name="expectation">if set to <c>true</c> [expectation].</param> [Theory] [InlineData(TypeOfFunding.AdultSkills, TypeOfLearningProgramme.AdvancedLevelApprenticeship, false)] [InlineData(TypeOfFunding.AdultSkills, TypeOfLearningProgramme.ApprenticeshipStandard, false)] [InlineData(TypeOfFunding.Age16To19ExcludingApprenticeships, TypeOfLearningProgramme.HigherApprenticeshipLevel4, false)] [InlineData(TypeOfFunding.Age16To19ExcludingApprenticeships, TypeOfLearningProgramme.ApprenticeshipStandard, false)] [InlineData(TypeOfFunding.ApprenticeshipsFrom1May2017, TypeOfLearningProgramme.HigherApprenticeshipLevel5, false)] [InlineData(TypeOfFunding.ApprenticeshipsFrom1May2017, TypeOfLearningProgramme.ApprenticeshipStandard, false)] [InlineData(TypeOfFunding.CommunityLearning, TypeOfLearningProgramme.AdvancedLevelApprenticeship, false)] [InlineData(TypeOfFunding.CommunityLearning, TypeOfLearningProgramme.ApprenticeshipStandard, false)] [InlineData(TypeOfFunding.EuropeanSocialFund, TypeOfLearningProgramme.HigherApprenticeshipLevel6, false)] [InlineData(TypeOfFunding.EuropeanSocialFund, TypeOfLearningProgramme.ApprenticeshipStandard, false)] [InlineData(TypeOfFunding.NotFundedByESFA, TypeOfLearningProgramme.HigherApprenticeshipLevel7Plus, false)] [InlineData(TypeOfFunding.NotFundedByESFA, TypeOfLearningProgramme.ApprenticeshipStandard, false)] [InlineData(TypeOfFunding.Other16To19, TypeOfLearningProgramme.Traineeship, false)] [InlineData(TypeOfFunding.Other16To19, TypeOfLearningProgramme.ApprenticeshipStandard, false)] [InlineData(TypeOfFunding.OtherAdult, TypeOfLearningProgramme.IntermediateLevelApprenticeship, false)] [InlineData(TypeOfFunding.OtherAdult, TypeOfLearningProgramme.ApprenticeshipStandard, true)] public void IsInTrainingReturnsExpectation(int forTypeOfFunding, int andProgrammeType, bool expectation) { // arrange var sut = NewRule(); var mockDelivery = new Mock<ILearningDelivery>(); mockDelivery .SetupGet(x => x.FundModel) .Returns(forTypeOfFunding); mockDelivery .SetupGet(x => x.ProgTypeNullable) .Returns(andProgrammeType); // act var result = sut.IsInTraining(mockDelivery.Object); // assert Assert.Equal(expectation, result); } /// <summary> /// Determines whether [is in a programme returns expectation] [for the specified type of aim]. /// </summary> /// <param name="forTypeOfAim">For type of aim.</param> /// <param name="expectation">if set to <c>true</c> [expectation].</param> [Theory] [InlineData(TypeOfAim.AimNotPartOfAProgramme, false)] [InlineData(TypeOfAim.ComponentAimInAProgramme, false)] [InlineData(TypeOfAim.CoreAim16To19ExcludingApprenticeships, false)] [InlineData(TypeOfAim.ProgrammeAim, true)] public void IsInAProgrammeReturnsExpectation(int forTypeOfAim, bool expectation) { // arrange var sut = NewRule(); var mockDelivery = new Mock<ILearningDelivery>(MockBehavior.Strict); mockDelivery .SetupGet(x => x.AimType) .Returns(forTypeOfAim); // act var result = sut.IsInAProgramme(mockDelivery.Object); // assert Assert.Equal(expectation, result); mockDelivery.VerifyAll(); } /// <summary> /// Invalid item raises validation message. /// </summary> /// <param name="forTypeOfFunding">For type of funding.</param> /// <param name="andProgrammeType">Type of the and programme.</param> [Theory] [InlineData(TypeOfFunding.ApprenticeshipsFrom1May2017, TypeOfLearningProgramme.AdvancedLevelApprenticeship)] [InlineData(TypeOfFunding.ApprenticeshipsFrom1May2017, TypeOfLearningProgramme.ApprenticeshipStandard)] [InlineData(TypeOfFunding.ApprenticeshipsFrom1May2017, TypeOfLearningProgramme.HigherApprenticeshipLevel4)] [InlineData(TypeOfFunding.ApprenticeshipsFrom1May2017, TypeOfLearningProgramme.HigherApprenticeshipLevel5)] [InlineData(TypeOfFunding.ApprenticeshipsFrom1May2017, TypeOfLearningProgramme.HigherApprenticeshipLevel6)] [InlineData(TypeOfFunding.ApprenticeshipsFrom1May2017, TypeOfLearningProgramme.HigherApprenticeshipLevel7Plus)] [InlineData(TypeOfFunding.ApprenticeshipsFrom1May2017, TypeOfLearningProgramme.IntermediateLevelApprenticeship)] [InlineData(TypeOfFunding.ApprenticeshipsFrom1May2017, TypeOfLearningProgramme.Traineeship)] [InlineData(TypeOfFunding.OtherAdult, TypeOfLearningProgramme.ApprenticeshipStandard)] public void InvalidItemRaisesValidationMessage(int forTypeOfFunding, int andProgrammeType) { // arrange const string LearnRefNumber = "123456789X"; var mockDelivery = new Mock<ILearningDelivery>(); mockDelivery .SetupGet(x => x.FundModel) .Returns(forTypeOfFunding); mockDelivery .SetupGet(x => x.ProgTypeNullable) .Returns(andProgrammeType); mockDelivery .SetupGet(x => x.AimType) .Returns(TypeOfAim.ProgrammeAim); mockDelivery .SetupGet(x => x.AppFinRecords) .Returns((IReadOnlyCollection<IAppFinRecord>)null); var deliveries = Collection.Empty<ILearningDelivery>(); deliveries.Add(mockDelivery.Object); var mockLearner = new Mock<ILearner>(); mockLearner .SetupGet(x => x.LearnRefNumber) .Returns(LearnRefNumber); mockLearner .SetupGet(x => x.LearningDeliveries) .Returns(deliveries.AsSafeReadOnlyList()); var mockHandler = new Mock<IValidationErrorHandler>(MockBehavior.Strict); mockHandler.Setup(x => x.Handle( Moq.It.Is<string>(y => y == AFinType_09Rule.Name), Moq.It.Is<string>(y => y == LearnRefNumber), null, Moq.It.IsAny<IEnumerable<IErrorMessageParameter>>())); mockHandler .Setup(x => x.BuildErrorMessageParameter( Moq.It.Is<string>(y => y == AFinType_09Rule.MessagePropertyName), Moq.It.Is<object>(y => y == mockDelivery.Object))) .Returns(new Mock<IErrorMessageParameter>().Object); var sut = new AFinType_09Rule(mockHandler.Object); // act sut.Validate(mockLearner.Object); // assert mockHandler.VerifyAll(); } /// <summary> /// Valid item does not raise a validation message. /// every case (bar three) is out of scope, and therefore by definition valid /// </summary> /// <param name="forTypeOfFunding">For type of funding.</param> /// <param name="andProgrammeType">Type of the and programme.</param> [Theory] [InlineData(TypeOfFunding.AdultSkills, TypeOfLearningProgramme.AdvancedLevelApprenticeship)] [InlineData(TypeOfFunding.AdultSkills, TypeOfLearningProgramme.ApprenticeshipStandard)] [InlineData(TypeOfFunding.Age16To19ExcludingApprenticeships, TypeOfLearningProgramme.HigherApprenticeshipLevel4)] [InlineData(TypeOfFunding.Age16To19ExcludingApprenticeships, TypeOfLearningProgramme.ApprenticeshipStandard)] [InlineData(TypeOfFunding.ApprenticeshipsFrom1May2017, TypeOfLearningProgramme.HigherApprenticeshipLevel5)] // in scope [InlineData(TypeOfFunding.ApprenticeshipsFrom1May2017, TypeOfLearningProgramme.ApprenticeshipStandard)] // in scope [InlineData(TypeOfFunding.CommunityLearning, TypeOfLearningProgramme.AdvancedLevelApprenticeship)] [InlineData(TypeOfFunding.CommunityLearning, TypeOfLearningProgramme.ApprenticeshipStandard)] [InlineData(TypeOfFunding.EuropeanSocialFund, TypeOfLearningProgramme.HigherApprenticeshipLevel6)] [InlineData(TypeOfFunding.EuropeanSocialFund, TypeOfLearningProgramme.ApprenticeshipStandard)] [InlineData(TypeOfFunding.NotFundedByESFA, TypeOfLearningProgramme.HigherApprenticeshipLevel7Plus)] [InlineData(TypeOfFunding.NotFundedByESFA, TypeOfLearningProgramme.ApprenticeshipStandard)] [InlineData(TypeOfFunding.Other16To19, TypeOfLearningProgramme.Traineeship)] [InlineData(TypeOfFunding.Other16To19, TypeOfLearningProgramme.ApprenticeshipStandard)] [InlineData(TypeOfFunding.OtherAdult, TypeOfLearningProgramme.IntermediateLevelApprenticeship)] [InlineData(TypeOfFunding.OtherAdult, TypeOfLearningProgramme.ApprenticeshipStandard)] // in scope public void ValidItemDoesNotRaiseAValidationMessage(int forTypeOfFunding, int andProgrammeType) { // arrange const string LearnRefNumber = "123456789X"; var appFinRecords = Collection.Empty<IAppFinRecord>(); appFinRecords.Add(new Mock<IAppFinRecord>().Object); var mockDelivery = new Mock<ILearningDelivery>(); mockDelivery .SetupGet(x => x.FundModel) .Returns(forTypeOfFunding); mockDelivery .SetupGet(x => x.ProgTypeNullable) .Returns(andProgrammeType); mockDelivery .SetupGet(x => x.AppFinRecords) .Returns(appFinRecords.AsSafeReadOnlyList()); var deliveries = Collection.Empty<ILearningDelivery>(); deliveries.Add(mockDelivery.Object); var mockLearner = new Mock<ILearner>(); mockLearner .SetupGet(x => x.LearnRefNumber) .Returns(LearnRefNumber); mockLearner .SetupGet(x => x.LearningDeliveries) .Returns(deliveries.AsSafeReadOnlyList()); var mockHandler = new Mock<IValidationErrorHandler>(MockBehavior.Strict); var sut = new AFinType_09Rule(mockHandler.Object); // act sut.Validate(mockLearner.Object); // assert mockHandler.VerifyAll(); } /// <summary> /// New rule. /// </summary> /// <returns>a constructed and mocked up validation rule</returns> public AFinType_09Rule NewRule() { var mock = new Mock<IValidationErrorHandler>(); return new AFinType_09Rule(mock.Object); } } }
42.208232
128
0.636416
[ "MIT" ]
SkillsFundingAgency/DC-ILR-1819-ValidationService
src/ESFA.DC.ILR.ValidationService.Rules.Tests/LearningDelivery/AFinType/AFinType_09RuleTests.cs
17,434
C#
using System; using System.Web; using ServiceStack.Common.Web; using ServiceStack.ServiceInterface; using Nohros.ServiceStack; namespace Nohros.Security.Auth.ServiceStack { /// <summary> /// A <see cref="Service"/> that can be used to handle authentication request /// that uses the well know "login/password" credentials. /// </summary> public abstract class AbstractAuthService : Service { readonly HttpAuthenticationManager authenticator_; protected AbstractAuthService(HttpAuthenticationManager authenticator) { authenticator_ = authenticator; } /// <summary> /// Attempts to sign the given subject in by using the given login and /// password information. /// </summary> /// <param name="subject"> /// The subject to be signed in. /// </param> /// <param name="login"> /// The login associated with the given subject. /// </param> /// <param name="password"> /// The password of the given login. /// </param> /// <exception cref="HttpError.Unauthorized"> /// The given login/password credentials are not valid. /// </exception> protected void SignIn(ISubject subject, string login, string password) { if (login == null || password == null) { OnUnauthorized(); } var token = authenticator_.Authenticate(subject, new LoginPasswordCallbackHandler(login, password)); if (!token.Authenticated) { OnUnauthorized(); } } /// <summary> /// Sign the current signed in subject out. /// </summary> /// <remarks> /// If there is no subject signed in this method performs no operation. /// </remarks> public void SignOut() { authenticator_.SignOut(HttpContext.Current); } /// <summary> /// Method that is called when the authentication process fail. /// </summary> protected virtual void OnUnauthorized() { Response.AddHeader(HttpHeaders.WwwAuthenticate, "Auth br.com.nohros"); throw HttpError.Unauthorized(Resources.Request_Unauthorized); } /// <summary> /// Gets a value indicating if the current request is associated with /// an authenticated subject. /// </summary> public bool IsAuthenticated { get { ISubject subject; return authenticator_.GetSubject(HttpContext.Current, out subject); } } } }
30.8375
80
0.629915
[ "MIT" ]
nohros/must
src/platform/toolkit/servicestack/auth/services/auth/AbstractAuthService.cs
2,469
C#
using System; public class Program { public static void Main(string[] args) { } }
11.875
42
0.621053
[ "MIT" ]
bobo4aces/06.SoftUni-DataStructuresOpenCourse
02. Linear Data Structures - Stacks And Queues/Exercises/StacksAndQueues/03. Array Stack/Program.cs
97
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace g3 { /// <summary> /// Sweep a 2D Profile Polygon along a 3D Path. /// Supports closed and open paths, and capping open paths. /// However caps are triangulated using a fan around a center vertex (which you /// can set using CapCenter). If Polygon is non-convex, this will have foldovers. /// In that case, you have to triangulate and append it yourself. /// /// If your profile curve does not contain the polygon bbox center, /// set OverrideCapCenter=true and set CapCenter to a suitable center point. /// /// The output normals are currently set to those for a circular profile. /// Call MeshNormals.QuickCompute() on the output DMesh to estimate proper /// vertex normals /// /// </summary> public class TubeGenerator : MeshGenerator { public List<Vector3d> Vertices; public Polygon2d Polygon; public bool Capped = true; // center of endcap triangle fan, relative to Polygon public bool OverrideCapCenter = false; public Vector2d CapCenter = Vector2d.Zero; public bool ClosedLoop = false; // [TODO] Frame3d ?? public Frame3f Frame = Frame3f.Identity; // set to true if you are going to texture this or want sharp edges public bool NoSharedVertices = true; public int startCapCenterIndex = -1; public int endCapCenterIndex = -1; public TubeGenerator() { } public TubeGenerator(Polygon2d tubePath, Frame3f pathPlane, Polygon2d tubeShape, int nPlaneNormal = 2) { Vertices = new List<Vector3d>(); foreach (Vector2d v in tubePath.Vertices) Vertices.Add(pathPlane.FromPlaneUV((Vector2f)v, nPlaneNormal)); Polygon = new Polygon2d(tubeShape); ClosedLoop = true; Capped = false; } public TubeGenerator(PolyLine2d tubePath, Frame3f pathPlane, Polygon2d tubeShape, int nPlaneNormal = 2) { Vertices = new List<Vector3d>(); foreach (Vector2d v in tubePath.Vertices) Vertices.Add(pathPlane.FromPlaneUV((Vector2f)v, nPlaneNormal)); Polygon = new Polygon2d(tubeShape); ClosedLoop = false; Capped = true; } public TubeGenerator(DCurve3 tubePath, Polygon2d tubeShape) { Vertices = new List<Vector3d>(tubePath.Vertices); Polygon = new Polygon2d(tubeShape); ClosedLoop = tubePath.Closed; Capped = ! ClosedLoop; } override public MeshGenerator Generate() { if (Polygon == null) Polygon = Polygon2d.MakeCircle(1.0f, 8); int NV = Vertices.Count; int Slices = Polygon.VertexCount; int nRings = (ClosedLoop && NoSharedVertices) ? NV + 1 : NV; int nRingSize = (NoSharedVertices) ? Slices + 1 : Slices; int nCapVertices = (NoSharedVertices) ? Slices + 1 : 1; if (Capped == false || ClosedLoop == true) nCapVertices = 0; vertices = new VectorArray3d(nRings * nRingSize + 2 * nCapVertices); uv = new VectorArray2f(vertices.Count); normals = new VectorArray3f(vertices.Count); int quad_strips = (ClosedLoop) ? NV : NV-1; int nSpanTris = quad_strips * (2 * Slices); int nCapTris = (Capped && ClosedLoop == false) ? 2 * Slices : 0; triangles = new IndexArray3i(nSpanTris + nCapTris); Frame3f fCur = new Frame3f(Frame); Vector3d dv = CurveUtils.GetTangent(Vertices, 0, ClosedLoop); fCur.Origin = (Vector3f)Vertices[0]; fCur.AlignAxis(2, (Vector3f)dv); Frame3f fStart = new Frame3f(fCur); double circumference = Polygon.ArcLength; double pathLength = CurveUtils.ArcLength(Vertices, ClosedLoop); double accum_path_u = 0; // generate tube for (int ri = 0; ri < nRings; ++ri) { int vi = ri % NV; // propagate frame Vector3d tangent = CurveUtils.GetTangent(Vertices, vi, ClosedLoop); fCur.Origin = (Vector3f)Vertices[vi]; fCur.AlignAxis(2, (Vector3f)tangent); // generate vertices int nStartR = ri * nRingSize; double accum_ring_v = 0; for (int j = 0; j < nRingSize; ++j) { int k = nStartR + j; Vector2d pv = Polygon.Vertices[j % Slices]; Vector2d pvNext = Polygon.Vertices[(j + 1) % Slices]; Vector3d v = fCur.FromPlaneUV((Vector2f)pv, 2); vertices[k] = v; uv[k] = new Vector2f(accum_path_u, accum_ring_v); accum_ring_v += (pv.Distance(pvNext) / circumference); Vector3f n = (Vector3f)(v - fCur.Origin).Normalized; normals[k] = n; } int viNext = (ri + 1) % NV; double d = Vertices[vi].Distance(Vertices[viNext]); accum_path_u += d / pathLength; } // generate triangles int ti = 0; int nStop = (ClosedLoop && NoSharedVertices == false) ? nRings : (nRings - 1); for (int ri = 0; ri < nStop; ++ri) { int r0 = ri * nRingSize; int r1 = r0 + nRingSize; if (ClosedLoop && ri == nStop - 1 && NoSharedVertices == false) r1 = 0; for (int k = 0; k < nRingSize - 1; ++k) { triangles.Set(ti++, r0 + k, r0 + k + 1, r1 + k + 1, Clockwise); triangles.Set(ti++, r0 + k, r1 + k + 1, r1 + k, Clockwise); } if (NoSharedVertices == false) { // last quad if we aren't sharing vertices int M = nRingSize-1; triangles.Set(ti++, r0 + M, r0, r1, Clockwise); triangles.Set(ti++, r0 + M, r1, r1 + M, Clockwise); } } if (Capped && ClosedLoop == false) { Vector2d c = (OverrideCapCenter) ? CapCenter : Polygon.Bounds.Center; // add endcap verts int nBottomC = nRings * nRingSize; vertices[nBottomC] = fStart.FromPlaneUV((Vector2f)c,2); uv[nBottomC] = new Vector2f(0.5f, 0.5f); normals[nBottomC] = -fStart.Z; startCapCenterIndex = nBottomC; int nTopC = nBottomC + 1; vertices[nTopC] = fCur.FromPlaneUV((Vector2f)c, 2); uv[nTopC] = new Vector2f(0.5f, 0.5f); normals[nTopC] = fCur.Z; endCapCenterIndex = nTopC; if (NoSharedVertices) { // duplicate first loop and make a fan w/ bottom-center int nExistingB = 0; int nStartB = nTopC + 1; for (int k = 0; k < Slices; ++k) { vertices[nStartB + k] = vertices[nExistingB + k]; Vector2d vuv = ((Polygon[k] - c).Normalized + Vector2d.One) * 0.5; uv[nStartB + k] = (Vector2f)vuv; normals[nStartB + k] = normals[nBottomC]; } append_disc(Slices, nBottomC, nStartB, true, Clockwise, ref ti); // duplicate second loop and make fan int nExistingT = nRingSize * (nRings - 1); int nStartT = nStartB + Slices; for (int k = 0; k < Slices; ++k) { vertices[nStartT + k] = vertices[nExistingT + k]; uv[nStartT + k] = uv[nStartB + k]; normals[nStartT + k] = normals[nTopC]; } append_disc(Slices, nTopC, nStartT, true, !Clockwise, ref ti); } else { append_disc(Slices, nBottomC, 0, true, Clockwise, ref ti); append_disc(Slices, nTopC, nRingSize * (nRings-1), true, !Clockwise, ref ti); } } return this; } } }
40.576923
111
0.523578
[ "MIT" ]
JiokKae/Portal-imitation
Assets/geometry3Sharp-master/mesh_generators/GenCylGenerators.cs
8,442
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Sistema_de_Vendas.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.580645
151
0.583955
[ "MIT" ]
Emanuel-Marques/meus_projectos_em_csharp
Sistema_de_Vendas/Properties/Settings.Designer.cs
1,074
C#
// Created by Ronis Vision. All rights reserved // 22.09.2020. using System; using System.Linq; using System.Reflection; using RVModules.RVSmartAI.Content.AI.DataProviders; using RVModules.RVSmartAI.Editor.SelectWindows; using RVModules.RVUtilities.Editor; using RVModules.RVUtilities.Reflection; using UnityEditor; using UnityEngine; using Object = UnityEngine.Object; namespace RVModules.RVSmartAI.Editor.CustomInspectors { [CustomPropertyDrawer(typeof(DataProviderBase), true)] public class DataProviderPropertyDrawer : PropertyDrawer { #region Public methods public override float GetPropertyHeight(SerializedProperty property, GUIContent label) => 1; public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { var obj = property.serializedObject.targetObject; var field = obj.GetType().GetField(property.name, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public); EditorHelpers.WrapInBox(() => { var provider = field.GetValue(obj) as Object; var desc = (provider as DataProviderBase)?.Description; EditorGUILayout.BeginHorizontal(); var tooltipAttribute = field.GetCustomAttribute<TooltipAttribute>(); label.tooltip = tooltipAttribute != null ? tooltipAttribute.tooltip : ""; GUILayout.Label(label); var buttonText = $"{ObjectNames.NicifyVariableName(field.GetValue(obj)?.GetType().Name).Replace("Provider", "")}"; if (field.GetValue(obj) as Object == null) buttonText = "Add data provider"; if (GUILayout.Button(buttonText)) AssignNewProvider(field, obj); if (provider != null) { if (field.GetCustomAttributes(typeof(OptionalDataProvider)).Any() && GUILayout.Button("X")) { DataProviderBase.DestroyReferencedDataProviders(provider as Component); Object.DestroyImmediate(provider); field.SetValue(provider, null); } EditorGUILayout.EndHorizontal(); if (!string.IsNullOrEmpty(desc)) EditorGUILayout.HelpBox(desc, MessageType.Info); GUIHelpers.GUIDrawFields(provider); } else { if (field.GetCustomAttributes(typeof(OptionalDataProvider)).Any() == false) { CreateDefaultDataProviderIfExist(obj, field); } EditorGUILayout.EndHorizontal(); } }); // EditorGUI.EndProperty(); } #endregion #region Not public methods private static void AssignNewProvider(FieldInfo field, Object obj) => DataProviderWindow(obj, field, () => { var old = field.GetValue(obj) as MonoBehaviour; if (obj != null) { DataProviderBase.DestroyReferencedDataProviders(old); Object.DestroyImmediate(old); } }); private static void CreateDefaultDataProviderIfExist(Object obj, FieldInfo field) { var assignableDataProviders = ReflectionHelper.GetDerivedTypes(typeof(DataProviderBase)) .Where(_type => field.FieldType.IsAssignableFrom(_type)).ToArray(); Type firsType = null; Type defaultType = null; foreach (var assignableDataProvider in assignableDataProviders) { if (assignableDataProvider.Name.ToUpper().Contains("default".ToUpper())) { defaultType = assignableDataProvider; break; } if (firsType == null) firsType = assignableDataProvider; } if (defaultType != null) { CreateDataProvider(obj, field, null, defaultType); return; } if (firsType != null) CreateDataProvider(obj, field, null, firsType); } private static void DataProviderWindow(Object obj, FieldInfo field, Action onCreate) { var w = ScriptableObject.CreateInstance<DataProvidersWindow>(); w.types = w.types.Where(_type => field.FieldType.IsAssignableFrom(_type)).ToArray(); try { w.titleContent = new GUIContent($"Select data provider of type {w.types[0].BaseType.BaseType.GetGenericArguments()[0].Name}"); } catch (Exception e) { w.titleContent = new GUIContent("Select data provider"); } w.onSelectedItem = _type => { CreateDataProvider(obj, field, onCreate, _type); }; } private static void CreateDataProvider(Object obj, FieldInfo field, Action onCreate, Type _type) { Undo.RecordObject(obj, "inspector"); onCreate?.Invoke(); var newProvider = Undo.AddComponent((obj as Component).gameObject, _type); Undo.RecordObject(obj, "inspector"); field.SetValue(obj, newProvider); } #endregion } }
38.126761
142
0.579239
[ "MIT" ]
Telvy/ScumSmackerArena_Repo
Assets/RVModules/RVSmartAI/Editor/CustomInspectors/DataProviderPropertyDrawer.cs
5,414
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; using System.Runtime.Serialization; using System.Text; using System.Xml; namespace DocumentFormat.OpenXml.Validation.Schema.Restrictions { /// <summary> /// Holds all simple type constraints in array. /// </summary> [DataContract] [KnownType(typeof(AnyUriRestriction))] [KnownType(typeof(Base64BinaryRestriction))] [KnownType(typeof(BooleanValueRestriction))] [KnownType(typeof(ByteValueRestriction))] [KnownType(typeof(DateTimeValueRestriction))] [KnownType(typeof(DateValueRestriction))] [KnownType(typeof(DecimalValueRestriction))] [KnownType(typeof(DoubleValueRestriction))] [KnownType(typeof(EnumValueRestriction))] [KnownType(typeof(IdStringRestriction))] [KnownType(typeof(Int16ValueRestriction))] [KnownType(typeof(Int32ValueRestriction))] [KnownType(typeof(Int64ValueRestriction))] [KnownType(typeof(IntegerValueRestriction))] [KnownType(typeof(HexBinaryRestriction))] [KnownType(typeof(LanguageRestriction))] [KnownType(typeof(ListValueRestriction))] [KnownType(typeof(NcNameRestriction))] [KnownType(typeof(NonNegativeIntegerValueRestriction))] [KnownType(typeof(PositiveIntegerValueRestriction))] [KnownType(typeof(QnameRestriction))] [KnownType(typeof(RedirectedRestriction))] [KnownType(typeof(SByteValueRestriction))] [KnownType(typeof(SingleValueRestriction))] [KnownType(typeof(StringRestriction))] [KnownType(typeof(SimpleTypeRestrictions))] [KnownType(typeof(TokenRestriction))] [KnownType(typeof(UInt16ValueRestriction))] [KnownType(typeof(UInt32ValueRestriction))] [KnownType(typeof(UInt64ValueRestriction))] [KnownType(typeof(UnionValueRestriction))] internal class SimpleTypeRestrictions { [DataMember] public int SimpleTypeCount { get; set; } [DataMember] public SimpleTypeRestriction[] SimpleTypes { get; set; } private static DataContractSerializer GetSerializer() { #if FEATURE_DCS_SETTINGS var settings = new DataContractSerializerSettings { PreserveObjectReferences = true, }; return new DataContractSerializer(typeof(SimpleTypeRestrictions), settings); #else return new DataContractSerializer( typeof(SimpleTypeRestrictions), null, int.MaxValue, false, true, null); #endif } internal void Serialize(Stream stream) { var settings = new XmlWriterSettings { Indent = true }; using (var writer = new StreamWriter(stream, Encoding.UTF8)) using (var xml = XmlWriter.Create(writer, settings)) { GetSerializer().WriteObject(xml, this); } } /// <summary> /// Deserialize the binary data into memory object. /// </summary> /// <param name="stream">The data stream.</param> /// <param name="fileFormat">The target file format version.</param> /// <returns></returns> internal static SimpleTypeRestrictions Deserialize(Stream stream, FileFormatVersions fileFormat) { using (var reader = new StreamReader(stream, Encoding.UTF8, false)) using (var xml = XmlReader.Create(reader)) { var simpleTypeRestrictions = (SimpleTypeRestrictions)GetSerializer().ReadObject(xml); foreach (var simpleType in simpleTypeRestrictions.SimpleTypes) { simpleType.FileFormat = fileFormat; } return simpleTypeRestrictions; } } /// <summary> /// Indexer to retriver a specified data in the SimpleTypes. /// </summary> /// <param name="index">The index of the data in the SimpleTypes array.</param> /// <returns>The simple type constraint data.</returns> public SimpleTypeRestriction this[int index] => SimpleTypes[index]; } }
36.338983
104
0.649021
[ "MIT" ]
coderIML/Open-XML-SDK.net
src/DocumentFormat.OpenXml/Validation/Schema/Restrictions/SimpleTypeRestrictions.cs
4,290
C#
using System.Collections.Generic; using System.Linq; using Microsoft.Office.Interop.Excel; using NavfertyExcelAddIn.Commons; namespace NavfertyExcelAddIn.WorksheetCellsEditing { public class CellsUnmerger : ICellsUnmerger { public void Unmerge(Range range) { range.OfType<Range>() .Select(x => x.MergeArea) .Where(x => x.Count != 1) .Distinct(new MergeAreaEqualityComparer()) .ForEach(UnmergeArea); } private void UnmergeArea(Range currentRange) { var formula = currentRange.Cells.OfType<Range>().First().Formula; currentRange.UnMerge(); currentRange.Formula = formula; } private class MergeAreaEqualityComparer : IEqualityComparer<Range> { public bool Equals(Range x, Range y) { return y != null && x != null && x.Row == y.Row && x.Column == y.Column; } public int GetHashCode(Range obj) { return obj.Row * 9973 + obj.Column; } } } }
20.282609
68
0.676313
[ "MIT" ]
navferty/NavfertyExcelAddIn
NavfertyExcelAddIn/WorksheetCellsEditing/CellsUnmerger.cs
935
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; using Unity.WebRTC; using Unity.WebRTC.Samples; using UnityEngine.UI; using Button = UnityEngine.UI.Button; class TrickleIceSample : MonoBehaviour { #pragma warning disable 0649 [SerializeField] private Button addServerButton; [SerializeField] private Button removeServerButton; [SerializeField] private Button resetToDefaultButton; [SerializeField] private Button gatherCandidatesButton; [SerializeField] private InputField urlInputField; [SerializeField] private InputField usernameInputField; [SerializeField] private InputField passwordInputField; [SerializeField] private GameObject optionElement; [SerializeField] private Transform optionParent; [SerializeField] private GameObject candidateElement; [SerializeField] private Transform candidateParent; [SerializeField] private ToggleGroup iceTransportOption; [SerializeField] private Slider candidatePoolSizeSlider; #pragma warning restore 0649 private RTCPeerConnection _pc1; private RTCRtpTransceiver _transceiver; private float beginTime = 0f; private Dictionary<GameObject, RTCIceServer> iceServers = new Dictionary<GameObject, RTCIceServer>(); private GameObject selectedOption = null; private void Awake() { WebRTC.Initialize(WebRTCSettings.EncoderType, WebRTCSettings.LimitTextureSize); addServerButton.onClick.AddListener(OnAddServer); removeServerButton.onClick.AddListener(OnRemoveServer); resetToDefaultButton.onClick.AddListener(OnResetToDefault); gatherCandidatesButton.onClick.AddListener(OnGatherCandidate); } private void OnDestroy() { WebRTC.Dispose(); } private void Start() { OnResetToDefault(); } void OnAddServer() { string url = urlInputField.text; string username = usernameInputField.text; string password = passwordInputField.text; string scheme = url.Split(':')[0]; if (scheme != "stun" && scheme != "turn" && scheme != "turns") { Debug.LogError( $"URI scheme `{scheme}` is not valid parameter. \n" + $"ex. `stun:192.168.11.1`, `turn:192.168.11.2:3478?transport=udp`"); return; } AddServer(url, username, password); } void AddServer(string url, string username = null, string password = null) { // Store the ICE server as a stringified JSON object in option.value. GameObject option = Instantiate(optionElement, optionParent); Text optionText = option.GetComponentInChildren<Text>(); Button optionButton = option.GetComponentInChildren<Button>(); RTCIceServer iceServer = new RTCIceServer { urls = new[] { url }, username = usernameInputField.text, credential = passwordInputField.text }; optionText.text = url; if (!string.IsNullOrEmpty(username) || !string.IsNullOrEmpty(password)) { optionText.text += $"[{username}:{password}]"; } optionButton.onClick.AddListener(() => OnSelectServer(option)); iceServers.Add(option, iceServer); urlInputField.text = string.Empty; usernameInputField.text = string.Empty; passwordInputField.text = string.Empty; } void OnRemoveServer() { if (selectedOption == null) return; iceServers.Remove(selectedOption); Destroy(selectedOption); selectedOption = null; } void OnResetToDefault() { const string url = "stun:stun.l.google.com:19302"; foreach (Transform child in optionParent) { Destroy(child.gameObject); } iceServers.Clear(); AddServer(url); } void OnSelectServer(GameObject option) { selectedOption = option; } private RTCConfiguration GetSelectedSdpSemantics() { List<Toggle> toggles = iceTransportOption.ActiveToggles().ToList(); int index = toggles.FindIndex(toggle => toggle.isOn); RTCIceTransportPolicy policy = 0 == index ? RTCIceTransportPolicy.All: RTCIceTransportPolicy.Relay; RTCConfiguration config = default; config.iceServers = iceServers.Values.ToArray(); config.iceTransportPolicy = policy; config.iceCandidatePoolSize = (int)candidatePoolSizeSlider.value; return config; } IEnumerator CreateOffer(RTCPeerConnection pc) { var op = pc.CreateOffer(); yield return op; if (!op.IsError) { if (pc.SignalingState != RTCSignalingState.Stable) { Debug.LogError($"signaling state is not stable."); yield break; } beginTime = Time.realtimeSinceStartup; yield return StartCoroutine(OnCreateOfferSuccess(pc, op.Desc)); } else { OnCreateSessionDescriptionError(op.Error); } } private void OnGatherCandidate() { foreach (Transform child in candidateParent) { Destroy(child.gameObject); } gatherCandidatesButton.interactable = false; var configuration = GetSelectedSdpSemantics(); _pc1 = new RTCPeerConnection(ref configuration); _pc1.OnIceCandidate = OnIceCandidate; _pc1.OnIceGatheringStateChange = OnIceGatheringStateChange; _transceiver = _pc1.AddTransceiver(TrackKind.Video); StartCoroutine(CreateOffer(_pc1)); } private void OnIceCandidate(RTCIceCandidate candidate) { GameObject newCandidate = Instantiate(candidateElement, candidateParent); Text[] texts = newCandidate.GetComponentsInChildren<Text>(); foreach (Text text in texts) { switch (text.name) { case "Time": text.text = (Time.realtimeSinceStartup - beginTime).ToString("F"); break; case "Component": text.text = candidate.Component.Value.ToString(); break; case "Type": text.text = candidate.Type.Value.ToString(); break; case "Foundation": text.text = candidate.Foundation; break; case "Protocol": text.text = candidate.Protocol.Value.ToString(); break; case "Address": text.text = candidate.Address; break; case "Port": text.text = candidate.Port.ToString(); break; case "Priority": text.text = FormatPriority(candidate.Priority); break; } } } private void OnIceGatheringStateChange(RTCIceGatheringState state) { if (state != RTCIceGatheringState.Complete) { return; } string elapsed = (Time.realtimeSinceStartup - beginTime).ToString("F"); GameObject newCandidate = Instantiate(candidateElement, candidateParent); Text[] texts = newCandidate.GetComponentsInChildren<Text>(); foreach (Text text in texts) { switch (text.name) { case "Time": text.text = (Time.realtimeSinceStartup - beginTime).ToString("F"); break; case "Priority": text.text = "Done"; break; default: text.text = string.Empty; break; } } _transceiver.Dispose(); _pc1.Close(); _pc1 = null; gatherCandidatesButton.interactable = true; } private IEnumerator OnCreateOfferSuccess(RTCPeerConnection pc, RTCSessionDescription desc) { Debug.Log("setLocalDescription start"); var op = pc.SetLocalDescription(ref desc); yield return op; if (!op.IsError) { OnSetLocalSuccess(pc); } else { var error = op.Error; OnSetSessionDescriptionError(ref error); } } private void OnSetLocalSuccess(RTCPeerConnection pc) { Debug.Log("SetLocalDescription complete"); } static void OnSetSessionDescriptionError(ref RTCError error) { Debug.LogError($"Error Detail Type: {error.message}"); } static string FormatPriority(uint priority) { return $"{priority >> 24} | {(priority >> 8) & 0xFFFF} | {priority & 0xFF}"; } private static void OnCreateSessionDescriptionError(RTCError error) { Debug.LogError($"Error Detail Type: {error.message}"); } }
31.138408
107
0.604178
[ "Apache-2.0" ]
AndrewMeadows/com.unity.webrtc
Samples~/TrickleIce/TrickleIceSample.cs
8,999
C#
namespace Azure.ResourceManager.DnsResolver { public partial class DnsForwardingRulesetCollection : Azure.ResourceManager.ArmCollection, System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource>, System.Collections.Generic.IEnumerable<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource>, System.Collections.IEnumerable { protected DnsForwardingRulesetCollection() { } public virtual Azure.ResourceManager.ArmOperation<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource> CreateOrUpdate(Azure.WaitUntil waitUntil, string dnsForwardingRulesetName, Azure.ResourceManager.DnsResolver.DnsForwardingRulesetData data, string ifMatch = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource>> CreateOrUpdateAsync(Azure.WaitUntil waitUntil, string dnsForwardingRulesetName, Azure.ResourceManager.DnsResolver.DnsForwardingRulesetData data, string ifMatch = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<bool> Exists(string dnsForwardingRulesetName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(string dnsForwardingRulesetName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource> Get(string dnsForwardingRulesetName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource> GetAll(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource> GetAllAsync(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource>> GetAsync(string dnsForwardingRulesetName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } System.Collections.Generic.IAsyncEnumerator<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource> System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource>.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) { throw null; } System.Collections.Generic.IEnumerator<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource> System.Collections.Generic.IEnumerable<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class DnsForwardingRulesetData : Azure.ResourceManager.Models.TrackedResourceData { public DnsForwardingRulesetData(Azure.Core.AzureLocation location) : base (default(Azure.Core.AzureLocation)) { } public System.Collections.Generic.IList<Azure.ResourceManager.Resources.Models.WritableSubResource> DnsResolverOutboundEndpoints { get { throw null; } } public string Etag { get { throw null; } } public Azure.ResourceManager.DnsResolver.Models.ProvisioningState? ProvisioningState { get { throw null; } } public string ResourceGuid { get { throw null; } } } public partial class DnsForwardingRulesetResource : Azure.ResourceManager.ArmResource { public static readonly Azure.Core.ResourceType ResourceType; protected DnsForwardingRulesetResource() { } public virtual Azure.ResourceManager.DnsResolver.DnsForwardingRulesetData Data { get { throw null; } } public virtual bool HasData { get { throw null; } } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource> AddTag(string key, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource>> AddTagAsync(string key, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string dnsForwardingRulesetName) { throw null; } public virtual Azure.ResourceManager.ArmOperation Delete(Azure.WaitUntil waitUntil, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation> DeleteAsync(Azure.WaitUntil waitUntil, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource>> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.ForwardingRuleResource> GetForwardingRule(string forwardingRuleName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.ForwardingRuleResource>> GetForwardingRuleAsync(string forwardingRuleName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.DnsResolver.ForwardingRuleCollection GetForwardingRules() { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource> GetVirtualNetworkLink(string virtualNetworkLinkName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource>> GetVirtualNetworkLinkAsync(string virtualNetworkLinkName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.DnsResolver.VirtualNetworkLinkCollection GetVirtualNetworkLinks() { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource> RemoveTag(string key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource>> RemoveTagAsync(string key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource> SetTags(System.Collections.Generic.IDictionary<string, string> tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource>> SetTagsAsync(System.Collections.Generic.IDictionary<string, string> tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class DnsResolverCollection : Azure.ResourceManager.ArmCollection, System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.DnsResolver.DnsResolverResource>, System.Collections.Generic.IEnumerable<Azure.ResourceManager.DnsResolver.DnsResolverResource>, System.Collections.IEnumerable { protected DnsResolverCollection() { } public virtual Azure.ResourceManager.ArmOperation<Azure.ResourceManager.DnsResolver.DnsResolverResource> CreateOrUpdate(Azure.WaitUntil waitUntil, string dnsResolverName, Azure.ResourceManager.DnsResolver.DnsResolverData data, string ifMatch = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation<Azure.ResourceManager.DnsResolver.DnsResolverResource>> CreateOrUpdateAsync(Azure.WaitUntil waitUntil, string dnsResolverName, Azure.ResourceManager.DnsResolver.DnsResolverData data, string ifMatch = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<bool> Exists(string dnsResolverName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(string dnsResolverName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.DnsResolverResource> Get(string dnsResolverName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.DnsResolver.DnsResolverResource> GetAll(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.DnsResolver.DnsResolverResource> GetAllAsync(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.DnsResolverResource>> GetAsync(string dnsResolverName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } System.Collections.Generic.IAsyncEnumerator<Azure.ResourceManager.DnsResolver.DnsResolverResource> System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.DnsResolver.DnsResolverResource>.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) { throw null; } System.Collections.Generic.IEnumerator<Azure.ResourceManager.DnsResolver.DnsResolverResource> System.Collections.Generic.IEnumerable<Azure.ResourceManager.DnsResolver.DnsResolverResource>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class DnsResolverData : Azure.ResourceManager.Models.TrackedResourceData { public DnsResolverData(Azure.Core.AzureLocation location) : base (default(Azure.Core.AzureLocation)) { } public Azure.ResourceManager.DnsResolver.Models.DnsResolverState? DnsResolverState { get { throw null; } } public string Etag { get { throw null; } } public Azure.ResourceManager.DnsResolver.Models.ProvisioningState? ProvisioningState { get { throw null; } } public string ResourceGuid { get { throw null; } } public Azure.Core.ResourceIdentifier VirtualNetworkId { get { throw null; } set { } } } public static partial class DnsResolverExtensions { public static Azure.Response<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource> GetDnsForwardingRuleset(this Azure.ResourceManager.Resources.ResourceGroupResource resourceGroupResource, string dnsForwardingRulesetName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource>> GetDnsForwardingRulesetAsync(this Azure.ResourceManager.Resources.ResourceGroupResource resourceGroupResource, string dnsForwardingRulesetName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource GetDnsForwardingRulesetResource(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } public static Azure.ResourceManager.DnsResolver.DnsForwardingRulesetCollection GetDnsForwardingRulesets(this Azure.ResourceManager.Resources.ResourceGroupResource resourceGroupResource) { throw null; } public static Azure.Pageable<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource> GetDnsForwardingRulesets(this Azure.ResourceManager.Resources.SubscriptionResource subscriptionResource, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.AsyncPageable<Azure.ResourceManager.DnsResolver.DnsForwardingRulesetResource> GetDnsForwardingRulesetsAsync(this Azure.ResourceManager.Resources.SubscriptionResource subscriptionResource, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.Pageable<Azure.ResourceManager.DnsResolver.Models.VirtualNetworkDnsForwardingRuleset> GetDnsForwardingRulesetsByVirtualNetwork(this Azure.ResourceManager.Resources.ResourceGroupResource resourceGroupResource, string virtualNetworkName, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.AsyncPageable<Azure.ResourceManager.DnsResolver.Models.VirtualNetworkDnsForwardingRuleset> GetDnsForwardingRulesetsByVirtualNetworkAsync(this Azure.ResourceManager.Resources.ResourceGroupResource resourceGroupResource, string virtualNetworkName, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.Response<Azure.ResourceManager.DnsResolver.DnsResolverResource> GetDnsResolver(this Azure.ResourceManager.Resources.ResourceGroupResource resourceGroupResource, string dnsResolverName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.DnsResolverResource>> GetDnsResolverAsync(this Azure.ResourceManager.Resources.ResourceGroupResource resourceGroupResource, string dnsResolverName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.ResourceManager.DnsResolver.DnsResolverResource GetDnsResolverResource(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } public static Azure.ResourceManager.DnsResolver.DnsResolverCollection GetDnsResolvers(this Azure.ResourceManager.Resources.ResourceGroupResource resourceGroupResource) { throw null; } public static Azure.Pageable<Azure.ResourceManager.DnsResolver.DnsResolverResource> GetDnsResolvers(this Azure.ResourceManager.Resources.SubscriptionResource subscriptionResource, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.AsyncPageable<Azure.ResourceManager.DnsResolver.DnsResolverResource> GetDnsResolversAsync(this Azure.ResourceManager.Resources.SubscriptionResource subscriptionResource, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.Pageable<Azure.ResourceManager.Resources.Models.WritableSubResource> GetDnsResolversByVirtualNetwork(this Azure.ResourceManager.Resources.ResourceGroupResource resourceGroupResource, string virtualNetworkName, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.AsyncPageable<Azure.ResourceManager.Resources.Models.WritableSubResource> GetDnsResolversByVirtualNetworkAsync(this Azure.ResourceManager.Resources.ResourceGroupResource resourceGroupResource, string virtualNetworkName, int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.ResourceManager.DnsResolver.ForwardingRuleResource GetForwardingRuleResource(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } public static Azure.ResourceManager.DnsResolver.InboundEndpointResource GetInboundEndpointResource(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } public static Azure.ResourceManager.DnsResolver.OutboundEndpointResource GetOutboundEndpointResource(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } public static Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource GetVirtualNetworkLinkResource(this Azure.ResourceManager.ArmClient client, Azure.Core.ResourceIdentifier id) { throw null; } } public partial class DnsResolverResource : Azure.ResourceManager.ArmResource { public static readonly Azure.Core.ResourceType ResourceType; protected DnsResolverResource() { } public virtual Azure.ResourceManager.DnsResolver.DnsResolverData Data { get { throw null; } } public virtual bool HasData { get { throw null; } } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.DnsResolverResource> AddTag(string key, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.DnsResolverResource>> AddTagAsync(string key, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string dnsResolverName) { throw null; } public virtual Azure.ResourceManager.ArmOperation Delete(Azure.WaitUntil waitUntil, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation> DeleteAsync(Azure.WaitUntil waitUntil, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.DnsResolverResource> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.DnsResolverResource>> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.InboundEndpointResource> GetInboundEndpoint(string inboundEndpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.InboundEndpointResource>> GetInboundEndpointAsync(string inboundEndpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.DnsResolver.InboundEndpointCollection GetInboundEndpoints() { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.OutboundEndpointResource> GetOutboundEndpoint(string outboundEndpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.OutboundEndpointResource>> GetOutboundEndpointAsync(string outboundEndpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.DnsResolver.OutboundEndpointCollection GetOutboundEndpoints() { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.DnsResolverResource> RemoveTag(string key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.DnsResolverResource>> RemoveTagAsync(string key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.DnsResolverResource> SetTags(System.Collections.Generic.IDictionary<string, string> tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.DnsResolverResource>> SetTagsAsync(System.Collections.Generic.IDictionary<string, string> tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class ForwardingRuleCollection : Azure.ResourceManager.ArmCollection, System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.DnsResolver.ForwardingRuleResource>, System.Collections.Generic.IEnumerable<Azure.ResourceManager.DnsResolver.ForwardingRuleResource>, System.Collections.IEnumerable { protected ForwardingRuleCollection() { } public virtual Azure.ResourceManager.ArmOperation<Azure.ResourceManager.DnsResolver.ForwardingRuleResource> CreateOrUpdate(Azure.WaitUntil waitUntil, string forwardingRuleName, Azure.ResourceManager.DnsResolver.ForwardingRuleData data, string ifMatch = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation<Azure.ResourceManager.DnsResolver.ForwardingRuleResource>> CreateOrUpdateAsync(Azure.WaitUntil waitUntil, string forwardingRuleName, Azure.ResourceManager.DnsResolver.ForwardingRuleData data, string ifMatch = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<bool> Exists(string forwardingRuleName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(string forwardingRuleName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.ForwardingRuleResource> Get(string forwardingRuleName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.DnsResolver.ForwardingRuleResource> GetAll(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.DnsResolver.ForwardingRuleResource> GetAllAsync(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.ForwardingRuleResource>> GetAsync(string forwardingRuleName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } System.Collections.Generic.IAsyncEnumerator<Azure.ResourceManager.DnsResolver.ForwardingRuleResource> System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.DnsResolver.ForwardingRuleResource>.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) { throw null; } System.Collections.Generic.IEnumerator<Azure.ResourceManager.DnsResolver.ForwardingRuleResource> System.Collections.Generic.IEnumerable<Azure.ResourceManager.DnsResolver.ForwardingRuleResource>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class ForwardingRuleData : Azure.ResourceManager.Models.ResourceData { public ForwardingRuleData() { } public string DomainName { get { throw null; } set { } } public string Etag { get { throw null; } } public Azure.ResourceManager.DnsResolver.Models.ForwardingRuleState? ForwardingRuleState { get { throw null; } set { } } public System.Collections.Generic.IDictionary<string, string> Metadata { get { throw null; } } public Azure.ResourceManager.DnsResolver.Models.ProvisioningState? ProvisioningState { get { throw null; } } public System.Collections.Generic.IList<Azure.ResourceManager.DnsResolver.Models.TargetDnsServer> TargetDnsServers { get { throw null; } } } public partial class ForwardingRuleResource : Azure.ResourceManager.ArmResource { public static readonly Azure.Core.ResourceType ResourceType; protected ForwardingRuleResource() { } public virtual Azure.ResourceManager.DnsResolver.ForwardingRuleData Data { get { throw null; } } public virtual bool HasData { get { throw null; } } public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string dnsForwardingRulesetName, string forwardingRuleName) { throw null; } public virtual Azure.ResourceManager.ArmOperation Delete(Azure.WaitUntil waitUntil, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation> DeleteAsync(Azure.WaitUntil waitUntil, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.ForwardingRuleResource> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.ForwardingRuleResource>> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.ForwardingRuleResource> Update(Azure.ResourceManager.DnsResolver.Models.PatchableForwardingRuleData data, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.ForwardingRuleResource>> UpdateAsync(Azure.ResourceManager.DnsResolver.Models.PatchableForwardingRuleData data, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class InboundEndpointCollection : Azure.ResourceManager.ArmCollection, System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.DnsResolver.InboundEndpointResource>, System.Collections.Generic.IEnumerable<Azure.ResourceManager.DnsResolver.InboundEndpointResource>, System.Collections.IEnumerable { protected InboundEndpointCollection() { } public virtual Azure.ResourceManager.ArmOperation<Azure.ResourceManager.DnsResolver.InboundEndpointResource> CreateOrUpdate(Azure.WaitUntil waitUntil, string inboundEndpointName, Azure.ResourceManager.DnsResolver.InboundEndpointData data, string ifMatch = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation<Azure.ResourceManager.DnsResolver.InboundEndpointResource>> CreateOrUpdateAsync(Azure.WaitUntil waitUntil, string inboundEndpointName, Azure.ResourceManager.DnsResolver.InboundEndpointData data, string ifMatch = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<bool> Exists(string inboundEndpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(string inboundEndpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.InboundEndpointResource> Get(string inboundEndpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.DnsResolver.InboundEndpointResource> GetAll(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.DnsResolver.InboundEndpointResource> GetAllAsync(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.InboundEndpointResource>> GetAsync(string inboundEndpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } System.Collections.Generic.IAsyncEnumerator<Azure.ResourceManager.DnsResolver.InboundEndpointResource> System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.DnsResolver.InboundEndpointResource>.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) { throw null; } System.Collections.Generic.IEnumerator<Azure.ResourceManager.DnsResolver.InboundEndpointResource> System.Collections.Generic.IEnumerable<Azure.ResourceManager.DnsResolver.InboundEndpointResource>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class InboundEndpointData : Azure.ResourceManager.Models.TrackedResourceData { public InboundEndpointData(Azure.Core.AzureLocation location) : base (default(Azure.Core.AzureLocation)) { } public string Etag { get { throw null; } } public System.Collections.Generic.IList<Azure.ResourceManager.DnsResolver.Models.IPConfiguration> IPConfigurations { get { throw null; } } public Azure.ResourceManager.DnsResolver.Models.ProvisioningState? ProvisioningState { get { throw null; } } public string ResourceGuid { get { throw null; } } } public partial class InboundEndpointResource : Azure.ResourceManager.ArmResource { public static readonly Azure.Core.ResourceType ResourceType; protected InboundEndpointResource() { } public virtual Azure.ResourceManager.DnsResolver.InboundEndpointData Data { get { throw null; } } public virtual bool HasData { get { throw null; } } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.InboundEndpointResource> AddTag(string key, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.InboundEndpointResource>> AddTagAsync(string key, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string dnsResolverName, string inboundEndpointName) { throw null; } public virtual Azure.ResourceManager.ArmOperation Delete(Azure.WaitUntil waitUntil, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation> DeleteAsync(Azure.WaitUntil waitUntil, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.InboundEndpointResource> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.InboundEndpointResource>> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.InboundEndpointResource> RemoveTag(string key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.InboundEndpointResource>> RemoveTagAsync(string key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.InboundEndpointResource> SetTags(System.Collections.Generic.IDictionary<string, string> tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.InboundEndpointResource>> SetTagsAsync(System.Collections.Generic.IDictionary<string, string> tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class OutboundEndpointCollection : Azure.ResourceManager.ArmCollection, System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.DnsResolver.OutboundEndpointResource>, System.Collections.Generic.IEnumerable<Azure.ResourceManager.DnsResolver.OutboundEndpointResource>, System.Collections.IEnumerable { protected OutboundEndpointCollection() { } public virtual Azure.ResourceManager.ArmOperation<Azure.ResourceManager.DnsResolver.OutboundEndpointResource> CreateOrUpdate(Azure.WaitUntil waitUntil, string outboundEndpointName, Azure.ResourceManager.DnsResolver.OutboundEndpointData data, string ifMatch = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation<Azure.ResourceManager.DnsResolver.OutboundEndpointResource>> CreateOrUpdateAsync(Azure.WaitUntil waitUntil, string outboundEndpointName, Azure.ResourceManager.DnsResolver.OutboundEndpointData data, string ifMatch = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<bool> Exists(string outboundEndpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(string outboundEndpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.OutboundEndpointResource> Get(string outboundEndpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.DnsResolver.OutboundEndpointResource> GetAll(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.DnsResolver.OutboundEndpointResource> GetAllAsync(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.OutboundEndpointResource>> GetAsync(string outboundEndpointName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } System.Collections.Generic.IAsyncEnumerator<Azure.ResourceManager.DnsResolver.OutboundEndpointResource> System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.DnsResolver.OutboundEndpointResource>.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) { throw null; } System.Collections.Generic.IEnumerator<Azure.ResourceManager.DnsResolver.OutboundEndpointResource> System.Collections.Generic.IEnumerable<Azure.ResourceManager.DnsResolver.OutboundEndpointResource>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class OutboundEndpointData : Azure.ResourceManager.Models.TrackedResourceData { public OutboundEndpointData(Azure.Core.AzureLocation location) : base (default(Azure.Core.AzureLocation)) { } public string Etag { get { throw null; } } public Azure.ResourceManager.DnsResolver.Models.ProvisioningState? ProvisioningState { get { throw null; } } public string ResourceGuid { get { throw null; } } public Azure.Core.ResourceIdentifier SubnetId { get { throw null; } set { } } } public partial class OutboundEndpointResource : Azure.ResourceManager.ArmResource { public static readonly Azure.Core.ResourceType ResourceType; protected OutboundEndpointResource() { } public virtual Azure.ResourceManager.DnsResolver.OutboundEndpointData Data { get { throw null; } } public virtual bool HasData { get { throw null; } } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.OutboundEndpointResource> AddTag(string key, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.OutboundEndpointResource>> AddTagAsync(string key, string value, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string dnsResolverName, string outboundEndpointName) { throw null; } public virtual Azure.ResourceManager.ArmOperation Delete(Azure.WaitUntil waitUntil, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation> DeleteAsync(Azure.WaitUntil waitUntil, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.OutboundEndpointResource> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.OutboundEndpointResource>> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.OutboundEndpointResource> RemoveTag(string key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.OutboundEndpointResource>> RemoveTagAsync(string key, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.OutboundEndpointResource> SetTags(System.Collections.Generic.IDictionary<string, string> tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.OutboundEndpointResource>> SetTagsAsync(System.Collections.Generic.IDictionary<string, string> tags, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class VirtualNetworkLinkCollection : Azure.ResourceManager.ArmCollection, System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource>, System.Collections.Generic.IEnumerable<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource>, System.Collections.IEnumerable { protected VirtualNetworkLinkCollection() { } public virtual Azure.ResourceManager.ArmOperation<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource> CreateOrUpdate(Azure.WaitUntil waitUntil, string virtualNetworkLinkName, Azure.ResourceManager.DnsResolver.VirtualNetworkLinkData data, string ifMatch = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource>> CreateOrUpdateAsync(Azure.WaitUntil waitUntil, string virtualNetworkLinkName, Azure.ResourceManager.DnsResolver.VirtualNetworkLinkData data, string ifMatch = null, string ifNoneMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<bool> Exists(string virtualNetworkLinkName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(string virtualNetworkLinkName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource> Get(string virtualNetworkLinkName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Pageable<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource> GetAll(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource> GetAllAsync(int? top = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource>> GetAsync(string virtualNetworkLinkName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } System.Collections.Generic.IAsyncEnumerator<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource> System.Collections.Generic.IAsyncEnumerable<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource>.GetAsyncEnumerator(System.Threading.CancellationToken cancellationToken) { throw null; } System.Collections.Generic.IEnumerator<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource> System.Collections.Generic.IEnumerable<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource>.GetEnumerator() { throw null; } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { throw null; } } public partial class VirtualNetworkLinkData : Azure.ResourceManager.Models.ResourceData { public VirtualNetworkLinkData() { } public string Etag { get { throw null; } } public System.Collections.Generic.IDictionary<string, string> Metadata { get { throw null; } } public Azure.ResourceManager.DnsResolver.Models.ProvisioningState? ProvisioningState { get { throw null; } } public Azure.Core.ResourceIdentifier VirtualNetworkId { get { throw null; } set { } } } public partial class VirtualNetworkLinkResource : Azure.ResourceManager.ArmResource { public static readonly Azure.Core.ResourceType ResourceType; protected VirtualNetworkLinkResource() { } public virtual Azure.ResourceManager.DnsResolver.VirtualNetworkLinkData Data { get { throw null; } } public virtual bool HasData { get { throw null; } } public static Azure.Core.ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string dnsForwardingRulesetName, string virtualNetworkLinkName) { throw null; } public virtual Azure.ResourceManager.ArmOperation Delete(Azure.WaitUntil waitUntil, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation> DeleteAsync(Azure.WaitUntil waitUntil, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource> Get(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource>> GetAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.ResourceManager.ArmOperation<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource> Update(Azure.WaitUntil waitUntil, Azure.ResourceManager.DnsResolver.Models.PatchableVirtualNetworkLinkData data, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.ResourceManager.ArmOperation<Azure.ResourceManager.DnsResolver.VirtualNetworkLinkResource>> UpdateAsync(Azure.WaitUntil waitUntil, Azure.ResourceManager.DnsResolver.Models.PatchableVirtualNetworkLinkData data, string ifMatch = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } } namespace Azure.ResourceManager.DnsResolver.Models { [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct DnsResolverState : System.IEquatable<Azure.ResourceManager.DnsResolver.Models.DnsResolverState> { private readonly object _dummy; private readonly int _dummyPrimitive; public DnsResolverState(string value) { throw null; } public static Azure.ResourceManager.DnsResolver.Models.DnsResolverState Connected { get { throw null; } } public static Azure.ResourceManager.DnsResolver.Models.DnsResolverState Disconnected { get { throw null; } } public bool Equals(Azure.ResourceManager.DnsResolver.Models.DnsResolverState other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.DnsResolver.Models.DnsResolverState left, Azure.ResourceManager.DnsResolver.Models.DnsResolverState right) { throw null; } public static implicit operator Azure.ResourceManager.DnsResolver.Models.DnsResolverState (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.DnsResolver.Models.DnsResolverState left, Azure.ResourceManager.DnsResolver.Models.DnsResolverState right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct ForwardingRuleState : System.IEquatable<Azure.ResourceManager.DnsResolver.Models.ForwardingRuleState> { private readonly object _dummy; private readonly int _dummyPrimitive; public ForwardingRuleState(string value) { throw null; } public static Azure.ResourceManager.DnsResolver.Models.ForwardingRuleState Disabled { get { throw null; } } public static Azure.ResourceManager.DnsResolver.Models.ForwardingRuleState Enabled { get { throw null; } } public bool Equals(Azure.ResourceManager.DnsResolver.Models.ForwardingRuleState other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.DnsResolver.Models.ForwardingRuleState left, Azure.ResourceManager.DnsResolver.Models.ForwardingRuleState right) { throw null; } public static implicit operator Azure.ResourceManager.DnsResolver.Models.ForwardingRuleState (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.DnsResolver.Models.ForwardingRuleState left, Azure.ResourceManager.DnsResolver.Models.ForwardingRuleState right) { throw null; } public override string ToString() { throw null; } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct IPAllocationMethod : System.IEquatable<Azure.ResourceManager.DnsResolver.Models.IPAllocationMethod> { private readonly object _dummy; private readonly int _dummyPrimitive; public IPAllocationMethod(string value) { throw null; } public static Azure.ResourceManager.DnsResolver.Models.IPAllocationMethod Dynamic { get { throw null; } } public static Azure.ResourceManager.DnsResolver.Models.IPAllocationMethod Static { get { throw null; } } public bool Equals(Azure.ResourceManager.DnsResolver.Models.IPAllocationMethod other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.DnsResolver.Models.IPAllocationMethod left, Azure.ResourceManager.DnsResolver.Models.IPAllocationMethod right) { throw null; } public static implicit operator Azure.ResourceManager.DnsResolver.Models.IPAllocationMethod (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.DnsResolver.Models.IPAllocationMethod left, Azure.ResourceManager.DnsResolver.Models.IPAllocationMethod right) { throw null; } public override string ToString() { throw null; } } public partial class IPConfiguration { public IPConfiguration() { } public string PrivateIPAddress { get { throw null; } set { } } public Azure.ResourceManager.DnsResolver.Models.IPAllocationMethod? PrivateIPAllocationMethod { get { throw null; } set { } } public Azure.Core.ResourceIdentifier SubnetId { get { throw null; } set { } } } public partial class PatchableForwardingRuleData { public PatchableForwardingRuleData() { } public Azure.ResourceManager.DnsResolver.Models.ForwardingRuleState? ForwardingRuleState { get { throw null; } set { } } public System.Collections.Generic.IDictionary<string, string> Metadata { get { throw null; } } public System.Collections.Generic.IList<Azure.ResourceManager.DnsResolver.Models.TargetDnsServer> TargetDnsServers { get { throw null; } } } public partial class PatchableVirtualNetworkLinkData { public PatchableVirtualNetworkLinkData() { } public System.Collections.Generic.IDictionary<string, string> Metadata { get { throw null; } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct ProvisioningState : System.IEquatable<Azure.ResourceManager.DnsResolver.Models.ProvisioningState> { private readonly object _dummy; private readonly int _dummyPrimitive; public ProvisioningState(string value) { throw null; } public static Azure.ResourceManager.DnsResolver.Models.ProvisioningState Canceled { get { throw null; } } public static Azure.ResourceManager.DnsResolver.Models.ProvisioningState Creating { get { throw null; } } public static Azure.ResourceManager.DnsResolver.Models.ProvisioningState Deleting { get { throw null; } } public static Azure.ResourceManager.DnsResolver.Models.ProvisioningState Failed { get { throw null; } } public static Azure.ResourceManager.DnsResolver.Models.ProvisioningState Succeeded { get { throw null; } } public static Azure.ResourceManager.DnsResolver.Models.ProvisioningState Updating { get { throw null; } } public bool Equals(Azure.ResourceManager.DnsResolver.Models.ProvisioningState other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.ResourceManager.DnsResolver.Models.ProvisioningState left, Azure.ResourceManager.DnsResolver.Models.ProvisioningState right) { throw null; } public static implicit operator Azure.ResourceManager.DnsResolver.Models.ProvisioningState (string value) { throw null; } public static bool operator !=(Azure.ResourceManager.DnsResolver.Models.ProvisioningState left, Azure.ResourceManager.DnsResolver.Models.ProvisioningState right) { throw null; } public override string ToString() { throw null; } } public partial class TargetDnsServer { public TargetDnsServer() { } public string IPAddress { get { throw null; } set { } } public int? Port { get { throw null; } set { } } } public partial class VirtualNetworkDnsForwardingRuleset { internal VirtualNetworkDnsForwardingRuleset() { } public string Id { get { throw null; } } public Azure.Core.ResourceIdentifier VirtualNetworkLinkId { get { throw null; } set { } } } }
150.071795
461
0.811629
[ "MIT" ]
alexbuckgit/azure-sdk-for-net
sdk/dnsresolver/Azure.ResourceManager.DnsResolver/api/Azure.ResourceManager.DnsResolver.netstandard2.0.cs
58,528
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.R_kvstore.Model.V20150101; namespace Aliyun.Acs.R_kvstore.Transform.V20150101 { public class DescribeIntranetAttributeResponseUnmarshaller { public static DescribeIntranetAttributeResponse Unmarshall(UnmarshallerContext _ctx) { DescribeIntranetAttributeResponse describeIntranetAttributeResponse = new DescribeIntranetAttributeResponse(); describeIntranetAttributeResponse.HttpResponse = _ctx.HttpResponse; describeIntranetAttributeResponse.RequestId = _ctx.StringValue("DescribeIntranetAttribute.RequestId"); describeIntranetAttributeResponse.IntranetBandwidth = _ctx.IntegerValue("DescribeIntranetAttribute.IntranetBandwidth"); describeIntranetAttributeResponse.ExpireTime = _ctx.StringValue("DescribeIntranetAttribute.ExpireTime"); describeIntranetAttributeResponse.BandwidthExpireTime = _ctx.StringValue("DescribeIntranetAttribute.BandwidthExpireTime"); return describeIntranetAttributeResponse; } } }
43.953488
125
0.791005
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-r-kvstore/R_kvstore/Transform/V20150101/DescribeIntranetAttributeResponseUnmarshaller.cs
1,890
C#
using Kickstart.Pass2.CModel.Code; namespace Kickstart.Interface { public interface ICProjectFileVisitor { void Visit(IVisitor visitor, CFile file); } }
19.333333
49
0.712644
[ "MIT" ]
videa-tv/kickstart
src/Kickstart/Kickstart.Core/Interface/ICProjectFileVisitor.cs
176
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("Pets")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Pets")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("4cc7f4bd-d058-4429-8ee7-54bb88b63b96")] // 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")]
37.324324
84
0.742216
[ "MIT" ]
pavlinpetkov88/ProgramingBasic
ProgrammingBasicsExam/Pets/Properties/AssemblyInfo.cs
1,384
C#
using UnityEngine; using System.Collections; public class Brittle : MonoBehaviour { public float partsMass = 1f; public void Break() { GameObject.FindGameObjectWithTag ("GameController").GetComponent<PointsTracker> ().buildingsBroken++; foreach (Transform child in transform) { if (child.GetComponent<MeshRenderer>() == null) continue; //child.gameObject.AddComponent<Rigidbody>().mass = partsMass; //child.gameObject.GetComponent<Rigidbody>().drag = 0; //child.gameObject.AddComponent<Heavy>(); child.gameObject.AddComponent<SplitMeshIntoPolygons>().Break(); } gameObject.transform.DetachChildren(); Destroy (gameObject); } }
31.428571
104
0.743939
[ "MIT" ]
timujin/stoned-golem
Assets/Brittle.cs
662
C#
/* * Copyright (c) 2014 All Rights Reserved by the SDL Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Management.Automation; using Trisoft.ISHRemote.Objects; using Trisoft.ISHRemote.Objects.Public; using Trisoft.ISHRemote.Exceptions; using System.Collections.Generic; using System.Xml; using Trisoft.ISHRemote.HelperClasses; namespace Trisoft.ISHRemote.Cmdlets.EDT { public abstract class EDTCmdlet : TrisoftCmdlet { public Enumerations.ISHType[] ISHType { get { return new Enumerations.ISHType[] { Enumerations.ISHType.ISHEDT }; } } } }
31.305556
86
0.741792
[ "Apache-2.0" ]
jlaridon/ISHRemote
Source/ISHRemote/Trisoft.ISHRemote/Cmdlets/EDT/EDTCmdlet.cs
1,127
C#
using System; using System.ComponentModel; namespace Pidgin { public abstract partial class Parser<TToken, T> { /// <summary> /// Returns a parser which runs the current parser and applies a selector function. /// The selector function receives a <see cref="ReadOnlySpan{TToken}"/> as its first argument, and the result of the current parser as its second argument. /// The <see cref="ReadOnlySpan{TToken}"/> represents the sequence of input tokens which were consumed by the parser. /// /// This allows you to write "pattern"-style parsers which match a sequence of tokens and return a view of the part of the input stream which they matched. /// </summary> /// <param name="selector"> /// A selector function which computes a result of type <typeparamref name="U"/>. /// The arguments of the selector function are a <see cref="ReadOnlySpan{TToken}"/> containing the sequence of input tokens which were consumed by this parser, /// and the result of this parser. /// </param> /// <typeparam name="U">The result type</typeparam> /// <returns>A parser which runs the current parser and applies a selector function.</returns> public Parser<TToken, U> MapWithInput<U>(ReadOnlySpanFunc<TToken, T, U> selector) { if (selector == null) { throw new ArgumentNullException(nameof(selector)); } return new MapWithInputParser<U>(this, selector); } private class MapWithInputParser<U> : Parser<TToken, U> { private Parser<TToken, T> _parser; private ReadOnlySpanFunc<TToken, T, U> _selector; public MapWithInputParser(Parser<TToken, T> parser, ReadOnlySpanFunc<TToken, T, U> selector) { _parser = parser; _selector = selector; } internal override InternalResult<U> Parse(ref ParseState<TToken> state) { var start = state.Location; state.PushBookmark(); // don't discard input buffer var result = _parser.Parse(ref state); if (!result.Success) { state.PopBookmark(); return InternalResult.Failure<U>(result.ConsumedInput); } var delta = state.Location - start; var val = _selector(state.LookBehind(delta), result.Value); state.PopBookmark(); return InternalResult.Success<U>(val, result.ConsumedInput); } } } }
40.515152
167
0.591997
[ "MIT" ]
beho/Pidgin
Pidgin/Parser.MapWithInput.cs
2,674
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Autodesk.Revit.DB; using Autodesk.Revit.UI; using Autodesk.Revit.DB.ExtensibleStorage; using System.Reflection; namespace ExtensibleStorageManager { /// <summary> /// An enum to select which sample schema to create. /// </summary> public enum SampleSchemaComplexity { SimpleExample =1, ComplexExample = 2 } /// <summary> /// A static class that issues sample commands to a SchemaWrapper to demonstrate /// schema and data storage. /// </summary> /// public static class StorageCommand { #region Create new sample schemas and write data to them /// <summary> /// Creates a new sample Schema, creates an instance of that Schema (an Entity) in the given element, /// sets data on that element's entity, and exports the schema to a given XML file. /// </summary> /// <returns>A new SchemaWrapper</returns> public static SchemaWrapperTools.SchemaWrapper CreateSetAndExport(Element storageElement, string xmlPathOut, Guid schemaId, AccessLevel readAccess, AccessLevel writeAccess, string vendorId, string applicationId, string name, string documentation, SampleSchemaComplexity schemaComplexity) { #region Start a new transaction, and create a new Schema if (Schema.Lookup(schemaId) != null) { throw new Exception("A Schema with this Guid already exists in this document -- another one cannot be created."); } Transaction storageWrite = new Transaction(storageElement.Document, "storageWrite"); storageWrite.Start(); //Create a new schema. SchemaWrapperTools.SchemaWrapper mySchemaWrapper = SchemaWrapperTools.SchemaWrapper.NewSchema(schemaId, readAccess, writeAccess, vendorId, applicationId, name, documentation); mySchemaWrapper.SetXmlPath(xmlPathOut); #endregion Entity storageElementEntityWrite = null; //Create some sample schema fields. There are two sample schemas hard coded here, "simple" and "complex." switch (schemaComplexity) { case SampleSchemaComplexity.SimpleExample: SimpleSchemaAndData(mySchemaWrapper, out storageElementEntityWrite); break; case SampleSchemaComplexity.ComplexExample: ComplexSchemaAndData(mySchemaWrapper, storageElement, xmlPathOut, schemaId, readAccess, writeAccess, vendorId, applicationId, name, documentation, out storageElementEntityWrite); break; } #region Store the main entity in an element, save the Serializeable SchemaWrapper to xml, and finish the transaction storageElement.SetEntity(storageElementEntityWrite); TransactionStatus storageResult = storageWrite.Commit(); if (storageResult != TransactionStatus.Committed) { throw new Exception("Error storing Schema. Transaction status: " + storageResult.ToString()); } else { mySchemaWrapper.ToXml(xmlPathOut); return mySchemaWrapper; } #endregion } #region Helper methods for CreateSetAndExport /// <summary> /// Adds several small, simple fields to a SchemaWrapper and Entity /// </summary> private static void SimpleSchemaAndData(SchemaWrapperTools.SchemaWrapper mySchemaWrapper, out Entity storageElementEntityWrite) { //Create some sample fields. mySchemaWrapper.AddField<int>(int0Name, UnitType.UT_Undefined, null); mySchemaWrapper.AddField<short>(short0Name, UnitType.UT_Undefined, null); mySchemaWrapper.AddField<double>(double0Name, UnitType.UT_Length, null); mySchemaWrapper.AddField<float>(float0Name, UnitType.UT_Length, null); mySchemaWrapper.AddField<bool>(bool0Name, UnitType.UT_Undefined, null); mySchemaWrapper.AddField<string>(string0Name, UnitType.UT_Undefined, null); //Generate the Autodesk.Revit.DB.ExtensibleStorage.Schema. mySchemaWrapper.FinishSchema(); //Get the fields Field fieldInt0 = mySchemaWrapper.GetSchema().GetField(int0Name); Field fieldShort0 = mySchemaWrapper.GetSchema().GetField(short0Name); Field fieldDouble0 = mySchemaWrapper.GetSchema().GetField(double0Name); Field fieldFloat0 = mySchemaWrapper.GetSchema().GetField(float0Name); Field fieldBool0 = mySchemaWrapper.GetSchema().GetField(bool0Name); Field fieldString0 = mySchemaWrapper.GetSchema().GetField(string0Name); storageElementEntityWrite = null; //Create a new entity of the given Schema storageElementEntityWrite = new Entity(mySchemaWrapper.GetSchema()); //Set data in the entity. storageElementEntityWrite.Set<int>(fieldInt0, 5); storageElementEntityWrite.Set<short>(fieldShort0, 2); storageElementEntityWrite.Set<double>(fieldDouble0, 7.1, DisplayUnitType.DUT_METERS); storageElementEntityWrite.Set<float>(fieldFloat0, 3.1f, DisplayUnitType.DUT_METERS); storageElementEntityWrite.Set(fieldBool0, false); storageElementEntityWrite.Set(fieldString0, "hello"); } /// <summary> /// Adds a simple fields, arrays, maps, subEntities, and arrays and maps of subEntities to a SchemaWrapper and Entity /// </summary> private static void ComplexSchemaAndData(SchemaWrapperTools.SchemaWrapper mySchemaWrapper, Element storageElement, string xmlPathOut, Guid schemaId, AccessLevel readAccess, AccessLevel writeAccess, string vendorId, string applicationId, string name, string documentation, out Entity storageElementEntityWrite) { #region Add Fields to the SchemaWrapper mySchemaWrapper.AddField<int>(int0Name, UnitType.UT_Undefined, null); mySchemaWrapper.AddField<short>(short0Name, UnitType.UT_Undefined, null); mySchemaWrapper.AddField<double>(double0Name, UnitType.UT_Length, null); mySchemaWrapper.AddField<float>(float0Name, UnitType.UT_Length, null); mySchemaWrapper.AddField<bool>(bool0Name, UnitType.UT_Undefined, null); mySchemaWrapper.AddField<string>(string0Name, UnitType.UT_Undefined, null); mySchemaWrapper.AddField<ElementId>(id0Name, UnitType.UT_Undefined, null); mySchemaWrapper.AddField<XYZ>(point0Name, UnitType.UT_Length, null); mySchemaWrapper.AddField<UV>(uv0Name, UnitType.UT_Length, null); mySchemaWrapper.AddField<Guid>(guid0Name, UnitType.UT_Undefined, null); //Note that we use IDictionary<> for map types and IList<> for array types mySchemaWrapper.AddField<IDictionary<string, string>>(map0Name, UnitType.UT_Undefined, null); mySchemaWrapper.AddField<IList<bool>>(array0Name, UnitType.UT_Undefined, null); //Create a sample subEntity SchemaWrapperTools.SchemaWrapper mySubSchemaWrapper0 = SchemaWrapperTools.SchemaWrapper.NewSchema(subEntityGuid0, readAccess, writeAccess, vendorId, applicationId, entity0Name, "A sub entity"); mySubSchemaWrapper0.AddField<int>("subInt0", UnitType.UT_Undefined, null); mySubSchemaWrapper0.FinishSchema(); Entity subEnt0 = new Entity(mySubSchemaWrapper0.GetSchema()); subEnt0.Set<int>(mySubSchemaWrapper0.GetSchema().GetField("subInt0"), 11); mySchemaWrapper.AddField<Entity>(entity0Name, UnitType.UT_Undefined, mySubSchemaWrapper0); // //Create a sample map of subEntities (An IDictionary<> with key type "int" and value type "Entity") // //Create a new sample schema. SchemaWrapperTools.SchemaWrapper mySubSchemaWrapper1_Map = SchemaWrapperTools.SchemaWrapper.NewSchema(subEntityGuid_Map1, readAccess, writeAccess, vendorId, applicationId, map1Name, "A map of int to Entity"); mySubSchemaWrapper1_Map.AddField<int>("subInt1", UnitType.UT_Undefined, null); mySubSchemaWrapper1_Map.FinishSchema(); //Create a new sample Entity. Entity subEnt1 = new Entity(mySubSchemaWrapper1_Map.GetSchema()); //Set data in that entity. subEnt1.Set<int>(mySubSchemaWrapper1_Map.GetSchema().GetField("subInt1"), 22); //Add a new map field to the top-level Schema. We will add the entity we just created after all top-level //fields are created. mySchemaWrapper.AddField<IDictionary<int, Entity>>(map1Name, UnitType.UT_Undefined, mySubSchemaWrapper1_Map); // //Create a sample array of subentities (An IList<> of type "Entity") // //Create a new sample schema SchemaWrapperTools.SchemaWrapper mySubSchemaWrapper2_Array = SchemaWrapperTools.SchemaWrapper.NewSchema(subEntityGuid_Array2, readAccess, writeAccess, vendorId, applicationId, array1Name, "An array of Entities"); mySubSchemaWrapper2_Array.AddField<int>("subInt2", UnitType.UT_Undefined, null); mySubSchemaWrapper2_Array.FinishSchema(); //Create a new sample Entity. Entity subEnt2 = new Entity(mySubSchemaWrapper2_Array.GetSchema()); //Set the data in that Entity. subEnt2.Set<int>(mySubSchemaWrapper2_Array.GetSchema().GetField("subInt2"), 33); //Add a new array field to the top-level Schema We will add the entity we just crated after all top-level fields //are created. mySchemaWrapper.AddField<IList<Entity>>(array1Name, UnitType.UT_Undefined, mySubSchemaWrapper2_Array); #endregion #region Populate the Schema in the SchemaWrapper with data mySchemaWrapper.FinishSchema(); #endregion #region Create a new entity to store an instance of schema data storageElementEntityWrite = null; storageElementEntityWrite = new Entity(mySchemaWrapper.GetSchema()); #endregion #region Get fields and set data in them Field fieldInt0 = mySchemaWrapper.GetSchema().GetField(int0Name); Field fieldShort0 = mySchemaWrapper.GetSchema().GetField(short0Name); Field fieldDouble0 = mySchemaWrapper.GetSchema().GetField(double0Name); Field fieldFloat0 = mySchemaWrapper.GetSchema().GetField(float0Name); Field fieldBool0 = mySchemaWrapper.GetSchema().GetField(bool0Name); Field fieldString0 = mySchemaWrapper.GetSchema().GetField(string0Name); Field fieldId0 = mySchemaWrapper.GetSchema().GetField(id0Name); Field fieldPoint0 = mySchemaWrapper.GetSchema().GetField(point0Name); Field fieldUv0 = mySchemaWrapper.GetSchema().GetField(uv0Name); Field fieldGuid0 = mySchemaWrapper.GetSchema().GetField(guid0Name); Field fieldMap0 = mySchemaWrapper.GetSchema().GetField(map0Name); Field fieldArray0 = mySchemaWrapper.GetSchema().GetField(array0Name); Field fieldEntity0 = mySchemaWrapper.GetSchema().GetField(entity0Name); Field fieldMap1 = mySchemaWrapper.GetSchema().GetField(map1Name); Field fieldArray1 = mySchemaWrapper.GetSchema().GetField(array1Name); storageElementEntityWrite.Set<int>(fieldInt0, 5); storageElementEntityWrite.Set<short>(fieldShort0, 2); storageElementEntityWrite.Set<double>(fieldDouble0, 7.1, DisplayUnitType.DUT_METERS); storageElementEntityWrite.Set<float>(fieldFloat0, 3.1f, DisplayUnitType.DUT_METERS); storageElementEntityWrite.Set(fieldBool0, false); storageElementEntityWrite.Set(fieldString0, "hello"); storageElementEntityWrite.Set(fieldId0, storageElement.Id); storageElementEntityWrite.Set(fieldPoint0, new XYZ(1, 2, 3), DisplayUnitType.DUT_METERS); storageElementEntityWrite.Set(fieldUv0, new UV(1, 2), DisplayUnitType.DUT_METERS); storageElementEntityWrite.Set(fieldGuid0, new Guid("D8301329-F207-43B8-8AA1-634FD344F350")); //Note that we must pass an IDictionary<>, not a Dictionary<> to Set(). IDictionary<string, string> myMap0 = new Dictionary<string, string>(); myMap0.Add("mykeystr", "myvalstr"); storageElementEntityWrite.Set(fieldMap0, myMap0); //Note that we must pass an IList<>, not a List<> to Set(). IList<bool> myBoolArrayList0 = new List<bool>(); myBoolArrayList0.Add(true); myBoolArrayList0.Add(false); storageElementEntityWrite.Set(fieldArray0, myBoolArrayList0); storageElementEntityWrite.Set(fieldEntity0, subEnt0); //Create a map of Entities IDictionary<int, Entity> myMap1 = new Dictionary<int, Entity>(); myMap1.Add(5, subEnt1); //Set the map of Entities. storageElementEntityWrite.Set(fieldMap1, myMap1); //Create a list of entities IList<Entity> myEntArrayList1 = new List<Entity>(); myEntArrayList1.Add(subEnt2); myEntArrayList1.Add(subEnt2); //Set the list of entities. storageElementEntityWrite.Set(fieldArray1, myEntArrayList1); #endregion } #endregion #endregion #region Create and query SchemaWrappers from existing schemas or XML /// <summary> /// Given an Autodesk.Revit.DB.ExtensibleStorage.Schema that already exists, /// create a SchemaWrapper containing that Schema's data. /// </summary> /// <param name="schemaId">The Guid of the existing Schema</param> public static void CreateWrapperFromSchema(Guid schemaId, out SchemaWrapperTools.SchemaWrapper schemaWrapper) { Schema toLookup = Schema.Lookup(schemaId); if (toLookup == null) { throw new Exception("Schema not found in current document."); } else { schemaWrapper = SchemaWrapperTools.SchemaWrapper.FromSchema(toLookup); } } /// <summary> /// Create a SchemaWrapper from a Schema Guid and try to find an Entity of a matching Guid /// in a given Element. If successfull, try to change the data in that Entity. /// </summary> /// <param name="storageElement"></param> /// <param name="schemaId"></param> /// <param name="schemaWrapper"></param> public static void EditExistingData(Element storageElement, Guid schemaId, out SchemaWrapperTools.SchemaWrapper schemaWrapper) { //Try to find the schema in the active document. Schema schemaLookup = Schema.Lookup(schemaId); if (schemaLookup == null) { throw new Exception("Schema not found in current document."); } //Create a SchemaWrapper. schemaWrapper = SchemaWrapperTools.SchemaWrapper.FromSchema(schemaLookup); //Try to get an Entity of the given Schema Entity storageElementEntityWrite = storageElement.GetEntity(schemaLookup); if (storageElementEntityWrite.SchemaGUID != schemaId) { throw new Exception("SchemaID of found entity does not match the SchemaID passed to GetEntity."); } if (storageElementEntityWrite == null) { throw new Exception("Entity of given Schema not found."); } //Get the fields of the schema Field fieldInt0 = schemaWrapper.GetSchema().GetField(int0Name); Field fieldShort0 = schemaWrapper.GetSchema().GetField(short0Name); Field fieldDouble0 = schemaWrapper.GetSchema().GetField(double0Name); Field fieldFloat0 = schemaWrapper.GetSchema().GetField(float0Name); Field fieldBool0 = schemaWrapper.GetSchema().GetField(bool0Name); Field fieldString0 = schemaWrapper.GetSchema().GetField(string0Name); //Edit the fields. Transaction tStore = new Transaction(storageElement.Document, "tStore"); tStore.Start(); storageElementEntityWrite = null; storageElementEntityWrite = new Entity(schemaWrapper.GetSchema()); storageElementEntityWrite.Set<int>(fieldInt0, 10); storageElementEntityWrite.Set<short>(fieldShort0, 20); storageElementEntityWrite.Set<double>(fieldDouble0, 14.2, DisplayUnitType.DUT_METERS); storageElementEntityWrite.Set<float>(fieldFloat0, 6.12f, DisplayUnitType.DUT_METERS); storageElementEntityWrite.Set(fieldBool0, true); storageElementEntityWrite.Set(fieldString0, "goodbye"); //Set the entity back into the storage element. storageElement.SetEntity(storageElementEntityWrite); tStore.Commit(); } /// <summary> /// Given an element, try to find an entity containing instance data from a given Schema Guid. /// </summary> /// <param name="storageElement">The element to query</param> /// <param name="schemaId">The id of the Schema to query</param> public static void LookupAndExtractData(Element storageElement, Guid schemaId, out SchemaWrapperTools.SchemaWrapper schemaWrapper) { Schema schemaLookup = Schema.Lookup(schemaId); if (schemaLookup == null) { throw new Exception("Schema not found in current document."); } schemaWrapper = SchemaWrapperTools.SchemaWrapper.FromSchema(schemaLookup); Entity storageElementEntityRead = storageElement.GetEntity(schemaLookup); if (storageElementEntityRead.SchemaGUID != schemaId) { throw new Exception("SchemaID of found entity does not match the SchemaID passed to GetEntity."); } if (storageElementEntityRead == null) { throw new Exception("Entity of given Schema not found."); } } /// <summary> /// Given an xml path containing serialized schema data, create a new Schema and SchemaWrapper /// </summary> public static void ImportSchemaFromXml(string path, out SchemaWrapperTools.SchemaWrapper sWrapper) { sWrapper = SchemaWrapperTools.SchemaWrapper.FromXml(path); sWrapper.SetXmlPath(path); } #endregion #region Helper methods /// <summary> /// Create a new pseudorandom Guid /// </summary> /// <returns></returns> public static Guid NewGuid() { byte[] guidBytes = new byte[16]; Random randomGuidBytes = new Random(s_counter); randomGuidBytes.NextBytes(guidBytes); s_counter++; return new Guid(guidBytes); } #endregion #region Data //A counter field used to assist in creating pseudorandom Guids private static int s_counter = System.DateTime.Now.Second; //Field names and schema guids used in sample schemas private static string int0Name = "int0Name"; private static string double0Name = "double0Name"; private static string bool0Name = "bool0Name"; private static string string0Name = "string0Name"; private static string id0Name = "id0Name"; private static string point0Name = "point0Name"; private static string uv0Name = "uv0Name"; private static string float0Name = "float0Name"; private static string short0Name = "short0Name"; private static string guid0Name = "guid0Name"; private static string map0Name = "map0Name"; private static string array0Name = "array0Name"; private static Guid subEntityGuid0 = NewGuid(); private static string entity0Name = "entity0Name"; private static Guid subEntityGuid_Map1 = NewGuid(); private static string entity1Name_Map = "entity1Name_Map"; private static Guid subEntityGuid_Array2 = NewGuid(); private static string entity2Name_Array = "entity2Name_Array"; private static string array1Name = entity2Name_Array; private static string map1Name = entity1Name_Map; #endregion } }
46.436937
316
0.666214
[ "BSD-3-Clause" ]
AMEE/rev
samples/Revit 2012 SDK/Samples/ExtensibleStorageManager/ExtensibleStorageManager/CS/User/StorageCommand.cs
20,620
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Input; using Acr.UserDialogs; using Hyperledger.Aries.Agents; using Hyperledger.Aries.Contracts; using Hyperledger.Aries.Features.DidExchange; using Hyperledger.Aries.Features.Discovery; using Hyperledger.Aries.Features.TrustPing; using Osma.Mobile.App.Events; using Osma.Mobile.App.Extensions; using Osma.Mobile.App.Services.Interfaces; using Osma.Mobile.App.Views.Connections; using ReactiveUI; using Xamarin.Forms; namespace Osma.Mobile.App.ViewModels.Connections { public class ConnectionViewModel : ABaseViewModel { private readonly ConnectionRecord _record; private readonly IAgentProvider _agentContextProvider; private readonly IMessageService _messageService; private readonly IDiscoveryService _discoveryService; private readonly IConnectionService _connectionService; private readonly IEventAggregator _eventAggregator; public ConnectionViewModel(IUserDialogs userDialogs, INavigationService navigationService, IAgentProvider agentContextProvider, IMessageService messageService, IDiscoveryService discoveryService, IConnectionService connectionService, IEventAggregator eventAggregator, ConnectionRecord record) : base(nameof(ConnectionViewModel), userDialogs, navigationService) { _agentContextProvider = agentContextProvider; _messageService = messageService; _discoveryService = discoveryService; _connectionService = connectionService; _eventAggregator = eventAggregator; _record = record; MyDid = _record.MyDid; TheirDid = _record.TheirDid; ConnectionName = _record.Alias?.Name; ConnectionSubtitle = $"{_record.State:G}"; ConnectionImageUrl = _record.Alias?.ImageUrl; } public override async Task InitializeAsync(object navigationData) { await RefreshTransactions(); await base.InitializeAsync(navigationData); } public async Task RefreshTransactions() { RefreshingTransactions = true; var context = await _agentContextProvider.GetContextAsync(); var message = _discoveryService.CreateQuery(context, "*"); DiscoveryDiscloseMessage protocols = null; try { var response = await _messageService.SendReceiveAsync(context, message, _record) as UnpackedMessageContext; protocols = response.GetMessage<DiscoveryDiscloseMessage>(); } catch (Exception) { //Swallow exception //TODO more granular error protection } IList<TransactionItem> transactions = new List<TransactionItem>(); Transactions.Clear(); if (protocols == null) { HasTransactions = false; RefreshingTransactions = false; return; } foreach (var protocol in protocols.Protocols) { switch (protocol.ProtocolId) { case MessageTypes.TrustPingMessageType: transactions.Add(new TransactionItem() { Title = "Trust Ping", Subtitle = "Version 1.0", PrimaryActionTitle = "Ping", PrimaryActionCommand = new Command(async () => { await PingConnectionAsync(); }, () => true), Type = TransactionItemType.Action.ToString("G") }); break; } } Transactions.InsertRange(transactions); HasTransactions = transactions.Any(); RefreshingTransactions = false; } public async Task PingConnectionAsync() { var dialog = UserDialogs.Instance.Loading("Pinging"); var context = await _agentContextProvider.GetContextAsync(); var message = new TrustPingMessage { ResponseRequested = true }; bool success = false; try { var response = await _messageService.SendReceiveAsync(context, message, _record) as UnpackedMessageContext; var trustPingResponse = response.GetMessage<TrustPingResponseMessage>(); success = true; } catch (Exception) { //Swallow exception //TODO more granular error protection } if (dialog.IsShowing) { dialog.Hide(); dialog.Dispose(); } DialogService.Alert( success ? "Ping Response Recieved" : "No Ping Response Recieved" ); } #region Bindable Command public ICommand NavigateBackCommand => new Command(async () => { await NavigationService.NavigateBackAsync(); }); public ICommand DeleteConnectionCommand => new Command(async () => { var dialog = DialogService.Loading("Deleting"); var context = await _agentContextProvider.GetContextAsync(); await _connectionService.DeleteAsync(context, _record.Id); _eventAggregator.Publish(new ApplicationEvent() { Type = ApplicationEventType.ConnectionsUpdated }); if (dialog.IsShowing) { dialog.Hide(); dialog.Dispose(); } await NavigationService.NavigateBackAsync(); }); public ICommand RefreshTransactionsCommand => new Command(async () => await RefreshTransactions()); #endregion #region Bindable Properties private string _connectionName; public string ConnectionName { get => _connectionName; set => this.RaiseAndSetIfChanged(ref _connectionName, value); } private string _myDid; public string MyDid { get => _myDid; set => this.RaiseAndSetIfChanged(ref _myDid, value); } private string _theirDid; public string TheirDid { get => _theirDid; set => this.RaiseAndSetIfChanged(ref _theirDid, value); } private string _connectionImageUrl; public string ConnectionImageUrl { get => _connectionImageUrl; set => this.RaiseAndSetIfChanged(ref _connectionImageUrl, value); } private string _connectionSubtitle = "Lorem ipsum dolor sit amet"; public string ConnectionSubtitle { get => _connectionSubtitle; set => this.RaiseAndSetIfChanged(ref _connectionSubtitle, value); } private RangeEnabledObservableCollection<TransactionItem> _transactions = new RangeEnabledObservableCollection<TransactionItem>(); public RangeEnabledObservableCollection<TransactionItem> Transactions { get => _transactions; set => this.RaiseAndSetIfChanged(ref _transactions, value); } private bool _refreshingTransactions; public bool RefreshingTransactions { get => _refreshingTransactions; set => this.RaiseAndSetIfChanged(ref _refreshingTransactions, value); } private bool _hasTransactions; public bool HasTransactions { get => _hasTransactions; set => this.RaiseAndSetIfChanged(ref _hasTransactions, value); } #endregion } }
34.6639
138
0.566794
[ "Apache-2.0" ]
horationunez/aries-mobileagent-xamarin
src/Osma.Mobile.App/ViewModels/Connections/ConnectionViewModel.cs
8,356
C#
using EifelMono.Fluent.IO; using EifelMono.Fluent.NuGet; using EifelMono.Fluent.Test.XunitTests; using Xunit; using Xunit.Abstractions; #pragma warning disable IDE1006 // Naming Styles namespace EifelMono.Fluent.Test.DotNetTests { public class GlobalJsonTest : XunitCore { public GlobalJsonTest(ITestOutputHelper output) : base(output) { } [Fact] public async void GetGlobalJsonTests() { { var result = await dotnet.GlobalJson.GetFilesBackwardsAsync(); Assert.True(result.Count > 0); } { var result = await dotnet.GlobalJson.GetExistingFilesBackwardsAsync(); Assert.True(result.Count == 1); } } } #pragma warning restore IDE1006 // Naming Styles }
26.354839
86
0.624235
[ "MIT" ]
EifelMono/EifelMono.Fluent
src/EifelMono.Fluent.Test/DotNetTests/GlobalJsonTests.cs
819
C#
using System.IO; using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class Slave_Test : gameObject { [Ordinal(0)] [RED("deviceComponent")] public CHandle<PSD_Detector> DeviceComponent { get; set; } public Slave_Test(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
24.875
100
0.711055
[ "MIT" ]
Eingin/CP77Tools
CP77.CR2W/Types/cp77/Slave_Test.cs
383
C#
using System; using System.Numerics; namespace Neo.Compiler.CSharp.UnitTests.TestClasses { public class Contract_Types : SmartContract.Framework.SmartContract { public enum EDummy : byte { test = 5 } public delegate EDummy enumDel(); public delegate void del(string msg); public static event del dummyEvent; public class DummyClass { public string Value; } public struct DummyStruct { public string Value; } public static object checkNull() { return null; } public static bool checkBoolTrue() { return true; } public static bool checkBoolFalse() { return false; } public static sbyte checkSbyte() { return (sbyte)5; } public static byte checkByte() { return (byte)5; } public static short checkShort() { return (short)5; } public static ushort checkUshort() { return (ushort)5; } public static int checkInt() { return (int)5; } public static uint checkUint() { return (uint)5; } public static long checkLong() { return (long)5; } public static ulong checkUlong() { return (ulong)5; } public static char checkChar() { return 'n'; } public static string checkString() { return "neo"; } public static char checkStringIndex(string input, int index) => input[index]; public static object[] checkArrayObj() { return new object[] { "neo" }; } public static BigInteger checkBigInteger() { return (BigInteger)5; } public static byte[] checkByteArray() { return new byte[] { 1, 2, 3 }; } public static object checkEnum() { return EDummy.test; } private static EDummy icheckEnum() { return EDummy.test; } public static void checkEnumArg(Neo.SmartContract.Framework.Native.OracleResponseCode arg) { } public static string checkNameof() { return nameof(checkNull); } public static object checkDelegate() { return new enumDel(icheckEnum); } public static object checkLambda() { return new Func<EDummy>(icheckEnum); } public static void checkEvent() { dummyEvent("neo"); } public static object checkClass() { var ret = new DummyClass(); ret.Value = "neo"; return ret; } public static object checkStruct() { var ret = new DummyStruct(); ret.Value = "neo"; return ret; } public static (string value1, string value2) checkTuple() { return ("neo", "smart economy"); } public static (string value1, string value2) checkTuple2() { var tuple = ("neo", "smart economy"); return tuple; } } }
34.903614
102
0.579565
[ "MIT" ]
DanPopa46/neo-devpack-dotnet
tests/Neo.Compiler.CSharp.UnitTests/TestClasses/Contract_Types.cs
2,897
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace PowerLines { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
24.083333
99
0.586505
[ "MIT" ]
LynxMagnus/power-lines
PowerLines/App_Start/RouteConfig.cs
580
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace LikesDemo { public partial class Posts { /// <summary> /// ListViewPosts control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.ListView ListViewPosts; } }
30.48
84
0.465879
[ "MIT" ]
EmilMitev/Telerik-Academy
ASP.NET Web Forms/13. User Controls/Demo/LikesDemo/Posts.aspx.designer.cs
764
C#
using agrix.Extensions; using System; using System.Linq; using YamlDotNet.RepresentationModel; namespace agrix.Configuration.Parsers { /// <summary> /// Parses a firewall configuration. /// </summary> internal class FirewallParser { /// <summary> /// Delegate used to create a FirewallRule instance from a YAML configuration. Can /// be overridden in subclasses. /// </summary> protected Parse<FirewallRule> ParseRule = new FirewallRuleParser().Parse; /// <summary> /// Creates a Firewall instance from a YAML configuration. /// </summary> /// <param name="node">The YAML configuration to parse.</param> /// <returns>The Firewall instance parsed from the given YAML.</returns> public virtual Firewall Parse(YamlNode node) { if (node.NodeType != YamlNodeType.Mapping) throw new InvalidCastException( $"script item must be a mapping type (line {node.Start.Line}"); var firewallItem = (YamlMappingNode)node; var name = firewallItem.GetKey("name"); var rules = firewallItem.GetSequence("rules") .Select(childNode => ParseRule(childNode)).ToList(); return new Firewall(name, rules.ToArray()); } } }
35.307692
91
0.597676
[ "MIT" ]
okinta/agrix
Configuration/Parsers/FirewallParser.cs
1,379
C#
namespace SoftUni.WebServer.Http.Requests { using System; using System.Collections.Generic; using System.Linq; using System.Net; using Cookies; using Enums; using Exceptions; using Headers; using Interfaces; using Session; using SoftUni.WebServer.Common; public class HttpRequest : IHttpRequest { private const int HttpRequestLinePartsLength = 3; // Method; URL; HTTP version private const string HttpVersion = "HTTP/1.1"; private const string HeaderSeparator = ": "; private const string QueryStringSeparator = "?"; private const string UrlParameterSeparator = "&"; private const string UrlKeyValueSeparator = "="; private const string CookieSeparator = ";"; private const string CookieKeyValueSeparator = "="; private string requestString; public HttpRequest(string requestString) { this.requestString = requestString; this.UrlParameters = new Dictionary<string, string>(); this.QueryParameters = new Dictionary<string, string>(); this.Headers = new HttpHeaderCollection(); this.Cookies = new HttpCookieCollection(); this.FormData = new Dictionary<string, string>(); this.ParseRequest(requestString); } public HttpRequestMethod Method { get; private set; } public string Url { get; private set; } public string Path { get; private set; } public IDictionary<string, string> UrlParameters { get; private set; } public IDictionary<string, string> QueryParameters { get; private set; } public IHttpHeaderCollection Headers { get; private set; } public IHttpCookieCollection Cookies { get; private set; } public IHttpSession Session { get; set; } public IDictionary<string, string> FormData { get; private set; } public void AddUrlParameter(string key, string value) { Validation.EnsureNotNullOrEmptyString(key, nameof(key)); Validation.EnsureNotNullOrEmptyString(value, nameof(value)); this.UrlParameters.Add(key, value); } public override string ToString() => this.requestString; private void ParseRequest(string requestString) { string[] requestLines = requestString.Split(Environment.NewLine, StringSplitOptions.None); if (!requestLines.Any()) { throw new BadRequestException(); } string[] requestLineParts = requestLines[0] .Trim() .Split(" ", StringSplitOptions.RemoveEmptyEntries); if (requestLineParts.Length != HttpRequestLinePartsLength || requestLineParts[HttpRequestLinePartsLength - 1].ToLower() != HttpVersion.ToLower()) { throw new BadRequestException(); } this.Method = this.ParseRequestMethod(requestLineParts[0]); this.Url = requestLineParts[1]; this.Path = requestLineParts[1].Split(new[] { '?', '#' }, StringSplitOptions.RemoveEmptyEntries)[0]; var headerLines = requestLines .Skip(1) .TakeWhile(line => !string.IsNullOrEmpty(line)); this.ParseHeaders(headerLines); this.ParseCookies(); this.ParseParameters(this.Url); if (this.Method == HttpRequestMethod.Post) { this.FormData = this.ParseFormData(requestLines[requestLines.Length - 1]); } this.InitializeSession(); } private HttpRequestMethod ParseRequestMethod(string method) { HttpRequestMethod methodResult; bool parsingSuccess = Enum.TryParse<HttpRequestMethod>(method, true, out methodResult); if (!parsingSuccess) { throw new BadRequestException("The request method is invalid or not supported."); } return methodResult; } private void ParseHeaders(IEnumerable<string> headerLines) { foreach (string headerLine in headerLines) { string[] headerParts = headerLine.Split(HeaderSeparator); if (headerParts.Length != 2) { throw new BadRequestException(); } this.Headers.Add(new HttpHeader(headerParts[0], headerParts[1].Trim())); } if (!this.Headers.ContainsKey(HttpHeader.Host)) { throw new BadRequestException("The headers must specify a host."); } } private void ParseCookies() { if (this.Headers.ContainsKey(HttpHeader.Cookie)) { string allCookiesString = this.Headers.Get(HttpHeader.Cookie).Value; string[] cookies = allCookiesString.Split(CookieSeparator, StringSplitOptions.RemoveEmptyEntries); foreach (var cookie in cookies) { string[] cookieParts = cookie.Split(CookieKeyValueSeparator, StringSplitOptions.RemoveEmptyEntries); if (cookieParts.Length != 2) { throw new BadRequestException(); } string key = cookieParts[0]; string value = cookieParts[1]; this.Cookies.Add(new HttpCookie(key, value, isNew: false)); } } } private void ParseParameters(string url) { if (url.IndexOf(QueryStringSeparator) < 0) { return; } string query = url.Split(QueryStringSeparator, 2)[1]; this.QueryParameters = this.ParseQuery(query); } private IDictionary<string, string> ParseQuery(string query) { var queryParameters = new Dictionary<string, string>(); string[] keyValuePairs = query.Split(UrlParameterSeparator, StringSplitOptions.RemoveEmptyEntries); foreach (var keyValuePair in keyValuePairs) { string[] keyAndValue = keyValuePair.Split(UrlKeyValueSeparator, StringSplitOptions.RemoveEmptyEntries); if (keyAndValue.Length != 2) { continue; } string key = WebUtility.UrlDecode(keyAndValue[0]); string value = WebUtility.UrlDecode(keyAndValue[1]); queryParameters[key] = value; } return queryParameters; } private IDictionary<string, string> ParseFormData(string query) { if (this.Method == HttpRequestMethod.Get) { return new Dictionary<string, string>(); } return this.ParseQuery(query); } private void InitializeSession() { if (this.Cookies.ContainsKey(SessionStore.SessionCookieKey)) { var cookie = this.Cookies.Get(SessionStore.SessionCookieKey); string sessionId = cookie.Value; this.Session = SessionStore.GetSession(sessionId); } } } }
34.890995
120
0.577017
[ "MIT" ]
Iliyan7/SoftUni
CSharpWebDevBasics/CSharpWebDevBasicsExam-01-Jul-18/SoftUni.WebServer.Http/Requests/HttpRequest.cs
7,364
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using tibs.stem.EntityFrameworkCore; using Abp.Authorization; using Abp.BackgroundJobs; using Abp.Notifications; using tibs.stem.Chat; using tibs.stem.Friendships; using tibs.stem.MultiTenancy.Payments; namespace tibs.stem.Migrations { [DbContext(typeof(stemDbContext))] [Migration("20180321054229_alter-User-Add-Designation")] partial class alterUserAddDesignation { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.1.2") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Abp.Application.Editions.Edition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("Discriminator") .IsRequired(); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.HasKey("Id"); b.ToTable("AbpEditions"); b.HasDiscriminator<string>("Discriminator").HasValue("Edition"); }); modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Discriminator") .IsRequired(); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<string>("Value") .IsRequired() .HasMaxLength(2000); b.HasKey("Id"); b.ToTable("AbpFeatures"); b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting"); }); modelBuilder.Entity("Abp.Auditing.AuditLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("BrowserInfo") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<string>("CustomData") .HasMaxLength(2000); b.Property<string>("Exception") .HasMaxLength(2000); b.Property<int>("ExecutionDuration"); b.Property<DateTime>("ExecutionTime"); b.Property<int?>("ImpersonatorTenantId"); b.Property<long?>("ImpersonatorUserId"); b.Property<string>("MethodName") .HasMaxLength(256); b.Property<string>("Parameters") .HasMaxLength(1024); b.Property<string>("ServiceName") .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionDuration"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Abp.Authorization.PermissionSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Discriminator") .IsRequired(); b.Property<bool>("IsGranted"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpPermissions"); b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int>("RoleId"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("EmailAddress"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastLoginTime"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.Property<long?>("UserLinkId"); b.Property<string>("UserName"); b.HasKey("Id"); b.HasIndex("EmailAddress"); b.HasIndex("UserName"); b.HasIndex("TenantId", "EmailAddress"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "UserName"); b.ToTable("AbpUserAccounts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("LoginProvider") .IsRequired() .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("BrowserInfo") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<byte>("Result"); b.Property<string>("TenancyName") .HasMaxLength(64); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.Property<string>("UserNameOrEmailAddress") .HasMaxLength(255); b.HasKey("Id"); b.HasIndex("UserId", "TenantId"); b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result"); b.ToTable("AbpUserLoginAttempts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<bool>("IsDeleted"); b.Property<long>("OrganizationUnitId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int>("RoleId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "RoleId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.Property<string>("Value"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<bool>("IsAbandoned"); b.Property<string>("JobArgs") .IsRequired() .HasMaxLength(1048576); b.Property<string>("JobType") .IsRequired() .HasMaxLength(512); b.Property<DateTime?>("LastTryTime"); b.Property<DateTime>("NextTryTime"); b.Property<byte>("Priority"); b.Property<short>("TryCount"); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.Property<string>("Value") .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Abp.IdentityServer4.PersistedGrantEntity", b => { b.Property<string>("Id") .HasMaxLength(200); b.Property<string>("ClientId") .IsRequired() .HasMaxLength(200); b.Property<DateTime>("CreationTime"); b.Property<string>("Data") .IsRequired() .HasMaxLength(50000); b.Property<DateTime?>("Expiration"); b.Property<string>("SubjectId") .HasMaxLength(200); b.Property<string>("Type") .IsRequired() .HasMaxLength(50); b.HasKey("Id"); b.HasIndex("SubjectId", "ClientId", "Type"); b.ToTable("AbpPersistedGrants"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<string>("Icon") .HasMaxLength(128); b.Property<bool>("IsDeleted"); b.Property<bool>("IsDisabled"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(10); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpLanguages"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Key") .IsRequired() .HasMaxLength(256); b.Property<string>("LanguageName") .IsRequired() .HasMaxLength(10); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Source") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.Property<string>("Value") .IsRequired() .HasMaxLength(67108864); b.HasKey("Id"); b.HasIndex("TenantId", "Source", "LanguageName", "Key"); b.ToTable("AbpLanguageTexts"); }); modelBuilder.Entity("Abp.Notifications.NotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Data") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasMaxLength(512); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("ExcludedUserIds") .HasMaxLength(131072); b.Property<string>("NotificationName") .IsRequired() .HasMaxLength(96); b.Property<byte>("Severity"); b.Property<string>("TenantIds") .HasMaxLength(131072); b.Property<string>("UserIds") .HasMaxLength(131072); b.HasKey("Id"); b.ToTable("AbpNotifications"); }); modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("NotificationName") .HasMaxLength(96); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId"); b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId"); b.ToTable("AbpNotificationSubscriptions"); }); modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Data") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasMaxLength(512); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("NotificationName") .IsRequired() .HasMaxLength(96); b.Property<byte>("Severity"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AbpTenantNotifications"); }); modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<int>("State"); b.Property<int?>("TenantId"); b.Property<Guid>("TenantNotificationId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId", "State", "CreationTime"); b.ToTable("AbpUserNotifications"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Code") .IsRequired() .HasMaxLength(95); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(128); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<long?>("ParentId"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("ParentId"); b.HasIndex("TenantId", "Code"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("tibs.stem.AbpSalesCoOrinators.AbpSalesCoOrinator", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<long?>("CoordinatorId"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<long?>("UserId"); b.HasKey("Id"); b.HasIndex("CoordinatorId"); b.HasIndex("UserId"); b.ToTable("AbpSalesCoOrinator"); }); modelBuilder.Entity("tibs.stem.AcitivityTracks.AcitivityTrack", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("ActivityId"); b.Property<int?>("ContactId"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("CurrentStatus"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int>("EnquiryId"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Message"); b.Property<string>("PreviousStatus"); b.Property<string>("Title"); b.HasKey("Id"); b.HasIndex("ActivityId"); b.HasIndex("ContactId"); b.HasIndex("EnquiryId"); b.ToTable("AcitivityTrack"); }); modelBuilder.Entity("tibs.stem.Activities.Activity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ActivityCode") .IsRequired(); b.Property<string>("ActivityName") .IsRequired(); b.Property<string>("ColorCode"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.HasKey("Id"); b.ToTable("Activity"); }); modelBuilder.Entity("tibs.stem.ActivityTrackComments.ActivityTrackComment", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("ActivityTrackId"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Message"); b.HasKey("Id"); b.HasIndex("ActivityTrackId"); b.ToTable("ActivityTrackComment"); }); modelBuilder.Entity("tibs.stem.AttributeGroupDetails.AttributeGroupDetail", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AttributeGroupId"); b.Property<int>("AttributeId"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.HasKey("Id"); b.HasIndex("AttributeGroupId"); b.HasIndex("AttributeId"); b.ToTable("AttributeGroupDetail"); }); modelBuilder.Entity("tibs.stem.Authorization.Roles.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<bool>("IsDefault"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsStatic"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.Property<string>("NormalizedName") .IsRequired() .HasMaxLength(32); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("tibs.stem.Authorization.Users.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("AuthenticationSource") .HasMaxLength(64); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int?>("DepartmentId"); b.Property<string>("EmailAddress") .IsRequired() .HasMaxLength(256); b.Property<string>("EmailConfirmationCode") .HasMaxLength(328); b.Property<string>("GoogleAuthenticatorKey"); b.Property<bool>("IsActive"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsEmailConfirmed"); b.Property<bool>("IsLockoutEnabled"); b.Property<bool>("IsPhoneNumberConfirmed"); b.Property<bool>("IsTwoFactorEnabled"); b.Property<DateTime?>("LastLoginTime"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<DateTime?>("LockoutEndDateUtc"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.Property<string>("NormalizedEmailAddress") .IsRequired() .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasMaxLength(32); b.Property<string>("Password") .IsRequired() .HasMaxLength(128); b.Property<string>("PasswordResetCode") .HasMaxLength(328); b.Property<string>("PhoneNumber"); b.Property<Guid?>("ProfilePictureId"); b.Property<string>("SecurityStamp"); b.Property<bool>("ShouldChangePasswordOnNextLogin"); b.Property<string>("SignInToken"); b.Property<DateTime?>("SignInTokenExpireTimeUtc"); b.Property<string>("Surname") .IsRequired() .HasMaxLength(32); b.Property<int?>("TenantId"); b.Property<string>("Url"); b.Property<int?>("UserDesignationId"); b.Property<string>("UserName") .IsRequired() .HasMaxLength(32); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("DepartmentId"); b.HasIndex("LastModifierUserId"); b.HasIndex("UserDesignationId"); b.HasIndex("TenantId", "NormalizedEmailAddress"); b.HasIndex("TenantId", "NormalizedUserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("tibs.stem.Chat.ChatMessage", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<string>("Message") .IsRequired() .HasMaxLength(4096); b.Property<int>("ReadState"); b.Property<int>("Side"); b.Property<int?>("TargetTenantId"); b.Property<long>("TargetUserId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("TargetTenantId", "TargetUserId", "ReadState"); b.HasIndex("TargetTenantId", "UserId", "ReadState"); b.HasIndex("TenantId", "TargetUserId", "ReadState"); b.HasIndex("TenantId", "UserId", "ReadState"); b.ToTable("AppChatMessages"); }); modelBuilder.Entity("tibs.stem.Citys.City", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("CityCode") .IsRequired(); b.Property<string>("CityName") .IsRequired(); b.Property<int>("CountryId"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.HasKey("Id"); b.HasIndex("CountryId"); b.ToTable("City"); }); modelBuilder.Entity("tibs.stem.Collections.Collection", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("CollectionCode"); b.Property<string>("CollectionName"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.HasKey("Id"); b.ToTable("Collection"); }); modelBuilder.Entity("tibs.stem.ColorCodes.ColorCode", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Code"); b.Property<string>("Color"); b.Property<string>("Component"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.HasKey("Id"); b.ToTable("ColorCode"); }); modelBuilder.Entity("tibs.stem.Companies.Company", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<long?>("AccountManagerId"); b.Property<string>("Address"); b.Property<int>("CityId"); b.Property<string>("CompanyCode"); b.Property<string>("CompanyName"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int>("CustomerTypeId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("Email"); b.Property<string>("Fax"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Mob_No"); b.Property<string>("PhoneNo"); b.Property<string>("TelNo"); b.HasKey("Id"); b.HasIndex("AccountManagerId"); b.HasIndex("CityId"); b.HasIndex("CustomerTypeId"); b.ToTable("Companies"); }); modelBuilder.Entity("tibs.stem.CompanyContacts.CompanyContact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Address"); b.Property<int>("CompanyId"); b.Property<string>("ContactPersonName"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("Description"); b.Property<int?>("DesiginationId"); b.Property<string>("Email"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Mobile_No"); b.Property<int>("TitleId"); b.Property<string>("Work_No"); b.HasKey("Id"); b.HasIndex("CompanyId"); b.HasIndex("DesiginationId"); b.HasIndex("TitleId"); b.ToTable("CompanyContacts"); }); modelBuilder.Entity("tibs.stem.Countrys.Country", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("CountryCode") .IsRequired() .HasMaxLength(3); b.Property<string>("CountryName") .IsRequired() .HasMaxLength(50); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("ISDCode") .HasMaxLength(5); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.HasKey("Id"); b.ToTable("Country"); }); modelBuilder.Entity("tibs.stem.CustomerTypes.CustomerType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Code"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("CustomerTypeName"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.HasKey("Id"); b.ToTable("CustomerType"); }); modelBuilder.Entity("tibs.stem.Departments.Department", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DepartmentCode"); b.Property<string>("DepatmentName"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.HasKey("Id"); b.ToTable("Department"); }); modelBuilder.Entity("tibs.stem.Designations.Designation", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DesiginationName"); b.Property<string>("DesignationCode"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.HasKey("Id"); b.ToTable("Designations"); }); modelBuilder.Entity("tibs.stem.Dimensions.Dimension", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DimensionCode"); b.Property<string>("DimensionName"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.HasKey("Id"); b.ToTable("Dimension"); }); modelBuilder.Entity("tibs.stem.Discounts.Discount", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<decimal>("Discountable"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("QuotationDescription"); b.Property<decimal>("UnDiscountable"); b.Property<int>("Vat"); b.HasKey("Id"); b.ToTable("Discount"); }); modelBuilder.Entity("tibs.stem.Emaildomains.Emaildomain", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("EmaildomainName"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.HasKey("Id"); b.ToTable("Emaildomain"); }); modelBuilder.Entity("tibs.stem.EnquiryContacts.EnquiryContact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("ContactId"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int?>("InquiryId"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.HasKey("Id"); b.HasIndex("ContactId"); b.HasIndex("InquiryId"); b.ToTable("EnquiryContacts"); }); modelBuilder.Entity("tibs.stem.EnquiryDetails.EnquiryDetail", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime?>("AssignedbyDate"); b.Property<long?>("AssignedbyId"); b.Property<DateTime?>("ClosureDate"); b.Property<int?>("CompanyId"); b.Property<int?>("CompatitorsId"); b.Property<int?>("ContactId"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int?>("DepartmentId"); b.Property<int?>("DesignationId"); b.Property<decimal>("EstimationValue"); b.Property<int?>("InquiryId"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastActivity"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int?>("LeadTypeId"); b.Property<string>("Size"); b.Property<string>("Summary"); b.Property<int?>("TeamId"); b.HasKey("Id"); b.HasIndex("AssignedbyId"); b.HasIndex("CompanyId"); b.HasIndex("CompatitorsId"); b.HasIndex("ContactId"); b.HasIndex("DepartmentId"); b.HasIndex("DesignationId"); b.HasIndex("InquiryId"); b.HasIndex("LeadTypeId"); b.HasIndex("TeamId"); b.ToTable("EnquiryDetail"); }); modelBuilder.Entity("tibs.stem.EnquirySources.EnquirySource", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int?>("InquiryId"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int?>("SourceId"); b.HasKey("Id"); b.HasIndex("InquiryId"); b.HasIndex("SourceId"); b.ToTable("EnquirySource"); }); modelBuilder.Entity("tibs.stem.EnquiryStatuss.EnquiryStatus", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("EnqStatusCode") .IsRequired(); b.Property<string>("EnqStatusColor"); b.Property<string>("EnqStatusName") .IsRequired(); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<decimal?>("Percentage"); b.Property<int?>("StagestateId"); b.HasKey("Id"); b.HasIndex("StagestateId"); b.ToTable("EnquiryStatus"); }); modelBuilder.Entity("tibs.stem.Friendships.Friendship", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<Guid?>("FriendProfilePictureId"); b.Property<string>("FriendTenancyName"); b.Property<int?>("FriendTenantId"); b.Property<long>("FriendUserId"); b.Property<string>("FriendUserName") .IsRequired() .HasMaxLength(32); b.Property<int>("State"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("FriendTenantId", "FriendUserId"); b.HasIndex("FriendTenantId", "UserId"); b.HasIndex("TenantId", "FriendUserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AppFriendships"); }); modelBuilder.Entity("tibs.stem.ImportHistorys.ImportHistory", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("FileName"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("ProductCode"); b.Property<string>("Quantity"); b.Property<int?>("QuotationId"); b.Property<string>("SectionName"); b.Property<string>("Status"); b.HasKey("Id"); b.HasIndex("QuotationId"); b.ToTable("ImportHistory"); }); modelBuilder.Entity("tibs.stem.Industrys.Industry", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("IndustryCode") .IsRequired(); b.Property<string>("IndustryName") .IsRequired(); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.HasKey("Id"); b.ToTable("Industry"); }); modelBuilder.Entity("tibs.stem.Inquirys.Inquiry", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Address"); b.Property<bool?>("Archieved"); b.Property<string>("Browcerinfo"); b.Property<string>("CEmail"); b.Property<string>("CLandlineNumber"); b.Property<string>("CMbNo"); b.Property<int?>("CompanyId"); b.Property<string>("CompanyName"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int?>("DepartmentId"); b.Property<int?>("DesignationId"); b.Property<string>("DesignationName"); b.Property<string>("Email"); b.Property<string>("IpAddress"); b.Property<bool?>("IsClosed"); b.Property<bool>("IsDeleted"); b.Property<bool?>("Junk"); b.Property<DateTime?>("JunkDate"); b.Property<string>("LandlineNumber"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int?>("LeadStatusId"); b.Property<int?>("LocationId"); b.Property<string>("MbNo"); b.Property<int?>("MileStoneId"); b.Property<string>("Name") .IsRequired(); b.Property<int?>("OpportunitySourceId"); b.Property<string>("Remarks"); b.Property<int?>("StatusId"); b.Property<string>("SubMmissionId"); b.Property<string>("WebSite"); b.Property<int?>("WhyBafcoId"); b.HasKey("Id"); b.HasIndex("CompanyId"); b.HasIndex("DepartmentId"); b.HasIndex("DesignationId"); b.HasIndex("LeadStatusId"); b.HasIndex("LocationId"); b.HasIndex("MileStoneId"); b.HasIndex("OpportunitySourceId"); b.HasIndex("StatusId"); b.HasIndex("WhyBafcoId"); b.ToTable("Inquiry"); }); modelBuilder.Entity("tibs.stem.Inquirys.JobActivity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime?>("AllottedDate"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<long?>("DesignerId"); b.Property<DateTime?>("EndDate"); b.Property<int?>("InquiryId"); b.Property<bool>("IsDeleted"); b.Property<bool>("Isopen"); b.Property<string>("JobNumber"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Remark"); b.Property<DateTime?>("StartDate"); b.Property<string>("Title"); b.HasKey("Id"); b.HasIndex("DesignerId"); b.HasIndex("InquiryId"); b.ToTable("JobActivity"); }); modelBuilder.Entity("tibs.stem.LeadDetails.LeadDetail", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<long?>("CoordinatorId"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<long?>("DesignerId"); b.Property<float?>("EstimationValue"); b.Property<int?>("InquiryId"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int?>("LeadSourceId"); b.Property<int?>("LeadTypeId"); b.Property<long?>("SalesManagerId"); b.Property<string>("Size"); b.HasKey("Id"); b.HasIndex("CoordinatorId"); b.HasIndex("DesignerId"); b.HasIndex("InquiryId"); b.HasIndex("LeadSourceId"); b.HasIndex("LeadTypeId"); b.HasIndex("SalesManagerId"); b.ToTable("LeadDetails"); }); modelBuilder.Entity("tibs.stem.LeadReasons.LeadReason", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("LeadReasonCode"); b.Property<string>("LeadReasonName"); b.HasKey("Id"); b.ToTable("LeadReason"); }); modelBuilder.Entity("tibs.stem.LeadSources.LeadSource", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("LeadSourceCode"); b.Property<string>("LeadSourceName"); b.HasKey("Id"); b.ToTable("LeadSources"); }); modelBuilder.Entity("tibs.stem.LeadStatuss.LeadStatus", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("LeadStatusCode"); b.Property<string>("LeadStatusName"); b.HasKey("Id"); b.ToTable("LeadStatus"); }); modelBuilder.Entity("tibs.stem.LeadTypes.LeadType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("LeadTypeCode"); b.Property<string>("LeadTypeName"); b.HasKey("Id"); b.ToTable("LeadType"); }); modelBuilder.Entity("tibs.stem.LineTypes.LineType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("LineTypeCode") .IsRequired(); b.Property<string>("LineTypeName") .IsRequired(); b.HasKey("Id"); b.ToTable("LineType"); }); modelBuilder.Entity("tibs.stem.Locations.Location", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CityId"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("LocationCode") .IsRequired(); b.Property<string>("LocationName") .IsRequired(); b.HasKey("Id"); b.HasIndex("CityId"); b.ToTable("Location"); }); modelBuilder.Entity("tibs.stem.Milestones.MileStone", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsQuotation"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("MileStoneCode"); b.Property<string>("MileStoneName"); b.Property<bool>("ResetActivity"); b.Property<int?>("RottingPeriod"); b.Property<int>("SourceTypeId"); b.HasKey("Id"); b.HasIndex("SourceTypeId"); b.ToTable("MileStone"); }); modelBuilder.Entity("tibs.stem.Milestones.StageDetails", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int>("MileStoneId"); b.Property<int>("StageId"); b.HasKey("Id"); b.HasIndex("MileStoneId"); b.HasIndex("StageId"); b.ToTable("MileStoneDetails"); }); modelBuilder.Entity("tibs.stem.MultiTenancy.Payments.SubscriptionPayment", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<decimal>("Amount"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int>("DayCount"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int>("EditionId"); b.Property<int>("Gateway"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("PaymentId"); b.Property<int?>("PaymentPeriodType"); b.Property<int>("Status"); b.Property<int>("TenantId"); b.HasKey("Id"); b.HasIndex("EditionId"); b.HasIndex("PaymentId", "Gateway"); b.HasIndex("Status", "CreationTime"); b.ToTable("AppSubscriptionPayments"); }); modelBuilder.Entity("tibs.stem.MultiTenancy.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConnectionString") .HasMaxLength(1024); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<Guid?>("CustomCssId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int?>("EditionId"); b.Property<bool>("IsActive"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsInTrialPeriod"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("LogoFileType") .HasMaxLength(64); b.Property<Guid?>("LogoId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<DateTime?>("SubscriptionEndDateUtc"); b.Property<string>("TenancyName") .IsRequired() .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("CreationTime"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("EditionId"); b.HasIndex("LastModifierUserId"); b.HasIndex("SubscriptionEndDateUtc"); b.HasIndex("TenancyName"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("tibs.stem.NewCustomerCompanys.NewAddressInfo", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Address1"); b.Property<string>("Address2"); b.Property<int?>("CityId"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int?>("NewCompanyId"); b.Property<int?>("NewContacId"); b.Property<int?>("NewInfoTypeId"); b.HasKey("Id"); b.HasIndex("CityId"); b.HasIndex("NewCompanyId"); b.HasIndex("NewContacId"); b.HasIndex("NewInfoTypeId"); b.ToTable("NewAddressInfo"); }); modelBuilder.Entity("tibs.stem.NewCustomerCompanys.NewCompany", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<long?>("AccountManagerId"); b.Property<long?>("ApprovedById"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("CustomerId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int>("Discountable"); b.Property<int?>("IndustryId"); b.Property<bool>("IsApproved"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name"); b.Property<int?>("NewCustomerTypeId"); b.Property<string>("TRNnumber"); b.Property<string>("TradeLicense"); b.Property<int>("UnDiscountable"); b.HasKey("Id"); b.HasIndex("AccountManagerId"); b.HasIndex("ApprovedById"); b.HasIndex("IndustryId"); b.HasIndex("NewCustomerTypeId"); b.ToTable("NewCompany"); }); modelBuilder.Entity("tibs.stem.NewCustomerCompanys.NewContact", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int?>("DesignationId"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("LastName"); b.Property<string>("Name"); b.Property<int?>("NewCompanyId"); b.Property<int?>("NewCustomerTypeId"); b.Property<int?>("TitleId"); b.HasKey("Id"); b.HasIndex("DesignationId"); b.HasIndex("NewCompanyId"); b.HasIndex("NewCustomerTypeId"); b.HasIndex("TitleId"); b.ToTable("NewContact"); }); modelBuilder.Entity("tibs.stem.NewCustomerCompanys.NewContactInfo", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("InfoData"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int?>("NewCompanyId"); b.Property<int?>("NewContacId"); b.Property<int?>("NewInfoTypeId"); b.HasKey("Id"); b.HasIndex("NewCompanyId"); b.HasIndex("NewContacId"); b.HasIndex("NewInfoTypeId"); b.ToTable("NewContactInfo"); }); modelBuilder.Entity("tibs.stem.NewCustomerCompanys.NewCustomerType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<bool?>("Company"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Title"); b.HasKey("Id"); b.ToTable("NewCustomerType"); }); modelBuilder.Entity("tibs.stem.NewCustomerCompanys.NewInfoType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ContactName"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool?>("Info"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.HasKey("Id"); b.ToTable("NewInfoType"); }); modelBuilder.Entity("tibs.stem.OpportunitySources.OpportunitySource", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Code"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("OpportunitySource"); }); modelBuilder.Entity("tibs.stem.Orientations.Orientation", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("OrientationCode"); b.Property<string>("OrientationName"); b.HasKey("Id"); b.ToTable("Orientation"); }); modelBuilder.Entity("tibs.stem.PriceLevels.PriceLevel", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("DiscountAllowed"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("PriceLevelCode"); b.Property<string>("PriceLevelName"); b.HasKey("Id"); b.ToTable("PriceLevel"); }); modelBuilder.Entity("tibs.stem.ProductAttributeGroups.ProductAttributeGroup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AttributeGroupCode"); b.Property<string>("AttributeGroupName"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.HasKey("Id"); b.ToTable("AttributeGroup"); }); modelBuilder.Entity("tibs.stem.ProductAttributes.ProductAttribute", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AttributeCode"); b.Property<string>("AttributeName"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("Description"); b.Property<string>("Imageurl"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.HasKey("Id"); b.ToTable("ProductAttributes"); }); modelBuilder.Entity("tibs.stem.ProductCategorys.ProductCategory", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Code"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("ProductCategory"); }); modelBuilder.Entity("tibs.stem.ProductFamilys.ProductFamily", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int?>("CollectionId"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("Description"); b.Property<bool?>("Discount"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("ProductFamilyCode"); b.Property<string>("ProductFamilyName"); b.Property<int>("Warranty"); b.HasKey("Id"); b.HasIndex("CollectionId"); b.ToTable("ProductFamily"); }); modelBuilder.Entity("tibs.stem.ProductGroups.ProductGroup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("AttributeData"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int?>("FamilyId"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int?>("ProductCategoryId"); b.Property<string>("ProductGroupName") .IsRequired(); b.HasKey("Id"); b.HasIndex("FamilyId"); b.HasIndex("ProductCategoryId"); b.ToTable("ProductGroup"); }); modelBuilder.Entity("tibs.stem.ProductGroups.ProductGroupDetail", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AttributeGroupId"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Metedata"); b.Property<int>("OrderBy"); b.Property<int>("ProductGroupId"); b.Property<int>("ReturnBy"); b.HasKey("Id"); b.HasIndex("AttributeGroupId"); b.HasIndex("ProductGroupId"); b.ToTable("ProductGroupDetail"); }); modelBuilder.Entity("tibs.stem.ProductImageUrls.ProductImageUrl", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("ImageUrl"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int>("ProductId"); b.HasKey("Id"); b.HasIndex("ProductId"); b.ToTable("ProductImageUrl"); }); modelBuilder.Entity("tibs.stem.Products.Product", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int>("Depth"); b.Property<string>("Description"); b.Property<string>("Gpcode"); b.Property<int>("Height"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<decimal?>("Price"); b.Property<string>("ProductCode"); b.Property<string>("ProductName"); b.Property<int?>("ProductSpecificationId"); b.Property<string>("SuspectCode"); b.Property<int>("Width"); b.HasKey("Id"); b.HasIndex("ProductSpecificationId"); b.ToTable("Product"); }); modelBuilder.Entity("tibs.stem.Products.ProductPricelevel", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<decimal>("Price"); b.Property<int>("PriceLevelId"); b.Property<int>("ProductId"); b.HasKey("Id"); b.HasIndex("PriceLevelId"); b.HasIndex("ProductId"); b.ToTable("ProductPricelevel"); }); modelBuilder.Entity("tibs.stem.ProductSpecificationDetails.ProductSpecificationDetail", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AttributeGroupId"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int>("ProductSpecificationId"); b.HasKey("Id"); b.HasIndex("AttributeGroupId"); b.HasIndex("ProductSpecificationId"); b.ToTable("ProductSpecificationDetail"); }); modelBuilder.Entity("tibs.stem.ProductSpecifications.ProductSpecification", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<bool>("BafcoMade"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("Description"); b.Property<string>("ImageUrl"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name"); b.Property<int?>("ProductGroupId"); b.Property<bool>("Reset"); b.HasKey("Id"); b.HasIndex("ProductGroupId"); b.ToTable("ProductSpecification"); }); modelBuilder.Entity("tibs.stem.ProductSubGroups.ProductSubGroup", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int>("GroupId"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("ProductSubGroupCode") .IsRequired(); b.Property<string>("ProductSubGroupName") .IsRequired(); b.HasKey("Id"); b.HasIndex("GroupId"); b.ToTable("ProductSubGroup"); }); modelBuilder.Entity("tibs.stem.ProductTypes.ProductType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("ProductTypeCode"); b.Property<string>("ProductTypeName"); b.HasKey("Id"); b.ToTable("ProductType"); }); modelBuilder.Entity("tibs.stem.ProdutSpecLinks.ProdutSpecLink", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AttributeGroupId"); b.Property<int>("AttributeId"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int>("ProductGroupId"); b.Property<int?>("ProductSpecificationId"); b.HasKey("Id"); b.HasIndex("AttributeGroupId"); b.HasIndex("AttributeId"); b.HasIndex("ProductGroupId"); b.HasIndex("ProductSpecificationId"); b.ToTable("ProdutSpecLink"); }); modelBuilder.Entity("tibs.stem.QuotationProducts.QuotationProduct", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<bool>("Approval"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<decimal>("Discount"); b.Property<bool?>("Discountable"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<bool>("Locked"); b.Property<decimal>("OverAllDiscount"); b.Property<decimal>("OverAllPrice"); b.Property<string>("ProductCode"); b.Property<int?>("ProductId"); b.Property<decimal>("Quantity"); b.Property<int>("QuotationId"); b.Property<int?>("SectionId"); b.Property<string>("TemporaryCode"); b.Property<int?>("TemporaryProductId"); b.Property<decimal>("TotalAmount"); b.Property<decimal>("UnitOfMeasurement"); b.Property<decimal>("UnitOfPrice"); b.HasKey("Id"); b.HasIndex("ProductId"); b.HasIndex("QuotationId"); b.HasIndex("SectionId"); b.HasIndex("TemporaryProductId"); b.ToTable("QuotationProduct"); }); modelBuilder.Entity("tibs.stem.Quotations.Quotation", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<bool?>("Archieved"); b.Property<int?>("AttentionContactId"); b.Property<int?>("CompatitorId"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("CustomerId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("Email"); b.Property<int?>("InquiryId"); b.Property<bool>("IsApproved"); b.Property<bool?>("IsClosed"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsVat"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<bool>("Lost"); b.Property<DateTime?>("LostDate"); b.Property<int?>("MileStoneId"); b.Property<string>("MobileNumber"); b.Property<string>("Name"); b.Property<bool>("Negotiation"); b.Property<DateTime?>("NegotiationDate"); b.Property<int?>("NewCompanyId"); b.Property<bool>("Optional"); b.Property<DateTime>("OrgDate"); b.Property<int>("OverAllDiscountAmount"); b.Property<int>("OverAllDiscountPercentage"); b.Property<string>("PONumber"); b.Property<int>("QuotationStatusId"); b.Property<string>("RFQNo"); b.Property<int?>("ReasonId"); b.Property<string>("ReasonRemark"); b.Property<string>("RefNo"); b.Property<string>("RefQNo"); b.Property<bool>("Revised"); b.Property<int?>("RevisionId"); b.Property<long?>("SalesPersonId"); b.Property<int?>("StageId"); b.Property<bool>("Submitted"); b.Property<DateTime?>("SubmittedDate"); b.Property<string>("TermsandCondition"); b.Property<int>("Total"); b.Property<int>("Vat"); b.Property<int>("VatAmount"); b.Property<bool>("Void"); b.Property<bool>("Won"); b.Property<DateTime?>("WonDate"); b.HasKey("Id"); b.HasIndex("AttentionContactId"); b.HasIndex("CompatitorId"); b.HasIndex("InquiryId"); b.HasIndex("MileStoneId"); b.HasIndex("NewCompanyId"); b.HasIndex("QuotationStatusId"); b.HasIndex("ReasonId"); b.HasIndex("SalesPersonId"); b.HasIndex("StageId"); b.ToTable("Quotation"); }); modelBuilder.Entity("tibs.stem.QuotationStatuss.QuotationStatus", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Code"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("QuotationStatus"); }); modelBuilder.Entity("tibs.stem.Region.RegionCity", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<int>("CityId"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int>("RegionId"); b.HasKey("Id"); b.HasIndex("CityId"); b.HasIndex("RegionId"); b.ToTable("RegionCity"); }); modelBuilder.Entity("tibs.stem.Region.Regions", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("RegionCode") .IsRequired(); b.Property<string>("RegionName") .IsRequired(); b.HasKey("Id"); b.ToTable("Region"); }); modelBuilder.Entity("tibs.stem.Sections.Section", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name"); b.Property<int>("QuotationId"); b.HasKey("Id"); b.HasIndex("QuotationId"); b.ToTable("Section"); }); modelBuilder.Entity("tibs.stem.Sources.Source", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ColorCode"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("SourceCode") .IsRequired(); b.Property<string>("SourceName") .IsRequired(); b.Property<int>("TypeId"); b.HasKey("Id"); b.HasIndex("TypeId"); b.ToTable("Source"); }); modelBuilder.Entity("tibs.stem.SourceTypes.SourceType", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("SourceTypeCode") .IsRequired(); b.Property<string>("SourceTypeName") .IsRequired(); b.HasKey("Id"); b.ToTable("SourceType"); }); modelBuilder.Entity("tibs.stem.Stagestates.Stagestate", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Stagestate"); }); modelBuilder.Entity("tibs.stem.Storage.BinaryObject", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<byte[]>("Bytes") .IsRequired(); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AppBinaryObjects"); }); modelBuilder.Entity("tibs.stem.Team.Teams", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int>("DepartmentId"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name"); b.Property<long>("SalesManagerId"); b.HasKey("Id"); b.HasIndex("DepartmentId"); b.HasIndex("SalesManagerId"); b.ToTable("Teams"); }); modelBuilder.Entity("tibs.stem.TeamDetails.TeamDetail", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<long>("SalesmanId"); b.Property<int?>("TeamId"); b.HasKey("Id"); b.HasIndex("SalesmanId"); b.HasIndex("TeamId"); b.ToTable("TeamDetail"); }); modelBuilder.Entity("tibs.stem.TemporaryProducts.TemporaryProduct", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int?>("Depth"); b.Property<string>("Description"); b.Property<string>("Gpcode"); b.Property<int?>("Height"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<decimal?>("Price"); b.Property<string>("ProductCode"); b.Property<string>("ProductName"); b.Property<string>("SuspectCode"); b.Property<bool>("Updated"); b.Property<int?>("Width"); b.HasKey("Id"); b.ToTable("TemporaryProduct"); }); modelBuilder.Entity("tibs.stem.TemporaryProducts.TemporaryProductImage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("ImageUrl"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int>("TemporaryProductId"); b.HasKey("Id"); b.HasIndex("TemporaryProductId"); b.ToTable("TemporaryProductImages"); }); modelBuilder.Entity("tibs.stem.TitleOfCourtes.TitleOfCourtesy", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("TitleOfCourtesy"); }); modelBuilder.Entity("tibs.stem.UserDesignations.UserDesignation", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("UserDesignation"); }); modelBuilder.Entity("tibs.stem.Ybafcos.Ybafco", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("YbafcoCode"); b.Property<string>("YbafcoName"); b.HasKey("Id"); b.ToTable("Ybafco"); }); modelBuilder.Entity("tibs.stem.Editions.SubscribableEdition", b => { b.HasBaseType("Abp.Application.Editions.Edition"); b.Property<decimal?>("AnnualPrice"); b.Property<int?>("ExpiringEditionId"); b.Property<decimal?>("MonthlyPrice"); b.Property<int?>("TrialDayCount"); b.Property<int?>("WaitingDayAfterExpire"); b.ToTable("AbpEditions"); b.HasDiscriminator().HasValue("SubscribableEdition"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("EditionId"); b.HasIndex("EditionId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("EditionFeatureSetting"); }); modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("TenantId"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("TenantFeatureSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<int>("RoleId"); b.HasIndex("RoleId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("RolePermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<long>("UserId"); b.HasIndex("UserId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("UserPermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.HasOne("tibs.stem.Authorization.Roles.Role") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.HasOne("tibs.stem.Authorization.Users.User") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.HasOne("tibs.stem.Authorization.Users.User") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.HasOne("tibs.stem.Authorization.Users.User") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.HasOne("tibs.stem.Authorization.Users.User") .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.HasOne("tibs.stem.Authorization.Users.User") .WithMany("Settings") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.HasOne("Abp.Organizations.OrganizationUnit", "Parent") .WithMany("Children") .HasForeignKey("ParentId"); }); modelBuilder.Entity("tibs.stem.AbpSalesCoOrinators.AbpSalesCoOrinator", b => { b.HasOne("tibs.stem.Authorization.Users.User", "Coordinator") .WithMany() .HasForeignKey("CoordinatorId"); b.HasOne("tibs.stem.Authorization.Users.User", "AbpUser") .WithMany() .HasForeignKey("UserId"); }); modelBuilder.Entity("tibs.stem.AcitivityTracks.AcitivityTrack", b => { b.HasOne("tibs.stem.Activities.Activity", "Activity") .WithMany() .HasForeignKey("ActivityId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("tibs.stem.NewCustomerCompanys.NewContact", "NewContacts") .WithMany() .HasForeignKey("ContactId"); b.HasOne("tibs.stem.Inquirys.Inquiry", "Enquiry") .WithMany() .HasForeignKey("EnquiryId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.ActivityTrackComments.ActivityTrackComment", b => { b.HasOne("tibs.stem.AcitivityTracks.AcitivityTrack", "ActivityTrack") .WithMany() .HasForeignKey("ActivityTrackId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.AttributeGroupDetails.AttributeGroupDetail", b => { b.HasOne("tibs.stem.ProductAttributeGroups.ProductAttributeGroup", "AttributeGroups") .WithMany() .HasForeignKey("AttributeGroupId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("tibs.stem.ProductAttributes.ProductAttribute", "Attributes") .WithMany() .HasForeignKey("AttributeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.Authorization.Roles.Role", b => { b.HasOne("tibs.stem.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("tibs.stem.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("tibs.stem.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("tibs.stem.Authorization.Users.User", b => { b.HasOne("tibs.stem.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("tibs.stem.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("tibs.stem.Departments.Department", "Departments") .WithMany() .HasForeignKey("DepartmentId"); b.HasOne("tibs.stem.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); b.HasOne("tibs.stem.UserDesignations.UserDesignation", "UserDesignations") .WithMany() .HasForeignKey("UserDesignationId"); }); modelBuilder.Entity("tibs.stem.Citys.City", b => { b.HasOne("tibs.stem.Countrys.Country", "Country") .WithMany() .HasForeignKey("CountryId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.Companies.Company", b => { b.HasOne("tibs.stem.Authorization.Users.User", "AbpAccountManager") .WithMany() .HasForeignKey("AccountManagerId"); b.HasOne("tibs.stem.Citys.City", "Cities") .WithMany() .HasForeignKey("CityId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("tibs.stem.CustomerTypes.CustomerType", "CustomerTypes") .WithMany() .HasForeignKey("CustomerTypeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.CompanyContacts.CompanyContact", b => { b.HasOne("tibs.stem.Companies.Company", "Companies") .WithMany() .HasForeignKey("CompanyId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("tibs.stem.Designations.Designation", "Desiginations") .WithMany() .HasForeignKey("DesiginationId"); b.HasOne("tibs.stem.TitleOfCourtes.TitleOfCourtesy", "TitleOfCourtesies") .WithMany() .HasForeignKey("TitleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.EnquiryContacts.EnquiryContact", b => { b.HasOne("tibs.stem.NewCustomerCompanys.NewContact", "Contacts") .WithMany() .HasForeignKey("ContactId"); b.HasOne("tibs.stem.Inquirys.Inquiry", "Inquiry") .WithMany() .HasForeignKey("InquiryId"); }); modelBuilder.Entity("tibs.stem.EnquiryDetails.EnquiryDetail", b => { b.HasOne("tibs.stem.Authorization.Users.User", "AbpAccountManager") .WithMany() .HasForeignKey("AssignedbyId"); b.HasOne("tibs.stem.NewCustomerCompanys.NewCompany", "Companys") .WithMany() .HasForeignKey("CompanyId"); b.HasOne("tibs.stem.NewCustomerCompanys.NewCompany", "Compatitor") .WithMany() .HasForeignKey("CompatitorsId"); b.HasOne("tibs.stem.NewCustomerCompanys.NewContact", "Contacts") .WithMany() .HasForeignKey("ContactId"); b.HasOne("tibs.stem.Departments.Department", "Departments") .WithMany() .HasForeignKey("DepartmentId"); b.HasOne("tibs.stem.Designations.Designation", "Designations") .WithMany() .HasForeignKey("DesignationId"); b.HasOne("tibs.stem.Inquirys.Inquiry", "Inquirys") .WithMany() .HasForeignKey("InquiryId"); b.HasOne("tibs.stem.LeadTypes.LeadType", "LeadTypes") .WithMany() .HasForeignKey("LeadTypeId"); b.HasOne("tibs.stem.Team.Teams", "Team") .WithMany() .HasForeignKey("TeamId"); }); modelBuilder.Entity("tibs.stem.EnquirySources.EnquirySource", b => { b.HasOne("tibs.stem.Inquirys.Inquiry", "Inquiry") .WithMany() .HasForeignKey("InquiryId"); b.HasOne("tibs.stem.Sources.Source", "Source") .WithMany() .HasForeignKey("SourceId"); }); modelBuilder.Entity("tibs.stem.EnquiryStatuss.EnquiryStatus", b => { b.HasOne("tibs.stem.Stagestates.Stagestate", "Stagestatess") .WithMany() .HasForeignKey("StagestateId"); }); modelBuilder.Entity("tibs.stem.ImportHistorys.ImportHistory", b => { b.HasOne("tibs.stem.Quotations.Quotation", "Quotations") .WithMany() .HasForeignKey("QuotationId"); }); modelBuilder.Entity("tibs.stem.Inquirys.Inquiry", b => { b.HasOne("tibs.stem.NewCustomerCompanys.NewCompany", "Companys") .WithMany() .HasForeignKey("CompanyId"); b.HasOne("tibs.stem.Departments.Department", "Departments") .WithMany() .HasForeignKey("DepartmentId"); b.HasOne("tibs.stem.Designations.Designation", "Designations") .WithMany() .HasForeignKey("DesignationId"); b.HasOne("tibs.stem.LeadStatuss.LeadStatus", "LeadStatuss") .WithMany() .HasForeignKey("LeadStatusId"); b.HasOne("tibs.stem.Locations.Location", "Locations") .WithMany() .HasForeignKey("LocationId"); b.HasOne("tibs.stem.Milestones.MileStone", "MileStones") .WithMany() .HasForeignKey("MileStoneId"); b.HasOne("tibs.stem.OpportunitySources.OpportunitySource", "opportunitySource") .WithMany() .HasForeignKey("OpportunitySourceId"); b.HasOne("tibs.stem.EnquiryStatuss.EnquiryStatus", "EnqStatus") .WithMany() .HasForeignKey("StatusId"); b.HasOne("tibs.stem.Ybafcos.Ybafco", "whyBafco") .WithMany() .HasForeignKey("WhyBafcoId"); }); modelBuilder.Entity("tibs.stem.Inquirys.JobActivity", b => { b.HasOne("tibs.stem.Authorization.Users.User", "Designer") .WithMany() .HasForeignKey("DesignerId"); b.HasOne("tibs.stem.Inquirys.Inquiry", "Inquiry") .WithMany() .HasForeignKey("InquiryId"); }); modelBuilder.Entity("tibs.stem.LeadDetails.LeadDetail", b => { b.HasOne("tibs.stem.Authorization.Users.User", "Coordinators") .WithMany() .HasForeignKey("CoordinatorId"); b.HasOne("tibs.stem.Authorization.Users.User", "Designers") .WithMany() .HasForeignKey("DesignerId"); b.HasOne("tibs.stem.Inquirys.Inquiry", "Inquirys") .WithMany() .HasForeignKey("InquiryId"); b.HasOne("tibs.stem.LeadSources.LeadSource", "LeadSources") .WithMany() .HasForeignKey("LeadSourceId"); b.HasOne("tibs.stem.LeadTypes.LeadType", "LeadTypes") .WithMany() .HasForeignKey("LeadTypeId"); b.HasOne("tibs.stem.Authorization.Users.User", "SalesManagers") .WithMany() .HasForeignKey("SalesManagerId"); }); modelBuilder.Entity("tibs.stem.Locations.Location", b => { b.HasOne("tibs.stem.Citys.City", "citys") .WithMany() .HasForeignKey("CityId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.Milestones.MileStone", b => { b.HasOne("tibs.stem.SourceTypes.SourceType", "SourceTypes") .WithMany() .HasForeignKey("SourceTypeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.Milestones.StageDetails", b => { b.HasOne("tibs.stem.Milestones.MileStone", "MileStones") .WithMany() .HasForeignKey("MileStoneId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("tibs.stem.EnquiryStatuss.EnquiryStatus", "EnquiryStatuss") .WithMany() .HasForeignKey("StageId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.MultiTenancy.Payments.SubscriptionPayment", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.MultiTenancy.Tenant", b => { b.HasOne("tibs.stem.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("tibs.stem.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId"); b.HasOne("tibs.stem.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("tibs.stem.NewCustomerCompanys.NewAddressInfo", b => { b.HasOne("tibs.stem.Citys.City", "Citys") .WithMany() .HasForeignKey("CityId"); b.HasOne("tibs.stem.NewCustomerCompanys.NewCompany", "NewCompanys") .WithMany() .HasForeignKey("NewCompanyId"); b.HasOne("tibs.stem.NewCustomerCompanys.NewContact", "NewContacts") .WithMany() .HasForeignKey("NewContacId"); b.HasOne("tibs.stem.NewCustomerCompanys.NewInfoType", "NewInfoTypes") .WithMany() .HasForeignKey("NewInfoTypeId"); }); modelBuilder.Entity("tibs.stem.NewCustomerCompanys.NewCompany", b => { b.HasOne("tibs.stem.Authorization.Users.User", "AbpAccountManager") .WithMany() .HasForeignKey("AccountManagerId"); b.HasOne("tibs.stem.Authorization.Users.User", "AbpApprovedBy") .WithMany() .HasForeignKey("ApprovedById"); b.HasOne("tibs.stem.Industrys.Industry", "Industries") .WithMany() .HasForeignKey("IndustryId"); b.HasOne("tibs.stem.NewCustomerCompanys.NewCustomerType", "NewCustomerTypes") .WithMany() .HasForeignKey("NewCustomerTypeId"); }); modelBuilder.Entity("tibs.stem.NewCustomerCompanys.NewContact", b => { b.HasOne("tibs.stem.Designations.Designation", "Designations") .WithMany() .HasForeignKey("DesignationId"); b.HasOne("tibs.stem.NewCustomerCompanys.NewCompany", "NewCompanys") .WithMany() .HasForeignKey("NewCompanyId"); b.HasOne("tibs.stem.NewCustomerCompanys.NewCustomerType", "NewCustomerTypes") .WithMany() .HasForeignKey("NewCustomerTypeId"); b.HasOne("tibs.stem.TitleOfCourtes.TitleOfCourtesy", "TitleOfCourtesies") .WithMany() .HasForeignKey("TitleId"); }); modelBuilder.Entity("tibs.stem.NewCustomerCompanys.NewContactInfo", b => { b.HasOne("tibs.stem.NewCustomerCompanys.NewCompany", "NewCompanys") .WithMany() .HasForeignKey("NewCompanyId"); b.HasOne("tibs.stem.NewCustomerCompanys.NewContact", "NewContacts") .WithMany() .HasForeignKey("NewContacId"); b.HasOne("tibs.stem.NewCustomerCompanys.NewInfoType", "NewInfoTypes") .WithMany() .HasForeignKey("NewInfoTypeId"); }); modelBuilder.Entity("tibs.stem.ProductFamilys.ProductFamily", b => { b.HasOne("tibs.stem.Collections.Collection", "Collections") .WithMany() .HasForeignKey("CollectionId"); }); modelBuilder.Entity("tibs.stem.ProductGroups.ProductGroup", b => { b.HasOne("tibs.stem.ProductFamilys.ProductFamily", "prodFamily") .WithMany() .HasForeignKey("FamilyId"); b.HasOne("tibs.stem.ProductCategorys.ProductCategory", "ProductCategorys") .WithMany() .HasForeignKey("ProductCategoryId"); }); modelBuilder.Entity("tibs.stem.ProductGroups.ProductGroupDetail", b => { b.HasOne("tibs.stem.ProductAttributeGroups.ProductAttributeGroup", "ProductAttributeGroups") .WithMany() .HasForeignKey("AttributeGroupId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("tibs.stem.ProductGroups.ProductGroup", "ProductGroups") .WithMany() .HasForeignKey("ProductGroupId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.ProductImageUrls.ProductImageUrl", b => { b.HasOne("tibs.stem.Products.Product", "Products") .WithMany() .HasForeignKey("ProductId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.Products.Product", b => { b.HasOne("tibs.stem.ProductSpecifications.ProductSpecification", "ProductSpecifications") .WithMany() .HasForeignKey("ProductSpecificationId"); }); modelBuilder.Entity("tibs.stem.Products.ProductPricelevel", b => { b.HasOne("tibs.stem.PriceLevels.PriceLevel", "PriceLevels") .WithMany() .HasForeignKey("PriceLevelId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("tibs.stem.Products.Product", "Products") .WithMany() .HasForeignKey("ProductId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.ProductSpecificationDetails.ProductSpecificationDetail", b => { b.HasOne("tibs.stem.ProductAttributeGroups.ProductAttributeGroup", "ProductAttributeGroups") .WithMany() .HasForeignKey("AttributeGroupId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("tibs.stem.ProductSpecifications.ProductSpecification", "ProductSpecifications") .WithMany() .HasForeignKey("ProductSpecificationId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.ProductSpecifications.ProductSpecification", b => { b.HasOne("tibs.stem.ProductGroups.ProductGroup", "ProductGroups") .WithMany() .HasForeignKey("ProductGroupId"); }); modelBuilder.Entity("tibs.stem.ProductSubGroups.ProductSubGroup", b => { b.HasOne("tibs.stem.ProductGroups.ProductGroup", "productGroups") .WithMany() .HasForeignKey("GroupId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.ProdutSpecLinks.ProdutSpecLink", b => { b.HasOne("tibs.stem.ProductAttributeGroups.ProductAttributeGroup", "AttributeGroups") .WithMany() .HasForeignKey("AttributeGroupId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("tibs.stem.ProductAttributes.ProductAttribute", "Attributes") .WithMany() .HasForeignKey("AttributeId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("tibs.stem.ProductGroups.ProductGroup", "ProductGroups") .WithMany() .HasForeignKey("ProductGroupId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("tibs.stem.ProductSpecifications.ProductSpecification", "ProductSpecifications") .WithMany() .HasForeignKey("ProductSpecificationId"); }); modelBuilder.Entity("tibs.stem.QuotationProducts.QuotationProduct", b => { b.HasOne("tibs.stem.Products.Product", "product") .WithMany() .HasForeignKey("ProductId"); b.HasOne("tibs.stem.Quotations.Quotation", "quotation") .WithMany() .HasForeignKey("QuotationId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("tibs.stem.Sections.Section", "section") .WithMany() .HasForeignKey("SectionId"); b.HasOne("tibs.stem.TemporaryProducts.TemporaryProduct", "TemporaryProducts") .WithMany() .HasForeignKey("TemporaryProductId"); }); modelBuilder.Entity("tibs.stem.Quotations.Quotation", b => { b.HasOne("tibs.stem.NewCustomerCompanys.NewContact", "AttentionContact") .WithMany() .HasForeignKey("AttentionContactId"); b.HasOne("tibs.stem.NewCustomerCompanys.NewCompany", "Compatitors") .WithMany() .HasForeignKey("CompatitorId"); b.HasOne("tibs.stem.Inquirys.Inquiry", "Inquiry") .WithMany() .HasForeignKey("InquiryId"); b.HasOne("tibs.stem.Milestones.MileStone", "MileStones") .WithMany() .HasForeignKey("MileStoneId"); b.HasOne("tibs.stem.NewCustomerCompanys.NewCompany", "NewCompanys") .WithMany() .HasForeignKey("NewCompanyId"); b.HasOne("tibs.stem.QuotationStatuss.QuotationStatus", "Quotationstatus") .WithMany() .HasForeignKey("QuotationStatusId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("tibs.stem.LeadReasons.LeadReason", "LostReason") .WithMany() .HasForeignKey("ReasonId"); b.HasOne("tibs.stem.Authorization.Users.User", "SalesPerson") .WithMany() .HasForeignKey("SalesPersonId"); b.HasOne("tibs.stem.EnquiryStatuss.EnquiryStatus", "EnqStatus") .WithMany() .HasForeignKey("StageId"); }); modelBuilder.Entity("tibs.stem.Region.RegionCity", b => { b.HasOne("tibs.stem.Citys.City", "Citys") .WithMany() .HasForeignKey("CityId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("tibs.stem.Region.Regions", "Regions") .WithMany() .HasForeignKey("RegionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.Sections.Section", b => { b.HasOne("tibs.stem.Quotations.Quotation", "quotation") .WithMany() .HasForeignKey("QuotationId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.Sources.Source", b => { b.HasOne("tibs.stem.SourceTypes.SourceType", "SourceTypes") .WithMany() .HasForeignKey("TypeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.Team.Teams", b => { b.HasOne("tibs.stem.Departments.Department", "Department") .WithMany() .HasForeignKey("DepartmentId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("tibs.stem.Authorization.Users.User", "SalesManager") .WithMany() .HasForeignKey("SalesManagerId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("tibs.stem.TeamDetails.TeamDetail", b => { b.HasOne("tibs.stem.Authorization.Users.User", "Salesman") .WithMany() .HasForeignKey("SalesmanId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("tibs.stem.Team.Teams", "Team") .WithMany() .HasForeignKey("TeamId"); }); modelBuilder.Entity("tibs.stem.TemporaryProducts.TemporaryProductImage", b => { b.HasOne("tibs.stem.TemporaryProducts.TemporaryProduct", "TemporaryProducts") .WithMany() .HasForeignKey("TemporaryProductId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasOne("tibs.stem.Authorization.Roles.Role") .WithMany("Permissions") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasOne("tibs.stem.Authorization.Users.User") .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); } } }
31.309079
117
0.445975
[ "Apache-2.0" ]
realvino/Core-2.0
src/tibs.stem.EntityFrameworkCore/Migrations/20180321054229_alter-User-Add-Designation.Designer.cs
144,149
C#
namespace Intel.RealSense.Math { public struct Vertex { public float x; public float y; public float z; } }
14.4
30
0.5625
[ "Apache-2.0" ]
130s/librealsense
wrappers/csharp/Intel.RealSense/Types/Math/Vertex.cs
144
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Volo.Abp; namespace Bamboo.Account.Samples { [RemoteService] [Route("api/Account/sample")] public class SampleController : AccountController, ISampleAppService { private readonly ISampleAppService _sampleAppService; public SampleController(ISampleAppService sampleAppService) { _sampleAppService = sampleAppService; } [HttpGet] public async Task<SampleDto> GetAsync() { return await _sampleAppService.GetAsync(); } [HttpGet] [Route("authorized")] [Authorize] public async Task<SampleDto> GetAuthorizedAsync() { return await _sampleAppService.GetAsync(); } } }
24.794118
72
0.647687
[ "MIT" ]
BlazorHub/bamboomodules
Bamboo.Account/src/Bamboo.Account.HttpApi/Samples/SampleController.cs
845
C#
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; namespace AbpDemoThree.Authentication.JwtBearer { public static class JwtTokenMiddleware { public static IApplicationBuilder UseJwtTokenMiddleware(this IApplicationBuilder app, string schema = JwtBearerDefaults.AuthenticationScheme) { return app.Use(async (ctx, next) => { if (ctx.User.Identity?.IsAuthenticated != true) { var result = await ctx.AuthenticateAsync(schema); if (result.Succeeded && result.Principal != null) { ctx.User = result.Principal; } } await next(); }); } } }
31.740741
149
0.570595
[ "MIT" ]
YandongZhao/AbpDemoThree
aspnet-core/src/AbpDemoThree.Web.Core/Authentication/JwtBearer/JwtTokenMiddleware.cs
859
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Net; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Rest.Azure; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using Xunit; using ResourceIdentityType = Microsoft.Azure.Management.ResourceManager.Models.ResourceIdentityType; namespace Compute.Tests.DiskRPTests { public class DiskRPTestsBase : VMTestBase { protected const string DiskNamePrefix = "diskrp"; private string DiskRPLocation = ComputeManagementTestUtilities.DefaultLocation.ToLower(); #region Execution protected void Disk_CRUD_Execute(string diskCreateOption, string methodName, int? diskSizeGB = null, string location = null, IList<string> zones = null) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); DiskRPLocation = location ?? DiskRPLocation; // Data var rgName = TestUtilities.GenerateName(TestPrefix); var diskName = TestUtilities.GenerateName(DiskNamePrefix); Disk disk = GenerateDefaultDisk(diskCreateOption, rgName, diskSizeGB, zones, location); try { // ********** // SETUP // ********** // Create resource group, unless create option is import in which case resource group will be created with vm, // or copy in which casethe resource group will be created with the original disk. if (diskCreateOption != DiskCreateOption.Import && diskCreateOption != DiskCreateOption.Copy) { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = DiskRPLocation }); } // ********** // TEST // ********** // Put Disk diskOut = m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk); Validate(disk, diskOut, DiskRPLocation); // Get diskOut = m_CrpClient.Disks.Get(rgName, diskName); Validate(disk, diskOut, DiskRPLocation); // Get disk access AccessUri accessUri = m_CrpClient.Disks.GrantAccess(rgName, diskName, AccessDataDefault); Assert.NotNull(accessUri.AccessSAS); // Get diskOut = m_CrpClient.Disks.Get(rgName, diskName); Validate(disk, diskOut, DiskRPLocation); // Patch // TODO: Bug 9865640 - DiskRP doesn't follow patch semantics for zones: skip this for zones if (zones == null) { const string tagKey = "tageKey"; var updatedisk = new DiskUpdate(); updatedisk.Tags = new Dictionary<string, string>() { { tagKey, "tagvalue" } }; diskOut = m_CrpClient.Disks.Update(rgName, diskName, updatedisk); Validate(disk, diskOut, DiskRPLocation); } // Get diskOut = m_CrpClient.Disks.Get(rgName, diskName); Validate(disk, diskOut, DiskRPLocation); // End disk access m_CrpClient.Disks.RevokeAccess(rgName, diskName); // Delete m_CrpClient.Disks.Delete(rgName, diskName); try { // Ensure it was really deleted m_CrpClient.Disks.Get(rgName, diskName); Assert.False(true); } catch(CloudException ex) { Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode); } } finally { // Delete resource group m_ResourcesClient.ResourceGroups.Delete(rgName); } } } protected void Snapshot_CRUD_Execute(string diskCreateOption, string methodName, int? diskSizeGB = null, string location = null, bool incremental = false) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); DiskRPLocation = location ?? DiskRPLocation; // Data var rgName = TestUtilities.GenerateName(TestPrefix); var diskName = TestUtilities.GenerateName(DiskNamePrefix); var snapshotName = TestUtilities.GenerateName(DiskNamePrefix); Disk sourceDisk = GenerateDefaultDisk(diskCreateOption, rgName, diskSizeGB); try { // ********** // SETUP // ********** // Create resource group m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = DiskRPLocation }); // Put disk Disk diskOut = m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, sourceDisk); Validate(sourceDisk, diskOut, DiskRPLocation); // Generate snapshot using disk info Snapshot snapshot = GenerateDefaultSnapshot(diskOut.Id, incremental: incremental); // ********** // TEST // ********** // Put Snapshot snapshotOut = m_CrpClient.Snapshots.CreateOrUpdate(rgName, snapshotName, snapshot); Validate(snapshot, snapshotOut, incremental: incremental); // Get snapshotOut = m_CrpClient.Snapshots.Get(rgName, snapshotName); Validate(snapshot, snapshotOut, incremental: incremental); // Get access AccessUri accessUri = m_CrpClient.Snapshots.GrantAccess(rgName, snapshotName, AccessDataDefault); Assert.NotNull(accessUri.AccessSAS); // Get snapshotOut = m_CrpClient.Snapshots.Get(rgName, snapshotName); Validate(snapshot, snapshotOut, incremental: incremental); // Patch var updatesnapshot = new SnapshotUpdate(); const string tagKey = "tageKey"; updatesnapshot.Tags = new Dictionary<string, string>() { { tagKey, "tagvalue" } }; snapshotOut = m_CrpClient.Snapshots.Update(rgName, snapshotName, updatesnapshot); Validate(snapshot, snapshotOut, incremental: incremental); // Get snapshotOut = m_CrpClient.Snapshots.Get(rgName, snapshotName); Validate(snapshot, snapshotOut, incremental: incremental); // End access m_CrpClient.Snapshots.RevokeAccess(rgName, snapshotName); // Delete m_CrpClient.Snapshots.Delete(rgName, snapshotName); try { // Ensure it was really deleted m_CrpClient.Snapshots.Get(rgName, snapshotName); Assert.False(true); } catch (CloudException ex) { Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode); } } finally { // Delete resource group m_ResourcesClient.ResourceGroups.Delete(rgName); } } } protected void DiskEncryptionSet_CRUD_Execute(string methodName, string location = null) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); DiskRPLocation = location ?? DiskRPLocation; // Data var rgName = TestUtilities.GenerateName(TestPrefix); var desName = TestUtilities.GenerateName(DiskNamePrefix); DiskEncryptionSet des = GenerateDefaultDiskEncryptionSet(DiskRPLocation); try { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = DiskRPLocation }); // Put DiskEncryptionSet DiskEncryptionSet desOut = m_CrpClient.DiskEncryptionSets.CreateOrUpdate(rgName, desName, des); Validate(des, desOut, desName); // Get DiskEncryptionSet desOut = m_CrpClient.DiskEncryptionSets.Get(rgName, desName); Validate(des, desOut, desName); // Patch DiskEncryptionSet const string tagKey = "tageKey"; var updateDes = new DiskEncryptionSetUpdate(); updateDes.Tags = new Dictionary<string, string>() { { tagKey, "tagvalue" } }; desOut = m_CrpClient.DiskEncryptionSets.Update(rgName, desName, updateDes); Validate(des, desOut, desName); Assert.Equal(1, desOut.Tags.Count); // Delete DiskEncryptionSet m_CrpClient.DiskEncryptionSets.Delete(rgName, desName); try { // Ensure it was really deleted m_CrpClient.DiskEncryptionSets.Get(rgName, desName); Assert.False(true); } catch (CloudException ex) { Assert.Equal(HttpStatusCode.NotFound, ex.Response.StatusCode); } } finally { // Delete resource group m_ResourcesClient.ResourceGroups.Delete(rgName); } } } protected void Disk_List_Execute(string diskCreateOption, string methodName, int? diskSizeGB = null, string location = null) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); DiskRPLocation = location ?? DiskRPLocation; // Data var rgName1 = TestUtilities.GenerateName(TestPrefix); var rgName2 = TestUtilities.GenerateName(TestPrefix); var diskName1 = TestUtilities.GenerateName(DiskNamePrefix); var diskName2 = TestUtilities.GenerateName(DiskNamePrefix); Disk disk1 = GenerateDefaultDisk(diskCreateOption, rgName1, diskSizeGB, location: location); Disk disk2 = GenerateDefaultDisk(diskCreateOption, rgName2, diskSizeGB, location: location); try { // ********** // SETUP // ********** // Create resource groups, unless create option is import in which case resource group will be created with vm if (diskCreateOption != DiskCreateOption.Import) { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName1, new ResourceGroup { Location = DiskRPLocation }); m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName2, new ResourceGroup { Location = DiskRPLocation }); } // Put 4 disks, 2 in each resource group m_CrpClient.Disks.CreateOrUpdate(rgName1, diskName1, disk1); m_CrpClient.Disks.CreateOrUpdate(rgName1, diskName2, disk2); m_CrpClient.Disks.CreateOrUpdate(rgName2, diskName1, disk1); m_CrpClient.Disks.CreateOrUpdate(rgName2, diskName2, disk2); // ********** // TEST // ********** // List disks under resource group IPage<Disk> disksOut = m_CrpClient.Disks.ListByResourceGroup(rgName1); Assert.Equal(2, disksOut.Count()); Assert.Null(disksOut.NextPageLink); disksOut = m_CrpClient.Disks.ListByResourceGroup(rgName2); Assert.Equal(2, disksOut.Count()); Assert.Null(disksOut.NextPageLink); // List disks under subscription disksOut = m_CrpClient.Disks.List(); Assert.True(disksOut.Count() >= 4); if (disksOut.NextPageLink != null) { disksOut = m_CrpClient.Disks.ListNext(disksOut.NextPageLink); Assert.True(disksOut.Any()); } } finally { // Delete resource group m_ResourcesClient.ResourceGroups.Delete(rgName1); m_ResourcesClient.ResourceGroups.Delete(rgName2); } } } protected void Snapshot_List_Execute(string diskCreateOption, string methodName, int? diskSizeGB = null) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); // Data var rgName1 = TestUtilities.GenerateName(TestPrefix); var rgName2 = TestUtilities.GenerateName(TestPrefix); var diskName1 = TestUtilities.GenerateName(DiskNamePrefix); var diskName2 = TestUtilities.GenerateName(DiskNamePrefix); var snapshotName1 = TestUtilities.GenerateName(DiskNamePrefix); var snapshotName2 = TestUtilities.GenerateName(DiskNamePrefix); Disk disk1 = GenerateDefaultDisk(diskCreateOption, rgName1, diskSizeGB); Disk disk2 = GenerateDefaultDisk(diskCreateOption, rgName2, diskSizeGB); try { // ********** // SETUP // ********** // Create resource groups m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName1, new ResourceGroup { Location = DiskRPLocation }); m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName2, new ResourceGroup { Location = DiskRPLocation }); // Put 4 disks, 2 in each resource group Disk diskOut11 = m_CrpClient.Disks.CreateOrUpdate(rgName1, diskName1, disk1); Disk diskOut12 = m_CrpClient.Disks.CreateOrUpdate(rgName1, diskName2, disk2); Disk diskOut21 = m_CrpClient.Disks.CreateOrUpdate(rgName2, diskName1, disk1); Disk diskOut22 = m_CrpClient.Disks.CreateOrUpdate(rgName2, diskName2, disk2); // Generate 4 snapshots using disks info Snapshot snapshot11 = GenerateDefaultSnapshot(diskOut11.Id); Snapshot snapshot12 = GenerateDefaultSnapshot(diskOut12.Id, SnapshotStorageAccountTypes.StandardZRS); Snapshot snapshot21 = GenerateDefaultSnapshot(diskOut21.Id); Snapshot snapshot22 = GenerateDefaultSnapshot(diskOut22.Id); // Put 4 snapshots, 2 in each resource group m_CrpClient.Snapshots.CreateOrUpdate(rgName1, snapshotName1, snapshot11); m_CrpClient.Snapshots.CreateOrUpdate(rgName1, snapshotName2, snapshot12); m_CrpClient.Snapshots.CreateOrUpdate(rgName2, snapshotName1, snapshot21); m_CrpClient.Snapshots.CreateOrUpdate(rgName2, snapshotName2, snapshot22); // ********** // TEST // ********** // List snapshots under resource group IPage<Snapshot> snapshotsOut = m_CrpClient.Snapshots.ListByResourceGroup(rgName1); Assert.Equal(2, snapshotsOut.Count()); Assert.Null(snapshotsOut.NextPageLink); snapshotsOut = m_CrpClient.Snapshots.ListByResourceGroup(rgName2); Assert.Equal(2, snapshotsOut.Count()); Assert.Null(snapshotsOut.NextPageLink); // List snapshots under subscription snapshotsOut = m_CrpClient.Snapshots.List(); Assert.True(snapshotsOut.Count() >= 4); if (snapshotsOut.NextPageLink != null) { snapshotsOut = m_CrpClient.Snapshots.ListNext(snapshotsOut.NextPageLink); Assert.True(snapshotsOut.Any()); } } finally { // Delete resource group m_ResourcesClient.ResourceGroups.Delete(rgName1); m_ResourcesClient.ResourceGroups.Delete(rgName2); } } } protected void DiskEncryptionSet_List_Execute(string methodName, string location = null) { using (MockContext context = MockContext.Start(this.GetType(), methodName)) { EnsureClientsInitialized(context); DiskRPLocation = location ?? DiskRPLocation; // Data var rgName1 = TestUtilities.GenerateName(TestPrefix); var rgName2 = TestUtilities.GenerateName(TestPrefix); var desName1 = TestUtilities.GenerateName(DiskNamePrefix); var desName2 = TestUtilities.GenerateName(DiskNamePrefix); DiskEncryptionSet des1 = GenerateDefaultDiskEncryptionSet(DiskRPLocation); DiskEncryptionSet des2 = GenerateDefaultDiskEncryptionSet(DiskRPLocation); try { // ********** // SETUP // ********** // Create resource groups m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName1, new ResourceGroup { Location = DiskRPLocation }); m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName2, new ResourceGroup { Location = DiskRPLocation }); // Put 4 diskEncryptionSets, 2 in each resource group m_CrpClient.DiskEncryptionSets.CreateOrUpdate(rgName1, desName1, des1); m_CrpClient.DiskEncryptionSets.CreateOrUpdate(rgName1, desName2, des2); m_CrpClient.DiskEncryptionSets.CreateOrUpdate(rgName2, desName1, des1); m_CrpClient.DiskEncryptionSets.CreateOrUpdate(rgName2, desName2, des2); // ********** // TEST // ********** // List diskEncryptionSets under resource group IPage<DiskEncryptionSet> dessOut = m_CrpClient.DiskEncryptionSets.ListByResourceGroup(rgName1); Assert.Equal(2, dessOut.Count()); Assert.Null(dessOut.NextPageLink); dessOut = m_CrpClient.DiskEncryptionSets.ListByResourceGroup(rgName2); Assert.Equal(2, dessOut.Count()); Assert.Null(dessOut.NextPageLink); // List diskEncryptionSets under subscription dessOut = m_CrpClient.DiskEncryptionSets.List(); Assert.True(dessOut.Count() >= 4); if (dessOut.NextPageLink != null) { dessOut = m_CrpClient.DiskEncryptionSets.ListNext(dessOut.NextPageLink); Assert.True(dessOut.Any()); } // Delete diskEncryptionSets m_CrpClient.DiskEncryptionSets.Delete(rgName1, desName1); m_CrpClient.DiskEncryptionSets.Delete(rgName1, desName2); m_CrpClient.DiskEncryptionSets.Delete(rgName2, desName1); m_CrpClient.DiskEncryptionSets.Delete(rgName2, desName2); } finally { // Delete resource group m_ResourcesClient.ResourceGroups.Delete(rgName1); m_ResourcesClient.ResourceGroups.Delete(rgName2); } } } protected void DiskEncryptionSet_CreateDisk_Execute(string methodName, string location = null) { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); var rgName = TestUtilities.GenerateName(TestPrefix); var diskName = TestUtilities.GenerateName(DiskNamePrefix); var desName = "longlivedSwaggerDES"; Disk disk = GenerateDefaultDisk(DiskCreateOption.Empty, rgName, 10); disk.Location = location; try { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = location }); // Get DiskEncryptionSet DiskEncryptionSet desOut = m_CrpClient.DiskEncryptionSets.Get("longrunningrg-centraluseuap", desName); Assert.NotNull(desOut); disk.Encryption = new Encryption { Type = EncryptionType.EncryptionAtRestWithCustomerKey.ToString(), DiskEncryptionSetId = desOut.Id }; //Put Disk m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk); Disk diskOut = m_CrpClient.Disks.Get(rgName, diskName); Validate(disk, diskOut, disk.Location); Assert.Equal(desOut.Id.ToLower(), diskOut.Encryption.DiskEncryptionSetId.ToLower()); Assert.Equal(EncryptionType.EncryptionAtRestWithCustomerKey, diskOut.Encryption.Type); m_CrpClient.Disks.Delete(rgName, diskName); } finally { m_ResourcesClient.ResourceGroups.Delete(rgName); } } } protected void DiskEncryptionSet_UpdateDisk_Execute(string methodName, string location = null) { using (MockContext context = MockContext.Start(this.GetType())) { EnsureClientsInitialized(context); var rgName = TestUtilities.GenerateName(TestPrefix); var diskName = TestUtilities.GenerateName(DiskNamePrefix); var desName = "longlivedSwaggerDES"; Disk disk = GenerateDefaultDisk(DiskCreateOption.Empty, rgName, 10); disk.Location = location; try { m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = location }); // Put Disk with PlatformManagedKey m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk); Disk diskOut = m_CrpClient.Disks.Get(rgName, diskName); Validate(disk, diskOut, disk.Location); Assert.Null(diskOut.Encryption.DiskEncryptionSetId); Assert.Equal(EncryptionType.EncryptionAtRestWithPlatformKey, diskOut.Encryption.Type); // Update Disk with CustomerManagedKey DiskEncryptionSet desOut = m_CrpClient.DiskEncryptionSets.Get("longrunningrg-centraluseuap", desName); Assert.NotNull(desOut); disk.Encryption = new Encryption { Type = EncryptionType.EncryptionAtRestWithCustomerKey.ToString(), DiskEncryptionSetId = desOut.Id }; m_CrpClient.Disks.CreateOrUpdate(rgName, diskName, disk); diskOut = m_CrpClient.Disks.Get(rgName, diskName); Assert.Equal(desOut.Id.ToLower(), diskOut.Encryption.DiskEncryptionSetId.ToLower()); Assert.Equal(EncryptionType.EncryptionAtRestWithCustomerKey, diskOut.Encryption.Type); m_CrpClient.Disks.Delete(rgName, diskName); } finally { m_ResourcesClient.ResourceGroups.Delete(rgName); } } } #endregion #region Generation public static readonly GrantAccessData AccessDataDefault = new GrantAccessData { Access = AccessLevel.Read, DurationInSeconds = 1000 }; protected Disk GenerateDefaultDisk(string diskCreateOption, string rgName, int? diskSizeGB = null, IList<string> zones = null, string location = null) { Disk disk; switch (diskCreateOption) { case "Upload": disk = GenerateBaseDisk(diskCreateOption); disk.CreationData.UploadSizeBytes = (long) (diskSizeGB ?? 10) * 1024 * 1024 * 1024 + 512; break; case "Empty": disk = GenerateBaseDisk(diskCreateOption); disk.DiskSizeGB = diskSizeGB; disk.Zones = zones; break; case "Import": disk = GenerateImportDisk(diskCreateOption, rgName, location); disk.DiskSizeGB = diskSizeGB; disk.Zones = zones; break; case "Copy": disk = GenerateCopyDisk(rgName, diskSizeGB ?? 10, location); disk.Zones = zones; break; default: throw new ArgumentOutOfRangeException("diskCreateOption", diskCreateOption, "Unsupported option provided."); } return disk; } /// <summary> /// Generates a disk used when the DiskCreateOption is Import /// </summary> /// <returns></returns> private Disk GenerateImportDisk(string diskCreateOption, string rgName, string location) { // Create a VM, so we can use its OS disk for creating the image string storageAccountName = ComputeManagementTestUtilities.GenerateName(DiskNamePrefix); string asName = ComputeManagementTestUtilities.GenerateName("as"); ImageReference imageRef = GetPlatformVMImage(useWindowsImage: true); VirtualMachine inputVM = null; m_location = location; // Create Storage Account var storageAccountOutput = CreateStorageAccount(rgName, storageAccountName); // Create the VM, whose OS disk will be used in creating the image var createdVM = CreateVM(rgName, asName, storageAccountOutput, imageRef, out inputVM); var listResponse = m_CrpClient.VirtualMachines.ListAll(); Assert.True(listResponse.Count() >= 1); string[] id = createdVM.Id.Split('/'); string subscription = id[2]; var uri = createdVM.StorageProfile.OsDisk.Vhd.Uri; m_CrpClient.VirtualMachines.Delete(rgName, inputVM.Name); m_CrpClient.VirtualMachines.Delete(rgName, createdVM.Name); Disk disk = GenerateBaseDisk(diskCreateOption); disk.CreationData.SourceUri = uri; disk.CreationData.StorageAccountId = "/subscriptions/" + subscription + "/resourceGroups/" + rgName + "/providers/Microsoft.Storage/storageAccounts/" + storageAccountName; return disk; } /// <summary> /// Generates a disk used when the DiskCreateOption is Copy /// </summary> /// <returns></returns> private Disk GenerateCopyDisk(string rgName, int diskSizeGB, string location) { // Create an empty disk Disk originalDisk = GenerateDefaultDisk("Empty", rgName, diskSizeGB: diskSizeGB); m_ResourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = location }); Disk diskOut = m_CrpClient.Disks.CreateOrUpdate(rgName, TestUtilities.GenerateName(DiskNamePrefix + "_original"), originalDisk); Snapshot snapshot = GenerateDefaultSnapshot(diskOut.Id); Snapshot snapshotOut = m_CrpClient.Snapshots.CreateOrUpdate(rgName, "snapshotswaaggertest", snapshot); Disk copyDisk = GenerateBaseDisk("Import"); copyDisk.CreationData.SourceResourceId = snapshotOut.Id; return copyDisk; } protected DiskEncryptionSet GenerateDefaultDiskEncryptionSet(string location) { string testVaultId = @"/subscriptions/0296790d-427c-48ca-b204-8b729bbd8670/resourcegroups/swagger/providers/Microsoft.KeyVault/vaults/swaggervault"; string encryptionKeyUri = @"https://swaggervault.vault.azure.net/keys/diskRPSSEKey/4780bcaf12384596b75cf63731f2046c"; var des = new DiskEncryptionSet { Identity = new EncryptionSetIdentity { Type = ResourceIdentityType.SystemAssigned.ToString() }, Location = location, ActiveKey = new KeyVaultAndKeyReference { SourceVault = new SourceVault { Id = testVaultId }, KeyUrl = encryptionKeyUri } }; return des; } public Disk GenerateBaseDisk(string diskCreateOption) { var disk = new Disk { Location = DiskRPLocation, }; disk.Sku = new DiskSku() { Name = StorageAccountTypes.StandardLRS }; disk.CreationData = new CreationData() { CreateOption = diskCreateOption, }; disk.OsType = OperatingSystemTypes.Linux; return disk; } protected Snapshot GenerateDefaultSnapshot(string sourceDiskId, string snapshotStorageAccountTypes = "Standard_LRS", bool incremental = false) { Snapshot snapshot = GenerateBaseSnapshot(sourceDiskId, snapshotStorageAccountTypes, incremental); return snapshot; } private Snapshot GenerateBaseSnapshot(string sourceDiskId, string snapshotStorageAccountTypes, bool incremental = false) { var snapshot = new Snapshot() { Location = DiskRPLocation, Incremental = incremental }; snapshot.Sku = new SnapshotSku() { Name = snapshotStorageAccountTypes ?? SnapshotStorageAccountTypes.StandardLRS }; snapshot.CreationData = new CreationData() { CreateOption = DiskCreateOption.Copy, SourceResourceId = sourceDiskId, }; return snapshot; } #endregion #region Validation private void Validate(DiskEncryptionSet diskEncryptionSetExpected, DiskEncryptionSet diskEncryptionSetActual, string expectedDESName) { Assert.Equal(expectedDESName, diskEncryptionSetActual.Name); Assert.Equal(diskEncryptionSetExpected.Location, diskEncryptionSetActual.Location); Assert.Equal(diskEncryptionSetExpected.ActiveKey.SourceVault.Id, diskEncryptionSetActual.ActiveKey.SourceVault.Id); Assert.Equal(diskEncryptionSetExpected.ActiveKey.KeyUrl, diskEncryptionSetActual.ActiveKey.KeyUrl); Assert.NotNull(diskEncryptionSetActual.Identity); Assert.Equal(ResourceIdentityType.SystemAssigned.ToString(), diskEncryptionSetActual.Identity.Type); } private void Validate(Snapshot snapshotExpected, Snapshot snapshotActual, bool diskHydrated = false, bool incremental = false) { // snapshot resource Assert.Equal(string.Format("{0}/{1}", ApiConstants.ResourceProviderNamespace, "snapshots"), snapshotActual.Type); Assert.NotNull(snapshotActual.Name); Assert.Equal(DiskRPLocation, snapshotActual.Location); // snapshot properties Assert.Equal(snapshotExpected.Sku.Name, snapshotActual.Sku.Name); Assert.True(snapshotActual.ManagedBy == null); Assert.NotNull(snapshotActual.ProvisioningState); Assert.Equal(incremental, snapshotActual.Incremental); Assert.NotNull(snapshotActual.CreationData.SourceUniqueId); if (snapshotExpected.OsType != null) //these properties are not mandatory for the client { Assert.Equal(snapshotExpected.OsType, snapshotActual.OsType); } if (snapshotExpected.DiskSizeGB != null) { // Disk resizing Assert.Equal(snapshotExpected.DiskSizeGB, snapshotActual.DiskSizeGB); } // Creation data CreationData creationDataExp = snapshotExpected.CreationData; CreationData creationDataAct = snapshotActual.CreationData; Assert.Equal(creationDataExp.CreateOption, creationDataAct.CreateOption); Assert.Equal(creationDataExp.SourceUri, creationDataAct.SourceUri); Assert.Equal(creationDataExp.SourceResourceId, creationDataAct.SourceResourceId); Assert.Equal(creationDataExp.StorageAccountId, creationDataAct.StorageAccountId); // Image reference ImageDiskReference imgRefExp = creationDataExp.GalleryImageReference ?? creationDataExp.ImageReference; ImageDiskReference imgRefAct = creationDataAct.GalleryImageReference ?? creationDataAct.ImageReference; if (imgRefExp != null) { Assert.Equal(imgRefExp.Id, imgRefAct.Id); Assert.Equal(imgRefExp.Lun, imgRefAct.Lun); } else { Assert.Null(imgRefAct); } } protected void Validate(Disk diskExpected, Disk diskActual, string location, bool diskHydrated = false, bool update = false) { // disk resource Assert.Equal(string.Format("{0}/{1}", ApiConstants.ResourceProviderNamespace, "disks"), diskActual.Type); Assert.NotNull(diskActual.Name); Assert.Equal(location, diskActual.Location); // disk properties Assert.Equal(diskExpected.Sku.Name, diskActual.Sku.Name); Assert.NotNull(diskActual.ProvisioningState); Assert.Equal(diskExpected.OsType, diskActual.OsType); Assert.NotNull(diskActual.UniqueId); if (diskExpected.DiskSizeGB != null) { // Disk resizing Assert.Equal(diskExpected.DiskSizeGB, diskActual.DiskSizeGB); Assert.NotNull(diskActual.DiskSizeBytes); } if (!update) { if (diskExpected.DiskIOPSReadWrite != null) { Assert.Equal(diskExpected.DiskIOPSReadWrite, diskActual.DiskIOPSReadWrite); } if (diskExpected.DiskMBpsReadWrite != null) { Assert.Equal(diskExpected.DiskMBpsReadWrite, diskActual.DiskMBpsReadWrite); } if (diskExpected.DiskIOPSReadOnly != null) { Assert.Equal(diskExpected.DiskIOPSReadOnly, diskActual.DiskIOPSReadOnly); } if (diskExpected.DiskMBpsReadOnly != null) { Assert.Equal(diskExpected.DiskMBpsReadOnly, diskActual.DiskMBpsReadOnly); } if (diskExpected.MaxShares != null) { Assert.Equal(diskExpected.MaxShares, diskActual.MaxShares); } } // Creation data CreationData creationDataExp = diskExpected.CreationData; CreationData creationDataAct = diskActual.CreationData; Assert.Equal(creationDataExp.CreateOption, creationDataAct.CreateOption); Assert.Equal(creationDataExp.SourceUri, creationDataAct.SourceUri); Assert.Equal(creationDataExp.SourceResourceId, creationDataAct.SourceResourceId); Assert.Equal(creationDataExp.StorageAccountId, creationDataAct.StorageAccountId); // Image reference ImageDiskReference imgRefExp = creationDataExp.GalleryImageReference ?? creationDataExp.ImageReference; ImageDiskReference imgRefAct = creationDataAct.GalleryImageReference ?? creationDataAct.ImageReference; if (imgRefExp != null) { Assert.Equal(imgRefExp.Id, imgRefAct.Id); Assert.Equal(imgRefExp.Lun, imgRefAct.Lun); } else { Assert.Null(imgRefAct); } // Zones IList<string> zonesExp = diskExpected.Zones; IList<string> zonesAct = diskActual.Zones; if (zonesExp != null) { Assert.Equal(zonesExp.Count, zonesAct.Count); foreach (string zone in zonesExp) { Assert.Contains(zone, zonesAct, StringComparer.OrdinalIgnoreCase); } } else { Assert.Null(zonesAct); } } #endregion } }
46.249701
183
0.563457
[ "MIT" ]
HaoQian-MS/azure-sdk-for-net
sdk/compute/Microsoft.Azure.Management.Compute/tests/DiskRPTests/DiskRPTestsBase.cs
38,711
C#
using MrMeeseeks.ResXToViewModelGenerator; namespace BFF.ViewModel.ViewModels.ForModels.Utility { public interface IBudgetMonthMenuTitles { string EmptyCellsHeader { get; } string BudgetLastMonth { get; } string OutflowsLastMonth { get; } string AvgOutflowLastThreeMonths { get; } string AvgOutflowsLastYear { get; } string BalanceToZero { get; } string AllCellsHeader { get; } string Zero { get; } } internal class BudgetMonthMenuTitles : IBudgetMonthMenuTitles { private readonly ICurrentTextsViewModel _currentTextsViewModel; public BudgetMonthMenuTitles( ICurrentTextsViewModel currentTextsViewModel) => _currentTextsViewModel = currentTextsViewModel; public string EmptyCellsHeader => _currentTextsViewModel.CurrentTexts.Budgeting_Month_ContextMenu_EmptyCellsHeader; public string BudgetLastMonth => _currentTextsViewModel.CurrentTexts.Budgeting_ContextMenu_BudgetLastMonth; public string OutflowsLastMonth => _currentTextsViewModel.CurrentTexts.Budgeting_ContextMenu_OutflowsLastMonth; public string AvgOutflowLastThreeMonths => _currentTextsViewModel.CurrentTexts.Budgeting_ContextMenu_AvgOutflowsLastThreeMonths; public string AvgOutflowsLastYear => _currentTextsViewModel.CurrentTexts.Budgeting_ContextMenu_AvgOutflowsLastYear; public string BalanceToZero => _currentTextsViewModel.CurrentTexts.Budgeting_ContextMenu_BalanceToZero; public string AllCellsHeader => _currentTextsViewModel.CurrentTexts.Budgeting_Month_ContextMenu_AllCellsHeader; public string Zero => _currentTextsViewModel.CurrentTexts.Budgeting_ContextMenu_Zero; } }
41.785714
136
0.768661
[ "MIT" ]
Yeah69/BFF
ViewModel/ViewModels/ForModels/Utility/BudgetMonthMenuTitles.cs
1,757
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace MC.Website.GenresReference { using System.Runtime.Serialization; using System; [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="GenreDto", Namespace="http://schemas.datacontract.org/2004/07/MC.ApplicationServices.DTOs")] [System.SerializableAttribute()] public partial class GenreDto : MC.Website.GenresReference.BaseDto { [System.Runtime.Serialization.OptionalFieldAttribute()] private string NameField; [System.Runtime.Serialization.DataMemberAttribute()] public string Name { get { return this.NameField; } set { if ((object.ReferenceEquals(this.NameField, value) != true)) { this.NameField = value; this.RaisePropertyChanged("Name"); } } } } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.Runtime.Serialization", "4.0.0.0")] [System.Runtime.Serialization.DataContractAttribute(Name="BaseDto", Namespace="http://schemas.datacontract.org/2004/07/MC.ApplicationServices.DTOs")] [System.SerializableAttribute()] [System.Runtime.Serialization.KnownTypeAttribute(typeof(MC.Website.GenresReference.GenreDto))] public partial class BaseDto : object, System.Runtime.Serialization.IExtensibleDataObject, System.ComponentModel.INotifyPropertyChanged { [System.NonSerializedAttribute()] private System.Runtime.Serialization.ExtensionDataObject extensionDataField; [System.Runtime.Serialization.OptionalFieldAttribute()] private int IdField; [global::System.ComponentModel.BrowsableAttribute(false)] public System.Runtime.Serialization.ExtensionDataObject ExtensionData { get { return this.extensionDataField; } set { this.extensionDataField = value; } } [System.Runtime.Serialization.DataMemberAttribute()] public int Id { get { return this.IdField; } set { if ((this.IdField.Equals(value) != true)) { this.IdField = value; this.RaisePropertyChanged("Id"); } } } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected void RaisePropertyChanged(string propertyName) { System.ComponentModel.PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if ((propertyChanged != null)) { propertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] [System.ServiceModel.ServiceContractAttribute(ConfigurationName="GenresReference.IGenres")] public interface IGenres { [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IGenres/GetGenres", ReplyAction="http://tempuri.org/IGenres/GetGenresResponse")] MC.Website.GenresReference.GenreDto[] GetGenres(); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IGenres/GetGenres", ReplyAction="http://tempuri.org/IGenres/GetGenresResponse")] System.Threading.Tasks.Task<MC.Website.GenresReference.GenreDto[]> GetGenresAsync(); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IGenres/PostGenre", ReplyAction="http://tempuri.org/IGenres/PostGenreResponse")] string PostGenre(MC.Website.GenresReference.GenreDto genreDto); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IGenres/PostGenre", ReplyAction="http://tempuri.org/IGenres/PostGenreResponse")] System.Threading.Tasks.Task<string> PostGenreAsync(MC.Website.GenresReference.GenreDto genreDto); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IGenres/PutGenre", ReplyAction="http://tempuri.org/IGenres/PutGenreResponse")] string PutGenre(MC.Website.GenresReference.GenreDto genreDto); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IGenres/PutGenre", ReplyAction="http://tempuri.org/IGenres/PutGenreResponse")] System.Threading.Tasks.Task<string> PutGenreAsync(MC.Website.GenresReference.GenreDto genreDto); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IGenres/DeleteGenre", ReplyAction="http://tempuri.org/IGenres/DeleteGenreResponse")] string DeleteGenre(int id); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IGenres/DeleteGenre", ReplyAction="http://tempuri.org/IGenres/DeleteGenreResponse")] System.Threading.Tasks.Task<string> DeleteGenreAsync(int id); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IGenres/Message", ReplyAction="http://tempuri.org/IGenres/MessageResponse")] string Message(); [System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/IGenres/Message", ReplyAction="http://tempuri.org/IGenres/MessageResponse")] System.Threading.Tasks.Task<string> MessageAsync(); } [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public interface IGenresChannel : MC.Website.GenresReference.IGenres, System.ServiceModel.IClientChannel { } [System.Diagnostics.DebuggerStepThroughAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")] public partial class GenresClient : System.ServiceModel.ClientBase<MC.Website.GenresReference.IGenres>, MC.Website.GenresReference.IGenres { public GenresClient() { } public GenresClient(string endpointConfigurationName) : base(endpointConfigurationName) { } public GenresClient(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public GenresClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public GenresClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public MC.Website.GenresReference.GenreDto[] GetGenres() { return base.Channel.GetGenres(); } public System.Threading.Tasks.Task<MC.Website.GenresReference.GenreDto[]> GetGenresAsync() { return base.Channel.GetGenresAsync(); } public string PostGenre(MC.Website.GenresReference.GenreDto genreDto) { return base.Channel.PostGenre(genreDto); } public System.Threading.Tasks.Task<string> PostGenreAsync(MC.Website.GenresReference.GenreDto genreDto) { return base.Channel.PostGenreAsync(genreDto); } public string PutGenre(MC.Website.GenresReference.GenreDto genreDto) { return base.Channel.PutGenre(genreDto); } public System.Threading.Tasks.Task<string> PutGenreAsync(MC.Website.GenresReference.GenreDto genreDto) { return base.Channel.PutGenreAsync(genreDto); } public string DeleteGenre(int id) { return base.Channel.DeleteGenre(id); } public System.Threading.Tasks.Task<string> DeleteGenreAsync(int id) { return base.Channel.DeleteGenreAsync(id); } public string Message() { return base.Channel.Message(); } public System.Threading.Tasks.Task<string> MessageAsync() { return base.Channel.MessageAsync(); } } }
46.888298
167
0.656495
[ "MIT" ]
pkyurkchiev/distributed-applications-for-se
exercises/06/MovieCatalog/MC.Website/Connected Services/GenresReference/Reference.cs
8,817
C#
#region MigraDoc - Creating Documents on the Fly // // Authors: // Stefan Lange // Klaus Potzesny // David Stephensen // // Copyright (c) 2001-2017 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://www.migradoc.com // http://sourceforge.net/projects/pdfsharp // // 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 namespace MigraDoc.DocumentObjectModel.Visitors { /// <summary> /// Represents the visitor for flattening the DocumentObject to be used in the RtfRenderer. /// </summary> public class RtfFlattenVisitor : VisitorBase { public override void VisitFormattedText(FormattedText formattedText) { Document document = formattedText.Document; ParagraphFormat format = null; Style style = document._styles[formattedText._style.Value]; if (style != null) format = style._paragraphFormat; else if (formattedText._style.Value != "") format = document._styles[StyleNames.InvalidStyleName]._paragraphFormat; if (format != null) { if (formattedText._font == null) formattedText.Font = format._font.Clone(); else if (format._font != null) FlattenFont(formattedText._font, format._font); } } public override void VisitHyperlink(Hyperlink hyperlink) { Font styleFont = hyperlink.Document.Styles[StyleNames.Hyperlink].Font; if (hyperlink._font == null) hyperlink.Font = styleFont.Clone(); else FlattenFont(hyperlink._font, styleFont); } } }
39.3
95
0.669938
[ "MIT" ]
MarcoPietersma/AspNetCorePdf
MigraDoc.DocumentObjectModel/DocumentObjectModel.Visitors/RtfFlattenVisitor.cs
2,751
C#
using System; using GUC.Scripting; using GUC.GUI; using GUC.Scripts.Menus; using GUC.Types; using GUC.Scripts.Sumpfkraut.Menus; using WinApi.User.Enumeration; namespace GUC.Scripts.Arena { /* * TODO * - bug fixen beim nachrichten splitten */ class ChatMenu : GUCMenu,IClosableMenu { private readonly Chat _Chat; public GUCVisual chatBackground; public GUCTextBox textBox; public GUCVisual prefix; private ChatMode openChatMode; ViewPoint screenSize; int chatHeigth, chatWidth; GUCTimer chatInactivityTimer; public ChatMenu(Chat chat) { _Chat = chat ?? throw new ArgumentNullException(nameof(chat)); _Chat.ChatMessageReceived += (sender, args) => ReceiveServerMessage(args.Mode, args.Message); screenSize = GUCView.GetScreenSize(); chatHeigth = screenSize.Y / 5; chatWidth = screenSize.X - 350; chatBackground = new GUCVisual(0, 0, chatWidth, chatHeigth + 5); chatBackground.SetBackTexture("Dlg_Conversation.tga"); const int space = 20; int lines = chatHeigth / space; for (int i = 0; i < lines; i++) { chatBackground.CreateText("" + i, 20, 5 + i * space); chatBackground.Texts[i].Text = ""; } textBox = new GUCTextBox(70, chatHeigth + 5, chatWidth - 90, false); prefix = new GUCVisual(15, chatHeigth + 5, chatWidth, 20); prefix.CreateText("", 0, 0); chatInactivityTimer = new GUCTimer(); chatInactivityTimer.SetCallback(() => { if (!textBox.Enabled) chatBackground.Hide(); chatInactivityTimer.Stop(); }); chatInactivityTimer.SetInterval(6 * TimeSpan.TicksPerSecond); } public void ToggleBackground() { if (chatBackground.Shown) { chatBackground.Hide(); } else { chatBackground.Show(); } } public override void Open() { textBox.Enabled = true; textBox.Show(); prefix.Show(); if (!chatBackground.Shown) chatBackground.Show(); base.Open(); } public override void Close() { textBox.Enabled = false; textBox.Hide(); prefix.Hide(); StartInactivityTimer(); base.Close(); } public void OpenAllChat() { openChatMode = ChatMode.All; prefix.Texts[0].Text = "All: "; Open(); } public void OpenTeamChat() { //if (TeamMode.TeamDef == null) { //AddMessage(ChatMode.All, "Du musst erst einem Team beitreten bevor du den Teamchat verwenden kannst!"); // OpenAllChat(); return; } openChatMode = ChatMode.Team; prefix.Texts[0].Text = "Team: "; Open(); } protected override void KeyPress(VirtualKeys key, bool hold) { switch (key) { case VirtualKeys.Escape: if (!hold) Close(); break; case VirtualKeys.Delete: if (!hold) { if (InputHandler.IsPressed(VirtualKeys.Control)) ClearChat(); else textBox.Input = ""; } break; case VirtualKeys.Return: if (!hold) { if (textBox.Input.Length != 0) SendInput(); if (!InputHandler.IsPressed(VirtualKeys.Shift)) Close(); } break; default: textBox.KeyPressed(key); break; } base.KeyPress(key, hold); } public void SendInput() { string message = textBox.Input.Trim(); if (message.Length == 0) return; else if (message.StartsWith("/test", StringComparison.OrdinalIgnoreCase) || message.StartsWith("test", StringComparison.OrdinalIgnoreCase)) { Sumpfkraut.Utilities.TestVarAbstract.Parse(message); textBox.Input = ""; return; } switch (openChatMode) { case ChatMode.Team: _Chat.SendTeamMessage(message); break; default: _Chat.SendMessage(message); break; } textBox.Input = ""; } public void ReceiveServerMessage(ChatMode chatmode, string message) { AddMessage(chatmode, message); StartInactivityTimer(); } public void StartInactivityTimer() { if (chatInactivityTimer.Started) chatInactivityTimer.Restart(); else chatInactivityTimer.Start(); } /// <summary> /// Shifts chat rows to create space for the new message and controls message length /// </summary> /// <param name="message"></param> public void AddMessage(ChatMode chatmode, string message) { Log.Logger.Log(chatmode); if (!this.textBox.Enabled) { chatBackground.Show(); StartInactivityTimer(); } // resort chat rows if necessary int maxScreenSize = chatWidth - 30; if (chatBackground.Texts[chatBackground.Texts.Count - 1].Text.Length > 0) for (int i = 0; i < chatBackground.Texts.Count - 1; i++) { chatBackground.Texts[i].Text = chatBackground.Texts[i + 1].Text; chatBackground.Texts[i].SetColor(chatBackground.Texts[i + 1].GetColor()); } // split messages to multiple rows if (GUCView.StringPixelWidth(message) > maxScreenSize) { int charCounter = 0; string newMessage = ""; foreach (char c in message) { newMessage += c; charCounter++; if (!(GUCView.StringPixelWidth(newMessage) < maxScreenSize)) { InsertMessage(openChatMode, newMessage); // remains of the message if (message.Length > charCounter) AddMessage(chatmode, message.Substring(charCounter)); return; } } } // set message in the correct place InsertMessage(chatmode, message); } /// <summary> /// Makes sure messages is added to the correct row in the chat. /// </summary> /// <param name="message"></param> private void InsertMessage(ChatMode chatMode, string message) { int index = 0; while (index < chatBackground.Texts.Count - 1) { if (chatBackground.Texts[index].Text.Length == 0) { chatBackground.Texts[index].Text = message; break; } index++; } //if (chatMode == ChatMode.Team && TeamMode.TeamDef != null) //{ // chatBackground.Texts[index].SetColor(TeamMode.TeamDef.Color); //} if (chatMode == ChatMode.Private) { chatBackground.Texts[index].SetColor(ColorRGBA.Pink); } else { chatBackground.Texts[index].SetColor(ColorRGBA.White); } chatBackground.Texts[index].Text = message; } public void ClearChat() { for (int i = 0; i < chatBackground.Texts.Count; i++) { chatBackground.Texts[i].Text = ""; } } } }
31.639405
128
0.474092
[ "BSD-2-Clause" ]
JulianVo/SumpfkrautOnline-Khorinis
RP_Client_Scripts/Chat/ChatMenu.cs
8,513
C#
namespace SplitByte { partial class frmDownloadUpdate { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmDownloadUpdate)); this.pgBar = new SplitByte.ucTextProgressBar(); this.btnCancelDownload = new System.Windows.Forms.Button(); this.bwDownload = new System.ComponentModel.BackgroundWorker(); this.label1 = new System.Windows.Forms.Label(); this.lblTotalSize = new System.Windows.Forms.Label(); this.SuspendLayout(); // // pgBar // this.pgBar.BackColor = System.Drawing.SystemColors.Control; resources.ApplyResources(this.pgBar, "pgBar"); this.pgBar.Name = "pgBar"; // // btnCancelDownload // resources.ApplyResources(this.btnCancelDownload, "btnCancelDownload"); this.btnCancelDownload.Name = "btnCancelDownload"; this.btnCancelDownload.UseVisualStyleBackColor = true; this.btnCancelDownload.Click += new System.EventHandler(this.btnCancelDownload_Click); // // label1 // resources.ApplyResources(this.label1, "label1"); this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Name = "label1"; // // lblTotalSize // resources.ApplyResources(this.lblTotalSize, "lblTotalSize"); this.lblTotalSize.BackColor = System.Drawing.Color.Transparent; this.lblTotalSize.Name = "lblTotalSize"; // // frmDownloadUpdate // resources.ApplyResources(this, "$this"); this.Controls.Add(this.lblTotalSize); this.Controls.Add(this.label1); this.Controls.Add(this.btnCancelDownload); this.Controls.Add(this.pgBar); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmDownloadUpdate"; this.Load += new System.EventHandler(this.frmDownloadUpdate_Load); this.ResumeLayout(false); this.PerformLayout(); } #endregion private ucTextProgressBar pgBar; private System.Windows.Forms.Button btnCancelDownload; private System.ComponentModel.BackgroundWorker bwDownload; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label lblTotalSize; } }
39.122222
149
0.594717
[ "MIT" ]
fourDotsSoftware/SplitByte
SplitByte/frmDownloadUpdate.Designer.cs
3,523
C#
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using NSubstitute; using NSubstitute.ExceptionExtensions; using NUnit.Framework; using System; using System.Collections.Generic; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; using Twilio.Rest.Api.V2010.Account.Usage.Record; namespace Twilio.Tests.Rest.Api.V2010.Account.Usage.Record { [TestFixture] public class ThisMonthTest : TwilioTest { [Test] public void TestReadRequest() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); var request = new Request( HttpMethod.Get, Twilio.Rest.Domain.Api, "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Usage/Records/ThisMonth.json", "" ); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(request).Throws(new ApiException("Server Error, no content")); try { ThisMonthResource.Read(client: twilioRestClient); Assert.Fail("Expected TwilioException to be thrown for 500"); } catch (ApiException) {} twilioRestClient.Received().Request(request); } [Test] public void TestReadFullResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"end\": 0,\"first_page_uri\": \"/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth?Page=0&PageSize=1\",\"last_page_uri\": \"/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth?Page=68&PageSize=1\",\"next_page_uri\": null,\"num_pages\": 69,\"page\": 0,\"page_size\": 1,\"previous_page_uri\": null,\"start\": 0,\"total\": 69,\"uri\": \"/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth\",\"usage_records\": [{\"account_sid\": \"ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"api_version\": \"2010-04-01\",\"category\": \"sms-inbound-shortcode\",\"count\": \"0\",\"count_unit\": \"messages\",\"description\": \"Short Code Inbound SMS\",\"end_date\": \"2015-09-04\",\"price\": \"0\",\"price_unit\": \"usd\",\"start_date\": \"2015-09-01\",\"subresource_uris\": {\"all_time\": \"/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/AllTime.json?Category=sms-inbound-shortcode\",\"daily\": \"/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Daily.json?Category=sms-inbound-shortcode\",\"last_month\": \"/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/LastMonth.json?Category=sms-inbound-shortcode\",\"monthly\": \"/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Monthly.json?Category=sms-inbound-shortcode\",\"this_month\": \"/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth.json?Category=sms-inbound-shortcode\",\"today\": \"/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Today.json?Category=sms-inbound-shortcode\",\"yearly\": \"/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yearly.json?Category=sms-inbound-shortcode\",\"yesterday\": \"/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/Yesterday.json?Category=sms-inbound-shortcode\"},\"uri\": \"/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth?Category=sms-inbound-shortcode&StartDate=2015-09-01&EndDate=2015-09-04\",\"usage\": \"0\",\"usage_unit\": \"messages\"}]}" )); var response = ThisMonthResource.Read(client: twilioRestClient); Assert.NotNull(response); } [Test] public void TestReadEmptyResponse() { var twilioRestClient = Substitute.For<ITwilioRestClient>(); twilioRestClient.AccountSid.Returns("ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"); twilioRestClient.Request(Arg.Any<Request>()) .Returns(new Response( System.Net.HttpStatusCode.OK, "{\"end\": 0,\"first_page_uri\": \"/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth?Page=0&PageSize=1\",\"last_page_uri\": \"/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth?Page=68&PageSize=1\",\"next_page_uri\": null,\"num_pages\": 69,\"page\": 0,\"page_size\": 1,\"previous_page_uri\": null,\"start\": 0,\"total\": 69,\"uri\": \"/2010-04-01/Accounts/ACaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/Usage/Records/ThisMonth\",\"usage_records\": []}" )); var response = ThisMonthResource.Read(client: twilioRestClient); Assert.NotNull(response); } } }
68.736842
2,147
0.655054
[ "MIT" ]
FMV1491/twilio-csharp
test/Twilio.Test/Rest/Api/V2010/Account/Usage/Record/ThisMonthResourceTest.cs
5,224
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210 { using static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Extensions; /// <summary>Recovery point for a migration item.</summary> public partial class MigrationRecoveryPoint { /// <summary> /// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json); /// <summary> /// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject" /// /> before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container); /// <summary> /// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of /// the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="json">The JsonNode that should be deserialized into this object.</param> /// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return /// instantly.</param> partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json, ref bool returnNow); /// <summary> /// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the /// object before it is serialized. /// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="container">The JSON container that the serialization result will be placed in.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, ref bool returnNow); /// <summary> /// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IMigrationRecoveryPoint. /// </summary> /// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" /> to deserialize from.</param> /// <returns> /// an instance of Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IMigrationRecoveryPoint. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IMigrationRecoveryPoint FromJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode node) { return node is Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json ? new MigrationRecoveryPoint(json) : null; } /// <summary> /// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject into a new instance of <see cref="MigrationRecoveryPoint" />. /// </summary> /// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject instance to deserialize from.</param> internal MigrationRecoveryPoint(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject json) { bool returnNow = false; BeforeFromJson(json, ref returnNow); if (returnNow) { return; } __resource = new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.Resource(json); {_property = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject>("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.MigrationRecoveryPointProperties.FromJson(__jsonProperties) : Property;} AfterFromJson(json); } /// <summary> /// Serializes this instance of <see cref="MigrationRecoveryPoint" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />. /// </summary> /// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller /// passes in <c>null</c>, a new instance will be created and returned to the caller.</param> /// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode"/>.</param> /// <returns> /// a serialized instance of <see cref="MigrationRecoveryPoint" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode" />. /// </returns> public Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.SerializationMode serializationMode) { container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonObject(); bool returnNow = false; BeforeToJson(ref container, ref returnNow); if (returnNow) { return container; } __resource?.ToJson(container, serializationMode); AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add ); AfterToJson(ref container); return container; } } }
66.912621
291
0.685142
[ "MIT" ]
AverageDesigner/azure-powershell
src/Migrate/generated/api/Models/Api20210210/MigrationRecoveryPoint.json.cs
6,790
C#
using Android.OS; using Android.App; using Android.Runtime; using Android.Content.PM; using FFImageLoading.Forms.Platform; namespace RestauranteApp.Droid { [Activity(Label = "RestauranteApp", Icon = "@mipmap/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity { protected override void OnCreate(Bundle savedInstanceState) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(savedInstanceState); Xamarin.Essentials.Platform.Init(this, savedInstanceState); global::Xamarin.Forms.Forms.Init(this, savedInstanceState); CachedImageRenderer.Init(true); LoadApplication(new App()); } public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults) { Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults); base.OnRequestPermissionsResult(requestCode, permissions, grantResults); } } }
42
189
0.713518
[ "MIT" ]
EmersonMeloMachado/RestauranteApp
RestauranteApp/RestauranteApp/RestauranteApp.Android/MainActivity.cs
1,304
C#
namespace FunctionApp1 { public partial class CommonMarkupHelper { public string SignInEmailMessage(string linkUrl, bool isInvitation, string companyName) { var message = t.GetString("Sign in to {0}", companyName); if(isInvitation) { message = t.GetString("Confirm invitation to {0}", companyName); } //http://www.industrydive.com/news/post/how-to-make-html-email-buttons-that-rock/#outlook return $@" <html> <body> <table cellspacing='0' cellpadding='0'> <tr> <td align='center' width='400' height='40' bgcolor='#000091' style='border-radius: 5px; color: #ffffff; display: block;'> <a href='{linkUrl}' style='font-size:16px; font-weight: bold; font-family: Helvetica, Arial, sans-serif; text-decoration: none; line-height:40px; width:100%; display:inline-block'> <span style='color: #FFFFFF'>{message}&nbsp;&nbsp;&nbsp;►</span></a> </td> </tr> </table> </body> </html>"; } } }
32.387097
180
0.62749
[ "MIT" ]
violet-guru/Kynodontas
Booking1/EmailMarkupHelper.cs
1,008
C#
#region License /* Copyright (c) 2016 VulkaNet Project - Daniil Rodin 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 namespace VulkaNet { public enum VkImageType { OneD = 0, TwoD = 1, ThreeD = 2, } }
37.212121
77
0.767915
[ "MIT" ]
Zulkir/VulkaNet
Source/VulkaNet/VkImageType.cs
1,230
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace Microsoft.eShopWeb.Infrastructure.Data.Migrations { public partial class tenantLocation_required : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Tenants_Locations_LocationId", table: "Tenants"); migrationBuilder.AlterColumn<long>( name: "LocationId", table: "Tenants", nullable: false, oldClrType: typeof(long), oldNullable: true); migrationBuilder.AddForeignKey( name: "FK_Tenants_Locations_LocationId", table: "Tenants", column: "LocationId", principalTable: "Locations", principalColumn: "Id", onDelete: ReferentialAction.NoAction); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_Tenants_Locations_LocationId", table: "Tenants"); migrationBuilder.AlterColumn<long>( name: "LocationId", table: "Tenants", nullable: true, oldClrType: typeof(long)); migrationBuilder.AddForeignKey( name: "FK_Tenants_Locations_LocationId", table: "Tenants", column: "LocationId", principalTable: "Locations", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
33.215686
71
0.553129
[ "MIT" ]
sahinme/edutro-api
src/Infrastructure/Data/Migrations/20191130200704_tenantLocation_required.cs
1,696
C#
using System; using Autofac; using Autofac.Extensions.DependencyInjection; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.eShopOnContainers.Services.AI.ProductSearchImageBased.TensorFlow.API.Classifier; using Microsoft.eShopOnContainers.Services.AI.ProductSearchImageBased.TensorFlow.API.Infrastructure.Filters; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace Microsoft.eShopOnContainers.Services.AI.ProductSearchImageBased.TensorFlow.API { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public virtual IServiceProvider ConfigureServices(IServiceCollection services) { services.Configure<AppSettings>(Configuration); services.AddTransient<ITensorFlowPredictionStrategy, TensorFlowPredictionStrategy>(); services.AddMvc(options => { options.Filters.Add(typeof(HttpGlobalExceptionFilter)); }) .AddControllersAsServices(); // Add framework services. services.AddSwaggerGen(options => { options.DescribeAllEnumsAsStrings(); options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info { Title = "eShopOnContainersAI - AI.ProductSearchImageBased.TensorFlow.API HTTP API", Version = "v1", Description = "The Product Image Search Microservice HTTP API.", TermsOfService = "Terms Of Service" }); options.OperationFilter<FormFileOperationFilter>(); }); services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() .AllowCredentials()); }); var container = new ContainerBuilder(); container.Populate(services); return new AutofacServiceProvider(container.Build()); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public virtual void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //Configure logs loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); loggerFactory.AddAzureWebAppDiagnostics(); loggerFactory.AddApplicationInsights(app.ApplicationServices, LogLevel.Trace); var pathBase = Configuration["PATH_BASE"]; if (!string.IsNullOrEmpty(pathBase)) { loggerFactory.CreateLogger("init").LogDebug($"Using PATH BASE '{pathBase}'"); app.UsePathBase(pathBase); } app.UseCors("CorsPolicy"); app.UseMvcWithDefaultRoute(); app.UseSwagger() .UseSwaggerUI(c => { c.SwaggerEndpoint($"{ (!string.IsNullOrEmpty(pathBase) ? pathBase : string.Empty) }/swagger/v1/swagger.json", "AI.ProductSearchImageBased.TensorFlow.API V1"); }); } } }
38.945652
176
0.625174
[ "MIT" ]
hhy37/eShopOnContainersAI
src/Services/AI.ProductSearchImageBased/AI.ProductSearchImageBased.TensorFlow.API/Startup.cs
3,585
C#
using System.Collections.Generic; using System.Linq; using MediatR; using Microsoft.Extensions.DependencyInjection; using System.Reflection; using MarkWildmanNerdMathWorkouts.Application.Features.ExtendedAttributes.Commands.AddEdit; using MarkWildmanNerdMathWorkouts.Application.Features.ExtendedAttributes.Commands.Delete; using MarkWildmanNerdMathWorkouts.Application.Features.ExtendedAttributes.Queries.Export; using MarkWildmanNerdMathWorkouts.Application.Features.ExtendedAttributes.Queries.GetAll; using MarkWildmanNerdMathWorkouts.Application.Features.ExtendedAttributes.Queries.GetAllByEntityId; using MarkWildmanNerdMathWorkouts.Application.Features.ExtendedAttributes.Queries.GetById; using MarkWildmanNerdMathWorkouts.Domain.Contracts; using MarkWildmanNerdMathWorkouts.Shared.Wrapper; namespace MarkWildmanNerdMathWorkouts.Application.Extensions { public static class ServiceCollectionExtensions { public static void AddApplicationLayer(this IServiceCollection services) { services.AddAutoMapper(Assembly.GetExecutingAssembly()); //services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly()); services.AddMediatR(Assembly.GetExecutingAssembly()); //services.AddTransient(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>)); } public static void AddExtendedAttributesHandlers(this IServiceCollection services) { var extendedAttributeTypes = typeof(IEntity) .Assembly .GetExportedTypes() .Where(t => t.IsClass && !t.IsAbstract && t.BaseType?.IsGenericType == true) .Select(t => new { BaseGenericType = t.BaseType, CurrentType = t }) .Where(t => t.BaseGenericType?.GetGenericTypeDefinition() == typeof(AuditableEntityExtendedAttribute<,,>)) .ToList(); foreach (var extendedAttributeType in extendedAttributeTypes) { var extendedAttributeTypeGenericArguments = extendedAttributeType.BaseGenericType.GetGenericArguments().ToList(); extendedAttributeTypeGenericArguments.Add(extendedAttributeType.CurrentType); #region AddEditExtendedAttributeCommandHandler var tRequest = typeof(AddEditExtendedAttributeCommand<,,,>).MakeGenericType(extendedAttributeTypeGenericArguments.ToArray()); var tResponse = typeof(Result<>).MakeGenericType(extendedAttributeTypeGenericArguments.First()); var serviceType = typeof(IRequestHandler<,>).MakeGenericType(tRequest, tResponse); var implementationType = typeof(AddEditExtendedAttributeCommandHandler<,,,>).MakeGenericType(extendedAttributeTypeGenericArguments.ToArray()); services.AddScoped(serviceType, implementationType); #endregion AddEditExtendedAttributeCommandHandler #region DeleteExtendedAttributeCommandHandler tRequest = typeof(DeleteExtendedAttributeCommand<,,,>).MakeGenericType(extendedAttributeTypeGenericArguments.ToArray()); tResponse = typeof(Result<>).MakeGenericType(extendedAttributeTypeGenericArguments.First()); serviceType = typeof(IRequestHandler<,>).MakeGenericType(tRequest, tResponse); implementationType = typeof(DeleteExtendedAttributeCommandHandler<,,,>).MakeGenericType(extendedAttributeTypeGenericArguments.ToArray()); services.AddScoped(serviceType, implementationType); #endregion DeleteExtendedAttributeCommandHandler #region GetAllExtendedAttributesByEntityIdQueryHandler tRequest = typeof(GetAllExtendedAttributesByEntityIdQuery<,,,>).MakeGenericType(extendedAttributeTypeGenericArguments.ToArray()); tResponse = typeof(Result<>).MakeGenericType(typeof(List<>).MakeGenericType( typeof(GetAllExtendedAttributesByEntityIdResponse<,>).MakeGenericType( extendedAttributeTypeGenericArguments[0], extendedAttributeTypeGenericArguments[1]))); serviceType = typeof(IRequestHandler<,>).MakeGenericType(tRequest, tResponse); implementationType = typeof(GetAllExtendedAttributesByEntityIdQueryHandler<,,,>).MakeGenericType(extendedAttributeTypeGenericArguments.ToArray()); services.AddScoped(serviceType, implementationType); #endregion GetAllExtendedAttributesByEntityIdQueryHandler #region GetExtendedAttributeByIdQueryHandler tRequest = typeof(GetExtendedAttributeByIdQuery<,,,>).MakeGenericType(extendedAttributeTypeGenericArguments.ToArray()); tResponse = typeof(Result<>).MakeGenericType( typeof(GetExtendedAttributeByIdResponse<,>).MakeGenericType( extendedAttributeTypeGenericArguments[0], extendedAttributeTypeGenericArguments[1])); serviceType = typeof(IRequestHandler<,>).MakeGenericType(tRequest, tResponse); implementationType = typeof(GetExtendedAttributeByIdQueryHandler<,,,>).MakeGenericType(extendedAttributeTypeGenericArguments.ToArray()); services.AddScoped(serviceType, implementationType); #endregion GetExtendedAttributeByIdQueryHandler #region GetAllExtendedAttributesQueryHandler tRequest = typeof(GetAllExtendedAttributesQuery<,,,>).MakeGenericType(extendedAttributeTypeGenericArguments.ToArray()); tResponse = typeof(Result<>).MakeGenericType(typeof(List<>).MakeGenericType( typeof(GetAllExtendedAttributesResponse<,>).MakeGenericType( extendedAttributeTypeGenericArguments[0], extendedAttributeTypeGenericArguments[1]))); serviceType = typeof(IRequestHandler<,>).MakeGenericType(tRequest, tResponse); implementationType = typeof(GetAllExtendedAttributesQueryHandler<,,,>).MakeGenericType(extendedAttributeTypeGenericArguments.ToArray()); services.AddScoped(serviceType, implementationType); #endregion GetAllExtendedAttributesQueryHandler #region ExportExtendedAttributesQueryHandler tRequest = typeof(ExportExtendedAttributesQuery<,,,>).MakeGenericType(extendedAttributeTypeGenericArguments.ToArray()); tResponse = typeof(Result<>).MakeGenericType(typeof(string)); serviceType = typeof(IRequestHandler<,>).MakeGenericType(tRequest, tResponse); implementationType = typeof(ExportExtendedAttributesQueryHandler<,,,>).MakeGenericType(extendedAttributeTypeGenericArguments.ToArray()); services.AddScoped(serviceType, implementationType); #endregion ExportExtendedAttributesQueryHandler } } } }
61.263158
162
0.71449
[ "MIT" ]
AshleyHollis/MarkWildmanNerdMathWorkouts
src/Application/Extensions/ServiceCollectionExtensions.cs
6,986
C#
using System; using System.Collections.Generic; using h73.Elastic.Core.Enums; using h73.Elastic.Core.Search.Interfaces; using Newtonsoft.Json; namespace h73.Elastic.Core.Search.Queries { [Serializable] public class NestedQuery : NestedQuery<object> { } public class NestedQuery<T> : QueryInit where T : class { [JsonProperty(PropertyName = "nested", NullValueHandling = NullValueHandling.Ignore)] public NestedItem<T> Nested { get; set; } } public class NestedItem : NestedItem<object> { } public class NestedItem<T> where T : class { [JsonProperty(PropertyName = "path", NullValueHandling = NullValueHandling.Ignore)] public string Path { get; set; } [JsonProperty(PropertyName = "score_mode", NullValueHandling = NullValueHandling.Ignore)] public ScoreMode? ScoreMode { get; set; } [JsonProperty(PropertyName = "query", NullValueHandling = NullValueHandling.Ignore)] public Dictionary<string, IQuery> Query { get; set; } [JsonProperty(PropertyName = "inner_hits", NullValueHandling = NullValueHandling.Ignore)] public InnerHits InnerHits { get; set; } } }
30.717949
97
0.686978
[ "MIT" ]
henskjold73/h73.Elastic.Core
h73.Elastic.Core/Search/Queries/NestedQuery.cs
1,200
C#
using Amazon.CDK; using System; using System.Collections.Generic; using System.Linq; namespace HelloCdk { class Program { static void Main(string[] args) { var app = new App(null); // A CDK app can contain multiple stacks. You can view a list of all the stacks in your // app by typing `cdk list`. new HelloStack(app, "hello-cdk-1", new StackProps()); new HelloStack(app, "hello-cdk-2", new StackProps()); app.Synth(); } } }
23.347826
99
0.569832
[ "Apache-2.0" ]
AlexCheema/aws-cdk
packages/aws-cdk/lib/init-templates/app/csharp/src/HelloCdk/Program.cs
539
C#
// Copyright (c) Peter Vrenken. All rights reserved. See the license on https://github.com/vrenken/EtAlii.Ubigia namespace EtAlii.Ubigia.Api.Functional.Traversal { internal interface IVariableRootHandlerPathPartMatcher : IRootHandlerPathPartMatcher { } }
29.777778
112
0.779851
[ "MIT" ]
vrenken/EtAlii.Ubigia
Source/Api/EtAlii.Ubigia.Api.Functional/Traversal/Roots/Handlers/Matching/Matchers/Variable/IVariableRootHandlerPathPartMatcher.cs
268
C#
using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace SideLoader.UI.Editor { #region IStructInfo helper public interface IStructInfo { string[] FieldNames { get; } object SetValue(ref object value, int fieldIndex, float val); void RefreshUI(InputField[] inputs, object value); } public class StructInfo<T> : IStructInfo where T : struct { public string[] FieldNames { get; set; } public delegate void SetMethod(ref T value, int fieldIndex, float val); public SetMethod SetValueMethod; public delegate void UpdateMethod(InputField[] inputs, object value); public UpdateMethod UpdateUIMethod; public object SetValue(ref object value, int fieldIndex, float val) { var box = (T)value; SetValueMethod.Invoke(ref box, fieldIndex, val); return box; } public void RefreshUI(InputField[] inputs, object value) { UpdateUIMethod.Invoke(inputs, value); } } // This part is a bit ugly, but everything else is generalized above. // I could generalize it more with reflection, but it would be different for // mono/il2cpp and also slower. public static class StructInfoFactory { public static IStructInfo Create(Type type) { if (type == typeof(Vector2)) { return new StructInfo<Vector2>() { FieldNames = new[] { "x", "y", }, SetValueMethod = (ref Vector2 vec, int fieldIndex, float val) => { switch (fieldIndex) { case 0: vec.x = val; break; case 1: vec.y = val; break; } }, UpdateUIMethod = (InputField[] inputs, object value) => { Vector2 vec = (Vector2)value; inputs[0].text = vec.x.ToString(); inputs[1].text = vec.y.ToString(); } }; } else if (type == typeof(Vector3)) { return new StructInfo<Vector3>() { FieldNames = new[] { "x", "y", "z" }, SetValueMethod = (ref Vector3 vec, int fieldIndex, float val) => { switch (fieldIndex) { case 0: vec.x = val; break; case 1: vec.y = val; break; case 2: vec.z = val; break; } }, UpdateUIMethod = (InputField[] inputs, object value) => { Vector3 vec = (Vector3)value; inputs[0].text = vec.x.ToString(); inputs[1].text = vec.y.ToString(); inputs[2].text = vec.z.ToString(); } }; } else if (type == typeof(Vector4)) { return new StructInfo<Vector4>() { FieldNames = new[] { "x", "y", "z", "w" }, SetValueMethod = (ref Vector4 vec, int fieldIndex, float val) => { switch (fieldIndex) { case 0: vec.x = val; break; case 1: vec.y = val; break; case 2: vec.z = val; break; case 3: vec.w = val; break; } }, UpdateUIMethod = (InputField[] inputs, object value) => { Vector4 vec = (Vector4)value; inputs[0].text = vec.x.ToString(); inputs[1].text = vec.y.ToString(); inputs[2].text = vec.z.ToString(); inputs[3].text = vec.w.ToString(); } }; } else if (type == typeof(Rect)) { return new StructInfo<Rect>() { FieldNames = new[] { "x", "y", "width", "height" }, SetValueMethod = (ref Rect vec, int fieldIndex, float val) => { switch (fieldIndex) { case 0: vec.x = val; break; case 1: vec.y = val; break; case 2: vec.width = val; break; case 3: vec.height = val; break; } }, UpdateUIMethod = (InputField[] inputs, object value) => { Rect vec = (Rect)value; inputs[0].text = vec.x.ToString(); inputs[1].text = vec.y.ToString(); inputs[2].text = vec.width.ToString(); inputs[3].text = vec.height.ToString(); } }; } else if (type == typeof(Color)) { return new StructInfo<Color>() { FieldNames = new[] { "r", "g", "b", "a" }, SetValueMethod = (ref Color vec, int fieldIndex, float val) => { switch (fieldIndex) { case 0: vec.r = val; break; case 1: vec.g = val; break; case 2: vec.b = val; break; case 3: vec.a = val; break; } }, UpdateUIMethod = (InputField[] inputs, object value) => { Color vec = (Color)value; inputs[0].text = vec.r.ToString(); inputs[1].text = vec.g.ToString(); inputs[2].text = vec.b.ToString(); inputs[3].text = vec.a.ToString(); } }; } else throw new NotImplementedException(); } } #endregion public class InteractiveUnityStruct : InteractiveValue { public static bool SupportsType(Type type) => s_supportedTypes.Contains(type); private static readonly HashSet<Type> s_supportedTypes = new HashSet<Type> { typeof(Vector2), typeof(Vector3), typeof(Vector4), typeof(Rect), typeof(Color) // todo might make a special editor for colors }; //~~~~~~~~~ Instance ~~~~~~~~~~ public InteractiveUnityStruct(object value, Type valueType) : base(value, valueType) { } public override bool HasSubContent => true; public override bool SubContentWanted => true; public override bool WantInspectBtn => false; public override bool WantCreateDestroyBtn => false; public IStructInfo StructInfo; internal override void QuickSave() { this.OnApplyClicked(); base.QuickSave(); } public override void RefreshUIForValue() { InitializeStructInfo(); base.RefreshUIForValue(); if (m_subContentConstructed) StructInfo.RefreshUI(m_inputs, this.Value); } internal override void OnToggleSubcontent(bool toggle) { InitializeStructInfo(); base.OnToggleSubcontent(toggle); StructInfo.RefreshUI(m_inputs, this.Value); } internal Type m_lastStructType; internal void InitializeStructInfo() { var type = Value?.GetType() ?? FallbackType; if (StructInfo != null && type == m_lastStructType) return; if (StructInfo != null) { DestroySubContent(); } m_lastStructType = type; StructInfo = StructInfoFactory.Create(type); if (m_subContentParent.activeSelf) { ConstructSubcontent(); } } #region UI CONSTRUCTION internal InputField[] m_inputs; public override void ConstructUI(GameObject parent, GameObject subGroup) { base.ConstructUI(parent, subGroup); } public override void ConstructSubcontent() { base.ConstructSubcontent(); if (StructInfo == null) { SL.LogWarning("Setting up subcontent but structinfo is null"); return; } var editorContainer = UIFactory.CreateVerticalGroup(m_subContentParent, new Color(0.08f, 0.08f, 0.08f)); var editorGroup = editorContainer.GetComponent<VerticalLayoutGroup>(); editorGroup.childForceExpandWidth = false; editorGroup.padding.top = 4; editorGroup.padding.right = 4; editorGroup.padding.left = 4; editorGroup.padding.bottom = 4; editorGroup.spacing = 2; m_inputs = new InputField[StructInfo.FieldNames.Length]; for (int i = 0; i < StructInfo.FieldNames.Length; i++) { AddEditorRow(i, editorContainer); } if (Owner.CanWrite) { var applyBtnObj = UIFactory.CreateButton(editorContainer, new Color(0.2f, 0.2f, 0.2f)); var applyLayout = applyBtnObj.AddComponent<LayoutElement>(); applyLayout.minWidth = 175; applyLayout.minHeight = 25; applyLayout.flexibleWidth = 0; var m_applyBtn = applyBtnObj.GetComponent<Button>(); m_applyBtn.onClick.AddListener(OnSetValue); void OnSetValue() { OnApplyClicked(); } var applyText = applyBtnObj.GetComponentInChildren<Text>(); applyText.text = "Apply"; } } private void OnApplyClicked() { int i = 0; foreach (var inputField in structInputFields) { if (!float.TryParse(inputField.text, out float f)) { SL.LogWarning("Could not parse input '" + inputField.text + "' to float!"); break; } Value = StructInfo.SetValue(ref this.Value, i, f); i++; } Owner.SetValue(); RefreshUIForValue(); } private readonly List<InputField> structInputFields = new List<InputField>(); internal void AddEditorRow(int index, GameObject groupObj) { var rowObj = UIFactory.CreateHorizontalGroup(groupObj, new Color(1, 1, 1, 0)); var rowGroup = rowObj.GetComponent<HorizontalLayoutGroup>(); rowGroup.childForceExpandHeight = true; rowGroup.childForceExpandWidth = false; rowGroup.spacing = 5; var label = UIFactory.CreateLabel(rowObj, TextAnchor.MiddleRight); var labelLayout = label.AddComponent<LayoutElement>(); labelLayout.minWidth = 50; labelLayout.flexibleWidth = 0; labelLayout.minHeight = 25; var labelText = label.GetComponent<Text>(); labelText.text = $"{StructInfo.FieldNames[index]}:"; labelText.color = Color.cyan; var inputFieldObj = UIFactory.CreateInputField(rowObj, 14, 3, 1); var inputField = inputFieldObj.GetComponent<InputField>(); // inputField.characterValidation = InputField.CharacterValidation.Decimal; var inputLayout = inputFieldObj.AddComponent<LayoutElement>(); inputLayout.flexibleWidth = 0; inputLayout.minWidth = 120; inputLayout.minHeight = 25; m_inputs[index] = inputField; structInputFields.Add(inputField); //inputField.onValueChanged.AddListener((string val) => { Value = StructInfo.SetValue(ref this.Value, index, float.Parse(val)); }); } #endregion } }
35.560563
143
0.476236
[ "MIT" ]
sinai-dev/Outward-SideLoader
src/UI/Editor/InteractiveValue/InteractiveUnityStruct.cs
12,626
C#
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Threading; namespace _Framework.Scripts.Extensions { public static class StringExtensions { /// <summary> /// Eg MY_INT_VALUE => MyIntValue /// </summary> public static string ToTitleCase(this string input) { var builder = new StringBuilder(); for (int i = 0; i < input.Length; i++) { var current = input[i]; if (current == '_' && i + 1 < input.Length) { var next = input[i + 1]; if (char.IsLower(next)) next = char.ToUpper(next); builder.Append(next); i++; } else builder.Append(current); } return builder.ToString(); } /// <summary> /// Performs a simple char-by-char comparison to see if input ends with postfix /// </summary> /// <returns></returns> public static bool IsPostfix(this string input, string postfix) { if (input == null) throw new ArgumentNullException("input"); if (postfix == null) throw new ArgumentNullException("postfix"); if (input.Length < postfix.Length) return false; for (int i = input.Length - 1, j = postfix.Length - 1; j >= 0; i--, j--) if (input[i] != postfix[j]) return false; return true; } /// <summary> /// Performs a simple char-by-char comparison to see if input starts with prefix /// </summary> /// <returns></returns> public static bool IsPrefix(this string input, string prefix) { if (input == null) throw new ArgumentNullException("input"); if (prefix == null) throw new ArgumentNullException("prefix"); if (input.Length < prefix.Length) return false; for (int i = 0; i < prefix.Length; i++) if (input[i] != prefix[i]) return false; return true; } public static Enum ToEnum(this string str, Type enumType) { return Enum.Parse(enumType, str) as Enum; } public static T ToEnum<T>(this string str) { return (T)Enum.Parse(typeof(T), str); } public static string FormatWith(this string str, params object[] args) { return string.Format(str, args); } /// <summary> /// Parses the specified string to the enum value of type T /// </summary> public static T ParseEnum<T>(this string value) { return (T)Enum.Parse(typeof(T), value, false); } /// <summary> /// Parses the specified string to the enum whose type is specified by enumType /// </summary> public static Enum ParseEnum(this string value, Type enumType) { return (Enum)Enum.Parse(enumType, value, false); } /// <summary> /// Returns the Nth index of the specified character in this string /// </summary> public static int IndexOfNth(this string str, char c, int n) { int s = -1; for (int i = 0; i < n; i++) { s = str.IndexOf(c, s + 1); if (s == -1) break; } return s; } /// <summary> /// Removes the last occurance of the specified string from this string. /// Returns the modified version. /// </summary> public static string RemoveLastOccurance(this string s, string what) { return s.Substring(0, s.LastIndexOf(what)); } /// <summary> /// Removes the type extension. ex "Medusa.mp3" => "Medusa" /// </summary> public static string RemoveExtension(this string s) { return s.Substring(0, s.LastIndexOf('.')); } /// <summary> /// Returns whether or not the specified string is contained with this string /// Credits to JaredPar http://stackoverflow.com/questions/444798/case-insensitive-containsstring/444818#444818 /// </summary> public static bool Contains(this string source, string toCheck, StringComparison comp) { return source.IndexOf(toCheck, comp) >= 0; } /// <summary> /// "tHiS is a sTring TesT" -> "This Is A String Test" /// Credits: http://extensionmethod.net/csharp/string/topropercase /// </summary> public static string ToProperCase(this string text) { CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture; TextInfo textInfo = cultureInfo.TextInfo; return textInfo.ToTitleCase(text); } /// <summary> /// Ex: "thisIsCamelCase" -> "this Is Camel Case" /// Credits: http://stackoverflow.com/questions/155303/net-how-can-you-split-a-caps-delimited-string-into-an-array /// </summary> public static string SplitCamelCase(this string input) { return Regex.Replace(input, "([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", "$1 "); } /// <summary> /// Ex: "thisIsCamelCase" -> "This Is Camel Case" /// </summary> public static string SplitPascalCase(this string input) { return string.IsNullOrEmpty(input) ? input : input.SplitCamelCase().ToUpperAt(0); } /// <summary> /// Normalizes this string by replacing all 'from's by 'to's and returns the normalized instance /// Ex: "path/to\dir".NormalizePath('/', '\\') => "path\\to\\dir" /// </summary> public static string NormalizePath(this string input, char from, char to) { return input.Replace(from, to); } /// <summary> /// Replaces the character specified by the passed index with newChar and returns the new string instance /// </summary> public static string ReplaceAt(this string input, int index, char newChar) { if (input == null) { throw new ArgumentNullException("input"); } var builder = new StringBuilder(input); builder[index] = newChar; return builder.ToString(); } /// <summary> /// Uppers the character specified by the passed index and returns the new string instance /// </summary> public static string ToUpperAt(this string input, int index) { return input.ReplaceAt(index, char.ToUpper(input[index])); } /// <summary> /// Returns true if this string is null or empty /// </summary> public static bool IsNullOrEmpty(this string str) { return string.IsNullOrEmpty(str); } public static string ReplaceAllWhiteSpace(this string str, string replaceWith) { return Regex.Replace(str, @"\s+", replaceWith); } public static IEnumerable<IEnumerable<T>> SplitToChunks<T>(this List<T> str, int maxChunkSize) { for (int i = 0; i < str.Count; i += maxChunkSize) yield return str.GetRange(i, Math.Min(maxChunkSize, str.Count - i)); } /// <summary> /// Returns true if <paramref name="path"/> starts with the path <paramref name="baseDirPath"/>. /// The comparison is case-insensitive, handles / and \ slashes as folder separators and /// only matches if the base dir folder name is matched exactly ("c:\foobar\file.txt" is not a sub path of "c:\foo"). /// </summary> public static bool IsSubPathOf(this string path, string baseDirPath) { var normalizedPath = NormalizePath(path); var normalizedBaseDirPath = NormalizePath(baseDirPath); return normalizedPath.StartsWith(normalizedBaseDirPath, StringComparison.OrdinalIgnoreCase); } public static string NormalizePath(this string path) { var normalizeSlashes = path.Replace('\\', '/'); // if has trailing slash then it's a directory if (normalizeSlashes.EndsWith("/")) { return Path.GetFullPath(normalizeSlashes.WithEnding("/")); } return Path.GetFullPath(normalizeSlashes); } /// <summary> /// Returns <paramref name="str"/> with the minimal concatenation of <paramref name="ending"/> (starting from end) that /// results in satisfying .EndsWith(ending). /// </summary> /// <example>"hel".WithEnding("llo") returns "hello", which is the result of "hel" + "lo".</example> public static string WithEnding(this string str, string ending) { if (str == null) return ending; string result = str; // Right() is 1-indexed, so include these cases // * Append no characters // * Append up to N characters, where N is ending length for (int i = 0; i <= ending.Length; i++) { string tmp = result + ending.Right(i); if (tmp.EndsWith(ending)) return tmp; } return result; } /// <summary>Gets the rightmost <paramref name="length" /> characters from a string.</summary> /// <param name="value">The string to retrieve the substring from.</param> /// <param name="length">The number of characters to retrieve.</param> /// <returns>The substring.</returns> public static string Right(this string value, int length) { if (value == null) { throw new ArgumentNullException("value"); } if (length < 0) { throw new ArgumentOutOfRangeException("length", length, "Length is less than zero"); } return (length < value.Length) ? value.Substring(value.Length - length) : value; } public static string Truncate(this string value, int maxChars) { return value.Length <= maxChars ? value : value.Substring(0, maxChars) + "..."; } public static string TruncateLast(this string value, int maxChars) { return value.Length <= maxChars ? value : "..." + value.Substring(value.Length-maxChars, maxChars); } } }
31.872549
123
0.607505
[ "MIT" ]
ElasticSea/BricksVR
Assets/_Framework/Scripts/Extensions/StringExtensions.cs
9,753
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class System_Collections_Generic_HashSet_1_Type_Binding_Enumerator_Binding { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; MethodBase method; Type[] args; Type type = typeof(System.Collections.Generic.HashSet<System.Type>.Enumerator); args = new Type[]{}; method = type.GetMethod("get_Current", flag, null, args, null); app.RegisterCLRMethodRedirection(method, get_Current_0); args = new Type[]{}; method = type.GetMethod("MoveNext", flag, null, args, null); app.RegisterCLRMethodRedirection(method, MoveNext_1); app.RegisterCLRCreateDefaultInstance(type, () => new System.Collections.Generic.HashSet<System.Type>.Enumerator()); } static void WriteBackInstance(ILRuntime.Runtime.Enviorment.AppDomain __domain, StackObject* ptr_of_this_method, IList<object> __mStack, ref System.Collections.Generic.HashSet<System.Type>.Enumerator instance_of_this_method) { ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); switch(ptr_of_this_method->ObjectType) { case ObjectTypes.Object: { __mStack[ptr_of_this_method->Value] = instance_of_this_method; } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = instance_of_this_method; } else { var t = __domain.GetType(___obj.GetType()) as CLRType; t.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, instance_of_this_method); } } break; case ObjectTypes.StaticFieldReference: { var t = __domain.GetType(ptr_of_this_method->Value); if(t is ILType) { ((ILType)t).StaticInstance[ptr_of_this_method->ValueLow] = instance_of_this_method; } else { ((CLRType)t).SetStaticFieldValue(ptr_of_this_method->ValueLow, instance_of_this_method); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as System.Collections.Generic.HashSet<System.Type>.Enumerator[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = instance_of_this_method; } break; } } static StackObject* get_Current_0(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Collections.Generic.HashSet<System.Type>.Enumerator instance_of_this_method = (System.Collections.Generic.HashSet<System.Type>.Enumerator)typeof(System.Collections.Generic.HashSet<System.Type>.Enumerator).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)16); var result_of_this_method = instance_of_this_method.Current; ptr_of_this_method = ILIntepreter.Minus(__esp, 1); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); return ILIntepreter.PushObject(__ret, __mStack, result_of_this_method); } static StackObject* MoveNext_1(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj) { ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain; StackObject* ptr_of_this_method; StackObject* __ret = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method); System.Collections.Generic.HashSet<System.Type>.Enumerator instance_of_this_method = (System.Collections.Generic.HashSet<System.Type>.Enumerator)typeof(System.Collections.Generic.HashSet<System.Type>.Enumerator).CheckCLRTypes(StackObject.ToObject(ptr_of_this_method, __domain, __mStack), (CLR.Utils.Extensions.TypeFlags)16); var result_of_this_method = instance_of_this_method.MoveNext(); ptr_of_this_method = ILIntepreter.Minus(__esp, 1); WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method); __intp.Free(ptr_of_this_method); __ret->ObjectType = ObjectTypes.Integer; __ret->Value = result_of_this_method ? 1 : 0; return __ret + 1; } } }
48.362205
336
0.633344
[ "MIT" ]
306739889/guessGame
Unity/Assets/Mono/ILRuntime/Generate/System_Collections_Generic_HashSet_1_Type_Binding_Enumerator_Binding.cs
6,142
C#
using memoria.Models; using System.Collections.Generic; using System.Linq; using memoria.Utils; using System.Windows.Input; using Xamarin.Forms; using System.Collections.ObjectModel; using System.Threading.Tasks; using System; using System.Threading; using memoria.Views; namespace memoria.ViewModels { [Flags] public enum Turno { Primero, // 0 Segundo, // 1 } class JuegoViewModel : BaseViewModel { public ObservableCollection<Celda> Celdas { get; set; } public Celda PrimeraCelda { get; set; } public Celda SegundaCelda { get; set; } public Turno NumTurno { get; set; } public ICommand JugarTurnoCommand { get; set; } readonly string VALUES = "AABBCCDDEEFFGGHHIIJJKKLLMMNNOOPPQQRRSSTTUUVVWWXXYYZZ"; public JuegoViewModel() { this.Celdas = new ObservableCollection<Celda>(); Stack<char> valores = GenerarValores(); for (int i = 0; i < 30; i++) { char valor = valores.Pop(); Celdas.Add(new Celda(i.ToString(), valor.ToString(), Celda.OCULTA)); } PrimeraCelda = null; SegundaCelda = null; NumTurno = Turno.Primero; JugarTurnoCommand = new Command(JugarTurno); } private void JugarTurno(object obj) { string id = (string)obj; Celda celda = Celdas.ElementAt(int.Parse(id)); switch (NumTurno) { case Turno.Primero: JugarPrimerTurno(celda); break; case Turno.Segundo: JugarSegundoTurno(celda); break; default: break; } } private void JugarPrimerTurno(Celda celda) { CambiarEstado(celda); PrimeraCelda = celda; NumTurno = Turno.Segundo; } private void JugarSegundoTurno(Celda celda) { CambiarEstado(celda); SegundaCelda = celda; ValidarSeleccionExitosa(); ValidarFinJuego(); NumTurno = Turno.Primero; } private void CambiarEstado(Celda celda) { switch (celda.Estado) { case Celda.OCULTA: celda.HacerVisible(); break; case Celda.VISIBLE: celda.Ocultar(); break; default: break; } RaisePropertyChanged("Celdas"); } private Stack<char> GenerarValores() { List<char> valores = ListUtils<char>.getRandomElements(VALUES.ToList(), 30); return new Stack<char>(valores); } private void ValidarSeleccionExitosa() { if (PrimeraCelda.ContenidoOculto == SegundaCelda.ContenidoOculto) { PrimeraCelda.HacerFija(); SegundaCelda.HacerFija(); RaisePropertyChanged("Celdas"); } else { var task = Task.Run(() => { foreach (var celda in Celdas) { if (celda.Estado != Celda.FIJA) { celda.Ocultar(); } } Thread.Sleep(500); // half a second RaisePropertyChanged("Celdas"); }); } PrimeraCelda = null; SegundaCelda = null; } private async void ValidarFinJuego() { bool final = Celdas.All((Celda celda) => { return celda.Estado == Celda.FIJA; }); if (final) { bool jugarDeNuevo = await Application.Current.MainPage.DisplayAlert( "Felicidades 🎉", "Has ganado!!! 😀, Quieres volver a jugar ?", "Si", "No" ); if (jugarDeNuevo) { await Application.Current.MainPage.Navigation.PushModalAsync(new Juego()); } else { await Application.Current.MainPage.Navigation.PushModalAsync(new MainPage()); } } } } }
27.926829
97
0.471179
[ "MIT" ]
ANDRESROMEROH/xamarin-memoria
memoria/memoria/ViewModels/JuegoViewModel.cs
4,588
C#
// This file is generated from JsonSchema. Don't modify this source code. using UniJSON; using System; using System.Collections.Generic; using UnityEngine; namespace UniGLTF.Extensions.VRMC_materials_mtoon { public static class GltfDeserializer { public static readonly Utf8String ExtensionNameUtf8 = Utf8String.From(VRMC_materials_mtoon.ExtensionName); public static bool TryGet(UniGLTF.glTFExtension src, out VRMC_materials_mtoon extension) { if(src is UniGLTF.glTFExtensionImport extensions) { foreach(var kv in extensions.ObjectItems()) { if(kv.Key.GetUtf8String() == ExtensionNameUtf8) { extension = Deserialize(kv.Value); return true; } } } extension = default; return false; } public static VRMC_materials_mtoon Deserialize(JsonNode parsed) { var value = new VRMC_materials_mtoon(); foreach(var kv in parsed.ObjectItems()) { var key = kv.Key.GetString(); if(key=="extensions"){ value.Extensions = new glTFExtensionImport(kv.Value); continue; } if(key=="extras"){ value.Extras = new glTFExtensionImport(kv.Value); continue; } if(key=="version"){ value.Version = kv.Value.GetString(); continue; } if(key=="transparentWithZWrite"){ value.TransparentWithZWrite = kv.Value.GetBoolean(); continue; } if(key=="renderQueueOffsetNumber"){ value.RenderQueueOffsetNumber = kv.Value.GetInt32(); continue; } if(key=="shadeColorFactor"){ value.ShadeColorFactor = Deserialize_ShadeColorFactor(kv.Value); continue; } if(key=="shadeMultiplyTexture"){ value.ShadeMultiplyTexture = Deserialize_ShadeMultiplyTexture(kv.Value); continue; } if(key=="shadingShiftFactor"){ value.ShadingShiftFactor = kv.Value.GetSingle(); continue; } if(key=="shadingShiftTexture"){ value.ShadingShiftTexture = Deserialize_ShadingShiftTexture(kv.Value); continue; } if(key=="shadingToonyFactor"){ value.ShadingToonyFactor = kv.Value.GetSingle(); continue; } if(key=="giIntensityFactor"){ value.GiIntensityFactor = kv.Value.GetSingle(); continue; } if(key=="matcapTexture"){ value.MatcapTexture = Deserialize_MatcapTexture(kv.Value); continue; } if(key=="parametricRimColorFactor"){ value.ParametricRimColorFactor = Deserialize_ParametricRimColorFactor(kv.Value); continue; } if(key=="rimMultiplyTexture"){ value.RimMultiplyTexture = Deserialize_RimMultiplyTexture(kv.Value); continue; } if(key=="rimLightingMixFactor"){ value.RimLightingMixFactor = kv.Value.GetSingle(); continue; } if(key=="parametricRimFresnelPowerFactor"){ value.ParametricRimFresnelPowerFactor = kv.Value.GetSingle(); continue; } if(key=="parametricRimLiftFactor"){ value.ParametricRimLiftFactor = kv.Value.GetSingle(); continue; } if(key=="outlineWidthMode"){ value.OutlineWidthMode = (OutlineWidthMode)Enum.Parse(typeof(OutlineWidthMode), kv.Value.GetString(), true); continue; } if(key=="outlineWidthFactor"){ value.OutlineWidthFactor = kv.Value.GetSingle(); continue; } if(key=="outlineWidthMultiplyTexture"){ value.OutlineWidthMultiplyTexture = Deserialize_OutlineWidthMultiplyTexture(kv.Value); continue; } if(key=="outlineColorFactor"){ value.OutlineColorFactor = Deserialize_OutlineColorFactor(kv.Value); continue; } if(key=="outlineLightingMixFactor"){ value.OutlineLightingMixFactor = kv.Value.GetSingle(); continue; } if(key=="uvAnimationMaskTexture"){ value.UvAnimationMaskTexture = Deserialize_UvAnimationMaskTexture(kv.Value); continue; } if(key=="uvAnimationScrollXSpeedFactor"){ value.UvAnimationScrollXSpeedFactor = kv.Value.GetSingle(); continue; } if(key=="uvAnimationScrollYSpeedFactor"){ value.UvAnimationScrollYSpeedFactor = kv.Value.GetSingle(); continue; } if(key=="uvAnimationRotationSpeedFactor"){ value.UvAnimationRotationSpeedFactor = kv.Value.GetSingle(); continue; } } return value; } public static float[] Deserialize_ShadeColorFactor(JsonNode parsed) { var value = new float[parsed.GetArrayCount()]; int i=0; foreach(var x in parsed.ArrayItems()) { value[i++] = x.GetSingle(); } return value; } public static TextureInfo Deserialize_ShadeMultiplyTexture(JsonNode parsed) { var value = new TextureInfo(); foreach(var kv in parsed.ObjectItems()) { var key = kv.Key.GetString(); if(key=="extensions"){ value.Extensions = new glTFExtensionImport(kv.Value); continue; } if(key=="extras"){ value.Extras = new glTFExtensionImport(kv.Value); continue; } if(key=="index"){ value.Index = kv.Value.GetInt32(); continue; } if(key=="texCoord"){ value.TexCoord = kv.Value.GetInt32(); continue; } } return value; } public static ShadingShiftTextureInfo Deserialize_ShadingShiftTexture(JsonNode parsed) { var value = new ShadingShiftTextureInfo(); foreach(var kv in parsed.ObjectItems()) { var key = kv.Key.GetString(); if(key=="extensions"){ value.Extensions = new glTFExtensionImport(kv.Value); continue; } if(key=="extras"){ value.Extras = new glTFExtensionImport(kv.Value); continue; } if(key=="index"){ value.Index = kv.Value.GetInt32(); continue; } if(key=="texCoord"){ value.TexCoord = kv.Value.GetInt32(); continue; } if(key=="scale"){ value.Scale = kv.Value.GetSingle(); continue; } } return value; } public static TextureInfo Deserialize_MatcapTexture(JsonNode parsed) { var value = new TextureInfo(); foreach(var kv in parsed.ObjectItems()) { var key = kv.Key.GetString(); if(key=="extensions"){ value.Extensions = new glTFExtensionImport(kv.Value); continue; } if(key=="extras"){ value.Extras = new glTFExtensionImport(kv.Value); continue; } if(key=="index"){ value.Index = kv.Value.GetInt32(); continue; } if(key=="texCoord"){ value.TexCoord = kv.Value.GetInt32(); continue; } } return value; } public static float[] Deserialize_ParametricRimColorFactor(JsonNode parsed) { var value = new float[parsed.GetArrayCount()]; int i=0; foreach(var x in parsed.ArrayItems()) { value[i++] = x.GetSingle(); } return value; } public static TextureInfo Deserialize_RimMultiplyTexture(JsonNode parsed) { var value = new TextureInfo(); foreach(var kv in parsed.ObjectItems()) { var key = kv.Key.GetString(); if(key=="extensions"){ value.Extensions = new glTFExtensionImport(kv.Value); continue; } if(key=="extras"){ value.Extras = new glTFExtensionImport(kv.Value); continue; } if(key=="index"){ value.Index = kv.Value.GetInt32(); continue; } if(key=="texCoord"){ value.TexCoord = kv.Value.GetInt32(); continue; } } return value; } public static TextureInfo Deserialize_OutlineWidthMultiplyTexture(JsonNode parsed) { var value = new TextureInfo(); foreach(var kv in parsed.ObjectItems()) { var key = kv.Key.GetString(); if(key=="extensions"){ value.Extensions = new glTFExtensionImport(kv.Value); continue; } if(key=="extras"){ value.Extras = new glTFExtensionImport(kv.Value); continue; } if(key=="index"){ value.Index = kv.Value.GetInt32(); continue; } if(key=="texCoord"){ value.TexCoord = kv.Value.GetInt32(); continue; } } return value; } public static float[] Deserialize_OutlineColorFactor(JsonNode parsed) { var value = new float[parsed.GetArrayCount()]; int i=0; foreach(var x in parsed.ArrayItems()) { value[i++] = x.GetSingle(); } return value; } public static TextureInfo Deserialize_UvAnimationMaskTexture(JsonNode parsed) { var value = new TextureInfo(); foreach(var kv in parsed.ObjectItems()) { var key = kv.Key.GetString(); if(key=="extensions"){ value.Extensions = new glTFExtensionImport(kv.Value); continue; } if(key=="extras"){ value.Extras = new glTFExtensionImport(kv.Value); continue; } if(key=="index"){ value.Index = kv.Value.GetInt32(); continue; } if(key=="texCoord"){ value.TexCoord = kv.Value.GetInt32(); continue; } } return value; } } // GltfDeserializer } // UniGLTF
24.576355
120
0.570655
[ "MIT" ]
Cringeyzz/UniVRM
Assets/VRM10/Runtime/Format/MaterialsMToon/Deserializer.g.cs
9,980
C#
using System.Security.Claims; using System.Threading.Tasks; using IdentityServer4.Validation; namespace IdentityServer { // If you need to add custom CLIENT claims in the client credentials // flow, you need to use a ICustomTokenRequestValidator. // // This is only applicable to the client credentials flow. // // Please note that client claims are differently configured from USER // claims. If you want to add custom USER claims, you need to use // IProfileService. public class CustomTokenRequestValidator : ICustomTokenRequestValidator { public Task ValidateAsync(CustomTokenRequestValidationContext context) { context.Result.ValidatedRequest.ClientClaims.Add(new Claim("my:client", "is:special")); return Task.CompletedTask; } } }
33.36
99
0.709832
[ "MIT" ]
Omegapoint/rest-sec
IdentityServer/CustomTokenRequestValidator.cs
834
C#
using System; using Newtonsoft.Json; namespace JsonSubTypes { // MIT License // // Copyright (c) 2017 Emmanuel Counasse // // 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. public class JsonSubtypesConverterBuilder { private Type _baseType; private string _discriminatorProperty; private readonly NullableDictionary<object, Type> _subTypeMapping = new NullableDictionary<object, Type>(); private bool _serializeDiscriminatorProperty; private bool _addDiscriminatorFirst; private Type _fallbackSubtype; public static JsonSubtypesConverterBuilder Of(Type baseType, string discriminatorProperty) { var customConverterBuilder = new JsonSubtypesConverterBuilder { _baseType = baseType, _discriminatorProperty = discriminatorProperty }; return customConverterBuilder; } public static JsonSubtypesConverterBuilder Of<T>(string discriminatorProperty) { return Of(typeof(T), discriminatorProperty); } public JsonSubtypesConverterBuilder SerializeDiscriminatorProperty() { return SerializeDiscriminatorProperty(false); } public JsonSubtypesConverterBuilder SerializeDiscriminatorProperty(bool addDiscriminatorFirst) { _serializeDiscriminatorProperty = true; _addDiscriminatorFirst = addDiscriminatorFirst; return this; } public JsonSubtypesConverterBuilder RegisterSubtype(Type subtype, object value) { _subTypeMapping.Add(value, subtype); return this; } public JsonSubtypesConverterBuilder RegisterSubtype<T>(object value) { return RegisterSubtype(typeof(T), value); } public JsonSubtypesConverterBuilder SetFallbackSubtype(Type fallbackSubtype) { _fallbackSubtype = fallbackSubtype; return this; } public JsonSubtypesConverterBuilder SetFallbackSubtype<T>(object value) { return RegisterSubtype(typeof(T), value); } public JsonConverter Build() { return new JsonSubtypesByDiscriminatorValueConverter(_baseType, _discriminatorProperty, _subTypeMapping, _serializeDiscriminatorProperty, _addDiscriminatorFirst, _fallbackSubtype); } } }
38.793478
192
0.677501
[ "CC0-1.0" ]
MufasaDoodle/GMD-Project
Assets/JsonConverter/JsonSubTypes/JsonSubtypesConverterBuilder.cs
3,571
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20181101 { /// <summary> /// Interface endpoint resource. /// </summary> [AzureNativeResourceType("azure-native:network/v20181101:InterfaceEndpoint")] public partial class InterfaceEndpoint : Pulumi.CustomResource { /// <summary> /// A reference to the service being brought into the virtual network. /// </summary> [Output("endpointService")] public Output<Outputs.EndpointServiceResponse?> EndpointService { get; private set; } = null!; /// <summary> /// Gets a unique read-only string that changes whenever the resource is updated. /// </summary> [Output("etag")] public Output<string?> Etag { get; private set; } = null!; /// <summary> /// A first-party service's FQDN that is mapped to the private IP allocated via this interface endpoint. /// </summary> [Output("fqdn")] public Output<string?> Fqdn { get; private set; } = null!; /// <summary> /// Resource location. /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// Resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Gets an array of references to the network interfaces created for this interface endpoint. /// </summary> [Output("networkInterfaces")] public Output<ImmutableArray<Outputs.NetworkInterfaceResponse>> NetworkInterfaces { get; private set; } = null!; /// <summary> /// A read-only property that identifies who created this interface endpoint. /// </summary> [Output("owner")] public Output<string> Owner { get; private set; } = null!; /// <summary> /// The provisioning state of the interface endpoint. Possible values are: 'Updating', 'Deleting', and 'Failed'. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// The ID of the subnet from which the private IP will be allocated. /// </summary> [Output("subnet")] public Output<Outputs.SubnetResponse?> Subnet { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a InterfaceEndpoint resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public InterfaceEndpoint(string name, InterfaceEndpointArgs args, CustomResourceOptions? options = null) : base("azure-native:network/v20181101:InterfaceEndpoint", name, args ?? new InterfaceEndpointArgs(), MakeResourceOptions(options, "")) { } private InterfaceEndpoint(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:network/v20181101:InterfaceEndpoint", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20180801:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20181001:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20181201:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20190201:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20190401:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20190601:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20190701:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20190801:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20190901:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20191101:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20191201:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20200301:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20200401:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20200501:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20200601:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20200701:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20200801:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-native:network/v20201101:InterfaceEndpoint"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20201101:InterfaceEndpoint"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing InterfaceEndpoint resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static InterfaceEndpoint Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new InterfaceEndpoint(name, id, options); } } public sealed class InterfaceEndpointArgs : Pulumi.ResourceArgs { /// <summary> /// A reference to the service being brought into the virtual network. /// </summary> [Input("endpointService")] public Input<Inputs.EndpointServiceArgs>? EndpointService { get; set; } /// <summary> /// Gets a unique read-only string that changes whenever the resource is updated. /// </summary> [Input("etag")] public Input<string>? Etag { get; set; } /// <summary> /// A first-party service's FQDN that is mapped to the private IP allocated via this interface endpoint. /// </summary> [Input("fqdn")] public Input<string>? Fqdn { get; set; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// The name of the interface endpoint. /// </summary> [Input("interfaceEndpointName")] public Input<string>? InterfaceEndpointName { get; set; } /// <summary> /// Resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The ID of the subnet from which the private IP will be allocated. /// </summary> [Input("subnet")] public Input<Inputs.SubnetArgs>? Subnet { get; set; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public InterfaceEndpointArgs() { } } }
47.347458
147
0.599785
[ "Apache-2.0" ]
sebtelko/pulumi-azure-native
sdk/dotnet/Network/V20181101/InterfaceEndpoint.cs
11,174
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ModelApp.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.290323
151
0.580433
[ "Apache-2.0" ]
michaelyes/LiteORM-For-DotNet
ModelApp/Properties/Settings.Designer.cs
1,065
C#
// Copyright (c) Microsoft. All rights reserved. namespace DevOpsLib { public enum BuildDefinitionId { BuildImages = 55174, CI = 45137, EdgeletCI = 37729, EdgeletPackages = 55463, EdgeletRelease = 31845, EndToEndTest = 87020, NestedEndToEndTest = 183241, ImageRelease = 31987, LibiothsmCI = 39853, ConnectivityTest = 108949, NestedConnectivityTest = 167737, LonghaulTestEnv1 = 66429, LonghaulTestEnv2 = 93654, LonghaulTestEnv3 = 93725, NestedLonghaulTest = 195636, StressTestEnv1 = 66357, StressTestEnv2 = 96102, StressTestEnv3 = 96103, } }
26.807692
48
0.609756
[ "MIT" ]
butlfrazp/iotedge
tools/IoTEdgeDevOps/DevOpsLib/BuildDefinitionId.cs
697
C#
using AssetConfigurator; using System; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.Events; public class RockPaperScissors : MonoBehaviour { // player = attack // 0 = player is draw // 1 = player is winner // 2 = player is loser private int[,] rpsMatrix = new int[3, 3] { // defend>r p s // attack v { 0, 2, 1 }, // rock (r) { 1, 0, 2 }, // paper (p) { 2, 1, 0 } // scissors (s) }; [SerializeField] private GameObject demonDog; [SerializeField] private AudioSource ambientAudio; [SerializeField] private AudioSource endbossAudio; [SerializeField] private AudioSource demonDogDefeated; [SerializeField] private AudioSource demonDogAttack; [SerializeField] private AudioSource demonDogHit; [SerializeField] private AudioSource demonDogHowl; [SerializeField] private AudioSource roundGoGoGo; [SerializeField] private List<GameObject> rpsCubes; [SerializeField] private TextMeshProUGUI leftRpsDebugText; [SerializeField] private TextMeshProUGUI rightRpsDebugText; [SerializeField] private TextMeshProUGUI roundStateDebugText; [SerializeField] private TextMeshProUGUI scoreDebugText; [SerializeField] private GetCustomGestureAction getCustomGestureAction; [SerializeField] private UnityEvent finishedBoss; private AssetConfigurationData target; private int currentCubeIndex; private int lastCubeIndex; private bool checkForResult; private bool gameOver; [SerializeField] private int score; private void Start() { foreach (GameObject cube in rpsCubes) { cube.SetActive(false); } score = 0; lastCubeIndex = -1; roundStateDebugText.text = "WAIT FOR NEXT\nROUND TO START"; InvokeRepeating("SetRandomCubeActive", 3, 3); target = demonDog.GetComponent<AssetConfigurationData>(); ambientAudio.Stop(); endbossAudio.Play(); // animation enter the scene target.TargetAnimator.Play(target.AnimationOptions[6].Animation.name); demonDogHowl.Play(); } private void Update() { if (!gameOver) { CustomGestures currentLeftHandGesture = getCustomGestureAction.QueryForLeftHandGestures(); CustomGestures currentRightHandGesture = getCustomGestureAction.QueryForRightHandGestures(); if (checkForResult) { leftRpsDebugText.text = GetDebugTextRps((int)currentLeftHandGesture, currentCubeIndex); } if (checkForResult) { rightRpsDebugText.text = GetDebugTextRps((int)currentRightHandGesture, currentCubeIndex); } scoreDebugText.text = "Your score: " + score; CheckIfBossIsDefeated(); } } private string GetDebugTextRps(int attacker, int defender) { string resultText = "NO RESULT"; roundStateDebugText.text = "GOGOGOGOGO!!!"; if (attacker >= 0) { int result = rpsMatrix[attacker, defender]; switch (result) { case 0: checkForResult = false; resultText = Enum.GetName(typeof(CustomGestures), attacker) + " DRAW"; roundStateDebugText.text = "WAIT FOR NEXT\nROUND TO START"; break; case 1: checkForResult = false; resultText = Enum.GetName(typeof(CustomGestures), attacker) + " YOU WIN"; roundStateDebugText.text = "WAIT FOR NEXT\nROUND TO START"; score++; // animation got hit target.TargetAnimator.Play(target.AnimationOptions[6].Animation.name); demonDogHit.Play(); break; case 2: checkForResult = false; resultText = Enum.GetName(typeof(CustomGestures), attacker) + " YOU LOSE"; roundStateDebugText.text = "WAIT FOR NEXT\nROUND TO START"; score--; // animation attack target.TargetAnimator.Play(target.AnimationOptions[2].Animation.name); demonDogAttack.Play(); break; } } return resultText; } private void CheckIfBossIsDefeated() { if (score >= 3) { CancelInvoke(); roundStateDebugText.text = "YOU WON!\nEXIT NOW!"; // animation die target.TargetAnimator.Play(target.AnimationOptions[4].Animation.name); // unlock door gameOver = true; endbossAudio.Stop(); demonDogDefeated.Play(); finishedBoss.Invoke(); } } private void SetRandomCubeActive() { if (lastCubeIndex >= 0) { rpsCubes[lastCubeIndex].SetActive(false); } currentCubeIndex = UnityEngine.Random.Range(0, 3); rpsCubes[currentCubeIndex].SetActive(true); lastCubeIndex = currentCubeIndex; checkForResult = true; roundGoGoGo.Play(); } }
31.401198
105
0.599924
[ "MIT" ]
brewmanandi/fb-xr-hackathong
Assets/Scripts/MaxHandTracking/GameMechanics/RockPaperScissors.cs
5,244
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("fukuv0625")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("fukuv0625")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // 次の GUID は、このプロジェクトが COM に公開される場合の、typelib の ID です [assembly: Guid("b7205159-8fce-45b1-bfe9-9772ad038e99")] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // Major Version // Minor Version // Build Number // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
29.432432
57
0.743802
[ "MIT" ]
kantasato/fukuv0625
fukuv0625/Properties/AssemblyInfo.cs
1,614
C#
namespace AbstractFactory.Facory { public interface IHero { } }
11.666667
33
0.714286
[ "Apache-2.0" ]
v-IIX/qj
csharp/DesignPattern/AbstractFactory/Facory/IHero.cs
72
C#
using Heroes.Models.AbilityTalents; using HeroesData.Parser.Overrides.DataOverrides; using HeroesData.Parser.Overrides.PropertyOverrides; using System; using System.Xml.Linq; namespace HeroesData.Parser.Overrides { public class UnitOverrideLoader : OverrideLoaderBase<UnitDataOverride>, IOverrideLoader { public UnitOverrideLoader(int? hotsBuild) : base(hotsBuild) { } public UnitOverrideLoader(string appPath, int? hotsBuild) : base(appPath, hotsBuild) { } protected override string OverrideFileName => $"unit-{base.OverrideFileName}"; protected override string OverrideElementName => "CUnit"; protected override void SetOverride(XElement element) { if (element is null) throw new ArgumentNullException(nameof(element)); UnitDataOverride unitDataOverride = new UnitDataOverride(); AbilityPropertyOverride abilityOverride = new AbilityPropertyOverride(); WeaponPropertyOverride weaponOverride = new WeaponPropertyOverride(); string unitId = element.Attribute("id")?.Value ?? string.Empty; foreach (XElement dataElement in element.Elements()) { string elementName = dataElement.Name.LocalName; string valueAttribute = dataElement.Attribute("value")?.Value ?? string.Empty; XElement? overrideElement; switch (elementName) { case "Name": unitDataOverride.NameOverride = (true, valueAttribute); break; case "HyperlinkId": unitDataOverride.HyperlinkIdOverride = (true, valueAttribute); break; case "CUnit": unitDataOverride.CUnitOverride = (true, valueAttribute); break; case "EnergyType": unitDataOverride.EnergyTypeOverride = (true, valueAttribute); break; case "Energy": string energyValue = valueAttribute; if (int.TryParse(energyValue, out int value)) { if (value < 0) value = 0; unitDataOverride.EnergyOverride = (true, value); } else { unitDataOverride.EnergyOverride = (true, 0); } break; case "ParentLink": unitDataOverride.ParentLinkOverride = (true, valueAttribute); break; case "Ability": string id = dataElement.Attribute("id")?.Value ?? string.Empty; string? abilityType = dataElement.Attribute("abilityType")?.Value; string? passiveAbility = dataElement.Attribute("passive")?.Value; string? addedAbility = dataElement.Attribute("add")?.Value; AbilityTalentId abilityTalentId = new AbilityTalentId(string.Empty, string.Empty); string[] idSplit = id.Split(',', StringSplitOptions.RemoveEmptyEntries); if (idSplit.Length >= 2) { abilityTalentId.ReferenceId = idSplit[0]; abilityTalentId.ButtonId = idSplit[1]; } else if (idSplit.Length == 1) { abilityTalentId.ReferenceId = idSplit[0]; abilityTalentId.ButtonId = idSplit[0]; } if (Enum.TryParse(abilityType, true, out AbilityTypes abilityTypeResult)) abilityTalentId.AbilityType = abilityTypeResult; if (bool.TryParse(passiveAbility, out bool abilityPassiveResult)) abilityTalentId.IsPassive = abilityPassiveResult; if (bool.TryParse(addedAbility, out bool abilityAddedResult)) { unitDataOverride.AddAddedAbility(abilityTalentId, abilityAddedResult); if (!abilityAddedResult) continue; } if (!string.IsNullOrEmpty(id)) { overrideElement = dataElement.Element("Override"); if (overrideElement != null) abilityOverride.SetOverride(abilityTalentId.ToString(), overrideElement, unitDataOverride.PropertyAbilityOverrideMethodByAbilityId); } break; case "Weapon": string? weaponId = dataElement.Attribute("id")?.Value; string? addedWeapon = dataElement.Attribute("add")?.Value; if (string.IsNullOrEmpty(weaponId)) continue; if (bool.TryParse(addedWeapon, out bool weaponValidResult)) { unitDataOverride.AddAddedWeapon(weaponId, weaponValidResult); if (!weaponValidResult) continue; } overrideElement = dataElement.Element("Override"); if (overrideElement != null) weaponOverride.SetOverride(weaponId, overrideElement, unitDataOverride.PropertyWeaponOverrideMethodByWeaponId); break; } } DataOverridesById[unitId] = unitDataOverride; } } }
41.917241
164
0.499671
[ "MIT" ]
HeroesToolChest/HeroesDataParser
HeroesData.Parser/Overrides/UnitOverrideLoader.cs
6,080
C#
/* * Lyzard Modeling and Simulation System * * Copyright 2019 William W. Westlake Jr. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using System.Collections.Generic; using ICSharpCode.AvalonEdit.Document; using ICSharpCode.AvalonEdit.Utils; namespace ICSharpCode.AvalonEdit.Editing { /// <summary> /// <see cref="IReadOnlySectionProvider"/> that has no read-only sections; all text is editable. /// </summary> sealed class NoReadOnlySections : IReadOnlySectionProvider { public static readonly NoReadOnlySections Instance = new NoReadOnlySections(); public bool CanInsert(int offset) { return true; } public IEnumerable<ISegment> GetDeletableSegments(ISegment segment) { if (segment == null) throw new ArgumentNullException("segment"); // the segment is always deletable return ExtensionMethods.Sequence(segment); } } /// <summary> /// <see cref="IReadOnlySectionProvider"/> that completely disables editing. /// </summary> sealed class ReadOnlyDocument : IReadOnlySectionProvider { public static readonly ReadOnlyDocument Instance = new ReadOnlyDocument(); public bool CanInsert(int offset) { return false; } public IEnumerable<ISegment> GetDeletableSegments(ISegment segment) { return Enumerable.Empty<ISegment>(); } } }
28.538462
97
0.739084
[ "Apache-2.0" ]
wwestlake/Lyzard
ICSharpCode.AvalonEdit/Editing/NoReadOnlySections.cs
1,857
C#
//------------------------------------------------------------------------------ // <auto-generated> // 此代码由工具生成。 // 运行时版本: 4.0.30319.42000 // // 对此文件的更改可能会导致不正确的行为,并且如果 // 重新生成代码,这些更改将丢失。 // </auto-generated> //------------------------------------------------------------------------------ namespace LiteQnaireEditor.Properties { /// <summary> /// 一个强类型的资源类,用于查找本地化的字符串等。 /// </summary> // 此类是由 StronglyTypedResourceBuilder // 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。 // 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen // (以 /str 作为命令选项),或重新生成 VS 项目。 [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// 返回此类使用的、缓存的 ResourceManager 实例。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("LiteQnaireEditor.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// 为所有资源查找重写当前线程的 CurrentUICulture 属性, /// 方法是使用此强类型资源类。 /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
34.125
182
0.577941
[ "MIT" ]
Nekorokke/LiteQnaire-Project
SourceCode/LiteQnaireEditor/LiteQnaireEditor/Properties/Resources.Designer.cs
2,813
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web.Mvc; namespace Blip.Data { public class RegionsRepository { public IEnumerable<SelectListItem> GetRegions() { List<SelectListItem> regions = new List<SelectListItem>() { new SelectListItem { Value = null, Text = " " } }; return regions; } public IEnumerable<SelectListItem> GetRegions(string iso3) { if (!String.IsNullOrWhiteSpace(iso3)) { using (var context = new ApplicationDbContext()) { IEnumerable<SelectListItem> regions = context.Regions.AsNoTracking() .OrderBy(n => n.RegionNameEnglish) .Where(n => n.Iso3 == iso3) .Select(n => new SelectListItem { Value = n.RegionCode, Text = n.RegionNameEnglish }).ToList(); return new SelectList(regions, "Value", "Text"); } } return null; } } }
30.090909
88
0.436556
[ "MIT" ]
Alikhan01/BlipBinding
Blip.Data/Geographies/RegionsRepository.cs
1,326
C#
using NetWork.Utilities; using ProtoBuf; using System; using System.ComponentModel; namespace Package { [ForRecv(940), ForSend(940), ProtoContract(Name = "IntensifyPositionReq")] [Serializable] public class IntensifyPositionReq : IExtensible { public static readonly short OP = 940; private int _position; private int _intensifyStoneId; private IExtension extensionObject; [ProtoMember(1, IsRequired = true, Name = "position", DataFormat = DataFormat.TwosComplement)] public int position { get { return this._position; } set { this._position = value; } } [ProtoMember(2, IsRequired = false, Name = "intensifyStoneId", DataFormat = DataFormat.TwosComplement), DefaultValue(0)] public int intensifyStoneId { get { return this._intensifyStoneId; } set { this._intensifyStoneId = value; } } IExtension IExtensible.GetExtensionObject(bool createIfMissing) { return Extensible.GetExtensionObject(ref this.extensionObject, createIfMissing); } } }
19.942308
122
0.717454
[ "MIT" ]
corefan/tianqi_src
src/Package/IntensifyPositionReq.cs
1,037
C#
public enum GridElements { EMPTY, OBSTACLE, TARGET }
12.8
26
0.640625
[ "MIT" ]
TUM-MLCMS/Crowd-Simulation-and-Visualization-in-Unity
Assets/Scripts/GridElements.cs
64
C#
 using System.Runtime.CompilerServices; namespace Serenity { [Imported(ObeysTypeSystem = true)] public interface ISetEditValue { void SetEditValue(dynamic source, PropertyItem property); } }
20.545455
66
0.685841
[ "MIT" ]
BTDevelop/Serenity
Serenity.Script.UI/PropertyGrid/ISetEditValue.cs
228
C#
using BusinessLayer.Abstract; using DataAccessLayer.Abstract; using EntityLayer.Concrete; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BusinessLayer.Concrete { public class AboutManager: IAboutService { IAboutDal _aboutDal; public AboutManager(IAboutDal aboutDal) { _aboutDal = aboutDal; } public About TGetById(int id) { throw new NotImplementedException(); } public List<About> GetList() { return _aboutDal.GetListAll(); } public void TAdd(About t) { throw new NotImplementedException(); } public void TDelete(About t) { throw new NotImplementedException(); } public void TUpdate(About t) { throw new NotImplementedException(); } } }
20.446809
48
0.593132
[ "MIT" ]
mertozler/BlogPanel
BusinessLayer/Concrete/AboutManager.cs
963
C#
namespace ExistsForAll.Shepherd.SimpleInjector.UnitTests.Subjects { public interface IOpenGenerics<T> { T TypeOfGeneric { get; set; } } }
21.285714
67
0.731544
[ "MIT" ]
existall/Shepherd
src/tests/ExistsForAll.Shepherd.SimpleInjector.UnitTests.Subjects/IOpenGenerics.cs
151
C#
using System; namespace Xms.Solution.Abstractions { public interface ISolutionComponentExporter { string GetXml(Guid solutionId); } }
17.222222
47
0.709677
[ "MIT" ]
861191244/xms
Libraries/Solution/Xms.Solution.Abstractions/ISolutionComponentExporter.cs
157
C#
#region License // Pomona is open source software released under the terms of the LICENSE specified in the // project's repository, or alternatively at http://pomona.io/ #endregion using NUnit.Framework; using Pomona.Common; using Pomona.Common.Proxies; namespace Pomona.UnitTests.Client { [TestFixture] public class ClientResourceTests { [Test] public void IsPersisted_OnPostForm_ReturnsFalse() { Assert.That((new DummyForm()).IsPersisted(), Is.False); } [Test] public void IsPersisted_OnResourceForm_ReturnsFalse() { Assert.That((new DummyResource()).IsPersisted(), Is.True); } [Test] public void IsTransient_OnPostForm_ReturnsTrue() { Assert.That((new DummyForm()).IsTransient(), Is.True); } [Test] public void IsTransient_OnResourceForm_ReturnsFalse() { Assert.That((new DummyResource()).IsTransient(), Is.False); } public class DummyForm : PostResourceBase, IClientResource { } public class DummyResource : ResourceBase, IClientResource { } } }
23.277778
91
0.591885
[ "MIT" ]
Pomona/Pomona
tests/Pomona.UnitTests/Client/ClientResourceTests.cs
1,206
C#
/* * The official C# API client for alpaca brokerage * Sourced from: https://github.com/alpacahq/alpaca-trade-api-csharp/commit/161b114b4b40d852a14a903bd6e69d26fe637922 */ using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace QuantConnect.Brokerages.Alpaca.Markets { /// <summary> /// Order side in Alpaca REST API. /// </summary> [JsonConverter(typeof(StringEnumConverter))] public enum OrderSide { /// <summary> /// Buy order. /// </summary> [EnumMember(Value = "buy")] Buy, /// <summary> /// Sell order. /// </summary> [EnumMember(Value = "sell")] Sell } }
24.066667
116
0.616343
[ "Apache-2.0" ]
AdvaithD/Lean
Brokerages/Alpaca/Markets/Enums/OrderSide.cs
724
C#
// Copyright (c) Stride contributors (https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System.ComponentModel; using Stride.Core; using Stride.Core.Annotations; using Stride.Engine.Design; using Stride.Engine.Processors; using Stride.Graphics; using Stride.Rendering; using Stride.Rendering.Background; namespace Stride.Engine { /// <summary> /// Add a background to an <see cref="Entity"/>. /// </summary> [DataContract("BackgroundComponent")] [Display("Background", Expand = ExpandRule.Once)] [DefaultEntityComponentRenderer(typeof(BackgroundRenderProcessor))] [ComponentOrder(9600)] public sealed class BackgroundComponent : ActivableEntityComponent { /// <summary> /// Create an empty Background component. /// </summary> public BackgroundComponent() { Intensity = 1f; } /// <summary> /// Gets or sets the texture to use as background /// </summary> /// <userdoc>The reference to the texture to use as background</userdoc> [DataMember(10)] [Display("Texture")] public Texture Texture { get; set; } /// <summary> /// Gets or sets the intensity. /// </summary> /// <value>The intensity.</value> /// <userdoc>The intensity of the background color</userdoc> [DataMember(20)] [DefaultValue(1.0f)] [DataMemberRange(0.0, 100.0, 0.01f, 1.0f, 2)] public float Intensity { get; set; } /// <summary> /// The render group for this component. /// </summary> [DataMember(30)] [Display("Render group")] [DefaultValue(RenderGroup.Group0)] public RenderGroup RenderGroup { get; set; } /// <summary> /// Indicate if the background should behave like a 2D image. /// </summary> /// <userdoc>Use the texture as a static 2D background (useful for 2D applications)</userdoc> [DataMember(40)] [Display("2D background")] [DefaultValue(false)] public bool Is2D { get; set; } = false; } }
32.797101
118
0.617322
[ "MIT" ]
Aggror/Stride
sources/engine/Stride.Engine/Engine/BackgroundComponent.cs
2,263
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Compute.V20190301.Inputs { /// <summary> /// Contains the IP tag associated with the public IP address. /// </summary> public sealed class VirtualMachineScaleSetIpTagArgs : Pulumi.ResourceArgs { /// <summary> /// IP tag type. Example: FirstPartyUsage. /// </summary> [Input("ipTagType")] public Input<string>? IpTagType { get; set; } /// <summary> /// IP tag associated with the public IP. Example: SQL, Storage etc. /// </summary> [Input("tag")] public Input<string>? Tag { get; set; } public VirtualMachineScaleSetIpTagArgs() { } } }
28.428571
81
0.630151
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Compute/V20190301/Inputs/VirtualMachineScaleSetIpTagArgs.cs
995
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChangeGravity : MonoBehaviour { public Vector3 lastPos; bool left = false; public float gravOffsetX = .5f; public float gravOffsetY = .5f; public Vector3 gravityVec = new Vector3 (0f, -9.8f, 0f); public bool dead = false; public float gravityAxisVal; public float gravityAxisValSlow; public bool triggers = true; // Start is called before the first frame update void Start() { lastPos = Input.mousePosition; } // Update is called once per frame void Update() { //if (Input.GetKey("joystick button 3")){ // if (triggers){ // triggers = false; // } // else{ // triggers = true; // } //} if (triggers){ gravityAxisVal = Input.GetAxis("Gravity"); gravityAxisValSlow = Input.GetAxis("GravitySlow"); if(Mathf.Abs(gravityAxisVal) >= Mathf.Abs(gravityAxisValSlow)) { if (gravityAxisVal > 0.01f || gravityAxisVal < -0.01f) { Debug.Log(gravityAxisVal); transform.Rotate(0, 0, gravityAxisVal); } } else { if (gravityAxisValSlow > 0.01f || gravityAxisValSlow < -0.01f) { Debug.Log(gravityAxisValSlow); transform.Rotate(0, 0, gravityAxisValSlow/2.0f); } } } else{ gravityAxisVal = Input.GetAxis("GravAlt"); if (gravityAxisVal > 0.01f || gravityAxisVal < -0.01f) { Debug.Log(gravityAxisVal); transform.Rotate(0, 0, gravityAxisVal); } } if (!dead && Input.GetMouseButton(0)){ Debug.Log(Input.mousePosition); if (Input.mousePosition.x == lastPos.x){ if (left){ transform.Rotate(0, 0, -1.5f); } else{ transform.Rotate(0, 0, 1.5f); } } if (Input.mousePosition.x > lastPos.x){ transform.Rotate(0, 0, 1.5f); left = false; } if (Input.mousePosition.x < lastPos.x){ transform.Rotate(0, 0, -1.5f); left = true; } } if (!dead && Input.GetKey(KeyCode.RightArrow)) { transform.Rotate(0, 0, 1.0f); } if (!dead && Input.GetKey(KeyCode.LeftArrow)) { transform.Rotate(0, 0, -1.0f); } lastPos = Input.mousePosition; Physics.gravity = -1f * transform.up.normalized * Physics.gravity.magnitude; //Debug.DrawRay(transform.position, Physics.gravity,Color.blue); } }
29.919192
84
0.490209
[ "MIT" ]
SirBrect/TimeTower
Capstone2 Prac/Assets/Scripts/ChangeGravity.cs
2,964
C#
// // SocketClient.cs // // Author: // Martin Baulig <mabaul@microsoft.com> // // Copyright (c) 2018 Xamarin Inc. (http://www.xamarin.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; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; namespace Xamarin.AsyncTests.Remoting { public class SocketClient : IDisposable { Socket socket; NetworkStream stream; public NetworkStream Stream => stream; public SocketClient () { socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } public Task ConnectAsync (EndPoint address, CancellationToken cancellationToken) { var tcs = new TaskCompletionSource<Socket> (); if (cancellationToken.IsCancellationRequested) { tcs.SetCanceled (); return tcs.Task; } var args = new SocketAsyncEventArgs (); args.RemoteEndPoint = address; args.Completed += (sender, e) => { if (cancellationToken.IsCancellationRequested) { tcs.TrySetCanceled (); } else if (args.SocketError != SocketError.Success) { var error = new IOException ($"AcceptAsync() failed: {args.SocketError})"); tcs.TrySetException (error); } else { stream = new NetworkStream (socket); tcs.TrySetResult (null); } args.Dispose (); }; try { if (!socket.ConnectAsync (args)) throw new InvalidOperationException (); } catch (Exception ex) { tcs.TrySetException (ex); } return tcs.Task; } int disposed; protected virtual void Dispose (bool disposing) { if (Interlocked.CompareExchange (ref disposed, 1, 0) != 0) return; if (socket != null) { try { socket.Dispose (); } catch { ; } socket = null; } } public void Dispose () { Dispose (true); } } }
27.854369
89
0.699198
[ "MIT" ]
xamarin/web-tests
Xamarin.AsyncTests.Framework/Xamarin.AsyncTests.Remoting/SocketClient.cs
2,871
C#
// ReSharper disable All using System; using System.Collections.Generic; using System.Dynamic; using PetaPoco; using MixERP.Net.Entities.Transactions; namespace MixERP.Net.Schemas.Transactions.Data { public interface IGetEoyProfitSummaryRepository { int OfficeId { get; set; } /// <summary> /// Prepares and executes IGetEoyProfitSummaryRepository. /// </summary> IEnumerable<DbGetEoyProfitSummaryResult> Execute(); } }
24.894737
65
0.708245
[ "MPL-2.0" ]
asine/mixerp
src/Libraries/DAL/Transactions/IGetEoyProfitSummaryRepository.cs
473
C#
using DeanAndSons.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace DeanAndSons.Models.WAP { public class ContactUser : Contact { [ForeignKey("ApplicationUser")] public string UserID { get; set; } public ApplicationUser ApplicationUser { get; set; } public ContactUser() { } public ContactUser(string propertyNo, string street, string town, string postCode, int? telephoneNo, string email, ApplicationUser userObj) { base.PropertyNo = propertyNo; base.Street = street; base.Town = town; base.PostCode = postCode; base.TelephoneNo = telephoneNo; base.Email = email; ApplicationUser = userObj; } } }
27.515152
148
0.609031
[ "Apache-2.0" ]
DACunningham/DeanAndSons
DeanAndSons/DeanAndSons/Models/WAP/ContactUser.cs
910
C#
namespace Decent.Minecraft.Client.Blocks { /// <summary> /// <a href="http://minecraft.gamepedia.com/Door">Gamepedia link</a>. /// </summary> public abstract class Door : IBlock { } public abstract class DoorTop : Door { protected DoorTop(bool isHingeOnTheRight, bool isPowered) { IsHingeOnTheRight = isHingeOnTheRight; IsPowered = isPowered; } public bool IsHingeOnTheRight { get; } public bool IsPowered { get; } } public abstract class DoorBottom : Door { protected DoorBottom(bool open, Direction facing) { IsOpen = open; // A Door is facing the direction you are facing when you place it or the direction it swings in. Facing = facing; } public bool IsOpen { get; } public Direction Facing { get; } } public interface IronDoor : IBlock { } public interface WoodenDoor : IBlock { } public class IronDoorTop : DoorTop, IronDoor { public IronDoorTop(bool isHingeOnTheRight, bool powered) : base(isHingeOnTheRight, powered) { } } public class IronDoorBottom : DoorBottom, IronDoor { public IronDoorBottom(bool open = false, Direction facing = Direction.South) : base(open, facing) { } } public class WoodenDoorTop : DoorTop, WoodenDoor { public WoodenDoorTop(bool isHingeOnTheRight = false, bool powered = false, WoodSpecies species = WoodSpecies.Oak) : base(isHingeOnTheRight, powered) { Species = species; } public WoodSpecies Species { get; } } public class WoodenDoorBottom : DoorBottom, WoodenDoor { public WoodenDoorBottom(bool open = false, Direction facing = Direction.South, WoodSpecies species = WoodSpecies.Oak) : base(open, facing) { Species = species; } public WoodSpecies Species { get; } } }
29.358209
156
0.620234
[ "MIT" ]
bleroy/minecraft.client
Decent.Minecraft.Client/Blocks/Door.cs
1,969
C#
/* * Copyright 2010-2013 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. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.IdentityManagement.Model { /// <summary> /// Container for the parameters to the UpdateLoginProfile operation. /// <para>Changes the password for the specified user.</para> /// </summary> public partial class UpdateLoginProfileRequest : AmazonIdentityManagementServiceRequest { private string userName; private string password; /// <summary> /// Name of the user whose password you want to update. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 64</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\w+=,.@-]*</description> /// </item> /// </list> /// </para> /// </summary> public string UserName { get { return this.userName; } set { this.userName = value; } } // Check to see if UserName property is set internal bool IsSetUserName() { return this.userName != null; } /// <summary> /// The new password for the user name. /// /// <para> /// <b>Constraints:</b> /// <list type="definition"> /// <item> /// <term>Length</term> /// <description>1 - 128</description> /// </item> /// <item> /// <term>Pattern</term> /// <description>[\u0009\u000A\u000D\u0020-\u00FF]+</description> /// </item> /// </list> /// </para> /// </summary> public string Password { get { return this.password; } set { this.password = value; } } // Check to see if Password property is set internal bool IsSetPassword() { return this.password != null; } } }
29.123711
91
0.538407
[ "Apache-2.0" ]
virajs/aws-sdk-net
AWSSDK_DotNet35/Amazon.IdentityManagement/Model/UpdateLoginProfileRequest.cs
2,825
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Reflection; using System.Threading.Tasks; using Microsoft.DotNet.RemoteExecutor; using Xunit; namespace System.Diagnostics.Tests { public class ActivityTests : IDisposable { /// <summary> /// Tests Activity constructor /// </summary> [Fact] public void DefaultActivity() { string activityName = "activity"; var activity = new Activity(activityName); Assert.Equal(activityName, activity.OperationName); Assert.Null(activity.Id); Assert.Null(activity.RootId); Assert.Equal(TimeSpan.Zero, activity.Duration); Assert.Null(activity.Parent); Assert.Null(activity.ParentId); Assert.Equal(0, activity.Baggage.ToList().Count); Assert.Equal(0, activity.Tags.ToList().Count); } /// <summary> /// Tests baggage operations /// </summary> [Fact] public void Baggage() { var activity = new Activity("activity"); // Baggage starts off empty Assert.Null(activity.GetBaggageItem("some baggage")); Assert.Empty(activity.Baggage); const string Key = "some baggage"; const string Value = "value"; // Add items, get them individually and via an enumerable for (int i = 0; i < 3; i++) { Assert.Equal(activity, activity.AddBaggage(Key + i, Value + i)); Assert.Equal(Value + i, activity.GetBaggageItem(Key + i)); Assert.Equal(i + 1, activity.Baggage.Count()); for (int j = 0; j < i; j++) { Assert.Contains(new KeyValuePair<string, string>(Key + j, Value + j), activity.Baggage); } } // Now test baggage via child activities activity.Start(); try { // Start a child var anotherActivity = new Activity("another activity"); anotherActivity.Start(); try { // Its parent should match. Assert.Same(activity, anotherActivity.Parent); // All of the parent's baggage should be available via the child. for (int i = 0; i < 3; i++) { Assert.Equal(Value + i, anotherActivity.GetBaggageItem(Key + i)); Assert.Contains(new KeyValuePair<string, string>(Key + i, Value + i), anotherActivity.Baggage); } // And we should be able to add additional baggage to the child, see that baggage, and still see the parent's. Assert.Same(anotherActivity, anotherActivity.AddBaggage("hello", "world")); Assert.Equal("world", anotherActivity.GetBaggageItem("hello")); Assert.Equal(4, anotherActivity.Baggage.Count()); Assert.Equal(new KeyValuePair<string, string>("hello", "world"), anotherActivity.Baggage.First()); Assert.Equal(new KeyValuePair<string, string>(Key + 2, Value + 2), anotherActivity.Baggage.Skip(1).First()); Assert.Equal(new KeyValuePair<string, string>(Key + 1, Value + 1), anotherActivity.Baggage.Skip(2).First()); Assert.Equal(new KeyValuePair<string, string>(Key + 0, Value + 0), anotherActivity.Baggage.Skip(3).First()); } finally { anotherActivity.Stop(); } } finally { activity.Stop(); } } [Fact] public void TestBaggageOrderAndDuplicateKeys() { Activity a = new Activity("Baggage"); a.AddBaggage("1", "1"); a.AddBaggage("1", "2"); a.AddBaggage("1", "3"); a.AddBaggage("1", "4"); int value = 4; foreach (KeyValuePair<string, string> kvp in a.Baggage) { Assert.Equal("1", kvp.Key); Assert.Equal(value.ToString(), kvp.Value); value--; } Assert.Equal("4", a.GetBaggageItem("1")); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void TestBaggageWithChainedActivities() { RemoteExecutor.Invoke(() => { Activity a1 = new Activity("a1"); a1.Start(); a1.AddBaggage("1", "1"); a1.AddBaggage("2", "2"); IEnumerable<KeyValuePair<string, string>> baggages = a1.Baggage; Assert.Equal(2, baggages.Count()); Assert.Equal(new KeyValuePair<string, string>("2", "2"), baggages.ElementAt(0)); Assert.Equal(new KeyValuePair<string, string>("1", "1"), baggages.ElementAt(1)); Activity a2 = new Activity("a2"); a2.Start(); a2.AddBaggage("3", "3"); baggages = a2.Baggage; Assert.Equal(3, baggages.Count()); Assert.Equal(new KeyValuePair<string, string>("3", "3"), baggages.ElementAt(0)); Assert.Equal(new KeyValuePair<string, string>("2", "2"), baggages.ElementAt(1)); Assert.Equal(new KeyValuePair<string, string>("1", "1"), baggages.ElementAt(2)); Activity a3 = new Activity("a3"); a3.Start(); a3.AddBaggage("4", "4"); baggages = a3.Baggage; Assert.Equal(4, baggages.Count()); Assert.Equal(new KeyValuePair<string, string>("4", "4"), baggages.ElementAt(0)); Assert.Equal(new KeyValuePair<string, string>("3", "3"), baggages.ElementAt(1)); Assert.Equal(new KeyValuePair<string, string>("2", "2"), baggages.ElementAt(2)); Assert.Equal(new KeyValuePair<string, string>("1", "1"), baggages.ElementAt(3)); a3.Dispose(); a2.Dispose(); a1.Dispose(); }).Dispose(); } /// <summary> /// Tests Tags operations /// </summary> [Fact] public void Tags() { var activity = new Activity("activity"); Assert.Empty(activity.Tags); const string Key = "some tag"; const string Value = "value"; for (int i = 0; i < 3; i++) { Assert.Equal(activity, activity.AddTag(Key + i, Value + i)); List<KeyValuePair<string, string>> tags = activity.Tags.ToList(); Assert.Equal(i + 1, tags.Count); Assert.Equal(tags[i].Key, Key + i); Assert.Equal(tags[i].Value, Value + i); } } /// <summary> /// Tests activity SetParentId /// </summary> [Fact] public void SetParentId() { var parent = new Activity("parent"); parent.SetParentId(null); // Error does nothing Assert.Null(parent.ParentId); parent.SetParentId(""); // Error does nothing Assert.Null(parent.ParentId); parent.SetParentId("1"); Assert.Equal("1", parent.ParentId); parent.SetParentId("2"); // Error does nothing Assert.Equal("1", parent.ParentId); Assert.Equal(parent.ParentId, parent.RootId); parent.Start(); var child = new Activity("child"); child.Start(); Assert.Equal(parent.Id, child.ParentId); child.SetParentId("3"); // Error does nothing; Assert.Equal(parent.Id, child.ParentId); } /// <summary> /// Tests activity SetParentId /// </summary> [Fact] public void ActivityIdOverflow() { //check parentId |abc.1.1...1.1.1.1.1. (1023 bytes) and check last .1.1.1.1 is replaced with #overflow_suffix 8 bytes long var parentId = new StringBuilder("|abc."); while (parentId.Length < 1022) parentId.Append("1."); var activity = new Activity("activity") .SetParentId(parentId.ToString()) .Start(); Assert.Equal( parentId.ToString().Substring(0, parentId.Length - 8), activity.Id.Substring(0, activity.Id.Length - 9)); Assert.Equal('#', activity.Id[activity.Id.Length - 1]); //check parentId |abc.1.1...1.012345678 (128 bytes) and check last .012345678 is replaced with #overflow_suffix 8 bytes long parentId = new StringBuilder("|abc."); while (parentId.Length < 1013) parentId.Append("1."); parentId.Append("012345678."); activity = new Activity("activity") .SetParentId(parentId.ToString()) .Start(); //last .012345678 will be replaced with #overflow_suffix 8 bytes long Assert.Equal( parentId.ToString().Substring(0, parentId.Length - 10), activity.Id.Substring(0, activity.Id.Length - 9)); Assert.Equal('#', activity.Id[activity.Id.Length - 1]); } /// <summary> /// Tests activity start and stop /// Checks Activity.Current correctness, Id generation /// </summary> [Fact] public void StartStop() { var activity = new Activity("activity"); Assert.Null(Activity.Current); activity.Start(); Assert.Equal(activity, Activity.Current); Assert.Null(activity.Parent); Assert.NotNull(activity.Id); Assert.NotNull(activity.RootId); Assert.NotEqual(default(DateTime), activity.StartTimeUtc); activity.Stop(); Assert.Null(Activity.Current); } /// <summary> /// Tests Id generation /// </summary> [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void IdGenerationNoParent() { var orphan1 = new Activity("orphan1"); var orphan2 = new Activity("orphan2"); Task.Run(() => orphan1.Start()).Wait(); Task.Run(() => orphan2.Start()).Wait(); Assert.NotEqual(orphan2.Id, orphan1.Id); Assert.NotEqual(orphan2.RootId, orphan1.RootId); } /// <summary> /// Tests Id generation /// </summary> [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public void IdGenerationInternalParent() { var parent = new Activity("parent"); parent.SetIdFormat(ActivityIdFormat.Hierarchical); parent.Start(); var child1 = new Activity("child1"); var child2 = new Activity("child2"); //start 2 children in different execution contexts Task.Run(() => child1.Start()).Wait(); Task.Run(() => child2.Start()).Wait(); // In Debug builds of System.Diagnostics.DiagnosticSource, the child operation Id will be constructed as follows // "|parent.RootId.<child.OperationName.Replace(., -)>-childCount.". // This is for debugging purposes to know which operation the child Id is comming from. // // In Release builds of System.Diagnostics.DiagnosticSource, it will not contain the operation name to keep it simple and it will be as // "|parent.RootId.childCount.". string child1DebugString = $"|{parent.RootId}.{child1.OperationName}-1."; string child2DebugString = $"|{parent.RootId}.{child2.OperationName}-2."; string child1ReleaseString = $"|{parent.RootId}.1."; string child2ReleaseString = $"|{parent.RootId}.2."; AssertExtensions.AtLeastOneEquals(child1DebugString, child1ReleaseString, child1.Id); AssertExtensions.AtLeastOneEquals(child2DebugString, child2ReleaseString, child2.Id); Assert.Equal(parent.RootId, child1.RootId); Assert.Equal(parent.RootId, child2.RootId); child1.Stop(); child2.Stop(); var child3 = new Activity("child3"); child3.Start(); string child3DebugString = $"|{parent.RootId}.{child3.OperationName}-3."; string child3ReleaseString = $"|{parent.RootId}.3."; AssertExtensions.AtLeastOneEquals(child3DebugString, child3ReleaseString, child3.Id); var grandChild = new Activity("grandChild"); grandChild.Start(); child3DebugString = $"{child3.Id}{grandChild.OperationName}-1."; child3ReleaseString = $"{child3.Id}1."; AssertExtensions.AtLeastOneEquals(child3DebugString, child3ReleaseString, grandChild.Id); } /// <summary> /// Tests Id generation /// </summary> [Fact] public void IdGenerationExternalParentId() { var child1 = new Activity("child1"); child1.SetParentId("123"); child1.Start(); Assert.Equal("123", child1.RootId); Assert.Equal('|', child1.Id[0]); Assert.Equal('_', child1.Id[child1.Id.Length - 1]); child1.Stop(); var child2 = new Activity("child2"); child2.SetParentId("123"); child2.Start(); Assert.NotEqual(child2.Id, child1.Id); Assert.Equal("123", child2.RootId); } /// <summary> /// Tests Id generation /// </summary> [Fact] public void RootId() { var parentIds = new[]{ "123", //Parent does not start with '|' and does not contain '.' "123.1", //Parent does not start with '|' but contains '.' "|123", //Parent starts with '|' and does not contain '.' "|123.1.1", //Parent starts with '|' and contains '.' }; foreach (var parentId in parentIds) { var activity = new Activity("activity"); activity.SetParentId(parentId); Assert.Equal("123", activity.RootId); } } public static bool IdIsW3CFormat(string id) { if (id.Length != 55) return false; if (id[2] != '-') return false; if (id[35] != '-') return false; if (id[52] != '-') return false; return Regex.IsMatch(id, "^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$"); } public static bool IsLowerCaseHex(string s) { return Regex.IsMatch(s, "^[0-9a-f]*$"); } /****** ActivityTraceId tests *****/ [Fact] public void ActivityTraceIdTests() { Span<byte> idBytes1 = stackalloc byte[16]; Span<byte> idBytes2 = stackalloc byte[16]; // Empty Constructor string zeros = "00000000000000000000000000000000"; ActivityTraceId emptyId = new ActivityTraceId(); Assert.Equal(zeros, emptyId.ToHexString()); emptyId.CopyTo(idBytes1); Assert.Equal(new byte[16], idBytes1.ToArray()); Assert.True(emptyId == new ActivityTraceId()); Assert.True(!(emptyId != new ActivityTraceId())); Assert.True(emptyId.Equals(new ActivityTraceId())); Assert.True(emptyId.Equals((object)new ActivityTraceId())); Assert.Equal(new ActivityTraceId().GetHashCode(), emptyId.GetHashCode()); // NewActivityTraceId ActivityTraceId newId1 = ActivityTraceId.CreateRandom(); Assert.True(IsLowerCaseHex(newId1.ToHexString())); Assert.Equal(32, newId1.ToHexString().Length); ActivityTraceId newId2 = ActivityTraceId.CreateRandom(); Assert.Equal(32, newId1.ToHexString().Length); Assert.NotEqual(newId1.ToHexString(), newId2.ToHexString()); // Test equality Assert.True(newId1 != newId2); Assert.True(!(newId1 == newId2)); Assert.True(!(newId1.Equals(newId2))); Assert.True(!(newId1.Equals((object)newId2))); Assert.NotEqual(newId1.GetHashCode(), newId2.GetHashCode()); ActivityTraceId newId3 = ActivityTraceId.CreateFromString("00000000000000000000000000000001".AsSpan()); Assert.True(newId3 != emptyId); Assert.True(!(newId3 == emptyId)); Assert.True(!(newId3.Equals(emptyId))); Assert.True(!(newId3.Equals((object)emptyId))); Assert.NotEqual(newId3.GetHashCode(), emptyId.GetHashCode()); // Use in Dictionary (this does assume we have no collisions in IDs over 100 tries (very good). var dict = new Dictionary<ActivityTraceId, string>(); for (int i = 0; i < 100; i++) { var newId7 = ActivityTraceId.CreateRandom(); dict[newId7] = newId7.ToHexString(); } int ctr = 0; foreach (string value in dict.Values) { string valueInDict; Assert.True(dict.TryGetValue(ActivityTraceId.CreateFromString(value.AsSpan()), out valueInDict)); Assert.Equal(value, valueInDict); ctr++; } Assert.Equal(100, ctr); // We got out what we put in. // AsBytes and Byte constructor. newId2.CopyTo(idBytes2); ActivityTraceId newId2Clone = ActivityTraceId.CreateFromBytes(idBytes2); Assert.Equal(newId2.ToHexString(), newId2Clone.ToHexString()); newId2Clone.CopyTo(idBytes1); Assert.Equal(idBytes2.ToArray(), idBytes1.ToArray()); Assert.True(newId2 == newId2Clone); Assert.True(newId2.Equals(newId2Clone)); Assert.True(newId2.Equals((object)newId2Clone)); Assert.Equal(newId2.GetHashCode(), newId2Clone.GetHashCode()); // String constructor and ToHexString(). string idStr = "0123456789abcdef0123456789abcdef"; ActivityTraceId id = ActivityTraceId.CreateFromString(idStr.AsSpan()); Assert.Equal(idStr, id.ToHexString()); // Utf8 Constructor. byte[] idUtf8 = Encoding.UTF8.GetBytes(idStr); ActivityTraceId id1 = ActivityTraceId.CreateFromUtf8String(idUtf8); Assert.Equal(idStr, id1.ToHexString()); // ToString Assert.Equal(idStr, id.ToString()); } /****** ActivitySpanId tests *****/ [Fact] public void ActivitySpanIdTests() { Span<byte> idBytes1 = stackalloc byte[8]; Span<byte> idBytes2 = stackalloc byte[8]; // Empty Constructor string zeros = "0000000000000000"; ActivitySpanId emptyId = new ActivitySpanId(); Assert.Equal(zeros, emptyId.ToHexString()); emptyId.CopyTo(idBytes1); Assert.Equal(new byte[8], idBytes1.ToArray()); Assert.True(emptyId == new ActivitySpanId()); Assert.True(!(emptyId != new ActivitySpanId())); Assert.True(emptyId.Equals(new ActivitySpanId())); Assert.True(emptyId.Equals((object)new ActivitySpanId())); Assert.Equal(new ActivitySpanId().GetHashCode(), emptyId.GetHashCode()); // NewActivitySpanId ActivitySpanId newId1 = ActivitySpanId.CreateRandom(); Assert.True(IsLowerCaseHex(newId1.ToHexString())); Assert.Equal(16, newId1.ToHexString().Length); ActivitySpanId newId2 = ActivitySpanId.CreateRandom(); Assert.Equal(16, newId1.ToHexString().Length); Assert.NotEqual(newId1.ToHexString(), newId2.ToHexString()); // Test equality Assert.True(newId1 != newId2); Assert.True(!(newId1 == newId2)); Assert.True(!(newId1.Equals(newId2))); Assert.True(!(newId1.Equals((object)newId2))); Assert.NotEqual(newId1.GetHashCode(), newId2.GetHashCode()); ActivitySpanId newId3 = ActivitySpanId.CreateFromString("0000000000000001".AsSpan()); Assert.True(newId3 != emptyId); Assert.True(!(newId3 == emptyId)); Assert.True(!(newId3.Equals(emptyId))); Assert.True(!(newId3.Equals((object)emptyId))); Assert.NotEqual(newId3.GetHashCode(), emptyId.GetHashCode()); // Use in Dictionary (this does assume we have no collisions in IDs over 100 tries (very good). var dict = new Dictionary<ActivitySpanId, string>(); for (int i = 0; i < 100; i++) { var newId7 = ActivitySpanId.CreateRandom(); dict[newId7] = newId7.ToHexString(); } int ctr = 0; foreach (string value in dict.Values) { string valueInDict; Assert.True(dict.TryGetValue(ActivitySpanId.CreateFromString(value.AsSpan()), out valueInDict)); Assert.Equal(value, valueInDict); ctr++; } Assert.Equal(100, ctr); // We got out what we put in. // AsBytes and Byte constructor. newId2.CopyTo(idBytes2); ActivitySpanId newId2Clone = ActivitySpanId.CreateFromBytes(idBytes2); Assert.Equal(newId2.ToHexString(), newId2Clone.ToHexString()); newId2Clone.CopyTo(idBytes1); Assert.Equal(idBytes2.ToArray(), idBytes1.ToArray()); Assert.True(newId2 == newId2Clone); Assert.True(newId2.Equals(newId2Clone)); Assert.True(newId2.Equals((object)newId2Clone)); Assert.Equal(newId2.GetHashCode(), newId2Clone.GetHashCode()); // String constructor and ToHexString(). string idStr = "0123456789abcdef"; ActivitySpanId id = ActivitySpanId.CreateFromString(idStr.AsSpan()); Assert.Equal(idStr, id.ToHexString()); // Utf8 Constructor. byte[] idUtf8 = Encoding.UTF8.GetBytes(idStr); ActivitySpanId id1 = ActivitySpanId.CreateFromUtf8String(idUtf8); Assert.Equal(idStr, id1.ToHexString()); // ToString Assert.Equal(idStr, id.ToString()); } /****** WC3 Format tests *****/ [Fact] public void IdFormat_W3CIsDefaultForNet5() { Activity activity = new Activity("activity1"); activity.Start(); Assert.Equal(PlatformDetection.IsNetCore ? ActivityIdFormat.W3C : ActivityIdFormat.Hierarchical, activity.IdFormat); } [Fact] public void IdFormat_W3CWhenParentIdIsW3C() { Activity activity = new Activity("activity2"); activity.SetParentId("00-0123456789abcdef0123456789abcdef-0123456789abcdef-00"); activity.Start(); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.Equal("0123456789abcdef0123456789abcdef", activity.TraceId.ToHexString()); Assert.Equal("0123456789abcdef", activity.ParentSpanId.ToHexString()); Assert.Equal(ActivityTraceFlags.None, activity.ActivityTraceFlags); Assert.False(activity.Recorded); Assert.True(IdIsW3CFormat(activity.Id)); } [Fact] public void IdFormat_W3CValidVersions() { Activity activity0 = new Activity("activity0"); Activity activity1 = new Activity("activity1"); Activity activity2 = new Activity("activity2"); activity0.SetParentId("01-0123456789abcdef0123456789abcdef-0123456789abcdef-00"); activity0.Start(); activity1.SetParentId("cc-1123456789abcdef0123456789abcdef-1123456789abcdef-00"); activity1.Start(); activity2.SetParentId("fe-2123456789abcdef0123456789abcdef-2123456789abcdef-00"); activity2.Start(); Assert.Equal(ActivityIdFormat.W3C, activity0.IdFormat); Assert.Equal(ActivityIdFormat.W3C, activity1.IdFormat); Assert.Equal(ActivityIdFormat.W3C, activity2.IdFormat); Assert.Equal("0123456789abcdef0123456789abcdef", activity0.TraceId.ToHexString()); Assert.Equal("1123456789abcdef0123456789abcdef", activity1.TraceId.ToHexString()); Assert.Equal("2123456789abcdef0123456789abcdef", activity2.TraceId.ToHexString()); Assert.Equal("0123456789abcdef", activity0.ParentSpanId.ToHexString()); Assert.Equal("1123456789abcdef", activity1.ParentSpanId.ToHexString()); Assert.Equal("2123456789abcdef", activity2.ParentSpanId.ToHexString()); } [Fact] public void IdFormat_W3CInvalidVersionFF() { Activity activity = new Activity("activity"); activity.SetParentId("ff-0123456789abcdef0123456789abcdef-0123456789abcdef-00"); activity.Start(); Assert.Equal(ActivityIdFormat.Hierarchical, activity.IdFormat); } [Fact] public void IdFormat_W3CWhenTraceIdAndSpanIdProvided() { Activity activity = new Activity("activity3"); ActivityTraceId activityTraceId = ActivityTraceId.CreateRandom(); activity.SetParentId(activityTraceId, ActivitySpanId.CreateRandom()); activity.Start(); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.Equal(activityTraceId.ToHexString(), activity.TraceId.ToHexString()); Assert.Equal(ActivityTraceFlags.None, activity.ActivityTraceFlags); Assert.False(activity.Recorded); Assert.True(IdIsW3CFormat(activity.Id)); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void IdFormat_W3CWhenDefaultIsW3C() { RemoteExecutor.Invoke(() => { Activity.DefaultIdFormat = ActivityIdFormat.W3C; Activity activity = new Activity("activity4"); activity.Start(); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.True(IdIsW3CFormat(activity.Id)); }).Dispose(); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void IdFormat_WithTheEnvironmentSwitch() { var psi = new ProcessStartInfo(); psi.Environment.Add("DOTNET_SYSTEM_DIAGNOSTICS_DEFAULTACTIVITYIDFORMATISHIERARCHIAL", "true"); RemoteExecutor.Invoke(() => { Activity activity = new Activity("activity15"); activity.Start(); Assert.Equal(ActivityIdFormat.Hierarchical, activity.IdFormat); }, new RemoteInvokeOptions() { StartInfo = psi }).Dispose(); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void IdFormat_HierarchicalWhenDefaultIsW3CButHierarchicalParentId() { RemoteExecutor.Invoke(() => { Activity.DefaultIdFormat = ActivityIdFormat.W3C; Activity activity = new Activity("activity5"); string parentId = "|a000b421-5d183ab6.1."; activity.SetParentId(parentId); activity.Start(); Assert.Equal(ActivityIdFormat.Hierarchical, activity.IdFormat); Assert.StartsWith(parentId, activity.Id); }).Dispose(); } [Fact] public void IdFormat_ZeroTraceIdAndSpanIdWithW3CFormat() { Activity activity = new Activity("activity"); activity.Start(); if (PlatformDetection.IsNetCore) { Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.NotEqual("00000000000000000000000000000000", activity.TraceId.ToHexString()); Assert.NotEqual("0000000000000000", activity.SpanId.ToHexString()); } else { Assert.Equal(ActivityIdFormat.Hierarchical, activity.IdFormat); Assert.Equal("00000000000000000000000000000000", activity.TraceId.ToHexString()); Assert.Equal("0000000000000000", activity.SpanId.ToHexString()); } } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void IdFormat_W3CWhenForcedAndHierarchicalParentId() { RemoteExecutor.Invoke(() => { Activity.DefaultIdFormat = ActivityIdFormat.W3C; Activity.ForceDefaultIdFormat = true; Activity activity = new Activity("activity6"); activity.SetParentId("|a000b421-5d183ab6.1."); activity.Start(); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.True(IdIsW3CFormat(activity.Id)); Assert.NotEqual("00000000000000000000000000000000", activity.TraceId.ToHexString()); Assert.NotEqual("0000000000000000", activity.SpanId.ToHexString()); }).Dispose(); } [Fact] public void TraceStateString_InheritsFromParent() { Activity parent = new Activity("parent"); parent.SetIdFormat(ActivityIdFormat.W3C); const string testString = "MyTestString"; parent.TraceStateString = testString; parent.Start(); Assert.Equal(testString, parent.TraceStateString); Activity activity = new Activity("activity7"); activity.Start(); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.True(IdIsW3CFormat(activity.Id)); Assert.Equal(testString, activity.TraceStateString); // Update child string childTestString = "ChildTestString"; activity.TraceStateString = childTestString; // Confirm that child sees update, but parent does not Assert.Equal(childTestString, activity.TraceStateString); Assert.Equal(testString, parent.TraceStateString); // Update parent string parentTestString = "newTestString"; parent.TraceStateString = parentTestString; // Confirm that parent sees update but child does not. Assert.Equal(childTestString, activity.TraceStateString); Assert.Equal(parentTestString, parent.TraceStateString); } [Fact] public void TraceId_W3CUppercaseCharsNotSupportedAndDoesNotThrow() { Activity activity = new Activity("activity8"); activity.SetParentId("00-0123456789ABCDEF0123456789ABCDEF-0123456789ABCDEF-01"); activity.Start(); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.True(IdIsW3CFormat(activity.Id)); } [Fact] public void TraceId_W3CNonHexCharsNotSupportedAndDoesNotThrow() { Activity activity = new Activity("activity9"); activity.SetParentId("00-xyz3456789abcdef0123456789abcdef-0123456789abcdef-01"); activity.Start(); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.True(IdIsW3CFormat(activity.Id)); } [Fact] public void ParentSpanId_W3CNonHexCharsNotSupportedAndDoesNotThrow() { Activity activity = new Activity("activity10"); activity.SetParentId("00-0123456789abcdef0123456789abcdef-x123456789abcdef-01"); activity.Start(); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.True(IdIsW3CFormat(activity.Id)); Assert.Equal("0000000000000000", activity.ParentSpanId.ToHexString()); Assert.Equal("0123456789abcdef0123456789abcdef", activity.TraceId.ToHexString()); } [Fact] public void Version_W3CNonHexCharsNotSupportedAndDoesNotThrow() { Activity activity = new Activity("activity"); activity.SetParentId("0.-0123456789abcdef0123456789abcdef-0123456789abcdef-00"); activity.Start(); Assert.Equal(ActivityIdFormat.Hierarchical, activity.IdFormat); } [Fact] public void Version_W3CNonHexCharsNotSupportedAndDoesNotThrow_ForceW3C() { Activity activity = new Activity("activity"); activity.SetIdFormat(ActivityIdFormat.W3C); activity.SetParentId("0.-0123456789abcdef0123456789abcdef-0123456789abcdef-00"); activity.Start(); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.NotEqual("0123456789abcdef0123456789abcdef", activity.TraceId.ToHexString()); Assert.Equal(default, activity.ParentSpanId); Assert.True(IdIsW3CFormat(activity.Id)); } [Fact] public void Options_W3CNonHexCharsNotSupportedAndDoesNotThrow() { Activity activity = new Activity("activity"); activity.SetParentId("00-0123456789abcdef0123456789abcdef-0123456789abcdef-.1"); activity.Start(); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.True(IdIsW3CFormat(activity.Id)); Assert.Equal("0123456789abcdef0123456789abcdef", activity.TraceId.ToHexString()); Assert.Equal("0123456789abcdef", activity.ParentSpanId.ToHexString()); Assert.Equal(ActivityTraceFlags.None, activity.ActivityTraceFlags); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void IdFormat_W3CForcedOverridesParentActivityIdFormat() { RemoteExecutor.Invoke(() => { Activity.DefaultIdFormat = ActivityIdFormat.W3C; Activity.ForceDefaultIdFormat = true; Activity parent = new Activity("parent").Start(); Activity activity = new Activity("child").Start(); Assert.Equal(parent.SpanId.ToHexString(), activity.ParentSpanId.ToHexString()); ; }).Dispose(); } [Fact] public void SetIdFormat_CanSetHierarchicalBeforeStart() { Activity activity = new Activity("activity1"); Assert.Equal(ActivityIdFormat.Unknown, activity.IdFormat); activity.SetIdFormat(ActivityIdFormat.Hierarchical); Assert.Equal(ActivityIdFormat.Hierarchical, activity.IdFormat); activity.Start(); Assert.Equal(ActivityIdFormat.Hierarchical, activity.IdFormat); // cannot change after activity starts activity.SetIdFormat(ActivityIdFormat.W3C); Assert.Equal(ActivityIdFormat.Hierarchical, activity.IdFormat); } [Fact] public void SetIdFormat_CanSetW3CBeforeStart() { Activity activity = new Activity("activity2"); Assert.Equal(ActivityIdFormat.Unknown, activity.IdFormat); activity.SetIdFormat(ActivityIdFormat.W3C); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); activity.Start(); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.True(IdIsW3CFormat(activity.Id)); } [Fact] public void SetIdFormat_CanSetW3CAfterHierarchicalParentIsSet() { Activity activity = new Activity("activity3"); activity.SetParentId("|foo.bar."); activity.SetIdFormat(ActivityIdFormat.W3C); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); activity.Start(); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.Equal("|foo.bar.", activity.ParentId); Assert.True(IdIsW3CFormat(activity.Id)); } [Fact] public void SetIdFormat_CanSetHierarchicalAfterW3CParentIsSet() { Activity activity = new Activity("activity4"); activity.SetParentId("00-0123456789abcdef0123456789abcdef-0123456789abcdef-00"); activity.SetIdFormat(ActivityIdFormat.Hierarchical); Assert.Equal(ActivityIdFormat.Hierarchical, activity.IdFormat); activity.Start(); Assert.Equal(ActivityIdFormat.Hierarchical, activity.IdFormat); Assert.Equal("00-0123456789abcdef0123456789abcdef-0123456789abcdef-00", activity.ParentId); Assert.True(activity.Id[0] == '|'); } [Fact] public void SetIdFormat_CanSetAndOverrideBeforeStart() { Activity activity = new Activity("activity5"); Assert.Equal(ActivityIdFormat.Unknown, activity.IdFormat); activity.SetIdFormat(ActivityIdFormat.Hierarchical); Assert.Equal(ActivityIdFormat.Hierarchical, activity.IdFormat); activity.SetIdFormat(ActivityIdFormat.W3C); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void SetIdFormat_OverridesForcedW3C() { RemoteExecutor.Invoke(() => { Activity.DefaultIdFormat = ActivityIdFormat.W3C; Activity.ForceDefaultIdFormat = true; Activity activity = new Activity("activity7"); activity.SetIdFormat(ActivityIdFormat.Hierarchical); activity.Start(); Assert.Equal(ActivityIdFormat.Hierarchical, activity.IdFormat); }).Dispose(); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void SetIdFormat_OverridesForcedHierarchical() { RemoteExecutor.Invoke(() => { Activity.DefaultIdFormat = ActivityIdFormat.Hierarchical; Activity.ForceDefaultIdFormat = true; Activity activity = new Activity("activity8"); activity.SetIdFormat(ActivityIdFormat.W3C); activity.Start(); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); }).Dispose(); } [Fact] public void SetIdFormat_OverridesParentHierarchicalFormat() { Activity parent = new Activity("parent") .SetIdFormat(ActivityIdFormat.Hierarchical) .Start(); Activity child = new Activity("child") .SetIdFormat(ActivityIdFormat.W3C) .Start(); Assert.Equal(ActivityIdFormat.W3C, child.IdFormat); } [Fact] public void SetIdFormat_OverridesParentW3CFormat() { Activity parent = new Activity("parent") .SetIdFormat(ActivityIdFormat.W3C) .Start(); Activity child = new Activity("child") .SetIdFormat(ActivityIdFormat.Hierarchical) .Start(); Assert.Equal(ActivityIdFormat.Hierarchical, child.IdFormat); } [Fact] public void TraceIdBeforeStart_FromTraceparentHeader() { Activity activity = new Activity("activity1"); activity.SetParentId("00-0123456789abcdef0123456789abcdef-0123456789abcdef-01"); Assert.Equal("0123456789abcdef0123456789abcdef", activity.TraceId.ToHexString()); } [Fact] public void TraceIdBeforeStart_FromExplicitTraceId() { Activity activity = new Activity("activity2"); activity.SetParentId( ActivityTraceId.CreateFromString("0123456789abcdef0123456789abcdef".AsSpan()), ActivitySpanId.CreateFromString("0123456789abcdef".AsSpan())); Assert.Equal("0123456789abcdef0123456789abcdef", activity.TraceId.ToHexString()); } [Fact] public void TraceIdBeforeStart_FromInProcParent() { Activity parent = new Activity("parent"); parent.SetParentId("00-0123456789abcdef0123456789abcdef-0123456789abcdef-01"); parent.Start(); Activity activity = new Activity("child"); activity.Start(); Assert.Equal("0123456789abcdef0123456789abcdef", activity.TraceId.ToHexString()); } [Fact] public void TraceIdBeforeStart_FromInvalidTraceparentHeader() { Activity activity = new Activity("activity"); activity.SetParentId("123"); Assert.Equal("00000000000000000000000000000000", activity.TraceId.ToHexString()); } [ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))] public void TraceIdBeforeStart_NoParent() { RemoteExecutor.Invoke(() => { Activity.DefaultIdFormat = ActivityIdFormat.W3C; Activity.ForceDefaultIdFormat = true; Activity activity = new Activity("activity3"); Assert.Equal("00000000000000000000000000000000", activity.TraceId.ToHexString()); }).Dispose(); } [Fact] public void RootIdBeforeStartTests() { Activity activity = new Activity("activity1"); Assert.Null(activity.RootId); activity.SetParentId("|0123456789abcdef0123456789abcdef.0123456789abcdef."); Assert.Equal("0123456789abcdef0123456789abcdef", activity.RootId); } [Fact] public void ActivityTraceFlagsTests() { Activity activity; // Set the 'Recorded' bit by using SetParentId with a -01 flags. activity = new Activity("activity1"); activity.SetParentId("00-0123456789abcdef0123456789abcdef-0123456789abcdef-01"); activity.Start(); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.Equal("0123456789abcdef0123456789abcdef", activity.TraceId.ToHexString()); Assert.Equal("0123456789abcdef", activity.ParentSpanId.ToHexString()); Assert.True(IdIsW3CFormat(activity.Id)); Assert.Equal($"00-0123456789abcdef0123456789abcdef-{activity.SpanId.ToHexString()}-01", activity.Id); Assert.Equal(ActivityTraceFlags.Recorded, activity.ActivityTraceFlags); Assert.True(activity.Recorded); activity.Stop(); // Set the 'Recorded' bit by using SetParentId by using the TraceId, SpanId, ActivityTraceFlags overload activity = new Activity("activity2"); ActivityTraceId activityTraceId = ActivityTraceId.CreateRandom(); activity.SetParentId(activityTraceId, ActivitySpanId.CreateRandom(), ActivityTraceFlags.Recorded); activity.Start(); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.Equal(activityTraceId.ToHexString(), activity.TraceId.ToHexString()); Assert.True(IdIsW3CFormat(activity.Id)); Assert.Equal($"00-{activity.TraceId.ToHexString()}-{activity.SpanId.ToHexString()}-01", activity.Id); Assert.Equal(ActivityTraceFlags.Recorded, activity.ActivityTraceFlags); Assert.True(activity.Recorded); activity.Stop(); /****************************************************/ // Set the 'Recorded' bit explicitly after the fact. activity = new Activity("activity3"); activity.SetParentId("00-0123456789abcdef0123456789abcdef-0123456789abcdef-00"); activity.Start(); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.Equal("0123456789abcdef0123456789abcdef", activity.TraceId.ToHexString()); Assert.Equal("0123456789abcdef", activity.ParentSpanId.ToHexString()); Assert.True(IdIsW3CFormat(activity.Id)); Assert.Equal($"00-{activity.TraceId.ToHexString()}-{activity.SpanId.ToHexString()}-00", activity.Id); Assert.Equal(ActivityTraceFlags.None, activity.ActivityTraceFlags); Assert.False(activity.Recorded); activity.ActivityTraceFlags = ActivityTraceFlags.Recorded; Assert.Equal(ActivityTraceFlags.Recorded, activity.ActivityTraceFlags); Assert.True(activity.Recorded); activity.Stop(); /****************************************************/ // Confirm that that flags are propagated to children. activity = new Activity("activity4"); activity.SetParentId("00-0123456789abcdef0123456789abcdef-0123456789abcdef-01"); activity.Start(); Assert.Equal(activity, Activity.Current); Assert.Equal(ActivityIdFormat.W3C, activity.IdFormat); Assert.Equal("0123456789abcdef0123456789abcdef", activity.TraceId.ToHexString()); Assert.Equal("0123456789abcdef", activity.ParentSpanId.ToHexString()); Assert.True(IdIsW3CFormat(activity.Id)); Assert.Equal($"00-{activity.TraceId.ToHexString()}-{activity.SpanId.ToHexString()}-01", activity.Id); Assert.Equal(ActivityTraceFlags.Recorded, activity.ActivityTraceFlags); Assert.True(activity.Recorded); // create a child var childActivity = new Activity("activity4Child"); childActivity.Start(); Assert.Equal(childActivity, Activity.Current); Assert.Equal("0123456789abcdef0123456789abcdef", childActivity.TraceId.ToHexString()); Assert.NotEqual(activity.SpanId.ToHexString(), childActivity.SpanId.ToHexString()); Assert.True(IdIsW3CFormat(childActivity.Id)); Assert.Equal($"00-{childActivity.TraceId.ToHexString()}-{childActivity.SpanId.ToHexString()}-01", childActivity.Id); Assert.Equal(ActivityTraceFlags.Recorded, childActivity.ActivityTraceFlags); Assert.True(childActivity.Recorded); childActivity.Stop(); activity.Stop(); } /// <summary> /// Tests Activity Start and Stop with timestamp /// </summary> [Fact] public void StartStopWithTimestamp() { var activity = new Activity("activity"); Assert.Equal(default(DateTime), activity.StartTimeUtc); activity.SetStartTime(DateTime.Now); // Error Does nothing because it is not UTC Assert.Equal(default(DateTime), activity.StartTimeUtc); var startTime = DateTime.UtcNow.AddSeconds(-1); // A valid time in the past that we want to be our offical start time. activity.SetStartTime(startTime); activity.Start(); Assert.Equal(startTime, activity.StartTimeUtc); // we use our offical start time not the time now. Assert.Equal(TimeSpan.Zero, activity.Duration); Thread.Sleep(35); activity.SetEndTime(DateTime.Now); // Error does nothing because it is not UTC Assert.Equal(TimeSpan.Zero, activity.Duration); var stopTime = DateTime.UtcNow; activity.SetEndTime(stopTime); Assert.Equal(stopTime - startTime, activity.Duration); } /// <summary> /// Tests Activity Stop without timestamp /// </summary> [Fact] public void StopWithoutTimestamp() { var startTime = DateTime.UtcNow.AddSeconds(-1); var activity = new Activity("activity") .SetStartTime(startTime); activity.Start(); Assert.Equal(startTime, activity.StartTimeUtc); activity.Stop(); // DateTime.UtcNow is not precise on some platforms, but Activity stop time is precise // in this test we set start time, but not stop time and check duration. // // Let's check that duration is 1sec - 2 * maximum DateTime.UtcNow error or bigger. // As both start and stop timestamps may have error. // There is another test (ActivityDateTimeTests.StartStopReturnsPreciseDuration) // that checks duration precision on .NET Framework. Assert.InRange(activity.Duration.TotalMilliseconds, 1000 - 2 * MaxClockErrorMSec, double.MaxValue); } /// <summary> /// Tests Activity stack: creates a parent activity and child activity /// Verifies /// - Activity.Parent and ParentId correctness /// - Baggage propagated from parent /// - Tags are not propagated /// Stops child and checks Activity,Current is set to parent /// </summary> [Fact] public void ParentChild() { var parent = new Activity("parent") .AddBaggage("id1", "baggage from parent") .AddTag("tag1", "tag from parent"); parent.Start(); Assert.Equal(parent, Activity.Current); var child = new Activity("child"); child.Start(); Assert.Equal(parent, child.Parent); Assert.Equal(parent.Id, child.ParentId); //baggage from parent Assert.Equal("baggage from parent", child.GetBaggageItem("id1")); //no tags from parent var childTags = child.Tags.ToList(); Assert.Equal(0, childTags.Count); child.Stop(); Assert.Equal(parent, Activity.Current); parent.Stop(); Assert.Null(Activity.Current); } /// <summary> /// Tests wrong stop order, when parent is stopped before child /// </summary> [Fact] public void StopParent() { var parent = new Activity("parent"); parent.Start(); var child = new Activity("child"); child.Start(); parent.Stop(); Assert.Null(Activity.Current); } /// <summary> /// Tests that activity can not be stated twice /// </summary> [Fact] public void StartTwice() { var activity = new Activity("activity"); activity.Start(); var id = activity.Id; activity.Start(); // Error already started. Does nothing. Assert.Equal(id, activity.Id); } /// <summary> /// Tests that activity that has not been started can not be stopped /// </summary> [Fact] public void StopNotStarted() { var activity = new Activity("activity"); activity.Stop(); // Error Does Nothing Assert.Equal(TimeSpan.Zero, activity.Duration); } /// <summary> /// Tests that second activity stop does not update Activity.Current /// </summary> [Fact] public void StopTwice() { var parent = new Activity("parent"); parent.Start(); var child1 = new Activity("child1"); child1.Start(); child1.Stop(); var child2 = new Activity("child2"); child2.Start(); child1.Stop(); Assert.Equal(child2, Activity.Current); } [Fact] [OuterLoop("https://github.com/dotnet/runtime/issues/23104")] public void DiagnosticSourceStartStop() { using (DiagnosticListener listener = new DiagnosticListener("Testing")) { DiagnosticSource source = listener; var observer = new TestObserver(); using (listener.Subscribe(observer)) { var arguments = new { args = "arguments" }; var activity = new Activity("activity"); var stopWatch = Stopwatch.StartNew(); // Test Activity.Start source.StartActivity(activity, arguments); Assert.Equal(activity.OperationName + ".Start", observer.EventName); Assert.Equal(arguments, observer.EventObject); Assert.NotNull(observer.Activity); Assert.NotEqual(default(DateTime), activity.StartTimeUtc); Assert.Equal(TimeSpan.Zero, observer.Activity.Duration); observer.Reset(); Thread.Sleep(100); // Test Activity.Stop source.StopActivity(activity, arguments); stopWatch.Stop(); Assert.Equal(activity.OperationName + ".Stop", observer.EventName); Assert.Equal(arguments, observer.EventObject); // Confirm that duration is set. Assert.NotNull(observer.Activity); Assert.InRange(observer.Activity.Duration, TimeSpan.FromTicks(1), TimeSpan.MaxValue); // let's only check that Duration is set in StopActivity, we do not intend to check precision here Assert.InRange(observer.Activity.Duration, TimeSpan.FromTicks(1), stopWatch.Elapsed.Add(TimeSpan.FromMilliseconds(2 * MaxClockErrorMSec))); } } } /// <summary> /// Tests that Activity.Current flows correctly within async methods /// </summary> [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public async Task ActivityCurrentFlowsWithAsyncSimple() { Activity activity = new Activity("activity").Start(); Assert.Same(activity, Activity.Current); await Task.Run(() => { Assert.Same(activity, Activity.Current); }); Assert.Same(activity, Activity.Current); } /// <summary> /// Tests that Activity.Current flows correctly within async methods /// </summary> [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public async Task ActivityCurrentFlowsWithAsyncComplex() { Activity originalActivity = Activity.Current; // Start an activity which spawns a task, but don't await it. // While that's running, start another, nested activity. Activity activity1 = new Activity("activity1").Start(); Assert.Same(activity1, Activity.Current); SemaphoreSlim semaphore = new SemaphoreSlim(initialCount: 0); Task task = Task.Run(async () => { // Wait until the semaphore is signaled. await semaphore.WaitAsync(); Assert.Same(activity1, Activity.Current); }); Activity activity2 = new Activity("activity2").Start(); Assert.Same(activity2, Activity.Current); // Let task1 complete. semaphore.Release(); await task; Assert.Same(activity2, Activity.Current); activity2.Stop(); Assert.Same(activity1, Activity.Current); activity1.Stop(); Assert.Same(originalActivity, Activity.Current); } /// <summary> /// Tests that Activity.Current could be set /// </summary> [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsThreadingSupported))] public async Task ActivityCurrentSet() { Activity activity = new Activity("activity"); // start Activity in the 'child' context await Task.Run(() => activity.Start()); Assert.Null(Activity.Current); Activity.Current = activity; Assert.Same(activity, Activity.Current); } /// <summary> /// Tests that Activity.Current could be set to null /// </summary> [Fact] public void ActivityCurrentSetToNull() { Activity started = new Activity("started").Start(); Activity.Current = null; Assert.Null(Activity.Current); } /// <summary> /// Tests that Activity.Current could not be set to Activity /// that has not been started yet /// </summary> [Fact] public void ActivityCurrentNotSetToNotStarted() { Activity started = new Activity("started").Start(); Activity notStarted = new Activity("notStarted"); Activity.Current = notStarted; Assert.Same(started, Activity.Current); } /// <summary> /// Tests that Activity.Current could not be set to stopped Activity /// </summary> [Fact] public void ActivityCurrentNotSetToStopped() { Activity started = new Activity("started").Start(); Activity stopped = new Activity("stopped").Start(); stopped.Stop(); Activity.Current = stopped; Assert.Same(started, Activity.Current); } [Fact] public void TestDispose() { Activity current = Activity.Current; using (Activity activity = new Activity("Mine").Start()) { Assert.Same(activity, Activity.Current); Assert.Same(current, activity.Parent); } Assert.Same(current, Activity.Current); } [Fact] public void TestCustomProperties() { Activity activity = new Activity("Custom"); activity.SetCustomProperty("P1", "Prop1"); activity.SetCustomProperty("P2", "Prop2"); activity.SetCustomProperty("P3", null); Assert.Equal("Prop1", activity.GetCustomProperty("P1")); Assert.Equal("Prop2", activity.GetCustomProperty("P2")); Assert.Null(activity.GetCustomProperty("P3")); Assert.Null(activity.GetCustomProperty("P4")); activity.SetCustomProperty("P1", "Prop5"); Assert.Equal("Prop5", activity.GetCustomProperty("P1")); } [Fact] public void TestKind() { Activity activity = new Activity("Kind"); Assert.Equal(ActivityKind.Internal, activity.Kind); } [Fact] public void TestDisplayName() { Activity activity = new Activity("Op1"); Assert.Equal("Op1", activity.OperationName); Assert.Equal("Op1", activity.DisplayName); activity.DisplayName = "Op2"; Assert.Equal("Op1", activity.OperationName); Assert.Equal("Op2", activity.DisplayName); } [Fact] public void TestEvent() { Activity activity = new Activity("EventTest"); Assert.Equal(0, activity.Events.Count()); DateTimeOffset ts1 = DateTimeOffset.UtcNow; DateTimeOffset ts2 = ts1.AddMinutes(1); Assert.True(object.ReferenceEquals(activity, activity.AddEvent(new ActivityEvent("Event1", ts1)))); Assert.True(object.ReferenceEquals(activity, activity.AddEvent(new ActivityEvent("Event2", ts2)))); Assert.Equal(2, activity.Events.Count()); Assert.Equal("Event1", activity.Events.ElementAt(0).Name); Assert.Equal(ts1, activity.Events.ElementAt(0).Timestamp); Assert.Equal(0, activity.Events.ElementAt(0).Tags.Count()); Assert.Equal("Event2", activity.Events.ElementAt(1).Name); Assert.Equal(ts2, activity.Events.ElementAt(1).Timestamp); Assert.Equal(0, activity.Events.ElementAt(1).Tags.Count()); } [Fact] public void TestIsAllDataRequested() { // Activity constructor allways set IsAllDataRequested to true for compatability. Activity a1 = new Activity("a1"); Assert.True(a1.IsAllDataRequested); Assert.True(object.ReferenceEquals(a1, a1.AddTag("k1", "v1"))); Assert.Equal(1, a1.Tags.Count()); } [Fact] public void TestTagObjects() { Activity activity = new Activity("TagObjects"); Assert.Equal(0, activity.Tags.Count()); Assert.Equal(0, activity.TagObjects.Count()); activity.AddTag("s1", "s1").AddTag("s2", "s2").AddTag("s3", null); Assert.Equal(3, activity.Tags.Count()); Assert.Equal(3, activity.TagObjects.Count()); KeyValuePair<string, string>[] tags = activity.Tags.ToArray(); KeyValuePair<string, object>[] tagObjects = activity.TagObjects.ToArray(); Assert.Equal(tags.Length, tagObjects.Length); for (int i = 0; i < tagObjects.Length; i++) { Assert.Equal(tags[i].Key, tagObjects[i].Key); Assert.Equal(tags[i].Value, tagObjects[i].Value); } activity.AddTag("s4", (object) null); Assert.Equal(4, activity.Tags.Count()); Assert.Equal(4, activity.TagObjects.Count()); tags = activity.Tags.ToArray(); tagObjects = activity.TagObjects.ToArray(); Assert.Equal(tags[3].Key, tagObjects[3].Key); Assert.Equal(tags[3].Value, tagObjects[3].Value); activity.AddTag("s5", 5); Assert.Equal(4, activity.Tags.Count()); Assert.Equal(5, activity.TagObjects.Count()); tagObjects = activity.TagObjects.ToArray(); Assert.Equal(5, tagObjects[4].Value); activity.AddTag(null, null); // we allow that and we keeping the behavior for the compatability reason Assert.Equal(5, activity.Tags.Count()); Assert.Equal(6, activity.TagObjects.Count()); activity.SetTag("s6", "s6"); Assert.Equal(6, activity.Tags.Count()); Assert.Equal(7, activity.TagObjects.Count()); activity.SetTag("s5", "s6"); Assert.Equal(7, activity.Tags.Count()); Assert.Equal(7, activity.TagObjects.Count()); activity.SetTag("s3", null); // remove the tag Assert.Equal(6, activity.Tags.Count()); Assert.Equal(6, activity.TagObjects.Count()); tags = activity.Tags.ToArray(); tagObjects = activity.TagObjects.ToArray(); for (int i = 0; i < tagObjects.Length; i++) { Assert.Equal(tags[i].Key, tagObjects[i].Key); Assert.Equal(tags[i].Value, tagObjects[i].Value); } } [Theory] [InlineData("key1", null, true, 1)] [InlineData("key2", null, false, 0)] [InlineData("key3", "v1", true, 1)] [InlineData("key4", "v2", false, 1)] public void TestInsertingFirstTag(string key, object value, bool add, int resultCount) { Activity a = new Activity("SetFirstTag"); if (add) { a.AddTag(key, value); } else { a.SetTag(key, value); } Assert.Equal(resultCount, a.TagObjects.Count()); } [Fact] public void StructEnumerator_TagsLinkedList() { // Note: This test verifies the presence of the struct Enumerator on TagsLinkedList used by customers dynamically to avoid allocations. Activity a = new Activity("TestActivity"); a.AddTag("Tag1", true); IEnumerable<KeyValuePair<string, object>> enumerable = a.TagObjects; MethodInfo method = enumerable.GetType().GetMethod("GetEnumerator", BindingFlags.Instance | BindingFlags.Public); Assert.NotNull(method); Assert.False(method.ReturnType.IsInterface); Assert.True(method.ReturnType.IsValueType); } [Fact] public void StructEnumerator_GenericLinkedList() { // Note: This test verifies the presence of the struct Enumerator on LinkedList<T> used by customers dynamically to avoid allocations. Activity a = new Activity("TestActivity"); a.AddEvent(new ActivityEvent()); IEnumerable<ActivityEvent> enumerable = a.Events; MethodInfo method = enumerable.GetType().GetMethod("GetEnumerator", BindingFlags.Instance | BindingFlags.Public); Assert.NotNull(method); Assert.False(method.ReturnType.IsInterface); Assert.True(method.ReturnType.IsValueType); } public void Dispose() { Activity.Current = null; } private class TestObserver : IObserver<KeyValuePair<string, object>> { public string EventName { get; private set; } public object EventObject { get; private set; } public Activity Activity { get; private set; } public void OnNext(KeyValuePair<string, object> value) { EventName = value.Key; EventObject = value.Value; Activity = Activity.Current; } public void Reset() { EventName = null; EventObject = null; Activity = null; } public void OnCompleted() { } public void OnError(Exception error) { } } private const int MaxClockErrorMSec = 20; } }
40.488429
159
0.582669
[ "MIT" ]
ANISSARIZKY/runtime
src/libraries/System.Diagnostics.DiagnosticSource/tests/ActivityTests.cs
66,482
C#
using System.Collections.Generic; namespace StackExchange.Opserver { public class RedisSettings : Settings<RedisSettings> { public override bool Enabled => Servers.Count > 0; public List<Server> Servers { get; set; } = new List<Server>(); public Server AllServers { get; set; } = new Server(); public Server Defaults { get; set; } = new Server(); public class Server : ISettingsCollectionItem { public List<Instance> Instances { get; set; } = new List<Instance>(); /// <summary> /// The machine name for this Redis server - used to match against the dashboard /// </summary> public string Name { get; set; } /// <summary> /// Unused currently /// </summary> public string Description { get; set; } /// <summary> /// How many seconds before polling this cluster for status again /// </summary> public int RefreshIntervalSeconds { get; set; } = 30; } public class Instance : ISettingsCollectionItem { /// <summary> /// The machine name for this node /// </summary> public string Name { get; set; } /// <summary> /// Connection for for this node /// </summary> public int Port { get; set; } = 6379; /// <summary> /// The password for this node /// </summary> public string Password { get; set; } /// <summary> /// Specify if ssl should be used. Defaults to false. /// </summary> public bool UseSSL { get; set; } = false; /// <summary> /// Regular expressions collection to crawl keys against, to break out Redis DB usage /// </summary> public Dictionary<string, string> AnalysisRegexes { get; set; } = new Dictionary<string, string>(); } } }
31.6
111
0.519474
[ "MIT" ]
bonskijr/Opserver
Opserver.Core/Settings/RedisSettings.cs
2,056
C#
// <copyright file="PasswordControlTestsUniversal.cs" company="Automate The Planet Ltd."> // Copyright 2020 Automate The Planet Ltd. // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Anton Angelov</author> // <site>https://bellatrix.solutions/</site> using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Bellatrix.Desktop.Tests { [TestClass] [App(Constants.UniversalAppPath, Lifecycle.RestartEveryTime)] [AllureSuite("Password Control")] [AllureTag("Universal")] public class PasswordControlTestsUniversal : MSTest.DesktopTest { [TestMethod] [TestCategory(Categories.Desktop)] public void MessageChanged_When_PasswordHovered_Universal() { var password = App.Components.CreateByAutomationId<Password>("passwordBox"); password.Hover(); var label = App.Components.CreateByAutomationId<Label>("resultTextBlock"); Assert.AreEqual("passwordBoxHovered", label.InnerText); } [TestMethod] [TestCategory(Categories.CI)] [TestCategory(Categories.Desktop)] public void MessageChanged_When_NewTextSet_Universal() { var password = App.Components.CreateByAutomationId<Password>("passwordBox"); password.SetPassword("topsecret"); Assert.AreEqual("●●●●●●●●●", password.GetPassword()); } [TestMethod] [TestCategory(Categories.CI)] [TestCategory(Categories.Desktop)] public void IsDisabledReturnsFalse_When_PasswordIsNotDisabled_Universal() { var password = App.Components.CreateByAutomationId<Password>("passwordBox"); Assert.AreEqual(false, password.IsDisabled); } [TestMethod] [TestCategory(Categories.CI)] [TestCategory(Categories.Desktop)] public void IsDisabledReturnsTrue_When_PasswordIsDisabled_Universal() { var password = App.Components.CreateByAutomationId<Password>("disabledPassword"); Assert.AreEqual(true, password.IsDisabled); } } }
37.869565
93
0.689246
[ "Apache-2.0" ]
48x16/BELLATRIX
tests/Bellatrix.Desktop.Tests/Controls/Pasword/PasswordControlTestsUniversal.cs
2,633
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Red.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Red.Formats.Red.Records.Enums; namespace GameEstate.Red.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class W3BoatSpawnerStateIdle : CScriptableState { public W3BoatSpawnerStateIdle(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new W3BoatSpawnerStateIdle(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
32.608696
134
0.752
[ "MIT" ]
bclnet/GameEstate
src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/W3BoatSpawnerStateIdle.cs
750
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.IO; using picovm.VM; namespace picovm.Packager.Elf.Elf32 { public sealed class LoaderElf32 : ILoader { private readonly Stream stream; public LoaderElf32(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); this.stream = stream; } public LoaderResult32 LoadImage() { if (!stream.CanRead) throw new ArgumentException("Stream is not available for reading", nameof(stream)); if (!stream.CanSeek) throw new ArgumentException("Stream is not available for seeking", nameof(stream)); var elfFileHeader = new Header32(); elfFileHeader.Read(stream); stream.Seek((long)elfFileHeader.E_PHOFF, SeekOrigin.Begin); var programHeader = new ProgramHeader32(); programHeader.Read(stream); var image = new byte[(int)programHeader.P_FILESZ - elfFileHeader.E_EHSIZE - (elfFileHeader.E_PHNUM * elfFileHeader.E_PHENTSIZE)]; UInt32 imageOffset = elfFileHeader.E_EHSIZE + (UInt32)elfFileHeader.E_EHSIZE.CalculateRoundUpTo16Pad() + (UInt32)(elfFileHeader.E_PHNUM * (elfFileHeader.E_PHENTSIZE + elfFileHeader.E_PHENTSIZE.CalculateRoundUpTo16Pad())); stream.Seek(imageOffset, SeekOrigin.Begin); stream.Read(image, 0, image.Length); return new LoaderResult32(elfFileHeader.E_ENTRY - imageOffset, image, metadata: new object[] { elfFileHeader, programHeader }); } public ImmutableList<object> LoadMetadata() { var metadata = new List<object>(); if (!stream.CanRead) throw new ArgumentException("Stream is not available for reading", nameof(stream)); if (!stream.CanSeek) throw new ArgumentException("Stream is not available for seeking", nameof(stream)); var elfFileHeader = new Header32(); elfFileHeader.Read(stream); metadata.Add(elfFileHeader); stream.Seek((long)elfFileHeader.E_PHOFF, SeekOrigin.Begin); var programHeader = new ProgramHeader32(); programHeader.Read(stream); metadata.Add(programHeader); return metadata.ToImmutableList(); } ILoaderResult ILoader.LoadImage() => this.LoadImage(); } }
36.6
141
0.620999
[ "MIT" ]
seanmcelroy/picovm
picovm/Packager/Elf/Elf32/LoaderElf32.cs
2,562
C#
// This file was automatically generated and may be regenerated at any // time. To ensure any changes are retained, modify the tool with any segment/component/group/field name // or type changes. namespace Machete.HL7Schema.V26.Maps { using V26; /// <summary> /// XPN (ComponentMap) - Extended Person Name /// </summary> public class XPNMap : HL7V26ComponentMap<XPN> { public XPNMap() { Entity(x => x.FamilyName, 0); Value(x => x.GivenName, 1); Value(x => x.SecondAndFurtherGivenNamesOrInitialsThereof, 2); Value(x => x.Suffix, 3); Value(x => x.Prefix, 4); Value(x => x.Degree, 5); Value(x => x.NameTypeCode, 6); Value(x => x.NameRepresentationCode, 7); Entity(x => x.NameContext, 8); Entity(x => x.NameValidityRange, 9); Value(x => x.NameAssemblyOrder, 10); Value(x => x.EffectiveDate, 11, x => {x.Converter = HL7.HL7ValueConverters.VariableLongDateTime;}); Value(x => x.ExpirationDate, 12, x => {x.Converter = HL7.HL7ValueConverters.VariableLongDateTime;}); Value(x => x.ProfessionalSuffix, 13); } } }
39.46875
113
0.567696
[ "Apache-2.0" ]
AreebaAroosh/Machete
src/Machete.HL7Schema/Generated/V26/Components/Maps/XPNMap.cs
1,263
C#