content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MobileOperator { class MobileOperator { static void Main(string[] args) { string duration = Console.ReadLine(); string contractType = Console.ReadLine(); string hasInternet = Console.ReadLine(); int months = int.Parse(Console.ReadLine()); decimal price = 0; decimal sum = 0; if (duration == "one") { if (contractType == "Small") { price = 9.98m; } else if (contractType == "Middle") { price = 18.99m; } else if (contractType == "Large") { price = 25.98m; } else if (contractType == "ExtraLarge") { price = 35.99m; } } else if (duration == "two") { if (contractType == "Small") { price = 8.58m; } else if (contractType == "Middle") { price = 17.09m; } else if (contractType == "Large") { price = 23.59m; } else if (contractType == "ExtraLarge") { price = 31.79m; } } if (hasInternet == "yes") { if (price <= 10) { price += 5.50m; } else if (price <= 30) { price += 4.35m; } else if (price > 30) { price += 3.85m; } } if (duration == "two") { price *= 0.9625m; } Console.WriteLine($"{price* months:f2} lv."); } } }
25.964286
57
0.339294
[ "MIT" ]
bodyquest/SoftwareUniversity-Bulgaria
Programming Basics C# Sept2018/EXAMS/2017-Sept-EXAM/MobileOperator/MobileOperator.cs
2,183
C#
using System.Web; using EPiServer.Web; namespace Foundation.Features.Preview { public class PartialViewDisplayChannel : DisplayChannel { public const string PartialViewDisplayChannelName = "Partial View Preview"; public override string ChannelName => PartialViewDisplayChannelName; public override bool IsActive(HttpContextBase context) => false; } }
27.857143
83
0.748718
[ "Apache-2.0" ]
eripe/foundation-mvc-cms
src/Foundation/Features/Preview/PartialViewDisplayChannel.cs
392
C#
namespace FavLocations.Properties { // This class allows you to handle specific events on the settings class: // The SettingChanging event is raised before a setting's value is changed. // The PropertyChanged event is raised after a setting's value is changed. // The SettingsLoaded event is raised after the setting values are loaded. // The SettingsSaving event is raised before the setting values are saved. internal sealed partial class Settings { public Settings() { // // To add event handlers for saving and changing settings, uncomment the lines below: // // this.SettingChanging += this.SettingChangingEventHandler; // // this.SettingsSaving += this.SettingsSavingEventHandler; // } private void SettingChangingEventHandler(object sender, System.Configuration.SettingChangingEventArgs e) { // Add code to handle the SettingChangingEvent event here. } private void SettingsSavingEventHandler(object sender, System.ComponentModel.CancelEventArgs e) { // Add code to handle the SettingsSaving event here. } } }
42.448276
114
0.657189
[ "MIT" ]
Anindra123/FavLocations
FavLocations/Settings.cs
1,233
C#
using System; using System.Collections.Generic; using System.Configuration.Provider; namespace Candor.Sample { public abstract class LocationProvider : ProviderBase { /// <summary> /// retrieve an existing location details by the identity. /// </summary> /// <param name="locationId"></param> /// <returns></returns> public abstract Location GetById(string locationId); /// <summary> /// Search for locations that partially match a term, such as for a search filter box. /// </summary> /// <param name="term">A full or partial match.</param> /// <returns></returns> public abstract IList<Location> Search(string term); /// <summary> /// Creates a new location. /// </summary> /// <param name="item"></param> /// <returns></returns> public abstract Location Save(Location item); } }
32.413793
94
0.595745
[ "MIT" ]
michael-lang/sample-ng2-mvc
Candor.Sample/LocationProvider.cs
942
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudtrail-2013-11-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.CloudTrail.Model { /// <summary> /// Container for the parameters to the CancelQuery operation. /// Cancels a query if the query is not in a terminated state, such as <code>CANCELLED</code>, /// <code>FAILED</code>, <code>TIMED_OUT</code>, or <code>FINISHED</code>. You must specify /// an ARN value for <code>EventDataStore</code>. The ID of the query that you want to /// cancel is also required. When you run <code>CancelQuery</code>, the query status might /// show as <code>CANCELLED</code> even if the operation is not yet finished. /// </summary> public partial class CancelQueryRequest : AmazonCloudTrailRequest { private string _eventDataStore; private string _queryId; /// <summary> /// Gets and sets the property EventDataStore. /// <para> /// The ARN (or the ID suffix of the ARN) of an event data store on which the specified /// query is running. /// </para> /// </summary> [AWSProperty(Required=true, Min=3, Max=256)] public string EventDataStore { get { return this._eventDataStore; } set { this._eventDataStore = value; } } // Check to see if EventDataStore property is set internal bool IsSetEventDataStore() { return this._eventDataStore != null; } /// <summary> /// Gets and sets the property QueryId. /// <para> /// The ID of the query that you want to cancel. The <code>QueryId</code> comes from the /// response of a <code>StartQuery</code> operation. /// </para> /// </summary> [AWSProperty(Required=true, Min=36, Max=36)] public string QueryId { get { return this._queryId; } set { this._queryId = value; } } // Check to see if QueryId property is set internal bool IsSetQueryId() { return this._queryId != null; } } }
34.388235
108
0.63428
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/CloudTrail/Generated/Model/CancelQueryRequest.cs
2,923
C#
// Copyright (c) Microsoft. All rights reserved. using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.IoTSolutions.DeviceSimulation.Services.Concurrency; using Microsoft.Azure.IoTSolutions.DeviceSimulation.Services.Diagnostics; using Microsoft.Azure.IoTSolutions.DeviceSimulation.SimulationAgent.DeviceProperties; namespace Microsoft.Azure.IoTSolutions.DeviceSimulation.SimulationAgent.SimulationThreads { public interface IUpdatePropertiesTask { Task RunAsync( ConcurrentDictionary<string, ISimulationManager> simulationManagers, ConcurrentDictionary<string, IDevicePropertiesActor> devicePropertiesActors, CancellationToken runningToken); } public class UpdatePropertiesTask : IUpdatePropertiesTask { // Global settings, not affected by hub SKU or simulation settings private readonly IAppConcurrencyConfig appConcurrencyConfig; private readonly ILogger log; public UpdatePropertiesTask( IAppConcurrencyConfig appConcurrencyConfig, ILogger logger) { this.appConcurrencyConfig = appConcurrencyConfig; this.log = logger; } public async Task RunAsync( ConcurrentDictionary<string, ISimulationManager> simulationManagers, ConcurrentDictionary<string, IDevicePropertiesActor> devicePropertiesActors, CancellationToken runningToken) { // Once N devices are attempting to write twins, wait until they are done var pendingTasksLimit = this.appConcurrencyConfig.MaxPendingTwinWrites; var tasks = new List<Task>(); while (!runningToken.IsCancellationRequested) { // TODO: resetting counters every few seconds seems to be a bug - to be revisited foreach (var manager in simulationManagers) { manager.Value.NewPropertiesLoop(); } var before = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds(); foreach (var device in devicePropertiesActors) { if (device.Value.HasWorkToDo()) { tasks.Add(device.Value.RunAsync()); } if (tasks.Count < pendingTasksLimit) continue; await Task.WhenAll(tasks); tasks.Clear(); } var durationMsecs = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() - before; this.log.Debug("Device-properties loop completed", () => new { durationMsecs }); this.SlowDownIfTooFast(durationMsecs, this.appConcurrencyConfig.MinDevicePropertiesLoopDuration); } // If there are pending tasks... if (tasks.Count > 0) { await Task.WhenAll(tasks); tasks.Clear(); } } private void SlowDownIfTooFast(long duration, int min) { // Avoid sleeping for only one millisecond if (duration >= min || min - duration <= 1) return; var pauseMsecs = min - (int) duration; this.log.Debug("Pausing device-properties thread", () => new { pauseMsecs }); Thread.Sleep(pauseMsecs); } } }
37.793478
113
0.623814
[ "MIT" ]
ZeroInfinite/device-simulation-dotnet
SimulationAgent/SimulationThreads/UpdatePropertiesTask.cs
3,479
C#
namespace CleanArchitecture.Core.Services { public class SomeDomainService { // TODO: This would handle operations involving multiple aggregates or entities } }
22.75
87
0.725275
[ "MIT" ]
1-NET-CORE-BASES/CleanArchitecture
src/CleanArchitecture.Core/Services/SomeDomainService.cs
184
C#
namespace MDManagement.Common { public static class DataValidations { public static class Adress { public const int AddressMaxLength = 150; } public static class Company { public const int NameMaxLength = 30; public const int DescriptionMaxLength = 1000; public const int CompanyCodeMaxValue = 15; } public static class Employee { public const int NameMaxLength = 30; public const string SalaryDeciamlSecifications = "decimal (18,4)"; } public static class Department { public const int NameMaxLength = 30; } public static class JobTitle { public const int NameMaxLength = 30; public const int DescriptionMaxLength = 100; } public static class Project { public const int NameMaxLength = 30; public const int DescriptionMaxLength = 100; } public static class Town { public const int NameMaxLength = 30; public const int PostCodeMaxLength = 4; } } }
25.869565
78
0.560504
[ "MIT" ]
Mirkoniks/MDManagement
MDManagement.Common/DataValidations.cs
1,192
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.UnitTests; using Xunit; namespace Microsoft.ApiDesignGuidelines.Analyzers.UnitTests { public class UriReturnValuesShouldNotBeStringsFixerTests : CodeFixTestBase { protected override DiagnosticAnalyzer GetBasicDiagnosticAnalyzer() { return new BasicUriReturnValuesShouldNotBeStringsAnalyzer(); } protected override DiagnosticAnalyzer GetCSharpDiagnosticAnalyzer() { return new CSharpUriReturnValuesShouldNotBeStringsAnalyzer(); } protected override CodeFixProvider GetBasicCodeFixProvider() { return new BasicUriReturnValuesShouldNotBeStringsFixer(); } protected override CodeFixProvider GetCSharpCodeFixProvider() { return new CSharpUriReturnValuesShouldNotBeStringsFixer(); } } }
35.090909
160
0.737478
[ "Apache-2.0" ]
amcasey/roslyn-analyzers
src/Microsoft.ApiDesignGuidelines.Analyzers/UnitTests/UriReturnValuesShouldNotBeStringsTests.Fixer.cs
1,158
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.V20180701 { /// <summary> /// VirtualHub Resource. /// </summary> [AzureNativeResourceType("azure-native:network/v20180701:VirtualHub")] public partial class VirtualHub : Pulumi.CustomResource { /// <summary> /// Address-prefix for this VirtualHub. /// </summary> [Output("addressPrefix")] public Output<string?> AddressPrefix { 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> /// list of all vnet connections with this VirtualHub. /// </summary> [Output("hubVirtualNetworkConnections")] public Output<ImmutableArray<Outputs.HubVirtualNetworkConnectionResponse>> HubVirtualNetworkConnections { 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> /// The provisioning state of the resource. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { 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> /// The VirtualWAN to which the VirtualHub belongs /// </summary> [Output("virtualWan")] public Output<Outputs.SubResourceResponse?> VirtualWan { get; private set; } = null!; /// <summary> /// Create a VirtualHub 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 VirtualHub(string name, VirtualHubArgs args, CustomResourceOptions? options = null) : base("azure-native:network/v20180701:VirtualHub", name, args ?? new VirtualHubArgs(), MakeResourceOptions(options, "")) { } private VirtualHub(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:network/v20180701:VirtualHub", 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/v20180701:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20180401:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180401:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20180601:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180601:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20180801:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20181001:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20181101:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20181201:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20190201:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20190401:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20190601:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20190701:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20190801:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20190901:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20191101:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20191201:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20200301:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20200401:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20200501:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20200601:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20200701:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20200801:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20201101:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20201101:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20210201:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20210201:VirtualHub"}, new Pulumi.Alias { Type = "azure-native:network/v20210301:VirtualHub"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20210301:VirtualHub"}, }, }; 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 VirtualHub 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 VirtualHub Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new VirtualHub(name, id, options); } } public sealed class VirtualHubArgs : Pulumi.ResourceArgs { /// <summary> /// Address-prefix for this VirtualHub. /// </summary> [Input("addressPrefix")] public Input<string>? AddressPrefix { get; set; } [Input("hubVirtualNetworkConnections")] private InputList<Inputs.HubVirtualNetworkConnectionArgs>? _hubVirtualNetworkConnections; /// <summary> /// list of all vnet connections with this VirtualHub. /// </summary> public InputList<Inputs.HubVirtualNetworkConnectionArgs> HubVirtualNetworkConnections { get => _hubVirtualNetworkConnections ?? (_hubVirtualNetworkConnections = new InputList<Inputs.HubVirtualNetworkConnectionArgs>()); set => _hubVirtualNetworkConnections = value; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } /// <summary> /// Resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The resource group name of the VirtualHub. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } /// <summary> /// The name of the VirtualHub. /// </summary> [Input("virtualHubName")] public Input<string>? VirtualHubName { get; set; } /// <summary> /// The VirtualWAN to which the VirtualHub belongs /// </summary> [Input("virtualWan")] public Input<Inputs.SubResourceArgs>? VirtualWan { get; set; } public VirtualHubArgs() { } } }
47.683761
142
0.591235
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Network/V20180701/VirtualHub.cs
11,158
C#
namespace QOAM.Website.Helpers { using System.Web.Security; public interface IMembership { bool ValidateUser(string username, string password); bool DeleteUser(string username, bool deleteAllRelatedData); MembershipCreateStatus CreateUser(string username, string password, string email); MembershipUser GetUser(string username, bool userIsOnline); } }
26.933333
90
0.725248
[ "MIT" ]
QOAM/qoam
src/Website/Helpers/IMembership.cs
406
C#
using BlazorApp.Context; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace BlazorApp.Server { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddRazorPages(); services.AddDbContext<BlazorAppDbContext>(option => { option.UseSqlite(Configuration["Connections:Sqlite"], b => b.MigrationsAssembly("server")); }); services.AddBlazorAppServices(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseWebAssemblyDebugging(); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseBlazorFrameworkFiles(); app.UseStaticFiles(); app.UseRouting(); app.UseEndpoints(endpoints => { endpoints.MapRazorPages(); endpoints.MapControllers(); endpoints.MapFallbackToFile("index.html"); }); } } }
27.33871
107
0.576401
[ "Apache-2.0" ]
JadedEric/fun-with-blazor
BlazorApp/Server/Startup.cs
1,695
C#
using System.Collections.Generic; using System.Linq; using RestSharp; namespace Indicia.HubSpot.Support { internal static class RestRequestExtensions { public static void AddQueryParameters(this RestRequest request, IDictionary<string, string> queryParameters) { if (queryParameters == null || !queryParameters.Any()) { return; } foreach (var queryParameter in queryParameters) { request.AddQueryParameter(queryParameter.Key, queryParameter.Value); } } } }
27.227273
116
0.614357
[ "MIT" ]
IndiciaConnectivity/Indicia.HubSpot
Indicia.HubSpot/Support/RestRequestExtensions.cs
601
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; namespace CodeBuilder.Util.Test { public class LoggerTest { private static Logger logger; [SetUp] public void Setup() { logger = InternalTrace.GetLogger(typeof(LoggerTest)); } [Test] public void Is_Not_Null() { Assert.That(logger, Is.Not.Null); } [Test] public void Is_Writer_Logs() { logger.Info("Info"); logger.Error("Error"); } [TearDown] public void Down() { logger = null; } } }
18.128205
65
0.519095
[ "MIT" ]
ijlynivfhp/CodeBuilder
CodeBuilder.Framework.Test/Util/Logging/LoggerTest.cs
709
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.Resources.V20210501 { public static class GetTemplateSpecVersion { /// <summary> /// Template Spec Version object. /// </summary> public static Task<GetTemplateSpecVersionResult> InvokeAsync(GetTemplateSpecVersionArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetTemplateSpecVersionResult>("azure-native:resources/v20210501:getTemplateSpecVersion", args ?? new GetTemplateSpecVersionArgs(), options.WithVersion()); } public sealed class GetTemplateSpecVersionArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the resource group. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// Name of the Template Spec. /// </summary> [Input("templateSpecName", required: true)] public string TemplateSpecName { get; set; } = null!; /// <summary> /// The version of the Template Spec. /// </summary> [Input("templateSpecVersion", required: true)] public string TemplateSpecVersion { get; set; } = null!; public GetTemplateSpecVersionArgs() { } } [OutputType] public sealed class GetTemplateSpecVersionResult { /// <summary> /// Template Spec version description. /// </summary> public readonly string? Description; /// <summary> /// String Id used to locate any resource on Azure. /// </summary> public readonly string Id; /// <summary> /// An array of linked template artifacts. /// </summary> public readonly ImmutableArray<Outputs.LinkedTemplateArtifactResponse> LinkedTemplates; /// <summary> /// The location of the Template Spec Version. It must match the location of the parent Template Spec. /// </summary> public readonly string Location; /// <summary> /// The main Azure Resource Manager template content. /// </summary> public readonly object? MainTemplate; /// <summary> /// The version metadata. Metadata is an open-ended object and is typically a collection of key-value pairs. /// </summary> public readonly object? Metadata; /// <summary> /// Name of this resource. /// </summary> public readonly string Name; /// <summary> /// Azure Resource Manager metadata containing createdBy and modifiedBy information. /// </summary> public readonly Outputs.SystemDataResponse SystemData; /// <summary> /// Resource tags. /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// Type of this resource. /// </summary> public readonly string Type; /// <summary> /// The Azure Resource Manager template UI definition content. /// </summary> public readonly object? UiFormDefinition; [OutputConstructor] private GetTemplateSpecVersionResult( string? description, string id, ImmutableArray<Outputs.LinkedTemplateArtifactResponse> linkedTemplates, string location, object? mainTemplate, object? metadata, string name, Outputs.SystemDataResponse systemData, ImmutableDictionary<string, string>? tags, string type, object? uiFormDefinition) { Description = description; Id = id; LinkedTemplates = linkedTemplates; Location = location; MainTemplate = mainTemplate; Metadata = metadata; Name = name; SystemData = systemData; Tags = tags; Type = type; UiFormDefinition = uiFormDefinition; } } }
32.761194
208
0.603417
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Resources/V20210501/GetTemplateSpecVersion.cs
4,390
C#
using System; using System.Linq; using Android.App; using Android.Graphics; using Android.Runtime; using Com.Google.Android.Exoplayer2; using Com.Google.Android.Exoplayer2.UI; using MediaManager.Media; namespace MediaManager.Platforms.Android.Media { public class MediaDescriptionAdapter : Java.Lang.Object, PlayerNotificationManager.IMediaDescriptionAdapter { protected MediaManagerImplementation MediaManager => CrossMediaManager.Android; public MediaDescriptionAdapter() { } protected MediaDescriptionAdapter(IntPtr handle, JniHandleOwnership transfer) : base(handle, transfer) { } public PendingIntent CreateCurrentContentIntent(IPlayer player) { return MediaManager.SessionActivityPendingIntent; } public string GetCurrentContentText(IPlayer player) { return MediaManager.MediaQueue.ElementAtOrDefault(player.CurrentWindowIndex)?.GetTitle(); } public string GetCurrentContentTitle(IPlayer player) { return MediaManager.MediaQueue.ElementAtOrDefault(player.CurrentWindowIndex)?.GetContentTitle(); } public Bitmap GetCurrentLargeIcon(IPlayer player, PlayerNotificationManager.BitmapCallback callback) { return MediaManager.MediaQueue.ElementAtOrDefault(player.CurrentWindowIndex)?.GetCover(); } } }
31.6
111
0.718706
[ "MIT" ]
mr5z/XamarinMediaManager
MediaManager/Platforms/Android/Media/MediaDescriptionAdapter.cs
1,424
C#
using UnityEditor; using UnityEditor.SceneManagement; using UnityEngine; [InitializeOnLoad] public static class DefaultSetup { const string k_NewSceneFolderParent = "Assets/Creator Kit - Puzzle/Scenes"; const string k_NewSceneFolderName = "UserCreated"; const string k_NewSceneFolder = k_NewSceneFolderParent + "/" + k_NewSceneFolderName; const string k_NewSceneReferenceFolderParent = "Assets/Creator Kit - Puzzle/SceneReferences"; const string k_NewSceneReferenceFolderName = "UserCreated"; const string k_NewSceneReferenceFolder = k_NewSceneReferenceFolderParent + "/" + k_NewSceneReferenceFolderName; static DefaultSetup () { EditorApplication.update += FirstFrameUpdate; } static void FirstFrameUpdate () { bool skyboxUpdated = UpdateSceneViewSkybox (); CheckAndCreateFolders (); if(skyboxUpdated) EditorApplication.update -= FirstFrameUpdate; } static bool UpdateSceneViewSkybox () { if (StageUtility.GetCurrentStageHandle () != StageUtility.GetMainStageHandle ()) return false; SceneView sceneView = SceneView.lastActiveSceneView; if (sceneView == null) return false; SceneView.SceneViewState state = sceneView.sceneViewState; state.showSkybox = false; sceneView.sceneViewState = state; return true; } static void CheckAndCreateFolders () { if (!AssetDatabase.IsValidFolder (k_NewSceneFolder)) { AssetDatabase.CreateFolder (k_NewSceneFolderParent, k_NewSceneFolderName); } if (!AssetDatabase.IsValidFolder (k_NewSceneReferenceFolder)) { AssetDatabase.CreateFolder (k_NewSceneReferenceFolderParent, k_NewSceneReferenceFolderName); } } }
30.733333
115
0.68872
[ "MIT" ]
tianxiawuzhei/unitystudy
Puzzle/PuzzleStudy/Assets/Creator Kit - Puzzle/Scripts/Editor/DefaultSetup.cs
1,846
C#
#if DEBUG using System; using System.Globalization; using System.IO; using System.Text; using System.Threading; using NUnit.Framework; namespace DevExpress.Logify.Core.Internal.Tests { [TestFixture] public class AttachmentsCollectorTests : CollectorTestsBase { AttachmentsCollector collector; AttachmentCollection attachments; AttachmentCollection additionalAttachments; [SetUp] public void Setup() { this.attachments = new AttachmentCollection(); this.additionalAttachments = new AttachmentCollection(); this.collector = new AttachmentsCollector(attachments, additionalAttachments); SetupCore(); } [TearDown] public void TearDown() { TearDownCore(); } [Test] public void Default() { collector.Process(null, Logger); string expected = ""; Assert.AreEqual(expected, Content); } [Test] public void EmptyAttachContent() { attachments.Add(new Attachment() { Name = "test", MimeType = "image/png" }); this.collector = new AttachmentsCollector(attachments, additionalAttachments); collector.Process(null, Logger); string expected = "\"attachments\":[]\r\n"; Assert.AreEqual(expected, Content); } [Test] public void EmptyAttachName() { attachments.Add(new Attachment() { MimeType = "image/png", Content = new byte[] { 0, 1, 2 } }); this.collector = new AttachmentsCollector(attachments, additionalAttachments); collector.Process(null, Logger); string expected = "\"attachments\":[]\r\n"; Assert.AreEqual(expected, Content); } [Test] public void SimpleAttach() { attachments.Add(new Attachment() { Name = "img", MimeType = "image/png", Content = new byte[] { 0, 1, 2 } }); this.collector = new AttachmentsCollector(attachments, additionalAttachments); collector.Process(null, Logger); string expected = "\"attachments\":[\r\n{\r\n\"name\":\"img\",\r\n\"mimeType\":\"image/png\",\r\n\"content\":\"H4sIAAAAAAAEAGNgZAIAf4lUCAMAAAA=\",\r\n\"compress\":\"gzip\"\r\n}\r\n]\r\n"; Assert.AreEqual(expected, Content); } } } #endif
40.20339
199
0.604975
[ "MIT" ]
cghersi/UWPExamples
TestARM64/Logify.Alert.Core/Tests/Collectors/AttachmentsCollectorTests.cs
2,374
C#
namespace Textorizer.Html { internal readonly struct TokenInfo { public readonly int ElementDepth; public readonly Token Token; public TokenInfo(int elementDepth, Token token) { ElementDepth = elementDepth; Token = token; } } }
22.428571
55
0.576433
[ "Unlicense" ]
Ruzzie/Textorizer
source/Textorizer/Html/TokenInfo.cs
316
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // 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 Microsoft.Azure.Commands.StreamAnalytics.Models; using Microsoft.Azure.Commands.StreamAnalytics.Properties; using System.Globalization; using System.Management.Automation; using System.Net; using System.Security.Permissions; namespace Microsoft.Azure.Commands.StreamAnalytics { [Cmdlet(VerbsLifecycle.Stop, Constants.StreamAnalyticsJob)] public class StopAzureStreamAnalyticsJobCommand : StreamAnalyticsResourceProviderBaseCmdlet { [Parameter(Position = 1, Mandatory = true, ValueFromPipelineByPropertyName = true, HelpMessage = "The azure stream analytics job name.")] [ValidateNotNullOrEmpty] public string Name { get; set; } [EnvironmentPermission(SecurityAction.Demand, Unrestricted = true)] public override void ExecuteCmdlet() { if (ResourceGroupName != null && string.IsNullOrWhiteSpace(ResourceGroupName)) { throw new PSArgumentNullException("ResourceGroupName"); } JobParametersBase parameter = new JobParametersBase() { ResourceGroupName = ResourceGroupName, JobName = Name }; try { HttpStatusCode statusCode = StreamAnalyticsClient.StopPSJob(parameter); if (statusCode == HttpStatusCode.OK) { WriteObject(true); } else if (statusCode == HttpStatusCode.NoContent) { WriteWarning(string.Format(CultureInfo.InvariantCulture, Resources.JobNotFound, Name, ResourceGroupName)); } else { WriteObject(false); } } catch { WriteObject(false); } } } }
40.059701
146
0.577496
[ "MIT" ]
FosterMichelle/azure-powershell
src/ResourceManager/StreamAnalytics/Commands.StreamAnalytics/Job/StopAzureStreamAnalyticsJobCommand.cs
2,620
C#
namespace RemoveVillain { public static class Configuration { public const string ConnectionString = @"Server=.;Database=MinionsDB;Integrated Security = True"; } }
23.125
105
0.702703
[ "MIT" ]
ivanov-mi/SoftUni-Training
05EntityFrameworkCore/01AdoNetIntroduction/06RemoveVillain/Configuration.cs
187
C#
using System.Threading; using System.Threading.Tasks; namespace SmtpServer.Protocol { public sealed class HeloCommand : SmtpCommand { readonly string _domain; /// <summary> /// Constructor. /// </summary> /// <param name="domain">The domain name.</param> public HeloCommand(string domain) { _domain = domain; } /// <summary> /// Execute the command. /// </summary> /// <param name="context">The execution context to operate on.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task which asynchronously performs the execution.</returns> public override Task ExecuteAsync(ISmtpSessionContext context, CancellationToken cancellationToken) { var response = new SmtpResponse(SmtpReplyCode.Ok, $"Hello {Domain}, haven't we met before?"); return context.Text.ReplyAsync(response, cancellationToken); } /// <summary> /// Gets the domain name. /// </summary> public string Domain { get { return _domain; } } } }
29.170732
107
0.584448
[ "MIT" ]
Wirth/SmtpServer
Src/SmtpServer/Protocol/HeloCommand.cs
1,198
C#
using System; using System.Collections.Generic; using System.Text; namespace Flattiverse { /// <summary> /// This exception will be thrown, when the you try to login but are already connected. /// </summary> public class AlreadyConnectedException : InvalidOperationException { internal AlreadyConnectedException() : base ("This instance is already connected.") { } } }
25.588235
92
0.652874
[ "MIT" ]
GhostTyper/flattiverse
Connector/Connector/AlreadyConnectedException.cs
437
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("08_CondenseArrayToNumber")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("08_CondenseArrayToNumber")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6d008f98-9a4c-4402-9929-a6d2ca8c6274")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.405405
84
0.749472
[ "MIT" ]
nellypeneva/SoftUniProjects
01_ProgrFundamentalsMay/15_Arrays-Lab/08_CondenseArrayToNumber/Properties/AssemblyInfo.cs
1,424
C#
using System; using System.IO; using System.Timers; using ConnectivityLib; using Microsoft.Win32; using ShutdownLib; namespace VxShutdownTimer.GUI.Triggers.DirectoryTrigger { public class DirectoryViewModel:BindableBase { private bool _isRunning, _isEnabled = true; private FileSystemWatcher _watcher; private string _shutdownType, _location; public bool IsRunning { get { return _isRunning; } set { OnPropertyChanged(ref _isRunning, value, nameof(IsRunning)); } } public bool IsEnabled { get { return _isEnabled; } set { OnPropertyChanged(ref _isEnabled, value, nameof(IsEnabled)); } } public string ShutdownType { get { return _shutdownType; } set { OnPropertyChanged(ref _shutdownType, value, nameof(ShutdownType)); } } public string DirectoryLocation { get { return _location; } set { OnPropertyChanged(ref _location, value, nameof(DirectoryLocation)); } } public RelayCommand StartCommand { get; private set; } public RelayCommand BrowseCommand { get; private set; } public RelayCommand CancelCommand { get; private set; } public override event EventHandler<string> Info; public override event EventHandler<string> Error; public DirectoryViewModel() { Load(); } private void ProcessCommand(string shutdownType) { try { switch (shutdownType) { case "Shutdown": ShutdownInvoker.InvokeShutdown(); break; case "Hibernate": ShutdownInvoker.SetSuspendState(true, true, true); break; case "Restart": ShutdownInvoker.InvokeRestart(); break; case "Sleep": ShutdownInvoker.SetSuspendState(false, true, true); break; case "Log Off": ShutdownInvoker.ExitWindowsEx(0, 0); break; case "Lock": ShutdownInvoker.LockWorkStation(); break; } } catch (Exception ex) { OnCancel(); OnErrorOccured(ex.Message); } } private void Load() { StartCommand = new RelayCommand(OnStart, CanStart); BrowseCommand = new RelayCommand(OnBrowse, CanBrowse); CancelCommand = new RelayCommand(OnCancel, CanCancel); _watcher = new FileSystemWatcher { NotifyFilter = NotifyFilters.Attributes | NotifyFilters.CreationTime | NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.Security | NotifyFilters.Size, IncludeSubdirectories = false }; } private void OnWatcherChanged(object sender, FileSystemEventArgs e) { ProcessCommand(ShutdownType); //to avoid error or non-shutdown/restart/log off operation OnCancel(); } private void OnWatcherCreated(object sender, FileSystemEventArgs e) { ProcessCommand(ShutdownType); //to avoid error or non-shutdown/restart/log off operation OnCancel(); } private void OnWatcherDeleted(object sender, FileSystemEventArgs e) { ProcessCommand(ShutdownType); //to avoid error or non-shutdown/restart/log off operation OnCancel(); } private void OnWatcherRenamed(object sender, RenamedEventArgs e) { ProcessCommand(ShutdownType); //to avoid error or non-shutdown/restart/log off operation OnCancel(); } private void OnWatcherError(object sender, ErrorEventArgs e) { OnCancel(); } private void OnStart() { try { _watcher.Changed += OnWatcherChanged; _watcher.Created += OnWatcherCreated; _watcher.Deleted += OnWatcherDeleted; _watcher.Renamed += OnWatcherRenamed; _watcher.Error += OnWatcherError; _watcher.Path = DirectoryLocation; _watcher.Filter = "*.*"; _watcher.EnableRaisingEvents = true; IsRunning = true; IsEnabled = false; } catch (Exception ex) { OnErrorOccured(ex.Message); } } private bool CanStart() { return !IsRunning && !String.IsNullOrEmpty(DirectoryLocation); } private void OnBrowse() { try { System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog(); if(dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { DirectoryLocation = dialog.SelectedPath; } } catch (Exception ex) { OnErrorOccured(ex.Message); } } private bool CanBrowse() { return !IsRunning; } private void OnCancel() { try { _watcher.EnableRaisingEvents = false; _watcher.Filter = ""; _watcher.Changed -= OnWatcherChanged; _watcher.Created -= OnWatcherCreated; _watcher.Deleted -= OnWatcherDeleted; _watcher.Renamed -= OnWatcherRenamed; _watcher.Error -= OnWatcherError; IsRunning = false; IsEnabled = true; } catch (Exception ex) { OnErrorOccured(ex.Message); } } private bool CanCancel() { return IsRunning; } protected virtual void OnInfoRequested(string e) { Info?.Invoke(this, e); } protected virtual void OnErrorOccured(string e) { Error?.Invoke(this, e); } } }
29.780172
138
0.495007
[ "Apache-2.0" ]
Hantang0517/Vx-Shutdown-Timer
VxShutdownTimer.GUI/Triggers/DirectoryTrigger/DirectoryViewModel.cs
6,911
C#
namespace Au.More { /// <summary> /// Assembly functions. /// </summary> internal static class AssemblyUtil_ { /// <summary> /// Returns true if the build configuration of the assembly is Debug. Returns false if Release (optimized). /// </summary> /// <remarks> /// Returns true if the assembly has <see cref="DebuggableAttribute"/> and its <b>IsJITTrackingEnabled</b> is true. /// </remarks> public static bool IsDebug(Assembly a) => a?.GetCustomAttribute<DebuggableAttribute>()?.IsJITTrackingEnabled ?? false; //IsJITTrackingEnabled depends on config, but not 100% reliable, eg may be changed explicitly in source code (maybe IsJITOptimizerDisabled too). //IsJITOptimizerDisabled depends on 'Optimize code' checkbox in project Properties, regardless of config. //note: GetEntryAssembly returns null in func called by host through coreclr_create_delegate. //not used. Don't add Au to GAC, because then process may start slowly, don't know why. ///// <summary> ///// Returns true if Au.dll is installed in the global assembly cache. ///// </summary> //internal static bool IsAuInGAC => typeof(AssemblyUtil_).Assembly.GlobalAssemblyCache; //no ngen in Core. ///// <summary> ///// Returns true if Au.dll is compiled to native code using ngen.exe. ///// It means - no JIT-compiling delay when its functions are called first time in process. ///// </summary> //internal static bool IsAuNgened => s_auNgened ??= IsNgened(typeof(AssemblyUtil_).Assembly); //static bool? s_auNgened; ////tested: Module.GetPEKind always gets ILOnly. ////test: new StackFrame().HasNativeImage() ///// <summary> ///// Returns true if assembly asm is compiled to native code using ngen.exe. ///// It means - no JIT-compiling delay when its functions are called first time in process. ///// </summary> //public static bool IsNgened(Assembly asm) //{ // var s = asm.CodeBase; // //if(asm.GlobalAssemblyCache) return s.Contains("/GAC_MSIL/"); //faster and maybe more reliable, but works only with GAC assemblies // s = s.Substring(s.LastIndexOf('/') + 1); // s = s.Insert(s.LastIndexOf('.') + 1, "ni."); // return default != Api.GetModuleHandle(s); //} //much slower first time when ngened. Also it is undocumented that GetModuleFileName returns 0 if non-ngened (LOAD_LIBRARY_AS_DATAFILE?). //public static unsafe bool IsAssemblyNgened2(Assembly asm) //{ // var module =asm.GetLoadedModules()[0]; // var h = Marshal.GetHINSTANCE(module); //slow first time, especially when ngened // var b = stackalloc char[4]; // return 0 != Api.GetModuleFileName(h, b, 4); //} /// <summary> /// Returns flags for loaded assemblies: 1 System.Windows.Forms, 2 WindowsBase (WPF). /// </summary> internal static int IsLoadedWinformsWpf() { if (s_isLoadedWinformsWpf == 0) { lock ("zjm5R47f7UOmgyHUVZaf1w") { if (s_isLoadedWinformsWpf == 0) { var ad = AppDomain.CurrentDomain; var a = ad.GetAssemblies(); foreach (var v in a) { _FlagFromName(v); if (s_isLoadedWinformsWpf == 3) return 3; } ad.AssemblyLoad += (_, x) => _FlagFromName(x.LoadedAssembly); s_isLoadedWinformsWpf |= 0x100; } } } return s_isLoadedWinformsWpf & 3; void _FlagFromName(Assembly a) { string s = a.FullName; //fast, cached. GetName can be slow because not cached. if (0 == (s_isLoadedWinformsWpf & 1) && s.Starts("System.Windows.Forms,")) s_isLoadedWinformsWpf |= 1; else if (0 == (s_isLoadedWinformsWpf & 2) && s.Starts("WindowsBase,")) s_isLoadedWinformsWpf |= 2; } } static volatile int s_isLoadedWinformsWpf; } }
41.91954
146
0.685221
[ "MIT" ]
qmgindi/Au
Au/Internal/AssemblyUtil_.cs
3,649
C#
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System; using System.Collections.Concurrent; using System.Collections.Generic; using SixLabors.ImageSharp.Formats; using SixLabors.ImageSharp.Formats.Bmp; using SixLabors.ImageSharp.Formats.Gif; using SixLabors.ImageSharp.Formats.Jpeg; using SixLabors.ImageSharp.Formats.Png; using SixLabors.ImageSharp.Formats.Tga; using SixLabors.ImageSharp.Formats.Tiff; using SixLabors.ImageSharp.IO; using SixLabors.ImageSharp.Memory; using SixLabors.ImageSharp.Processing; namespace SixLabors.ImageSharp { /// <summary> /// Provides configuration which allows altering default behaviour or extending the library. /// </summary> public sealed class Configuration { /// <summary> /// A lazily initialized configuration default instance. /// </summary> private static readonly Lazy<Configuration> Lazy = new Lazy<Configuration>(CreateDefaultInstance); private const int DefaultStreamProcessingBufferSize = 8096; private int streamProcessingBufferSize = DefaultStreamProcessingBufferSize; private int maxDegreeOfParallelism = Environment.ProcessorCount; /// <summary> /// Initializes a new instance of the <see cref="Configuration" /> class. /// </summary> public Configuration() { } /// <summary> /// Initializes a new instance of the <see cref="Configuration" /> class. /// </summary> /// <param name="configurationModules">A collection of configuration modules to register.</param> public Configuration(params IConfigurationModule[] configurationModules) { if (configurationModules != null) { foreach (IConfigurationModule p in configurationModules) { p.Configure(this); } } } /// <summary> /// Gets the default <see cref="Configuration"/> instance. /// </summary> public static Configuration Default { get; } = Lazy.Value; /// <summary> /// Gets or sets the maximum number of concurrent tasks enabled in ImageSharp algorithms /// configured with this <see cref="Configuration"/> instance. /// Initialized with <see cref="Environment.ProcessorCount"/> by default. /// </summary> public int MaxDegreeOfParallelism { get => this.maxDegreeOfParallelism; set { if (value == 0 || value < -1) { throw new ArgumentOutOfRangeException(nameof(this.MaxDegreeOfParallelism)); } this.maxDegreeOfParallelism = value; } } /// <summary> /// Gets or sets the size of the buffer to use when working with streams. /// Initialized with <see cref="DefaultStreamProcessingBufferSize"/> by default. /// </summary> public int StreamProcessingBufferSize { get => this.streamProcessingBufferSize; set { if (value <= 0) { throw new ArgumentOutOfRangeException(nameof(this.StreamProcessingBufferSize)); } this.streamProcessingBufferSize = value; } } /// <summary> /// Gets a set of properties for the Configuration. /// </summary> /// <remarks>This can be used for storing global settings and defaults to be accessible to processors.</remarks> public IDictionary<object, object> Properties { get; } = new ConcurrentDictionary<object, object>(); /// <summary> /// Gets the currently registered <see cref="IImageFormat"/>s. /// </summary> public IEnumerable<IImageFormat> ImageFormats => this.ImageFormatsManager.ImageFormats; /// <summary> /// Gets or sets the position in a stream to use for reading when using a seekable stream as an image data source. /// </summary> public ReadOrigin ReadOrigin { get; set; } = ReadOrigin.Current; /// <summary> /// Gets or sets the <see cref="ImageFormatManager"/> that is currently in use. /// </summary> public ImageFormatManager ImageFormatsManager { get; set; } = new ImageFormatManager(); /// <summary> /// Gets or sets the <see cref="MemoryAllocator"/> that is currently in use. /// </summary> public MemoryAllocator MemoryAllocator { get; set; } = ArrayPoolMemoryAllocator.CreateDefault(); /// <summary> /// Gets the maximum header size of all the formats. /// </summary> internal int MaxHeaderSize => this.ImageFormatsManager.MaxHeaderSize; /// <summary> /// Gets or sets the filesystem helper for accessing the local file system. /// </summary> internal IFileSystem FileSystem { get; set; } = new LocalFileSystem(); /// <summary> /// Gets or sets the working buffer size hint for image processors. /// The default value is 1MB. /// </summary> /// <remarks> /// Currently only used by Resize. If the working buffer is expected to be discontiguous, /// min(WorkingBufferSizeHintInBytes, BufferCapacityInBytes) should be used. /// </remarks> internal int WorkingBufferSizeHintInBytes { get; set; } = 1 * 1024 * 1024; /// <summary> /// Gets or sets the image operations provider factory. /// </summary> internal IImageProcessingContextFactory ImageOperationsProvider { get; set; } = new DefaultImageOperationsProviderFactory(); /// <summary> /// Registers a new format provider. /// </summary> /// <param name="configuration">The configuration provider to call configure on.</param> public void Configure(IConfigurationModule configuration) { Guard.NotNull(configuration, nameof(configuration)); configuration.Configure(this); } /// <summary> /// Creates a shallow copy of the <see cref="Configuration"/>. /// </summary> /// <returns>A new configuration instance.</returns> public Configuration Clone() { return new Configuration { MaxDegreeOfParallelism = this.MaxDegreeOfParallelism, StreamProcessingBufferSize = this.StreamProcessingBufferSize, ImageFormatsManager = this.ImageFormatsManager, MemoryAllocator = this.MemoryAllocator, ImageOperationsProvider = this.ImageOperationsProvider, ReadOrigin = this.ReadOrigin, FileSystem = this.FileSystem, WorkingBufferSizeHintInBytes = this.WorkingBufferSizeHintInBytes, }; } /// <summary> /// Creates the default instance with the following <see cref="IConfigurationModule"/>s preregistered: /// <see cref="PngConfigurationModule"/> /// <see cref="JpegConfigurationModule"/> /// <see cref="GifConfigurationModule"/> /// <see cref="BmpConfigurationModule"/>. /// <see cref="TgaConfigurationModule"/>. /// <see cref="TiffConfigurationModule"/>. /// </summary> /// <returns>The default configuration of <see cref="Configuration"/>.</returns> internal static Configuration CreateDefaultInstance() { return new Configuration( new PngConfigurationModule(), new JpegConfigurationModule(), new GifConfigurationModule(), new BmpConfigurationModule(), new TgaConfigurationModule(), new TiffConfigurationModule()); } } }
39.798995
132
0.61149
[ "Apache-2.0" ]
IldarKhayrutdinov/ImageSharp
src/ImageSharp/Configuration.cs
7,920
C#
namespace ElearningApp { partial class AddEditCourseView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel(); this.panel2 = new System.Windows.Forms.Panel(); this.saveButton = new MaterialSkin2DotNet.Controls.MaterialButton(); this.panel1 = new System.Windows.Forms.Panel(); this.addSubjectButton = new MaterialSkin2DotNet.Controls.MaterialFloatingActionButton(); this.subjectsLabel = new MaterialSkin2DotNet.Controls.MaterialLabel(); this.subjectsListBox = new MaterialSkin2DotNet.Controls.MaterialListBox(); this.teachersDGV = new System.Windows.Forms.DataGridView(); this.TeacherName = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.descriptionLabel = new MaterialSkin2DotNet.Controls.MaterialLabel(); this.descriptionMultiLineTextBox = new MaterialSkin2DotNet.Controls.MaterialMultiLineTextBox(); this.nameTextBox = new MaterialSkin2DotNet.Controls.MaterialTextBox(); this.tableLayoutPanel1.SuspendLayout(); this.panel2.SuspendLayout(); this.panel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.teachersDGV)).BeginInit(); this.SuspendLayout(); // // tableLayoutPanel1 // this.tableLayoutPanel1.ColumnCount = 1; this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel1.Controls.Add(this.panel2, 0, 1); this.tableLayoutPanel1.Controls.Add(this.panel1, 0, 0); this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel1.Location = new System.Drawing.Point(3, 64); this.tableLayoutPanel1.Name = "tableLayoutPanel1"; this.tableLayoutPanel1.RowCount = 2; this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 92.74756F)); this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 7.252441F)); this.tableLayoutPanel1.Size = new System.Drawing.Size(457, 717); this.tableLayoutPanel1.TabIndex = 0; // // panel2 // this.panel2.Controls.Add(this.saveButton); this.panel2.Dock = System.Windows.Forms.DockStyle.Fill; this.panel2.Location = new System.Drawing.Point(3, 668); this.panel2.Name = "panel2"; this.panel2.Size = new System.Drawing.Size(451, 46); this.panel2.TabIndex = 1; // // saveButton // this.saveButton.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.saveButton.Density = MaterialSkin2DotNet.Controls.MaterialButton.MaterialButtonDensity.Default; this.saveButton.Depth = 0; this.saveButton.HighEmphasis = true; this.saveButton.Icon = null; this.saveButton.Location = new System.Drawing.Point(170, 6); this.saveButton.Margin = new System.Windows.Forms.Padding(4, 6, 4, 6); this.saveButton.MouseState = MaterialSkin2DotNet.MouseState.HOVER; this.saveButton.Name = "saveButton"; this.saveButton.NoAccentTextColor = System.Drawing.Color.Empty; this.saveButton.Size = new System.Drawing.Size(118, 36); this.saveButton.TabIndex = 0; this.saveButton.Text = "Αποθήκευση"; this.saveButton.Type = MaterialSkin2DotNet.Controls.MaterialButton.MaterialButtonType.Contained; this.saveButton.UseAccentColor = false; this.saveButton.UseVisualStyleBackColor = true; this.saveButton.Click += new System.EventHandler(this.saveButton_Click); // // panel1 // this.panel1.Controls.Add(this.addSubjectButton); this.panel1.Controls.Add(this.subjectsLabel); this.panel1.Controls.Add(this.subjectsListBox); this.panel1.Controls.Add(this.teachersDGV); this.panel1.Controls.Add(this.descriptionLabel); this.panel1.Controls.Add(this.descriptionMultiLineTextBox); this.panel1.Controls.Add(this.nameTextBox); this.panel1.Dock = System.Windows.Forms.DockStyle.Fill; this.panel1.Location = new System.Drawing.Point(3, 3); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(451, 659); this.panel1.TabIndex = 0; // // addSubjectButton // this.addSubjectButton.Depth = 0; this.addSubjectButton.Icon = global::ElearningApp.Properties.Resources.icons8_add_24; this.addSubjectButton.Location = new System.Drawing.Point(336, 460); this.addSubjectButton.MouseState = MaterialSkin2DotNet.MouseState.HOVER; this.addSubjectButton.Name = "addSubjectButton"; this.addSubjectButton.Size = new System.Drawing.Size(56, 56); this.addSubjectButton.TabIndex = 6; this.addSubjectButton.Text = "materialFloatingActionButton1"; this.addSubjectButton.UseVisualStyleBackColor = true; this.addSubjectButton.Click += new System.EventHandler(this.addSubjectButton_Click); // // subjectsLabel // this.subjectsLabel.AutoSize = true; this.subjectsLabel.Depth = 0; this.subjectsLabel.Font = new System.Drawing.Font("Roboto", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); this.subjectsLabel.Location = new System.Drawing.Point(56, 438); this.subjectsLabel.MouseState = MaterialSkin2DotNet.MouseState.HOVER; this.subjectsLabel.Name = "subjectsLabel"; this.subjectsLabel.Size = new System.Drawing.Size(72, 19); this.subjectsLabel.TabIndex = 5; this.subjectsLabel.Text = "Καφάλαια"; // // subjectsListBox // this.subjectsListBox.BackColor = System.Drawing.Color.White; this.subjectsListBox.BorderColor = System.Drawing.Color.LightGray; this.subjectsListBox.Depth = 0; this.subjectsListBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); this.subjectsListBox.Location = new System.Drawing.Point(56, 460); this.subjectsListBox.MouseState = MaterialSkin2DotNet.MouseState.HOVER; this.subjectsListBox.Name = "subjectsListBox"; this.subjectsListBox.SelectedIndex = -1; this.subjectsListBox.SelectedItem = null; this.subjectsListBox.Size = new System.Drawing.Size(255, 155); this.subjectsListBox.TabIndex = 4; // // teachersDGV // this.teachersDGV.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.teachersDGV.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.TeacherName}); this.teachersDGV.Location = new System.Drawing.Point(56, 109); this.teachersDGV.Name = "teachersDGV"; this.teachersDGV.RowHeadersVisible = false; this.teachersDGV.RowTemplate.Height = 25; this.teachersDGV.Size = new System.Drawing.Size(336, 150); this.teachersDGV.TabIndex = 3; // // TeacherName // this.TeacherName.AutoSizeMode = System.Windows.Forms.DataGridViewAutoSizeColumnMode.Fill; this.TeacherName.HeaderText = "Όνομα Καθηγητή"; this.TeacherName.Name = "TeacherName"; // // descriptionLabel // this.descriptionLabel.AutoSize = true; this.descriptionLabel.Depth = 0; this.descriptionLabel.Font = new System.Drawing.Font("Roboto", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); this.descriptionLabel.Location = new System.Drawing.Point(56, 277); this.descriptionLabel.MouseState = MaterialSkin2DotNet.MouseState.HOVER; this.descriptionLabel.Name = "descriptionLabel"; this.descriptionLabel.Size = new System.Drawing.Size(165, 19); this.descriptionLabel.TabIndex = 2; this.descriptionLabel.Text = "Περιγραφή μαθήματος"; // // descriptionMultiLineTextBox // this.descriptionMultiLineTextBox.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(255))))); this.descriptionMultiLineTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None; this.descriptionMultiLineTextBox.Depth = 0; this.descriptionMultiLineTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); this.descriptionMultiLineTextBox.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(222)))), ((int)(((byte)(0)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); this.descriptionMultiLineTextBox.Location = new System.Drawing.Point(56, 299); this.descriptionMultiLineTextBox.MouseState = MaterialSkin2DotNet.MouseState.HOVER; this.descriptionMultiLineTextBox.Name = "descriptionMultiLineTextBox"; this.descriptionMultiLineTextBox.Size = new System.Drawing.Size(336, 96); this.descriptionMultiLineTextBox.TabIndex = 1; this.descriptionMultiLineTextBox.Text = ""; // // nameTextBox // this.nameTextBox.AnimateReadOnly = false; this.nameTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None; this.nameTextBox.Depth = 0; this.nameTextBox.Font = new System.Drawing.Font("Roboto", 16F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Pixel); this.nameTextBox.Hint = "Τίτλος μαθήματος"; this.nameTextBox.LeadingIcon = null; this.nameTextBox.Location = new System.Drawing.Point(56, 40); this.nameTextBox.MaxLength = 50; this.nameTextBox.MouseState = MaterialSkin2DotNet.MouseState.OUT; this.nameTextBox.Multiline = false; this.nameTextBox.Name = "nameTextBox"; this.nameTextBox.Size = new System.Drawing.Size(336, 50); this.nameTextBox.TabIndex = 0; this.nameTextBox.Text = ""; this.nameTextBox.TrailingIcon = null; // // AddEditCourseView // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(463, 784); this.Controls.Add(this.tableLayoutPanel1); this.Name = "AddEditCourseView"; this.Text = "CreateCourseView"; this.tableLayoutPanel1.ResumeLayout(false); this.panel2.ResumeLayout(false); this.panel2.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.teachersDGV)).EndInit(); this.ResumeLayout(false); } #endregion private TableLayoutPanel tableLayoutPanel1; private Panel panel2; private Panel panel1; private MaterialSkin2DotNet.Controls.MaterialButton saveButton; private MaterialSkin2DotNet.Controls.MaterialTextBox nameTextBox; private MaterialSkin2DotNet.Controls.MaterialLabel descriptionLabel; private MaterialSkin2DotNet.Controls.MaterialMultiLineTextBox descriptionMultiLineTextBox; private DataGridView teachersDGV; private DataGridViewTextBoxColumn TeacherName; private MaterialSkin2DotNet.Controls.MaterialFloatingActionButton addSubjectButton; private MaterialSkin2DotNet.Controls.MaterialLabel subjectsLabel; private MaterialSkin2DotNet.Controls.MaterialListBox subjectsListBox; } }
55.309917
177
0.643482
[ "MIT" ]
babis200/ElearningApp
ElearningApp/AddEditCourseView.Designer.cs
13,451
C#
/* This is free and unencumbered software released into the public domain. */ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyTitle("Conreality SDK for .NET")] [assembly: AssemblyDescription("Conreality Software Development Kit (SDK) for .NET")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Conreality.org")] [assembly: AssemblyProduct("Conreality")] [assembly: AssemblyCopyright("Public Domain")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: Guid("76b8e74c-ed39-464b-b340-c29cf3a323d9")] [assembly: CLSCompliant(true)] [assembly: AssemblyVersion("0.0.0.0")] [assembly: AssemblyFileVersion("0.0.0.0")] [assembly: InternalsVisibleTo("Conreality.Test")]
33.208333
85
0.772898
[ "Unlicense" ]
conreality/conreality.net
src/Conreality/Properties/AssemblyInfo.cs
797
C#
using System; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Ubiquity.NET.CSemVer; namespace CSemVer.Build.Tasks { public class CreateVersionInfo : Task { [Required] public string BuildMajor { get; set; } [Required] public string BuildMinor { get; set; } [Required] public string BuildPatch { get; set; } public string PreReleaseName { get; set; } public string PreReleaseNumber { get; set; } public string PreReleaseFix { get; set; } public string CiBuildName { get; set; } public string CiBuildIndex { get; set; } public string BuildMeta { get; set; } [Output] public string CSemVer { get; set; } [Output] public string ShortCSemVer { get; set; } [Output] public ushort FileVersionMajor { get; set; } [Output] public ushort FileVersionMinor { get; set; } [Output] public ushort FileVersionBuild { get; set; } [Output] public ushort FileVersionRevision { get; set; } public override bool Execute( ) { var preReleaseVersion = new PrereleaseVersion( PreReleaseName , string.IsNullOrWhiteSpace( PreReleaseNumber ) ? 0 : Convert.ToInt32( PreReleaseNumber ) , string.IsNullOrWhiteSpace( PreReleaseFix ) ? 0 : Convert.ToInt32( PreReleaseFix ) , CiBuildName , CiBuildIndex ); var fullVersion = new ConstrainedSemanticVersion( Convert.ToInt32( BuildMajor ) , Convert.ToInt32( BuildMinor ) , Convert.ToInt32( BuildPatch ) , preReleaseVersion , BuildMeta ); CSemVer = fullVersion.ToString( ); ShortCSemVer = fullVersion.ToString( false, true ); FileVersionMajor = ( ushort )fullVersion.FileVersion.Major; FileVersionMinor = ( ushort )fullVersion.FileVersion.Minor; FileVersionBuild = ( ushort )fullVersion.FileVersion.Build; FileVersionRevision = ( ushort )fullVersion.FileVersion.Revision; return true; } } }
34.294872
146
0.495701
[ "MIT" ]
UbiquityDotNET/CSemVer.GitBuild
src/CSemVer.Build.Tasks/CreateVersionInfo.cs
2,675
C#
/* * MIT License * * Copyright (c) 2017 Michael VanOverbeek and ShiftOS devs * * 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. */ //------------------------------------------------------------------------------ // <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 ShiftOS.Server.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ShiftOS.Server.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to &lt;!DOCTYPE html&gt; ///&lt;html lang=&quot;en&quot; dir=&quot;ltr&quot;&gt; /// &lt;head&gt; /// &lt;title&gt;ShiftOS Multi-User Domain &amp;bull; Admin Panel&lt;/title&gt; /// &lt;meta charset=&quot;UTF-8&quot;&gt; /// &lt;link rel=&quot;stylesheet&quot; href=&quot;http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css&quot;/&gt; /// &lt;script src=&quot;http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js&quot;&gt;&lt;/script&gt; /// /// &lt;/head&gt; /// &lt;body&gt; /// &lt;nav class=&quot;navbar navbar-inverse navbar-fixed-top&quot;&gt; /// &lt;div class=&quot;container&quot;&gt; /// &lt;a class=&quot;navbar-brand&quot; href=&quot;/&quot;&gt;MUD Admin Panel&lt;/a&gt; /// &lt;ul [rest of string was truncated]&quot;;. /// </summary> internal static string Home { get { return ResourceManager.GetString("Home", resourceCulture); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconArtpad { get { object obj = ResourceManager.GetObject("iconArtpad", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconAudioPlayer { get { object obj = ResourceManager.GetObject("iconAudioPlayer", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconBitnoteDigger { get { object obj = ResourceManager.GetObject("iconBitnoteDigger", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconBitnoteWallet { get { object obj = ResourceManager.GetObject("iconBitnoteWallet", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconCalculator { get { object obj = ResourceManager.GetObject("iconCalculator", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconClock { get { object obj = ResourceManager.GetObject("iconClock", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconColourPicker_fw { get { object obj = ResourceManager.GetObject("iconColourPicker_fw", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconDodge { get { object obj = ResourceManager.GetObject("iconDodge", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconDownloader { get { object obj = ResourceManager.GetObject("iconDownloader", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconFileOpener_fw { get { object obj = ResourceManager.GetObject("iconFileOpener_fw", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconFileSaver_fw { get { object obj = ResourceManager.GetObject("iconFileSaver_fw", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconFileSkimmer { get { object obj = ResourceManager.GetObject("iconFileSkimmer", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconfloodgate { get { object obj = ResourceManager.GetObject("iconfloodgate", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap icongraphicpicker { get { object obj = ResourceManager.GetObject("icongraphicpicker", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconIconManager { get { object obj = ResourceManager.GetObject("iconIconManager", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconInfoBox_fw { get { object obj = ResourceManager.GetObject("iconInfoBox_fw", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconKnowledgeInput { get { object obj = ResourceManager.GetObject("iconKnowledgeInput", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconmaze { get { object obj = ResourceManager.GetObject("iconmaze", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconNameChanger { get { object obj = ResourceManager.GetObject("iconNameChanger", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconoctocat { get { object obj = ResourceManager.GetObject("iconoctocat", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconorcwrite { get { object obj = ResourceManager.GetObject("iconorcwrite", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconPong { get { object obj = ResourceManager.GetObject("iconPong", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconShifter { get { object obj = ResourceManager.GetObject("iconShifter", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconShiftnet { get { object obj = ResourceManager.GetObject("iconShiftnet", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconShiftorium { get { object obj = ResourceManager.GetObject("iconShiftorium", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconshutdown { get { object obj = ResourceManager.GetObject("iconshutdown", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconSkinLoader { get { object obj = ResourceManager.GetObject("iconSkinLoader", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconSkinShifter { get { object obj = ResourceManager.GetObject("iconSkinShifter", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconSnakey { get { object obj = ResourceManager.GetObject("iconSnakey", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconSysinfo { get { object obj = ResourceManager.GetObject("iconSysinfo", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconTerminal { get { object obj = ResourceManager.GetObject("iconTerminal", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconTextPad { get { object obj = ResourceManager.GetObject("iconTextPad", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconunitytoggle { get { object obj = ResourceManager.GetObject("iconunitytoggle", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconVideoPlayer { get { object obj = ResourceManager.GetObject("iconVideoPlayer", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconvirusscanner { get { object obj = ResourceManager.GetObject("iconvirusscanner", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized resource of type System.Drawing.Bitmap. /// </summary> internal static System.Drawing.Bitmap iconWebBrowser { get { object obj = ResourceManager.GetObject("iconWebBrowser", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } /// <summary> /// Looks up a localized string similar to &lt;!DOCTYPE html&gt; ///&lt;html lang=&quot;en&quot; dir=&quot;ltr&gt; /// &lt;head&gt; /// &lt;title&gt;Multi-User Domain &amp;bull; Administration Panel - Page not found.&lt;/title&gt; /// &lt;meta charset=&quot;UTF-8&quot;&gt; /// &lt;/head&gt; /// &lt;body&gt; /// &lt;h1&gt;This page wasn&apos;t found.&lt;/h1&gt; /// &lt;p&gt;We couldn&apos;t find this page...&lt;/p&gt; /// &lt;/body&gt; ///&lt;/html&gt; ///. /// </summary> internal static string NotFound { get { return ResourceManager.GetString("NotFound", resourceCulture); } } } }
39.830612
180
0.55941
[ "MIT" ]
Gamer-Gaming/shiftos
ShiftOS.Server/Properties/Resources.Designer.cs
19,517
C#
 using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.WindowsAzure.Storage.Table; using Orleans; using Orleans.AzureUtils; using Orleans.Runtime; using Orleans.Runtime.Configuration; using Orleans.ServiceBus.Providers; using Orleans.Streams; using Orleans.TestingHost; using Orleans.TestingHost.Utils; using Tester; using Tester.TestStreamProviders.EventHub; using UnitTests.GrainInterfaces; using UnitTests.Tester; using Xunit; namespace UnitTests.StreamingTests { public class EHStreamPerPartitionTests : OrleansTestingBase, IClassFixture<EHStreamPerPartitionTests.Fixture> { private const string StreamProviderName = "EHStreamPerPartition"; private const string EHPath = "ehorleanstest"; private const string EHConsumerGroup = "orleansnightly"; private const string EHCheckpointTable = "ehcheckpoint"; private static readonly string CheckpointNamespace = Guid.NewGuid().ToString(); private static readonly EventHubSettings EventHubConfig = new EventHubSettings(StorageTestConstants.EventHubConnectionString, EHConsumerGroup, EHPath); private static readonly EventHubStreamProviderConfig ProviderConfig = new EventHubStreamProviderConfig(StreamProviderName); private static readonly EventHubCheckpointerSettings CheckpointerSettings = new EventHubCheckpointerSettings(StorageTestConstants.DataConnectionString, EHCheckpointTable, CheckpointNamespace, TimeSpan.FromSeconds(1)); private class Fixture : BaseTestClusterFixture { protected override TestCluster CreateTestCluster() { var options = new TestClusterOptions(2); // register stream provider options.ClusterConfiguration.AddMemoryStorageProvider("PubSubStore"); options.ClusterConfiguration.Globals.RegisterStreamProvider<StreamPerPartitionEventHubStreamProvider>(StreamProviderName, BuildProviderSettings()); options.ClientConfiguration.RegisterStreamProvider<EventHubStreamProvider>(StreamProviderName, BuildProviderSettings()); return new TestCluster(options); } public override void Dispose() { base.Dispose(); var dataManager = new AzureTableDataManager<TableEntity>(CheckpointerSettings.TableName, CheckpointerSettings.DataConnectionString); dataManager.InitTableAsync().Wait(); dataManager.ClearTableAsync().Wait(); } private static Dictionary<string, string> BuildProviderSettings() { var settings = new Dictionary<string, string>(); // get initial settings from configs ProviderConfig.WriteProperties(settings); EventHubConfig.WriteProperties(settings); CheckpointerSettings.WriteProperties(settings); // add queue balancer setting settings.Add(PersistentStreamProviderConfig.QUEUE_BALANCER_TYPE, StreamQueueBalancerType.StaticClusterConfigDeploymentBalancer.ToString()); return settings; } } [Fact, TestCategory("EventHub"), TestCategory("Streaming")] public async Task EH100StreamsTo4PartitionStreamsTest() { logger.Info("************************ EH100StreamsTo4PartitionStreamsTest *********************************"); int streamCount = 100; int eventsInStream = 10; int partitionCount = 4; List<ISampleStreaming_ConsumerGrain> consumers = new List<ISampleStreaming_ConsumerGrain>(partitionCount); for (int i = 0; i < partitionCount; i++) { consumers.Add(GrainClient.GrainFactory.GetGrain<ISampleStreaming_ConsumerGrain>(Guid.NewGuid())); } // subscribe to each partition List<Task> becomeConsumersTasks = consumers .Select( (consumer, i) => consumer.BecomeConsumer( StreamPerPartitionEventHubStreamProvider.GetPartitionGuid(i.ToString()), null, StreamProviderName)) .ToList(); await Task.WhenAll(becomeConsumersTasks); await GenerateEvents(streamCount, eventsInStream); await TestingUtils.WaitUntilAsync(assertIsTrue => CheckCounters(consumers, streamCount * eventsInStream, assertIsTrue), TimeSpan.FromSeconds(30)); } private async Task GenerateEvents(int streamCount, int eventsInStream) { IStreamProvider streamProvider = GrainClient.GetStreamProvider(StreamProviderName); IAsyncStream<int>[] producers = Enumerable.Range(0, streamCount) .Select(i => streamProvider.GetStream<int>(Guid.NewGuid(), null)) .ToArray(); for (int i = 0; i < eventsInStream; i++) { // send event on each stream for (int j = 0; j < streamCount; j++) { await producers[j].OnNextAsync(i); } } } private async Task<bool> CheckCounters(List<ISampleStreaming_ConsumerGrain> consumers, int totalEventCount, bool assertIsTrue) { List<Task<int>> becomeConsumersTasks = consumers .Select((consumer, i) => consumer.GetNumberConsumed()) .ToList(); int[] counts = await Task.WhenAll(becomeConsumersTasks); if (assertIsTrue) { // one stream per queue Assert.Equal(totalEventCount, counts.Sum()); } else if (totalEventCount != counts.Sum()) { return false; } return true; } } }
42.271429
166
0.643799
[ "MIT" ]
JingqiaoFu/orleans
test/Tester/StreamingTests/EHStreamPerPartitionTests.cs
5,920
C#
/* * API Doctor * Copyright (c) Microsoft Corporation * All rights reserved. * * MIT License * * 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. */ namespace ApiDoctor.Validation { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using ApiDoctor.Validation.Error; using ApiDoctor.Validation.TableSpec; using ApiDoctor.Validation.OData.Transformation; using Tags; using MarkdownDeep; using Newtonsoft.Json; using System.Threading.Tasks; using ApiDoctor.Validation.OData; using Newtonsoft.Json.Linq; /// <summary> /// A documentation file that may contain one more resources or API methods /// </summary> public partial class DocFile { private const string PageAnnotationType = "#page.annotation"; private readonly List<ResourceDefinition> resources = new List<ResourceDefinition>(); private readonly List<MethodDefinition> requests = new List<MethodDefinition>(); private readonly List<ExampleDefinition> examples = new List<ExampleDefinition>(); private readonly List<SamplesDefinition> samples = new List<SamplesDefinition>(); private readonly List<EnumerationDefinition> enums = new List<EnumerationDefinition>(); private readonly List<string> bookmarks = new List<string>(); protected bool HasScanRun; protected string BasePath; #region Properties /// <summary> /// Friendly name of the file /// </summary> public string DisplayName { get; protected set; } /// <summary> /// Path to the file on disk /// </summary> public string FullPath { get; protected set; } ///// <summary> ///// HTML-rendered version of the markdown source (for displaying). This content is not suitable for publishing. ///// </summary> //public string HtmlContent { get; protected set; } /// <summary> /// Contains information on the headers and content blocks found in this document. /// </summary> public List<string> ContentOutline { get; set; } public ResourceDefinition[] Resources { get { return this.resources.ToArray(); } } public MethodDefinition[] Requests { get { return this.requests.ToArray(); } } public ExampleDefinition[] Examples { get { return this.examples.ToArray(); } } public SamplesDefinition[] Samples { get { return this.samples.ToArray(); } } public EnumerationDefinition[] Enums { get { return this.enums.ToArray(); } } public AuthScopeDefinition[] AuthScopes { get; protected set; } public ErrorDefinition[] ErrorCodes { get; protected set; } public string[] LinkDestinations { get { if (this.MarkdownLinks == null) { return new string[0]; } var destinations = new List<string>(this.MarkdownLinks.Count); foreach (var link in this.MarkdownLinks) { if (link.Definition == null) { throw new ArgumentException("Link Definition was null. Link text: " + link.Text, nameof(link.Definition)); } destinations.Add(link.Definition.url); } return destinations.ToArray(); } } /// <summary> /// Raw Markdown parsed blocks /// </summary> public Block[] OriginalMarkdownBlocks { get; set; } protected List<ILinkInfo> MarkdownLinks { get; set; } public DocSet Parent { get; protected set; } public PageAnnotation Annotation { get; set; } public bool WriteFixesBackToDisk { get; set; } #endregion #region Constructor protected DocFile() { this.ContentOutline = new List<string>(); this.DocumentHeaders = new List<Config.DocumentHeader>(); } public DocFile(string basePath, string relativePath, DocSet parent) : this() { this.BasePath = basePath; this.FullPath = Path.Combine(basePath, relativePath.Substring(1)); this.DisplayName = relativePath; this.Parent = parent; this.DocumentHeaders = new List<Config.DocumentHeader>(); } #endregion #region Markdown Parsing /// <summary> /// Populate this object based on input markdown data /// </summary> /// <param name="inputMarkdown"></param> protected void TransformMarkdownIntoBlocksAndLinks(string inputMarkdown, string tags) { Markdown md = new Markdown { SafeMode = false, ExtraMode = true, AutoHeadingIDs = true, NewWindowForExternalLinks = true }; var htmlContent = md.Transform(inputMarkdown); //this.HtmlContent = PostProcessHtmlTags(htmlContent, tags); this.OriginalMarkdownBlocks = md.Blocks; this.MarkdownLinks = new List<ILinkInfo>(md.FoundLinks); this.bookmarks.AddRange(md.HeaderIdsInDocument); } protected virtual string PostProcessHtmlTags(string inputHtml, string tags) { TagProcessor tagProcessor = new TagProcessor(tags, this.Parent?.SourceFolderPath); var fileInfo = new FileInfo(this.FullPath); return tagProcessor.PostProcess(inputHtml, fileInfo, null); } protected virtual string GetContentsOfFile(string tags) { // Preprocess file content FileInfo docFile = new FileInfo(this.FullPath); TagProcessor tagProcessor = new TagProcessor(tags, Parent.SourceFolderPath); return tagProcessor.Preprocess(docFile); } /// <summary> /// Read the contents of the file into blocks and generate any resource or method definitions from the contents /// </summary> public virtual bool Scan(string tags, IssueLogger issues) { this.HasScanRun = true; List<ValidationError> detectedErrors = new List<ValidationError>(); try { string fileContents = this.ReadAndPreprocessFileContents(tags, issues); this.TransformMarkdownIntoBlocksAndLinks(fileContents, tags); } catch (IOException ioex) { issues.Error(ValidationErrorCode.ErrorOpeningFile, $"Error reading file contents.", ioex); return false; } catch (Exception ex) { issues.Error(ValidationErrorCode.ErrorReadingFile, $"Error reading file contents.", ex); return false; } return this.ParseMarkdownBlocks(issues); } /// <summary> /// Read the contents of the file and perform all preprocessing activities that transform the input into the final markdown-only data. /// </summary> /// <param name="tags"></param> /// <returns></returns> public string ReadAndPreprocessFileContents(string tags, IssueLogger issues) { try { string fileContents = this.GetContentsOfFile(tags); fileContents = this.ParseAndRemoveYamlFrontMatter(fileContents, issues); return fileContents; } catch (Exception ex) { Debug.WriteLine($"An error occuring reading and processing the contents of this file: {this.FullPath}. {ex.Message}."); throw; } } /// <summary> /// Parses the file contents and removes yaml front matter from the markdown. /// </summary> /// <param name="contents">Contents.</param> private string ParseAndRemoveYamlFrontMatter(string contents, IssueLogger issues) { const string YamlFrontMatterHeader = "---"; using (StringReader reader = new StringReader(contents)) { string currentLine = reader.ReadLine(); System.Text.StringBuilder frontMatter = new System.Text.StringBuilder(); YamlFrontMatterDetectionState currentState = YamlFrontMatterDetectionState.NotDetected; while (currentLine != null && currentState != YamlFrontMatterDetectionState.SecondTokenFound) { string trimmedCurrentLine = currentLine.Trim(); switch (currentState) { case YamlFrontMatterDetectionState.NotDetected: if (!string.IsNullOrWhiteSpace(trimmedCurrentLine) && trimmedCurrentLine != YamlFrontMatterHeader) { var requiredYamlHeaders = DocSet.SchemaConfig.RequiredYamlHeaders; if (requiredYamlHeaders.Any()) { issues.Error(ValidationErrorCode.RequiredYamlHeaderMissing, $"Missing required YAML headers: {requiredYamlHeaders.ComponentsJoinedByString(", ")}"); } // This file doesn't have YAML front matter, so we just return the full contents of the file return contents; } else if (trimmedCurrentLine == YamlFrontMatterHeader) { currentState = YamlFrontMatterDetectionState.FirstTokenFound; } break; case YamlFrontMatterDetectionState.FirstTokenFound: if (trimmedCurrentLine == YamlFrontMatterHeader) { // Found the end of the YAML front matter, so move to the final state currentState = YamlFrontMatterDetectionState.SecondTokenFound; } else { // Store the YAML data into our header frontMatter.AppendLine(currentLine); } break; case YamlFrontMatterDetectionState.SecondTokenFound: break; } if (currentState != YamlFrontMatterDetectionState.SecondTokenFound) { currentLine = reader.ReadLine(); } } if (currentState == YamlFrontMatterDetectionState.SecondTokenFound) { // Parse YAML metadata ParseYamlMetadata(frontMatter.ToString(), issues); return reader.ReadToEnd(); } else { // Something went wrong along the way, so we just return the full file return contents; } } } private void ParseYamlMetadata(string yamlMetadata, IssueLogger issues) { Dictionary<string, string> dictionary = new Dictionary<string, string>(); string[] items = yamlMetadata.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries); foreach (string item in items) { string[] keyValue = item.Split(':'); dictionary.Add(keyValue[0].Trim(), keyValue[1].Trim()); } List<string> missingHeaders = new List<string>(); foreach (var header in DocSet.SchemaConfig.RequiredYamlHeaders) { string value; if (dictionary.TryGetValue(header, out value)) { if (string.IsNullOrEmpty(value)) { issues.Error(ValidationErrorCode.RequiredYamlHeaderMissing, $"Missing value for YAML header: {header}"); } } else { missingHeaders.Add(header); } } if (missingHeaders.Any()) { issues.Error(ValidationErrorCode.RequiredYamlHeaderMissing, $"Missing required YAML header(s): {missingHeaders.ComponentsJoinedByString(", ")}"); } } private enum YamlFrontMatterDetectionState { NotDetected, FirstTokenFound, SecondTokenFound } private static bool IsHeaderBlock(Block block, int maxDepth = 2) { if (null == block) { return false; } var blockType = block.BlockType; if (maxDepth >= 1 && blockType == BlockType.h1) return true; if (maxDepth >= 2 && blockType == BlockType.h2) return true; if (maxDepth >= 3 && blockType == BlockType.h3) return true; if (maxDepth >= 4 && blockType == BlockType.h4) return true; if (maxDepth >= 5 && blockType == BlockType.h5) return true; if (maxDepth >= 6 && blockType == BlockType.h6) return true; return false; } protected string PreviewOfBlockContent(Block block) { if (block == null) return string.Empty; if (block.Content == null) return string.Empty; const int previewLength = 35; string contentPreview = block.Content.Length > previewLength ? block.Content.Substring(0, previewLength) : block.Content; contentPreview = contentPreview.Replace('\n', ' ').Replace('\r', ' '); return contentPreview; } protected Config.DocumentHeader CreateHeaderFromBlock(Block block) { var header = new Config.DocumentHeader(); switch (block.BlockType) { case BlockType.h1: header.Level = 1; break; case BlockType.h2: header.Level = 2; break; case BlockType.h3: header.Level = 3; break; case BlockType.h4: header.Level = 4; break; case BlockType.h5: header.Level = 5; break; case BlockType.h6: header.Level = 6; break; default: throw new InvalidOperationException("block wasn't a header!"); } header.Title = block.Content; return header; } /// <summary> /// Headers found in the markdown input (#, h1, etc) /// </summary> public List<Config.DocumentHeader> DocumentHeaders { get; set; } /// <summary> /// Convert blocks of text found inside the markdown file into things we know how to work /// with (methods, resources, examples, etc). /// </summary> /// <param name="errors"></param> /// <returns></returns> protected bool ParseMarkdownBlocks(IssueLogger issues) { string methodTitle = null; string methodDescription = null; Block previousHeaderBlock = null; List<object> foundElements = new List<object>(); Stack<Config.DocumentHeader> headerStack = new Stack<Config.DocumentHeader>(); for (int i = 0; i < this.OriginalMarkdownBlocks.Length; i++) { var block = this.OriginalMarkdownBlocks[i]; this.ContentOutline.Add(string.Format("{0} - {1}", block.BlockType, this.PreviewOfBlockContent(block))); // Capture GitHub Flavored Markdown Bookmarks if (IsHeaderBlock(block, 6)) { this.AddHeaderToHierarchy(headerStack, block); } // Capture h1 and/or p element to be used as the title and description for items on this page if (IsHeaderBlock(block)) { methodTitle = block.Content; methodDescription = null; // Clear this because we don't want new title + old description issues.Message($"Found title: {methodTitle}"); } else if (block.BlockType == BlockType.p) { if (null == previousHeaderBlock) { issues.Warning(ValidationErrorCode.MissingHeaderBlock, $"Paragraph text found before a valid header: {block.Content.Substring(0, Math.Min(block.Content.Length, 20))}..."); } else if (IsHeaderBlock(previousHeaderBlock)) { methodDescription = block.Content; issues.Message($"Found description: {methodDescription}"); } } else if (block.BlockType == BlockType.html) { // If the next block is a codeblock we've found a metadata + codeblock pair Block nextBlock = null; if (i + 1 < this.OriginalMarkdownBlocks.Length) { nextBlock = this.OriginalMarkdownBlocks[i + 1]; } if (null != nextBlock && nextBlock.BlockType == BlockType.codeblock) { // html + codeblock = likely request or response or resource List<ItemDefinition> definitions = this.ParseCodeBlock(block, nextBlock, issues); if (definitions != null && definitions.Any()) { foreach (var definition in definitions) { issues.Message($"Found code block: {definition.Title} [{definition.GetType().Name}]"); definition.Title = methodTitle; definition.Description = methodDescription; if (!foundElements.Contains(definition)) { foundElements.Add(definition); } } } } // See if this is the page-level annotation try { this.Annotation = this.ParsePageAnnotation(block); if (this.Annotation != null) { if (this.Annotation.Suppressions != null) { issues.AddSuppressions(this.Annotation.Suppressions); } if (string.IsNullOrEmpty(this.Annotation.Title)) { this.Annotation.Title = this.OriginalMarkdownBlocks.FirstOrDefault(b => IsHeaderBlock(b, 1))?.Content; } } } catch (JsonReaderException readerEx) { issues.Warning(ValidationErrorCode.JsonParserException, $"Unable to parse page annotation JSON: {readerEx}"); } catch (Exception ex) { issues.Warning(ValidationErrorCode.AnnotationParserException, $"Unable to parse annotation: {ex}"); } } else if (block.BlockType == BlockType.table_spec) { try { Block blockBeforeTable = (i - 1 >= 0) ? this.OriginalMarkdownBlocks[i - 1] : null; if (null == blockBeforeTable) continue; var table = this.Parent.TableParser.ParseTableSpec(block, headerStack, issues); issues.Message($"Found table: {table.Type}. Rows:\r\n{table.Rows.Select(r => JsonConvert.SerializeObject(r, Formatting.Indented)).ComponentsJoinedByString(" ,\r\n")}"); foundElements.Add(table); } catch (Exception ex) { issues.Error(ValidationErrorCode.MarkdownParserError, $"Failed to parse table.", ex); } } if (block.IsHeaderBlock()) { previousHeaderBlock = block; } } this.PostProcessFoundElements(foundElements, issues); return issues.Issues.All(x => !x.IsError); } /// <summary> /// Checks the document for outline errors compared to any required document structure. /// </summary> /// <returns></returns> public void CheckDocumentStructure(IssueLogger issues) { List<ValidationError> errors = new List<ValidationError>(); if (this.Parent.DocumentStructure != null) { ValidateDocumentStructure(this.Parent.DocumentStructure.AllowedHeaders, this.DocumentHeaders, issues); } } private static bool ContainsMatchingDocumentHeader(Config.DocumentHeader expectedHeader, IReadOnlyList<Config.DocumentHeader> collection) { return collection.Any(h => h.Matches(expectedHeader)); } private void ValidateDocumentStructure(IReadOnlyList<Config.DocumentHeader> expectedHeaders, IReadOnlyList<Config.DocumentHeader> foundHeaders, IssueLogger issues) { int expectedIndex = 0; int foundIndex = 0; while (expectedIndex < expectedHeaders.Count && foundIndex < foundHeaders.Count) { var expected = expectedHeaders[expectedIndex]; var found = foundHeaders[foundIndex]; if (expected.Matches(found)) { ValidateDocumentStructure(expected.ChildHeaders, found.ChildHeaders, issues); // Found an expected header, keep going! expectedIndex++; foundIndex++; continue; } if (!ContainsMatchingDocumentHeader(found, expectedHeaders)) { // This is an additional header that isn't in the expected header collection issues.Warning(ValidationErrorCode.ExtraDocumentHeaderFound, $"A extra document header was found: {found.Title}"); ValidateDocumentStructure(new Config.DocumentHeader[0], found.ChildHeaders, issues); foundIndex++; continue; } else { // If the current expected header is optional, we can move past it if (!expected.Required) { expectedIndex++; continue; } bool expectedMatchesInFoundHeaders = ContainsMatchingDocumentHeader(expected, foundHeaders); if (expectedMatchesInFoundHeaders) { // This header exists, but is in the wrong position issues.Warning(ValidationErrorCode.DocumentHeaderInWrongPosition, $"An expected document header was found in the wrong position: {found.Title}"); foundIndex++; continue; } else if (!expectedMatchesInFoundHeaders && expected.Required) { // Missing a required header! issues.Error(ValidationErrorCode.RequiredDocumentHeaderMissing, $"A required document header is missing from the document: {expected.Title}"); expectedIndex++; } else { // Expected wasn't found and is optional, that's fine. expectedIndex++; continue; } } } for (int i = foundIndex; i < foundHeaders.Count; i++) { issues.Warning(ValidationErrorCode.ExtraDocumentHeaderFound, $"A extra document header was found: {foundHeaders[i].Title}"); } for (int i = expectedIndex; i < expectedHeaders.Count; i++) { if (expectedHeaders[i].Required) { issues.Error(ValidationErrorCode.RequiredDocumentHeaderMissing, $"A required document header is missing from the document: {expectedHeaders[i].Title}"); } } } private void AddHeaderToHierarchy(Stack<Config.DocumentHeader> headerStack, Block block) { var header = CreateHeaderFromBlock(block); if (header.Level == 1 || headerStack.Count == 0) { DocumentHeaders.Add(header); headerStack.Clear(); headerStack.Push(header); } else { var parentHeader = headerStack.Peek(); if (null != parentHeader && parentHeader.Level < header.Level) { // This is a child of that previous level, so we add it and push parentHeader.ChildHeaders.Add(header); headerStack.Push(header); } else if (null != parentHeader && parentHeader.Level >= header.Level) { // We need to pop back and find the right parent for this higher level while (headerStack.Count > 0 && headerStack.Peek().Level >= header.Level) { headerStack.Pop(); } if (headerStack.Count > 0) { parentHeader = headerStack.Peek(); parentHeader.ChildHeaders.Add(header); } headerStack.Push(header); } else { throw new InvalidOperationException("Something went wrong in the outline creation"); } } } /// <summary> /// Remove <!-- and --> from the content string /// </summary> /// <param name="content"></param> /// <returns></returns> private static string StripHtmlCommentTags(string content) { const string startComment = "<!--"; const string endComment = "-->"; int index = content.IndexOf(startComment, StringComparison.Ordinal); if (index >= 0) content = content.Substring(index + startComment.Length); index = content.IndexOf(endComment, StringComparison.Ordinal); if (index >= 0) content = content.Substring(0, index); return content; } private PageAnnotation ParsePageAnnotation(Block block) { var commentText = StripHtmlCommentTags(block.Content).Trim(); if (!commentText.StartsWith("{")) return null; var response = JsonConvert.DeserializeObject<PageAnnotation>(commentText); if (null != response && null != response.Type && response.Type.Equals(PageAnnotationType, StringComparison.OrdinalIgnoreCase)) return response; return null; } private static Dictionary<char, string> BookmarkReplacmentMap = new Dictionary<char, string> { [' '] = "-", ['.'] = "", [','] = "", [':'] = "" }; /// <summary> /// Run post processing on the collection of elements found inside this doc file. /// </summary> private void PostProcessFoundElements(List<object> elements, IssueLogger issues) { /* if FoundMethods == 1 then Attach all tables found in the document to the method. else if FoundMethods > 1 then Table.Type == ErrorCodes - Attach errors to all methods in the file Table.Type == PathParameters - Find request with matching parameters Table.Type == Query String Parameters - Request may not have matching parameters, because query string parameters may not be part of the request Table.Type == Header Parameters - Find request with matching parameters Table.Type == Body Parameters - Find request with matching parameters */ var elementsFoundInDocument = elements as IList<object> ?? elements.ToList(); var foundMethods = elementsFoundInDocument.OfType<MethodDefinition>().ToList(); var foundResources = elementsFoundInDocument.OfType<ResourceDefinition>().ToList(); var foundTables = elementsFoundInDocument.OfType<TableDefinition>().ToList(); var foundEnums = foundTables.Where(t => t.Type == TableBlockType.EnumerationValues).SelectMany(t => t.Rows).Cast<EnumerationDefinition>().ToList(); this.PostProcessAuthScopes(elementsFoundInDocument); PostProcessResources(foundResources, foundTables, issues); this.PostProcessMethods(foundMethods, foundTables, issues); this.PostProcessEnums(foundEnums, foundTables, issues); } private void PostProcessAuthScopes(IList<object> foundElements) { var authScopeTables = (from s in foundElements where s is TableDefinition && ((TableDefinition)s).Type == TableBlockType.AuthScopes select ((TableDefinition)s)); List<AuthScopeDefinition> foundScopes = new List<AuthScopeDefinition>(); foreach (var table in authScopeTables) { foundScopes.AddRange(table.Rows.Cast<AuthScopeDefinition>()); } this.AuthScopes = foundScopes.ToArray(); } private void PostProcessEnums(List<EnumerationDefinition> foundEnums, List<TableDefinition> foundTables, IssueLogger issues) { // add all the enum values this.enums.AddRange(foundEnums.Where(e => !string.IsNullOrEmpty(e.MemberName) && !string.IsNullOrEmpty(e.TypeName))); // find all the property tables // find properties of type string that have a list of `enum`, `values`. see if they match me. foreach (var table in foundTables.Where(t => t.Type == TableBlockType.RequestObjectProperties || t.Type == TableBlockType.ResourcePropertyDescriptions)) { var rows = table.Rows.Cast<ParameterDefinition>(); foreach (var row in rows.Where(r => r.Type?.Type == SimpleDataType.String)) { var rowIssues = issues.For(row.Name); // if more than one word in the description happens to match an enum value... i'm suspicious var possibleEnumCandidates = row.Description.TokenizedWords(); var matches = possibleEnumCandidates?.Intersect(this.enums.Select(e => e.MemberName), StringComparer.OrdinalIgnoreCase).ToList(); if (matches?.Count > 1) { rowIssues.Warning(ValidationErrorCode.Unknown, $"Found potential enums in parameter description declared as a string: " + $"({string.Join(",", matches)}) are in enum {this.enums.First(e => e.MemberName.Equals(matches[0], StringComparison.OrdinalIgnoreCase)).TypeName}"); } } } foreach (var resource in this.resources) { foreach (var param in resource.Parameters.Where(p => p.Type?.Type == SimpleDataType.String)) { var possibleEnums = param.PossibleEnumValues(); if (possibleEnums.Length > 1) { var matches = possibleEnums.Intersect(this.enums.Select(e => e.MemberName), StringComparer.OrdinalIgnoreCase).ToList(); if (matches.Count < possibleEnums.Length) { issues.Warning(ValidationErrorCode.Unknown, $"Found potential enums in resource example that weren't defined in a table:" + $"({string.Join(",", possibleEnums)}) are in resource, but ({string.Join(",", this.enums.Select(e => e.MemberName))}) are in table"); } } } } } private void PostProcessResources(List<ResourceDefinition> foundResources, List<TableDefinition> foundTables, IssueLogger issues) { if (foundResources.Count > 1) { var resourceNames = string.Join(",", foundResources.Select(r => r.Name)); issues.Warning(ValidationErrorCode.ErrorReadingFile, $"Multiple resources found in file, but we only support one per file. '{resourceNames}'. Skipping."); return; } var onlyResource = foundResources.FirstOrDefault(); if (onlyResource != null) { foreach (var table in foundTables) { switch (table.Type) { case TableBlockType.RequestObjectProperties: case TableBlockType.ResourcePropertyDescriptions: case TableBlockType.ResourceNavigationPropertyDescriptions: // Merge information found in the resource property description table with the existing resources if (onlyResource == null) { if (table.Type != TableBlockType.RequestObjectProperties) { // TODO: this isn't exactly right... we want to fail RequestObjectProperties if the doc doesn't describe the resource anywhere else, either. // but that check needs to happen after everything has finished being read. this whole thing should probably be a post-check actually. // like we should aggregate all the object model data centrally, remembering where every bit of info came from, and then validate it all at the end // and throw about any inconsistencies. issues.Warning(ValidationErrorCode.ResourceTypeNotFound, $"Resource not found, but descriptive table(s) are present. Skipping."); } return; } table.UsedIn.Add(onlyResource); MergeParametersIntoCollection( onlyResource.Parameters, table.Rows.Cast<ParameterDefinition>(), issues.For(onlyResource.Name), addMissingParameters: true, expectedInResource: true, resourceToFixUp: this.WriteFixesBackToDisk ? onlyResource as JsonResourceDefinition : null); break; } } // at this point, all parameters should have descriptions from the table. var paramsToRemove = new List<ParameterDefinition>(); foreach (var param in onlyResource.Parameters) { if (string.IsNullOrEmpty(param.Description) && !param.Name.Contains("@")) { if (onlyResource.OriginalMetadata.IsOpenType && onlyResource.OriginalMetadata.OptionalProperties?.Contains(param.Name, StringComparer.OrdinalIgnoreCase) == true) { paramsToRemove.Add(param); } else { issues.Warning(ValidationErrorCode.AdditionalPropertyDetected, $"Property '{param.Name}' found in resource definition for '{onlyResource.Name}', but not described in markdown table."); } } } if (paramsToRemove.Count > 0) { foreach (var param in paramsToRemove) { onlyResource.Parameters.Remove(param); } } } } /// <summary> /// Merges parameter definitions from additionalData into the collection list. Pulls in missing data for existing /// parameters and adds any additional parameters found in the additionalData. /// </summary> /// <param name="collection"></param> /// <param name="additionalData"></param> private void MergeParametersIntoCollection( List<ParameterDefinition> collection, IEnumerable<ParameterDefinition> additionalData, IssueLogger issues, bool addMissingParameters = false, bool expectedInResource = true, JsonResourceDefinition resourceToFixUp = null) { foreach (var param in additionalData) { // See if this parameter already is known var match = collection.SingleOrDefault(x => x.Name == param.Name); if (match != null) { // The parameter was always known, let's merge in additional data. match.AddMissingDetails(param, issues.For(param.Name)); } else if (addMissingParameters) { if (expectedInResource) { // Navigation propeties may not appear in the example text, so don't report and error if (!param.IsNavigatable) { issues.Warning(ValidationErrorCode.AdditionalPropertyDetected, $"Property '{param.Name}' found in markdown table but not in resource definition."); if (resourceToFixUp?.SourceJObject != null) { resourceToFixUp.SourceJObject.Add(param.Name, param.ToExampleJToken()); resourceToFixUp.PatchSourceFile(); Console.WriteLine("Fixed missing property"); } } else { issues.Message($"Navigation property '{param.Name}' found in markdown table but not in resource definition."); } } // The parameter didn't exist in the collection, so let's add it. collection.Add(param); } else if (!param.IsNavigatable && expectedInResource) { // Oops, we didn't find the property in the resource definition issues.Warning(ValidationErrorCode.AdditionalPropertyDetected, $"Property '{param.Name}' found in markdown table but not in resource definition."); } } } private void PostProcessMethods(IEnumerable<MethodDefinition> foundMethods, IEnumerable<TableDefinition> foundTables, IssueLogger issues) { var totalTables = foundTables.Count(); if (totalTables == 0) { return; } var totalMethods = foundMethods.Count(); if (totalMethods == 0) { this.SetFoundTablesForFile(foundTables); } else if (totalMethods == 1) { var onlyMethod = foundMethods.Single(); SetFoundTablesOnMethod(foundTables, onlyMethod, issues); } else { // maybe the methods are really all the same and the dupes are just different examples var distinctMethodNames = foundMethods.Select(m => new Http.HttpParser().ParseHttpRequest(m.Request).Url).Select( url => { var method = url.Substring(url.LastIndexOf('/') + 1); var endIndex = method.IndexOfAny(new[] { '(', '?', '/' }); if (endIndex != -1) { method = method.Substring(0, endIndex); } return method; }).Distinct().Count(); if (distinctMethodNames == 1) { foreach (var method in foundMethods) { SetFoundTablesOnMethod(foundTables, method, issues); } return; } // if there's no more than one of each table, we can assume // they're meant to apply to all the methods. if (foundTables.GroupBy(t => t.Type).All(g => g.Count() <= 1)) { foreach (var method in foundMethods) { SetFoundTablesOnMethod(foundTables, method, issues); } return; } // TODO: Figure out how to map stuff when more than one method exists along with separate tables for each List<ValidationError> innerErrors = new List<ValidationError>(); var unmappedMethods = (from m in foundMethods select m.RequestMetadata.MethodName?.FirstOrDefault()).ComponentsJoinedByString(", "); if (!string.IsNullOrEmpty(unmappedMethods)) { innerErrors.Add(new ValidationMessage("Unmapped methods", unmappedMethods)); } var unmappedTables = (from t in foundTables select string.Format("{0} - {1}", t.Title, t.Type)).ComponentsJoinedByString(", "); if (!string.IsNullOrEmpty(unmappedTables)) { innerErrors.Add(new ValidationMessage("Unmapped tables", unmappedTables)); } var unmappedContentsError = new ValidationWarning(ValidationErrorCode.UnmappedDocumentElements, this.DisplayName, "Unable to map some markdown elements into schema.") { InnerErrors = innerErrors.ToArray(), }; issues.Warning(unmappedContentsError); } } private void SetFoundTablesOnMethod(IEnumerable<TableDefinition> foundTables, MethodDefinition onlyMethod, IssueLogger issues) { var methodName = onlyMethod.RequestMetadata.MethodName?.FirstOrDefault(); foreach (var table in foundTables) { switch (table.Type) { case TableBlockType.Unknown: // Unknown table format, nothing we can do with it. break; case TableBlockType.AuthScopes: // nothing to do on a specific method. handled at the file level break; case TableBlockType.EnumerationValues: // nothing special to do with enums right now. break; case TableBlockType.ErrorCodes: table.UsedIn.Add(onlyMethod); onlyMethod.Errors = table.Rows.Cast<ErrorDefinition>().ToList(); break; case TableBlockType.HttpHeaders: case TableBlockType.PathParameters: case TableBlockType.QueryStringParameters: table.UsedIn.Add(onlyMethod); onlyMethod.Parameters.AddRange(table.Rows.Cast<ParameterDefinition>()); break; case TableBlockType.RequestObjectProperties: table.UsedIn.Add(onlyMethod); MergeParametersIntoCollection(onlyMethod.RequestBodyParameters, table.Rows.Cast<ParameterDefinition>(), issues.For(methodName), addMissingParameters: true, expectedInResource: false); break; default: if (table.UsedIn.Count == 0) { // if the table wasn't used by anything else, we assume it's intended for this method, so we log a warning issues.Warning(ValidationErrorCode.Unknown, $"Table '{table.Title}' of type {table.Type} is not supported for methods '{onlyMethod.RequestMetadata.MethodName?.FirstOrDefault()}' and was ignored."); } break; } } } private void SetFoundTablesForFile(IEnumerable<TableDefinition> foundTables) { // Assume anything we found is a global resource foreach (var table in foundTables) { switch (table.Type) { case TableBlockType.ErrorCodes: this.ErrorCodes = table.Rows.Cast<ErrorDefinition>().ToArray(); break; } } } /// <summary> /// Filters the blocks to just a collection of blocks that may be /// relevent for our purposes /// </summary> /// <returns>The code blocks.</returns> /// <param name="blocks">Blocks.</param> protected static List<Block> FindCodeBlocks(Block[] blocks) { var blockList = new List<Block>(); foreach (var block in blocks) { switch (block.BlockType) { case BlockType.codeblock: case BlockType.html: blockList.Add(block); break; default: break; } } return blockList; } /// <summary> /// Convert an annotation and fenced code block in the documentation into something usable. Adds /// the detected object into one of the internal collections of resources, methods, or examples. /// </summary> public List<ItemDefinition> ParseCodeBlock(Block metadata, Block code, IssueLogger issues) { List<ValidationError> detectedErrors = new List<ValidationError>(); if (metadata.BlockType != BlockType.html) { issues.Error(ValidationErrorCode.MarkdownParserError, "metadata block does not appear to be metadata"); return null; } if (code.BlockType != BlockType.codeblock) { issues.Error(ValidationErrorCode.MarkdownParserError, "code block does not appear to be code"); return null; } var metadataJsonString = StripHtmlCommentTags(metadata.Content); CodeBlockAnnotation annotation = null; try { annotation = CodeBlockAnnotation.ParseMetadata(metadataJsonString, code, this); } catch (Exception ex) { issues.Error(ValidationErrorCode.MarkdownParserError, $"Unable to parse code block metadata.", ex); return null; } switch (annotation.BlockType) { case CodeBlockType.Resource: { ResourceDefinition resource; if (code.CodeLanguage.Equals("json", StringComparison.OrdinalIgnoreCase)) { try { resource = new JsonResourceDefinition(annotation, code.Content, this, issues); } catch (Exception ex) { issues.Error(ValidationErrorCode.MarkdownParserError, $"Unable to parse resource metadata in {annotation.ResourceType}.", ex); return null; } } else { issues.Error(ValidationErrorCode.MarkdownParserError, $"Unsupported resource definition language: {code.CodeLanguage}"); return null; } if (string.IsNullOrEmpty(resource.Name)) { issues.Error(ValidationErrorCode.MarkdownParserError, "Resource definition is missing a name."); return null; } this.resources.Add(resource); return new List<ItemDefinition>(new ItemDefinition[] { resource }); } case CodeBlockType.Request: { var method = MethodDefinition.FromRequest(code.Content, annotation, this, issues.For("RequestBlock")); if (string.IsNullOrEmpty(method.Identifier)) { method.Identifier = string.Format("{0} #{1}", this.DisplayName, this.requests.Count); } this.requests.Add(method); return new List<ItemDefinition>(new ItemDefinition[] { method }); } case CodeBlockType.Response: { var responses = new List<ItemDefinition>(); if (null != annotation.MethodName) { // Look up all the requests mentioned and pair them up foreach (var requestMethodName in annotation.MethodName) { // Look up paired request by name MethodDefinition pairedRequest = (from m in this.requests where m.Identifier == requestMethodName select m).FirstOrDefault(); if (pairedRequest != null) { pairedRequest.AddExpectedResponse(code.Content, annotation); responses.Add(pairedRequest); } else { detectedErrors.Add(new ValidationError(ValidationErrorCode.MarkdownParserError, this.DisplayName, "Unable to locate the corresponding request for response block: {0}. Requests must be defined before a response.", annotation.MethodName)); } } } else if (this.requests.Any()) { // Try to match with a previous request on the page. Will throw if the previous request on the page is already paired MethodDefinition pairedRequest = Enumerable.Last(this.requests); if (pairedRequest != null) { try { pairedRequest.AddExpectedResponse(code.Content, annotation); responses.Add(pairedRequest); } catch (Exception ex) { detectedErrors.Add(new ValidationError(ValidationErrorCode.MarkdownParserError, this.DisplayName, "Unable to pair response with request {0}: {1}.", annotation.MethodName, ex.Message)); } } else { throw new InvalidOperationException(string.Format("Unable to locate the corresponding request for response block: {0}. Requests must be defined before a response.", annotation.MethodName)); } } return responses; } case CodeBlockType.Example: { var example = new ExampleDefinition(annotation, code.Content, this, code.CodeLanguage); this.examples.Add(example); return new List<ItemDefinition>(new ItemDefinition[] { example }); } case CodeBlockType.Samples: { var sample = new SamplesDefinition(annotation, code.Content); this.samples.Add(sample); return new List<ItemDefinition>(new ItemDefinition[] { sample }); } case CodeBlockType.Ignored: { return null; } case CodeBlockType.SimulatedResponse: { var method = Enumerable.Last(this.requests); method.AddSimulatedResponse(code.Content, annotation); return new List<ItemDefinition>(new ItemDefinition[] { method }); } case CodeBlockType.TestParams: { var method = Enumerable.Last(this.requests); method.AddTestParams(code.Content); return new List<ItemDefinition>(new ItemDefinition[] { method }); } default: { issues.Error(ValidationErrorCode.MarkdownParserError, $"Unable to parse metadata block. Possibly an unsupported block type. Line {metadata.LineStart}. Content: {metadata.Content}"); return null; } } } #endregion #region Link Verification public bool ValidateNoBrokenLinks(bool includeWarnings, IssueLogger issues, bool requireFilenameCaseMatch) { string[] files; return this.ValidateNoBrokenLinks(includeWarnings, issues.For(this.DisplayName), out files, requireFilenameCaseMatch); } /// <summary> /// Checks all links detected in the source document to make sure they are valid. /// </summary> /// <param name="includeWarnings"></param> /// <param name="errors">Information about broken links</param> /// <param name="linkedDocFiles"></param> /// <returns>True if all links are valid. Otherwise false</returns> public bool ValidateNoBrokenLinks(bool includeWarnings, IssueLogger issues, out string[] linkedDocFiles, bool requireFilenameCaseMatch) { if (!this.HasScanRun) throw new InvalidOperationException("Cannot validate links until Scan() is called."); List<string> linkedPages = new List<string>(); // If there are no links in this document, just skip the validation. if (this.MarkdownLinks == null) { linkedDocFiles = new string[0]; return true; } foreach (var link in this.MarkdownLinks) { if (null == link.Definition) { // Don't treat TAGS or END markers like links if (!link.Text.ToUpper().Equals("END") && !link.Text.ToUpper().StartsWith("TAGS=")) { issues.Error(ValidationErrorCode.MissingLinkSourceId, $"Link ID '[{link.Text}]' used in document but not defined. Define with '[{link.Text}]: url' or remove square brackets."); } continue; } string relativeFileName; var result = this.VerifyLink(this.FullPath, link.Definition.url, this.BasePath, out relativeFileName, requireFilenameCaseMatch); string suggestion = (relativeFileName != null) ? $"Did you mean: {relativeFileName}" : string.Empty; switch (result) { case LinkValidationResult.ExternalSkipped: if (includeWarnings) issues.Warning(ValidationErrorCode.LinkValidationSkipped, $"Skipped validation of external link '[{link.Definition.url}]({link.Text})'"); break; case LinkValidationResult.FileNotFound: issues.Error(ValidationErrorCode.LinkDestinationNotFound, $"FileNotFound: '[{link.Definition.url}]({link.Text})'. {suggestion}"); break; case LinkValidationResult.BookmarkMissing: issues.Error(ValidationErrorCode.LinkDestinationNotFound, $"BookmarkMissing: '[{link.Definition.url}]({link.Text})'. {suggestion}"); break; case LinkValidationResult.ParentAboveDocSetPath: //Possible error because of the beta-disclaimer.md file is in the includes [!INCLUDE [beta-disclaimer](../../includes/beta-disclaimer.md)] //Needs further investigation and tests. issues.Error(ValidationErrorCode.LinkDestinationOutsideDocSet, $"Relative link outside of doc set: '[{link.Definition.url}]({link.Text})'."); break; case LinkValidationResult.UrlFormatInvalid: issues.Error(ValidationErrorCode.LinkFormatInvalid, $"InvalidUrlFormat '[{link.Definition.url}]({link.Text})'."); break; case LinkValidationResult.Valid: issues.Message($"Valid link '[{link.Definition.url}]({link.Text})'."); if (null != relativeFileName) { linkedPages.Add(relativeFileName); } break; default: issues.Error(ValidationErrorCode.Unknown, $"{result}: Link '[{link.Text}]({link.Definition.url})'."); break; } } linkedDocFiles = linkedPages.Distinct().ToArray(); return !(issues.Issues.WereErrors() || issues.Issues.WereWarnings()); } protected enum LinkValidationResult { Valid, FileNotFound, UrlFormatInvalid, ExternalSkipped, BookmarkSkipped, ParentAboveDocSetPath, BookmarkMissing, FileExistsBookmarkValidationSkipped, BookmarkSkippedDocFileNotFound } protected LinkValidationResult VerifyLink(string docFilePath, string linkUrl, string docSetBasePath, out string relativeFileName, bool requireFilenameCaseMatch) { relativeFileName = null; Uri parsedUri; var validUrl = Uri.TryCreate(linkUrl, UriKind.RelativeOrAbsolute, out parsedUri); FileInfo sourceFile = new FileInfo(docFilePath); if (validUrl) { if (parsedUri.IsAbsoluteUri && (parsedUri.Scheme == "http" || parsedUri.Scheme == "https")) { // TODO: verify an external URL is valid by making a HEAD request return LinkValidationResult.ExternalSkipped; } else if (linkUrl.StartsWith("#")) { string bookmarkName = linkUrl.Substring(1); if (this.bookmarks.Contains(bookmarkName)) { return LinkValidationResult.Valid; } else { var suggestion = StringSuggestions.SuggestStringFromCollection(bookmarkName, this.bookmarks); if (suggestion != null) relativeFileName = "#" + suggestion; return LinkValidationResult.BookmarkMissing; } } else { return this.VerifyRelativeLink(sourceFile, linkUrl, docSetBasePath, out relativeFileName, requireFilenameCaseMatch); } } else { return LinkValidationResult.UrlFormatInvalid; } } protected virtual LinkValidationResult VerifyRelativeLink(FileInfo sourceFile, string originalLinkUrl, string docSetBasePath, out string relativeFileName, bool requireFilenameCaseMatch) { if (sourceFile == null) throw new ArgumentNullException("sourceFile"); if (string.IsNullOrEmpty(originalLinkUrl)) throw new ArgumentNullException("linkUrl"); if (string.IsNullOrEmpty(docSetBasePath)) throw new ArgumentNullException("docSetBasePath"); if (originalLinkUrl.StartsWith("mailto:", StringComparison.OrdinalIgnoreCase)) { // TODO: Verify that this is an actual email address relativeFileName = null; return LinkValidationResult.Valid; } relativeFileName = null; var rootPath = sourceFile.DirectoryName; string bookmarkName = null; var workingLinkUrl = originalLinkUrl; if (workingLinkUrl.Contains("#")) { int indexOfHash = workingLinkUrl.IndexOf('#'); bookmarkName = workingLinkUrl.Substring(indexOfHash + 1); workingLinkUrl = workingLinkUrl.Substring(0, indexOfHash); } if (this.Parent?.LinkValidationConfig?.IgnoredPaths?.Any(ignoredPath => workingLinkUrl.StartsWith(ignoredPath, StringComparison.OrdinalIgnoreCase)) == true) { return LinkValidationResult.ExternalSkipped; } if (workingLinkUrl.StartsWith("/")) { // URL is relative to the base for the documentation rootPath = docSetBasePath; workingLinkUrl = workingLinkUrl.Substring(1); } while (workingLinkUrl.StartsWith("../")) { var nextLevelParent = new DirectoryInfo(rootPath).Parent; if (null != nextLevelParent) { rootPath = nextLevelParent.FullName; workingLinkUrl = workingLinkUrl.Substring(3); } else { break; } } if (rootPath.Length < docSetBasePath.Length) { return LinkValidationResult.ParentAboveDocSetPath; } try { workingLinkUrl = workingLinkUrl.Replace('/', Path.DirectorySeparatorChar); // normalize the path syntax between local file system and web var pathToFile = Path.Combine(rootPath, workingLinkUrl); FileInfo info = new FileInfo(pathToFile); if (!info.Exists) { if (info.Directory.Exists) { var candidateFiles = from f in info.Directory.GetFiles() select f.Name; relativeFileName = StringSuggestions.SuggestStringFromCollection(info.Name, candidateFiles); } return LinkValidationResult.FileNotFound; } relativeFileName = this.Parent.RelativePathToFile(info.FullName, urlStyle: true); if (bookmarkName != null) { // See if that bookmark exists in the target document, assuming we know about it var otherDocFile = this.Parent.LookupFileForPath(relativeFileName); if (otherDocFile == null) { return LinkValidationResult.BookmarkSkippedDocFileNotFound; } else if (!otherDocFile.bookmarks.Contains(bookmarkName)) { var suggestion = StringSuggestions.SuggestStringFromCollection(bookmarkName, otherDocFile.bookmarks); if (null != suggestion) relativeFileName = "#" + suggestion; return LinkValidationResult.BookmarkMissing; } } return LinkValidationResult.Valid; } catch (Exception) { return LinkValidationResult.UrlFormatInvalid; } } #endregion public string UrlRelativePathFromRoot() { var relativePath = this.DisplayName.Replace('\\', '/'); return relativePath.StartsWith("/") ? relativePath.Substring(1) : relativePath; } public override string ToString() { return this.DisplayName; } public override int GetHashCode() { return this.DisplayName.GetHashCode(); } public override bool Equals(object obj) { return this.DisplayName.Equals(obj); } } }
44.442495
273
0.521236
[ "MIT" ]
andrueastman/apidoctor
ApiDoctor.Validation/DocFile.cs
68,397
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Immutable; using System.ComponentModel; using System.Diagnostics; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Completion { /// <summary> /// One of many possible completions used to form the completion list presented to the user. /// </summary> [DebuggerDisplay("{DisplayText}")] public sealed class CompletionItem : IComparable<CompletionItem> { private readonly string _filterText; /// <summary> /// The text that is displayed to the user. /// </summary> public string DisplayText { get; } /// <summary> /// An optional prefix to be displayed prepended to <see cref="DisplayText"/>. Can be null. /// Pattern-matching of user input will not be performed against this, but only against <see /// cref="DisplayText"/>. /// </summary> public string DisplayTextPrefix { get; } /// <summary> /// An optional suffix to be displayed appended to <see cref="DisplayText"/>. Can be null. /// Pattern-matching of user input will not be performed against this, but only against <see /// cref="DisplayText"/>. /// </summary> public string DisplayTextSuffix { get; } /// <summary> /// The text used to determine if the item matches the filter and is show in the list. /// This is often the same as <see cref="DisplayText"/> but may be different in certain circumstances. /// </summary> public string FilterText => _filterText ?? DisplayText; internal bool HasDifferentFilterText => _filterText != null; /// <summary> /// The text used to determine the order that the item appears in the list. /// This is often the same as the <see cref="DisplayText"/> but may be different in certain circumstances. /// </summary> public string SortText { get; } /// <summary> /// Descriptive text to place after <see cref="DisplayText"/> in the display layer. Should /// be short as it will show up in the UI. Display will present this in a way to distinguish /// this from the normal text (for example, by fading out and right-aligning). /// </summary> public string InlineDescription { get; } /// <summary> /// The span of the syntax element associated with this item. /// /// The span identifies the text in the document that is used to filter the initial list presented to the user, /// and typically represents the region of the document that will be changed if this item is committed. /// </summary> public TextSpan Span { get; internal set; } /// <summary> /// Additional information attached to a completion item by it creator. /// </summary> public ImmutableDictionary<string, string> Properties { get; } /// <summary> /// Descriptive tags from <see cref="Tags.WellKnownTags"/>. /// These tags may influence how the item is displayed. /// </summary> public ImmutableArray<string> Tags { get; } /// <summary> /// Rules that declare how this item should behave. /// </summary> public CompletionItemRules Rules { get; } /// <summary> /// The name of the <see cref="CompletionProvider"/> that created this /// <see cref="CompletionItem"/>. Not available to clients. Only used by /// the Completion subsystem itself for things like getting description text /// and making additional change during commit. /// </summary> internal string ProviderName { get; set; } /// <summary> /// The automation text to use when narrating the completion item. If set to /// null, narration will use the <see cref="DisplayText"/> instead. /// </summary> internal string AutomationText { get; set; } internal CompletionItemFlags Flags { get; set; } private CompletionItem( string displayText, string filterText, string sortText, TextSpan span, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix, string inlineDescription) { DisplayText = displayText ?? ""; DisplayTextPrefix = displayTextPrefix ?? ""; DisplayTextSuffix = displayTextSuffix ?? ""; SortText = sortText ?? DisplayText; InlineDescription = inlineDescription ?? ""; Span = span; Properties = properties ?? ImmutableDictionary<string, string>.Empty; Tags = tags.NullToEmpty(); Rules = rules ?? CompletionItemRules.Default; if (!DisplayText.Equals(filterText, StringComparison.Ordinal)) { _filterText = filterText; } } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules) { return Create(displayText, filterText, sortText, properties, tags, rules, displayTextPrefix: null, displayTextSuffix: null); } // binary back compat overload public static CompletionItem Create( string displayText, string filterText, string sortText, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules, string displayTextPrefix, string displayTextSuffix) { return Create(displayText, filterText, sortText, properties, tags, rules, displayTextPrefix, displayTextSuffix, inlineDescription: null); } public static CompletionItem Create( string displayText, string filterText = null, string sortText = null, ImmutableDictionary<string, string> properties = null, ImmutableArray<string> tags = default, CompletionItemRules rules = null, string displayTextPrefix = null, string displayTextSuffix = null, string inlineDescription = null) { return new CompletionItem( span: default, displayText: displayText, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules, displayTextPrefix: displayTextPrefix, displayTextSuffix: displayTextSuffix, inlineDescription: inlineDescription); } /// <summary> /// Creates a new <see cref="CompletionItem"/> /// </summary> /// <param name="displayText">The text that is displayed to the user.</param> /// <param name="filterText">The text used to determine if the item matches the filter and is show in the list.</param> /// <param name="sortText">The text used to determine the order that the item appears in the list.</param> /// <param name="span">The span of the syntax element in the document associated with this item.</param> /// <param name="properties">Additional information.</param> /// <param name="tags">Descriptive tags that may influence how the item is displayed.</param> /// <param name="rules">The rules that declare how this item should behave.</param> /// <returns></returns> [Obsolete("Use the Create overload that does not take a span", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public static CompletionItem Create( string displayText, string filterText, string sortText, TextSpan span, ImmutableDictionary<string, string> properties, ImmutableArray<string> tags, CompletionItemRules rules) { return new CompletionItem( span: span, displayText: displayText, filterText: filterText, sortText: sortText, properties: properties, tags: tags, rules: rules, displayTextPrefix: null, displayTextSuffix: null, inlineDescription: null); } private CompletionItem With( Optional<TextSpan> span = default, Optional<string> displayText = default, Optional<string> filterText = default, Optional<string> sortText = default, Optional<ImmutableDictionary<string, string>> properties = default, Optional<ImmutableArray<string>> tags = default, Optional<CompletionItemRules> rules = default, Optional<string> displayTextPrefix = default, Optional<string> displayTextSuffix = default, Optional<string> inlineDescription = default) { var newSpan = span.HasValue ? span.Value : Span; var newDisplayText = displayText.HasValue ? displayText.Value : DisplayText; var newFilterText = filterText.HasValue ? filterText.Value : FilterText; var newSortText = sortText.HasValue ? sortText.Value : SortText; var newInlineDescription = inlineDescription.HasValue ? inlineDescription.Value : InlineDescription; var newProperties = properties.HasValue ? properties.Value : Properties; var newTags = tags.HasValue ? tags.Value : Tags; var newRules = rules.HasValue ? rules.Value : Rules; var newDisplayTextPrefix = displayTextPrefix.HasValue ? displayTextPrefix.Value : DisplayTextPrefix; var newDisplayTextSuffix = displayTextSuffix.HasValue ? displayTextSuffix.Value : DisplayTextSuffix; if (newSpan == Span && newDisplayText == DisplayText && newFilterText == FilterText && newSortText == SortText && newProperties == Properties && newTags == Tags && newRules == Rules && newDisplayTextPrefix == DisplayTextPrefix && newDisplayTextSuffix == DisplayTextSuffix && newInlineDescription == InlineDescription) { return this; } return new CompletionItem( displayText: newDisplayText, filterText: newFilterText, span: newSpan, sortText: newSortText, properties: newProperties, tags: newTags, rules: newRules, displayTextPrefix: newDisplayTextPrefix, displayTextSuffix: newDisplayTextSuffix, inlineDescription: newInlineDescription) { AutomationText = AutomationText, ProviderName = ProviderName, Flags = Flags, }; } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Span"/> property changed. /// </summary> [Obsolete("Not used anymore. CompletionList.Span is used to control the span used for filtering.", error: true)] [EditorBrowsable(EditorBrowsableState.Never)] public CompletionItem WithSpan(TextSpan span) { return this; } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayText"/> property changed. /// </summary> public CompletionItem WithDisplayText(string text) { return With(displayText: text); } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayTextPrefix"/> property changed. /// </summary> public CompletionItem WithDisplayTextPrefix(string displayTextPrefix) => With(displayTextPrefix: displayTextPrefix); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="DisplayTextSuffix"/> property changed. /// </summary> public CompletionItem WithDisplayTextSuffix(string displayTextSuffix) => With(displayTextSuffix: displayTextSuffix); /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="FilterText"/> property changed. /// </summary> public CompletionItem WithFilterText(string text) { return With(filterText: text); } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="SortText"/> property changed. /// </summary> public CompletionItem WithSortText(string text) { return With(sortText: text); } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Properties"/> property changed. /// </summary> public CompletionItem WithProperties(ImmutableDictionary<string, string> properties) { return With(properties: properties); } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with a property added to the <see cref="Properties"/> collection. /// </summary> public CompletionItem AddProperty(string name, string value) { return With(properties: Properties.Add(name, value)); } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Tags"/> property changed. /// </summary> public CompletionItem WithTags(ImmutableArray<string> tags) { return With(tags: tags); } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with a tag added to the <see cref="Tags"/> collection. /// </summary> public CompletionItem AddTag(string tag) { if (tag == null) { throw new ArgumentNullException(nameof(tag)); } if (Tags.Contains(tag)) { return this; } else { return With(tags: Tags.Add(tag)); } } /// <summary> /// Creates a copy of this <see cref="CompletionItem"/> with the <see cref="Rules"/> property changed. /// </summary> public CompletionItem WithRules(CompletionItemRules rules) { return With(rules: rules); } private string _entireDisplayText; int IComparable<CompletionItem>.CompareTo(CompletionItem other) { var result = StringComparer.OrdinalIgnoreCase.Compare(SortText, other.SortText); if (result == 0) { result = StringComparer.OrdinalIgnoreCase.Compare(GetEntireDisplayText(), other.GetEntireDisplayText()); } return result; } internal string GetEntireDisplayText() { if (_entireDisplayText == null) { _entireDisplayText = DisplayTextPrefix + DisplayText + DisplayTextSuffix; } return _entireDisplayText; } public override string ToString() => GetEntireDisplayText(); } }
40.834606
149
0.59403
[ "MIT" ]
ThadHouse/roslyn
src/Features/Core/Portable/Completion/CompletionItem.cs
16,050
C#
using System; using Gtk; namespace Moscrif.IDE.Option { public interface IOptionsPanel { void Initialize (PreferencesDialog dialog, object dataObject); string Label {get;} string Icon {get;} Widget CreatePanelWidget (); bool IsVisible (); bool ValidateChanges (); void ApplyChanges (); void ShowPanel(); } }
15.857143
64
0.708709
[ "BSD-3-Clause" ]
moscrif/ide
settings/IOptionsPanel.cs
333
C#
using System; using System.Collections.Generic; using System.Dynamic; using System.Linq; using System.Runtime.CompilerServices; using Comet.Reflection; namespace Comet { public class State<T> : BindingObject { public State(T value) { Value = value; } public State() { } public T Value { get => GetProperty<T>(); set => SetProperty(value); } public static implicit operator T(State<T> state) => state.Value; public static implicit operator Action<T>(State<T> state) => value => state.Value = value; public static implicit operator State<T>(T value) => new State<T>(value); public override string ToString() => Value?.ToString(); } public class StateBuilder : IDisposable { public StateBuilder(View view) { View = view; StateManager.StartBuilding(view); } public View View { get; private set; } public void Dispose() { StateManager.EndBuilding(View); View = null; } } //[Serializable] //public class State : BindingObjectManager { // public State() // { // } // internal object GetValue (string property) // { // return parent?.GetPropertyValue(property) ?? this.GetPropertyValue (property); // } // internal void SetChildrenValue<T>(string property, T value) // { // parent?.SetDeepPropertyValue(property, value); // parent?.BindingPropertyChanged(property, value); // } // } }
19.39726
92
0.65678
[ "MIT" ]
VincentH-Net/Comet
src/Comet/State.cs
1,418
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using Microsoft.Dynamics365.UIAutomation.Browser; using OpenQA.Selenium; namespace Microsoft.Dynamics365.UIAutomation.Api { public class Office365 : XrmPage { public Office365(InteractiveBrowser browser) : base(browser) { SwitchToPopup(); } private static BrowserCommandOptions NavigationRetryOptions { get { return new BrowserCommandOptions( Constants.DefaultTraceSource, "Add User", 0, 1000, null, true, typeof(StaleElementReferenceException)); } } public BrowserCommandResult<bool> CreateUser(string firstname, string lastname, string displayname, string username) { return CreateUser(firstname, lastname, displayname, username, Constants.DefaultThinkTime); } public BrowserCommandResult<bool> CreateUser(string firstname, string lastname, string displayname, string username, int thinkTime) { this.Browser.ThinkTime(thinkTime); return this.Execute(NavigationRetryOptions, driver => { driver.ClickWhenAvailable(By.XPath(Elements.Xpath[Reference.Office365.AddUser])); driver.ClickWhenAvailable(By.XPath(Elements.Xpath[Reference.Office365.FirstName])).SendKeys(firstname, true); driver.ClickWhenAvailable(By.XPath(Elements.Xpath[Reference.Office365.LastName])).SendKeys(lastname, true); driver.ClickWhenAvailable(By.XPath(Elements.Xpath[Reference.Office365.DisplayName])).SendKeys(displayname,true); driver.ClickWhenAvailable(By.XPath(Elements.Xpath[Reference.Office365.UserName])).SendKeys(username, true); //Click the Microsoft Dynamics CRM Online Professional License driver.ClickWhenAvailable(By.XPath(Elements.Xpath[Reference.Office365.License])); //Click Add driver.ClickWhenAvailable(By.XPath(Elements.Xpath[Reference.Office365.Add])); driver.LastWindow().Close(); driver.LastWindow(); return true; }); } } }
37.8125
139
0.613636
[ "MIT" ]
CuriositySoftwareIreland/TestModeller-Dynamics365Framework
Framework/Microsoft.Dynamics365.UIAutomation.Api/Pages/Office365.cs
2,422
C#
namespace MAVN.Service.CustomerAPI.Models.ConversionRate { public class BurnRuleConversionRateRequestModel: ConversionRateRequestModel { public string BurnRuleId { get; set; } } }
25.125
79
0.746269
[ "MIT" ]
HannaAndreevna/MAVN.Service.CustomerAPI
src/MAVN.Service.CustomerAPI/Models/ConversionRate/BurnRuleConversionRateRequestModel.cs
203
C#
using System; using System.Linq; using Realms; using Toggl.Multivac; namespace Toggl.PrimeRadiant.Realm { public sealed class RealmIdProvider : RealmObject { [PrimaryKey] public int Key { get; set; } public long Id { get; set; } } public sealed class IdProvider : IIdProvider { private readonly Func<Realms.Realm> getRealmInstance; public IdProvider(Func<Realms.Realm> getRealmInstance) { Ensure.Argument.IsNotNull(getRealmInstance, nameof(getRealmInstance)); this.getRealmInstance = getRealmInstance; } public long GetNextIdentifier() { var nextIdentifier = -1L; var realm = getRealmInstance(); using (var transaction = realm.BeginWrite()) { var entity = realm.All<RealmIdProvider>().SingleOrDefault(); if (entity == null) { entity = new RealmIdProvider { Id = -2 }; realm.Add(entity); } else { nextIdentifier = entity.Id; entity.Id = nextIdentifier - 1; } transaction.Commit(); } return nextIdentifier; } } }
25.538462
82
0.521837
[ "BSD-3-Clause" ]
AzureMentor/mobileapp
Toggl.PrimeRadiant.Realm/IdProvider.cs
1,330
C#
using Xunit; using Xunit.Internal; using Xunit.Runner.Common; using Xunit.v3; using ClassWithTraits = Namespace2.ClassWithTraits; using InnerClass1 = Namespace1.ClassInNamespace1.InnerClass1; using InnerClass2 = Namespace1.ClassInNamespace1.InnerClass2; public class XunitFiltersTests { static readonly _TestCaseDiscovered InnerClass1Name1 = TestData.TestCaseDiscovered<InnerClass1>(nameof(InnerClass1.Name1)); static readonly _TestCaseDiscovered InnerClass1Name2 = TestData.TestCaseDiscovered<InnerClass1>(nameof(InnerClass1.Name2)); static readonly _TestCaseDiscovered InnerClass1Name3 = TestData.TestCaseDiscovered<InnerClass1>(nameof(InnerClass1.Name3)); static readonly _TestCaseDiscovered InnerClass2Name3 = TestData.TestCaseDiscovered<InnerClass2>(nameof(InnerClass2.Name3)); static readonly _TestCaseDiscovered MethodWithFooBarTrait = TestData.TestCaseDiscovered<ClassWithTraits>(nameof(ClassWithTraits.FooBar)); static readonly _TestCaseDiscovered MethodWithBazBiffTrait = TestData.TestCaseDiscovered<ClassWithTraits>(nameof(ClassWithTraits.BazBiff)); static readonly _TestCaseDiscovered MethodWithNoTraits = TestData.TestCaseDiscovered<ClassWithTraits>(nameof(ClassWithTraits.NoTraits)); static readonly _TestCaseDiscovered NonClassTest = TestData.TestCaseDiscovered(); static readonly _TestCaseDiscovered NonMethodTest = TestData.TestCaseDiscovered( testClass: typeof(ClassWithTraits).Name, testClassWithNamespace: typeof(ClassWithTraits).FullName, testNamespace: typeof(ClassWithTraits).Namespace ); public static class NoFilters { [Fact] public static void AlwaysPass() { var filters = new XunitFilters(); Assert.True(filters.Filter(NonClassTest)); Assert.True(filters.Filter(NonMethodTest)); Assert.True(filters.Filter(InnerClass1Name1)); Assert.True(filters.Filter(InnerClass1Name2)); Assert.True(filters.Filter(InnerClass1Name3)); Assert.True(filters.Filter(InnerClass2Name3)); Assert.True(filters.Filter(MethodWithNoTraits)); Assert.True(filters.Filter(MethodWithFooBarTrait)); Assert.True(filters.Filter(MethodWithBazBiffTrait)); } } public static class ExcludedClasses { [Fact] public static void SingleFilter_ExcludesMatchingClass() { var filters = new XunitFilters(); filters.ExcludedClasses.Add(typeof(InnerClass1).FullName!); Assert.True(filters.Filter(NonClassTest)); Assert.True(filters.Filter(NonMethodTest)); Assert.False(filters.Filter(InnerClass1Name1)); Assert.False(filters.Filter(InnerClass1Name2)); Assert.False(filters.Filter(InnerClass1Name3)); Assert.True(filters.Filter(InnerClass2Name3)); } [Fact] public static void MultipleFilters_ActsAsAnOrOperation() { var filters = new XunitFilters(); filters.ExcludedClasses.Add(typeof(InnerClass1).FullName!); filters.ExcludedClasses.Add(typeof(InnerClass2).FullName!.ToUpperInvariant()); Assert.True(filters.Filter(NonClassTest)); Assert.True(filters.Filter(NonMethodTest)); Assert.False(filters.Filter(InnerClass1Name1)); Assert.False(filters.Filter(InnerClass1Name2)); Assert.False(filters.Filter(InnerClass1Name3)); Assert.False(filters.Filter(InnerClass2Name3)); } } public static class ExcludedMethods { [Fact] public static void ExactMatch_ExcludesMatchingMethod() { var filters = new XunitFilters(); filters.ExcludedMethods.Add($"{typeof(InnerClass1).FullName}.{nameof(InnerClass1.Name1)}"); Assert.True(filters.Filter(NonClassTest)); Assert.True(filters.Filter(NonMethodTest)); Assert.False(filters.Filter(InnerClass1Name1)); Assert.True(filters.Filter(InnerClass1Name2)); Assert.True(filters.Filter(InnerClass1Name3)); Assert.True(filters.Filter(InnerClass2Name3)); } [Fact] public static void WildcardMatch_ExcludesMatchingMethod() { var filters = new XunitFilters(); filters.ExcludedMethods.Add($"*.nAmE1"); Assert.True(filters.Filter(NonClassTest)); Assert.True(filters.Filter(NonMethodTest)); Assert.False(filters.Filter(InnerClass1Name1)); Assert.True(filters.Filter(InnerClass1Name2)); Assert.True(filters.Filter(InnerClass1Name3)); Assert.True(filters.Filter(InnerClass2Name3)); } [Fact] public static void MultipleFilters_ActsAsOrOperation() { var filters = new XunitFilters(); filters.ExcludedMethods.Add($"{typeof(InnerClass1).FullName}.{nameof(InnerClass1.Name1)}"); filters.ExcludedMethods.Add($"*.nAmE2"); Assert.True(filters.Filter(NonClassTest)); Assert.True(filters.Filter(NonMethodTest)); Assert.False(filters.Filter(InnerClass1Name1)); Assert.False(filters.Filter(InnerClass1Name2)); Assert.True(filters.Filter(InnerClass1Name3)); Assert.True(filters.Filter(InnerClass2Name3)); } } public static class ExcludedNamespaces { [Fact] public static void SingleFilter_ExcludesMatchingClass() { var filters = new XunitFilters(); filters.ExcludedNamespaces.Add(typeof(InnerClass1).Namespace!); Assert.True(filters.Filter(NonClassTest)); Assert.True(filters.Filter(NonMethodTest)); Assert.False(filters.Filter(InnerClass1Name1)); Assert.False(filters.Filter(InnerClass1Name2)); Assert.False(filters.Filter(InnerClass1Name3)); Assert.False(filters.Filter(InnerClass2Name3)); Assert.True(filters.Filter(MethodWithNoTraits)); Assert.True(filters.Filter(MethodWithFooBarTrait)); Assert.True(filters.Filter(MethodWithBazBiffTrait)); } [Fact] public static void MultipleFilters_ActsAsAnOrOperation() { var filters = new XunitFilters(); filters.ExcludedNamespaces.Add(typeof(InnerClass1).Namespace!); filters.ExcludedNamespaces.Add(typeof(ClassWithTraits).Namespace!.ToUpperInvariant()); Assert.True(filters.Filter(NonClassTest)); Assert.False(filters.Filter(NonMethodTest)); Assert.False(filters.Filter(InnerClass1Name1)); Assert.False(filters.Filter(InnerClass1Name2)); Assert.False(filters.Filter(InnerClass1Name3)); Assert.False(filters.Filter(InnerClass2Name3)); Assert.False(filters.Filter(MethodWithNoTraits)); Assert.False(filters.Filter(MethodWithFooBarTrait)); Assert.False(filters.Filter(MethodWithBazBiffTrait)); } } public static class ExcludedTraits { [Fact] public static void SingleFilter_ExcludesMatchingTrait() { var filters = new XunitFilters(); filters.ExcludedTraits.Add("foo", "bar"); Assert.True(filters.Filter(NonClassTest)); Assert.True(filters.Filter(NonMethodTest)); Assert.True(filters.Filter(MethodWithNoTraits)); Assert.False(filters.Filter(MethodWithFooBarTrait)); Assert.True(filters.Filter(MethodWithBazBiffTrait)); } [Fact] public static void MultipleFilters_ActsAsOrOperation() { var filters = new XunitFilters(); filters.ExcludedTraits.Add("fOo", "bAr"); filters.ExcludedTraits.Add("bAz", "bIff"); Assert.True(filters.Filter(NonClassTest)); Assert.True(filters.Filter(NonMethodTest)); Assert.True(filters.Filter(MethodWithNoTraits)); Assert.False(filters.Filter(MethodWithFooBarTrait)); Assert.False(filters.Filter(MethodWithBazBiffTrait)); } } public static class IncludedClasses { [Fact] public static void SingleFilter_IncludesMatchingClass() { var filters = new XunitFilters(); filters.IncludedClasses.Add(typeof(InnerClass1).FullName!); Assert.False(filters.Filter(NonClassTest)); Assert.False(filters.Filter(NonMethodTest)); Assert.True(filters.Filter(InnerClass1Name1)); Assert.True(filters.Filter(InnerClass1Name2)); Assert.True(filters.Filter(InnerClass1Name3)); Assert.False(filters.Filter(InnerClass2Name3)); } [Fact] public static void MultipleFilters_ActsAsAnAndOperation() { var filters = new XunitFilters(); filters.IncludedClasses.Add(typeof(InnerClass1).FullName!); filters.IncludedClasses.Add(typeof(InnerClass2).FullName!.ToUpperInvariant()); Assert.False(filters.Filter(NonClassTest)); Assert.False(filters.Filter(NonMethodTest)); Assert.True(filters.Filter(InnerClass1Name1)); Assert.True(filters.Filter(InnerClass1Name2)); Assert.True(filters.Filter(InnerClass1Name3)); Assert.True(filters.Filter(InnerClass2Name3)); } } public static class IncludedMethods { [Fact] public static void ExactMatch_IncludesMatchingMethod() { var filters = new XunitFilters(); filters.IncludedMethods.Add($"{typeof(InnerClass1).FullName}.{nameof(InnerClass1.Name1)}"); Assert.False(filters.Filter(NonClassTest)); Assert.False(filters.Filter(NonMethodTest)); Assert.True(filters.Filter(InnerClass1Name1)); Assert.False(filters.Filter(InnerClass1Name2)); Assert.False(filters.Filter(InnerClass1Name3)); Assert.False(filters.Filter(InnerClass2Name3)); } [Fact] public static void WildcardMatch_IncludesMatchingMethod() { var filters = new XunitFilters(); filters.IncludedMethods.Add($"*.{nameof(InnerClass1.Name1)}"); Assert.False(filters.Filter(NonClassTest)); Assert.False(filters.Filter(NonMethodTest)); Assert.True(filters.Filter(InnerClass1Name1)); Assert.False(filters.Filter(InnerClass1Name2)); Assert.False(filters.Filter(InnerClass1Name3)); Assert.False(filters.Filter(InnerClass2Name3)); } [Fact] public static void MultipleFilters_ActsAsAndOperation() { var filters = new XunitFilters(); filters.IncludedMethods.Add($"{typeof(InnerClass1).FullName}.{nameof(InnerClass1.Name1)}"); filters.IncludedMethods.Add($"*.{nameof(InnerClass1.Name2).ToUpperInvariant()}"); Assert.False(filters.Filter(NonClassTest)); Assert.False(filters.Filter(NonMethodTest)); Assert.True(filters.Filter(InnerClass1Name1)); Assert.True(filters.Filter(InnerClass1Name2)); Assert.False(filters.Filter(InnerClass1Name3)); Assert.False(filters.Filter(InnerClass2Name3)); } } public static class IncludedNamespaces { [Fact] public static void SingleFilter_ExcludesMatchingClass() { var filters = new XunitFilters(); filters.IncludedNamespaces.Add(typeof(InnerClass1).Namespace!); Assert.False(filters.Filter(NonClassTest)); Assert.False(filters.Filter(NonMethodTest)); Assert.True(filters.Filter(InnerClass1Name1)); Assert.True(filters.Filter(InnerClass1Name2)); Assert.True(filters.Filter(InnerClass1Name3)); Assert.True(filters.Filter(InnerClass2Name3)); Assert.False(filters.Filter(MethodWithNoTraits)); Assert.False(filters.Filter(MethodWithFooBarTrait)); Assert.False(filters.Filter(MethodWithBazBiffTrait)); } [Fact] public static void MultipleFilters_ActsAsAnOrOperation() { var filters = new XunitFilters(); filters.IncludedNamespaces.Add(typeof(InnerClass1).Namespace!); filters.IncludedNamespaces.Add(typeof(ClassWithTraits).Namespace!.ToUpperInvariant()); Assert.False(filters.Filter(NonClassTest)); Assert.True(filters.Filter(NonMethodTest)); Assert.True(filters.Filter(InnerClass1Name1)); Assert.True(filters.Filter(InnerClass1Name2)); Assert.True(filters.Filter(InnerClass1Name3)); Assert.True(filters.Filter(InnerClass2Name3)); Assert.True(filters.Filter(MethodWithNoTraits)); Assert.True(filters.Filter(MethodWithFooBarTrait)); Assert.True(filters.Filter(MethodWithBazBiffTrait)); } } public static class IncludedTraits { [Fact] public static void SingleFilter_IncludesMatchingTrait() { var filters = new XunitFilters(); filters.IncludedTraits.Add("foo", "bar"); Assert.False(filters.Filter(NonClassTest)); Assert.False(filters.Filter(NonMethodTest)); Assert.False(filters.Filter(MethodWithNoTraits)); Assert.True(filters.Filter(MethodWithFooBarTrait)); Assert.False(filters.Filter(MethodWithBazBiffTrait)); } [Fact] public static void MultipleFilters_ActsAsAndOperation() { var filters = new XunitFilters(); filters.IncludedTraits.Add("fOo", "bAr"); filters.IncludedTraits.Add("bAz", "bIff"); Assert.False(filters.Filter(NonClassTest)); Assert.False(filters.Filter(NonMethodTest)); Assert.False(filters.Filter(MethodWithNoTraits)); Assert.True(filters.Filter(MethodWithFooBarTrait)); Assert.True(filters.Filter(MethodWithBazBiffTrait)); } } public static class MixedFilters { [Fact] public static void ActsAsAnAndOperation() { var filters = new XunitFilters(); filters.IncludedClasses.Add(typeof(InnerClass1).FullName!); filters.IncludedMethods.Add("*.nAmE3"); Assert.False(filters.Filter(NonClassTest)); Assert.False(filters.Filter(NonMethodTest)); Assert.False(filters.Filter(InnerClass1Name1)); Assert.False(filters.Filter(InnerClass1Name2)); Assert.True(filters.Filter(InnerClass1Name3)); Assert.False(filters.Filter(InnerClass2Name3)); Assert.False(filters.Filter(MethodWithNoTraits)); Assert.False(filters.Filter(MethodWithFooBarTrait)); Assert.False(filters.Filter(MethodWithBazBiffTrait)); } } } namespace Namespace1 { class ClassInNamespace1 { internal class InnerClass1 { [Fact] public static void Name1() { } [Fact] public static void Name2() { } [Fact] public static void Name3() { } } internal class InnerClass2 { [Fact] public static void Name3() { } } } } namespace Namespace2 { internal class ClassWithTraits { [Fact] public static void NoTraits() { } [Fact] [Trait("foo", "bar")] public static void FooBar() { } [Fact] [Trait("baz", "biff")] public static void BazBiff() { } } }
33.613065
140
0.763418
[ "Apache-2.0" ]
KiKoS0/xunit
src/xunit.v3.runner.common.tests/Frameworks/XunitFiltersTests.cs
13,380
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using AppsFlyerSDK; // This class is intended to be used the the AppsFlyerObject.prefab public class AppsFlyerObjectScript : MonoBehaviour , IAppsFlyerConversionData { // These fields are set from the editor so do not modify! //******************************// public string devKey; public string appID; public bool isDebug; public bool getConversionData; //******************************// void Start() { // These fields are set from the editor so do not modify! //******************************// AppsFlyer.setIsDebug(isDebug); AppsFlyer.initSDK(devKey, appID, getConversionData ? this : null); //******************************// AppsFlyer.startSDK(); } void Update() { } // Mark AppsFlyer CallBacks public void onConversionDataSuccess(string conversionData) { AppsFlyer.AFLog("didReceiveConversionData", conversionData); Dictionary<string, object> conversionDataDictionary = AppsFlyer.CallbackStringToDictionary(conversionData); // add deferred deeplink logic here } public void onConversionDataFail(string error) { AppsFlyer.AFLog("didReceiveConversionDataWithError", error); } public void onAppOpenAttribution(string attributionData) { AppsFlyer.AFLog("onAppOpenAttribution", attributionData); Dictionary<string, object> attributionDataDictionary = AppsFlyer.CallbackStringToDictionary(attributionData); // add direct deeplink logic here } public void onAppOpenAttributionFailure(string error) { AppsFlyer.AFLog("onAppOpenAttributionFailure", error); } }
29.433333
117
0.648924
[ "Apache-2.0" ]
Avid-ly/Avidly-Unity-TraceAnalysisSDK-Demo
AvidlyTraceDemo/Assets/AppsFlyer/AppsFlyerObjectScript.cs
1,766
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 dynamodb-2012-08-10.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.DynamoDBv2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.DynamoDBv2.Model.Internal.MarshallTransformations { /// <summary> /// Endpoint discovery parameters for DescribeBackup operation /// </summary> public class DescribeBackupEndpointDiscoveryMarshaller : IMarshaller<EndpointDiscoveryDataBase, DescribeBackupRequest> , IMarshaller<EndpointDiscoveryDataBase,AmazonWebServiceRequest> { /// <summary> /// Marshaller the endpoint discovery object. /// </summary> /// <param name="input"></param> /// <returns></returns> public EndpointDiscoveryDataBase Marshall(AmazonWebServiceRequest input) { return this.Marshall((DescribeBackupRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public EndpointDiscoveryDataBase Marshall(DescribeBackupRequest publicRequest) { var endpointDiscoveryData = new EndpointDiscoveryData(false); return endpointDiscoveryData; } private static DescribeBackupEndpointDiscoveryMarshaller _instance = new DescribeBackupEndpointDiscoveryMarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static DescribeBackupEndpointDiscoveryMarshaller Instance { get { return _instance; } } } }
34.22973
187
0.679826
[ "Apache-2.0" ]
AltairMartinez/aws-sdk-unity-net
src/Services/DynamoDBv2/Generated/Model/Internal/MarshallTransformations/DescribeBackupEndpointDiscoveryMarshaller.cs
2,533
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ProjectOnion.Http.WebApi.V1.ViewModel.Entity; using ProjectOnion.Model.Models; namespace ProjectOnion.Http.WebApi.V1.ViewModel.TestViewData { public class TestGetViewModel : EntityConverter<Test> { public TestGetViewModel() { } public TestGetViewModel(Test test):base(test) { } public Guid Id { get; set; } public string TestName { get; set; } } }
21.28
60
0.669173
[ "MIT" ]
abhinav2127/Onion-Architecture-dotNet
src/ProjectOnion/WebApi/V1/ViewModel/TestViewData/TestGetViewModel.cs
534
C#
using System; using System.IO; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using DA = Autodesk.Forge.DesignAutomation.Http; using Autodesk.Forge.DesignAutomation.Model; namespace api { public class GetWorkItemStatus { private readonly DA.IWorkItemsApi _workItemApi; private readonly DA.IEnginesApi _engineApi; public GetWorkItemStatus(DA.IWorkItemsApi workItemApi, DA.IEnginesApi engineApi) { this._workItemApi = workItemApi; this._engineApi = engineApi; } [FunctionName("GetWorkItemStatus")] public async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "workitem/{workItemId}")] HttpRequest req, //[Queue("completedworkitems", Connection = "StorageConnectionString")] IAsyncCollector<WorkItemStatus> completedWorkItemsQueue, string workItemId, ILogger log) { log.LogInformation("C# HTTP trigger function processed the GetWorkItemStatus request."); try { Autodesk.Forge.Core.ApiResponse<WorkItemStatus> workItemResponse = await _workItemApi.GetWorkitemStatusAsync(workItemId); WorkItemStatus workItemStatus = workItemResponse.Content; if (workItemStatus.Status == Status.Pending || workItemStatus.Status == Status.Inprogress) { // check if the workItem run for less than a hour TimeZoneInfo timeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Dateline Standard Time"); DateTime now = TimeZoneInfo.ConvertTime(DateTime.Now, timeZoneInfo); TimeSpan? duration = now - workItemStatus.Stats.TimeDownloadStarted; TimeSpan maxDuration = new TimeSpan(0, 20, 0); if (duration != null) { TimeSpan durationNNull = duration ?? default(TimeSpan); int result = TimeSpan.Compare(durationNNull, maxDuration); if (result == 1) { await _workItemApi.DeleteWorkItemAsync(workItemId); } } } // else // { // await completedWorkItemsQueue.AddAsync(workItemStatus); // } return new OkObjectResult(workItemStatus); } catch (Exception ex) { return new BadRequestObjectResult(ex); } } } }
33.337838
136
0.681394
[ "MIT" ]
simonmoreau/RevitToIFCApp
api/WorkItem/GetWorkItemStatus.cs
2,467
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using NUnit.Framework; using SSRSMigrate.SSRS.Writer; using SSRSMigrate.SSRS.Item; using SSRSMigrate.TestHelper; using System.Net; using SSRSMigrate.SSRS.Errors; namespace SSRSMigrate.IntegrationTests.SSRS.Writer.ReportServer2010 { /// <summary> /// These integration tests will write ReportItems to a ReportingService2010 endpoint. /// The ReportItem objects used are already 'converted' to contain the destination information. /// </summary> [TestFixture, Category("ConnectsToSSRS")] [CoverageExcludeAttribute] class ReportServerWriter_ReportTests { IReportServerWriter writer = null; string outputPath = null; #region Report Items List<ReportItem> reportItems = null; ReportItem reportItem_CompanySales; ReportItem reportItem_SalesOrderDetail; ReportItem reportItem_StoreContacts; ReportItem reportItem_InvalidPath; ReportItem reportItem_AlreadyExists; ReportItem reportItem_NullDefinition; #endregion private void SetupReportItems() { reportItem_CompanySales = new ReportItem() { Name = "Company Sales", Path = string.Format("{0}/Reports/Company Sales", outputPath), CreatedBy = "DOMAIN\\user", CreationDate = DateTime.Parse("7/28/2014 12:06:43 PM"), Description = null, ID = "16d599e6-9c87-4ebc-b45b-5a47e3c73746", ModifiedBy = "DOMAIN\\user", ModifiedDate = DateTime.Parse("7/28/2014 12:06:43 PM"), Size = 10, VirtualPath = null, Definition = TesterUtility.StringToByteArray(TesterUtility.LoadRDLFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "Test AW Reports\\2010\\Company Sales.rdl"))) }; reportItem_StoreContacts = new ReportItem() { Name = "Store Contacts", Path = string.Format("{0}/Reports/Store Contacts", outputPath), CreatedBy = "DOMAIN\\user", CreationDate = DateTime.Parse("7/28/2014 12:06:43 PM"), Description = null, ID = "18fc782e-dd5f-4c65-95ff-957e1bdc98de", ModifiedBy = "DOMAIN\\user", ModifiedDate = DateTime.Parse("7/28/2014 12:06:43 PM"), Size = 10, VirtualPath = null, Definition = TesterUtility.StringToByteArray(TesterUtility.LoadRDLFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "Test AW Reports\\2010\\Store Contacts.rdl"))), }; reportItem_SalesOrderDetail = new ReportItem() { Name = "Sales Order Detail", Path = string.Format("{0}/Reports/Sales Order Detail", outputPath), CreatedBy = "DOMAIN\\user", CreationDate = DateTime.Parse("7/28/2014 12:06:43 PM"), Description = null, ID = "70650568-7dd4-4ef4-aeaa-67502de11b4f", ModifiedBy = "DOMAIN\\user", ModifiedDate = DateTime.Parse("7/28/2014 12:06:43 PM"), Size = 10, VirtualPath = null, Definition = TesterUtility.StringToByteArray(TesterUtility.LoadRDLFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "Test AW Reports\\2010\\Sales Order Detail.rdl"))), SubReports = new List<ReportItem>() { reportItem_StoreContacts } }; reportItem_AlreadyExists = new ReportItem() { Name = "Already Exists", Path = string.Format("{0}/Reports/Already Exists", outputPath), Description = null, ID = "5921480a-1b24-4a6e-abbc-f8db116cd24e", VirtualPath = null, Definition = TesterUtility.StringToByteArray(TesterUtility.LoadRDLFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "Test AW Reports\\2010\\Company Sales.rdl"))) }; reportItem_InvalidPath = new ReportItem() { Name = "Invalid.Path", Path = string.Format("{0}/Reports./Invalid.Path", outputPath), Description = null, ID = "5921480a-1b24-4a6e-abbc-f8db116cd24e", VirtualPath = null, Definition = TesterUtility.StringToByteArray(TesterUtility.LoadRDLFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "Test AW Reports\\2010\\Company Sales.rdl"))) }; reportItem_NullDefinition = new ReportItem() { Name = "Null Definition", Path = string.Format("{0}/Reports/Null Definition", outputPath), Description = null, ID = "5921480a-1b24-4a6e-abbc-f8db116cd24e", VirtualPath = null, Definition = null }; reportItems = new List<ReportItem>() { reportItem_CompanySales, reportItem_SalesOrderDetail, reportItem_StoreContacts }; } [OneTimeSetUp] public void TestFixtureSetUp() { outputPath = Properties.Settings.Default.DestinationPath; SetupReportItems(); writer = TestKernel.Instance.Get<IReportServerWriter>("2010-DEST"); } [OneTimeTearDown] public void TestFixtureTearDown() { writer = null; } [SetUp] public void SetUp() { SetupEnvironment(); writer.Overwrite = false; // Reset overwrite property } [TearDown] public void TearDown() { TeardownEnvironment(); } #region Environment Setup/Teardown private void SetupEnvironment() { ReportingService2010TestEnvironment.SetupReportWriterEnvironment( Properties.Settings.Default.ReportServer2008R2WebServiceUrl, CredentialCache.DefaultNetworkCredentials, outputPath, new List<ReportItem>() { reportItem_AlreadyExists }); } private void TeardownEnvironment() { ReportingService2010TestEnvironment.TeardownReportWriterEnvironment( Properties.Settings.Default.ReportServer2008R2WebServiceUrl, CredentialCache.DefaultNetworkCredentials, outputPath, new List<ReportItem>() { reportItem_AlreadyExists }); } #endregion #region WriteReport Tests [Test] public void WriteReport() { string[] actual = writer.WriteReport(reportItem_CompanySales); Assert.Null(actual); } [Test] public void WriteReport_AlreadyExists_OverwriteDisallowed() { ItemAlreadyExistsException ex = Assert.Throws<ItemAlreadyExistsException>( delegate { writer.WriteReport(reportItem_AlreadyExists); }); Assert.That(ex.Message, Is.EqualTo(string.Format("An item at '{0}' already exists.", reportItem_AlreadyExists.Path))); } [Test] public void WriteReport_AlreadyExists_OverwriteAllowed() { writer.Overwrite = true; // Allow overwriting of report string[] actual = writer.WriteReport(reportItem_AlreadyExists); Assert.Null(actual); } [Test] public void WriteReport_NullReportItem() { ArgumentNullException ex = Assert.Throws<ArgumentNullException>( delegate { writer.WriteReport(null); }); Assert.That(ex.Message, Is.EqualTo("Value cannot be null.\r\nParameter name: reportItem")); } [Test] public void WriteReport_InvalidReportPath() { InvalidPathException ex = Assert.Throws<InvalidPathException>( delegate { writer.WriteReport(reportItem_InvalidPath); }); Assert.That(ex.Message, Is.EqualTo(string.Format("Invalid path '{0}'.", reportItem_InvalidPath.Path))); } [Test] public void WriteReport_ReportItemNullName() { ReportItem report = new ReportItem() { Name = null, Path = "/SSRSMigrate_AW_Tests/Reports/Company Sales", Description = null, ID = "5921480a-1b24-4a6e-abbc-f8db116cd24e", VirtualPath = null, Definition = TesterUtility.StringToByteArray(TesterUtility.LoadRDLFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "Test AW Reports\\2010\\Company Sales.rdl"))) }; ArgumentException ex = Assert.Throws<ArgumentException>( delegate { writer.WriteReport(report); }); Assert.That(ex.Message, Is.EqualTo("item.Name")); } [Test] public void WriteReport_ReportItemEmptyName() { ReportItem report = new ReportItem() { Name = "", Path = "/SSRSMigrate_AW_Tests/Reports/Company Sales", Description = null, ID = "5921480a-1b24-4a6e-abbc-f8db116cd24e", VirtualPath = null, Definition = TesterUtility.StringToByteArray(TesterUtility.LoadRDLFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "Test AW Reports\\2010\\Company Sales.rdl"))) }; ArgumentException ex = Assert.Throws<ArgumentException>( delegate { writer.WriteReport(report); }); Assert.That(ex.Message, Is.EqualTo("item.Name")); } [Test] public void WriteReport_ReportItemNullPath() { ReportItem report = new ReportItem() { Name = "Company Sales", Path = null, Description = null, ID = "5921480a-1b24-4a6e-abbc-f8db116cd24e", VirtualPath = null, Definition = TesterUtility.StringToByteArray(TesterUtility.LoadRDLFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "Test AW Reports\\2010\\Company Sales.rdl"))) }; ArgumentException ex = Assert.Throws<ArgumentException>( delegate { writer.WriteReport(report); }); Assert.That(ex.Message, Is.EqualTo("item.Path")); } [Test] public void WriteReport_ReportItemEmptyPath() { ReportItem report = new ReportItem() { Name = "Company Sales", Path = "", Description = null, ID = "5921480a-1b24-4a6e-abbc-f8db116cd24e", VirtualPath = null, Definition = TesterUtility.StringToByteArray(TesterUtility.LoadRDLFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "Test AW Reports\\2010\\Company Sales.rdl"))) }; ArgumentException ex = Assert.Throws<ArgumentException>( delegate { writer.WriteReport(report); }); Assert.That(ex.Message, Is.EqualTo("item.Path")); } [Test] public void WriteReport_ReportItemNullDefinition() { InvalidReportDefinitionException ex = Assert.Throws<InvalidReportDefinitionException>( delegate { writer.WriteReport(reportItem_NullDefinition); }); Assert.That(ex.Message, Is.EqualTo(string.Format("Invalid report definition for report '{0}'.", reportItem_NullDefinition.Path))); } #endregion #region WriteReports Tests [Test] public void WriteReports() { string[] actual = writer.WriteReports(reportItems.ToArray()); Assert.AreEqual(0, actual.Count()); } [Test] public void WriteReports_OneOrMoreAlreadyExists_OverwriteDisallowed() { List<ReportItem> items = new List<ReportItem>() { reportItem_AlreadyExists }; items.AddRange(reportItems); ItemAlreadyExistsException ex = Assert.Throws<ItemAlreadyExistsException>( delegate { writer.WriteReports(items.ToArray()); }); Assert.That(ex.Message, Is.EqualTo(string.Format("An item at '{0}' already exists.", reportItem_AlreadyExists.Path))); } [Test] public void WriteReports_OneOrMoreAlreadyExists_OverwriteAllowedllowed() { List<ReportItem> items = new List<ReportItem>() { reportItem_AlreadyExists }; items.AddRange(reportItems); writer.Overwrite = true; // Allow overwriting of report string[] actual = writer.WriteReports(items.ToArray()); Assert.AreEqual(0, actual.Count()); } [Test] public void WriteReports_NullReportItems() { ArgumentNullException ex = Assert.Throws<ArgumentNullException>( delegate { writer.WriteReports(null); }); Assert.That(ex.Message, Is.EqualTo("Value cannot be null.\r\nParameter name: reportItems")); } [Test] public void WriteReports_OneOrMoreInvalidReportPath() { List<ReportItem> items = new List<ReportItem>() { reportItem_InvalidPath }; items.AddRange(reportItems); InvalidPathException ex = Assert.Throws<InvalidPathException>( delegate { writer.WriteReports(items.ToArray()); }); Assert.That(ex.Message, Is.EqualTo(string.Format("Invalid path '{0}'.", reportItem_InvalidPath.Path))); } [Test] public void WriteReports_OneOrMoreReportItemNullName() { ReportItem report = new ReportItem() { Name = null, Path = "/SSRSMigrate_AW_Tests/Reports/Company Sales", Description = null, ID = "5921480a-1b24-4a6e-abbc-f8db116cd24e", VirtualPath = null, Definition = TesterUtility.StringToByteArray(TesterUtility.LoadRDLFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "Test AW Reports\\2010\\Company Sales.rdl"))) }; List<ReportItem> items = new List<ReportItem>() { report }; items.AddRange(reportItems); ArgumentException ex = Assert.Throws<ArgumentException>( delegate { writer.WriteReports(items.ToArray()); }); Assert.That(ex.Message, Is.EqualTo("item.Name")); } [Test] public void WriteReports_OneOrMoreReportItemEmptyName() { ReportItem report = new ReportItem() { Name = "", Path = "/SSRSMigrate_AW_Tests/Reports/Company Sales", Description = null, ID = "5921480a-1b24-4a6e-abbc-f8db116cd24e", VirtualPath = null, Definition = TesterUtility.StringToByteArray(TesterUtility.LoadRDLFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "Test AW Reports\\2010\\Company Sales.rdl"))) }; List<ReportItem> items = new List<ReportItem>() { report }; items.AddRange(reportItems); ArgumentException ex = Assert.Throws<ArgumentException>( delegate { writer.WriteReports(items.ToArray()); }); Assert.That(ex.Message, Is.EqualTo("item.Name")); } [Test] public void WriteReports_OneOrMoteReportItemNullPath() { ReportItem report = new ReportItem() { Name = "Company Sales", Path = null, Description = null, ID = "5921480a-1b24-4a6e-abbc-f8db116cd24e", VirtualPath = null, Definition = TesterUtility.StringToByteArray(TesterUtility.LoadRDLFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "Test AW Reports\\2010\\Company Sales.rdl"))) }; List<ReportItem> items = new List<ReportItem>() { report }; items.AddRange(reportItems); ArgumentException ex = Assert.Throws<ArgumentException>( delegate { writer.WriteReports(items.ToArray()); }); Assert.That(ex.Message, Is.EqualTo("item.Path")); } [Test] public void WriteReports_OneOrMoreReportItemEmptyPath() { ReportItem report = new ReportItem() { Name = "Company Sales", Path = "", Description = null, ID = "5921480a-1b24-4a6e-abbc-f8db116cd24e", VirtualPath = null, Definition = TesterUtility.StringToByteArray(TesterUtility.LoadRDLFile(Path.Combine(TestContext.CurrentContext.TestDirectory, "Test AW Reports\\2010\\Company Sales.rdl"))) }; List<ReportItem> items = new List<ReportItem>() { report }; items.AddRange(reportItems); ArgumentException ex = Assert.Throws<ArgumentException>( delegate { writer.WriteReports(items.ToArray()); }); Assert.That(ex.Message, Is.EqualTo("item.Path")); } [Test] public void WriteReports_OneOrMoreReportItemNullDefinition() { List<ReportItem> items = new List<ReportItem>() { reportItem_NullDefinition }; items.AddRange(reportItems); InvalidReportDefinitionException ex = Assert.Throws<InvalidReportDefinitionException>( delegate { writer.WriteReports(items.ToArray()); }); Assert.That(ex.Message, Is.EqualTo(string.Format("Invalid report definition for report '{0}'.", reportItem_NullDefinition.Path))); } #endregion } }
36.049002
194
0.536273
[ "MIT" ]
jpann/SSRSMigrate
SSRSMigrate/SSRSMigrate.IntegrationTests/SSRS/Writer/ReportServer2010/ReportServerWriter_ReportTests.cs
19,865
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> //------------------------------------------------------------------------------ // Generation date: 11/28/2021 8:55:09 PM namespace Microsoft.Dynamics.DataEntities { /// <summary> /// There are no comments for AssetMaintenanceJobTypeSingle in the schema. /// </summary> public partial class AssetMaintenanceJobTypeSingle : global::Microsoft.OData.Client.DataServiceQuerySingle<AssetMaintenanceJobType> { /// <summary> /// Initialize a new AssetMaintenanceJobTypeSingle object. /// </summary> public AssetMaintenanceJobTypeSingle(global::Microsoft.OData.Client.DataServiceContext context, string path) : base(context, path) {} /// <summary> /// Initialize a new AssetMaintenanceJobTypeSingle object. /// </summary> public AssetMaintenanceJobTypeSingle(global::Microsoft.OData.Client.DataServiceContext context, string path, bool isComposable) : base(context, path, isComposable) {} /// <summary> /// Initialize a new AssetMaintenanceJobTypeSingle object. /// </summary> public AssetMaintenanceJobTypeSingle(global::Microsoft.OData.Client.DataServiceQuerySingle<AssetMaintenanceJobType> query) : base(query) {} /// <summary> /// There are no comments for AssetMaintenanceJobGroup in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobGroupSingle AssetMaintenanceJobGroup { get { if (!this.IsComposable) { throw new global::System.NotSupportedException("The previous function is not composable."); } if ((this._AssetMaintenanceJobGroup == null)) { this._AssetMaintenanceJobGroup = new global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobGroupSingle(this.Context, GetPath("AssetMaintenanceJobGroup")); } return this._AssetMaintenanceJobGroup; } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobGroupSingle _AssetMaintenanceJobGroup; /// <summary> /// There are no comments for AssetMaintenanceAssetRound in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetRound> AssetMaintenanceAssetRound { get { if (!this.IsComposable) { throw new global::System.NotSupportedException("The previous function is not composable."); } if ((this._AssetMaintenanceAssetRound == null)) { this._AssetMaintenanceAssetRound = Context.CreateQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetRound>(GetPath("AssetMaintenanceAssetRound")); } return this._AssetMaintenanceAssetRound; } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetRound> _AssetMaintenanceAssetRound; /// <summary> /// There are no comments for AssetMaintenanceJobTypeDefault in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeDefault> AssetMaintenanceJobTypeDefault { get { if (!this.IsComposable) { throw new global::System.NotSupportedException("The previous function is not composable."); } if ((this._AssetMaintenanceJobTypeDefault == null)) { this._AssetMaintenanceJobTypeDefault = Context.CreateQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeDefault>(GetPath("AssetMaintenanceJobTypeDefault")); } return this._AssetMaintenanceJobTypeDefault; } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeDefault> _AssetMaintenanceJobTypeDefault; /// <summary> /// There are no comments for AssetMaintenanceWorkOrderLine in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceWorkOrderLine> AssetMaintenanceWorkOrderLine { get { if (!this.IsComposable) { throw new global::System.NotSupportedException("The previous function is not composable."); } if ((this._AssetMaintenanceWorkOrderLine == null)) { this._AssetMaintenanceWorkOrderLine = Context.CreateQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceWorkOrderLine>(GetPath("AssetMaintenanceWorkOrderLine")); } return this._AssetMaintenanceWorkOrderLine; } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceWorkOrderLine> _AssetMaintenanceWorkOrderLine; /// <summary> /// There are no comments for AssetMaintenanceAssetCalendar in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetCalendar> AssetMaintenanceAssetCalendar { get { if (!this.IsComposable) { throw new global::System.NotSupportedException("The previous function is not composable."); } if ((this._AssetMaintenanceAssetCalendar == null)) { this._AssetMaintenanceAssetCalendar = Context.CreateQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetCalendar>(GetPath("AssetMaintenanceAssetCalendar")); } return this._AssetMaintenanceAssetCalendar; } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetCalendar> _AssetMaintenanceAssetCalendar; /// <summary> /// There are no comments for AssetMaintenanceJobTypeSucceedJobType in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeSucceedJobType> AssetMaintenanceJobTypeSucceedJobType { get { if (!this.IsComposable) { throw new global::System.NotSupportedException("The previous function is not composable."); } if ((this._AssetMaintenanceJobTypeSucceedJobType == null)) { this._AssetMaintenanceJobTypeSucceedJobType = Context.CreateQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeSucceedJobType>(GetPath("AssetMaintenanceJobTypeSucceedJobType")); } return this._AssetMaintenanceJobTypeSucceedJobType; } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeSucceedJobType> _AssetMaintenanceJobTypeSucceedJobType; /// <summary> /// There are no comments for AssetMaintenanceJobTypeVariant in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeVariant> AssetMaintenanceJobTypeVariant { get { if (!this.IsComposable) { throw new global::System.NotSupportedException("The previous function is not composable."); } if ((this._AssetMaintenanceJobTypeVariant == null)) { this._AssetMaintenanceJobTypeVariant = Context.CreateQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeVariant>(GetPath("AssetMaintenanceJobTypeVariant")); } return this._AssetMaintenanceJobTypeVariant; } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeVariant> _AssetMaintenanceJobTypeVariant; /// <summary> /// There are no comments for AssetMaintenanceWorkerResponsible in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceWorkerResponsible> AssetMaintenanceWorkerResponsible { get { if (!this.IsComposable) { throw new global::System.NotSupportedException("The previous function is not composable."); } if ((this._AssetMaintenanceWorkerResponsible == null)) { this._AssetMaintenanceWorkerResponsible = Context.CreateQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceWorkerResponsible>(GetPath("AssetMaintenanceWorkerResponsible")); } return this._AssetMaintenanceWorkerResponsible; } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceWorkerResponsible> _AssetMaintenanceWorkerResponsible; /// <summary> /// There are no comments for AssetMaintenanceAssetCriticality in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetCriticality> AssetMaintenanceAssetCriticality { get { if (!this.IsComposable) { throw new global::System.NotSupportedException("The previous function is not composable."); } if ((this._AssetMaintenanceAssetCriticality == null)) { this._AssetMaintenanceAssetCriticality = Context.CreateQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetCriticality>(GetPath("AssetMaintenanceAssetCriticality")); } return this._AssetMaintenanceAssetCriticality; } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetCriticality> _AssetMaintenanceAssetCriticality; /// <summary> /// There are no comments for AssetMaintenanceScheduledExecution in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceScheduledExecution> AssetMaintenanceScheduledExecution { get { if (!this.IsComposable) { throw new global::System.NotSupportedException("The previous function is not composable."); } if ((this._AssetMaintenanceScheduledExecution == null)) { this._AssetMaintenanceScheduledExecution = Context.CreateQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceScheduledExecution>(GetPath("AssetMaintenanceScheduledExecution")); } return this._AssetMaintenanceScheduledExecution; } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceScheduledExecution> _AssetMaintenanceScheduledExecution; /// <summary> /// There are no comments for AssetMaintenanceFunctionalLocationRound in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceFunctionalLocationRound> AssetMaintenanceFunctionalLocationRound { get { if (!this.IsComposable) { throw new global::System.NotSupportedException("The previous function is not composable."); } if ((this._AssetMaintenanceFunctionalLocationRound == null)) { this._AssetMaintenanceFunctionalLocationRound = Context.CreateQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceFunctionalLocationRound>(GetPath("AssetMaintenanceFunctionalLocationRound")); } return this._AssetMaintenanceFunctionalLocationRound; } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceQuery<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceFunctionalLocationRound> _AssetMaintenanceFunctionalLocationRound; } /// <summary> /// There are no comments for AssetMaintenanceJobType in the schema. /// </summary> /// <KeyProperties> /// dataAreaId /// JobTypeId /// </KeyProperties> [global::Microsoft.OData.Client.Key("dataAreaId", "JobTypeId")] [global::Microsoft.OData.Client.EntitySet("AssetMaintenanceJobTypes")] public partial class AssetMaintenanceJobType : global::Microsoft.OData.Client.BaseEntityType, global::System.ComponentModel.INotifyPropertyChanged { /// <summary> /// Create a new AssetMaintenanceJobType object. /// </summary> /// <param name="dataAreaId">Initial value of dataAreaId.</param> /// <param name="jobTypeId">Initial value of JobTypeId.</param> /// <param name="numberOfWorkers">Initial value of NumberOfWorkers.</param> /// <param name="assetMaintenanceJobGroup">Initial value of AssetMaintenanceJobGroup.</param> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public static AssetMaintenanceJobType CreateAssetMaintenanceJobType(string dataAreaId, string jobTypeId, int numberOfWorkers, global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobGroup assetMaintenanceJobGroup) { AssetMaintenanceJobType assetMaintenanceJobType = new AssetMaintenanceJobType(); assetMaintenanceJobType.dataAreaId = dataAreaId; assetMaintenanceJobType.JobTypeId = jobTypeId; assetMaintenanceJobType.NumberOfWorkers = numberOfWorkers; if ((assetMaintenanceJobGroup == null)) { throw new global::System.ArgumentNullException("assetMaintenanceJobGroup"); } assetMaintenanceJobType.AssetMaintenanceJobGroup = assetMaintenanceJobGroup; return assetMaintenanceJobType; } /// <summary> /// There are no comments for Property dataAreaId in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "dataAreaId is required.")] public virtual string dataAreaId { get { return this._dataAreaId; } set { this.OndataAreaIdChanging(value); this._dataAreaId = value; this.OndataAreaIdChanged(); this.OnPropertyChanged("dataAreaId"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private string _dataAreaId; partial void OndataAreaIdChanging(string value); partial void OndataAreaIdChanged(); /// <summary> /// There are no comments for Property JobTypeId in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "JobTypeId is required.")] public virtual string JobTypeId { get { return this._JobTypeId; } set { this.OnJobTypeIdChanging(value); this._JobTypeId = value; this.OnJobTypeIdChanged(); this.OnPropertyChanged("JobTypeId"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private string _JobTypeId; partial void OnJobTypeIdChanging(string value); partial void OnJobTypeIdChanged(); /// <summary> /// There are no comments for Property MaintenanceStopRequired in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::System.Nullable<global::Microsoft.Dynamics.DataEntities.NoYes> MaintenanceStopRequired { get { return this._MaintenanceStopRequired; } set { this.OnMaintenanceStopRequiredChanging(value); this._MaintenanceStopRequired = value; this.OnMaintenanceStopRequiredChanged(); this.OnPropertyChanged("MaintenanceStopRequired"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::System.Nullable<global::Microsoft.Dynamics.DataEntities.NoYes> _MaintenanceStopRequired; partial void OnMaintenanceStopRequiredChanging(global::System.Nullable<global::Microsoft.Dynamics.DataEntities.NoYes> value); partial void OnMaintenanceStopRequiredChanged(); /// <summary> /// There are no comments for Property Name in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual string Name { get { return this._Name; } set { this.OnNameChanging(value); this._Name = value; this.OnNameChanged(); this.OnPropertyChanged("Name"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private string _Name; partial void OnNameChanging(string value); partial void OnNameChanged(); /// <summary> /// There are no comments for Property JobGroupId in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual string JobGroupId { get { return this._JobGroupId; } set { this.OnJobGroupIdChanging(value); this._JobGroupId = value; this.OnJobGroupIdChanged(); this.OnPropertyChanged("JobGroupId"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private string _JobGroupId; partial void OnJobGroupIdChanging(string value); partial void OnJobGroupIdChanged(); /// <summary> /// There are no comments for Property NumberOfWorkers in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "NumberOfWorkers is required.")] public virtual int NumberOfWorkers { get { return this._NumberOfWorkers; } set { this.OnNumberOfWorkersChanging(value); this._NumberOfWorkers = value; this.OnNumberOfWorkersChanged(); this.OnPropertyChanged("NumberOfWorkers"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private int _NumberOfWorkers; partial void OnNumberOfWorkersChanging(int value); partial void OnNumberOfWorkersChanged(); /// <summary> /// There are no comments for Property Description in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual string Description { get { return this._Description; } set { this.OnDescriptionChanging(value); this._Description = value; this.OnDescriptionChanged(); this.OnPropertyChanged("Description"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private string _Description; partial void OnDescriptionChanging(string value); partial void OnDescriptionChanged(); /// <summary> /// There are no comments for Property AssetMaintenanceJobGroup in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] [global::System.ComponentModel.DataAnnotations.RequiredAttribute(ErrorMessage = "AssetMaintenanceJobGroup is required.")] public virtual global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobGroup AssetMaintenanceJobGroup { get { return this._AssetMaintenanceJobGroup; } set { this.OnAssetMaintenanceJobGroupChanging(value); this._AssetMaintenanceJobGroup = value; this.OnAssetMaintenanceJobGroupChanged(); this.OnPropertyChanged("AssetMaintenanceJobGroup"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobGroup _AssetMaintenanceJobGroup; partial void OnAssetMaintenanceJobGroupChanging(global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobGroup value); partial void OnAssetMaintenanceJobGroupChanged(); /// <summary> /// There are no comments for Property AssetMaintenanceAssetRound in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetRound> AssetMaintenanceAssetRound { get { return this._AssetMaintenanceAssetRound; } set { this.OnAssetMaintenanceAssetRoundChanging(value); this._AssetMaintenanceAssetRound = value; this.OnAssetMaintenanceAssetRoundChanged(); this.OnPropertyChanged("AssetMaintenanceAssetRound"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetRound> _AssetMaintenanceAssetRound = new global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetRound>(null, global::Microsoft.OData.Client.TrackingMode.None); partial void OnAssetMaintenanceAssetRoundChanging(global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetRound> value); partial void OnAssetMaintenanceAssetRoundChanged(); /// <summary> /// There are no comments for Property AssetMaintenanceJobTypeDefault in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeDefault> AssetMaintenanceJobTypeDefault { get { return this._AssetMaintenanceJobTypeDefault; } set { this.OnAssetMaintenanceJobTypeDefaultChanging(value); this._AssetMaintenanceJobTypeDefault = value; this.OnAssetMaintenanceJobTypeDefaultChanged(); this.OnPropertyChanged("AssetMaintenanceJobTypeDefault"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeDefault> _AssetMaintenanceJobTypeDefault = new global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeDefault>(null, global::Microsoft.OData.Client.TrackingMode.None); partial void OnAssetMaintenanceJobTypeDefaultChanging(global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeDefault> value); partial void OnAssetMaintenanceJobTypeDefaultChanged(); /// <summary> /// There are no comments for Property AssetMaintenanceWorkOrderLine in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceWorkOrderLine> AssetMaintenanceWorkOrderLine { get { return this._AssetMaintenanceWorkOrderLine; } set { this.OnAssetMaintenanceWorkOrderLineChanging(value); this._AssetMaintenanceWorkOrderLine = value; this.OnAssetMaintenanceWorkOrderLineChanged(); this.OnPropertyChanged("AssetMaintenanceWorkOrderLine"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceWorkOrderLine> _AssetMaintenanceWorkOrderLine = new global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceWorkOrderLine>(null, global::Microsoft.OData.Client.TrackingMode.None); partial void OnAssetMaintenanceWorkOrderLineChanging(global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceWorkOrderLine> value); partial void OnAssetMaintenanceWorkOrderLineChanged(); /// <summary> /// There are no comments for Property AssetMaintenanceAssetCalendar in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetCalendar> AssetMaintenanceAssetCalendar { get { return this._AssetMaintenanceAssetCalendar; } set { this.OnAssetMaintenanceAssetCalendarChanging(value); this._AssetMaintenanceAssetCalendar = value; this.OnAssetMaintenanceAssetCalendarChanged(); this.OnPropertyChanged("AssetMaintenanceAssetCalendar"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetCalendar> _AssetMaintenanceAssetCalendar = new global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetCalendar>(null, global::Microsoft.OData.Client.TrackingMode.None); partial void OnAssetMaintenanceAssetCalendarChanging(global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetCalendar> value); partial void OnAssetMaintenanceAssetCalendarChanged(); /// <summary> /// There are no comments for Property AssetMaintenanceJobTypeSucceedJobType in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeSucceedJobType> AssetMaintenanceJobTypeSucceedJobType { get { return this._AssetMaintenanceJobTypeSucceedJobType; } set { this.OnAssetMaintenanceJobTypeSucceedJobTypeChanging(value); this._AssetMaintenanceJobTypeSucceedJobType = value; this.OnAssetMaintenanceJobTypeSucceedJobTypeChanged(); this.OnPropertyChanged("AssetMaintenanceJobTypeSucceedJobType"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeSucceedJobType> _AssetMaintenanceJobTypeSucceedJobType = new global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeSucceedJobType>(null, global::Microsoft.OData.Client.TrackingMode.None); partial void OnAssetMaintenanceJobTypeSucceedJobTypeChanging(global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeSucceedJobType> value); partial void OnAssetMaintenanceJobTypeSucceedJobTypeChanged(); /// <summary> /// There are no comments for Property AssetMaintenanceJobTypeVariant in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeVariant> AssetMaintenanceJobTypeVariant { get { return this._AssetMaintenanceJobTypeVariant; } set { this.OnAssetMaintenanceJobTypeVariantChanging(value); this._AssetMaintenanceJobTypeVariant = value; this.OnAssetMaintenanceJobTypeVariantChanged(); this.OnPropertyChanged("AssetMaintenanceJobTypeVariant"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeVariant> _AssetMaintenanceJobTypeVariant = new global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeVariant>(null, global::Microsoft.OData.Client.TrackingMode.None); partial void OnAssetMaintenanceJobTypeVariantChanging(global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceJobTypeVariant> value); partial void OnAssetMaintenanceJobTypeVariantChanged(); /// <summary> /// There are no comments for Property AssetMaintenanceWorkerResponsible in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceWorkerResponsible> AssetMaintenanceWorkerResponsible { get { return this._AssetMaintenanceWorkerResponsible; } set { this.OnAssetMaintenanceWorkerResponsibleChanging(value); this._AssetMaintenanceWorkerResponsible = value; this.OnAssetMaintenanceWorkerResponsibleChanged(); this.OnPropertyChanged("AssetMaintenanceWorkerResponsible"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceWorkerResponsible> _AssetMaintenanceWorkerResponsible = new global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceWorkerResponsible>(null, global::Microsoft.OData.Client.TrackingMode.None); partial void OnAssetMaintenanceWorkerResponsibleChanging(global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceWorkerResponsible> value); partial void OnAssetMaintenanceWorkerResponsibleChanged(); /// <summary> /// There are no comments for Property AssetMaintenanceAssetCriticality in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetCriticality> AssetMaintenanceAssetCriticality { get { return this._AssetMaintenanceAssetCriticality; } set { this.OnAssetMaintenanceAssetCriticalityChanging(value); this._AssetMaintenanceAssetCriticality = value; this.OnAssetMaintenanceAssetCriticalityChanged(); this.OnPropertyChanged("AssetMaintenanceAssetCriticality"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetCriticality> _AssetMaintenanceAssetCriticality = new global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetCriticality>(null, global::Microsoft.OData.Client.TrackingMode.None); partial void OnAssetMaintenanceAssetCriticalityChanging(global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceAssetCriticality> value); partial void OnAssetMaintenanceAssetCriticalityChanged(); /// <summary> /// There are no comments for Property AssetMaintenanceScheduledExecution in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceScheduledExecution> AssetMaintenanceScheduledExecution { get { return this._AssetMaintenanceScheduledExecution; } set { this.OnAssetMaintenanceScheduledExecutionChanging(value); this._AssetMaintenanceScheduledExecution = value; this.OnAssetMaintenanceScheduledExecutionChanged(); this.OnPropertyChanged("AssetMaintenanceScheduledExecution"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceScheduledExecution> _AssetMaintenanceScheduledExecution = new global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceScheduledExecution>(null, global::Microsoft.OData.Client.TrackingMode.None); partial void OnAssetMaintenanceScheduledExecutionChanging(global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceScheduledExecution> value); partial void OnAssetMaintenanceScheduledExecutionChanged(); /// <summary> /// There are no comments for Property AssetMaintenanceFunctionalLocationRound in the schema. /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public virtual global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceFunctionalLocationRound> AssetMaintenanceFunctionalLocationRound { get { return this._AssetMaintenanceFunctionalLocationRound; } set { this.OnAssetMaintenanceFunctionalLocationRoundChanging(value); this._AssetMaintenanceFunctionalLocationRound = value; this.OnAssetMaintenanceFunctionalLocationRoundChanged(); this.OnPropertyChanged("AssetMaintenanceFunctionalLocationRound"); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] private global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceFunctionalLocationRound> _AssetMaintenanceFunctionalLocationRound = new global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceFunctionalLocationRound>(null, global::Microsoft.OData.Client.TrackingMode.None); partial void OnAssetMaintenanceFunctionalLocationRoundChanging(global::Microsoft.OData.Client.DataServiceCollection<global::Microsoft.Dynamics.DataEntities.AssetMaintenanceFunctionalLocationRound> value); partial void OnAssetMaintenanceFunctionalLocationRoundChanged(); /// <summary> /// This event is raised when the value of the property is changed /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] public event global::System.ComponentModel.PropertyChangedEventHandler PropertyChanged; /// <summary> /// The value of the property is changed /// </summary> /// <param name="property">property name</param> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.OData.Client.Design.T4", "#VersionNumber#")] protected virtual void OnPropertyChanged(string property) { if ((this.PropertyChanged != null)) { this.PropertyChanged(this, new global::System.ComponentModel.PropertyChangedEventArgs(property)); } } } }
58.966125
387
0.680883
[ "MIT" ]
NathanClouseAX/AAXDataEntityPerfTest
Projects/AAXDataEntityPerfTest/ODataUtility/Connected Services/D365/AssetMaintenanceJobType.cs
43,519
C#
using LanguageExt; using RVis.Base.Extensions; using RVis.Model; using RVis.Model.Extensions; using RVisUI.AppInf; using System; using System.Linq; using System.Reactive.Linq; namespace Sampling { internal sealed partial class ModuleState { private class _ParametersStateDTO { public string? SelectedParameter { get; set; } } private class _SamplesStateDTO { public int? NumberOfSamples { get; set; } public int? Seed { get; set; } public _LatinHypercubeDesignDTO? LatinHypercubeDesign { get; set; } public _RankCorrelationDesignDTO? RankCorrelationDesign { get; set; } } private class _OutputsStateDTO { public string? SelectedOutputName { get; set; } public bool IsSeriesTypeLine { get; set; } public string[]? ObservationsReferences { get; set; } } private class _FilteredSamplesStateDTO { public bool IsEnabled { get; set; } public bool IsUnion { get; set; } } private class _ParameterStateDTO { public string? Name { get; set; } public string? DistributionType { get; set; } public string[]? DistributionStates { get; set; } public bool IsSelected { get; set; } } private class _ModuleStateDTO { public _ParametersStateDTO? ParametersState { get; set; } public _SamplesStateDTO? SamplesState { get; set; } public _OutputsStateDTO? OutputsState { get; set; } public _FilteredSamplesStateDTO? FilteredSamplesStateDTO { get; set; } public _ParameterStateDTO[]? ParameterStates { get; set; } public string? SamplingDesign { get; set; } public string? RootExportDirectory { get; set; } public bool OpenAfterExport { get; set; } public bool? AutoApplyParameterSharedState { get; set; } = false; public bool? AutoShareParameterSharedState { get; set; } = false; public bool? AutoApplyElementSharedState { get; set; } public bool? AutoShareElementSharedState { get; set; } public bool? AutoApplyObservationsSharedState { get; set; } public bool? AutoShareObservationsSharedState { get; set; } } internal static void Save(ModuleState instance, Simulation simulation) { simulation.SavePrivateData( new _ModuleStateDTO { ParametersState = new _ParametersStateDTO { SelectedParameter = instance.ParametersState.SelectedParameter }, SamplesState = new _SamplesStateDTO { NumberOfSamples = instance.SamplesState.NumberOfSamples, Seed = instance.SamplesState.Seed, LatinHypercubeDesign = instance.SamplesState.LatinHypercubeDesign.ToDTO(), RankCorrelationDesign = instance.SamplesState.RankCorrelationDesign.ToDTO() }, OutputsState = new _OutputsStateDTO { SelectedOutputName = instance.OutputsState.SelectedOutputName, IsSeriesTypeLine = instance.OutputsState.IsSeriesTypeLine, ObservationsReferences = instance.OutputsState.ObservationsReferences.ToArray() }, FilteredSamplesStateDTO = new _FilteredSamplesStateDTO { IsEnabled = instance.FilteredSamplesState.IsEnabled, IsUnion = instance.FilteredSamplesState.IsUnion }, ParameterStates = instance.ParameterStates .Map(ps => new _ParameterStateDTO { Name = ps.Name, DistributionType = ps.DistributionType.ToString(), DistributionStates = Distribution.SerializeDistributions(ps.Distributions), IsSelected = ps.IsSelected }) .OrderBy(ps => ps.Name!.ToUpperInvariant()) .ToArray(), SamplingDesign = instance.SamplingDesign?.CreatedOn.ToDirectoryName(), RootExportDirectory = instance.RootExportDirectory, OpenAfterExport = instance.OpenAfterExport, AutoApplyParameterSharedState = instance.AutoApplyParameterSharedState, AutoShareParameterSharedState = instance.AutoShareParameterSharedState, AutoApplyElementSharedState = instance.AutoApplyElementSharedState, AutoShareElementSharedState = instance.AutoShareElementSharedState, AutoApplyObservationsSharedState = instance.AutoApplyObservationsSharedState, AutoShareObservationsSharedState = instance.AutoShareObservationsSharedState }, nameof(Sampling), nameof(ViewModel), nameof(ModuleState) ); } internal static ModuleState LoadOrCreate(Simulation simulation, SamplingDesigns samplingDesigns) { var maybeDTO = simulation.LoadPrivateData<_ModuleStateDTO>( nameof(Sampling), nameof(ViewModel), nameof(ModuleState) ); return maybeDTO.Match( dto => new ModuleState(dto, samplingDesigns), () => new ModuleState(samplingDesigns) ); } private ModuleState(_ModuleStateDTO dto, SamplingDesigns samplingDesigns) { ParametersState.SelectedParameter = dto.ParametersState?.SelectedParameter; SamplesState.NumberOfSamples = dto.SamplesState?.NumberOfSamples; SamplesState.Seed = dto.SamplesState?.Seed; SamplesState.LatinHypercubeDesign = dto.SamplesState?.LatinHypercubeDesign?.FromDTO() ?? default; SamplesState.RankCorrelationDesign = dto.SamplesState?.RankCorrelationDesign?.FromDTO() ?? default; OutputsState.SelectedOutputName = dto.OutputsState?.SelectedOutputName; OutputsState.IsSeriesTypeLine = dto.OutputsState?.IsSeriesTypeLine ?? false; OutputsState.ObservationsReferences = dto.OutputsState?.ObservationsReferences?.ToArr() ?? default; FilteredSamplesState.IsEnabled = dto.FilteredSamplesStateDTO?.IsEnabled ?? false; FilteredSamplesState.IsUnion = dto.FilteredSamplesStateDTO?.IsUnion ?? true; if (!dto.ParameterStates.IsNullOrEmpty()) { _parameterStates = dto.ParameterStates .Select(ps => { var name = ps.Name.AssertNotNull(); var distributionType = Enum.TryParse(ps.DistributionType, out DistributionType dt) ? dt : DistributionType.None; var distributionStates = Distribution.DeserializeDistributions(ps.DistributionStates.AssertNotNull()); var isSelected = ps.IsSelected; return new ParameterState(name, distributionType, distributionStates, isSelected); }) .ToArr(); } if (dto.SamplingDesign.IsAString()) { try { var createdOn = dto.SamplingDesign.FromDirectoryName(); SamplingDesign = samplingDesigns.Load(createdOn); Samples = SamplingDesign.Samples; FilterConfig = samplingDesigns.LoadFilterConfig(SamplingDesign); } catch (Exception) { /* logged elsewhere */ } } RootExportDirectory = dto.RootExportDirectory; OpenAfterExport = dto.OpenAfterExport; _autoApplyParameterSharedState = dto.AutoApplyParameterSharedState; _autoShareParameterSharedState = dto.AutoShareParameterSharedState; _autoApplyElementSharedState = dto.AutoApplyElementSharedState; _autoShareElementSharedState = dto.AutoShareElementSharedState; _autoApplyObservationsSharedState = dto.AutoApplyObservationsSharedState; _autoShareObservationsSharedState = dto.AutoShareObservationsSharedState; } private ModuleState(SamplingDesigns samplingDesigns) : this(new _ModuleStateDTO(), samplingDesigns) { } } }
38.130653
124
0.68951
[ "MIT" ]
GMPtk/RVis
UI/Module/Sampling/State/Impl/ModuleState.cs
7,590
C#
using System.Collections.Generic; using CoolNameGenerator.GA.Chromosomes; using CoolNameGenerator.GA.Populations; namespace CoolNameGenerator.GA.Reinsertions { /// <summary> /// Defines an interface for reinsertions. /// <remarks> /// If less offspring are produced than the min size of the original population then to /// maintain the size of the population, the offspring have to be reinserted /// into the old population. Similarly, if not all offspring are to be used at each /// generation or if more offspring are generated than the max size of the /// population then a reinsertion scheme must be used to determine which individuals are to exist in the new /// population /// <see href="http://usb-bg.org/Bg/Annual_Informatics/2011/SUB-Informatics-2011-4-29-35.pdf"> /// Generalized Nets /// Model of offspring Reinsertion in Genetic Algorithm /// </see> /// </remarks> /// </summary> public interface IReinsertion { #region Methods /// <summary> /// Selects the chromosomes which will be reinserted. /// </summary> /// <returns>The chromosomes to be reinserted in next generation..</returns> /// <param name="population">The population.</param> /// <param name="offspring">The offspring.</param> /// <param name="parents">The parents.</param> IList<IChromosome> SelectChromosomes(IPopulation population, IList<IChromosome> offspring, IList<IChromosome> parents); #endregion #region Properties /// <summary> /// Gets a value indicating whether can collapse the number of selected chromosomes for reinsertion. /// </summary> bool CanCollapse { get; } /// <summary> /// Gets a value indicating whether can expand the number of selected chromosomes for reinsertion. /// </summary> bool CanExpand { get; } #endregion } }
40.134615
120
0.620987
[ "Apache-2.0" ]
Behzadkhosravifar/CoolNameGenerator
src/CoolNameGenerator/GA/Reinsertions/IReinsertion.cs
2,089
C#
namespace HomeAutomation.Protocols.App.v0.Requests.Rooms { [RequestType(0x02, 0x01, 0x00, 0x00)] public class GetAllRoomsDataRequest : ConnectionRequiredRequestBase { } }
25.571429
69
0.776536
[ "MIT" ]
jan-schubert/HomeAutomation
Source/HomeAutomation.Protocols.App/v0/Requests/Rooms/GetAllRoomsDataRequest.cs
181
C#
using System; using System.Collections.Generic; using Android.Runtime; using Java.Interop; namespace Java.IO { // Metadata.xml XPath class reference: path="/api/package[@name='java.io']/class[@name='FilterOutputStream']" [global::Android.Runtime.Register ("java/io/FilterOutputStream", DoNotGenerateAcw=true)] public partial class FilterOutputStream : global::Java.IO.OutputStream { internal static new readonly JniPeerMembers _members = new JniPeerMembers ("java/io/FilterOutputStream", typeof (FilterOutputStream)); internal static new IntPtr class_ref { get { return _members.JniPeerType.PeerReference.Handle; } } public override global::Java.Interop.JniPeerMembers JniPeerMembers { get { return _members; } } protected override IntPtr ThresholdClass { get { return _members.JniPeerType.PeerReference.Handle; } } protected override global::System.Type ThresholdType { get { return _members.ManagedPeerType; } } protected FilterOutputStream (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} // Metadata.xml XPath constructor reference: path="/api/package[@name='java.io']/class[@name='FilterOutputStream']/constructor[@name='FilterOutputStream' and count(parameter)=1 and parameter[1][@type='java.io.OutputStream']]" [Register (".ctor", "(Ljava/io/OutputStream;)V", "")] public unsafe FilterOutputStream (global::System.IO.Stream @out) : base (IntPtr.Zero, JniHandleOwnership.DoNotTransfer) { const string __id = "(Ljava/io/OutputStream;)V"; if (((global::Java.Lang.Object) this).Handle != IntPtr.Zero) return; IntPtr native__out = global::Android.Runtime.OutputStreamAdapter.ToLocalJniHandle (@out); try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue (native__out); var __r = _members.InstanceMethods.StartCreateInstance (__id, ((object) this).GetType (), __args); SetHandle (__r.Handle, JniHandleOwnership.TransferLocalRef); _members.InstanceMethods.FinishCreateInstance (__id, this, __args); } finally { JNIEnv.DeleteLocalRef (native__out); } } static Delegate cb_write_I; #pragma warning disable 0169 static Delegate GetWrite_IHandler () { if (cb_write_I == null) cb_write_I = JNINativeWrapper.CreateDelegate ((Action<IntPtr, IntPtr, int>) n_Write_I); return cb_write_I; } static void n_Write_I (IntPtr jnienv, IntPtr native__this, int oneByte) { global::Java.IO.FilterOutputStream __this = global::Java.Lang.Object.GetObject<global::Java.IO.FilterOutputStream> (jnienv, native__this, JniHandleOwnership.DoNotTransfer); __this.Write (oneByte); } #pragma warning restore 0169 // Metadata.xml XPath method reference: path="/api/package[@name='java.io']/class[@name='FilterOutputStream']/method[@name='write' and count(parameter)=1 and parameter[1][@type='int']]" [Register ("write", "(I)V", "GetWrite_IHandler")] public override unsafe void Write (int oneByte) { const string __id = "write.(I)V"; try { JniArgumentValue* __args = stackalloc JniArgumentValue [1]; __args [0] = new JniArgumentValue (oneByte); _members.InstanceMethods.InvokeVirtualVoidMethod (__id, this, __args); } finally { } } } }
38.023256
227
0.736086
[ "MIT" ]
mattleibow/java.interop
tools/generator/Tests/expected.ji/Streams/Java.IO.FilterOutputStream.cs
3,270
C#
// © 2015 Mario Lelas #define EDITOR_UTILS_INFO #if UNITY_EDITOR using UnityEngine; using UnityEditor; namespace MLSpace { /// <summary> /// control axis information /// </summary> public class InputAxis { public enum AxisType { KeyOrMouseButton = 0, MouseMovement = 1, JoystickAxis = 2 }; public string name; public string descriptiveName; public string descriptiveNegativeName; public string negativeButton; public string positiveButton; public string altNegativeButton; public string altPositiveButton; public float gravity; public float dead; public float sensitivity; public bool snap = false; public bool invert = false; public AxisType type; public int axis; public int joyNum; } /// <summary> /// editor utilities /// </summary> public class EditorUtils { /// <summary> /// add tag /// </summary> /// <param name="tag">tag name</param> public static void AddTag(string tag) { UnityEngine.Object[] asset = AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset"); if ((asset != null) && (asset.Length > 0)) { SerializedObject so = new SerializedObject(asset[0]); SerializedProperty tags = so.FindProperty("tags"); for (int i = 0; i < tags.arraySize; ++i) { if (tags.GetArrayElementAtIndex(i).stringValue == tag) { #if EDITOR_UTILS_INFO Debug.Log("tag "+tag + " already defined"); #endif return; // Tag already present, nothing to do. } } int numTags = tags.arraySize; tags.InsertArrayElementAtIndex(numTags ); tags.GetArrayElementAtIndex(numTags ).stringValue = tag; so.ApplyModifiedProperties(); so.Update(); Debug.Log("tag ' " + tag + "' added at index " + (numTags ) + "."); } } /// <summary> /// set layer at index /// </summary> /// <param name="layer"></param> /// <param name="index"></param> public static void AddLayer(string layer, int index) { UnityEngine.Object[] asset = AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/TagManager.asset"); if ((asset != null) && (asset.Length > 0)) { SerializedObject so = new SerializedObject(asset[0]); SerializedProperty layers = so.FindProperty("layers"); if (layers.GetArrayElementAtIndex(index).stringValue == layer) { #if EDITOR_UTILS_INFO Debug.Log("layer " + layer + " already defined"); #endif return; // layer already present, nothing to do. } layers.InsertArrayElementAtIndex(index); layers.GetArrayElementAtIndex(index).stringValue = layer; so.ApplyModifiedProperties(); so.Update(); Debug.Log("layer ' " + layer + "' added at index " + index + "."); } } /// <summary> /// add input axis /// </summary> /// <param name="axis"></param> public static void AddAxis(InputAxis axis) { if (AxisDefined(axis.name)) { #if EDITOR_UTILS_INFO Debug.Log("axis '" + axis.name + "' already defined."); #endif return; } SerializedObject serializedObject = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/InputManager.asset")[0]); SerializedProperty axesProperty = serializedObject.FindProperty("m_Axes"); axesProperty.arraySize++; serializedObject.ApplyModifiedProperties(); SerializedProperty axisProperty = axesProperty.GetArrayElementAtIndex(axesProperty.arraySize - 1); GetChildProperty(axisProperty, "m_Name").stringValue = axis.name; GetChildProperty(axisProperty, "descriptiveName").stringValue = axis.descriptiveName; GetChildProperty(axisProperty, "descriptiveNegativeName").stringValue = axis.descriptiveNegativeName; GetChildProperty(axisProperty, "negativeButton").stringValue = axis.negativeButton; GetChildProperty(axisProperty, "positiveButton").stringValue = axis.positiveButton; GetChildProperty(axisProperty, "altNegativeButton").stringValue = axis.altNegativeButton; GetChildProperty(axisProperty, "altPositiveButton").stringValue = axis.altPositiveButton; GetChildProperty(axisProperty, "gravity").floatValue = axis.gravity; GetChildProperty(axisProperty, "dead").floatValue = axis.dead; GetChildProperty(axisProperty, "sensitivity").floatValue = axis.sensitivity; GetChildProperty(axisProperty, "snap").boolValue = axis.snap; GetChildProperty(axisProperty, "invert").boolValue = axis.invert; GetChildProperty(axisProperty, "type").intValue = (int)axis.type; GetChildProperty(axisProperty, "axis").intValue = axis.axis - 1; GetChildProperty(axisProperty, "joyNum").intValue = axis.joyNum; serializedObject.ApplyModifiedProperties(); Debug.Log("axis ' " + axis.name + "' added."); } /// <summary> /// get child property /// </summary> /// <param name="parent"></param> /// <param name="name"></param> /// <returns></returns> private static SerializedProperty GetChildProperty(SerializedProperty parent, string name) { SerializedProperty child = parent.Copy(); child.Next(true); do { if (child.name == name) return child; } while (child.Next(false)); return null; } /// <summary> /// is axis already defined ? /// </summary> /// <param name="axisName"></param> /// <returns></returns> private static bool AxisDefined(string axisName) { SerializedObject serializedObject = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/InputManager.asset")[0]); SerializedProperty axesProperty = serializedObject.FindProperty("m_Axes"); axesProperty.Next(true); axesProperty.Next(true); while (axesProperty.Next(false)) { SerializedProperty axis = axesProperty.Copy(); axis.Next(true); if (axis.stringValue == axisName) return true; } return false; } } } #endif
36.06701
145
0.571816
[ "MIT" ]
emirbeyhatun/EnemyCoverSystem
EnemyCoverSystem/Assets/_RagdollManager/Scripts/Editor/EditorUtils.cs
7,000
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // // Microsoft Bot Framework: http://botframework.com // // Bot Builder SDK GitHub: // https://github.com/Microsoft/BotBuilder // // Copyright (c) Microsoft Corporation // All rights reserved. // // MIT License: // 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.Linq; using Microsoft.Bot.Builder.Classic.FormFlow.Advanced; namespace Microsoft.Bot.Builder.Classic.FormFlow { /// <summary> /// Abstract base class for FormFlow attributes. /// </summary> [Serializable] public abstract class FormFlowAttribute : Attribute { /// <summary> /// True if attribute is localizable. /// </summary> /// <remarks> /// Attributes that are used on classes, fields and properties should have this set. /// That way those attributes will be in the localization files that are generated. /// </remarks> public bool IsLocalizable { get; set; } = true; } /// <summary> /// Attribute to override the default description of a field, property or enum value. /// </summary> [Serializable] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Enum | AttributeTargets.Property)] public class DescribeAttribute : FormFlowAttribute { /// <summary> /// Description of the field, property or enum to use in templates and choices. /// </summary> public string Description; /// <summary> /// Title when a card is generated from description. /// </summary> public string Title; /// <summary> /// SubTitle when a card is generated from description. /// </summary> public string SubTitle; /// <summary> /// URL of image to use when creating cards or buttons. /// </summary> public string Image; /// <summary> /// Message to return when a button is pressed in a card. /// </summary> public string Message; /// <summary> /// Description for field, property or enum value. /// </summary> /// <param name="description">Description of field, property or enum value.</param> /// <param name="image">URL of image to use when generating buttons.</param> /// <param name="message">Message to return from button.</param> /// <param name="title">Text if generating card.</param> /// <param name="subTitle">SubTitle if generating card.</param> public DescribeAttribute(string description = null, string image = null, string message = null, string title = null, string subTitle = null) { Description = description; Title = title; SubTitle = subTitle; Image = image; Message = message; } } /// <summary> /// Attribute to override the default terms used to match a field, property or enum value to user input. /// </summary> /// <remarks> /// By default terms are generated by calling the <see cref="Advanced.Language.GenerateTerms(string, int)"/> method with a max phrase length of 3 /// on the name of the field, property or enum value. Using this attribute you can specify your own regular expressions to match or if you specify the /// <see cref="MaxPhrase"/> attribute you can cause <see cref="Advanced.Language.GenerateTerms(string, int)"/> to be called on your strings with the /// maximum phrase length you specify. If your term is a simple alphanumeric one, then it will only be matched on word boundaries with \b unless you start your /// expression with parentheses in which case you control the boundary matching behavior through your regular expression. /// </remarks> [Serializable] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class TermsAttribute : FormFlowAttribute { /// <summary> /// Regular expressions for matching user input. /// </summary> public string[] Alternatives; private int _maxPhrase; /// <summary> /// The maximum pharse length to use when calling <see cref="Advanced.Language.GenerateTerms(string, int)"/> on your supplied terms. /// </summary> public int MaxPhrase { get { return _maxPhrase; } set { _maxPhrase = value; Alternatives = Alternatives.SelectMany(alt => Advanced.Language.GenerateTerms(alt, _maxPhrase)).ToArray(); } } /// <summary> /// Regular expressions or terms used when matching user input. /// </summary> /// <remarks> /// If <see cref="MaxPhrase"/> is specified the supplied alternatives will be passed to <see cref="Advanced.Language.GenerateTerms(string, int)"/> to generate regular expressions /// with a maximum phrase size of <see cref="MaxPhrase"/>. /// </remarks> /// <param name="alternatives">Regular expressions or terms.</param> public TermsAttribute(params string[] alternatives) { Alternatives = alternatives; } } /// <summary> /// Specifies how to show choices generated by {||} in a \ref patterns string. /// </summary> public enum ChoiceStyleOptions { /// <summary> /// Use the default <see cref="TemplateBaseAttribute.ChoiceStyle"/> from the <see cref="FormConfiguration.DefaultPrompt"/>. /// </summary> Default, /// <summary> /// Automatically choose how to render choices. /// </summary> Auto, /// <summary> /// Automatically generate text and switch between the <see cref="Inline"/> and <see cref="PerLine"/> styles based on the number of choices. /// </summary> AutoText, /// <summary> /// Show choices on the same line. /// </summary> Inline, /// <summary> /// Show choices with one per line. /// </summary> PerLine, /// <summary> Show choices on the same line without surrounding parentheses. </summary> InlineNoParen, /// <summary> /// Show choices as buttons if possible. /// </summary> Buttons, /// <summary> /// Show choices as a carousel if possibe. /// </summary> Carousel }; /// <summary> /// How to normalize the case of words. /// </summary> public enum CaseNormalization { /// <summary> /// Use the default from the <see cref="FormConfiguration.DefaultPrompt"/>. /// </summary> Default, /// <summary> /// First letter of each word is capitalized /// </summary> InitialUpper, /// <summary> /// Normalize words to lower case. /// </summary> Lower, /// <summary> /// Normalize words to upper case. /// </summary> Upper, /// <summary> /// Don't normalize words. /// </summary> None }; /// <summary> /// Three state boolean value. /// </summary> /// <remarks> /// This is necessary because C# attributes do not support nullable properties. /// </remarks> public enum BoolDefault { /// <summary> /// Use the default from the <see cref="FormConfiguration.DefaultPrompt"/>. /// </summary> Default, /// <summary> /// Boolean true. /// </summary> True, /// <summary> /// Boolean false. /// </summary> False }; /// <summary> /// Control how the user gets feedback after each entry. /// </summary> public enum FeedbackOptions { /// <summary> /// Use the default from the <see cref="FormConfiguration.DefaultPrompt"/>. /// </summary> Default, /// <summary> /// Provide feedback using the <see cref="TemplateUsage.Feedback"/> template only if part of the user input was not understood. /// </summary> Auto, /// <summary> /// Provide feedback after every user input. /// </summary> Always, /// <summary> /// Never provide feedback. /// </summary> Never }; /// <summary> /// Define the prompt used when asking about a field. /// </summary> /// <remarks> /// Prompts by default will come from \ref Templates. /// This attribute allows you to override this with one more \ref patterns strings. /// The actual prompt will be randomly selected from the alternatives you provide. /// </remarks> [Serializable] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class PromptAttribute : TemplateBaseAttribute { /// <summary> /// Define a prompt with one or more \ref patterns patterns to choose from randomly. /// </summary> /// <param name="patterns">Patterns to select from.</param> public PromptAttribute(params string[] patterns) : base(patterns) { } /// <summary> /// Define a prompt based on a <see cref="TemplateAttribute"/>. /// </summary> /// <param name="pattern">Template to use.</param> public PromptAttribute(TemplateAttribute pattern) : base(pattern) { IsLocalizable = false; } } /// <summary> /// All of the built-in templates. /// </summary> /// <remarks> /// A good way to understand these is to look at the default templates defined in <see cref="FormConfiguration.Templates"/> /// </remarks> public enum TemplateUsage { /// <summary> An enum constant representing the none option. </summary> None, /// <summary> /// How to ask for a boolean. /// </summary> Bool, /// <summary> /// What you can enter when entering a bool. /// </summary> /// <remarks> /// Within this template {0} is the current choice if any and {1} is no preference if optional. /// </remarks> BoolHelp, /// <summary> /// Clarify an ambiguous choice. /// </summary> /// <remarks>This template can use {0} to capture the term that was ambiguous.</remarks> Clarify, /// <summary> /// Default confirmation. /// </summary> Confirmation, /// <summary> /// Show the current choice. /// </summary> /// <remarks> /// This is how the current choice is represented as an option. /// If you change this, you should also change <see cref="FormConfiguration.CurrentChoice"/> /// so that what people can type matches what you show. /// </remarks> CurrentChoice, /// <summary> /// How to ask for a <see cref="DateTime"/>. /// </summary> DateTime, /// <summary> /// What you can enter when entering a <see cref="DateTime"/>. /// </summary> /// <remarks> /// Within this template {0} is the current choice if any and {1} is no preference if optional. /// </remarks> /// <remarks> /// This template can use {0} to get the current choice or {1} for no preference if field is optional. /// </remarks> DateTimeHelp, /// <summary> /// How to ask for a double. /// </summary> /// <remarks> /// Within this template if numerical limits are specified using <see cref="NumericAttribute"/>, /// {0} is the minimum possible value and {1} is the maximum possible value. /// </remarks> Double, /// <summary> /// What you can enter when entering a double. /// </summary> /// <remarks> /// Within this template {0} is the current choice if any and {1} is no preference if optional. /// If limits are specified through <see cref="NumericAttribute"/>, then {2} will be the minimum possible value /// and {3} the maximum possible value. /// </remarks> /// <remarks> /// Within this template, {0} is current choice if any, {1} is no preference for optional and {1} and {2} are min/max if specified. /// </remarks> DoubleHelp, /// <summary> /// What you can enter when selecting a single value from a numbered enumeration. /// </summary> /// <remarks> /// Within this template, {0} is the minimum choice. {1} is the maximum choice and {2} is a description of all the possible words. /// </remarks> EnumOneNumberHelp, /// <summary> /// What you can enter when selecting multiple values from a numbered enumeration. /// </summary> /// <remarks> /// Within this template, {0} is the minimum choice. {1} is the maximum choice and {2} is a description of all the possible words. /// </remarks> EnumManyNumberHelp, /// <summary> /// What you can enter when selecting one value from an enumeration. /// </summary> /// <remarks> /// Within this template, {2} is a list of the possible values. /// </remarks> EnumOneWordHelp, /// <summary> /// What you can enter when selecting mutiple values from an enumeration. /// </summary> /// <remarks> /// Within this template, {2} is a list of the possible values. /// </remarks> EnumManyWordHelp, /// <summary> /// How to ask for one value from an enumeration. /// </summary> EnumSelectOne, /// <summary> /// How to ask for multiple values from an enumeration. /// </summary> EnumSelectMany, /// <summary> /// How to show feedback after user input. /// </summary> /// <remarks> /// Within this template, unmatched input is available through {0}, but it should be wrapped in an optional {?} in \ref patterns in case everything was matched. /// </remarks> Feedback, /// <summary> /// What to display when asked for help. /// </summary> /// <remarks> /// This template controls the overall help experience. {0} will be recognizer specific help and {1} will be command help. /// </remarks> Help, /// <summary> /// What to display when asked for help while clarifying. /// </summary> /// <remarks> /// This template controls the overall help experience. {0} will be recognizer specific help and {1} will be command help. /// </remarks> HelpClarify, /// <summary> /// What to display when asked for help while in a confirmation. /// </summary> /// <remarks> /// This template controls the overall help experience. {0} will be recognizer specific help and {1} will be command help. /// </remarks> HelpConfirm, /// <summary> /// What to display when asked for help while navigating. /// </summary> /// <remarks> /// This template controls the overall help experience. {0} will be recognizer specific help and {1} will be command help. /// </remarks> HelpNavigation, /// <summary> /// How to ask for an integer. /// </summary> /// <remarks> /// Within this template if numerical limits are specified using <see cref="NumericAttribute"/>, /// {0} is the minimum possible value and {1} is the maximum possible value. /// </remarks> Integer, /// <summary> /// What you can enter while entering an integer. /// </summary> /// <remarks> /// Within this template, {0} is current choice if any, {1} is no preference for optional and {1} and {2} are min/max if specified. /// </remarks> IntegerHelp, /// <summary> /// How to ask for a navigation. /// </summary> Navigation, /// <summary> /// Help pattern for navigation commands. /// </summary> /// <remarks> /// Within this template, {0} has the list of possible field names. /// </remarks> NavigationCommandHelp, /// <summary> /// Navigation format for one line in navigation choices. /// </summary> NavigationFormat, /// <summary> /// What you can enter when navigating. /// </summary> /// <remarks> /// Within this template, if numeric choies are allowed {0} is the minimum possible choice /// and {1} the maximum possible choice. /// </remarks> NavigationHelp, /// <summary> /// How to show no preference in an optional field. /// </summary> NoPreference, /// <summary> /// Response when an input is not understood. /// </summary> /// <remarks> /// When no input is matched this template is used and gets {0} for what the user entered. /// </remarks> NotUnderstood, /// <summary> /// Format for one entry in status. /// </summary> StatusFormat, /// <summary> /// How to ask for a string. /// </summary> String, /// <summary> /// What to display when asked for help when entering a string. /// </summary> /// <remarks> /// Within this template {0} is the current choice if any and {1} is no preference if optional. /// </remarks> StringHelp, /// <summary> /// How to represent a value that has not yet been specified. /// </summary> Unspecified }; /// <summary> /// Define a template for generating strings. /// </summary> /// <remarks> /// Templates provide a pattern that uses the template language defined in \ref patterns. See <see cref="TemplateUsage"/> to see a description of all the different kinds of templates. /// You can also look at <see cref="FormConfiguration.Templates"/> to see all the default templates that are provided. Templates can be overriden at the form, class/struct of field level. /// They also support randomly selecting between templates which is a good way to introduce some variation in your responses. /// </remarks> [Serializable] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)] public class TemplateAttribute : TemplateBaseAttribute { /// <summary> /// What kind of template this is. /// </summary> public readonly TemplateUsage Usage; /// <summary> /// Specify a set of templates to randomly choose between for a particular usage. /// </summary> /// <param name="usage">How the template will be used.</param> /// <param name="patterns">The set of \ref patterns to randomly choose from.</param> public TemplateAttribute(TemplateUsage usage, params string[] patterns) : base(patterns) { Usage = usage; } #region Documentation /// <summary> Initialize from another template. </summary> /// <param name="other"> The other template. </param> #endregion public TemplateAttribute(TemplateAttribute other) : base(other) { Usage = other.Usage; } } /// <summary> /// Define a field or property as optional. /// </summary> /// <remarks> /// An optional field is one where having no value is an acceptable response. By default every field is considered required and must be filled in to complete the form. /// </remarks> [Serializable] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class OptionalAttribute : Attribute { /// <summary> /// Mark a field or property as optional. /// </summary> public OptionalAttribute() { } } /// <summary> /// Provide limits on the possible values in a numeric field or property. /// </summary> /// <remarks> /// By default the limits are the min and max of the underlying field type. /// </remarks> [Serializable] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class NumericAttribute : Attribute { /// <summary> /// Min possible value. /// </summary> public readonly double Min; /// <summary> /// Max possible value. /// </summary> public readonly double Max; /// <summary> /// Specify the range of possible values for a number field. /// </summary> /// <param name="min">Min value allowed.</param> /// <param name="max">Max value allowed.</param> public NumericAttribute(double min, double max) { Min = min; Max = max; } } /// <summary> /// Provide a regular expression to validate a string field. /// </summary> /// <remarks> /// If the regular expression is not matched the <see cref="TemplateUsage.NotUnderstood"/> template will be used for feedback. /// </remarks> [Serializable] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class PatternAttribute : Attribute { public readonly string Pattern; /// <summary> /// Regular expression for validating the content of a string field. /// </summary> /// <param name="pattern">Regular expression for validation.</param> public PatternAttribute(string pattern) { Pattern = pattern; } } /// <summary> /// Define a field or property as excluded. /// </summary> /// <remarks> /// The ignored field is a field that is excluded from the list of fields. /// </remarks> [Serializable] [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)] public class IgnoreFieldAttribute : Attribute { /// <summary> /// Mark a field or property as excluded. /// </summary> public IgnoreFieldAttribute() { } } } namespace Microsoft.Bot.Builder.Classic.FormFlow.Advanced { /// <summary> /// Abstract base class used by all attributes that use \ref patterns. /// </summary> public abstract class TemplateBaseAttribute : FormFlowAttribute { private static Random _generator = new Random(); /// <summary> /// When processing choices {||} in a \ref patterns string, provide a choice for the default value if present. /// </summary> public BoolDefault AllowDefault { get; set; } /// <summary> /// Control case when showing choices in {||} references in a \ref patterns string. /// </summary> public CaseNormalization ChoiceCase { get; set; } /// <summary> /// Format string used for presenting each choice when showing {||} choices in a \ref patterns string. /// </summary> /// <remarks>The choice format is passed two arguments, {0} is the number of the choice and {1} is the field name.</remarks> public string ChoiceFormat { get; set; } /// <summary> /// When constructing inline lists of choices using {||} in a \ref patterns string, the string used before the last choice. /// </summary> public string ChoiceLastSeparator { get; set; } /// <summary> /// When constructing inline choice lists for {||} in a \ref patterns string controls whether to include parentheses around choices. /// </summary> public BoolDefault ChoiceParens { get; set; } /// <summary> /// When constructing inline lists using {||} in a \ref patterns string, the string used between all choices except the last. /// </summary> public string ChoiceSeparator { get; set; } /// <summary> /// How to display choices {||} when processed in a \ref patterns string. /// </summary> public ChoiceStyleOptions ChoiceStyle { get; set; } /// <summary> /// Control what kind of feedback the user gets after each input. /// </summary> public FeedbackOptions Feedback { get; set; } /// <summary> /// Control case when showing {&amp;} field name references in a \ref patterns string. /// </summary> public CaseNormalization FieldCase { get; set; } /// <summary> /// When constructing lists using {[]} in a \ref patterns string, the string used before the last value in the list. /// </summary> public string LastSeparator { get; set; } /// <summary> /// When constructing lists using {[]} in a \ref patterns string, the string used between all values except the last. /// </summary> public string Separator { get; set; } /// <summary> /// Control case when showing {} value references in a \ref patterns string. /// </summary> public CaseNormalization ValueCase { get; set; } internal bool AllowNumbers { get { // You can match on numbers only if they are included in Choices and choices are shown return ChoiceFormat.Contains("{0}") && Patterns.Any((pattern) => pattern.Contains("{||}")); } } /// <summary> /// The pattern to use when generating a string using <see cref="Advanced.IPrompt{T}"/>. /// </summary> /// <remarks>If multiple patterns were specified, then each call to this function will return a random pattern.</remarks> /// <returns>Pattern to use.</returns> public string Pattern() { var choice = 0; if (Patterns.Length > 1) { lock (_generator) { choice = _generator.Next(Patterns.Length); } } return Patterns[choice]; } /// <summary> /// All possible templates. /// </summary> /// <returns>The possible templates.</returns> public string[] Patterns { get; set; } /// <summary> /// Any default values in this template will be overridden by the supplied <paramref name="defaultTemplate"/>. /// </summary> /// <param name="defaultTemplate">Default template to use to override default values.</param> public void ApplyDefaults(TemplateBaseAttribute defaultTemplate) { if (AllowDefault == BoolDefault.Default) AllowDefault = defaultTemplate.AllowDefault; if (ChoiceCase == CaseNormalization.Default) ChoiceCase = defaultTemplate.ChoiceCase; if (ChoiceFormat == null) ChoiceFormat = defaultTemplate.ChoiceFormat; if (ChoiceLastSeparator == null) ChoiceLastSeparator = defaultTemplate.ChoiceLastSeparator; if (ChoiceParens == BoolDefault.Default) ChoiceParens = defaultTemplate.ChoiceParens; if (ChoiceSeparator == null) ChoiceSeparator = defaultTemplate.ChoiceSeparator; if (ChoiceStyle == ChoiceStyleOptions.Default) ChoiceStyle = defaultTemplate.ChoiceStyle; if (FieldCase == CaseNormalization.Default) FieldCase = defaultTemplate.FieldCase; if (Feedback == FeedbackOptions.Default) Feedback = defaultTemplate.Feedback; if (LastSeparator == null) LastSeparator = defaultTemplate.LastSeparator; if (Separator == null) Separator = defaultTemplate.Separator; if (ValueCase == CaseNormalization.Default) ValueCase = defaultTemplate.ValueCase; } /// <summary> /// Initialize with multiple patterns that will be chosen from randomly. /// </summary> /// <param name="patterns">Possible patterns.</param> public TemplateBaseAttribute(params string[] patterns) { Patterns = patterns; Initialize(); } /// <summary> /// Initialize from another template. /// </summary> /// <param name="other">The template to copy from.</param> public TemplateBaseAttribute(TemplateBaseAttribute other) { Patterns = other.Patterns; AllowDefault = other.AllowDefault; ChoiceCase = other.ChoiceCase; ChoiceFormat = other.ChoiceFormat; ChoiceLastSeparator = other.ChoiceLastSeparator; ChoiceParens = other.ChoiceParens; ChoiceSeparator = other.ChoiceSeparator; ChoiceStyle = other.ChoiceStyle; FieldCase = other.FieldCase; Feedback = other.Feedback; LastSeparator = other.LastSeparator; Separator = other.Separator; ValueCase = other.ValueCase; } private void Initialize() { AllowDefault = BoolDefault.Default; ChoiceCase = CaseNormalization.Default; ChoiceFormat = null; ChoiceLastSeparator = null; ChoiceParens = BoolDefault.Default; ChoiceSeparator = null; ChoiceStyle = ChoiceStyleOptions.Default; FieldCase = CaseNormalization.Default; Feedback = FeedbackOptions.Default; LastSeparator = null; Separator = null; ValueCase = CaseNormalization.Default; } } }
36.221187
194
0.587388
[ "MIT" ]
DeeJayTC/botbuilder-dotnet
libraries/Microsoft.Bot.Builder.Classic/Microsoft.Bot.Builder.Classic/FormFlow/Attributes.cs
31,116
C#
/* _BEGIN_TEMPLATE_ { "id": "DRGA_BOSS_33t", "name": [ "达拉燃烧弹", "DALA-SMASH!!" ], "text": [ "对所有随从造成$10点伤害,再对所有随从造成$5点伤害。", "Deal $10 damage to all minions, then deal $5 damage to all minions." ], "cardClass": "NEUTRAL", "type": "SPELL", "cost": 0, "rarity": null, "set": "YEAR_OF_THE_DRAGON", "collectible": null, "dbfId": 58350 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_DRGA_BOSS_33t : SimTemplate { } }
17.481481
73
0.597458
[ "MIT" ]
chi-rei-den/Silverfish
cards/YEAR_OF_THE_DRAGON/DRGA/Sim_DRGA_BOSS_33t.cs
528
C#
using UnityEngine.EventSystems; using UnityEngine; public class SprintButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler { public void OnPointerDown(PointerEventData eventData) { PlayerController.isSprinting = true; } public void OnPointerUp(PointerEventData eventData) { PlayerController.isSprinting = false; } }
23.0625
81
0.739837
[ "MIT" ]
jeremiahbaclig/Goby
Assets/Scripts/SprintButton.cs
371
C#
namespace Jane.ObjectMapping { /// <summary> /// Defines a simple interface to map objects. /// </summary> public interface IObjectMapper { /// <summary> /// Converts an object to another. Creates a new object of <see cref="TDestination"/>. /// </summary> /// <typeparam name="TDestination">Type of the destination object</typeparam> /// <param name="source">Source object</param> TDestination Map<TDestination>(object source); /// <summary> /// Execute a mapping from the source object to the existing destination object /// </summary> /// <typeparam name="TSource">Source type</typeparam> /// <typeparam name="TDestination">Destination type</typeparam> /// <param name="source">Source object</param> /// <param name="destination">Destination object</param> /// <returns>Returns the same <see cref="destination"/> object after mapping operation</returns> TDestination Map<TSource, TDestination>(TSource source, TDestination destination); } }
43.52
104
0.637868
[ "Apache-2.0" ]
Caskia/Jane
src/Jane/ObjectMapping/IObjectMapper.cs
1,090
C#
using System; using System.Collections; using System.Collections.Generic; namespace g3 { public class MeshConnectedComponents : IEnumerable<MeshConnectedComponents.Component> { public DMesh3 Mesh; // if a Filter is set, only triangles contained in Filter are // considered. Both filters will be applied if available. public IEnumerable<int> FilterSet = null; public Func<int, bool> FilterF = null; // filter on seed values for region-growing. This can be useful // to restrict components to certain areas, when you don't want // (or don't know) a full-triangle-set filter public Func<int, bool> SeedFilterF = null; public struct Component { public int[] Indices; } public List<Component> Components; public MeshConnectedComponents(DMesh3 mesh) { Mesh = mesh; Components = new List<Component>(); } public int Count { get { return Components.Count; } } public Component this[int index] { get { return Components[index]; } } public IEnumerator<Component> GetEnumerator() { return Components.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return Components.GetEnumerator(); } public int LargestByCount { get { int largest_i = 0; int largest_count = Components[largest_i].Indices.Length; for (int i = 1; i < Components.Count; ++i) { if (Components[i].Indices.Length > largest_count) { largest_count = Components[i].Indices.Length; largest_i = i; } } return largest_i; } } public void SortByCount(bool bIncreasing = true) { if (bIncreasing) { Components.Sort((x, y) => { return x.Indices.Length.CompareTo(y.Indices.Length); }); } else { Components.Sort((x, y) => { return -x.Indices.Length.CompareTo(y.Indices.Length); }); } } /// <summary> /// Evaluate valueF for each component and sort by that /// </summary> public void SortByValue(Func<Component, double> valueF, bool bIncreasing = true) { var vals = new Dictionary<Component, double>(); foreach (Component c in Components) { vals[c] = valueF(c); } if (bIncreasing) { Components.Sort((x, y) => { return vals[x].CompareTo(vals[y]); }); } else { Components.Sort((x, y) => { return -vals[x].CompareTo(vals[y]); }); } } public void FindConnectedT() { Components = new List<Component>(); int NT = Mesh.MaxTriangleID; // [TODO] could use Euler formula to determine if mesh is closed genus-0... Func<int, bool> filter_func = (i) => { return Mesh.IsTriangle(i); }; if (FilterF != null) { filter_func = (i) => { return Mesh.IsTriangle(i) && FilterF(i); }; } // initial active set contains all valid triangles byte[] active = new byte[Mesh.MaxTriangleID]; Interval1i activeRange = Interval1i.Empty; if (FilterSet != null) { for (int i = 0; i < NT; ++i) { active[i] = 255; } foreach (int tid in FilterSet) { bool bValid = filter_func(tid); if (bValid) { active[tid] = 0; activeRange.Contain(tid); } } } else { for (int i = 0; i < NT; ++i) { bool bValid = filter_func(i); if (bValid) { active[i] = 0; activeRange.Contain(i); } else { active[i] = 255; } } } // temporary buffers var queue = new List<int>(NT / 10); var cur_comp = new List<int>(NT / 10); // keep finding valid seed triangles and growing connected components // until we are done IEnumerable<int> range = (FilterSet != null) ? FilterSet : activeRange; foreach (int i in range) { //for ( int i = 0; i < NT; ++i ) { if (active[i] == 255) { continue; } int seed_t = i; if (SeedFilterF != null && SeedFilterF(seed_t) == false) { continue; } queue.Add(seed_t); active[seed_t] = 1; // in queue while (queue.Count > 0) { int cur_t = queue[queue.Count - 1]; queue.RemoveAt(queue.Count - 1); active[cur_t] = 2; // tri has been processed cur_comp.Add(cur_t); Index3i nbrs = Mesh.GetTriNeighbourTris(cur_t); for (int j = 0; j < 3; ++j) { int nbr_t = nbrs[j]; if (nbr_t != DMesh3.InvalidID && active[nbr_t] == 0) { queue.Add(nbr_t); active[nbr_t] = 1; // in queue } } } var comp = new Component() { Indices = cur_comp.ToArray() }; Components.Add(comp); // remove tris in this component from active set for (int j = 0; j < comp.Indices.Length; ++j) { active[comp.Indices[j]] = 255; } cur_comp.Clear(); queue.Clear(); } } /// <summary> /// Separate input mesh into disconnected shells. /// Resulting array is sorted by decreasing triangle count. /// </summary> public static DMesh3[] Separate(DMesh3 meshIn) { var c = new MeshConnectedComponents(meshIn); c.FindConnectedT(); c.SortByCount(false); var result = new DMesh3[c.Components.Count]; int ri = 0; foreach (Component comp in c.Components) { var submesh = new DSubmesh3(meshIn, comp.Indices); result[ri++] = submesh.SubMesh; } return result; } /// <summary> /// extract largest shell of meshIn /// </summary> public static DMesh3 LargestT(DMesh3 meshIn) { var c = new MeshConnectedComponents(meshIn); c.FindConnectedT(); c.SortByCount(false); var submesh = new DSubmesh3(meshIn, c.Components[0].Indices); return submesh.SubMesh; } /// <summary> /// Utility function that finds set of triangles connected to tSeed. Does not use MeshConnectedComponents class. /// </summary> public static HashSet<int> FindConnectedT(DMesh3 mesh, int tSeed) { var found = new HashSet<int>(); found.Add(tSeed); var queue = new List<int>(64) { tSeed }; while (queue.Count > 0) { int tid = queue[queue.Count - 1]; queue.RemoveAt(queue.Count - 1); Index3i nbr_t = mesh.GetTriNeighbourTris(tid); for (int j = 0; j < 3; ++j) { int nbrid = nbr_t[j]; if (nbrid == DMesh3.InvalidID || found.Contains(nbrid)) { continue; } found.Add(nbrid); queue.Add(nbrid); } } return found; } } }
20.827815
114
0.60461
[ "BSD-2-Clause" ]
595787816/agg-sharp
geometry3Sharp/mesh_selection/MeshConnectedComponents.cs
6,292
C#
using System; using System.Collections.Generic; using System.Text; namespace SkyDCore.Log { /// <summary> /// 不含脚本的HTML日志 /// </summary> public class HtmlLogLayoutNoScript : HtmlLogLayout { protected override string _Script => String.Empty; } }
18.6
58
0.666667
[ "Apache-2.0" ]
manasheep/SkyDCore
SkyDCore.Log/HtmlLogLayoutNoScript.cs
295
C#
using AppStudio.Services; using AppStudio.ViewModels; using Windows.ApplicationModel.DataTransfer; using Windows.UI.Core; using Windows.UI.ViewManagement; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace AppStudio.Views { public sealed partial class RssDetail : Page { private NavigationHelper _navigationHelper; private DataTransferManager _dataTransferManager; public RssDetail() { this.InitializeComponent(); _navigationHelper = new NavigationHelper(this); SizeChanged += OnSizeChanged; RssModel = new RssViewModel(); } public RssViewModel RssModel { get; private set; } public NavigationHelper NavigationHelper { get { return _navigationHelper; } } private void OnSizeChanged(object sender, SizeChangedEventArgs e) { if (e.NewSize.Width < 500) { VisualStateManager.GoToState(this, "SnappedView", true); } else if (e.NewSize.Width < e.NewSize.Height) { VisualStateManager.GoToState(this, "PortraitView", true); } else { VisualStateManager.GoToState(this, "FullscreenView", true); } } protected override async void OnNavigatedTo(NavigationEventArgs e) { _dataTransferManager = DataTransferManager.GetForCurrentView(); _dataTransferManager.DataRequested += OnDataRequested; _navigationHelper.OnNavigatedTo(e); if (RssModel != null) { await RssModel.LoadItemsAsync(); RssModel.SelectItem(e.Parameter); RssModel.ViewType = ViewTypes.Detail; } DataContext = this; } protected override void OnNavigatedFrom(NavigationEventArgs e) { _navigationHelper.OnNavigatedFrom(e); _dataTransferManager.DataRequested -= OnDataRequested; } private void OnDataRequested(DataTransferManager sender, DataRequestedEventArgs args) { if (RssModel != null) { RssModel.GetShareContent(args.Request); } } } }
28.337349
93
0.596514
[ "MIT" ]
SangramChavan/IEEE-Connected-Learning-Win-8.1
AppStudio.Windows/Views/RssDetailPage.xaml.cs
2,352
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hoops.Core.Enum { public static class GroupTypes { public enum GroupType { BoardMember = 0, SeasonCandidateOnly = 1, SeasonPlayers = 2, CoachesSponsors = 3, AllMembers = 4 }; public enum GameTypes { Regular = 0, Playoff = 1}; } }
25.733333
131
0.702073
[ "MIT" ]
rsalit1516/Hoops
Hoops.Core/Enum/GroupTypes.cs
388
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.DataFactory.V20180601.Inputs { /// <summary> /// Azure ML Studio Web Service linked service. /// </summary> public sealed class AzureMLLinkedServiceArgs : Pulumi.ResourceArgs { [Input("annotations")] private InputList<object>? _annotations; /// <summary> /// List of tags that can be used for describing the linked service. /// </summary> public InputList<object> Annotations { get => _annotations ?? (_annotations = new InputList<object>()); set => _annotations = value; } /// <summary> /// The API key for accessing the Azure ML model endpoint. /// </summary> [Input("apiKey", required: true)] public InputUnion<Inputs.AzureKeyVaultSecretReferenceArgs, Inputs.SecureStringArgs> ApiKey { get; set; } = null!; /// <summary> /// Type of authentication (Required to specify MSI) used to connect to AzureML. Type: string (or Expression with resultType string). /// </summary> [Input("authentication")] public Input<object>? Authentication { get; set; } /// <summary> /// The integration runtime reference. /// </summary> [Input("connectVia")] public Input<Inputs.IntegrationRuntimeReferenceArgs>? ConnectVia { get; set; } /// <summary> /// Linked service description. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The encrypted credential used for authentication. Credentials are encrypted using the integration runtime credential manager. Type: string (or Expression with resultType string). /// </summary> [Input("encryptedCredential")] public Input<object>? EncryptedCredential { get; set; } /// <summary> /// The Batch Execution REST URL for an Azure ML Studio Web Service endpoint. Type: string (or Expression with resultType string). /// </summary> [Input("mlEndpoint", required: true)] public Input<object> MlEndpoint { get; set; } = null!; [Input("parameters")] private InputMap<Inputs.ParameterSpecificationArgs>? _parameters; /// <summary> /// Parameters for linked service. /// </summary> public InputMap<Inputs.ParameterSpecificationArgs> Parameters { get => _parameters ?? (_parameters = new InputMap<Inputs.ParameterSpecificationArgs>()); set => _parameters = value; } /// <summary> /// The ID of the service principal used to authenticate against the ARM-based updateResourceEndpoint of an Azure ML Studio web service. Type: string (or Expression with resultType string). /// </summary> [Input("servicePrincipalId")] public Input<object>? ServicePrincipalId { get; set; } /// <summary> /// The key of the service principal used to authenticate against the ARM-based updateResourceEndpoint of an Azure ML Studio web service. /// </summary> [Input("servicePrincipalKey")] public InputUnion<Inputs.AzureKeyVaultSecretReferenceArgs, Inputs.SecureStringArgs>? ServicePrincipalKey { get; set; } /// <summary> /// The name or ID of the tenant to which the service principal belongs. Type: string (or Expression with resultType string). /// </summary> [Input("tenant")] public Input<object>? Tenant { get; set; } /// <summary> /// Type of linked service. /// Expected value is 'AzureML'. /// </summary> [Input("type", required: true)] public Input<string> Type { get; set; } = null!; /// <summary> /// The Update Resource REST URL for an Azure ML Studio Web Service endpoint. Type: string (or Expression with resultType string). /// </summary> [Input("updateResourceEndpoint")] public Input<object>? UpdateResourceEndpoint { get; set; } public AzureMLLinkedServiceArgs() { } } }
39.096491
197
0.624187
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/DataFactory/V20180601/Inputs/AzureMLLinkedServiceArgs.cs
4,457
C#
//----------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //----------------------------------------------------------------------- using System.Collections.Generic; namespace HR.TA.Common.Email { /// <summary> /// Class to encapsulate all the constants. /// </summary> public static class Constants { /// <summary>Prefix for EmailSubjectTemplate Resource</summary> public const string EmailSubjectTemplateResourcePrefix = "EmailSubjectTemplate_"; /// <summary>Prefix for EmailMessageTemplate Resource</summary> public const string EmailMessageTemplateResourcePrefix = "EmailMessageTemplate_"; /// <summary>SendGrid Url</summary> public const string SendGridUrl = "https://api.sendgrid.com/"; /// <summary>SendGrid Key Token Secret Name</summary> public const string SendGridApiKeyTokenSecretName = "SendGridApiKeyToken"; /// <summary>Email Send Rest Endpoint</summary> public const string SendGridEmailSendEndpoint = "v3/mail/send"; /// <summary>Email Footer Field Name.</summary> public const string EmailFooterFieldName = "EmailFooterPrivateField"; /// <summary>Limit of Characters in an email message.</summary> public const int EmailMessageLengthLimitInCharacters = 20000; /// <summary>Limit of Characters in an email Subject.</summary> public const int EmailSubjectLengthLimitInCharacters = 1000; /// <summary>Limit on the email addresses one can send emails to.</summary> public const int EmailLimitOnToAddresses = 25; /// <summary>Limit on the number of attachments in an email.</summary> public const int EmailLimitOnNumberOfAttachments = 15; /// <summary>Limit on the number of headers in an email.</summary> public const int EmailLimitOnNumberOfHeaders = 20; /// <summary>Limit on the size of each attachment.</summary> public const int EmailLimitOnSizeOfAttachmentsInKB = 1024; /// <summary>Number of bytes in one KiloByte.</summary> public const int KiloBytes = 1024; /// <summary>Email At Char.</summary> public const string EmailAtCharacter = "@"; public const string GraphSendMailUrl = "https://graph.microsoft.com/v1.0/me/sendMail"; public const string EmailContentType = "html"; /// <summary> /// Default Email alias from where the email should be sent from. /// Set to Internal because we don't want the other services to access it. /// </summary> internal const string DefaultEmailAliasToSendFrom = "No-reply"; /// <summary> /// Default Name of Email from where the email should be sent from. /// Set to Internal because we don't want the other services to access it. /// </summary> internal const string DefaultEmailNameToSendFrom = "Dynamics 365 for Talent"; /// <summary>Too many requests status code</summary> public const int TooManyRequestCode = 429; /// <summary>Max Retry Count for request</summary> public const int MaxRetryCount = 3; public static readonly string Candidate = "Candidate"; public static readonly string Interviewer = "Interviewer"; public static readonly string Scheduler = "Scheduler"; public static readonly string Approver = "Approver"; public static readonly string ApprovalRequester = "ApprovalRequester"; public static readonly string OfferApprover = "OfferApprover"; public static readonly string HiringManager = "HiringManager"; public static readonly string Recruiter = "Recruiter"; public static readonly string OfferCreator = "OfferCreator"; public static readonly string Contributor = "Contributor"; public static readonly string Unknown = "Unknown"; public static readonly Dictionary<string, string> TemplateTypeRecipientMap = new Dictionary<string, string>() { { "CandidateInterview", Candidate }, { "CandidateInvite", Candidate }, { "CandidateAvailability", Candidate }, { "InterviewerMeeting", Interviewer }, { "InterviewerSummary", Interviewer }, { "InterviewerMeetingReminder", Interviewer }, { "InterviewerFeedbackReminder", Interviewer }, { "ReviewActivitiesTemplate", Candidate }, { "OfferNotificationTemplate", Unknown }, //// Not in Attract Client { "NewCandidateScheduler", Contributor }, { "NotifySchedulerAcceptDecline", Scheduler }, { "RequestForFeedback", Interviewer }, { "RoomDeclineReminder", Scheduler }, { "PendingDeclinedResponseReminder", Scheduler }, { "ProspectCandidateApplyInvite", Candidate }, //// Not in Attract Client { "InterviewInvitationFailed", Scheduler }, { "RequestForJobApproval", Approver }, { "NotifyJobApprovedToRequester", ApprovalRequester }, { "NotifyJobDeniedToRequester", ApprovalRequester }, { "RequestOfferApproval", OfferApprover }, { "NotifyOfferApproved", ApprovalRequester }, //// Not in Attract Client { "NotifyOfferRejected", ApprovalRequester }, //// Not in Attract Client { "NotifyOfferPublishedToCandidate", Candidate }, { "NotifyOfferWithdraw", Candidate }, { "OfferExpiryReminder", Candidate }, { "NotifyOfferDeclinedToRecruiter", Recruiter }, { "NotifyOfferDeclinedToHiringManager", HiringManager }, { "NotifyOfferAcceptedToRecruiter", Recruiter }, { "NotifyOfferAcceptedToHiringManager", HiringManager }, { "NotifyOfferExpired", Candidate }, { "NotifyOfferApprovalToOfferCreator", OfferCreator }, { "NotifyOfferRejectionToOfferCreator", OfferCreator }, { "NotifyOfferCloseToRecruiter", Recruiter }, { "NotifyOfferCloseToHiringManager", HiringManager }, { "CandidateLoginFailed", Candidate }, { "CandidateLoginInformation", Candidate }, //// Not in Attract Client { "RequestForJobApprovalReminder", Approver }, { "NotifyApplicationRejectedToCandidate", Candidate }, { "InviteProspectToApply", Candidate }, }; /// <summary>The company name</summary> public const string CompanyName = "Microsoft"; } }
48.558824
117
0.642641
[ "MIT" ]
QPC-database/msrecruit-scheduling-engine
common/HR.TA.CommonLibrary/HR.TA.Common/Common/Common.Email/Constants.cs
6,604
C#
using IotHub.Core.Cqrs; using IotHub.Core.Redis; using Newtonsoft.Json; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Threading; namespace IotHub.Core.CqrsEngine { public static class EngineeCommandWorkerQueue { //in-memory queue, can be use redis queue, rabitmq ... // remember dispatched by type of command static readonly ConcurrentDictionary<string, ConcurrentQueue<ICommand>> _cmdDataQueue = new ConcurrentDictionary<string, ConcurrentQueue<ICommand>>(); static readonly ConcurrentDictionary<string, List<Thread>> _cmdWorker = new ConcurrentDictionary<string, List<Thread>>(); static readonly ConcurrentDictionary<string, bool> _stopWorker = new ConcurrentDictionary<string, bool>(); static readonly ConcurrentDictionary<string, int> _workerCounterStoped = new ConcurrentDictionary<string, int>(); static readonly ConcurrentDictionary<string, bool> _workerStoped = new ConcurrentDictionary<string, bool>(); static readonly ConcurrentDictionary<string, Type> _cmdTypeName = new ConcurrentDictionary<string, Type>(); static readonly object _locker = new object(); static readonly string ListCommandTypeNameRedisKey = "EngineeCommandWorkerQueue_ListCommandTypeName"; internal static void Push(ICommand cmd) { var type = cmd.GetType().FullName; _cmdTypeName[type] = cmd.GetType(); if (RedisServices.IsEnable) { var queueName = BuildRedisQueueName(type); RedisServices.RedisDatabase.HashSet(ListCommandTypeNameRedisKey, queueName, queueName); if (RedisServices.RedisDatabase.KeyExists(queueName)) { RedisServices.RedisDatabase .ListLeftPush(queueName, JsonConvert.SerializeObject(cmd)); } else { RedisServices.RedisDatabase .ListLeftPush(queueName, JsonConvert.SerializeObject(cmd)); InitFirstWorker(type); } } else { if (_cmdDataQueue.ContainsKey(type) && _cmdDataQueue[type] != null) { //in-memory queue, can be use redis queue, rabitmq ... _cmdDataQueue[type].Enqueue(cmd); } else { //in-memory queue, can be use redis queue, rabitmq ... _cmdDataQueue[type] = new ConcurrentQueue<ICommand>(); _cmdDataQueue[type].Enqueue(cmd); InitFirstWorker(type); } } } private static string BuildRedisQueueName(string type) { return "EngineeCommandWorkerQueue_" + type; } private static void InitFirstWorker(string type) { while (_stopWorker.ContainsKey(type) && _stopWorker[type]) { Thread.Sleep(100); //wait stopping } lock (_locker) { if (!_cmdWorker.ContainsKey(type) || _cmdWorker[type] == null || _cmdWorker[type].Count == 0) { _stopWorker[type] = false; _workerCounterStoped[type] = 0; _workerStoped[type] = false; _cmdWorker[type] = new List<Thread>(); } var firstThread = new Thread(() => { WorkerDo(type); }); _cmdWorker[type].Add(firstThread); firstThread.Start(); } } static EngineeCommandWorkerQueue() { } static void WorkerDo(string type) { while (true) { try { while (_stopWorker.ContainsKey(type) == false || _stopWorker[type] == false) { try { var canDequeue = CommandsAndEventsRegisterEngine.CommandWorkerCanDequeue(type); if (!canDequeue) { Thread.Sleep(100); continue; } if (RedisServices.IsEnable) { var queueName = BuildRedisQueueName(type); var typeRegistered = CommandsAndEventsRegisterEngine.FindTypeOfCommandOrEvent(type); var cmdJson = RedisServices.RedisDatabase .ListRightPop(queueName); if (cmdJson.HasValue) { var cmd = JsonConvert.DeserializeObject(cmdJson, typeRegistered) as ICommand; if (cmd != null) { try { CommandsAndEventsRegisterEngine.ExecCommand(cmd); } catch (Exception ex) { Console.WriteLine(ex.Message); RedisServices.RedisDatabase .ListLeftPush(queueName, cmdJson); } } else { RedisServices.RedisDatabase .ListLeftPush(queueName, cmdJson); } } } else { if (_cmdDataQueue.TryGetValue(type, out ConcurrentQueue<ICommand> cmdQueue) && cmdQueue != null) { //in-memory queue, can be use redis queue, rabitmq ... if (cmdQueue.TryDequeue(out ICommand cmd) && cmd != null) { CommandsAndEventsRegisterEngine.ExecCommand(cmd); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { Thread.Sleep(100); } } if (!_workerCounterStoped.ContainsKey(type)) { _workerCounterStoped[type] = 0; } if (_workerStoped[type] == false) { var counter = _workerCounterStoped[type]; counter++; _workerCounterStoped[type] = counter; lock (_locker) { if (_cmdWorker.TryGetValue(type, out List<Thread> listThread)) { if (listThread.Count == counter) { _workerStoped[type] = true; _workerCounterStoped[type] = 0; } } } } } finally { Thread.Sleep(100); } } } /// <summary> /// reset thread to one. each command have one thread to process /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool ResetToOneWorker(string type) { _stopWorker[type] = true; while (!_workerStoped.ContainsKey(type) || _workerStoped[type] == false) { Thread.Sleep(100); //wait all worker done its job } //List<Thread> threads; //if (_cmdWorker.TryGetValue(type, out threads)) //{ // foreach (var t in threads) // { // try // { // t.Abort(); // } // catch { } // } //} _workerCounterStoped[type] = 0; _workerStoped[type] = false; _cmdWorker[type].Clear(); _stopWorker[type] = false; InitFirstWorker(type); return true; } public static bool AddAndStartWorker(string type) { if (!_cmdWorker.ContainsKey(type) || _cmdWorker[type] == null || _cmdWorker[type].Count == 0) { InitFirstWorker(type); } else { lock (_locker) { _workerStoped[type] = false; var thread = new Thread(() => WorkerDo(type)); _cmdWorker[type].Add(thread); thread.Start(); } } return true; } public static void CountStatistic(string type, out int queueDataCount, out int workerCount) { queueDataCount = 0; workerCount = 0; if (_cmdWorker.TryGetValue(type, out List<Thread> list) && list != null) { workerCount = list.Count; } if (RedisServices.IsEnable) { var queueName = BuildRedisQueueName(type); queueDataCount = (int)RedisServices.RedisDatabase.ListLength(queueName); } else { if (_cmdDataQueue.TryGetValue(type, out ConcurrentQueue<ICommand> queue) && queue != null) { queueDataCount = queue.Count; } } } public static bool IsWorkerStopping(string type) { bool val; if (_stopWorker.TryGetValue(type, out val)) { return val; } return false; } public static void Start() { var listCmd = CommandsAndEventsRegisterEngine._commandsEvents.Values .Where(i => typeof(ICommand).IsAssignableFrom(i)).ToList(); foreach (var t in listCmd) { InitFirstWorker(t.FullName); } } public static List<string> ListAllCommandTypeName() { if (RedisServices.IsEnable) { return RedisServices.RedisDatabase.HashGetAll(ListCommandTypeNameRedisKey) .Select(i => i.Name.ToString()).ToList(); } lock (_locker) { return _cmdTypeName.Select(i => i.Key).ToList(); } } public static Type GetType(string fullName) { lock (_locker) { return _cmdTypeName[fullName]; } } } }
35.304478
158
0.430794
[ "MIT" ]
badpaybad/cqrs-dot-net-core
IotHub.Core/CqrsEngine/EngineeCommandWorkerQueue.cs
11,829
C#
using System; using XposeCraft.Game; using XposeCraft.Game.Actors.Buildings; using XposeCraft.Game.Actors.Units; using XposeCraft.Game.Control.GameActions; using XposeCraft.Game.Enums; using XposeCraft.Game.Helpers; namespace XposeCraft.GameInternal.TestExamples { /// <summary> /// Prva faza hry. /// /// Cielom je zbierat suroviny pomocou jednotiek pracovnikov /// a pri dostatocnom pocte surovin vytvarat dalsich pracovnikov na zrychlenie ekonomie. /// </summary> internal class EconomyTest : BotScript { public MyBotData MyBotData; private GameEvent _producingWorker; public void EconomyStage(Action startNextStage) { BotRunner.Tutorial = false; BotRunner.HotSwap = false; // Game started, the first worker will get to work Worker[] firstWorkers = UnitHelper.GetMyUnits<Worker>(); foreach (Worker worker in firstWorkers) { Gather(worker); } EventForCreatingAnother(); BattleTest.RegisterReceiveFire(); startNextStage(); } void EventForCreatingAnother() { GameEvent.Register(GameEventType.MineralsChanged, argsA => { if (_producingWorker == null && argsA.Minerals >= 50) { // After he collected minerals, another worker will be built var baseCenter = BuildingHelper.GetMyBuildings<BaseCenter>()[0]; baseCenter.ProduceUnit(UnitType.Worker); // After creating (it means after few seconds), he will need to go gather too _producingWorker = GameEvent.Register(GameEventType.UnitProduced, argsB => { if (argsB.MyUnit is Worker) { Worker worker = (Worker) argsB.MyUnit; Gather(worker); argsB.ThisGameEvent.UnregisterEvent(); _producingWorker = null; } }); } // This event will work only while there are not enough workers. // After that, minerals will be left to go over 150. if (UnitHelper.GetMyUnits<Worker>().Length >= 7) { argsA.ThisGameEvent.UnregisterEvent(); } }); } public static void Gather(Worker worker) { var resource = ResourceHelper.GetNearestMineralTo(worker); if (resource == null) { BotRunner.Log("Worker couldn't find another Resource"); return; } if (CreateBaseIfNone(worker)) { return; } worker.SendGather(resource).After(new CustomFunction(() => Gather(worker))); } private static bool CreateBaseIfNone(Worker worker) { // If all bases were destroyed, try to make a new one var bases = BuildingHelper.GetMyBuildings<BaseCenter>(); if (bases.Length == 0) { worker.CreateBuilding( BuildingType.BaseCenter, BuildingHelper.ClosestEmptySpaceTo( BuildingHelper.GetMyBuildings<IBuilding>()[0], BuildingType.BaseCenter)); return true; } if (!bases[0].Finished) { worker.FinishBuiding(bases[0]); return true; } return false; } } }
34.675926
97
0.525234
[ "Apache-2.0" ]
scscgit/XposeCraft
Assets/Game/Scripts/GameInternal/TestExamples/EconomyTest.cs
3,745
C#
using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Xml; using UnityEngine; namespace AsmExplorer { public partial class WebService { private const BindingFlags AllInstanceBindings = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; private const BindingFlags AllStaticBindings = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static; private const BindingFlags AllBindings = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static; private WebServer _webServer; private string _completePrefix; private Explorer _explorer; public WebService(Explorer explorer, string prefix, int port=8080) { _explorer = explorer; _completePrefix = "http://localhost:" + port + "/" + prefix + "/"; _webServer = new WebServer(HandleRequest, _completePrefix, "http://127.0.0.1:" + port + "/" + prefix + "/"); } public void Start() { _webServer.Run(); } public void Stop() { _webServer.Stop(); } private void HandleRequest(HttpListenerContext ctxt) { var settings = new XmlWriterSettings { // this is crucial to get rid of the BOM header, see https://stackoverflow.com/questions/1755958/how-can-i-remove-the-bom-from-xmltextwriter-using-c Encoding = new System.Text.UTF8Encoding(false), OmitXmlDeclaration = true, ConformanceLevel = ConformanceLevel.Fragment, CloseOutput = false, }; // decode command string url = ctxt.Request.RawUrl; int commandStart = url.IndexOf('/', 1) + 1; string command; if (commandStart != -1) { int commandEnd = url.IndexOf('?', commandStart); if (commandEnd == -1) { commandEnd = url.Length; } command = url.Substring(commandStart, commandEnd - commandStart); } else { command = "inspect"; } using (MemoryStream stream = new MemoryStream()) { using (var writer = XmlWriter.Create(stream, settings)) { var htmlWriter = new HtmlWriter(writer); try { writer.WriteStartElement("html"); writer.WriteStartElement("head"); WriteStyle(htmlWriter); writer.WriteEndElement(); writer.WriteStartElement("body"); switchStart: switch(command) { case "inspect": ExecuteInspect(htmlWriter, ctxt.Request.QueryString); break; default: command = "inspect"; goto switchStart; } writer.WriteEndElement(); writer.WriteEndElement(); } catch (Exception ex) { htmlWriter.Write(ex.Message); htmlWriter.Break(); using (htmlWriter.Tag("pre")) htmlWriter.Write(ex.StackTrace); writer.WriteFullEndElement(); } } stream.Flush(); ctxt.Response.ContentLength64 = stream.Length; stream.Position = 0; stream.WriteTo(ctxt.Response.OutputStream); } ctxt.Response.OutputStream.Close(); } private static void WriteStyle(HtmlWriter writer) { using (writer.Tag("style")) { writer.Write( @"table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; }" ); } } private void ExecuteInspect(HtmlWriter writer, NameValueCollection args) { if (args["assembly"] != null) { var asm = args["assembly"]; if (args["type"] != null) { var type = args["type"]; if (args["method"] != null) InspectMethod(writer, asm, type, args["method"]); else InspectType(writer, asm, type); } else if (args["namespace"] != null) { InspectNamespace(writer, asm, args["namespace"]); } else { InspectAssembly(writer, asm); } } else { InspectDomain(writer); } } private void MakeTable<T>(HtmlWriter writer, IEnumerable<T> ts, params Action<T>[] inner) { using(writer.Tag("table")) { foreach (var t in ts) { using (writer.Tag("tr")) { foreach(var cell in inner) { using (writer.Tag("td")) cell(t); } } } } } private void WriteAttributes(HtmlWriter writer, object[] attributes, bool stacked=true) { if (attributes.Length == 0) return; if (!stacked) writer.Write("["); for (int i = 0; i < attributes.Length; i++) { if (stacked) writer.Write("["); else if (i > 0) writer.Write(" ,"); var type = attributes[i].GetType(); TypeLink(writer, type); var properties = type.GetProperties(AllInstanceBindings); if (properties.Length > 0) { bool first = true; for (int j = 0; j < properties.Length; j++) { var prop = properties[j]; if (!prop.CanRead || prop.GetIndexParameters().Length > 0 || prop.Name == "TypeId") continue; if (!first) writer.Write(", "); else writer.Write(" ( "); first = false; writer.Write(prop.Name); writer.Write(" = "); var value = prop.GetValue(attributes[i], null); if (value == null) writer.Write("null"); else if (value is string) { writer.Write("\""); writer.Write((value as string)); writer.Write("\""); } } if (!first) writer.Write(" ) "); } if (stacked) { writer.Write("]"); writer.Break(); } } if (!stacked) writer.Write("]"); } private void FunctionLink(HtmlWriter writer, MethodBase method) { FunctionLink(writer, method, method.DeclaringType.Name + "." + method.Name); } private void FunctionLink(HtmlWriter writer, MethodBase method, string txt) { writer.AHref(txt, Html.Url( _completePrefix + "inspect", "assembly", method.DeclaringType.Assembly.FullName, "type", method.DeclaringType.FullName, "method", method.ToString() ) ); } private void TypeLink(HtmlWriter writer, Type type) { TypeLink(writer, type, type.PrettyName()); } private void TypeLink(HtmlWriter writer, Type type, string txt) { writer.AHref(txt, Html.Url( _completePrefix + "inspect", "assembly", type.Assembly.FullName, "type", type.FullName ) ); } private void NamespaceLink(HtmlWriter writer, Namespace ns) { NamespaceLink(writer, ns, ns.FullName); } private void NamespaceLink(HtmlWriter writer, Namespace ns, string txt) { writer.AHref(txt, Html.Url( _completePrefix + "inspect", "assembly", ns.Assembly.FullName, "namespace", ns.FullName ) ); } private void AssemblyLink(HtmlWriter writer, Assembly assembly) { AssemblyLink(writer, assembly, assembly.Name); } private void AssemblyLink(HtmlWriter writer, Assembly assembly, string txt) { writer.AHref(txt, Html.Url( _completePrefix + "inspect", "assembly", assembly.FullName ) ); } } }
37.894309
164
0.47404
[ "BSD-2-Clause", "MIT" ]
sschoener/unity-asmexplorer
AsmExplorer/WebService.cs
9,322
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("Hermes.Entity")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Hermes.Entity")] [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("4e4595da-d634-4553-9962-8389c2bfced7")] // 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.810811
84
0.744103
[ "MIT" ]
Mithra/hermes
source/_Common/Hermes.Entity/Properties/AssemblyInfo.cs
1,402
C#
using System; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; using FluentAssertions; using PossumLabs.Specflow.Core.FluidDataCreation; namespace PossumLabs.Specflow.Core.UnitTests.FluidDataCreation { [TestClass] public class SetupUnitTestJson { public DataCreatorFactory DataCreatorFactory { get; set; } [TestInitialize] public void Initialize() { DataCreatorFactory = new DataCreatorFactory(); var factory = new PossumLabs.Specflow.Core.Variables.ObjectFactory(); var interperter = new PossumLabs.Specflow.Core.Variables.Interpeter(factory); var templateManager = new PossumLabs.Specflow.Core.Variables.TemplateManager(); templateManager.Initialize(Assembly.GetExecutingAssembly()); Setup = new Setup(DataCreatorFactory, factory, templateManager, interperter); Driver = new SetupDriver<Setup>(Setup, interperter); } private Setup Setup { get; set; } private SetupDriver<Setup> Driver { get; set; } /// <summary> /// These are tests that are all the basics /// </summary> [TestMethod] public void CreateAParentObject() { Driver.Processor(@"{""ParentObjects"":[{""var"":""P1""}]}"); DataCreatorFactory.ParentObjectDataCreator.Store.Should().HaveCount(1); DataCreatorFactory.ParentObjectDataCreator.Store[0].Id.Should().Be(1); } [TestMethod] public void CreateAParentObjects() { Driver.Processor(@"{""ParentObjects"":[{""count"":2}]}"); DataCreatorFactory.ParentObjectDataCreator.Store.Should().HaveCount(2); DataCreatorFactory.ParentObjectDataCreator.Store[0].Id.Should().Be(1); DataCreatorFactory.ParentObjectDataCreator.Store[1].Id.Should().Be(2); } [TestMethod] public void CreateAParentObjectWithACustomName() { Driver.Processor(@"{""ParentObjects"":[{""var"":""P1"", ""name"":""Bob""}]}"); DataCreatorFactory.ParentObjectDataCreator.Store.Should().HaveCount(1); DataCreatorFactory.ParentObjectDataCreator.Store[0].Id.Should().Be(1); DataCreatorFactory.ParentObjectDataCreator.Store[0].Name.Should().Be("Bob"); } [TestMethod] public void CreateAParentObjectWithACustomNameBeforeChildObject() { Driver.Processor(@"{""ParentObjects"":[{""var"":""P1"", ""name"":""Bob"", ""ChildObjects"":[{""var"":""C1""}]}]}"); DataCreatorFactory.ParentObjectDataCreator.Store.Should().HaveCount(1); DataCreatorFactory.ParentObjectDataCreator.Store[0].Id.Should().Be(1); DataCreatorFactory.ParentObjectDataCreator.Store[0].Name.Should().Be("Bob"); DataCreatorFactory.ChildObjectDataCreator.Store.Should().HaveCount(1); DataCreatorFactory.ChildObjectDataCreator.Store[0].Id.Should().Be(1); } [TestMethod] public void CreateAParentObjectsWithACustomNameBeforeChildObjects() { Driver.Processor(@"{""ParentObjects"":[{""count"":2, ""name"":""Bob"", ""ChildObjects"":[{""count"":1}]}]}"); DataCreatorFactory.ParentObjectDataCreator.Store.Should().HaveCount(2); DataCreatorFactory.ParentObjectDataCreator.Store[0].Id.Should().Be(1); DataCreatorFactory.ParentObjectDataCreator.Store[0].Name.Should().Be("Bob"); DataCreatorFactory.ParentObjectDataCreator.Store[1].Id.Should().Be(2); DataCreatorFactory.ParentObjectDataCreator.Store[1].Name.Should().Be("Bob"); DataCreatorFactory.ChildObjectDataCreator.Store.Should().HaveCount(2); DataCreatorFactory.ChildObjectDataCreator.Store[0].Id.Should().Be(1); DataCreatorFactory.ChildObjectDataCreator.Store[1].Id.Should().Be(2); } [TestMethod] public void CreateAParentObjectWithChildObject() { Driver.Processor(@"{""ParentObjects"":[{""var"":""P1"", ""ChildObjects"":[{""var"":""C1""}]}]}"); DataCreatorFactory.ParentObjectDataCreator.Store.Should().HaveCount(1); DataCreatorFactory.ParentObjectDataCreator.Store[0].Id.Should().Be(1); DataCreatorFactory.ChildObjectDataCreator.Store.Should().HaveCount(1); DataCreatorFactory.ChildObjectDataCreator.Store[0].Id.Should().Be(1); } [TestMethod] public void CreateAParentObjectWithChildObjectAccessingData() { Driver.Processor(@"{""ParentObjects"":[{""var"":""P1"", ""ChildObjects"":[{""var"":""C1""}]}]}"); Setup.ParentObjects["P1"].Id.Should().Be(1); Setup.ChildObjects["C1"].Id.Should().Be(1); } [TestMethod] public void CreateChildObjectTemplatesListsData() { Driver.Processor(@"{""ParentObjects"":[{""var"":""P1"", ""ChildObjects"":[{""var"":""C1"", ""template"":""ListString""}, {""var"":""C2"", ""template"":""ListInt""}]}]}"); Setup.ParentObjects["P1"].Id.Should().Be(1); Setup.ChildObjects["C1"].Id.Should().Be(1); } [TestMethod] public void CreateListStringNoData() { Driver.Processor(@"{""ParentObjects"":[{""var"":""P1"", ""ChildObjects"":[{""var"":""C1"", ""ListOfStrings"":[]}]}]}"); Setup.ParentObjects["P1"].Id.Should().Be(1); Setup.ChildObjects["C1"].Id.Should().Be(1); } [TestMethod] public void CreateListStringData() { Driver.Processor(@"{""ParentObjects"":[{""var"":""P1"", ""ChildObjects"":[{""var"":""C1"", ""ListOfStrings"":[""Bob""]}]}]}"); Setup.ParentObjects["P1"].Id.Should().Be(1); Setup.ChildObjects["C1"].Id.Should().Be(1); } [TestMethod] public void CreateListStringsData() { Driver.Processor(@"{""ParentObjects"":[{""var"":""P1"", ""ChildObjects"":[{""var"":""C1"", ""ListOfStrings"":[""Bob"",""Mary""]}]}]}"); Setup.ParentObjects["P1"].Id.Should().Be(1); Setup.ChildObjects["C1"].Id.Should().Be(1); } public void CreateListIntNoData() { Driver.Processor(@"{""ParentObjects"":[{""var"":""P1"", ""ChildObjects"":[{""var"":""C1"", ""ListOfInts"":[]}]}]}"); Setup.ParentObjects["P1"].Id.Should().Be(1); Setup.ChildObjects["C1"].Id.Should().Be(1); } public void CreateListIntData() { Driver.Processor(@"{""ParentObjects"":[{""var"":""P1"", ""ChildObjects"":[{""var"":""C1"", ""ListOfInts"":[42]}]}]}"); Setup.ParentObjects["P1"].Id.Should().Be(1); Setup.ChildObjects["C1"].Id.Should().Be(1); } [TestMethod] public void CreateListIntsData() { Driver.Processor(@"{""ParentObjects"":[{""var"":""P1"", ""ChildObjects"":[{""var"":""C1"", ""ListOfInts"":[1,2]}]}]}"); Setup.ParentObjects["P1"].Id.Should().Be(1); Setup.ChildObjects["C1"].Id.Should().Be(1); Setup.ChildObjects["C1"].ListOfInts.Should().Contain(1); Setup.ChildObjects["C1"].ListOfInts.Should().Contain(2); } [TestMethod] public void CreateAParentObjectsWithACustomNameAndChildObjectsAccessingData() { Driver.Processor(@"{""ParentObjects"":[{""count"":2, ""name"":""Bob"", ""ChildObjects"":[{""count"":1}]}]}"); Setup.ParentObjects["1"].Id.Should().Be(1); Setup.ParentObjects["1"].Name.Should().Be("Bob"); Setup.ParentObjects["2"].Id.Should().Be(2); Setup.ParentObjects["2"].Name.Should().Be("Bob"); Setup.ChildObjects["1"].Id.Should().Be(1); Setup.ChildObjects["2"].Id.Should().Be(2); } /// <summary> /// Templates /// </summary> [TestMethod] public void CreateAParentObjectWithTemplates() { Driver.Processor(@"{""ParentObjects"":[{""var"":""P1""},{""var"":""P2"", ""template"":""option1""},{""var"":""P3"", ""template"":""option2""}]}"); Setup.ParentObjects["P1"].Value.Should().Be(55); Setup.ParentObjects["P2"].Value.Should().Be(1); Setup.ParentObjects["P3"].Value.Should().Be(2); } /// <summary> /// Object Factory /// </summary> [TestMethod] public void CreateLinks() { Driver.Processor(@" {""ParentObjects"":[{ ""var"":""P1"", ""name"":""Bob"", ""ChildObjects"":[{""var"":""C1""},{""var"":""C2""}], ""relations"":[{""first"":""C1"", ""second"":""C2""}] }]}"); DataCreatorFactory.ParentObjectDataCreator.Store[0].Links.Keys.Count.Should().Be(1); } } }
37.495798
182
0.575415
[ "MIT" ]
BasHamer/PossumLabs.Specflow.Core
PossumLabs.Specflow.Core.UnitTests/FluidDataCreation/SetupUnitTestJson.cs
8,926
C#
namespace BackOffice.Infrastructure.EF.Configurations { public class EmployeeConfiguration : IEntityTypeConfiguration<Employee> { public void Configure(EntityTypeBuilder<Employee> builder) { builder.ToTable("Employees"); builder.HasKey(p => p.Id); builder.Property(x => x.Name).HasColumnName(nameof(Employee.Name).ToDatabaseFormat()); builder.Property(x => x.Status).HasColumnName(nameof(Employee.Status).ToDatabaseFormat()); } } }
30.588235
102
0.661538
[ "MIT" ]
beyondnetPeru/Beyondnet.Product.SkillMap
src/Services/BackOffice/BackOffice.Infrastructure.EF/Configurations/EmployeeConfiguration.cs
522
C#
#pragma checksum "D:\project\MSP\UWP\MathGame\MathGame\View\MenujuGameDua.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "7791F09E5FB1B6328B4D0A2E4EA5BED8" //------------------------------------------------------------------------------ // <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 MathGame.View { partial class MenujuGameDua : global::Windows.UI.Xaml.Controls.Page { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] private global::Windows.UI.Xaml.Controls.Grid Display; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] private global::Windows.UI.Xaml.Controls.Button btnPlayGameDua; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] private global::Windows.UI.Xaml.Controls.Button btnPlayBack; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] private global::Windows.UI.Xaml.Controls.TextBlock Title; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] private bool _contentLoaded; /// <summary> /// InitializeComponent() /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public void InitializeComponent() { if (_contentLoaded) return; _contentLoaded = true; global::System.Uri resourceLocator = new global::System.Uri("ms-appx:///View/MenujuGameDua.xaml"); global::Windows.UI.Xaml.Application.LoadComponent(this, resourceLocator, global::Windows.UI.Xaml.Controls.Primitives.ComponentResourceLocation.Application); } } }
47.520833
169
0.630425
[ "MIT" ]
bintangthunder/UWP_MathLogic
MathGame/obj/ARM/Release/View/MenujuGameDua.g.i.cs
2,283
C#
namespace SpriteVortex { partial class AboutSplash { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.kryptonManager = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components); this.splashPictureBox = new System.Windows.Forms.PictureBox(); this.versionLabel = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.splashPictureBox)).BeginInit(); this.SuspendLayout(); // // splashPictureBox // this.splashPictureBox.BackgroundImageLayout = System.Windows.Forms.ImageLayout.None; this.splashPictureBox.Dock = System.Windows.Forms.DockStyle.Fill; this.splashPictureBox.Image = global::SpriteVortex.Properties.Resources.spritevortexSplash; this.splashPictureBox.Location = new System.Drawing.Point(0, 0); this.splashPictureBox.Name = "splashPictureBox"; this.splashPictureBox.Size = new System.Drawing.Size(541, 297); this.splashPictureBox.TabIndex = 0; this.splashPictureBox.TabStop = false; this.splashPictureBox.Click += new System.EventHandler(this.splashPictureBox_Click); // // versionLabel // this.versionLabel.AutoSize = true; this.versionLabel.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.versionLabel.Location = new System.Drawing.Point(472, 9); this.versionLabel.Name = "versionLabel"; this.versionLabel.Size = new System.Drawing.Size(38, 13); this.versionLabel.TabIndex = 1; this.versionLabel.Text = "label1"; // // AboutSplash // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.Control; this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center; this.ClientSize = new System.Drawing.Size(541, 297); this.Controls.Add(this.versionLabel); this.Controls.Add(this.splashPictureBox); this.DoubleBuffered = true; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Name = "AboutSplash"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "AboutSplash"; ((System.ComponentModel.ISupportInitialize)(this.splashPictureBox)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager; private System.Windows.Forms.PictureBox splashPictureBox; private System.Windows.Forms.Label versionLabel; } }
44.181818
159
0.622428
[ "MIT" ]
rafaelvasco/SpriteVortex
SpriteVortex/Forms/AboutSplash.Designer.cs
3,888
C#
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ namespace Microsoft.Azure.PowerShell.Cmdlets.ContainerInstance.Runtime { using System; using System.Threading; ///<summary>Represents the data in signaled event.</summary> public partial class EventData { /// <summary> /// The type of the event being signaled /// </summary> public string Id; /// <summary> /// The user-ready message from the event. /// </summary> public string Message; /// <summary> /// When the event is about a parameter, this is the parameter name. /// Used in Validation Events /// </summary> public string Parameter; /// <summary> /// This represents a numeric value associated with the event. /// Use for progress-style events /// </summary> public double Value; /// <summary> /// Any extended data for an event should be serialized and stored here. /// </summary> public string ExtendedData; /// <summary> /// If the event triggers after the request message has been created, this will contain the Request Message (which in HTTP calls would be HttpRequestMessage) /// /// Typically you'd cast this to the expected type to use it: /// <code> /// if(eventData.RequestMessgae is HttpRequestMessage httpRequest) /// { /// httpRequest.Headers.Add("x-request-flavor", "vanilla"); /// } /// </code> /// </summary> public object RequestMessage; /// <summary> /// If the event triggers after the response is back, this will contain the Response Message (which in HTTP calls would be HttpResponseMessage) /// /// Typically you'd cast this to the expected type to use it: /// <code> /// if(eventData.ResponseMessage is HttpResponseMessage httpResponse){ /// var flavor = httpResponse.Headers.GetValue("x-request-flavor"); /// } /// </code> /// </summary> public object ResponseMessage; /// <summary> /// Cancellation method for this event. /// /// If the event consumer wishes to cancel the request that initiated this event, call <c>Cancel()</c> /// </summary> /// <remarks> /// The original initiator of the request must provide the implementation of this. /// </remarks> public System.Action Cancel; } }
37.525641
166
0.539802
[ "MIT" ]
Agazoth/azure-powershell
src/ContainerInstance/generated/runtime/EventData.cs
2,850
C#
// <copyright file="RequestCultureProvider.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. // </copyright> namespace Microsoft.Teams.Apps.CompanyCommunicator.Localization { using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Localization; using Microsoft.Bot.Schema; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; /// <summary> /// The CompanyCommunicatorCultureProvider implements the interface <see cref="IRequestCultureProvider"/>. /// The provider gets locale info from User-Agent header for requests come from the BOT framework. /// It gets the info from Accept-Language header if it's a not a BOT request. /// </summary> public sealed class RequestCultureProvider : IRequestCultureProvider { /// <summary> /// Get the culture of the current request. /// </summary> /// <param name="httpContext">The current request.</param> /// <returns>A Task resolving to the culture info if found, null otherwise.</returns> #pragma warning disable UseAsyncSuffix // Interface method doesn't have Async suffix. public async Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext) #pragma warning restore UseAsyncSuffix { if (httpContext?.Request?.Body?.CanRead != true) { return null; } var isBotFrameworkUserAgent = httpContext.Request.Headers["User-Agent"] .Any(userAgent => userAgent.Contains("Microsoft-BotFramework", StringComparison.OrdinalIgnoreCase)); if (!isBotFrameworkUserAgent) { var locale = httpContext.Request.Headers["Accept-Language"].FirstOrDefault(); locale = locale?.Split(",")?.FirstOrDefault(); if (string.IsNullOrWhiteSpace(locale)) { return null; } return new ProviderCultureResult(locale); } try { // Wrap the request stream so that we can rewind it back to the start for regular request processing. httpContext.Request.EnableBuffering(); // Read the request body, parse out the activity object, and set the parsed culture information. using (var streamReader = new StreamReader(httpContext.Request.Body, Encoding.UTF8, true, 1024, leaveOpen: true)) { using (var jsonReader = new JsonTextReader(streamReader)) { var obj = await JObject.LoadAsync(jsonReader); var activity = obj.ToObject<Activity>(); var result = new ProviderCultureResult(activity.Locale); httpContext.Request.Body.Seek(0, SeekOrigin.Begin); return result; } } } #pragma warning disable CA1031 // part of the middle ware pipeline, better to use default locale then fail the request. catch (Exception) #pragma warning restore CA1031 { return null; } } } }
41.256098
129
0.607153
[ "MIT" ]
asensionacher/microsoft-teams-apps-company-communicator-itnow
Source/CompanyCommunicator/Localization/RequestCultureProvider.cs
3,383
C#
 namespace WinFormsApp1 { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.btnnovaconta = new System.Windows.Forms.Button(); this.SuspendLayout(); // // btnnovaconta // this.btnnovaconta.Location = new System.Drawing.Point(268, 89); this.btnnovaconta.Name = "btnnovaconta"; this.btnnovaconta.Size = new System.Drawing.Size(75, 23); this.btnnovaconta.TabIndex = 0; this.btnnovaconta.Text = "nova conta"; this.btnnovaconta.UseVisualStyleBackColor = true; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(7F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.btnnovaconta); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnnovaconta; } }
31.629032
107
0.552269
[ "CC0-1.0" ]
DiegoLChagas/C-entra21
forms/forms/WinFormsApp1/WinFormsApp1/Form1.Designer.cs
1,963
C#
/* Copyright 2017 Cimpress Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ namespace VP.FF.PT.Common.WpfInfrastructure.Screens.Model { public enum MessageType { Consumable, Info, Warning, Error } }
27.692308
72
0.741667
[ "Apache-2.0" ]
sizilium/Mosaic.Infrastructure
src/WpfInfrastructure/Screens/Model/MessageType.cs
720
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> //------------------------------------------------------------------------------ using System; using Newtonsoft.Json; using Scripts; namespace cfg.test { [Serializable] public partial class CompositeJsonTable2 : AConfig { [JsonProperty("y")] private int _y { get; set; } [JsonIgnore] public EncryptInt y { get; private set; } = new(); public override void EndInit() { y = _y; } public override string ToString() => JsonConvert.SerializeObject(this); } }
21.333333
80
0.485577
[ "MIT" ]
HFX-93/luban_examples
Projects/Csharp_CustomTemplate_EncryptMemory/Assets/Scripts/Configs/Gen/test/CompositeJsonTable2.cs
832
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace SZORM.InternalExtensions { public static class ReflectionExtension { public static Type GetMemberType(this MemberInfo propertyOrField) { if (propertyOrField.MemberType == MemberTypes.Property) return ((PropertyInfo)propertyOrField).PropertyType; if (propertyOrField.MemberType == MemberTypes.Field) return ((FieldInfo)propertyOrField).FieldType; throw new ArgumentException(); } public static void SetMemberValue(this MemberInfo propertyOrField, object obj, object value) { if (propertyOrField.MemberType == MemberTypes.Property) ((PropertyInfo)propertyOrField).SetValue(obj, value, null); else if (propertyOrField.MemberType == MemberTypes.Field) ((FieldInfo)propertyOrField).SetValue(obj, value); throw new ArgumentException(); } public static object GetMemberValue(this MemberInfo propertyOrField, object obj) { if (propertyOrField.MemberType == MemberTypes.Property) return ((PropertyInfo)propertyOrField).GetValue(obj, null); else if (propertyOrField.MemberType == MemberTypes.Field) return ((FieldInfo)propertyOrField).GetValue(obj); throw new ArgumentException(); } public static MemberInfo AsReflectedMemberOf(this MemberInfo propertyOrField, Type type) { if (propertyOrField.ReflectedType != type) { MemberInfo tempMember = null; if (propertyOrField.MemberType == MemberTypes.Property) { tempMember = type.GetProperty(propertyOrField.Name); } else if (propertyOrField.MemberType == MemberTypes.Field) { tempMember = type.GetField(propertyOrField.Name); } if (tempMember != null) propertyOrField = tempMember; } return propertyOrField; } public static bool IsNullable(this Type type) { Type underlyingType; return IsNullable(type, out underlyingType); } public static bool IsNullable(this Type type, out Type underlyingType) { underlyingType = Nullable.GetUnderlyingType(type); return underlyingType != null; } public static Type GetUnderlyingType(this Type type) { Type underlyingType; if (!IsNullable(type, out underlyingType)) underlyingType = type; return underlyingType; } public static bool IsAnonymousType(this Type type) { string typeName = type.Name; return typeName.Contains("<>") && typeName.Contains("__") && typeName.Contains("AnonymousType"); } public static bool IsClass(this Type type) { return type.IsClass; } public static bool IsInterface(this Type type) { return type.IsInterface; } public static bool IsEnum(this Type type) { return type.IsEnum; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } } }
34.396226
108
0.589687
[ "MIT" ]
WinterWoods/SZORM
InternalExtensions/ReflectionExtension.cs
3,648
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // ------------------------------------------------------------ namespace Microsoft.Azure.Cosmos.Pagination { using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Cosmos.Query.Core; using Microsoft.Azure.Cosmos.Query.Core.Collections; using Microsoft.Azure.Cosmos.Query.Core.Monads; using Microsoft.Azure.Cosmos.Tracing; /// <summary> /// Coordinates draining pages from multiple <see cref="PartitionRangePageAsyncEnumerator{TPage, TState}"/>, while maintaining a global sort order and handling repartitioning (splits, merge). /// </summary> internal sealed class CrossPartitionRangePageAsyncEnumerator<TPage, TState> : IAsyncEnumerator<TryCatch<CrossFeedRangePage<TPage, TState>>> where TPage : Page<TState> where TState : State { private readonly IFeedRangeProvider feedRangeProvider; private readonly CreatePartitionRangePageAsyncEnumerator<TPage, TState> createPartitionRangeEnumerator; private readonly AsyncLazy<IQueue<PartitionRangePageAsyncEnumerator<TPage, TState>>> lazyEnumerators; private CancellationToken cancellationToken; private FeedRangeState<TState>? nextState; public CrossPartitionRangePageAsyncEnumerator( IFeedRangeProvider feedRangeProvider, CreatePartitionRangePageAsyncEnumerator<TPage, TState> createPartitionRangeEnumerator, IComparer<PartitionRangePageAsyncEnumerator<TPage, TState>> comparer, int? maxConcurrency, CancellationToken cancellationToken, CrossFeedRangeState<TState> state = default) { this.feedRangeProvider = feedRangeProvider ?? throw new ArgumentNullException(nameof(feedRangeProvider)); this.createPartitionRangeEnumerator = createPartitionRangeEnumerator ?? throw new ArgumentNullException(nameof(createPartitionRangeEnumerator)); this.cancellationToken = cancellationToken; this.lazyEnumerators = new AsyncLazy<IQueue<PartitionRangePageAsyncEnumerator<TPage, TState>>>(async (ITrace trace, CancellationToken token) => { ReadOnlyMemory<FeedRangeState<TState>> rangeAndStates; if (state != default) { rangeAndStates = state.Value; } else { // Fan out to all partitions with default state List<FeedRangeEpk> ranges = await feedRangeProvider.GetFeedRangesAsync(trace, token); List<FeedRangeState<TState>> rangesAndStatesBuilder = new List<FeedRangeState<TState>>(ranges.Count); foreach (FeedRangeInternal range in ranges) { rangesAndStatesBuilder.Add(new FeedRangeState<TState>(range, default)); } rangeAndStates = rangesAndStatesBuilder.ToArray(); } List<BufferedPartitionRangePageAsyncEnumerator<TPage, TState>> bufferedEnumerators = new List<BufferedPartitionRangePageAsyncEnumerator<TPage, TState>>(rangeAndStates.Length); for (int i = 0; i < rangeAndStates.Length; i++) { FeedRangeState<TState> feedRangeState = rangeAndStates.Span[i]; PartitionRangePageAsyncEnumerator<TPage, TState> enumerator = createPartitionRangeEnumerator(feedRangeState); BufferedPartitionRangePageAsyncEnumerator<TPage, TState> bufferedEnumerator = new BufferedPartitionRangePageAsyncEnumerator<TPage, TState>(enumerator, cancellationToken); bufferedEnumerators.Add(bufferedEnumerator); } if (maxConcurrency.HasValue) { await ParallelPrefetch.PrefetchInParallelAsync(bufferedEnumerators, maxConcurrency.Value, trace, token); } IQueue<PartitionRangePageAsyncEnumerator<TPage, TState>> queue; if (comparer == null) { queue = new QueueWrapper<PartitionRangePageAsyncEnumerator<TPage, TState>>( new Queue<PartitionRangePageAsyncEnumerator<TPage, TState>>(bufferedEnumerators)); } else { queue = new PriorityQueueWrapper<PartitionRangePageAsyncEnumerator<TPage, TState>>( new PriorityQueue<PartitionRangePageAsyncEnumerator<TPage, TState>>( bufferedEnumerators, comparer)); } return queue; }); } public TryCatch<CrossFeedRangePage<TPage, TState>> Current { get; private set; } public FeedRangeInternal CurrentRange { get; private set; } public ValueTask<bool> MoveNextAsync() { return this.MoveNextAsync(NoOpTrace.Singleton); } public async ValueTask<bool> MoveNextAsync(ITrace trace) { if (trace == null) { throw new ArgumentNullException(nameof(trace)); } using (ITrace childTrace = trace.StartChild(name: nameof(MoveNextAsync), component: TraceComponent.Pagination, level: TraceLevel.Info)) { IQueue<PartitionRangePageAsyncEnumerator<TPage, TState>> enumerators = await this.lazyEnumerators.GetValueAsync( childTrace, cancellationToken: this.cancellationToken); if (enumerators.Count == 0) { this.Current = default; this.CurrentRange = default; this.nextState = default; return false; } PartitionRangePageAsyncEnumerator<TPage, TState> currentPaginator = enumerators.Dequeue(); currentPaginator.SetCancellationToken(this.cancellationToken); bool moveNextResult = false; try { moveNextResult = await currentPaginator.MoveNextAsync(childTrace); } catch { // Re-queue the enumerator to avoid emptying the queue enumerators.Enqueue(currentPaginator); throw; } if (!moveNextResult) { // Current enumerator is empty, // so recursively retry on the next enumerator. return await this.MoveNextAsync(childTrace); } if (currentPaginator.Current.Failed) { // Check if it's a retryable exception. Exception exception = currentPaginator.Current.Exception; while (exception.InnerException != null) { exception = exception.InnerException; } if (IsSplitException(exception)) { // Handle split List<FeedRangeEpk> childRanges = await this.feedRangeProvider.GetChildRangeAsync( currentPaginator.FeedRangeState.FeedRange, childTrace, this.cancellationToken); if (childRanges.Count <= 1) { // We optimistically assumed that the cache is not stale. // In the event that it is (where we only get back one child / the partition that we think got split) // Then we need to refresh the cache await this.feedRangeProvider.RefreshProviderAsync(childTrace, this.cancellationToken); childRanges = await this.feedRangeProvider.GetChildRangeAsync( currentPaginator.FeedRangeState.FeedRange, childTrace, this.cancellationToken); } if (childRanges.Count < 1) { string errorMessage = "SDK invariant violated 4795CC37: Must have at least one EPK range in a cross partition enumerator"; throw Resource.CosmosExceptions.CosmosExceptionFactory.CreateInternalServerErrorException( message: errorMessage, headers: null, stackTrace: null, trace: childTrace, error: new Microsoft.Azure.Documents.Error { Code = "SDK_invariant_violated_4795CC37", Message = errorMessage }); } if (childRanges.Count == 1) { // On a merge, the 410/1002 results in a single parent // We maintain the current enumerator's range and let the RequestInvokerHandler logic kick in enumerators.Enqueue(currentPaginator); } else { // Split foreach (FeedRangeInternal childRange in childRanges) { PartitionRangePageAsyncEnumerator<TPage, TState> childPaginator = this.createPartitionRangeEnumerator( new FeedRangeState<TState>(childRange, currentPaginator.FeedRangeState.State)); enumerators.Enqueue(childPaginator); } } // Recursively retry return await this.MoveNextAsync(childTrace); } // Just enqueue the paginator and the user can decide if they want to retry. enumerators.Enqueue(currentPaginator); this.Current = TryCatch<CrossFeedRangePage<TPage, TState>>.FromException(currentPaginator.Current.Exception); this.CurrentRange = currentPaginator.FeedRangeState.FeedRange; this.nextState = CrossPartitionRangePageAsyncEnumerator<TPage, TState>.GetNextRange(enumerators); return true; } if (currentPaginator.FeedRangeState.State != default) { // Don't enqueue the paginator otherwise it's an infinite loop. enumerators.Enqueue(currentPaginator); } CrossFeedRangeState<TState> crossPartitionState; if (enumerators.Count == 0) { crossPartitionState = null; } else { FeedRangeState<TState>[] feedRangeAndStates = new FeedRangeState<TState>[enumerators.Count]; int i = 0; foreach (PartitionRangePageAsyncEnumerator<TPage, TState> enumerator in enumerators) { feedRangeAndStates[i++] = enumerator.FeedRangeState; } crossPartitionState = new CrossFeedRangeState<TState>(feedRangeAndStates); } this.Current = TryCatch<CrossFeedRangePage<TPage, TState>>.FromResult( new CrossFeedRangePage<TPage, TState>(currentPaginator.Current.Result, crossPartitionState)); this.CurrentRange = currentPaginator.FeedRangeState.FeedRange; this.nextState = CrossPartitionRangePageAsyncEnumerator<TPage, TState>.GetNextRange(enumerators); return true; } } public ValueTask DisposeAsync() { // Do Nothing. return default; } public bool TryPeekNext(out FeedRangeState<TState> nextState) { if (this.nextState.HasValue) { nextState = this.nextState.Value; return true; } nextState = default; return false; } public void SetCancellationToken(CancellationToken cancellationToken) { this.cancellationToken = cancellationToken; } private static bool IsSplitException(Exception exeception) { return exeception is CosmosException cosmosException && (cosmosException.StatusCode == HttpStatusCode.Gone) && (cosmosException.SubStatusCode == (int)Documents.SubStatusCodes.PartitionKeyRangeGone); } private static FeedRangeState<TState>? GetNextRange(IQueue<PartitionRangePageAsyncEnumerator<TPage, TState>> enumerators) { if (enumerators == null || enumerators.Count == 0) { return default; } return enumerators.Peek()?.FeedRangeState; } private interface IQueue<T> : IEnumerable<T> { T Peek(); void Enqueue(T item); T Dequeue(); public int Count { get; } } private sealed class PriorityQueueWrapper<T> : IQueue<T> { private readonly PriorityQueue<T> implementation; public PriorityQueueWrapper(PriorityQueue<T> implementation) { this.implementation = implementation ?? throw new ArgumentNullException(nameof(implementation)); } public int Count => this.implementation.Count; public T Dequeue() => this.implementation.Dequeue(); public void Enqueue(T item) => this.implementation.Enqueue(item); public T Peek() => this.implementation.Peek(); public IEnumerator<T> GetEnumerator() => this.implementation.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => this.implementation.GetEnumerator(); } private sealed class QueueWrapper<T> : IQueue<T> { private readonly Queue<T> implementation; public QueueWrapper(Queue<T> implementation) { this.implementation = implementation ?? throw new ArgumentNullException(nameof(implementation)); } public int Count => this.implementation.Count; public T Dequeue() => this.implementation.Dequeue(); public void Enqueue(T item) => this.implementation.Enqueue(item); public T Peek() => this.implementation.Peek(); public IEnumerator<T> GetEnumerator() => this.implementation.GetEnumerator(); IEnumerator IEnumerable.GetEnumerator() => this.implementation.GetEnumerator(); } } }
44.421512
195
0.563445
[ "MIT" ]
askazakov/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/src/Pagination/CrossPartitionRangePageAsyncEnumerator.cs
15,283
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.Asn1; namespace System.Security.Cryptography.Pkcs.Asn1 { [StructLayout(LayoutKind.Sequential)] internal partial struct CertBagAsn { internal string CertId; internal ReadOnlyMemory<byte> CertValue; internal void Encode(AsnWriter writer) { Encode(writer, Asn1Tag.Sequence); } internal void Encode(AsnWriter writer, Asn1Tag tag) { writer.PushSequence(tag); writer.WriteObjectIdentifier(CertId); writer.PushSequence(new Asn1Tag(TagClass.ContextSpecific, 0)); writer.WriteEncodedValue(CertValue); writer.PopSequence(new Asn1Tag(TagClass.ContextSpecific, 0)); writer.PopSequence(tag); } internal static CertBagAsn Decode(ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet) { return Decode(Asn1Tag.Sequence, encoded, ruleSet); } internal static CertBagAsn Decode(Asn1Tag expectedTag, ReadOnlyMemory<byte> encoded, AsnEncodingRules ruleSet) { AsnReader reader = new AsnReader(encoded, ruleSet); Decode(reader, expectedTag, out CertBagAsn decoded); reader.ThrowIfNotEmpty(); return decoded; } internal static void Decode(AsnReader reader, out CertBagAsn decoded) { if (reader == null) throw new ArgumentNullException(nameof(reader)); Decode(reader, Asn1Tag.Sequence, out decoded); } internal static void Decode(AsnReader reader, Asn1Tag expectedTag, out CertBagAsn decoded) { if (reader == null) throw new ArgumentNullException(nameof(reader)); decoded = default; AsnReader sequenceReader = reader.ReadSequence(expectedTag); AsnReader explicitReader; decoded.CertId = sequenceReader.ReadObjectIdentifierAsString(); explicitReader = sequenceReader.ReadSequence(new Asn1Tag(TagClass.ContextSpecific, 0)); decoded.CertValue = explicitReader.GetEncodedValue(); explicitReader.ThrowIfNotEmpty(); sequenceReader.ThrowIfNotEmpty(); } } }
34.302632
118
0.64135
[ "MIT" ]
diverdan92/corefx
src/System.Security.Cryptography.Pkcs/src/System/Security/Cryptography/Pkcs/Asn1/CertBagAsn.xml.cs
2,609
C#
using System; using System.Collections.Generic; namespace PagarmeCoreApi.PCL.Http.Response { public class HttpStringResponse : HttpResponse { /// <summary> /// Raw string body of the http response /// </summary> public string Body { get; set; } } }
21.928571
51
0.602606
[ "MIT" ]
gotsu-unica/pagarme-core-api-dotnet-framework
PagarmeCoreApi.PCL/Http/Response/HttpStringResponse.cs
307
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IMethodRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The interface IDeviceManagementResourceAccessProfileBaseQueryByPlatformTypeRequestBuilder. /// </summary> public partial interface IDeviceManagementResourceAccessProfileBaseQueryByPlatformTypeRequestBuilder : IBaseRequestBuilder { /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> IDeviceManagementResourceAccessProfileBaseQueryByPlatformTypeRequest Request(IEnumerable<Option> options = null); } }
41.137931
153
0.625314
[ "MIT" ]
ScriptBox99/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IDeviceManagementResourceAccessProfileBaseQueryByPlatformTypeRequestBuilder.cs
1,193
C#
/* _BEGIN_TEMPLATE_ { "id": "OG_254", "name": [ "奥秘吞噬者", "Eater of Secrets" ], "text": [ "<b>战吼:</b>摧毁所有敌方<b>奥秘</b>。每摧毁一个,便获得+1/+1。", "<b>Battlecry:</b> Destroy all enemy <b>Secrets</b>. Gain +1/+1 for each." ], "cardClass": "NEUTRAL", "type": "MINION", "cost": 4, "rarity": "RARE", "set": "OG", "collectible": true, "dbfId": 38792 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_OG_254 : SimTemplate //* Eater of Secrets { //Destroy all enemy Secrets. Gain +1/+1 for each. public override void getBattlecryEffect(Playfield p, Minion own, Minion target, int choice) { var buff = own.own ? p.enemySecretList.Count : p.ownSecretsIDList.Count; p.minionGetBuffed(own, buff, buff); if (own.own) { p.enemySecretList.Clear(); } else { p.ownSecretsIDList.Clear(); } } } }
22.431818
99
0.524823
[ "MIT" ]
chi-rei-den/Silverfish
cards/OG/OG/Sim_OG_254.cs
1,041
C#
using System; using CompanyName.MyMeetings.Modules.Payments.Domain.MeetingGroupPaymentRegisters; using CompanyName.MyMeetings.Modules.Payments.Domain.MeetingGroupPaymentRegisters.Events; using CompanyName.MyMeetings.Modules.Payments.Domain.MeetingGroupPaymentRegisters.Rules; using CompanyName.MyMeetings.Modules.Payments.Domain.Payers; using CompanyName.MyMeetings.Modules.Payments.Domain.UnitTests.SeedWork; using NUnit.Framework; namespace CompanyName.MyMeetings.Modules.Payments.Domain.UnitTests.MeetingGroupPaymentRegisters { [TestFixture] public class MeetingGroupPaymentRegistersTests : TestBase { [Test] public void CreatePaymentScheduleForMeetingGroup_IsSuccessful() { var meetingGroupId = new MeetingGroupId(Guid.NewGuid()); var paymentScheduleForMeetingGroup = MeetingGroupPaymentRegister.CreatePaymentScheduleForMeetingGroup(meetingGroupId); var meetingGroupPaymentRegisterCreated = AssertPublishedDomainEvent<MeetingGroupPaymentRegisterCreatedDomainEvent>(paymentScheduleForMeetingGroup); Assert.That(meetingGroupPaymentRegisterCreated.MeetingGroupPaymentRegisterId.Value, Is.EqualTo(meetingGroupId.Value)); } [Test] public void RegisterPayment_OnlyOnePayment_IsSuccessful() { var meetingGroupId = new MeetingGroupId(Guid.NewGuid()); var paymentScheduleForMeetingGroup = MeetingGroupPaymentRegister.CreatePaymentScheduleForMeetingGroup(meetingGroupId); var payerId = new PayerId(Guid.NewGuid()); var paymentTerm = new PaymentTerm( new DateTime(2019, 1, 1), new DateTime(2019, 1, 31)); paymentScheduleForMeetingGroup.RegisterPayment( paymentTerm, payerId); var paymentRegistered = AssertPublishedDomainEvent<PaymentRegisteredDomainEvent>(paymentScheduleForMeetingGroup); Assert.That(paymentRegistered.MeetingGroupPaymentRegisterId, Is.EqualTo(paymentScheduleForMeetingGroup.Id)); Assert.That(paymentRegistered.DateTo, Is.EqualTo(paymentTerm.EndDate)); } [Test] public void RegisterPayment_TermsAreNotOverlapping_IsSuccessful() { var meetingGroupId = new MeetingGroupId(Guid.NewGuid()); var paymentScheduleForMeetingGroup = MeetingGroupPaymentRegister.CreatePaymentScheduleForMeetingGroup(meetingGroupId); var payerId = new PayerId(Guid.NewGuid()); var paymentTerm = new PaymentTerm( new DateTime(2019, 1, 1), new DateTime(2019, 1, 31)); paymentScheduleForMeetingGroup.RegisterPayment( paymentTerm, payerId); var nextPaymentTerm = new PaymentTerm( new DateTime(2019, 2, 1), new DateTime(2019, 2, 28)); paymentScheduleForMeetingGroup.RegisterPayment( nextPaymentTerm, payerId); var domainEvents = AssertPublishedDomainEvents<PaymentRegisteredDomainEvent>(paymentScheduleForMeetingGroup); Assert.That(domainEvents.Count, Is.EqualTo(2)); Assert.That(domainEvents[1].DateTo, Is.EqualTo(nextPaymentTerm.EndDate)); } [Test] public void RegisterPayment_TermsAreOverlapping_BreaksPaymentTermsCannotOverlapRule() { var meetingGroupId = new MeetingGroupId(Guid.NewGuid()); var paymentScheduleForMeetingGroup = MeetingGroupPaymentRegister.CreatePaymentScheduleForMeetingGroup(meetingGroupId); var payerId = new PayerId(Guid.NewGuid()); var paymentTerm = new PaymentTerm( new DateTime(2019, 1, 1), new DateTime(2019, 1, 31)); paymentScheduleForMeetingGroup.RegisterPayment( paymentTerm, payerId); var nextPaymentTerm = new PaymentTerm( new DateTime(2019, 1, 31), new DateTime(2019, 2, 28)); AssertBrokenRule<MeetingGroupPaymentsCannotOverlapRule>(() => { paymentScheduleForMeetingGroup.RegisterPayment( nextPaymentTerm, payerId); }); } } }
44.768421
130
0.686339
[ "MIT" ]
Bardr/modular-monolith-with-ddd
src/Modules/Payments/Tests/UnitTests/MeetingGroupPaymentRegisters/MeetingGroupPaymentRegistersTests.cs
4,255
C#
namespace com.xamarin.recipes.filepicker { using Android.App; using Android.OS; using Android.Support.V4.App; using PDFNetAndroidXamarinSample; [Activity(Label = "@string/file_browser_name")] public class FilePickerActivity : FragmentActivity { protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.file_picker_activity); } } }
24.722222
56
0.692135
[ "MIT" ]
moljac/Samples.AndroidX
samples/issues/0014-NoClassDefFoundError androidx.lifecycle.LifecycleOwner/to-Xamarin-v2/samples/PDFNetAndroidXamarinSample/PDFNetAndroidXamarinSample/FilePickerActivity.cs
447
C#
using Reactive.Bindings; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Yomiage.GUI.Models { public class LayoutService { /// <summary> /// ボイスプリセットの表示 /// </summary> public ReactivePropertySlim<bool> PresetVisible { get; } = new(); /// <summary> /// チューニングの表示 /// </summary> public ReactivePropertySlim<bool> TuningVisible { get; } = new(); /// <summary> /// キャラクターの表示 /// </summary> public ReactivePropertySlim<bool> CharacterVisible { get; } = new(); /// <summary> /// キャラクターを大きく表示 /// </summary> public ReactivePropertySlim<bool> IsCharacterMaximized { get; } = new(); /// <summary> /// テキストに行数を表示 /// </summary> public ReactivePropertySlim<bool> IsLineNumberVisible { get; } = new(); /// <summary> /// レイアウトの初期化コマンド /// </summary> public ReactiveCommand InitializeCommand { get; } = new(); public ReactiveCommand<TabType> ShowTabCommand { get; } = new(); SettingService settingService; public LayoutService(SettingService settingService) { this.settingService = settingService; PresetVisible.Value = settingService.Settings.Default.PresetVisible; TuningVisible.Value = settingService.Settings.Default.TuningVisible; CharacterVisible.Value = settingService.Settings.Default.CharacterVisible; IsCharacterMaximized.Value = settingService.Settings.Default.IsCharacterMaximized; IsLineNumberVisible.Value = settingService.Settings.Default.IsLineNumberVisible; PresetVisible.Subscribe(value => { settingService.Settings.Default.PresetVisible = value; Save(); }); TuningVisible.Subscribe(value => { settingService.Settings.Default.TuningVisible = value; Save(); }); CharacterVisible.Subscribe(value => { settingService.Settings.Default.CharacterVisible = value; Save(); }); IsCharacterMaximized.Subscribe(value => { settingService.Settings.Default.IsCharacterMaximized = value; Save(); }); IsLineNumberVisible.Subscribe(value => { settingService.Settings.Default.IsLineNumberVisible = value; Save(); }); } private void Save() { settingService.Save(); } } public enum TabType { UserTab, } }
36.985294
127
0.629821
[ "MIT" ]
InochiPM/YomiageLibrary
Yomiage.GUI/Models/LayoutService.cs
2,645
C#
using MS.Lib.Config.Abstractions; using System.ComponentModel.DataAnnotations; namespace MS.Module.Admin.Application.ConfigService.ViewModels { public class ConfigUpdateModel { [Required(ErrorMessage = "配置类编码不能为空")] public string Code { get; set; } public ConfigType Type { get; set; } [Required(ErrorMessage = "配置内容不能为空")] public string Json { get; set; } } }
26
62
0.670673
[ "MIT" ]
billowliu2/MS
src/Admin/Library/Application/ConfigService/ViewModels/ConfigUpdateModel.cs
452
C#
using System.Collections.Specialized; using DNTProfiler.Common.Models; using DNTProfiler.Common.Mvvm; using DNTProfiler.Infrastructure.ViewModels; using DNTProfiler.PluginsBase; namespace DNTProfiler.CommandsByRowsReturned.ViewModels { public class MainViewModel : ChartsViewModelBase { public MainViewModel(ProfilerPluginBase pluginContext) : base(pluginContext) { if (Designer.IsInDesignModeStatic) return; SetActions(); setEvenets(); GuiModelData.PlotModel.Title = "Commands By Rows Returned"; AddXAxis("Command (Id)"); AddYAxis("Rows Returned"); InitPlotModelEvents(); InitUpdatePlotInterval(); } private void CommandResults_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (CommandResult item in e.NewItems) { if (item.CommandId != null && item.RowsReturned != null) { AddDataPoint(item.ApplicationIdentity, item.CommandId.Value, item.RowsReturned.Value); PluginContext.NotifyPluginsHost(NotificationType.Update, 1); CallbacksManagerBase.UpdateAppIdentityNotificationsCount(item); } } break; } } private void setEvenets() { PluginContext.ProfilerData.Results.CollectionChanged += CommandResults_CollectionChanged; } } }
33.865385
104
0.568995
[ "Apache-2.0" ]
Mohsenbahrzadeh/DNTProfiler
Plugins/DNTProfiler.CommandsByRowsReturned/ViewModels/MainViewModel.cs
1,763
C#
// Decompiled with JetBrains decompiler // Type: HPQWMIEXLib.hpqWmiEventsClass // Assembly: Interop.HPQWMIEXLib, Version=4.0.112.1, Culture=neutral, PublicKeyToken=9c6f83d5b7f3d097 // MVID: E296F39D-9128-4C42-8E9C-5979CDD45E80 // Assembly location: C:\Windows.old\Program Files (x86)\Hewlett-Packard\Shared\Interop.HPQWMIEXLib.dll using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace HPQWMIEXLib { [Guid("4BE1F202-E872-4127-8E3F-A24A4A021203")] [ClassInterface((short) 0)] [TypeLibType((short) 2)] [ComImport] public class hpqWmiEventsClass : IhpqWmiEvents, hpqWmiEvents { [DispId(1)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] public extern void hpqMonitorEvents([In] uint ulState); [DispId(2)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] public extern void hpqRegisterEvent([MarshalAs(UnmanagedType.BStr), In] string bstrEventName, [In] uint dwEventID, out uint pulRetCode); [DispId(3)] [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)] public extern void hpqUnRegisterEvent([MarshalAs(UnmanagedType.BStr), In] string bstrEventName, [In] uint dwEventID, out uint pulRetCode); } }
40.40625
142
0.774169
[ "Apache-2.0" ]
lancelot-1987/KoolSense
Interop.HPQWMIEXLib/hpqWmiEventsClass.cs
1,295
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using System.Text.Json; using Azure.Core; namespace Azure.Graph.Rbac.Models { public partial class OptionalClaims : IUtf8JsonSerializable { void IUtf8JsonSerializable.Write(Utf8JsonWriter writer) { writer.WriteStartObject(); if (Optional.IsCollectionDefined(IdToken)) { writer.WritePropertyName("idToken"); writer.WriteStartArray(); foreach (var item in IdToken) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (Optional.IsCollectionDefined(AccessToken)) { writer.WritePropertyName("accessToken"); writer.WriteStartArray(); foreach (var item in AccessToken) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } if (Optional.IsCollectionDefined(SamlToken)) { writer.WritePropertyName("samlToken"); writer.WriteStartArray(); foreach (var item in SamlToken) { writer.WriteObjectValue(item); } writer.WriteEndArray(); } writer.WriteEndObject(); } internal static OptionalClaims DeserializeOptionalClaims(JsonElement element) { Optional<IList<OptionalClaim>> idToken = default; Optional<IList<OptionalClaim>> accessToken = default; Optional<IList<OptionalClaim>> samlToken = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("idToken")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<OptionalClaim> array = new List<OptionalClaim>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(OptionalClaim.DeserializeOptionalClaim(item)); } idToken = array; continue; } if (property.NameEquals("accessToken")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<OptionalClaim> array = new List<OptionalClaim>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(OptionalClaim.DeserializeOptionalClaim(item)); } accessToken = array; continue; } if (property.NameEquals("samlToken")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<OptionalClaim> array = new List<OptionalClaim>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(OptionalClaim.DeserializeOptionalClaim(item)); } samlToken = array; continue; } } return new OptionalClaims(Optional.ToList(idToken), Optional.ToList(accessToken), Optional.ToList(samlToken)); } } }
36.917431
122
0.488817
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/testcommon/Azure.Graph.Rbac/src/Generated/Models/OptionalClaims.Serialization.cs
4,024
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Windows.Forms; using System.Drawing; using System.Text; namespace SharpLogger { public partial class LogControl : UserControl, ILogAppender, ILogHandler { private readonly Dictionary<string, Color> colors = new Dictionary<string, Color>(); private readonly LinkedList<LogLine> shown = new LinkedList<LogLine>(); private readonly LinkedList<LogDto> queue = new LinkedList<LogDto>(); private LogFormatter formatter = LogFormatter.TIMEONLY_MESSAGE; private int limit = 1000; private Logger logger; private bool dirty; public LogControl() { colors.Add(LogDto.DEBUG, Color.Gray); colors.Add(LogDto.INFO, Color.White); colors.Add(LogDto.WARN, Color.Yellow); colors.Add(LogDto.ERROR, Color.Tomato); colors.Add(LogDto.SUCCESS, Color.PaleGreen); logger = Create(typeof(LogControl).Name); InitializeComponent(); } //DESIGN TIME [Category("Logging")] public float FontSize { get { return logPanel.FontSize; } set { logPanel.FontSize = value; } } [Category("Logging")] public Color LogBackColor { get { return logPanel.BackColor; } set { logPanel.BackColor = value; } } [Category("Logging")] public Color SelectionBack { get { return logPanel.SelectionBack; } set { logPanel.SelectionBack = value; } } [Category("Logging")] public Color SelectingBack { get { return logPanel.SelectingBack; } set { logPanel.SelectingBack = value; } } [Category("Logging")] public Color SelectionFront { get { return logPanel.SelectionFront; } set { logPanel.SelectionFront = value; } } [Category("Logging")] public Color SuccessColor { get { return colors[LogDto.SUCCESS]; } set { colors[LogDto.SUCCESS] = value; } } [Category("Logging")] public Color ErrorColor { get { return colors[LogDto.ERROR]; } set { colors[LogDto.ERROR] = value; } } [Category("Logging")] public Color WarnColor { get { return colors[LogDto.WARN]; } set { colors[LogDto.WARN] = value; } } [Category("Logging")] public Color InfoColor { get { return colors[LogDto.INFO]; } set { colors[LogDto.INFO] = value; } } [Category("Logging")] public Color DebugColor { get { return colors[LogDto.DEBUG]; } set { colors[LogDto.DEBUG] = value; } } [Category("Logging")] public int LineLimit { get { return limit; } set { limit = value; } } [Category("Logging")] public int PollPeriod { get { return timer.Interval; } set { timer.Interval = value; } } [Category("Logging")] public string LogFormat { get { return formatter.Format; } set { formatter = new LogFormatter(value); } } //DESIGN & RUNTIME [Category("Logging")] public bool ShowDebug { get { return showDebugCheckBox.Checked; } set { showDebugCheckBox.Checked = value; } } [Category("Logging")] public bool FreezeView { get { return freezeViewCheckBox.Checked; } set { freezeViewCheckBox.Checked = value; } } public void AddColor(string level, Color color) { colors.Add(level, color); } //Should not switch to UI to prevent thread //deathlock when disposing from UI events public void AppendLog(params LogDto[] dtos) { lock (queue) { //memory leak if disposed clear timer foreach (var dto in dtos) queue.AddLast(dto); } } //Should not switch to UI to prevent thread //deathlock when disposing from UI events public void HandleLog(LogDto dto) { lock (queue) { //memory leak if disposed clear timer queue.AddLast(dto); } } public Logger Create(string source) { return new Logger(this, source); } private void Timer_Tick(object sender, EventArgs e) { timer.Enabled = false; var debug = ShowDebug; var freeze = freezeViewCheckBox.Checked; foreach (var dto in Pop()) { if (debug || dto.Level != LogDto.DEBUG) { var text = formatter.ConvertLog(dto); var color = ToColor(dto.Level); Lines(text, (single) => { var line = new LogLine(); line.Color = color; line.Line = single; shown.AddLast(line); }); dirty = true; } } while (shown.Count > limit) { shown.RemoveFirst(); dirty = true; } if (dirty && !freeze) { logPanel.SetLines(Shown()); dirty = false; } timer.Enabled = true; } private LogDto[] Pop() { lock (queue) { var array = new LogDto[queue.Count]; queue.CopyTo(array, 0); queue.Clear(); return array; } } private void ClearButton_Click(object sender, EventArgs e) { shown.Clear(); logPanel.SetLines(); } private void CopyButton_Click(object sender, EventArgs e) { Clipboard.Clear(); var selectedText = logPanel.SelectedText(); if (!string.IsNullOrEmpty(selectedText)) { //throws even on empty strings Clipboard.SetText(selectedText); } } private void Lines(string text, Action<string> callback) { if (text.Contains("\n")) { var sb = new StringBuilder(); foreach (var c in text) { switch (c) { case '\r': break; case '\n': callback(sb.ToString()); sb.Clear(); break; case '\t': sb.Append(" "); break; default: sb.Append(c); break; } } callback(sb.ToString()); } else { callback(text); } } private LogLine[] Shown() { var array = new LogLine[shown.Count]; shown.CopyTo(array, 0); return array; } private Color ToColor(string level) { if (colors.TryGetValue(level, out var color)) { return color; } throw new Exception($"Invalid level {level}"); } } public partial class LogControl : ILogger { public void Log(string level, string format, params object[] args) { logger.Log(level, format, args); } public void Debug(string format, params object[] args) { logger.Debug(format, args); } public void Info(string format, params object[] args) { logger.Info(format, args); } public void Warn(string format, params object[] args) { logger.Warn(format, args); } public void Error(string format, params object[] args) { logger.Error(format, args); } public void Success(string format, params object[] args) { logger.Success(format, args); } } }
28.923588
92
0.470365
[ "MIT" ]
samuelventura/SharpLogger
SharpLogger.UI/LogControl.cs
8,708
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; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Mime; using System.Security.Claims; using System.Text; using System.Threading.Tasks; using System.Web; using Microsoft.AspNet.SignalR; using Microsoft.AspNet.SignalR.Hosting; using Microsoft.AspNet.SignalR.Hubs; using Microsoft.AspNet.SignalR.Json; using Microsoft.Azure.SignalR.Common; using Microsoft.Extensions.Logging; using Microsoft.Owin; using Newtonsoft.Json; namespace Microsoft.Azure.SignalR.AspNet { internal class NegotiateMiddleware : OwinMiddleware { private static readonly HashSet<string> PreservedQueryParameters = new HashSet<string>(new[] {"clientProtocol", "connectionToken", "connectionData"}); private static readonly Version ClientSupportQueryStringVersion = new Version(2, 1); private static readonly string AssemblyVersion = typeof(NegotiateMiddleware).Assembly.GetName().Version.ToString(); private readonly string _appName; private readonly Func<IOwinContext, IEnumerable<Claim>> _claimsProvider; private readonly ILogger _logger; private readonly IServiceEndpointManager _endpointManager; private readonly IEndpointRouter _router; private readonly IConnectionRequestIdProvider _connectionRequestIdProvider; private readonly IUserIdProvider _provider; private readonly HubConfiguration _configuration; private readonly string _serverName; private readonly ServerStickyMode _mode; private readonly bool _enableDetailedErrors; private readonly int _endpointsCount; public NegotiateMiddleware(OwinMiddleware next, HubConfiguration configuration, string appName, IServiceEndpointManager endpointManager, IEndpointRouter router, ServiceOptions options, IServerNameProvider serverNameProvider, IConnectionRequestIdProvider connectionRequestIdProvider, ILoggerFactory loggerFactory) : base(next) { _configuration = configuration; _provider = configuration.Resolver.Resolve<IUserIdProvider>(); _appName = appName ?? throw new ArgumentNullException(nameof(appName)); _claimsProvider = options?.ClaimsProvider; _endpointManager = endpointManager ?? throw new ArgumentNullException(nameof(endpointManager)); _router = router ?? throw new ArgumentNullException(nameof(router)); _connectionRequestIdProvider = connectionRequestIdProvider ?? throw new ArgumentNullException(nameof(connectionRequestIdProvider)); _logger = loggerFactory?.CreateLogger<NegotiateMiddleware>() ?? throw new ArgumentNullException(nameof(loggerFactory)); _serverName = serverNameProvider?.GetName(); _mode = options.ServerStickyMode; _enableDetailedErrors = configuration.EnableDetailedErrors; _endpointsCount = options.Endpoints.Length; } public override Task Invoke(IOwinContext owinContext) { if (owinContext == null) { throw new ArgumentNullException(nameof(owinContext)); } var context = new HostContext(owinContext.Environment); if (IsNegotiationRequest(context.Request)) { return ProcessNegotiationRequest(owinContext, context); } return Next.Invoke(owinContext); } private Task ProcessNegotiationRequest(IOwinContext owinContext, HostContext context) { string accessToken = null; var claims = BuildClaims(owinContext, context.Request); var dispatcher = new HubDispatcher(_configuration); try { dispatcher.Initialize(_configuration.Resolver); if (!dispatcher.Authorize(context.Request)) { string error = null; if (context.Request.User != null && context.Request.User.Identity.IsAuthenticated) { // If the user is authenticated and authorize failed then 403 error = "Forbidden"; context.Response.StatusCode = 403; } else { // If failed to authorize the request then return 401 error = "Unauthorized"; context.Response.StatusCode = 401; } Log.NegotiateFailed(_logger, error); return context.Response.End(error); } } catch (Exception e) { Log.NegotiateFailed(_logger, e.Message); context.Response.StatusCode = 500; return context.Response.End(""); } IServiceEndpointProvider provider; try { // Take the service endpoints for the app provider = _endpointManager.GetEndpointProvider(_router.GetNegotiateEndpoint(owinContext, _endpointManager.GetEndpoints(_appName))); // When status code changes, we consider the inner router changed the response, then we stop here if (context.Response.StatusCode != 200) { // Inner handler already write to context.Response, no need to continue with error case return Task.CompletedTask; } // Consider it as internal server error when we don't successfully get negotiate response if (provider == null) { var message = "Unable to get the negotiate endpoint"; Log.NegotiateFailed(_logger, message); context.Response.StatusCode = 500; return context.Response.End(message); } } catch (AzureSignalRNotConnectedException e) { Log.NegotiateFailed(_logger, e.Message); context.Response.StatusCode = 500; return context.Response.End(e.Message); } // Redirect to Service var clientProtocol = context.Request.QueryString["clientProtocol"]; string originalPath = null; string queryString = null; // add OriginalPath and QueryString when the clients protocol is higher than 2.0, earlier ASP.NET SignalR clients does not support redirect URL with query parameters if (!string.IsNullOrEmpty(clientProtocol) && Version.TryParse(clientProtocol, out var version) && version >= ClientSupportQueryStringVersion) { var clientRequestId = _connectionRequestIdProvider.GetRequestId(); if (clientRequestId != null) { // remove system preserved query strings queryString = "?" + string.Join("&", context.Request.QueryString.Where(s => !PreservedQueryParameters.Contains(s.Key)).Concat( new[] { new KeyValuePair<string, string>( Constants.QueryParameter.ConnectionRequestId, clientRequestId) }) .Select(s => $"{Uri.EscapeDataString(s.Key)}={Uri.EscapeDataString(s.Value)}")); } originalPath = GetOriginalPath(context.Request.LocalPath); } var url = provider.GetClientEndpoint(null, originalPath, queryString); try { accessToken = provider.GenerateClientAccessToken(null, claims); } catch (AzureSignalRAccessTokenTooLongException ex) { Log.NegotiateFailed(_logger, ex.Message); context.Response.StatusCode = 413; return context.Response.End(ex.Message); } return SendJsonResponse(context, GetRedirectNegotiateResponse(url, accessToken)); } private static string GetOriginalPath(string path) { path = path.TrimEnd('/'); return path.EndsWith(Constants.Path.Negotiate) ? path.Substring(0, path.Length - Constants.Path.Negotiate.Length) : string.Empty; } private IEnumerable<Claim> BuildClaims(IOwinContext owinContext, IRequest request) { // Pass appname through jwt token to client, so that when client establishes connection with service, it will also create a corresponding AppName-connection yield return new Claim(Constants.ClaimType.AppName, _appName); var user = owinContext.Authentication?.User; var userId = _provider?.GetUserId(request); var claims = ClaimsUtility.BuildJwtClaims(user, userId, GetClaimsProvider(owinContext), _serverName, _mode, _enableDetailedErrors, _endpointsCount); yield return new Claim(Constants.ClaimType.Version, AssemblyVersion); foreach (var claim in claims) { yield return claim; } } private Func<IEnumerable<Claim>> GetClaimsProvider(IOwinContext context) { if (_claimsProvider == null) { return null; } return () => _claimsProvider.Invoke(context); } private static string GetRedirectNegotiateResponse(string url, string token) { var sb = new StringBuilder(); using (var jsonWriter = new JsonTextWriter(new StringWriter(sb))) { jsonWriter.WriteStartObject(); jsonWriter.WritePropertyName("ProtocolVersion"); jsonWriter.WriteValue("2.0"); jsonWriter.WritePropertyName("RedirectUrl"); jsonWriter.WriteValue(url); jsonWriter.WritePropertyName("AccessToken"); jsonWriter.WriteValue(token); jsonWriter.WritePropertyName("TryWebSockets"); // fix the c# client issue https://github.com/SignalR/SignalR/issues/4435 jsonWriter.WriteValue(true); jsonWriter.WriteEndObject(); } return sb.ToString(); } private static bool IsNegotiationRequest(IRequest request) { return request.LocalPath.EndsWith(Constants.Path.Negotiate, StringComparison.OrdinalIgnoreCase); } private static Task SendJsonResponse(HostContext context, string jsonPayload) { var callback = context.Request.QueryString["callback"]; if (String.IsNullOrEmpty(callback)) { // Send normal JSON response context.Response.ContentType = JsonUtility.JsonMimeType; return context.Response.End(jsonPayload); } // JSONP response is no longer supported. context.Response.StatusCode = 400; return context.Response.End("JSONP is no longer supported."); } private static class Log { private static readonly Action<ILogger, string, Exception> _negotiateFailed = LoggerMessage.Define<string>(LogLevel.Warning, new EventId(1, "NegotiateFailed"), "Client negotiate failed: {Error}"); public static void NegotiateFailed(ILogger logger, string error) { _negotiateFailed(logger, error, null); } } } }
43.625455
320
0.604735
[ "MIT" ]
tebeco/azure-signalr
src/Microsoft.Azure.SignalR.AspNet/Middleware/NegotiateMiddleware.cs
11,999
C#
using Tizen.UIExtensions.ElmSharp; namespace Microsoft.Maui { public static class DatePickerExtensions { public static void UpdateFormat(this Entry nativeDatePicker, IDatePicker datePicker) { UpdateDate(nativeDatePicker, datePicker); } public static void UpdateDate(this Entry nativeDatePicker, IDatePicker datePicker) { nativeDatePicker.Text = datePicker.Date.ToString(datePicker.Format); } } }
24.647059
86
0.785203
[ "MIT" ]
JoonghyunCho/TestBed
src/Core/src/Platform/Tizen/DatePickerExtensions.cs
421
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Store : MonoBehaviour { public GameManager gm; public Slider progressSlider; public Text storeCountText; public Text buyButtonText; public int storeTimer; public int profit; private bool startTimer; private float currentTimer; public int baseStorePrice; public int storeMultiplier; public int storeCount; public bool hasManager = false; // Use this for initialization void Start () { storeCountText.text = storeCount.ToString (); buyButtonText.text = "Buy ($" + baseStorePrice.ToString () + ")"; currentTimer = 0; } // Update is called once per frame void Update () { if (startTimer || hasManager) { currentTimer = currentTimer + Time.deltaTime; progressSlider.value = currentTimer / storeTimer; if (currentTimer > storeTimer) { startTimer = false; gm.addToBalance (profit * storeCount); progressSlider.value = 0; currentTimer = 0; } } } public void clickme() { if (storeCount > 0) { startTimer = true; } } public void buyStore(){ if (gm.canBuy (baseStorePrice)) { gm.addToBalance (-baseStorePrice); storeCount++; storeCountText.text = storeCount.ToString (); baseStorePrice = baseStorePrice + (storeCount * storeMultiplier); buyButtonText.text = "Buy ($" + baseStorePrice.ToString () + ")"; } } }
21.424242
68
0.702263
[ "MIT" ]
hungrybanana/clicker-game
Version 0.1/Assets/Scripts/Store.cs
1,416
C#
using Blog.Core.Common; using Blog.Core.Common.LogHelper; using Blog.Core.IRepository.UnitOfWork; using Castle.DynamicProxy; using Microsoft.AspNetCore.SignalR; using StackExchange.Profiling; using System; using System.Linq; using System.Reflection; using System.Threading.Tasks; namespace Blog.Core.AOP { /// <summary> /// 事务拦截器BlogTranAOP 继承IInterceptor接口 /// </summary> public class BlogTranAOP : IInterceptor { private readonly IUnitOfWork _unitOfWork; public BlogTranAOP(IUnitOfWork unitOfWork) { _unitOfWork = unitOfWork; } /// <summary> /// 实例化IInterceptor唯一方法 /// </summary> /// <param name="invocation">包含被拦截方法的信息</param> public void Intercept(IInvocation invocation) { var method = invocation.MethodInvocationTarget ?? invocation.Method; //对当前方法的特性验证 //如果需要验证 if (method.GetCustomAttributes(true).FirstOrDefault(x => x.GetType() == typeof(UseTranAttribute)) is UseTranAttribute) { try { Console.WriteLine($"Begin Transaction"); _unitOfWork.BeginTran(); invocation.Proceed(); // 异步获取异常,先执行 if (IsAsyncMethod(invocation.Method)) { var result = invocation.ReturnValue; if (result is Task) { Task.WaitAll(result as Task); } } _unitOfWork.CommitTran(); } catch (Exception) { Console.WriteLine($"Rollback Transaction"); _unitOfWork.RollbackTran(); } } else { invocation.Proceed();//直接执行被拦截方法 } } private async Task SuccessAction(IInvocation invocation) { await Task.Run(() => { //... }); } public static bool IsAsyncMethod(MethodInfo method) { return ( method.ReturnType == typeof(Task) || (method.ReturnType.IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>)) ); } private async Task TestActionAsync(IInvocation invocation) { await Task.Run(null); } } }
27.031579
130
0.503115
[ "MIT" ]
183demao/Blog.Core
Blog.Core/AOP/BlogTranAOP.cs
2,692
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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // using org.apache.plc4net.api.value; namespace org.apache.plc4net.spi.model.values { public class PlcLINT : SimpleNumericValueAdapter<long> { public PlcLINT(long value) : base(value) { } } }
34.6
63
0.726397
[ "Apache-2.0" ]
apache/incubator-plc4x
plc4net/spi/spi/model/values/PlcLINT.cs
1,038
C#
 using System; using ProjectBlue.RepulserEngine.DataStore; using ProjectBlue.RepulserEngine.Domain.Model; using ProjectBlue.RepulserEngine.Presentation; using UniRx; using UnityEngine; using Zenject; namespace ProjectBlue.RepulserEngine.Domain.UseCase { public class PulseSettingUseCase : IInitializable, IDisposable { private IPulseSettingListPresenter pulseSettingListPresenter; private IPulseSettingRepository pulseSettingRepository; private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable saveButtonRegistrationDisposable = new CompositeDisposable(); private Subject<OscMessage> onSendTriggeredSubject = new Subject<OscMessage>(); public IObservable<OscMessage> OnSendTriggeredAsObservable => onSendTriggeredSubject; public PulseSettingUseCase(IPulseSettingListPresenter pulseSettingListPresenter, IPulseSettingRepository pulseSettingRepository) { this.pulseSettingListPresenter = pulseSettingListPresenter; this.pulseSettingRepository = pulseSettingRepository; this.pulseSettingListPresenter.OnSaveButtonClickedAsObservable.Subscribe(_ => { // _pulseSettingListPresenter.UpdateData(); this.pulseSettingRepository.Save(this.pulseSettingListPresenter.PulseSettingList); }).AddTo(disposable); pulseSettingListPresenter.OnSaveButtonClickedAsObservable.Subscribe(_ => { RegisterComponentPerSend(); }).AddTo(disposable); } public void Initialize() { var data = pulseSettingRepository.Load(); pulseSettingListPresenter.SetData(data); RegisterComponentPerSend(); } public void Dispose() { disposable.Dispose(); onSendTriggeredSubject.Dispose(); } // Sendボタンを機能させる部分 private void RegisterComponentPerSend() { // 永遠に残るのでセーブボタンが押されるたびに破棄して接続しなおす saveButtonRegistrationDisposable.Dispose(); saveButtonRegistrationDisposable = new CompositeDisposable(); foreach (var pulseSettingPresenter in pulseSettingListPresenter.PulseSettingPresenterList) { pulseSettingPresenter.OnSendButtonClickedAsObservable.Subscribe(__ => { var pulseSetting = pulseSettingPresenter.PulseSetting; onSendTriggeredSubject.OnNext(new OscMessage(pulseSetting.OverrideIp, pulseSetting.OscAddress, pulseSetting.OscData)); }).AddTo(saveButtonRegistrationDisposable); // コンポーネント削除に対応できてないのでよくない -> IPulseSettingPresenterにDisposable持たせるのがベターだけど変な実装になるのでこうしている } } } }
36.7875
153
0.664288
[ "MIT" ]
sugi-cho/RepulserEngine
Assets/Scripts/Domain/UseCase/PulseSettingUseCase.cs
3,131
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum CardVisibility { None, Player, Everyone }
12.384615
34
0.677019
[ "MIT" ]
metalac190/CardGamePrototype
Assets/Scripts/CardSystem/Enums/CardVisibility.cs
163
C#
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using DClean.Application.Interfaces; using DClean.Domain.Entities.Presistence.Identity; using DClean.Infrastructure.Persistence.Repositories; namespace DClean.Infrastructure.Persistence.Seeds { public class DefaultTenantSeed : ISeedService { private readonly IRepository<Tenant, Guid> _tenantRepo; public int Order => -1; public DefaultTenantSeed( IRepository<Tenant, Guid> tenantRepo) { _tenantRepo = tenantRepo; } public async Task SeedAsync() { var tenant = new Tenant() { Id = Guid.Parse("87be80c4-1650-4045-bfab-7be922e92349"), Name = "Default", ConcurrencyStamp = Guid.NewGuid(), }; var dbTenant = await _tenantRepo.GetTable().IgnoreQueryFilters().FirstOrDefaultAsync(t => t.Id == tenant.Id); if (dbTenant != null) return; _tenantRepo.Create(tenant); await _tenantRepo.SaveAsync(); } } }
31.105263
121
0.633672
[ "MIT" ]
amro93/DClean
DClean/DClean.Infrastructure.Persistence/Seeds/DefaultTenantSeed.cs
1,184
C#
using System; using System.Collections; using System.Collections.Generic; enum EInt8 : sbyte { A = -1, B, C, D } enum EUInt8 : byte { A, B, C, D } enum EInt16 : short { A = -1, B, C, D } enum EUInt16 : ushort { A, B, C, D } enum EInt32 : int { A = -1, B, C, D } enum EUInt32 : uint { A, B, C, D } enum EInt64 : long { A = -1, B, C, D } enum EUInt64 : ulong { A, B, C, D } enum E2Int8 : sbyte { E = -1, F, G, K,} enum E2UInt8 : byte { E, F, G, K,} enum E2Int16 : short { E = -1, F, G, K,} enum E2UInt16 : ushort { E, F, G, K,} enum E2Int32 : int { E = -1, F, G, K,} enum E2UInt32 : uint { E, F, G, K,} enum E2Int64 : long { E = -1, F, G, K,} enum E2UInt64 : ulong { E, F, G, K,} struct Point : IComparable<Point>, IComparable<int>, IEquatable<Point>, IEquatable<int>, IComparable { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public override string ToString() { return string.Format("({0}, {1})", x, y); } public int Len { get { return (int)Math.Sqrt(x*x + y*y); } } public int CompareTo(Point p) { return Len - p.Len; } public int CompareTo(int value) { return Len - value; } public bool Equals(Point other) { return x == other.x && y == other.y; } public bool Equals(int other) { return Len == other; } public int CompareTo(Object obj) { if (obj is Point) return CompareTo((Point)obj); if (obj is int) return CompareTo((int)obj); throw new InvalidOperationException(); } } namespace PageFX { using T = EUInt8; class X { static void print(T[] set) { foreach (var item in set) Console.WriteLine(item); } static void TestAs(object a) { Console.WriteLine("-- as"); try { var b = a as T[]; print(b); Console.WriteLine(ReferenceEquals(a, b)); } catch (Exception e) { Console.WriteLine(e.GetType()); } } static void TestIs(object a) { Console.WriteLine("-- is"); try { Console.WriteLine(a is T[]); } catch (Exception e) { Console.WriteLine(e.GetType()); } } static void TestCast(object a) { Console.WriteLine("-- cast"); try { var b = (T[])a; print(b); Console.WriteLine(ReferenceEquals(a, b)); } catch (Exception e) { Console.WriteLine(e.GetType()); } } static void TestCore(object a) { TestAs(a); TestIs(a); TestCast(a); } static void FromBool() { Console.WriteLine("--- FromBool"); bool[] a = new bool[] { true, false, true }; TestCore(a); } static void FromUInt8() { Console.WriteLine("--- FromUInt8"); byte[] a = new byte[] { 10, 20, 30 }; TestCore(a); } static void FromInt8() { Console.WriteLine("--- FromInt8"); sbyte[] a = new sbyte[] { 10, 20, 30 }; TestCore(a); } static void FromInt16() { Console.WriteLine("--- FromInt16"); short[] a = new short[] { 10, 20, 30 }; TestCore(a); } static void FromUInt16() { Console.WriteLine("--- FromUInt16"); ushort[] a = new ushort[] { 10, 20, 30 }; TestCore(a); } static void FromChar() { Console.WriteLine("--- FromChar"); char[] a = new char[] { 'a', 'b', 'c' }; TestCore(a); } static void FromInt32() { Console.WriteLine("--- FromInt32"); int[] a = new int[] { 10, 20, 30 }; TestCore(a); } static void FromUInt32() { Console.WriteLine("--- FromUInt32"); uint[] a = new uint[] { 10, 20, 30 }; TestCore(a); } static void FromInt64() { Console.WriteLine("--- FromInt64"); long[] a = new long[] { 10, 20, 30 }; TestCore(a); } static void FromUInt64() { Console.WriteLine("--- FromUInt64"); ulong[] a = new ulong[] { 10, 20, 30 }; TestCore(a); } static void FromDouble() { Console.WriteLine("--- FromDouble"); double[] a = new double[] { 10, 20, 30 }; TestCore(a); } static void FromEInt8() { Console.WriteLine("--- FromEInt8"); EInt8[] a = new EInt8[] { EInt8.A, EInt8.B, EInt8.C, EInt8.D }; TestCore(a); } static void FromEUInt8() { Console.WriteLine("--- FromEUInt8"); EUInt8[] a = new EUInt8[] { EUInt8.A, EUInt8.B, EUInt8.C, EUInt8.D }; TestCore(a); } static void FromEInt16() { Console.WriteLine("--- FromEInt16"); EInt16[] a = new EInt16[] { EInt16.A, EInt16.B, EInt16.C, EInt16.D }; TestCore(a); } static void FromEUInt16() { Console.WriteLine("--- FromEUInt16"); EUInt16[] a = new EUInt16[] { EUInt16.A, EUInt16.B, EUInt16.C, EUInt16.D }; TestCore(a); } static void FromEInt32() { Console.WriteLine("--- FromEInt32"); EInt32[] a = new EInt32[] { EInt32.A, EInt32.B, EInt32.C, EInt32.D }; TestCore(a); } static void FromEUInt32() { Console.WriteLine("--- FromEUInt32"); EUInt32[] a = new EUInt32[] { EUInt32.A, EUInt32.B, EUInt32.C, EUInt32.D }; TestCore(a); } static void FromEInt64() { Console.WriteLine("--- FromEInt64"); EInt64[] a = new EInt64[] { EInt64.A, EInt64.B, EInt64.C, EInt64.D }; TestCore(a); } static void FromEUInt64() { Console.WriteLine("--- FromEUInt64"); EUInt64[] a = new EUInt64[] { EUInt64.A, EUInt64.B, EUInt64.C, EUInt64.D }; TestCore(a); } static void FromNull() { Console.WriteLine("--- FromNull"); TestCore(null); } static void FromNullable() { Console.WriteLine("--- FromNullable"); TestCore(new int?()); } static void FromString() { Console.WriteLine("--- FromString"); TestCore("aaa"); } static void FromObject() { Console.WriteLine("--- FromObject"); TestCore(new object()); } static void From2DArray() { Console.WriteLine("--- From2DArray"); T[,] arr = new T[1, 1]; TestCore(arr); } static void FromObjectArray() { Console.WriteLine("--- FromObjectArray"); object[] a = new object[10]; TestCore(a); } static void FromStruct() { Console.WriteLine("--- FromStruct"); TestCore(new Point[] { new Point(10, 10), new Point(20, 20), new Point(30, 30), }); } static void Main() { FromBool(); FromInt8(); FromUInt8(); FromInt16(); FromUInt16(); FromChar(); FromInt32(); FromUInt32(); FromInt64(); FromUInt64(); FromDouble(); FromEInt8(); FromEUInt8(); FromEInt16(); FromEUInt16(); FromEInt32(); FromEUInt32(); FromEInt64(); FromEUInt64(); FromNull(); FromNullable(); FromString(); FromObject(); From2DArray(); FromObjectArray(); FromStruct(); Console.WriteLine("<%END%>"); } } }
19.861582
80
0.535201
[ "MIT" ]
GrapeCity/pagefx
tests/Simple/CSharp/Casting/Arrays/ToValue/FromValue/EUInt8.cs
7,031
C#
using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; using UnityEngine; public class Server : MonoBehaviour { private enum eConnectionType { udp, tcp } CliParser parser = new CliParser(); [Header("Client config")] [SerializeField] private eConnectionType protocol; private AConnection connection; [SerializeField] private int receivePort; // private string sendIP; // 192.168.1.28 // private int sendPort; // 5600 ? public int timer = 0; [Header("Debug")] [SerializeField] private bool triggerSend = false; [SerializeField] private string debugMsg; private void Start() { if (protocol == eConnectionType.udp) connection = new UdpConnection(); else if (protocol == eConnectionType.tcp) connection = new TcpConnection(); connection.StartConnection(receivePort); } private async void Update() { // Debug from Editor if (triggerSend) { triggerSend = false; connection.Send(debugMsg); } if (connection.incomingQueue.Count > 0) { string msg = connection.incomingQueue.Dequeue(); await Task.Delay(timer); GameManager.gm.AppendLogLine(msg); parser.DeserializeInput(msg); } } private void OnDestroy() { connection.Stop(); } ///<summary> /// Send a message to the client. ///</summary> ///<param name="_msg">The message to send</param> public void Send(string _msg) { connection.Send(_msg + "\n"); } }
23.180556
60
0.59976
[ "MPL-2.0" ]
ditrit/OGrEE-3D
Assets/Scripts/Network/Server.cs
1,669
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; namespace CustomerProcessor { [Serializable] public sealed class BasicAccountDetails : IAccountDetails, ISerializable { public string Name { get; private set; } public decimal Balance { get; private set; } public IDictionary<string, decimal> Creditors { get; private set; } public BasicAccountDetails(SerializationInfo info, StreamingContext context) { Name = (string)info.GetValue("Name", typeof(string)); Balance = (decimal)info.GetValue("Balance", typeof(decimal)); Creditor[] convertedCreditors = (Creditor[])info.GetValue("Creditors", typeof(Creditor[])); Creditors = convertedCreditors == null ? null : convertedCreditors.ToDictionary(c => c.Name, t => t.Balance); } public void GetObjectData(SerializationInfo info, StreamingContext context) { info.AddValue("Name", Name); info.AddValue("Balance", Balance); Creditor[] convertedCreditors = Creditors == null ? null : Creditors.Select(kvp => new Creditor { Name = kvp.Key, Balance = kvp.Value }).ToArray(); info.AddValue("Creditors", convertedCreditors); } [Serializable] private class Creditor { internal string Name { get; set; } internal decimal Balance { get; set; } } } }
37.625
121
0.627243
[ "MIT" ]
sport-monkey/devtest
CustomerProcessor/BasicAccountDetails.cs
1,507
C#
namespace MechEngineer.Features.Performance; internal class PerformanceSettings : ISettings { public bool Enabled { get; set; } = false; public string EnabledDescription => "Some performance patches to the vanilla game. Could interfere with other performance patches from other mods."; }
42.285714
152
0.780405
[ "Unlicense" ]
CptMoore/MechEngineMod
source/Features/Performance/PerformanceSettings.cs
296
C#