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
namespace NorthwindApi.Areas.HelpPage { /// <summary> /// Indicates whether the sample is used for request or response /// </summary> public enum SampleDirection { Request = 0, Response } }
20.818182
68
0.611354
[ "MIT" ]
addinfinity/Northwind
NorthwindApi/Areas/HelpPage/SampleGeneration/SampleDirection.cs
229
C#
using AntMe.Runtime; using System; using System.Collections.Generic; using System.Linq; namespace AntMe.Generator { /// <summary> /// Code Generator to generate the players Source Template. /// </summary> public sealed class TemplateGenerator { private List<string> factions; private List<string> languages; private List<string> programmingLanguages; private List<string> environments; /// <summary> /// List of available Factions to generate for. /// </summary> public IEnumerable<string> Factions { get { return factions; } } /// <summary> /// List of available natural Languages. /// </summary> public IEnumerable<string> Languages { get { return languages; } } /// <summary> /// List of available Programming Languages. /// </summary> public IEnumerable<string> ProgrammingLanguages { get { return programmingLanguages; } } /// <summary> /// List of supported IDEs. /// </summary> public IEnumerable<string> Environments { get { return environments; } } public TemplateGenerator() { factions = new List<string>(ExtensionLoader.DefaultTypeMapper.Factions.Select(f => f.Name)); languages = new List<string>(ExtensionLoader.LocalizedLanguages); programmingLanguages = new List<string>(new[] { "C#", "VB.NET" }); environments = new List<string>(new[] { "Visual Studio 2015", "Visual Studio Code" }); } public void Generate(string name, string author, string faction, string language, string programmingLanguage, string environment, string outputFolder) { // TODO: Do the Magic ModpackGenerator.Generate(language, outputFolder, ExtensionLoader.DefaultTypeMapper); } } }
33.333333
158
0.621053
[ "MIT" ]
OmegaRogue/AntMeCore
src/AntMe.Generator/TemplateGenerator.cs
1,902
C#
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Immutable; using System.Composition; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslynator.CSharp.Refactorings; namespace Roslynator.CSharp.CodeFixes { [ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(LocalDeclarationStatementCodeFixProvider))] [Shared] public class LocalDeclarationStatementCodeFixProvider : BaseCodeFixProvider { public sealed override ImmutableArray<string> FixableDiagnosticIds { get { return ImmutableArray.Create( DiagnosticIdentifiers.MarkLocalVariableAsConst, DiagnosticIdentifiers.InlineLocalVariable); } } public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { SyntaxNode root = await context.GetSyntaxRootAsync().ConfigureAwait(false); if (!TryFindFirstAncestorOrSelf(root, context.Span, out LocalDeclarationStatementSyntax localDeclaration)) return; foreach (Diagnostic diagnostic in context.Diagnostics) { switch (diagnostic.Id) { case DiagnosticIdentifiers.MarkLocalVariableAsConst: { string names = GetNames(localDeclaration); CodeAction codeAction = CodeAction.Create( $"Mark {names} as const", cancellationToken => MarkLocalVariableAsConstRefactoring.RefactorAsync(context.Document, localDeclaration, cancellationToken), GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); break; } case DiagnosticIdentifiers.InlineLocalVariable: { CodeAction codeAction = CodeAction.Create( "Inline local variable", cancellationToken => InlineLocalVariableRefactoring.RefactorAsync(context.Document, localDeclaration, cancellationToken), GetEquivalenceKey(diagnostic)); context.RegisterCodeFix(codeAction, diagnostic); break; } } } } private string GetNames(LocalDeclarationStatementSyntax localDeclaration) { VariableDeclarationSyntax declaration = localDeclaration.Declaration; SeparatedSyntaxList<VariableDeclaratorSyntax> variables = declaration.Variables; if (variables.Count == 1) { return $"'{variables.First().Identifier.ValueText}'"; } else { return string.Join(", ", variables.Select(f => $"'{f.Identifier.ValueText}'")); } } } }
40.361446
160
0.590746
[ "Apache-2.0" ]
TechnoridersForks/Roslynator
source/Analyzers/CodeFixProviders/LocalDeclarationStatementCodeFixProvider.cs
3,352
C#
using Microsoft.Maui.Graphics; #if __IOS__ || MACCATALYST using PlatformView = UIKit.UIView; #elif __ANDROID__ using PlatformView = Android.Views.View; #elif WINDOWS using PlatformView = Microsoft.UI.Xaml.FrameworkElement; #elif TIZEN using PlatformView = ElmSharp.EvasObject; #elif (NETSTANDARD || !PLATFORM) using PlatformView = System.Object; #endif namespace Microsoft.Maui.Handlers { public abstract partial class ViewHandler : ElementHandler, IViewHandler { public static IPropertyMapper<IView, IViewHandler> ViewMapper = #if ANDROID // Use a custom mapper for Android which knows how to batch the initial property sets new AndroidBatchPropertyMapper<IView, IViewHandler>(ElementMapper) #else new PropertyMapper<IView, IViewHandler>(ElementHandler.ElementMapper) #endif { [nameof(IView.AutomationId)] = MapAutomationId, [nameof(IView.Clip)] = MapClip, [nameof(IView.Shadow)] = MapShadow, [nameof(IView.Visibility)] = MapVisibility, [nameof(IView.Background)] = MapBackground, [nameof(IView.FlowDirection)] = MapFlowDirection, [nameof(IView.Width)] = MapWidth, [nameof(IView.Height)] = MapHeight, [nameof(IView.MinimumHeight)] = MapMinimumHeight, [nameof(IView.MaximumHeight)] = MapMaximumHeight, [nameof(IView.MinimumWidth)] = MapMinimumWidth, [nameof(IView.MaximumWidth)] = MapMaximumWidth, [nameof(IView.IsEnabled)] = MapIsEnabled, [nameof(IView.Opacity)] = MapOpacity, [nameof(IView.Semantics)] = MapSemantics, [nameof(IView.TranslationX)] = MapTranslationX, [nameof(IView.TranslationY)] = MapTranslationY, [nameof(IView.Scale)] = MapScale, [nameof(IView.ScaleX)] = MapScaleX, [nameof(IView.ScaleY)] = MapScaleY, [nameof(IView.Rotation)] = MapRotation, [nameof(IView.RotationX)] = MapRotationX, [nameof(IView.RotationY)] = MapRotationY, [nameof(IView.AnchorX)] = MapAnchorX, [nameof(IView.AnchorY)] = MapAnchorY, [nameof(IViewHandler.ContainerView)] = MapContainerView, [nameof(IBorder.Border)] = MapBorderView, #if ANDROID || WINDOWS [nameof(IToolbarElement.Toolbar)] = MapToolbar, #endif [nameof(IView.InputTransparent)] = MapInputTransparent, }; public static CommandMapper<IView, IViewHandler> ViewCommandMapper = new() { [nameof(IView.InvalidateMeasure)] = MapInvalidateMeasure, [nameof(IView.Frame)] = MapFrame, [nameof(IView.ZIndex)] = MapZIndex, [nameof(IView.Focus)] = MapFocus, [nameof(IView.Unfocus)] = MapUnfocus, }; bool _hasContainer; protected ViewHandler(IPropertyMapper mapper, CommandMapper? commandMapper = null) : base(mapper, commandMapper ?? ViewCommandMapper) { } public bool HasContainer { get => _hasContainer; set { if (_hasContainer == value) return; _hasContainer = value; if (value) SetupContainer(); else RemoveContainer(); } } protected abstract void SetupContainer(); protected abstract void RemoveContainer(); public PlatformView? ContainerView { get; private protected set; } object? IViewHandler.ContainerView => ContainerView; public new PlatformView? PlatformView { get => (PlatformView?)base.PlatformView; private protected set => base.PlatformView = value; } public new IView? VirtualView { get => (IView?)base.VirtualView; private protected set => base.VirtualView = value; } public abstract Size GetDesiredSize(double widthConstraint, double heightConstraint); public abstract void PlatformArrange(Rect frame); private protected abstract PlatformView OnCreatePlatformView(); private protected sealed override object OnCreatePlatformElement() => OnCreatePlatformView(); #if ANDROID // This sets up AndroidBatchPropertyMapper public override void SetVirtualView(IElement element) { base.SetVirtualView(element); if (element is IView view) { ((PlatformView?)PlatformView)?.Initialize(view); } } #endif #if !(NETSTANDARD || !PLATFORM) private protected abstract void OnConnectHandler(PlatformView platformView); partial void ConnectingHandler(PlatformView? platformView); private protected sealed override void OnConnectHandler(object platformView) { ConnectingHandler((PlatformView)platformView); OnConnectHandler((PlatformView)platformView); } private protected abstract void OnDisconnectHandler(PlatformView platformView); partial void DisconnectingHandler(PlatformView platformView); private protected sealed override void OnDisconnectHandler(object platformView) { DisconnectingHandler((PlatformView)platformView); OnDisconnectHandler((PlatformView)platformView); } #endif public static void MapWidth(IViewHandler handler, IView view) { ((PlatformView?)handler.PlatformView)?.UpdateWidth(view); } public static void MapHeight(IViewHandler handler, IView view) { ((PlatformView?)handler.PlatformView)?.UpdateHeight(view); } public static void MapMinimumHeight(IViewHandler handler, IView view) { ((PlatformView?)handler.PlatformView)?.UpdateMinimumHeight(view); } public static void MapMaximumHeight(IViewHandler handler, IView view) { ((PlatformView?)handler.PlatformView)?.UpdateMaximumHeight(view); } public static void MapMinimumWidth(IViewHandler handler, IView view) { ((PlatformView?)handler.PlatformView)?.UpdateMinimumWidth(view); } public static void MapMaximumWidth(IViewHandler handler, IView view) { ((PlatformView?)handler.PlatformView)?.UpdateMaximumWidth(view); } public static void MapIsEnabled(IViewHandler handler, IView view) { ((PlatformView?)handler.PlatformView)?.UpdateIsEnabled(view); } public static void MapVisibility(IViewHandler handler, IView view) { if (handler.HasContainer) ((PlatformView?)handler.ContainerView)?.UpdateVisibility(view); else ((PlatformView?)handler.PlatformView)?.UpdateVisibility(view); } public static void MapBackground(IViewHandler handler, IView view) { if (handler.PlatformView is not PlatformView platformView) return; if (view.Background is ImageSourcePaint image) { var provider = handler.GetRequiredService<IImageSourceServiceProvider>(); platformView.UpdateBackgroundImageSourceAsync(image.ImageSource, provider) .FireAndForget(handler); } else { platformView.UpdateBackground(view); } } public static void MapFlowDirection(IViewHandler handler, IView view) { ((PlatformView?)handler.PlatformView)?.UpdateFlowDirection(view); } public static void MapOpacity(IViewHandler handler, IView view) { if (handler.HasContainer) ((PlatformView?)handler.ContainerView)?.UpdateOpacity(view); else ((PlatformView?)handler.PlatformView)?.UpdateOpacity(view); } public static void MapAutomationId(IViewHandler handler, IView view) { ((PlatformView?)handler.PlatformView)?.UpdateAutomationId(view); } public static void MapClip(IViewHandler handler, IView view) { var clipShape = view.Clip; if (clipShape != null) { handler.HasContainer = true; } else { if (handler is ViewHandler viewHandler) handler.HasContainer = viewHandler.NeedsContainer; } ((PlatformView?)handler.ContainerView)?.UpdateClip(view); } public static void MapShadow(IViewHandler handler, IView view) { var shadow = view.Shadow; UpdateHasContainer(handler, shadow != null); ((PlatformView?)handler.ContainerView)?.UpdateShadow(view); } static partial void MappingSemantics(IViewHandler handler, IView view); public static void MapSemantics(IViewHandler handler, IView view) { MappingSemantics(handler, view); ((PlatformView?)handler.PlatformView)?.UpdateSemantics(view); } public static void MapInvalidateMeasure(IViewHandler handler, IView view, object? args) { (handler.PlatformView as PlatformView)?.InvalidateMeasure(view); } public static void MapContainerView(IViewHandler handler, IView view) { if (handler is ViewHandler viewHandler) handler.HasContainer = viewHandler.NeedsContainer; } public static void MapBorderView(IViewHandler handler, IView view) { var border = (view as IBorder)?.Border; if (border != null) { handler.HasContainer = true; } else { if (handler is ViewHandler viewHandler) handler.HasContainer = viewHandler.NeedsContainer; } ((PlatformView?)handler.ContainerView)?.UpdateBorder(view); } static partial void MappingFrame(IViewHandler handler, IView view); public static void MapFrame(IViewHandler handler, IView view, object? args) { MappingFrame(handler, view); } public static void MapZIndex(IViewHandler handler, IView view, object? args) { if (view.Parent is ILayout layout) { layout.Handler?.Invoke(nameof(ILayoutHandler.UpdateZIndex), view); } } public static void MapFocus(IViewHandler handler, IView view, object? args) { if (args is FocusRequest request) { if (handler.PlatformView == null) { return; } ((PlatformView?)handler.PlatformView)?.Focus(request); } } public static void MapInputTransparent(IViewHandler handler, IView view) { #if ANDROID var inputTransparent = view.InputTransparent; UpdateHasContainer(handler, inputTransparent); if (handler.ContainerView is WrapperView wrapper) { wrapper.InputTransparent = inputTransparent; } #else ((PlatformView?)handler.PlatformView)?.UpdateInputTransparent(handler, view); #endif } public static void MapUnfocus(IViewHandler handler, IView view, object? args) { ((PlatformView?)handler.PlatformView)?.Unfocus(view); } static void UpdateHasContainer(IViewHandler handler, bool definitelyNeedsContainer) { if (definitelyNeedsContainer) { handler.HasContainer = true; } else { if (handler is ViewHandler viewHandler) handler.HasContainer = viewHandler.NeedsContainer; } } } }
27.655556
89
0.732824
[ "MIT" ]
10088/maui
src/Core/src/Handlers/View/ViewHandler.cs
9,956
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Iot.Model.V20180120; namespace Aliyun.Acs.Iot.Transform.V20180120 { public class CreateConsumerGroupResponseUnmarshaller { public static CreateConsumerGroupResponse Unmarshall(UnmarshallerContext _ctx) { CreateConsumerGroupResponse createConsumerGroupResponse = new CreateConsumerGroupResponse(); createConsumerGroupResponse.HttpResponse = _ctx.HttpResponse; createConsumerGroupResponse.RequestId = _ctx.StringValue("CreateConsumerGroup.RequestId"); createConsumerGroupResponse.Success = _ctx.BooleanValue("CreateConsumerGroup.Success"); createConsumerGroupResponse.ErrorMessage = _ctx.StringValue("CreateConsumerGroup.ErrorMessage"); createConsumerGroupResponse.GroupId = _ctx.StringValue("CreateConsumerGroup.GroupId"); createConsumerGroupResponse.Code = _ctx.StringValue("CreateConsumerGroup.Code"); return createConsumerGroupResponse; } } }
41.659091
100
0.775777
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-iot/Iot/Transform/V20180120/CreateConsumerGroupResponseUnmarshaller.cs
1,833
C#
// <copyright file="IHistogram.cs" company="App Metrics Contributors"> // Copyright (c) App Metrics Contributors. All rights reserved. // </copyright> namespace App.Metrics.Histogram { /// <summary> /// A Histogram measures the distribution of values in a stream of data: e.g., the number of results returned by a /// search. /// </summary> public interface IHistogram : IResetableMetric { /// <summary> /// Records a value. /// </summary> /// <param name="value">Value to be added to the histogram.</param> /// <param name="userValue"> /// A custom user value that will be associated to the results. /// Useful for tracking (for example) for which id the max or min value was recorded. /// </param> void Update(long value, string userValue); /// <summary> /// Records a value. /// </summary> /// <param name="value">Value to be added to the histogram.</param> void Update(long value); } }
36.413793
122
0.590909
[ "Apache-2.0" ]
8adre/AppMetrics
src/Core/src/App.Metrics.Abstractions/Histogram/IHistogram.cs
1,058
C#
using System.Text.Json.Serialization; namespace nerderies.TelegramBotApi.DTOS { public class SendPhotoReply : Reply { [JsonPropertyName("result")] [JsonInclude] public Message SentMessage; } }
19.25
39
0.670996
[ "MIT" ]
devnulli/TelegramBotApi.NET
TelegramBotApi/TelegramBotApi/DTOS/Replies/SendPhotoReply.cs
233
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Jag.Spice.Interfaces { using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Regardingobjectidspiceexportrequestemail operations. /// </summary> public partial interface IRegardingobjectidspiceexportrequestemail { /// <summary> /// Get regardingobjectid_spice_exportrequest_email from emails /// </summary> /// <param name='activityid'> /// key: activityid of email /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse<MicrosoftDynamicsCRMspiceExportrequest>> GetWithHttpMessagesAsync(string activityid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
39.313725
335
0.648878
[ "Apache-2.0" ]
BrendanBeachBC/jag-spd-spice
interfaces/Dynamics-Autorest/IRegardingobjectidspiceexportrequestemail.cs
2,005
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Network.V20190801 { /// <summary> /// Route table resource. /// </summary> [AzureNextGenResourceType("azure-nextgen:network/v20190801:RouteTable")] public partial class RouteTable : Pulumi.CustomResource { /// <summary> /// Whether to disable the routes learned by BGP on that route table. True means disable. /// </summary> [Output("disableBgpRoutePropagation")] public Output<bool?> DisableBgpRoutePropagation { get; private set; } = null!; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Output("etag")] public Output<string?> Etag { 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 route table resource. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// Collection of routes contained within a route table. /// </summary> [Output("routes")] public Output<ImmutableArray<Outputs.RouteResponse>> Routes { get; private set; } = null!; /// <summary> /// A collection of references to subnets. /// </summary> [Output("subnets")] public Output<ImmutableArray<Outputs.SubnetResponse>> Subnets { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a RouteTable 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 RouteTable(string name, RouteTableArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:network/v20190801:RouteTable", name, args ?? new RouteTableArgs(), MakeResourceOptions(options, "")) { } private RouteTable(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:network/v20190801:RouteTable", 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:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/latest:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20150501preview:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20150615:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20160330:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20160601:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20160901:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20161201:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170301:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170601:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170801:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20170901:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20171001:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20171101:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180101:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180201:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180401:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180601:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180701:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20180801:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181001:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181101:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20181201:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190201:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:RouteTable"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:RouteTable"}, }, }; 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 RouteTable 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 RouteTable Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new RouteTable(name, id, options); } } public sealed class RouteTableArgs : Pulumi.ResourceArgs { /// <summary> /// Whether to disable the routes learned by BGP on that route table. True means disable. /// </summary> [Input("disableBgpRoutePropagation")] public Input<bool>? DisableBgpRoutePropagation { get; set; } /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Input("etag")] public Input<string>? Etag { get; set; } /// <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 name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the route table. /// </summary> [Input("routeTableName")] public Input<string>? RouteTableName { get; set; } [Input("routes")] private InputList<Inputs.RouteArgs>? _routes; /// <summary> /// Collection of routes contained within a route table. /// </summary> public InputList<Inputs.RouteArgs> Routes { get => _routes ?? (_routes = new InputList<Inputs.RouteArgs>()); set => _routes = value; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public RouteTableArgs() { } } }
44.678733
134
0.583451
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Network/V20190801/RouteTable.cs
9,874
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace dla { class dla { static void Main(string[] args) { foreach (var t in args) { Console.WriteLine(t); } if (args.Length == 0) { dlaHelpWanted(); } else { Commands ResultICommand; if (Enum.TryParse(args[0], out ResultICommand)) { System.Diagnostics.ProcessStartInfo NewProcess = new System.Diagnostics.ProcessStartInfo(ResultICommand.ToString()); NewProcess.UseShellExecute = false; NewProcess.Arguments = string.Concat(args.Where(x => x != ResultICommand.ToString()).Select(x => x + ' ')); System.Diagnostics.Process.Start(NewProcess); } else { dlaHelpWanted(); } } } static void dlaHelpWanted() { Console.WriteLine("Using dla: [Command] [PathBase] [PathDest] {Method:int}"); Console.WriteLine(" 1: ar - Zipping"); Console.WriteLine(" 2: dar - Unzipping"); } } }
29.822222
136
0.487332
[ "Unlicense" ]
DLArch/Dynamically-linked-archiving-methods-Console
Console/dla/dla.cs
1,344
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; using System.Text.Encodings.Web; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; namespace TestUserAuth.Areas.Identity.Pages.Account.Manage { public partial class EmailModel : PageModel { private readonly UserManager<IdentityUser> _userManager; private readonly SignInManager<IdentityUser> _signInManager; private readonly IEmailSender _emailSender; public EmailModel( UserManager<IdentityUser> userManager, SignInManager<IdentityUser> signInManager, IEmailSender emailSender) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; } public string Username { get; set; } public string Email { get; set; } public bool IsEmailConfirmed { get; set; } [TempData] public string StatusMessage { get; set; } [BindProperty] public InputModel Input { get; set; } public class InputModel { [Required] [EmailAddress] [Display(Name = "New email")] public string NewEmail { get; set; } } private async Task LoadAsync(IdentityUser user) { var email = await _userManager.GetEmailAsync(user); Email = email; Input = new InputModel { NewEmail = email, }; IsEmailConfirmed = await _userManager.IsEmailConfirmedAsync(user); } public async Task<IActionResult> OnGetAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } await LoadAsync(user); return Page(); } public async Task<IActionResult> OnPostChangeEmailAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } if (!ModelState.IsValid) { await LoadAsync(user); return Page(); } var email = await _userManager.GetEmailAsync(user); if (Input.NewEmail != email) { var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateChangeEmailTokenAsync(user, Input.NewEmail); var callbackUrl = Url.Page( "/Account/ConfirmEmailChange", pageHandler: null, values: new { userId = userId, email = Input.NewEmail, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync( Input.NewEmail, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); StatusMessage = "Confirmation link to change email sent. Please check your email."; return RedirectToPage(); } StatusMessage = "Your email is unchanged."; return RedirectToPage(); } public async Task<IActionResult> OnPostSendVerificationEmailAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } if (!ModelState.IsValid) { await LoadAsync(user); return Page(); } var userId = await _userManager.GetUserIdAsync(user); var email = await _userManager.GetEmailAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync( email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); StatusMessage = "Verification email sent. Please check your email."; return RedirectToPage(); } } }
34.326531
126
0.572731
[ "MIT" ]
Csharp2020/csharp2020
pmrvic/MVCRazvoj/Fakultet/Areas/Identity/Pages/Account/Manage/Email.cshtml.cs
5,048
C#
using System.Collections.Generic; using AonWeb.FluentHttp.HAL; namespace AonWeb.FluentHttp.Mocks.Hal { public class MockHalBuilderFactory : HalBuilderFactory, IMockHalBuilderFactory { public MockHalBuilderFactory() : this(new MockTypedBuilderFactory(), new [] { new HalConfiguration() }) { } public MockHalBuilderFactory( ITypedBuilderFactory typedBuilderFactory, IEnumerable<IBuilderConfiguration<IHalBuilder>> configurations) : base(typedBuilderFactory, configurations) { } protected override IHalBuilder GetBuilder(IChildTypedBuilder innerBuilder) { return new MockHalBuilder((IMockTypedBuilder)innerBuilder); } public new IMockHalBuilder Create() { return (IMockHalBuilder)base.Create(); } } }
30.551724
82
0.651242
[ "MIT" ]
andrewescutia/fluent-http
AonWeb.FluentHttp.Mocks/Hal/MockHalBuilderFactory.cs
886
C#
using System; namespace lab_17_selection { public class PassFailClass { static void Main(string[] args) { Console.WriteLine(PassFailTernary(41)); } public static string PassFailTernary(int mark) { return mark >= 40 ? "Pass" : "Fail"; } public static string PassFail (int mark) { var grade = "Fail"; if (mark >= 40) { grade = "Pass"; } return grade; } public static string Grade (int mark) { if (mark >= 40 && mark <= 59) return "Pass"; else if (mark >= 75 && mark <= 100) return "Pass with distinction"; else if (mark >= 60 && mark <= 74) return "Pass with merit"; else if (mark >= 0 && mark <= 39) return "Fail"; else return "Invalid input"; } public static string GradeNish(int mark) { var grade = ""; if (mark >= 40) { grade = "Pass"; if (mark >= 75) { grade += " with Distinction"; } else if (mark > -60) { grade += " with Merit"; } } else { grade = "Fail"; } return grade; } public static string AlertLevel(int level) { string priority = "Code"; switch (level) { case 3: priority = priority + "Red"; break; case 2: case 1: priority = priority + "Amber"; break; case 0: priority = priority + "Green"; break; default: priority = "error"; break; } return priority; } } }
25.182927
79
0.373366
[ "MIT" ]
chenshanmugarajah/2020-06-c-sharp-labs
labs/lab_17_selection/Program.cs
2,067
C#
namespace Furiza.AspNetCore.WebApi.Configuration.SecurityProvider.Dtos.v1.Auth { public enum GrantType { Password, RefreshToken } }
20
79
0.68125
[ "MIT" ]
ivanborges/furiza-aspnetcore
src/Furiza.AspNetCore.WebApi.Configuration.SecurityProvider/Dtos/v1/Auth/GrantType.cs
162
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 System.Xml.Linq; using Azure.Core; namespace ContasimpleAPI.Models { public partial class ApiListResultProductStockOperationApiModel { internal static ApiListResultProductStockOperationApiModel DeserializeApiListResultProductStockOperationApiModel(JsonElement element) { Optional<long> count = default; Optional<IReadOnlyList<ProductStockOperationApiModel>> data = default; Optional<long> totalCount = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("count")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } count = property.Value.GetInt64(); continue; } if (property.NameEquals("data")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } List<ProductStockOperationApiModel> array = new List<ProductStockOperationApiModel>(); foreach (var item in property.Value.EnumerateArray()) { array.Add(ProductStockOperationApiModel.DeserializeProductStockOperationApiModel(item)); } data = array; continue; } if (property.NameEquals("totalCount")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } totalCount = property.Value.GetInt64(); continue; } } return new ApiListResultProductStockOperationApiModel(Optional.ToNullable(count), Optional.ToList(data), Optional.ToNullable(totalCount)); } internal static ApiListResultProductStockOperationApiModel DeserializeApiListResultProductStockOperationApiModel(XElement element) { long? count = default; long? totalCount = default; IReadOnlyList<ProductStockOperationApiModel> data = default; if (element.Element("count") is XElement countElement) { count = (long?)countElement; } if (element.Element("totalCount") is XElement totalCountElement) { totalCount = (long?)totalCountElement; } var array = new List<ProductStockOperationApiModel>(); foreach (var e in element.Elements("ProductStockOperationApiModel")) { array.Add(ProductStockOperationApiModel.DeserializeProductStockOperationApiModel(e)); } data = array; return new ApiListResultProductStockOperationApiModel(count, data, totalCount); } } }
39.872093
150
0.560222
[ "MIT" ]
JonasBr68/ContaSimpleClient
ClientApi/generated/Models/ApiListResultProductStockOperationApiModel.Serialization.cs
3,429
C#
using System; using System.Collections.Generic; using System.IO; using System.Net; namespace DotnetHttpClient { /// <summary> /// A container for generalized request inputs. This type allows consumers to extend the request functionality /// by abstracting away from the default (built-in) request framework (e.g. RestSharp). /// </summary> public class RequestOptions { /// <summary> /// Parameters to be bound to path parts of the Request's URL /// </summary> public Dictionary<string, string> PathParameters { get; set; } /// <summary> /// Query parameters to be applied to the request. /// Keys may have 1 or more values associated. /// </summary> public IDictionary<string, string> QueryParameters { get; set; } /// <summary> /// Header parameters to be applied to to the request. /// Keys may have 1 or more values associated. /// </summary> public IDictionary<string, string> HeaderParameters { get; set; } /// <summary> /// Form parameters to be sent along with the request. /// </summary> public Dictionary<string, string> FormParameters { get; set; } /// <summary> /// File parameters to be sent along with the request. /// </summary> public Dictionary<string, Stream> FileParameters { get; set; } /// <summary> /// Cookies to be sent along with the request. /// </summary> public List<Cookie> Cookies { get; set; } /// <summary> /// Any data associated with a request body. /// </summary> public Object Data { get; set; } /// <summary> /// Constructs a new instance of <see cref="RequestOptions"/> /// </summary> public RequestOptions() { PathParameters = new Dictionary<string, string>(); QueryParameters = new Dictionary<string, string>(); HeaderParameters = new Dictionary<string, string>(); FormParameters = new Dictionary<string, string>(); FileParameters = new Dictionary<string, Stream>(); Cookies = new List<Cookie>(); } } }
34.446154
114
0.589549
[ "MIT" ]
ddieruf/dotnet-httpclient
dotnet-httpclient/RequestOptions.cs
2,239
C#
using Newtonsoft.Json; using System; using System.Globalization; namespace TMDbLib.Utilities.Converters { public class TmdbPartialDateConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(DateTime?); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { string str = reader.Value as string; if (string.IsNullOrEmpty(str)) return null; DateTime result; if (!DateTime.TryParse(str, CultureInfo.InvariantCulture.DateTimeFormat, DateTimeStyles.None, out result)) return null; return result; } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { DateTime? date = value as DateTime?; writer.WriteValue(date?.ToString(CultureInfo.InvariantCulture)); } } }
31.121212
124
0.639727
[ "MIT" ]
1337joe/TMDbLib
TMDbLib/Utilities/Converters/TmdbPartialDateConverter.cs
1,029
C#
using SNT.Data; using SNT.Models; using SNT.ServiceModels; using SNT.ViewModels.Home; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SNT.Services { public class ShoppingBagService : IShoppingBagService { private SntDbContext context; public ShoppingBagService(SntDbContext context) { this.context = context; } public async Task<bool> AddTyreToShoppingBag(string tyreId, string userId) { var user = this.context.Users.FirstOrDefault(x => x.Id == userId); if (user == null || tyreId == null) { return false; } var currentTyre = context.ShoppingBagTyres.FirstOrDefault(x => x.UserId == user.Id && x.TyreId == tyreId); if (currentTyre != null) { return true; } var tyre = this.context.Tyres.SingleOrDefault(x => x.Id == tyreId); var shoppingBagTyre = new ShoppingBagTyre { UserId = user.Id, TyreId = tyreId, Model = tyre.Model, Brand = tyre.Brand, Price = tyre.Price, Picture = tyre.Picture, Quantity = 1, }; this.context.ShoppingBagTyres.Add(shoppingBagTyre); await this.context.SaveChangesAsync(); return true; } public async Task<bool> AddMotorOilToShoppingBag(string motorOilId, string userId) { var user = this.context.Users.FirstOrDefault(x => x.Id == userId); if (user == null || motorOilId == null) { return false; } var currentMotorOil = context.ShoppingBagMotorOils.FirstOrDefault(x => x.UserId == user.Id && x.MotorOilId == motorOilId); if (currentMotorOil != null) { return true; } var motorOil = this.context.MotorOils.SingleOrDefault(x => x.Id == motorOilId); var shoppingMotorOil = new ShoppingBagMotorOil { UserId = user.Id, MotorOilId = motorOil.Id, Model = motorOil.Model, Brand = motorOil.Brand, Price = motorOil.Price, Picture = motorOil.Picture, Quantity = 1, }; this.context.ShoppingBagMotorOils.Add(shoppingMotorOil); await this.context.SaveChangesAsync(); return true; } public async Task<bool> AddWheelRimToShoppingBag(string wheelRimId, string userId) { var user = this.context.Users.FirstOrDefault(x => x.Id == userId); if (user == null || wheelRimId == null) { return false; } var currentTyre = context.ShoppingBagWheelRims.FirstOrDefault(x => x.UserId == user.Id && x.WheelRimId == wheelRimId); if (currentTyre != null) { return true; } var wheelRim = this.context.WheelRims.SingleOrDefault(x => x.Id == wheelRimId); var shoppingBagWheelRim = new ShoppingBagWheelRim { UserId = user.Id, WheelRimId = wheelRimId, Model = wheelRim.Model, Brand = wheelRim.Brand, Price = wheelRim.Price, Picture = wheelRim.Picture, Quantity = 1, }; this.context.ShoppingBagWheelRims.Add(shoppingBagWheelRim); await this.context.SaveChangesAsync(); return true; } public ShoppingBagHomeViewModel GetAllCartProducts(string userId) { var user = this.context.Users.FirstOrDefault(x => x.Id == userId); HashSet<ShoppingBagTyre> bagTyres = new HashSet<ShoppingBagTyre>(); foreach (var tyre in this.context.ShoppingBagTyres.Where(x => x.UserId == user.Id)) { bagTyres.Add(tyre); } HashSet<ShoppingBagWheelRim> bagWheelRims = new HashSet<ShoppingBagWheelRim>(); foreach (var wheelRim in this.context.ShoppingBagWheelRims.Where(x => x.UserId == user.Id)) { bagWheelRims.Add(wheelRim); } HashSet<ShoppingBagMotorOil> bagMotorOils = new HashSet<ShoppingBagMotorOil>(); foreach (var motorOil in this.context.ShoppingBagMotorOils.Where(x => x.UserId == user.Id)) { bagMotorOils.Add(motorOil); } user.ShoppingBag.Tyres = bagTyres; user.ShoppingBag.WheelRims = bagWheelRims; user.ShoppingBag.MotorOils = bagMotorOils; this.context.ShoppingBag.Update(user.ShoppingBag); this.context.SaveChangesAsync(); return new ShoppingBagHomeViewModel(bagTyres, bagWheelRims, bagMotorOils, user.Id); } public void RemoveTyreFromShoppingBag(string bagTyreId, string userId) { var bagTyre = this.context.ShoppingBagTyres.FirstOrDefault(x => x.Id == bagTyreId && x.UserId == userId); this.context.ShoppingBagTyres.Remove(bagTyre); this.context.SaveChanges(); } public void RemoveWheelRimFromShoppingBag(string bagWheelRimId, string userId) { var bagWheelRim = this.context.ShoppingBagWheelRims.FirstOrDefault(x => x.Id == bagWheelRimId && x.UserId == userId); this.context.ShoppingBagWheelRims.Remove(bagWheelRim); this.context.SaveChanges(); } public void RemoveMotorOilFromShoppingBag(string bagMotorOilId, string userId) { var bagMotorOil = this.context.ShoppingBagMotorOils.FirstOrDefault(x => x.Id == bagMotorOilId && x.UserId == userId); this.context.ShoppingBagMotorOils.Remove(bagMotorOil); this.context.SaveChanges(); } public void RemoveAllShoppingBagProducts(string userId) { var user = this.context.Users.FirstOrDefault(x => x.Id == userId); var bagTyres = this.context.ShoppingBagTyres.Where(x => x.UserId == userId); var bagWheelRims = this.context.ShoppingBagWheelRims.Where(x => x.UserId == userId); var bagMotorOils = this.context.ShoppingBagMotorOils.Where(x => x.UserId == userId); this.context.ShoppingBagTyres.RemoveRange(bagTyres); this.context.ShoppingBagWheelRims.RemoveRange(bagWheelRims); this.context.ShoppingBagMotorOils.RemoveRange(bagMotorOils); this.context.SaveChanges(); } public void UpdateShoppingBagTyreQuantity (string bagTyreId,int quantity) { var tyreFromDb = this.context.ShoppingBagTyres.FirstOrDefault(x => x.Id == bagTyreId); tyreFromDb.Quantity = quantity; this.context.Update(tyreFromDb); this.context.SaveChanges(); } public void UpdateShoppingBagWheelRimQuantity (string bagWheelRimId,int quantity) { var wheelRimFromDb = this.context.ShoppingBagWheelRims.FirstOrDefault(x => x.Id == bagWheelRimId); wheelRimFromDb.Quantity = quantity; this.context.Update(wheelRimFromDb); this.context.SaveChanges(); } public void UpdateShoppingBagMotorOilQuantity (string motorOilId, int quantity) { var motorOilFromDb = this.context.ShoppingBagMotorOils.FirstOrDefault(x => x.Id == motorOilId); motorOilFromDb.Quantity = quantity; this.context.Update(motorOilFromDb); this.context.SaveChanges(); } public Task<ShoppingBagServiceModel> AddTyreToShoppingBag() { throw new NotImplementedException(); } } }
32.605691
134
0.581224
[ "MIT" ]
danailstratiev/SNT-Beta
SNT/SNT/Services/ShoppingBagService.cs
8,023
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; // Code adapted from Nicole's "note_launcher" script. public class Bull_Note_Attack : Actor { [SerializeField] int ProjectileAmount = 10; [SerializeField] GameObject musicNotes = null; Vector2 startPoint = Vector2.zero; public float radius = 5f; public float moveSpeed = 5f; public float repeatRate = 5.0f; public int waveMinRange = 3; public int waveMaxRange = 7; protected int waveTotal = 0; protected int counter = 0; private float repeatCounter = 5f; //public Transform spawnPos; void Update() { //float for time total //random.range 5-9 //if if (counter >= waveTotal) { Destroy(gameObject); } if(repeatCounter >= repeatRate) { SpawnNotes(ProjectileAmount); } else { repeatCounter += Time.deltaTime; } } void Awake() { startPoint = transform.position; waveTotal = Random.Range(waveMinRange, waveMaxRange + 1); repeatCounter = repeatRate; } private void Active(Collider other) { InvokeRepeating("projectile", 0.5f, repeatRate); gameObject.GetComponent<BoxCollider2D>().enabled = false; } void SpawnNotes(int ProjectileAmount) { repeatCounter = 0f; float angle = 0f; int actualAmount = ProjectileAmount + Random.Range(-2, 3); //float angleStep = 360f / actualAmount; for (int i = 0; i < actualAmount; i++) { angle = Random.Range(-110f, 110f); float projectileDirXposition = startPoint.x + Mathf.Sin((angle * Mathf.PI) / 180) * radius; float projectileDirYposition = startPoint.y + Mathf.Cos((angle * Mathf.PI) / 180) * radius; Vector2 projectileVector = new Vector2(projectileDirXposition, projectileDirYposition); Vector2 projectileMoveDirection = (projectileVector - startPoint).normalized * moveSpeed; //GameObject note = Instantiate(musicNotes, startPoint, Quaternion.identity); GameObject note = Spawner(musicNotes, startPoint, Quaternion.identity, Owner); note.GetComponent<Rigidbody2D>().velocity = new Vector2(projectileMoveDirection.x, projectileMoveDirection.y); //angle += angleStep; } counter++; } }
25.536082
122
0.616068
[ "MIT" ]
AGGP-NHTI/GinyuForce
Assets/Scripts/Bosses/Bull/Attacks/Bull_Note_Attack.cs
2,479
C#
// // Copyright 2010-2017 Deveel // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Threading.Tasks; using Deveel.Data.Serialization; namespace Deveel.Data.Sql.Statements { public class LoopStatement : CodeBlockStatement, IPlSqlStatement { public LoopStatement() : this((string) null) { } public LoopStatement(string label) : base(label) { } internal LoopStatement(SerializationInfo info) : base(info) { } internal virtual LoopStatement CreateNew() { return new LoopStatement(Label); } private bool HasControl { get; set; } private LoopControlType ControlType { get; set; } internal void Control(LoopControlType controlType) { HasControl = true; ControlType = controlType; } protected override SqlStatement PrepareStatement(IContext context) { var loop = CreateNew(); foreach (var statement in Statements) { var prepared = statement.Prepare(context); if (prepared == null) throw new SqlStatementException("The preparation of a child statement was invalid"); loop.Statements.Add(prepared); } return loop; } protected override async Task ExecuteStatementAsync(StatementContext context) { await InitializeAsync(context); while (await CanLoopAsync(context)) { bool stopLoop = false; foreach (var statement in Statements) { if (stopLoop) break; await statement.ExecuteAsync(context); if (context.WasTerminated) return; if (HasControl) { if (ControlType == LoopControlType.Exit) return; if (ControlType == LoopControlType.Continue) { stopLoop = true; } } } await AfterLoopAsync(context); } } protected virtual Task<bool> CanLoopAsync(StatementContext context) { return Task.FromResult(!HasControl || ControlType != LoopControlType.Exit); } protected virtual Task InitializeAsync(StatementContext context) { return Task.CompletedTask; } protected virtual Task AfterLoopAsync(StatementContext context) { return Task.CompletedTask; } internal void AppendLabelTo(SqlStringBuilder builder) { if (!String.IsNullOrEmpty(Label)) { builder.AppendFormat("<<{0}>>", Label); builder.AppendLine(); } } internal void AppendBodyTo(SqlStringBuilder builder) { builder.AppendLine("LOOP"); builder.Indent(); foreach (var child in Statements) { child.AppendTo(builder); builder.AppendLine(); } builder.DeIndent(); builder.Append("END LOOP;"); } protected override void AppendTo(SqlStringBuilder builder) { AppendLabelTo(builder); AppendBodyTo(builder); } } }
24.335878
89
0.698243
[ "Apache-2.0" ]
deveel/deveeldb.core
src/DeveelDb.Core/Data/Sql/Statements/LoopStatement.cs
3,190
C#
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Tests { using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Affinity; using Apache.Ignite.Core.Client; using Apache.Ignite.Core.Cluster; using Apache.Ignite.Core.Configuration; using Apache.Ignite.Core.Discovery.Tcp; using Apache.Ignite.Core.Discovery.Tcp.Static; using Apache.Ignite.Core.Failure; using Apache.Ignite.Core.Impl; using Apache.Ignite.Core.Impl.Binary; using Apache.Ignite.Core.Impl.Client; using Apache.Ignite.Core.Impl.Common; using Apache.Ignite.Core.Log; using Apache.Ignite.Core.Tests.Process; using NUnit.Framework; /// <summary> /// Test utility methods. /// </summary> public static class TestUtils { /** Indicates long running and/or memory/cpu intensive test. */ public const string CategoryIntensive = "LONG_TEST"; /** Indicates examples tests. */ public const string CategoryExamples = "EXAMPLES_TEST"; /** */ public const int DfltBusywaitSleepInterval = 200; /** System cache name. */ public const string UtilityCacheName = "ignite-sys-cache"; /** Work dir. */ private static readonly string WorkDir = // ReSharper disable once AssignNullToNotNullAttribute Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "ignite_work"); /** */ private static readonly IList<string> TestJvmOpts = Environment.Is64BitProcess ? new List<string> { "-XX:+HeapDumpOnOutOfMemoryError", "-Xms1g", "-Xmx4g", "-ea", "-DIGNITE_QUIET=true", "-Duser.timezone=UTC" } : new List<string> { "-XX:+HeapDumpOnOutOfMemoryError", "-Xms64m", "-Xmx99m", "-ea", "-DIGNITE_ATOMIC_CACHE_DELETE_HISTORY_SIZE=1000", "-DIGNITE_QUIET=true", "-Duser.timezone=UTC" }; /** */ private static readonly IList<string> JvmDebugOpts = new List<string> { "-Xdebug", "-Xnoagent", "-Djava.compiler=NONE", "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005", "-DIGNITE_LOG_CLASSPATH_CONTENT_ON_STARTUP=false" }; /** */ public static bool JvmDebug = true; /** */ [ThreadStatic] private static Random _random; /** */ private static int _seed = Environment.TickCount; /// <summary> /// /// </summary> public static Random Random { get { return _random ?? (_random = new Random(Interlocked.Increment(ref _seed))); } } /// <summary> /// Gets current test name. /// </summary> public static string TestName { get { return TestContext.CurrentContext.Test.Name; } } /// <summary> /// /// </summary> /// <returns></returns> public static IList<string> TestJavaOptions(bool? jvmDebug = null) { IList<string> ops = new List<string>(TestJvmOpts); if (jvmDebug ?? JvmDebug) { foreach (string opt in JvmDebugOpts) ops.Add(opt); } return ops; } /// <summary> /// /// </summary> /// <param name="action"></param> /// <param name="threadNum"></param> public static void RunMultiThreaded(Action action, int threadNum) { List<Thread> threads = new List<Thread>(threadNum); var errors = new ConcurrentBag<Exception>(); for (int i = 0; i < threadNum; i++) { threads.Add(new Thread(() => { try { action(); } catch (Exception e) { errors.Add(e); } })); } foreach (Thread thread in threads) thread.Start(); foreach (Thread thread in threads) thread.Join(); foreach (var ex in errors) Assert.Fail("Unexpected exception: " + ex); } /// <summary> /// /// </summary> /// <param name="action"></param> /// <param name="threadNum"></param> /// <param name="duration">Duration of test execution in seconds</param> public static void RunMultiThreaded(Action action, int threadNum, int duration) { List<Thread> threads = new List<Thread>(threadNum); var errors = new ConcurrentBag<Exception>(); bool stop = false; for (int i = 0; i < threadNum; i++) { threads.Add(new Thread(() => { try { while (true) { Thread.MemoryBarrier(); // ReSharper disable once AccessToModifiedClosure if (stop) break; action(); } } catch (Exception e) { errors.Add(e); } })); } foreach (Thread thread in threads) thread.Start(); Thread.Sleep(duration * 1000); stop = true; Thread.MemoryBarrier(); foreach (Thread thread in threads) thread.Join(); foreach (var ex in errors) Assert.Fail("Unexpected exception: " + ex); } /// <summary> /// Wait for particular topology size. /// </summary> /// <param name="grid">Grid.</param> /// <param name="size">Size.</param> /// <param name="timeout">Timeout.</param> /// <returns> /// <c>True</c> if topology took required size. /// </returns> public static bool WaitTopology(this IIgnite grid, int size, int timeout = 30000) { int left = timeout; while (true) { if (grid.GetCluster().GetNodes().Count != size) { if (left > 0) { Thread.Sleep(100); left -= 100; } else break; } else return true; } return false; } /// <summary> /// Waits for particular topology on specific cache (system cache by default). /// </summary> /// <param name="grid">Grid.</param> /// <param name="waitingTop">Topology version.</param> /// <param name="cacheName">Cache name.</param> /// <param name="timeout">Timeout.</param> /// <returns> /// <c>True</c> if topology took required size. /// </returns> public static bool WaitTopology(this IIgnite grid, AffinityTopologyVersion waitingTop, string cacheName = UtilityCacheName, int timeout = 30000) { int checkPeriod = 200; // Wait for late affinity. for (var iter = 0;; iter++) { var result = grid.GetCompute().ExecuteJavaTask<long[]>( "org.apache.ignite.platform.PlatformCacheAffinityVersionTask", cacheName); var top = new AffinityTopologyVersion(result[0], (int) result[1]); if (top.CompareTo(waitingTop) >= 0) { Console.Out.WriteLine("Current topology: " + top); break; } if (iter % 10 == 0) Console.Out.WriteLine("Waiting topology cur=" + top + " wait=" + waitingTop); if (iter * checkPeriod > timeout) return false; Thread.Sleep(checkPeriod); } return true; } /// <summary> /// Waits for condition, polling in busy wait loop. /// </summary> /// <param name="cond">Condition.</param> /// <param name="timeout">Timeout, in milliseconds.</param> /// <returns>True if condition predicate returned true within interval; false otherwise.</returns> public static bool WaitForCondition(Func<bool> cond, int timeout) { if (timeout <= 0) return cond(); var maxTime = DateTime.Now.AddMilliseconds(timeout + DfltBusywaitSleepInterval); while (DateTime.Now < maxTime) { if (cond()) return true; Thread.Sleep(DfltBusywaitSleepInterval); } return false; } /// <summary> /// Waits for condition, polling in a busy wait loop, then asserts that condition is true. /// </summary> /// <param name="cond">Condition.</param> /// <param name="timeout">Timeout, in milliseconds.</param> /// <param name="message">Assertion message.</param> public static void WaitForTrueCondition(Func<bool> cond, int timeout = 1000, string message = null) { WaitForTrueCondition(cond, message == null ? (Func<string>) null : () => message, timeout); } /// <summary> /// Waits for condition, polling in a busy wait loop, then asserts that condition is true. /// </summary> /// <param name="cond">Condition.</param> /// <param name="messageFunc">Assertion message func.</param> /// <param name="timeout">Timeout, in milliseconds.</param> public static void WaitForTrueCondition(Func<bool> cond, Func<string> messageFunc, int timeout = 1000) { var res = WaitForCondition(cond, timeout); var message = string.Format("Condition not reached within {0} ms", timeout); if (messageFunc != null) { message += string.Format(" ({0})", messageFunc()); } Assert.IsTrue(res, message); } /// <summary> /// Gets the static discovery. /// </summary> public static TcpDiscoverySpi GetStaticDiscovery() { return new TcpDiscoverySpi { IpFinder = new TcpDiscoveryStaticIpFinder { Endpoints = new[] { "127.0.0.1:47500" } }, SocketTimeout = TimeSpan.FromSeconds(0.3) }; } /// <summary> /// Gets cache keys. /// </summary> public static IEnumerable<int> GetKeys(IIgnite ignite, string cacheName, IClusterNode node = null, bool primary = true) { var aff = ignite.GetAffinity(cacheName); node = node ?? ignite.GetCluster().GetLocalNode(); return Enumerable.Range(1, int.MaxValue).Where(x => aff.IsPrimary(node, x) == primary); } /// <summary> /// Gets the primary keys. /// </summary> public static IEnumerable<int> GetPrimaryKeys(IIgnite ignite, string cacheName, IClusterNode node = null) { return GetKeys(ignite, cacheName, node); } /// <summary> /// Gets the primary key. /// </summary> public static int GetPrimaryKey(IIgnite ignite, string cacheName, IClusterNode node = null) { return GetPrimaryKeys(ignite, cacheName, node).First(); } /// <summary> /// Gets the primary key. /// </summary> public static int GetKey(IIgnite ignite, string cacheName, IClusterNode node = null, bool primaryKey = false) { return GetKeys(ignite, cacheName, node, primaryKey).First(); } /// <summary> /// Asserts that the handle registry is empty. /// </summary> /// <param name="timeout">Timeout, in milliseconds.</param> /// <param name="grids">Grids to check.</param> public static void AssertHandleRegistryIsEmpty(int timeout, params IIgnite[] grids) { foreach (var g in grids) AssertHandleRegistryHasItems(g, 0, timeout); } /// <summary> /// Asserts that the handle registry has specified number of entries. /// </summary> /// <param name="timeout">Timeout, in milliseconds.</param> /// <param name="expectedCount">Expected item count.</param> /// <param name="grids">Grids to check.</param> public static void AssertHandleRegistryHasItems(int timeout, int expectedCount, params IIgnite[] grids) { foreach (var g in grids) AssertHandleRegistryHasItems(g, expectedCount, timeout); } /// <summary> /// Asserts that the handle registry has specified number of entries. /// </summary> /// <param name="grid">The grid to check.</param> /// <param name="expectedCount">Expected item count.</param> /// <param name="timeout">Timeout, in milliseconds.</param> public static void AssertHandleRegistryHasItems(IIgnite grid, int expectedCount, int timeout) { var handleRegistry = ((Ignite)grid).HandleRegistry; expectedCount++; // Skip default lifecycle bean if (WaitForCondition(() => handleRegistry.Count == expectedCount, timeout)) return; var items = handleRegistry.GetItems().Where(x => !(x.Value is LifecycleHandlerHolder)).ToList(); if (items.Any()) { Assert.Fail("HandleRegistry is not empty in grid '{0}' (expected {1}, actual {2}):\n '{3}'", grid.Name, expectedCount, handleRegistry.Count, items.Select(x => x.ToString()).Aggregate((x, y) => x + "\n" + y)); } } /// <summary> /// Serializes and deserializes back an object. /// </summary> public static T SerializeDeserialize<T>(T obj, bool raw = false) { var cfg = new BinaryConfiguration { Serializer = raw ? new BinaryReflectiveSerializer {RawMode = true} : null }; var marsh = new Marshaller(cfg) { CompactFooter = false }; return marsh.Unmarshal<T>(marsh.Marshal(obj)); } /// <summary> /// Clears the work dir. /// </summary> public static void ClearWorkDir() { if (!Directory.Exists(WorkDir)) { return; } // Delete everything we can. Some files may be locked. foreach (var e in Directory.GetFileSystemEntries(WorkDir, "*", SearchOption.AllDirectories)) { try { File.Delete(e); } catch (Exception) { // Ignore } try { Directory.Delete(e, true); } catch (Exception) { // Ignore } } } /// <summary> /// Gets the dot net source dir. /// </summary> public static DirectoryInfo GetDotNetSourceDir() { // ReSharper disable once AssignNullToNotNullAttribute var dir = new DirectoryInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); while (dir != null) { if (dir.GetFiles().Any(x => x.Name == "Apache.Ignite.sln")) return dir; dir = dir.Parent; } throw new InvalidOperationException("Could not resolve Ignite.NET source directory."); } /// <summary> /// Gets a value indicating whether specified partition is reserved. /// </summary> public static bool IsPartitionReserved(IIgnite ignite, string cacheName, int part) { Debug.Assert(ignite != null); Debug.Assert(cacheName != null); const string taskName = "org.apache.ignite.platform.PlatformIsPartitionReservedTask"; return ignite.GetCompute().ExecuteJavaTask<bool>(taskName, new object[] {cacheName, part}); } /// <summary> /// Gets the innermost exception. /// </summary> public static Exception GetInnermostException(this Exception ex) { while (ex.InnerException != null) { ex = ex.InnerException; } return ex; } /// <summary> /// Gets the private field value. /// </summary> public static T GetPrivateField<T>(object obj, string name) { Assert.IsNotNull(obj); var field = obj.GetType().GetField(name, BindingFlags.Instance | BindingFlags.NonPublic); Assert.IsNotNull(field); return (T) field.GetValue(obj); } /// <summary> /// Gets active notification listeners. /// </summary> public static ICollection GetActiveNotificationListeners(this IIgniteClient client) { var failoverSocket = GetPrivateField<ClientFailoverSocket>(client, "_socket"); var socket = GetPrivateField<ClientSocket>(failoverSocket, "_socket"); return GetPrivateField<ICollection>(socket, "_notificationListeners"); } /// <summary> /// /// </summary> /// <returns></returns> public static string CreateTestClasspath() { var home = IgniteHome.Resolve(); return Classpath.CreateClasspath(null, home, forceTestClasspath: true); } /// <summary> /// Kill Ignite processes. /// </summary> public static void KillProcesses() { IgniteProcess.KillAll(); } /// <summary> /// Gets the default code-based test configuration. /// </summary> public static IgniteConfiguration GetTestConfiguration(bool? jvmDebug = null, string name = null) { return new IgniteConfiguration { DiscoverySpi = GetStaticDiscovery(), Localhost = "127.0.0.1", JvmOptions = TestJavaOptions(jvmDebug), JvmClasspath = CreateTestClasspath(), IgniteInstanceName = name, DataStorageConfiguration = new DataStorageConfiguration { DefaultDataRegionConfiguration = new DataRegionConfiguration { Name = DataStorageConfiguration.DefaultDataRegionName, InitialSize = 128 * 1024 * 1024, MaxSize = Environment.Is64BitProcess ? DataRegionConfiguration.DefaultMaxSize : 256 * 1024 * 1024 } }, FailureHandler = new NoOpFailureHandler(), WorkDirectory = WorkDir, Logger = new TestContextLogger() }; } /// <summary> /// Runs the test in new process. /// </summary> [SuppressMessage("ReSharper", "AssignNullToNotNullAttribute")] public static void RunTestInNewProcess(string fixtureName, string testName) { var procStart = new ProcessStartInfo { FileName = typeof(TestUtils).Assembly.Location, Arguments = fixtureName + " " + testName, CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; var proc = System.Diagnostics.Process.Start(procStart); Assert.IsNotNull(proc); try { proc.AttachProcessConsoleReader(); Assert.IsTrue(proc.WaitForExit(50000)); Assert.AreEqual(0, proc.ExitCode); } finally { if (!proc.HasExited) { proc.Kill(); } } } /// <summary> /// Deploys the Java service. /// </summary> public static string DeployJavaService(IIgnite ignite) { const string serviceName = "javaService"; ignite.GetCompute() .ExecuteJavaTask<object>("org.apache.ignite.platform.PlatformDeployServiceTask", serviceName); var services = ignite.GetServices(); WaitForCondition(() => services.GetServiceDescriptors().Any(x => x.Name == serviceName), 1000); return serviceName; } /// <summary> /// Logs to test progress. Produces immediate console output on .NET Core. /// </summary> public class TestContextLogger : ILogger { /** <inheritdoc /> */ public void Log(LogLevel level, string message, object[] args, IFormatProvider formatProvider, string category, string nativeErrorInfo, Exception ex) { if (!IsEnabled(level)) { return; } var text = args != null ? string.Format(formatProvider ?? CultureInfo.InvariantCulture, message, args) : message; #if NETCOREAPP TestContext.Progress.WriteLine(text); #else Console.WriteLine(text); #endif } /** <inheritdoc /> */ public bool IsEnabled(LogLevel level) { return level >= LogLevel.Info; } } } }
33.605974
201
0.520508
[ "CC0-1.0" ]
IrenJones/ignite
modules/platforms/dotnet/Apache.Ignite.Core.Tests/TestUtils.cs
23,625
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect 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 System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.Specialized; using System.Linq; using QuantConnect.Data.UniverseSelection; namespace QuantConnect.Securities { /// <summary> /// Manages the algorithm's collection of universes /// </summary> public class UniverseManager : IDictionary<Symbol, Universe>, INotifyCollectionChanged { private readonly ConcurrentDictionary<Symbol, Universe> _universes; /// <summary> /// Event fired when a universe is added or removed /// </summary> public event NotifyCollectionChangedEventHandler CollectionChanged; /// <summary> /// Initializes a new instance of the <see cref="UniverseManager"/> class /// </summary> public UniverseManager() { _universes = new ConcurrentDictionary<Symbol, Universe>(); } #region IDictionary implementation /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="T:System.Collections.Generic.IEnumerator`1"/> that can be used to iterate through the collection. /// </returns> /// <filterpriority>1</filterpriority> public IEnumerator<KeyValuePair<Symbol, Universe>> GetEnumerator() { return _universes.GetEnumerator(); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="T:System.Collections.IEnumerator"/> object that can be used to iterate through the collection. /// </returns> /// <filterpriority>2</filterpriority> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_universes).GetEnumerator(); } /// <summary> /// Adds an item to the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <param name="item">The object to add to the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> public void Add(KeyValuePair<Symbol, Universe> item) { Add(item.Key, item.Value); } /// <summary> /// Removes all items from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. </exception> public void Clear() { _universes.Clear(); } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.ICollection`1"/> contains a specific value. /// </summary> /// <returns> /// true if <paramref name="item"/> is found in the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. /// </returns> /// <param name="item">The object to locate in the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param> public bool Contains(KeyValuePair<Symbol, Universe> item) { return _universes.Contains(item); } /// <summary> /// Copies the elements of the <see cref="T:System.Collections.Generic.ICollection`1"/> to an <see cref="T:System.Array"/>, starting at a particular <see cref="T:System.Array"/> index. /// </summary> /// <param name="array">The one-dimensional <see cref="T:System.Array"/> that is the destination of the elements copied from <see cref="T:System.Collections.Generic.ICollection`1"/>. The <see cref="T:System.Array"/> must have zero-based indexing.</param><param name="arrayIndex">The zero-based index in <paramref name="array"/> at which copying begins.</param><exception cref="T:System.ArgumentNullException"><paramref name="array"/> is null.</exception><exception cref="T:System.ArgumentOutOfRangeException"><paramref name="arrayIndex"/> is less than 0.</exception><exception cref="T:System.ArgumentException">The number of elements in the source <see cref="T:System.Collections.Generic.ICollection`1"/> is greater than the available space from <paramref name="arrayIndex"/> to the end of the destination <paramref name="array"/>.</exception> public void CopyTo(KeyValuePair<Symbol, Universe>[] array, int arrayIndex) { ((IDictionary<Symbol, Universe>)_universes).CopyTo(array, arrayIndex); } /// <summary> /// Removes the first occurrence of a specific object from the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <returns> /// true if <paramref name="item"/> was successfully removed from the <see cref="T:System.Collections.Generic.ICollection`1"/>; otherwise, false. This method also returns false if <paramref name="item"/> is not found in the original <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> /// <param name="item">The object to remove from the <see cref="T:System.Collections.Generic.ICollection`1"/>.</param><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only.</exception> public bool Remove(KeyValuePair<Symbol, Universe> item) { Universe universe; return _universes.TryRemove(item.Key, out universe); } /// <summary> /// Gets the number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </summary> /// <returns> /// The number of elements contained in the <see cref="T:System.Collections.Generic.ICollection`1"/>. /// </returns> public int Count => _universes.Skip(0).Count(); /// <summary> /// Gets a value indicating whether the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only. /// </summary> /// <returns> /// true if the <see cref="T:System.Collections.Generic.ICollection`1"/> is read-only; otherwise, false. /// </returns> public bool IsReadOnly { get { return false; } } /// <summary> /// Determines whether the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key. /// </summary> /// <returns> /// true if the <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the key; otherwise, false. /// </returns> /// <param name="key">The key to locate in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception> public bool ContainsKey(Symbol key) { return _universes.ContainsKey(key); } /// <summary> /// Adds an element with the provided key and value to the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <param name="key">The object to use as the key of the element to add.</param><param name="universe">The object to use as the value of the element to add.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception><exception cref="T:System.ArgumentException">An element with the same key already exists in the <see cref="T:System.Collections.Generic.IDictionary`2"/>.</exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception> public void Add(Symbol key, Universe universe) { if (_universes.TryAdd(key, universe)) { OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, universe)); } } /// <summary> /// Removes the element with the specified key from the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <returns> /// true if the element is successfully removed; otherwise, false. This method also returns false if <paramref name="key"/> was not found in the original <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </returns> /// <param name="key">The key of the element to remove.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception><exception cref="T:System.NotSupportedException">The <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception> public bool Remove(Symbol key) { Universe universe; if (_universes.TryRemove(key, out universe)) { OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, universe)); return true; } return false; } /// <summary> /// Gets the value associated with the specified key. /// </summary> /// <returns> /// true if the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/> contains an element with the specified key; otherwise, false. /// </returns> /// <param name="key">The key whose value to get.</param><param name="value">When this method returns, the value associated with the specified key, if the key is found; otherwise, the default value for the type of the <paramref name="value"/> parameter. This parameter is passed uninitialized.</param><exception cref="T:System.ArgumentNullException"><paramref name="key"/> is null.</exception> public bool TryGetValue(Symbol key, out Universe value) { return _universes.TryGetValue(key, out value); } /// <summary> /// Gets or sets the element with the specified key. /// </summary> /// <returns> /// The element with the specified key. /// </returns> /// <param name="symbol">The key of the element to get or set.</param><exception cref="T:System.ArgumentNullException"><paramref name="symbol"/> is null.</exception><exception cref="T:System.Collections.Generic.KeyNotFoundException">The property is retrieved and <paramref name="symbol"/> is not found.</exception><exception cref="T:System.NotSupportedException">The property is set and the <see cref="T:System.Collections.Generic.IDictionary`2"/> is read-only.</exception> public Universe this[Symbol symbol] { get { if (!_universes.ContainsKey(symbol)) { throw new Exception(string.Format("This universe symbol ({0}) was not found in your universe list. Please add this security or check it exists before using it with 'Universes.ContainsKey(\"{1}\")'", symbol, SymbolCache.GetTicker(symbol))); } return _universes[symbol]; } set { Universe existing; if (_universes.TryGetValue(symbol, out existing) && existing != value) { throw new ArgumentException("Unable to over write existing Universe: " + symbol.Value); } // no security exists for the specified symbol key, add it now if (existing == null) { Add(symbol, value); } } } /// <summary> /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <returns> /// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the keys of the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </returns> public ICollection<Symbol> Keys => _universes.Select(x => x.Key).ToList(); /// <summary> /// Gets an <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </summary> /// <returns> /// An <see cref="T:System.Collections.Generic.ICollection`1"/> containing the values in the object that implements <see cref="T:System.Collections.Generic.IDictionary`2"/>. /// </returns> public ICollection<Universe> Values => _universes.Select(x => x.Value).ToList(); #endregion /// <summary> /// Event invocator for the <see cref="CollectionChanged"/> event /// </summary> /// <param name="e"></param> protected virtual void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { var handler = CollectionChanged; if (handler != null) handler(this, e); } } }
53.872093
851
0.639686
[ "Apache-2.0" ]
Bimble/Lean
Common/Securities/UniverseManager.cs
13,901
C#
using System.Collections.Generic; namespace Stein.Common.InstallerFiles { /// <summary> /// A configuration to configure an <see cref="IInstallerFileBundleProvider"/>. /// </summary> public interface IInstallerFileBundleProviderConfiguration { /// <summary> /// Type of the provider this configuration belongs to. /// </summary> string ProviderType { get; } /// <summary> /// Configuration parameters of the provider. /// </summary> IDictionary<string, string> Parameters { get; } } }
27.428571
83
0.623264
[ "MIT" ]
nkristek/Stein
src/Stein.Common/InstallerFiles/IInstallerFileBundleProviderConfiguration.cs
578
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; public class UIStreetControl : MonoBehaviour { public Text section; [SerializeField] private GameObject SectionPanel; StreetBehaivor sb; private List<GameObject> selectedGameObjects = new List<GameObject>(); void Update () { if (GetComponent<GenericUIController> ().isActive) { //GameObject go = GetComponent<GenericUIController> ().UIcaller; selectedGameObjects = GetComponent<GenericUIController> ().UIcaller; if (selectedGameObjects.Count == 1) { sb = selectedGameObjects [0].GetComponent<StreetBehaivor> (); if (sb.ElementToTransport == null) section.text = "Open"; else section.text = sb.ElementToTransport.ToString (); } else { section.text = ReturnSection (selectedGameObjects); } } } public string ReturnSection(List<GameObject> _goL) { if (_goL.Count > 0) { if (_goL [0].GetComponent<StreetBehaivor> () == null) return "undefined."; string returnVal = _goL [0].GetComponent<StreetBehaivor> ().ElementToTransport.ToString (); for (int i = 0; i < _goL.Count; i++) { string elementToTransport = _goL [i].GetComponent<StreetBehaivor> ().ElementToTransport.ToString (); if (returnVal != elementToTransport) returnVal = "several.."; } return returnVal; } return "undefined.."; } public void ShowSectionPanel(bool _v) { SectionPanel.SetActive (_v); } public void DefineElement (Element _element) { foreach (GameObject _go in selectedGameObjects) { _go.GetComponent<StreetBehaivor> ().ElementToTransport = _element; } } public void UndefineElement () { foreach (GameObject _go in selectedGameObjects) { _go.GetComponent<StreetBehaivor> ().ElementToTransport = new Element(); } } }
26.661765
104
0.710976
[ "Apache-2.0" ]
cwaidelich/Handel
Handel2/Assets/Scripts/UI/UIStreetControl.cs
1,815
C#
using System.Collections.Generic; namespace Xunit.Runners { /// <summary> /// Represents a test that passed. /// </summary> public class TestPassedInfo : TestExecutedInfo { /// <summary/> public TestPassedInfo( string typeName, string methodName, Dictionary<string, List<string>>? traits, string testDisplayName, string testCollectionDisplayName, decimal executionTime, string? output) : base(typeName, methodName, traits, testDisplayName, testCollectionDisplayName, executionTime, output) { } } }
23.347826
107
0.726257
[ "Apache-2.0" ]
0xced/xunit
src/xunit.v3.runner.utility/Runners/TestPassedInfo.cs
539
C#
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// AlphaSenderResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Messaging.V1.Service { public class AlphaSenderResource : Resource { private static Request BuildCreateRequest(CreateAlphaSenderOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Messaging, "/v1/Services/" + options.PathServiceSid + "/AlphaSenders", client.Region, postParams: options.GetParams() ); } /// <summary> /// create /// </summary> /// <param name="options"> Create AlphaSender parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AlphaSender </returns> public static AlphaSenderResource Create(CreateAlphaSenderOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create AlphaSender parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AlphaSender </returns> public static async System.Threading.Tasks.Task<AlphaSenderResource> CreateAsync(CreateAlphaSenderOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="pathServiceSid"> The SID of the Service to create the resource under </param> /// <param name="alphaSender"> The Alphanumeric Sender ID string </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AlphaSender </returns> public static AlphaSenderResource Create(string pathServiceSid, string alphaSender, ITwilioRestClient client = null) { var options = new CreateAlphaSenderOptions(pathServiceSid, alphaSender); return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="pathServiceSid"> The SID of the Service to create the resource under </param> /// <param name="alphaSender"> The Alphanumeric Sender ID string </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AlphaSender </returns> public static async System.Threading.Tasks.Task<AlphaSenderResource> CreateAsync(string pathServiceSid, string alphaSender, ITwilioRestClient client = null) { var options = new CreateAlphaSenderOptions(pathServiceSid, alphaSender); return await CreateAsync(options, client); } #endif private static Request BuildReadRequest(ReadAlphaSenderOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Messaging, "/v1/Services/" + options.PathServiceSid + "/AlphaSenders", client.Region, queryParams: options.GetParams() ); } /// <summary> /// read /// </summary> /// <param name="options"> Read AlphaSender parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AlphaSender </returns> public static ResourceSet<AlphaSenderResource> Read(ReadAlphaSenderOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<AlphaSenderResource>.FromJson("alpha_senders", response.Content); return new ResourceSet<AlphaSenderResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read AlphaSender parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AlphaSender </returns> public static async System.Threading.Tasks.Task<ResourceSet<AlphaSenderResource>> ReadAsync(ReadAlphaSenderOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<AlphaSenderResource>.FromJson("alpha_senders", response.Content); return new ResourceSet<AlphaSenderResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the resources from </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AlphaSender </returns> public static ResourceSet<AlphaSenderResource> Read(string pathServiceSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadAlphaSenderOptions(pathServiceSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathServiceSid"> The SID of the Service to read the resources from </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AlphaSender </returns> public static async System.Threading.Tasks.Task<ResourceSet<AlphaSenderResource>> ReadAsync(string pathServiceSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadAlphaSenderOptions(pathServiceSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<AlphaSenderResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<AlphaSenderResource>.FromJson("alpha_senders", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<AlphaSenderResource> NextPage(Page<AlphaSenderResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl( Rest.Domain.Messaging, client.Region ) ); var response = client.Request(request); return Page<AlphaSenderResource>.FromJson("alpha_senders", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<AlphaSenderResource> PreviousPage(Page<AlphaSenderResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl( Rest.Domain.Messaging, client.Region ) ); var response = client.Request(request); return Page<AlphaSenderResource>.FromJson("alpha_senders", response.Content); } private static Request BuildFetchRequest(FetchAlphaSenderOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Messaging, "/v1/Services/" + options.PathServiceSid + "/AlphaSenders/" + options.PathSid + "", client.Region, queryParams: options.GetParams() ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch AlphaSender parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AlphaSender </returns> public static AlphaSenderResource Fetch(FetchAlphaSenderOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch AlphaSender parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AlphaSender </returns> public static async System.Threading.Tasks.Task<AlphaSenderResource> FetchAsync(FetchAlphaSenderOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The SID of the Messaging Service to fetch the resource from </param> /// <param name="pathSid"> The SID that identifies the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AlphaSender </returns> public static AlphaSenderResource Fetch(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchAlphaSenderOptions(pathServiceSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathServiceSid"> The SID of the Messaging Service to fetch the resource from </param> /// <param name="pathSid"> The SID that identifies the resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AlphaSender </returns> public static async System.Threading.Tasks.Task<AlphaSenderResource> FetchAsync(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchAlphaSenderOptions(pathServiceSid, pathSid); return await FetchAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteAlphaSenderOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Messaging, "/v1/Services/" + options.PathServiceSid + "/AlphaSenders/" + options.PathSid + "", client.Region, queryParams: options.GetParams() ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete AlphaSender parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AlphaSender </returns> public static bool Delete(DeleteAlphaSenderOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete AlphaSender parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AlphaSender </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteAlphaSenderOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param> /// <param name="pathSid"> The SID that identifies the resource to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of AlphaSender </returns> public static bool Delete(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteAlphaSenderOptions(pathServiceSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathServiceSid"> The SID of the Service to delete the resource from </param> /// <param name="pathSid"> The SID that identifies the resource to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of AlphaSender </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteAlphaSenderOptions(pathServiceSid, pathSid); return await DeleteAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a AlphaSenderResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> AlphaSenderResource object represented by the provided JSON </returns> public static AlphaSenderResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<AlphaSenderResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// The SID of the Service that the resource is associated with /// </summary> [JsonProperty("service_sid")] public string ServiceSid { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The Alphanumeric Sender ID string /// </summary> [JsonProperty("alpha_sender")] public string AlphaSender { get; private set; } /// <summary> /// An array of values that describe whether the number can receive calls or messages /// </summary> [JsonProperty("capabilities")] public List<object> Capabilities { get; private set; } /// <summary> /// The absolute URL of the AlphaSender resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private AlphaSenderResource() { } } }
44.904328
132
0.563587
[ "MIT" ]
FishDawg/twilio-csharp
src/Twilio/Rest/Messaging/V1/Service/AlphaSenderResource.cs
19,713
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BooInterpreter { public class StringLiteral : Expression { public StringLiteral() { } public string Value { get; set; } public override string ToString() { return Value; } } }
16.125
43
0.602067
[ "MIT" ]
nordleif/BooInterpreter
BooInterpreter/Expressions/StringLiteral.cs
389
C#
using Bitfinex.Net.Enums; using CryptoExchange.Net.Objects; using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Bitfinex.Net.Objects.Models; using Bitfinex.Net.Objects.Models.V1; namespace Bitfinex.Net.Interfaces.Clients.SpotApi { /// <summary> /// Bitfinex exchange data endpoints. Exchange data includes market data (tickers, order books, etc) and system status. /// </summary> public interface IBitfinexClientSpotApiExchangeData { /// <summary> /// Gets the platform status /// <para><a href="https://docs.bitfinex.com/reference#rest-public-platform-status" /></para> /// </summary> /// <param name="ct">Cancellation token</param> /// <returns>Whether Bitfinex platform is running normally or not</returns> Task<WebCallResult<BitfinexPlatformStatus>> GetPlatformStatusAsync(CancellationToken ct = default); /// <summary> /// Gets a list of supported assets /// <para><a href="https://docs.bitfinex.com/reference#rest-public-conf" /></para> /// </summary> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<IEnumerable<BitfinexAsset>>> GetAssetsAsync(CancellationToken ct = default); /// <summary> /// Returns basic market data for the provided symbols /// <para><a href="https://docs.bitfinex.com/reference#rest-public-ticker" /></para> /// </summary> /// <param name="symbol">The symbol to get data for</param> /// <param name="ct">Cancellation token</param> /// <returns>Symbol data</returns> Task<WebCallResult<BitfinexSymbolOverview>> GetTickerAsync(string symbol, CancellationToken ct = default); /// <summary> /// Returns basic market data for the provided symbols /// <para><a href="https://docs.bitfinex.com/reference#rest-public-tickers" /></para> /// </summary> /// <param name="symbols">The symbols to get data for</param> /// <param name="ct">Cancellation token</param> /// <returns>Symbol data</returns> Task<WebCallResult<IEnumerable<BitfinexSymbolOverview>>> GetTickersAsync(IEnumerable<string>? symbols = null, CancellationToken ct = default); /// <summary> /// Get recent trades for a symbol /// <para><a href="https://docs.bitfinex.com/reference#rest-public-trades" /></para> /// </summary> /// <param name="symbol">The symbol to get trades for</param> /// <param name="limit">The amount of results</param> /// <param name="startTime">The start time to return trades for</param> /// <param name="endTime">The end time to return trades for</param> /// <param name="sorting">The way the result is sorted</param> /// <param name="ct">Cancellation token</param> /// <returns>Trades for the symbol</returns> Task<WebCallResult<IEnumerable<BitfinexTradeSimple>>> GetTradeHistoryAsync(string symbol, int? limit = null, DateTime? startTime = null, DateTime? endTime = null, Sorting? sorting = null, CancellationToken ct = default); /// <summary> /// Gets the order book for a symbol /// <para><a href="https://docs.bitfinex.com/reference#rest-public-book" /></para> /// </summary> /// <param name="symbol">The symbol to get the order book for</param> /// <param name="precision">The precision of the data</param> /// <param name="limit">The amount of results in the book</param> /// <param name="ct">Cancellation token</param> /// <returns>The order book for the symbol</returns> Task<WebCallResult<BitfinexOrderBook>> GetOrderBookAsync(string symbol, Precision precision, int? limit = null, CancellationToken ct = default); /// <summary> /// Get the raw order book for a symbol /// <para><a href="https://docs.bitfinex.com/reference#rest-public-book" /></para> /// </summary> /// <param name="symbol">The symbol</param> /// <param name="limit">The amount of results in the book</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<BitfinexOrderBook>> GetRawOrderBookAsync(string symbol, int? limit = null, CancellationToken ct = default); /// <summary> /// Get various stats for the symbol /// <para><a href="https://docs.bitfinex.com/reference#rest-public-stats1" /></para> /// </summary> /// <param name="symbol">The symbol to request stats for</param> /// <param name="key">The type of stats</param> /// <param name="side">Side of the stats</param> /// <param name="section">Section of the stats</param> /// <param name="sorting">The way the result should be sorted</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<IEnumerable<BitfinexStats>>> GetStatsAsync(string symbol, StatKey key, StatSide side, StatSection section, Sorting? sorting = null, CancellationToken ct = default); /// <summary> /// Get the last kline for a symbol /// <para><a href="https://docs.bitfinex.com/reference#rest-public-candles" /></para> /// </summary> /// <param name="interval">The time frame of the kline</param> /// <param name="symbol">The symbol to get the kline for</param> /// <param name="fundingPeriod">The Funding period. Only required for funding candles. Enter after the symbol (trade:1m:fUSD:p30/hist).</param> /// <param name="ct">Cancellation token</param> /// <returns>The last kline for the symbol</returns> Task<WebCallResult<BitfinexKline>> GetLastKlineAsync(string symbol, KlineInterval interval, string? fundingPeriod = null, CancellationToken ct = default); /// <summary> /// Gets klines for a symbol /// <para><a href="https://docs.bitfinex.com/reference#rest-public-candles" /></para> /// </summary> /// <param name="interval">The time frame of the klines</param> /// <param name="symbol">The symbol to get the klines for</param> /// <param name="fundingPeriod">The Funding period. Only required for funding candles. Enter after the symbol (trade:1m:fUSD:p30/hist).</param> /// <param name="limit">The amount of results</param> /// <param name="startTime">The start time of the klines</param> /// <param name="endTime">The end time of the klines</param> /// <param name="sorting">The way the result is sorted</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<IEnumerable<BitfinexKline>>> GetKlinesAsync(string symbol, KlineInterval interval, string? fundingPeriod = null, int? limit = null, DateTime? startTime = null, DateTime? endTime = null, Sorting? sorting = null, CancellationToken ct = default); /// <summary> /// Calculate the average execution price /// <para><a href="https://docs.bitfinex.com/reference#rest-public-calc-market-average-price" /></para> /// </summary> /// <param name="symbol">The symbol to calculate for</param> /// <param name="quantity">The quantity to execute</param> /// <param name="rateLimit">Limit to price</param> /// <param name="period">Maximum period for margin funding</param> /// <param name="ct">Cancellation token</param> /// <returns>The average price at which the execution would happen</returns> Task<WebCallResult<BitfinexAveragePrice>> GetAveragePriceAsync(string symbol, decimal quantity, decimal? rateLimit = null, int? period = null, CancellationToken ct = default); /// <summary> /// Returns the exchange rate for the assets /// <para><a href="https://docs.bitfinex.com/reference#rest-public-calc-foreign-exchange-rate" /></para> /// </summary> /// <param name="asset1">The first asset</param> /// <param name="asset2">The second asset</param> /// <param name="ct">Cancellation token</param> /// <returns>Exchange rate</returns> Task<WebCallResult<BitfinexForeignExchangeRate>> GetForeignExchangeRateAsync(string asset1, string asset2, CancellationToken ct = default); /// <summary> /// Gets the margin funding book /// <para><a href="https://docs.bitfinex.com/v1/reference#rest-public-fundingbook" /></para> /// </summary> /// <param name="asset">Asset to get the book for</param> /// <param name="limit">Limit of the results</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<BitfinexFundingBook>> GetFundingBookAsync(string asset, int? limit = null, CancellationToken ct = default); /// <summary> /// Gets the most recent lends /// <para><a href="https://docs.bitfinex.com/v1/reference#rest-public-lends" /></para> /// </summary> /// <param name="asset">Asset to get the book for</param> /// <param name="startTime">Return data after this time</param> /// <param name="limit">Limit of the results</param> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<IEnumerable<BitfinexLend>>> GetLendsAsync(string asset, DateTime? startTime = null, int? limit = null, CancellationToken ct = default); /// <summary> /// Gets a list of all symbols /// <para><a href="https://docs.bitfinex.com/v1/reference#rest-public-symbols" /></para> /// </summary> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<IEnumerable<string>>> GetSymbolsAsync(CancellationToken ct = default); /// <summary> /// Gets details of all symbols /// <para><a href="https://docs.bitfinex.com/v1/reference#rest-public-symbol-details" /></para> /// </summary> /// <param name="ct">Cancellation token</param> /// <returns></returns> Task<WebCallResult<IEnumerable<BitfinexSymbolDetails>>> GetSymbolDetailsAsync(CancellationToken ct = default); } }
56.472826
270
0.637956
[ "MIT" ]
GetoXs/Bitfinex.Net
Bitfinex.Net/Interfaces/Clients/SpotApi/IBitfinexClientSpotApiExchangeData.cs
10,393
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.AspNetCore.Mvc; using WordCounterMVC.Controllers; namespace WordCounterMVC.Tests.ControllerTests { [TestClass] public class WordCounterMVCControllerTests { [TestMethod] public void Counter_ReturnsCorrectView_True() { WordCounterMVCController controller = new WordCounterMVCController(); ActionResult counterView = controller.Counter(); Assert.IsInstanceOfType(counterView, typeof(ViewResult)); } [TestMethod] public void Counter_HasCorrectModelType_True() { ViewResult counterView = new WordCounterMVCController().Counter() as ViewResult; var result = counterView.ViewData.Model; Assert.IsInstanceOfType(result, typeof(ViewResult)); } [TestMethod] public void Result_ReturnsCorrectView_True() { WordCounterMVCController controller = new WordCounterMVCController(); ActionResult resultView = controller.Result(); Assert.IsInstanceOfType(resultView, typeof(ViewResult)); } [TestMethod] public void Result_HasCorrectModelType_True() { ViewResult resultView = new WordCounterMVCController().Result() as ViewResult; var result = resultView.ViewData.Model; Assert.IsInstanceOfType(result, typeof(ViewResult)); } [TestMethod] public void Info_ReturnsCorrectView_True() { WordCounterMVCController controller = new WordCounterMVCController(); ActionResult infoView = controller.Info(); Assert.IsInstanceOfType(infoView, typeof(ViewResult)); } [TestMethod] public void Info_HasCorrectModelType_True() { ViewResult infoView = new WordCounterMVCController().Info() as ViewResult; var result = infoView.ViewData.Model; Assert.IsInstanceOfType(result, typeof(ViewResult)); } } }
35.949153
93
0.638378
[ "MIT" ]
nikkiboyd/word-counter
WordCounterMVC.Tests/ControllerTests/WordCounterMVCTests.cs
2,121
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("EmberHello")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("EmberHello")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("e328d63d-7ece-4d73-9180-f9d86d945109")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.583333
84
0.747967
[ "MIT" ]
Silvenga/Small-Projects
SchoolCode/Code/VS Workspace/EmberHello/EmberHello/Properties/AssemblyInfo.cs
1,356
C#
using System; using NimbleConfig.Core.Logging; namespace NimbleConfig.Core.Configuration { public abstract class ConfigurationSetting<TValue> { public virtual TValue Value { get; set; } /// <summary> /// This method gets called when setting the value, use this to customize the logic /// </summary> /// <param name="value">The value read from the configuration</param> public virtual void SetValue(TValue value) { if (value == null || value.Equals(default(TValue))) { StaticLoggingHelper.Info($"{GetType().Name} value has been resolved as null/default"); Value = default(TValue); } Value = value; } public static implicit operator TValue(ConfigurationSetting<TValue> d) => d.Value; } }
29.793103
102
0.596065
[ "MIT" ]
dasiths/NimbleConfig
NimbleConfig.Core/Configuration/ConfigurationSetting.cs
866
C#
// Copyright (c) Wiesław Šoltés. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Dock.Model { /// <summary> /// Dock window contract. /// </summary> public interface IDockWindow { /// <summary> /// Gets or sets id. /// </summary> string Id { get; set; } /// <summary> /// Gets or sets window X coordinate. /// </summary> double X { get; set; } /// <summary> /// Gets or sets window X coordinate. /// </summary> double Y { get; set; } /// <summary> /// Gets or sets window width. /// </summary> double Width { get; set; } /// <summary> /// Gets or sets window height. /// </summary> double Height { get; set; } /// <summary> /// Gets or sets whether this window appears on top of all other windows. /// </summary> bool Topmost { get; set; } /// <summary> /// Gets or sets window title. /// </summary> string Title { get; set; } /// <summary> /// Gets or sets window context. /// </summary> object Context { get; set; } /// <summary> /// Gets or sets window owner view. /// </summary> IView Owner { get; set; } /// <summary> /// Gets or sets dock factory. /// </summary> IDockFactory Factory { get; set; } /// <summary> /// Gets or sets views layout. /// </summary> IDock Layout { get; set; } /// <summary> /// Gets or sets dock window. /// </summary> IDockHost Host { get; set; } /// <summary> /// Saves window properties. /// </summary> void Save(); /// <summary> /// Presents window. /// </summary> /// <param name="isDialog">The value that indicates whether window is dialog.</param> void Present(bool isDialog); /// <summary> /// Exits window. /// </summary> void Exit(); } }
24.909091
101
0.482208
[ "MIT" ]
PurpleGray/Dock
src/Dock.Model/IDockWindow.cs
2,197
C#
using Archimedes.Framework.Stereotype; namespace Archimedes.Framework.Test.ContainerTest { [Service] public class ServiceB : IServiceB { public void Test() { } } }
15.642857
49
0.584475
[ "MIT" ]
ElderByte-/Archimedes.Framework
Archimedes.Framework.Test/ContainerTest/ServiceB.cs
221
C#
using System; using Newtonsoft.Json; using System.Xml.Serialization; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// KoubeiMerchantShopQueryModel Data Structure. /// </summary> [Serializable] public class KoubeiMerchantShopQueryModel : AlipayObject { /// <summary> /// 用户从口碑商家中心页面跳转到ISV页面时url中带有的authCode值,用来ISV获取用户身份。 /// </summary> [JsonProperty("auth_code")] [XmlElement("auth_code")] public string AuthCode { get; set; } /// <summary> /// 商户的部门id,如果有值,返回当前商户下的所有未分配过部门的门店,加上当前部门id及其下分支部门的门店一起返回。如果为空,则仅返回当前商户下的所有未分配过部门的门店。 /// </summary> [JsonProperty("dept_id")] [XmlElement("dept_id")] public string DeptId { get; set; } } }
27.928571
95
0.639386
[ "MIT" ]
Aosir/Payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/KoubeiMerchantShopQueryModel.cs
1,002
C#
// <auto-generated/> #pragma warning disable 1591 #pragma warning disable 0414 #pragma warning disable 0649 #pragma warning disable 0169 namespace EC1._44CharacterGenerator.Pages { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #nullable restore #line 1 "C:\Code\Repos\Blazor\EC1.44CharacterGenerator\_Imports.razor" using System.Net.Http; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Code\Repos\Blazor\EC1.44CharacterGenerator\_Imports.razor" using Microsoft.AspNetCore.Authorization; #line default #line hidden #nullable disable #nullable restore #line 3 "C:\Code\Repos\Blazor\EC1.44CharacterGenerator\_Imports.razor" using Microsoft.AspNetCore.Components.Authorization; #line default #line hidden #nullable disable #nullable restore #line 4 "C:\Code\Repos\Blazor\EC1.44CharacterGenerator\_Imports.razor" using Microsoft.AspNetCore.Components.Forms; #line default #line hidden #nullable disable #nullable restore #line 5 "C:\Code\Repos\Blazor\EC1.44CharacterGenerator\_Imports.razor" using Microsoft.AspNetCore.Components.Routing; #line default #line hidden #nullable disable #nullable restore #line 6 "C:\Code\Repos\Blazor\EC1.44CharacterGenerator\_Imports.razor" using Microsoft.AspNetCore.Components.Web; #line default #line hidden #nullable disable #nullable restore #line 7 "C:\Code\Repos\Blazor\EC1.44CharacterGenerator\_Imports.razor" using Microsoft.AspNetCore.Components.Web.Virtualization; #line default #line hidden #nullable disable #nullable restore #line 8 "C:\Code\Repos\Blazor\EC1.44CharacterGenerator\_Imports.razor" using Microsoft.JSInterop; #line default #line hidden #nullable disable #nullable restore #line 9 "C:\Code\Repos\Blazor\EC1.44CharacterGenerator\_Imports.razor" using EC1._44CharacterGenerator; #line default #line hidden #nullable disable #nullable restore #line 10 "C:\Code\Repos\Blazor\EC1.44CharacterGenerator\_Imports.razor" using EC1._44CharacterGenerator.Shared; #line default #line hidden #nullable disable [Microsoft.AspNetCore.Components.RouteAttribute("/counter")] public partial class Counter : Microsoft.AspNetCore.Components.ComponentBase { #pragma warning disable 1998 protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) { } #pragma warning restore 1998 #nullable restore #line 9 "C:\Code\Repos\Blazor\EC1.44CharacterGenerator\Pages\Counter.razor" private int currentCount = 0; private void IncrementCount() { currentCount++; } #line default #line hidden #nullable disable } } #pragma warning restore 1591
25.431193
118
0.782828
[ "MIT" ]
FlintTD/EC1.44CharacterGenerator
obj/Debug/net5.0/RazorDeclaration/Pages/Counter.razor.g.cs
2,772
C#
public abstract class BaseArtSet : ScriptableObject // TypeDefIndex: 9630 { // Methods // RVA: 0x22AEEF0 Offset: 0x22AEFF1 VA: 0x22AEEF0 protected void .ctor() { } }
19
73
0.719298
[ "MIT" ]
SinsofSloth/RF5-global-metadata
Funly/SkyStudio/BaseArtSet.cs
171
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using System.Windows.Forms; namespace TouchKB { class GraphicTouchKey : TouchKey { private Bitmap releasedBmp_ = null; private Bitmap pressedBmp_ = null; private Rectangle? textRect_; public GraphicTouchKey( Point Position, int ScanCode, InputLanguage InLang, Bitmap ReleasedBmp, Bitmap PressedBmp ) : base( Position, ScanCode, InLang ) { releasedBmp_ = ReleasedBmp; pressedBmp_ = PressedBmp; } public GraphicTouchKey( Point Position, int ScanCode, InputLanguage InLang, Rectangle TxtRect, Bitmap ReleasedBmp, Bitmap PressedBmp ) : this(Position, ScanCode, InLang, ReleasedBmp, PressedBmp ) { textRect_ = TxtRect; } protected override Rectangle GetTextRect() { return textRect_.HasValue ? textRect_.Value : base.GetTextRect(); } protected override Bitmap DoGetReleasedBmp( bool Locked ) { return releasedBmp_; } protected override Bitmap DoGetPressedBmp(bool Locked ) { return pressedBmp_; } } }
27.770833
90
0.6009
[ "Unlicense" ]
gcardi/TouchKB
TouchKB/GraphicTouchKey.cs
1,335
C#
/* Copyright (c) Citrix Systems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * Redistributions of source code must retain the above * copyright notice, this list of conditions and the * following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using XenAdmin.Alerts; using XenAdmin.Model; using System.Drawing; using XenAdmin.Core; using XenAdmin.Network; using XenAPI; using XenAdmin.XenSearch; using System.IO; namespace XenAdmin { static class Images { public static readonly ImageList ImageList16 = new ImageList(); /// <summary> /// This is the same images as in ImageList16, but in an array. /// Reading from the ImageList is strangely slow. /// </summary> private static readonly Image[] ImageArray16 = new Image[Enum.GetValues(typeof(Icons)).Length]; static Images() { ImageList16.ColorDepth = ColorDepth.Depth32Bit; ImageList16.TransparentColor = Color.Transparent; // Initialize our ImageList. We do this programatically (as opposed to using the designer) because // of a known bug in ImageList with transparency. // See http://www.codeproject.com/cs/miscctrl/AlphaImageImagelist.asp?df=100&forumid=137678&exp=0&select=1392020#xx1392020xx // To workaround the bug, we just add the images from the resource file. // Note that this list is in the same order as the enum in Icons.cs. ImageList16.Images.Add("Logo.png", XenAdmin.Properties.Resources.Logo); ImageList16.Images.Add("000_ServerInProgress_h32bit_16.png", XenAdmin.Properties.Resources._000_ServerInProgress_h32bit_16); ImageList16.Images.Add("000_TreeConnected_h32bit_16.png", XenAdmin.Properties.Resources._000_TreeConnected_h32bit_16); ImageList16.Images.Add("000_ServerDisconnected_h32bit_16.png", XenAdmin.Properties.Resources._000_ServerDisconnected_h32bit_16); ImageList16.Images.Add("000_ServerMaintenance_h32bit_16.png", XenAdmin.Properties.Resources._000_ServerMaintenance_h32bit_16); ImageList16.Images.Add("000_HostUnpatched_h32bit_16.png", XenAdmin.Properties.Resources._000_HostUnpatched_h32bit_16); ImageList16.Images.Add("server_up_16.png", XenAdmin.Properties.Resources.server_up_16); ImageList16.Images.Add("000_ServerErrorFile_h32bit_16.png", XenAdmin.Properties.Resources._000_ServerErrorFile_h32bit_16); ImageList16.Images.Add("000_StartVM_h32bit_16.png", XenAdmin.Properties.Resources._000_StartVM_h32bit_16); ImageList16.Images.Add("000_VMDisabled_h32bit_16.png", XenAdmin.Properties.Resources._000_VMDisabled_h32bit_16); ImageList16.Images.Add("000_StoppedVM_h32bit_16.png", XenAdmin.Properties.Resources._000_StoppedVM_h32bit_16); ImageList16.Images.Add("000_VMStoppedDisabled_h32bit_16.png", XenAdmin.Properties.Resources._000_VMStoppedDisabled_h32bit_16); ImageList16.Images.Add("000_SuspendVM_h32bit_16.png", XenAdmin.Properties.Resources._000_SuspendVM_h32bit_16); ImageList16.Images.Add("000_VMPausedDisabled_h32bit_16.png", XenAdmin.Properties.Resources._000_VMPausedDisabled_h32bit_16); ImageList16.Images.Add("000_VMStarting_h32bit_16.png", XenAdmin.Properties.Resources._000_VMStarting_h32bit_16); ImageList16.Images.Add("000_VMStartingDisabled_h32bit_16.png", XenAdmin.Properties.Resources._000_VMStartingDisabled_h32bit_16); ImageList16.Images.Add("000_VMTemplate_h32bit_16.png", XenAdmin.Properties.Resources._000_VMTemplate_h32bit_16); ImageList16.Images.Add("000_TemplateDisabled_h32bit_16.png", XenAdmin.Properties.Resources._000_TemplateDisabled_h32bit_16); ImageList16.Images.Add("000_UserTemplate_h32bit_16.png", XenAdmin.Properties.Resources._000_UserTemplate_h32bit_16); ImageList16.Images.Add("000_VMSession_h32bit_16.png", XenAdmin.Properties.Resources._000_VMSession_h32bit_16); ImageList16.Images.Add("000_VMSnapShotDiskOnly_h32bit_16.png", XenAdmin.Properties.Resources._000_VMSnapShotDiskOnly_h32bit_16); ImageList16.Images.Add("000_VMSnapshotDiskMemory_h32bit_16.png", XenAdmin.Properties.Resources._000_VMSnapshotDiskMemory_h32bit_16); ImageList16.Images.Add("_000_ScheduledVMsnapshotDiskOnly_h32bit_16.png", XenAdmin.Properties.Resources._000_ScheduledVMsnapshotDiskOnly_h32bit_16); ImageList16.Images.Add("_000_ScheduledVMsnapshotDiskMemory_h32bit_16.png", XenAdmin.Properties.Resources._000_ScheduledVMsnapshotDiskMemory_h32bit_16); ImageList16.Images.Add("000_PoolConnected_h32bit_16.png", XenAdmin.Properties.Resources._000_PoolConnected_h32bit_16); ImageList16.Images.Add("pool_up_16.png", XenAdmin.Properties.Resources.pool_up_16); ImageList16.Images.Add("000_Storage_h32bit_16.png", XenAdmin.Properties.Resources._000_Storage_h32bit_16); ImageList16.Images.Add("000_StorageBroken_h32bit_16.png", XenAdmin.Properties.Resources._000_StorageBroken_h32bit_16); ImageList16.Images.Add("000_StorageDefault_h32bit_16.png", XenAdmin.Properties.Resources._000_StorageDefault_h32bit_16); ImageList16.Images.Add("000_StorageDisabled_h32bit_16.png", XenAdmin.Properties.Resources._000_StorageDisabled_h32bit_16); ImageList16.Images.Add("001_ShutDown_h32bit_16.png", Properties.Resources._001_ShutDown_h32bit_16); ImageList16.Images.Add("000_paused_h32bit_16.png", Properties.Resources._000_paused_h32bit_16); ImageList16.Images.Add("001_PowerOn_h32bit_16.png", Properties.Resources._001_PowerOn_h32bit_16); ImageList16.Images.Add("000_HelpIM_h32bit_16.png", Properties.Resources._000_HelpIM_h32bit_16); ImageList16.Images.Add("000_Network_h32bit_16.png", Properties.Resources._000_Network_h32bit_16); ImageList16.Images.Add("000_defaultSpyglass_h32bit_16.png", Properties.Resources._000_defaultSpyglass_h32bit_16); ImageList16.Images.Add("000_Search_h32bit_16.png", Properties.Resources._000_Search_h32bit_16); #region Server message images ImageList16.Images.Add("001_PowerOn_h32bit_16.png", Properties.Resources._001_PowerOn_h32bit_16); ImageList16.Images.Add("001_ShutDown_h32bit_16.png", Properties.Resources._001_ShutDown_h32bit_16); ImageList16.Images.Add("001_Reboot_h32bit_16.png", Properties.Resources._001_Reboot_h32bit_16); ImageList16.Images.Add("000_paused_h32bit_16.png", Properties.Resources._000_paused_h32bit_16); ImageList16.Images.Add("000_Resumed_h32bit_16.png", Properties.Resources._000_Resumed_h32bit_16); ImageList16.Images.Add("clonevm_16.png", Properties.Resources.clonevm_16); ImageList16.Images.Add("Logo.png", Properties.Resources.Logo); ImageList16.Images.Add("alert1_16.png", Properties.Resources.alert1_16); ImageList16.Images.Add("alert2_16.png", Properties.Resources.alert2_16); ImageList16.Images.Add("alert3_16.png", Properties.Resources.alert3_16); ImageList16.Images.Add("alert4_16.png", Properties.Resources.alert4_16); ImageList16.Images.Add("alert5_16.png", Properties.Resources.alert5_16); #endregion ImageList16.Images.Add("centos_16x.png", Properties.Resources.centos_16x); ImageList16.Images.Add("debian_16x.png", Properties.Resources.debian_16x); ImageList16.Images.Add("oracle_16x.png", Properties.Resources.oracle_16x); ImageList16.Images.Add("redhat_16x.png", Properties.Resources.redhat_16x); ImageList16.Images.Add("suse_16x.png", Properties.Resources.suse_16x); ImageList16.Images.Add("ubuntu_16x.png", Properties.Resources.ubuntu_16x); ImageList16.Images.Add("scilinux_16x.png", Properties.Resources.scilinux_16x); ImageList16.Images.Add("neokylin_16x.png", Properties.Resources.neokylin_16x); ImageList16.Images.Add("windows_h32bit_16.png", Properties.Resources.windows_h32bit_16); ImageList16.Images.Add("coreos-globe-icon.png", Properties.Resources.coreos_globe_icon); ImageList16.Images.Add("tools_uptodate_16x.png", Properties.Resources.tools_uptodate_16x); ImageList16.Images.Add("tools_notinstalled_16x.png", Properties.Resources.tools_notinstalled_16x); ImageList16.Images.Add("tools_outofdate_16x.png", Properties.Resources.tools_outofdate_16x); ImageList16.Images.Add("000_VM_h32bit_16.png", Properties.Resources._000_VM_h32bit_16); ImageList16.Images.Add("000_Server_h32bit_16.png", Properties.Resources._000_Server_h32bit_16); ImageList16.Images.Add("000_Pool_h32bit_16.png", Properties.Resources._000_Pool_h32bit_16); ImageList16.Images.Add("000_VirtualStorage_h32bit_16.png", Properties.Resources._000_VirtualStorage_h32bit_16); ImageList16.Images.Add("virtualstorage_snapshot_16.png", Properties.Resources.virtualstorage_snapshot_16); ImageList16.Images.Add("000_Folder_open_h32bit_16.png", Properties.Resources._000_Folder_open_h32bit_16); ImageList16.Images.Add("folder_grey.png", Properties.Resources.folder_grey); ImageList16.Images.Add("000_Tag_h32bit_16.png", Properties.Resources._000_Tag_h32bit_16); ImageList16.Images.Add("000_Fields_h32bit_16.png", Properties.Resources._000_Fields_h32bit_16); ImageList16.Images.Add("ha_16.png", Properties.Resources.ha_16); ImageList16.Images.Add("virtualappliance_16.png", Properties.Resources._000_VirtualAppliance_h32bit_16); ImageList16.Images.Add("000_MigrateVM_h32bit_16.png", Properties.Resources._000_MigrateVM_h32bit_16); ImageList16.Images.Add("000_MigrateStoppedVM_h32bit_16.png", Properties.Resources._000_MigrateStoppedVM_h32bit_16); ImageList16.Images.Add("000_MigrateSuspendedVM_h32bit_16.png", Properties.Resources._000_MigrateSuspendedVM_h32bit_16); ImageList16.Images.Add("_000_ManagementInterface_h32bit_16.png", Properties.Resources._000_ManagementInterface_h32bit_16); ImageList16.Images.Add("000_TCP_IPGroup_h32bit_16.png", Properties.Resources._000_TCP_IPGroup_h32bit_16); ImageList16.Images.Add("infra_view_16_textured.png", Properties.Resources.infra_view_16_textured); ImageList16.Images.Add("objects_16_textured.png", Properties.Resources.objects_16_textured); ImageList16.Images.Add("000_Sites_h32bit_16.png", Properties.Resources._000_Sites_h32bit_16); ImageList16.Images.Add("RunningDC_16.png", Properties.Resources.RunningDC_16); ImageList16.Images.Add("StoppedDC_16.png", Properties.Resources.StoppedDC_16); ImageList16.Images.Add("PausedDC_16.png", Properties.Resources.PausedDC_16); #region Status Icons ImageList16.Images.Add("000_Tick_h32bit_16", Properties.Resources._000_Tick_h32bit_16); //Ok ImageList16.Images.Add("000_Info3_h32bit_16.png", Properties.Resources._000_Info3_h32bit_16); //Info ImageList16.Images.Add("000_Alert2_h32bit_16.png", Properties.Resources._000_Alert2_h32bit_16); //Warning ImageList16.Images.Add("000_Abort_h32bit_16.png", Properties.Resources._000_Abort_h32bit_16); //Error #endregion System.Diagnostics.Trace.Assert(ImageList16.Images.Count == Enum.GetValues(typeof(Icons)).Length, "Programmer error - you must add an entry to the image list when you add a new icon to the enum"); int i = 0; foreach (Image im in ImageList16.Images) { ImageArray16[i++] = im; } } public static Image GetImage16For(IXenConnection connection) { Icons icon = GetIconFor(connection); return ImageArray16[(int)icon]; } public static Image GetImage16For(IXenObject o) { Icons icon = GetIconFor(o); return ImageArray16[(int)icon]; } public static Image GetImage16For(Search search) { return GetImage16For(GetIconFor(search)); } public static Image GetImage16For(XenAPI.Message.MessageType type) { return GetImage16For(GetIconFor(type)); } public static Image GetImage16For(AlertPriority priority) { var icon = GetIconFor(priority); return icon == Icons.MessageUnknown ? null : GetImage16For(icon); } public static Image GetImage32For(IXenObject o) { return new Bitmap(GetImage16For(o), 32, 32); } public static Image GetImage16For(Icons icon) { return ImageArray16[(int)icon]; } public static Icons GetIconFor(IXenObject o) { VM vm = o as VM; if (vm != null) return GetIconFor(vm); VM_appliance appl = o as VM_appliance; if (appl != null) return GetIconFor(appl); SR sr = o as SR; if (sr != null) return GetIconFor(sr); Host host = o as Host; if (host != null) return GetIconFor(host); Pool pool = o as Pool; if (pool != null) return GetIconFor(pool); XenAPI.Network network = o as XenAPI.Network; if (network != null) return GetIconFor(network); VDI vdi = o as VDI; if (vdi != null) return GetIconFor(vdi); VBD vbd = o as VBD; if (vbd != null) return GetIconFor(vbd); Folder folder = o as Folder; if (folder != null) return GetIconFor(folder); PIF pif = o as PIF; if (pif != null) return GetIconFor(pif); DockerContainer dockerContainer = o as DockerContainer; if (dockerContainer != null) return GetIconFor(dockerContainer); System.Diagnostics.Trace.Assert(false, "You asked for an icon for a type I don't recognise!"); return Icons.XenCenter; } public static Icons GetIconFor(Search search) { return search.DefaultSearch ? Icons.DefaultSearch : Icons.Search; } public static Icons GetIconFor(IXenConnection connection) { Pool pool = Helpers.GetPool(connection); if (pool != null) return GetIconFor(pool); Host host = Helpers.GetMaster(connection); if (host != null) return GetIconFor(host); if (connection.InProgress) // Yellow connection in progress icon return Icons.HostConnecting; else // Red disconnected icon return Icons.HostDisconnected; } public static Icons GetIconFor(Folder folder) { return folder.Grey ? Icons.FolderGrey : Icons.Folder; } public static Icons GetIconFor(VM_appliance appl) { return Icons.VmAppliance; } public static Icons GetIconFor(VM vm) { bool disabled = vm.IsHidden; if (vm.is_a_snapshot) { if (vm.is_snapshot_from_vmpp || vm.is_vmss_snapshot) { if (vm.power_state == vm_power_state.Suspended) return Icons.ScheduledSnapshotDiskMemory; else return Icons.ScheduledSnapshotDiskOnly; } else { if (vm.power_state == vm_power_state.Suspended) return Icons.SnapshotWithMem; else return Icons.SnapshotDisksOnly; } } if (vm.is_a_template && vm.DefaultTemplate) return disabled ? Icons.TemplateDisabled : Icons.Template; if (vm.is_a_template && !vm.DefaultTemplate) return disabled ? Icons.TemplateDisabled : Icons.TemplateUser; if (!vm.ExistsOnServer) return disabled ? Icons.VmStoppedDisabled : Icons.VmStopped; if (vm.current_operations.ContainsValue(vm_operations.migrate_send)) { switch (vm.power_state) { case vm_power_state.Halted: return Icons.VmCrossPoolMigrateStopped; case vm_power_state.Suspended: case vm_power_state.Paused: return Icons.VmCrossPoolMigrateSuspended; default: return Icons.VmCrossPoolMigrate; } } // If a VM lifecycle operation is in progress, show the orange "starting" icon foreach (vm_operations op in vm.current_operations.Values) { if (VM.is_lifecycle_operation(op)) return disabled ? Icons.VmStartingDisabled : Icons.VmStarting; } switch (vm.power_state) { case XenAPI.vm_power_state.Suspended: return disabled ? Icons.VmSuspendedDisabled : Icons.VmSuspended; case XenAPI.vm_power_state.Running: return disabled ? Icons.VmRunningDisabled : Icons.VmRunning; case XenAPI.vm_power_state.Paused: return disabled ? Icons.VmSuspendedDisabled : Icons.VmSuspended; default: return disabled ? Icons.VmStoppedDisabled : Icons.VmStopped; } } public static Icons GetIconFor(SR sr) { return sr.GetIcon; } public static Icons GetIconFor(Host host) { Host_metrics metrics = host.Connection.Resolve<Host_metrics>(host.metrics); bool host_is_live = metrics != null && metrics.live; if (host_is_live) { if (host.HasCrashDumps) { return Icons.HostHasCrashDumps; } if (host.current_operations.ContainsValue(host_allowed_operations.evacuate) || !host.enabled) { return Icons.HostEvacuate; } else if (Helpers.IsOlderThanMaster(host)) { return Icons.HostOlderThanMaster; } else { return Icons.HostConnected; } } else { // XenAdmin.XenSearch.Group puts a fake host in the treeview for disconnected // XenConnections. So here we give the yellow 'connection in progress' icon which formerly // applied only to XenConnections. if (host.Connection.InProgress && !host.Connection.IsConnected) return Icons.HostConnecting; else return Icons.HostDisconnected; } } public static Icons GetIconFor(Pool pool) { return pool.Connection.IsConnected ? pool.IsPoolFullyUpgraded ? Icons.PoolConnected : Icons.PoolNotFullyUpgraded : Icons.HostDisconnected; } public static Icons GetIconFor(XenAPI.Network network) { return Icons.Network; } public static Icons GetIconFor(VDI vdi) { if (vdi.is_a_snapshot) return Icons.VDISnapshot; else return Icons.VDI; } public static Icons GetIconFor(VBD vbd) { return Icons.VDI; } public static Icons GetIconFor(XenAPI.Message.MessageType type) { switch (type) { case XenAPI.Message.MessageType.VM_STARTED: return Icons.VmStart; case XenAPI.Message.MessageType.VM_SHUTDOWN: return Icons.VmShutdown; case XenAPI.Message.MessageType.VM_REBOOTED: return Icons.VmReboot; case XenAPI.Message.MessageType.VM_SUSPENDED: return Icons.VmSuspend; case XenAPI.Message.MessageType.VM_RESUMED: return Icons.VmResumed; case XenAPI.Message.MessageType.VM_CLONED: return Icons.VmCloned; default: return Icons.MessageUnknown; } } public static Icons GetIconFor(AlertPriority priority) { switch (priority) { case AlertPriority.Priority1: return Icons.MessagePriority1; case AlertPriority.Priority2: return Icons.MessagePriority2; case AlertPriority.Priority3: return Icons.MessagePriority3; case AlertPriority.Priority4: return Icons.MessagePriority4; case AlertPriority.Priority5: return Icons.MessagePriority5; default: return Icons.MessageUnknown; } } public static void GenImageHTML() { // create a writer and open the file TextWriter tw = new StreamWriter("images.htm"); tw.WriteLine("<html><head><title>XenCenter Images</title></head>"); tw.WriteLine("<body><table>"); foreach (Icons icon in Enum.GetValues(typeof(Icons))) { tw.WriteLine("<tr><td>{0}</td><td><image src='{1}'></td></tr>", icon, ImageList16.Images.Keys[(int)icon]); } tw.WriteLine("</table></body></html>"); // close the stream tw.Close(); } public static Icons GetIconFor(PIF pif) { return pif.IsPrimaryManagementInterface() ? Icons.PifPrimary : Icons.PifSecondary; } public static Icons GetIconFor(DockerContainer dockerContainer) { switch (dockerContainer.power_state) { case vm_power_state.Paused: return Icons.DCPaused; case vm_power_state.Running: return Icons.DCRunning; default: return Icons.DCStopped; } } public static class StaticImages { // the followings are generated from Resources using: // cat Resources.Designer.cs | grep 'internal static System.Drawing.Bitmap' | sed "s/ {//g" | awk -F"Bitmap " '{print"public static Image " $2 " = Properties.Resources." $2 ";"}' public static Image _000_Abort_h32bit_16 = Properties.Resources._000_Abort_h32bit_16; public static Image _000_AddApplicationServer_h32bit_16 = Properties.Resources._000_AddApplicationServer_h32bit_16; public static Image _000_AddApplicationServer_h32bit_24 = Properties.Resources._000_AddApplicationServer_h32bit_24; public static Image _000_AddIPAddress_h32bit_16 = Properties.Resources._000_AddIPAddress_h32bit_16; public static Image _000_AddSite_h32bit_16 = Properties.Resources._000_AddSite_h32bit_16; public static Image _000_Alert2_h32bit_16 = Properties.Resources._000_Alert2_h32bit_16; public static Image _000_BackupMetadata_h32bit_16 = Properties.Resources._000_BackupMetadata_h32bit_16; public static Image _000_BackupMetadata_h32bit_32 = Properties.Resources._000_BackupMetadata_h32bit_32; public static Image _000_ConfigureIPAddresses_h32bit_16 = Properties.Resources._000_ConfigureIPAddresses_h32bit_16; public static Image _000_CPU_h32bit_16 = Properties.Resources._000_CPU_h32bit_16; public static Image _000_CreateVirtualStorage_h32bit_32 = Properties.Resources._000_CreateVirtualStorage_h32bit_32; public static Image _000_CreateVM_h32bit_24 = Properties.Resources._000_CreateVM_h32bit_24; public static Image _000_CreateVM_h32bit_32 = Properties.Resources._000_CreateVM_h32bit_32; public static Image _000_defaultSpyglass_h32bit_16 = Properties.Resources._000_defaultSpyglass_h32bit_16; public static Image _000_DeleteAllMessages_h32bit_16 = Properties.Resources._000_DeleteAllMessages_h32bit_16; public static Image _000_DeleteMessage_h32bit_16 = Properties.Resources._000_DeleteMessage_h32bit_16; public static Image _000_DeleteVirtualAppliance_h32bit_16 = Properties.Resources._000_DeleteVirtualAppliance_h32bit_16; public static Image _000_DisasterRecovery_h32bit_32 = Properties.Resources._000_DisasterRecovery_h32bit_32; public static Image _000_Email_h32bit_16 = Properties.Resources._000_Email_h32bit_16; public static Image _000_EnablePowerControl_h32bit_16 = Properties.Resources._000_EnablePowerControl_h32bit_16; public static Image _000_error_h32bit_16 = Properties.Resources._000_error_h32bit_16; public static Image _000_error_h32bit_32 = Properties.Resources._000_error_h32bit_32; public static Image _000_ExcludeHost_h32bit_16 = Properties.Resources._000_ExcludeHost_h32bit_16; public static Image _000_ExportMessages_h32bit_16 = Properties.Resources._000_ExportMessages_h32bit_16; public static Image _000_ExportVirtualAppliance_h32bit_16 = Properties.Resources._000_ExportVirtualAppliance_h32bit_16; public static Image _000_ExportVirtualAppliance_h32bit_32 = Properties.Resources._000_ExportVirtualAppliance_h32bit_32; public static Image _000_Failback_h32bit_32 = Properties.Resources._000_Failback_h32bit_32; public static Image _000_Failover_h32bit_32 = Properties.Resources._000_Failover_h32bit_32; public static Image _000_Fields_h32bit_16 = Properties.Resources._000_Fields_h32bit_16; public static Image _000_FilterDates_h32bit_16 = Properties.Resources._000_FilterDates_h32bit_16; public static Image _000_FilterServer_h32bit_16 = Properties.Resources._000_FilterServer_h32bit_16; public static Image _000_FilterSeverity_h32bit_16 = Properties.Resources._000_FilterSeverity_h32bit_16; public static Image _000_Folder_open_h32bit_16 = Properties.Resources._000_Folder_open_h32bit_16; public static Image _000_GetMemoryInfo_h32bit_16 = Properties.Resources._000_GetMemoryInfo_h32bit_16; public static Image _000_GetMemoryInfo_h32bit_32 = Properties.Resources._000_GetMemoryInfo_h32bit_32; public static Image _000_GetServerReport_h32bit_16 = Properties.Resources._000_GetServerReport_h32bit_16; public static Image _000_GetServerReport_h32bit_32 = Properties.Resources._000_GetServerReport_h32bit_32; public static Image _000_HAServer_h32bit_32 = Properties.Resources._000_HAServer_h32bit_32; public static Image _000_HelpIM_h32bit_16 = Properties.Resources._000_HelpIM_h32bit_16; public static Image _000_HelpIM_h32bit_32 = Properties.Resources._000_HelpIM_h32bit_32; public static Image _000_HighlightVM_h32bit_24 = Properties.Resources._000_HighlightVM_h32bit_24; public static Image _000_HighLightVM_h32bit_32 = Properties.Resources._000_HighLightVM_h32bit_32; public static Image _000_host_0_star = Properties.Resources._000_host_0_star; public static Image _000_host_1_star = Properties.Resources._000_host_1_star; public static Image _000_host_10_star = Properties.Resources._000_host_10_star; public static Image _000_host_2_star = Properties.Resources._000_host_2_star; public static Image _000_host_3_star = Properties.Resources._000_host_3_star; public static Image _000_host_4_star = Properties.Resources._000_host_4_star; public static Image _000_host_5_star = Properties.Resources._000_host_5_star; public static Image _000_host_6_star = Properties.Resources._000_host_6_star; public static Image _000_host_7_star = Properties.Resources._000_host_7_star; public static Image _000_host_8_star = Properties.Resources._000_host_8_star; public static Image _000_host_9_star = Properties.Resources._000_host_9_star; public static Image _000_HostUnpatched_h32bit_16 = Properties.Resources._000_HostUnpatched_h32bit_16; public static Image _000_ImportVirtualAppliance_h32bit_16 = Properties.Resources._000_ImportVirtualAppliance_h32bit_16; public static Image _000_ImportVirtualAppliance_h32bit_32 = Properties.Resources._000_ImportVirtualAppliance_h32bit_32; public static Image _000_ImportVM_h32bit_32 = Properties.Resources._000_ImportVM_h32bit_32; public static Image _000_Info3_h32bit_16 = Properties.Resources._000_Info3_h32bit_16; public static Image _000_ManagementInterface_h32bit_16 = Properties.Resources._000_ManagementInterface_h32bit_16; public static Image _000_MigrateStoppedVM_h32bit_16 = Properties.Resources._000_MigrateStoppedVM_h32bit_16; public static Image _000_MigrateSuspendedVM_h32bit_16 = Properties.Resources._000_MigrateSuspendedVM_h32bit_16; public static Image _000_MigrateVM_h32bit_16 = Properties.Resources._000_MigrateVM_h32bit_16; public static Image _000_MigrateVM_h32bit_32 = Properties.Resources._000_MigrateVM_h32bit_32; public static Image _000_Module_h32bit_16 = Properties.Resources._000_Module_h32bit_16; public static Image _000_Network_h32bit_16 = Properties.Resources._000_Network_h32bit_16; public static Image _000_NewNetwork_h32bit_32 = Properties.Resources._000_NewNetwork_h32bit_32; public static Image _000_NewStorage_h32bit_16 = Properties.Resources._000_NewStorage_h32bit_16; public static Image _000_NewStorage_h32bit_24 = Properties.Resources._000_NewStorage_h32bit_24; public static Image _000_NewStorage_h32bit_32 = Properties.Resources._000_NewStorage_h32bit_32; public static Image _000_NewVirtualAppliance_h32bit_16 = Properties.Resources._000_NewVirtualAppliance_h32bit_16; public static Image _000_NewVirtualAppliance_h32bit_32 = Properties.Resources._000_NewVirtualAppliance_h32bit_32; public static Image _000_Optimize_h32bit_16 = Properties.Resources._000_Optimize_h32bit_16; public static Image _000_Patch_h32bit_16 = Properties.Resources._000_Patch_h32bit_16; public static Image _000_Patch_h32bit_32 = Properties.Resources._000_Patch_h32bit_32; public static Image _000_paused_h32bit_16 = Properties.Resources._000_paused_h32bit_16; public static Image _000_Paused_h32bit_24 = Properties.Resources._000_Paused_h32bit_24; public static Image _000_Pool_h32bit_16 = Properties.Resources._000_Pool_h32bit_16; public static Image _000_PoolConnected_h32bit_16 = Properties.Resources._000_PoolConnected_h32bit_16; public static Image _000_PoolNew_h32bit_16 = Properties.Resources._000_PoolNew_h32bit_16; public static Image _000_PoolNew_h32bit_24 = Properties.Resources._000_PoolNew_h32bit_24; public static Image _000_RebootVM_h32bit_16 = Properties.Resources._000_RebootVM_h32bit_16; public static Image _000_RemoveIPAddress_h32bit_16 = Properties.Resources._000_RemoveIPAddress_h32bit_16; public static Image _000_RemoveSite_h32bit_16 = Properties.Resources._000_RemoveSite_h32bit_16; public static Image _000_Resumed_h32bit_16 = Properties.Resources._000_Resumed_h32bit_16; public static Image _000_Resumed_h32bit_24 = Properties.Resources._000_Resumed_h32bit_24; public static Image _000_ScheduledVMsnapshotDiskMemory_h32bit_16 = Properties.Resources._000_ScheduledVMsnapshotDiskMemory_h32bit_16; public static Image _000_ScheduledVMSnapshotDiskMemory_h32bit_32 = Properties.Resources._000_ScheduledVMSnapshotDiskMemory_h32bit_32; public static Image _000_ScheduledVMsnapshotDiskOnly_h32bit_16 = Properties.Resources._000_ScheduledVMsnapshotDiskOnly_h32bit_16; public static Image _000_ScheduledVMsnapshotDiskOnly_h32bit_32 = Properties.Resources._000_ScheduledVMsnapshotDiskOnly_h32bit_32; public static Image _000_Search_h32bit_16 = Properties.Resources._000_Search_h32bit_16; public static Image _000_Server_h32bit_16 = Properties.Resources._000_Server_h32bit_16; public static Image _000_ServerDisconnected_h32bit_16 = Properties.Resources._000_ServerDisconnected_h32bit_16; public static Image _000_ServerErrorFile_h32bit_16 = Properties.Resources._000_ServerErrorFile_h32bit_16; public static Image _000_ServerHome_h32bit_16 = Properties.Resources._000_ServerHome_h32bit_16; public static Image _000_ServerInProgress_h32bit_16 = Properties.Resources._000_ServerInProgress_h32bit_16; public static Image _000_ServerMaintenance_h32bit_16 = Properties.Resources._000_ServerMaintenance_h32bit_16; public static Image _000_ServerMaintenance_h32bit_32 = Properties.Resources._000_ServerMaintenance_h32bit_32; public static Image _000_ServerWlb_h32bit_16 = Properties.Resources._000_ServerWlb_h32bit_16; public static Image _000_Sites_h32bit_16 = Properties.Resources._000_Sites_h32bit_16; public static Image _000_SliderTexture = Properties.Resources._000_SliderTexture; public static Image _000_StartVM_h32bit_16 = Properties.Resources._000_StartVM_h32bit_16; public static Image _000_StoppedVM_h32bit_16 = Properties.Resources._000_StoppedVM_h32bit_16; public static Image _000_Storage_h32bit_16 = Properties.Resources._000_Storage_h32bit_16; public static Image _000_StorageBroken_h32bit_16 = Properties.Resources._000_StorageBroken_h32bit_16; public static Image _000_StorageDefault_h32bit_16 = Properties.Resources._000_StorageDefault_h32bit_16; public static Image _000_StorageDisabled_h32bit_16 = Properties.Resources._000_StorageDisabled_h32bit_16; public static Image _000_SuspendVM_h32bit_16 = Properties.Resources._000_SuspendVM_h32bit_16; public static Image _000_SwitcherBackground = Properties.Resources._000_SwitcherBackground; public static Image _000_Tag_h32bit_16 = Properties.Resources._000_Tag_h32bit_16; public static Image _000_TCP_IPGroup_h32bit_16 = Properties.Resources._000_TCP_IPGroup_h32bit_16; public static Image _000_TemplateDisabled_h32bit_16 = Properties.Resources._000_TemplateDisabled_h32bit_16; public static Image _000_TestFailover_h32bit_32 = Properties.Resources._000_TestFailover_h32bit_32; public static Image _000_Tick_h32bit_16 = Properties.Resources._000_Tick_h32bit_16; public static Image _000_ToolBar_Pref_Icon_dis = Properties.Resources._000_ToolBar_Pref_Icon_dis; public static Image _000_ToolBar_Pref_Icon_ovr = Properties.Resources._000_ToolBar_Pref_Icon_ovr; public static Image _000_ToolBar_Pref_Icon_up = Properties.Resources._000_ToolBar_Pref_Icon_up; public static Image _000_ToolBar_USB_Icon_dis = Properties.Resources._000_ToolBar_USB_Icon_dis; public static Image _000_ToolBar_USB_Icon_ovr = Properties.Resources._000_ToolBar_USB_Icon_ovr; public static Image _000_ToolBar_USB_Icon_up = Properties.Resources._000_ToolBar_USB_Icon_up; public static Image _000_TreeConnected_h32bit_16 = Properties.Resources._000_TreeConnected_h32bit_16; public static Image _000_UpgradePool_h32bit_32 = Properties.Resources._000_UpgradePool_h32bit_32; public static Image _000_User_h32bit_16 = Properties.Resources._000_User_h32bit_16; public static Image _000_UserAndGroup_h32bit_32 = Properties.Resources._000_UserAndGroup_h32bit_32; public static Image _000_UserTemplate_h32bit_16 = Properties.Resources._000_UserTemplate_h32bit_16; public static Image _000_ViewModeList_h32bit_16 = Properties.Resources._000_ViewModeList_h32bit_16; public static Image _000_ViewModeTree_h32bit_16 = Properties.Resources._000_ViewModeTree_h32bit_16; public static Image _000_VirtualAppliance_h32bit_16 = Properties.Resources._000_VirtualAppliance_h32bit_16; public static Image _000_VirtualStorage_h32bit_16 = Properties.Resources._000_VirtualStorage_h32bit_16; public static Image _000_VM_h32bit_16 = Properties.Resources._000_VM_h32bit_16; public static Image _000_VM_h32bit_24 = Properties.Resources._000_VM_h32bit_24; public static Image _000_VMDisabled_h32bit_16 = Properties.Resources._000_VMDisabled_h32bit_16; public static Image _000_VMPausedDisabled_h32bit_16 = Properties.Resources._000_VMPausedDisabled_h32bit_16; public static Image _000_VMSession_h32bit_16 = Properties.Resources._000_VMSession_h32bit_16; public static Image _000_VMSnapshotDiskMemory_h32bit_16 = Properties.Resources._000_VMSnapshotDiskMemory_h32bit_16; public static Image _000_VMSnapshotDiskMemory_h32bit_32 = Properties.Resources._000_VMSnapshotDiskMemory_h32bit_32; public static Image _000_VMSnapShotDiskOnly_h32bit_16 = Properties.Resources._000_VMSnapShotDiskOnly_h32bit_16; public static Image _000_VMSnapShotDiskOnly_h32bit_32 = Properties.Resources._000_VMSnapShotDiskOnly_h32bit_32; public static Image _000_VMStarting_h32bit_16 = Properties.Resources._000_VMStarting_h32bit_16; public static Image _000_VMStartingDisabled_h32bit_16 = Properties.Resources._000_VMStartingDisabled_h32bit_16; public static Image _000_VMStoppedDisabled_h32bit_16 = Properties.Resources._000_VMStoppedDisabled_h32bit_16; public static Image _000_VMTemplate_h32bit_16 = Properties.Resources._000_VMTemplate_h32bit_16; public static Image _000_WarningAlert_h32bit_32 = Properties.Resources._000_WarningAlert_h32bit_32; public static Image _000_weighting_h32bit_16 = Properties.Resources._000_weighting_h32bit_16; public static Image _000_XenCenterAlerts_h32bit_24 = Properties.Resources._000_XenCenterAlerts_h32bit_24; public static Image _001_Back_h32bit_24 = Properties.Resources._001_Back_h32bit_24; public static Image _001_CreateVM_h32bit_16 = Properties.Resources._001_CreateVM_h32bit_16; public static Image _001_ForceReboot_h32bit_16 = Properties.Resources._001_ForceReboot_h32bit_16; public static Image _001_ForceReboot_h32bit_24 = Properties.Resources._001_ForceReboot_h32bit_24; public static Image _001_ForceShutDown_h32bit_16 = Properties.Resources._001_ForceShutDown_h32bit_16; public static Image _001_ForceShutDown_h32bit_24 = Properties.Resources._001_ForceShutDown_h32bit_24; public static Image _001_Forward_h32bit_24 = Properties.Resources._001_Forward_h32bit_24; public static Image _001_LifeCycle_h32bit_24 = Properties.Resources._001_LifeCycle_h32bit_24; public static Image _001_PerformanceGraph_h32bit_16 = Properties.Resources._001_PerformanceGraph_h32bit_16; public static Image _001_Pin_h32bit_16 = Properties.Resources._001_Pin_h32bit_16; public static Image _001_PowerOn_h32bit_16 = Properties.Resources._001_PowerOn_h32bit_16; public static Image _001_PowerOn_h32bit_24 = Properties.Resources._001_PowerOn_h32bit_24; public static Image _001_Reboot_h32bit_16 = Properties.Resources._001_Reboot_h32bit_16; public static Image _001_Reboot_h32bit_24 = Properties.Resources._001_Reboot_h32bit_24; public static Image _001_ShutDown_h32bit_16 = Properties.Resources._001_ShutDown_h32bit_16; public static Image _001_ShutDown_h32bit_24 = Properties.Resources._001_ShutDown_h32bit_24; public static Image _001_Tools_h32bit_16 = Properties.Resources._001_Tools_h32bit_16; public static Image _001_WindowView_h32bit_16 = Properties.Resources._001_WindowView_h32bit_16; public static Image _002_Configure_h32bit_16 = Properties.Resources._002_Configure_h32bit_16; public static Image _015_Download_h32bit_32 = Properties.Resources._015_Download_h32bit_32; public static Image _075_TickRound_h32bit_16 = Properties.Resources._075_TickRound_h32bit_16; public static Image _075_WarningRound_h32bit_16 = Properties.Resources._075_WarningRound_h32bit_16; public static Image _112_LeftArrowLong_Blue_24x24_72 = Properties.Resources._112_LeftArrowLong_Blue_24x24_72; public static Image _112_RightArrowLong_Blue_24x24_72 = Properties.Resources._112_RightArrowLong_Blue_24x24_72; public static Image about_box_graphic_423x79 = Properties.Resources.about_box_graphic_423x79; public static Image ajax_loader = Properties.Resources.ajax_loader; public static Image alert1_16 = Properties.Resources.alert1_16; public static Image alert2_16 = Properties.Resources.alert2_16; public static Image alert3_16 = Properties.Resources.alert3_16; public static Image alert4_16 = Properties.Resources.alert4_16; public static Image alert5_16 = Properties.Resources.alert5_16; public static Image alert6_16 = Properties.Resources.alert6_16; public static Image alerts_32 = Properties.Resources.alerts_32; public static Image ascending_triangle = Properties.Resources.ascending_triangle; public static Image asterisk = Properties.Resources.asterisk; public static Image attach_24 = Properties.Resources.attach_24; public static Image attach_virtualstorage_32 = Properties.Resources.attach_virtualstorage_32; public static Image backup_restore_32 = Properties.Resources.backup_restore_32; public static Image cancelled_action_16 = Properties.Resources.cancelled_action_16; public static Image centos_16x = Properties.Resources.centos_16x; public static Image change_password_16 = Properties.Resources.change_password_16; public static Image change_password_32 = Properties.Resources.change_password_32; public static Image clonevm_16 = Properties.Resources.clonevm_16; public static Image close_16 = Properties.Resources.close_16; public static Image commands_16 = Properties.Resources.commands_16; public static Image console_16 = Properties.Resources.console_16; public static Image contracted_triangle = Properties.Resources.contracted_triangle; public static Image copy_16 = Properties.Resources.copy_16; public static Image coreos_16 = Properties.Resources.coreos_16; public static Image coreos_globe_icon = Properties.Resources.coreos_globe_icon; public static Image cross = Properties.Resources.cross; public static Image DateTime16 = Properties.Resources.DateTime16; public static Image DC_16 = Properties.Resources.DC_16; public static Image debian_16x = Properties.Resources.debian_16x; public static Image descending_triangle = Properties.Resources.descending_triangle; public static Image desktop = Properties.Resources.desktop; public static Image detach_24 = Properties.Resources.detach_24; public static Image edit_16 = Properties.Resources.edit_16; public static Image expanded_triangle = Properties.Resources.expanded_triangle; public static Image export_32 = Properties.Resources.export_32; public static Image folder_grey = Properties.Resources.folder_grey; public static Image folder_separator = Properties.Resources.folder_separator; public static Image grab = Properties.Resources.grab; public static Image grapharea = Properties.Resources.grapharea; public static Image graphline = Properties.Resources.graphline; public static Image gripper = Properties.Resources.gripper; public static Image ha_16 = Properties.Resources.ha_16; public static Image help_16_hover = Properties.Resources.help_16_hover; public static Image help_24 = Properties.Resources.help_24; public static Image help_24_hover = Properties.Resources.help_24_hover; public static Image help_32_hover = Properties.Resources.help_32_hover; public static Image homepage_bullet = Properties.Resources.homepage_bullet; public static Image import_32 = Properties.Resources.import_32; public static Image infra_view_16 = Properties.Resources.infra_view_16; public static Image infra_view_16_textured = Properties.Resources.infra_view_16_textured; public static Image infra_view_24 = Properties.Resources.infra_view_24; public static Image licensekey_32 = Properties.Resources.licensekey_32; public static Image lifecycle_hot = Properties.Resources.lifecycle_hot; public static Image lifecycle_pressed = Properties.Resources.lifecycle_pressed; public static Image log_destination_16 = Properties.Resources.log_destination_16; public static Image Logo = Properties.Resources.Logo; public static Image memory_dynmax_slider = Properties.Resources.memory_dynmax_slider; public static Image memory_dynmax_slider_dark = Properties.Resources.memory_dynmax_slider_dark; public static Image memory_dynmax_slider_light = Properties.Resources.memory_dynmax_slider_light; public static Image memory_dynmax_slider_noedit = Properties.Resources.memory_dynmax_slider_noedit; public static Image memory_dynmax_slider_noedit_small = Properties.Resources.memory_dynmax_slider_noedit_small; public static Image memory_dynmax_slider_small = Properties.Resources.memory_dynmax_slider_small; public static Image memory_dynmin_slider = Properties.Resources.memory_dynmin_slider; public static Image memory_dynmin_slider_dark = Properties.Resources.memory_dynmin_slider_dark; public static Image memory_dynmin_slider_light = Properties.Resources.memory_dynmin_slider_light; public static Image memory_dynmin_slider_noedit = Properties.Resources.memory_dynmin_slider_noedit; public static Image memory_dynmin_slider_noedit_small = Properties.Resources.memory_dynmin_slider_noedit_small; public static Image memory_dynmin_slider_small = Properties.Resources.memory_dynmin_slider_small; public static Image minus = Properties.Resources.minus; public static Image more_16 = Properties.Resources.more_16; public static Image neokylin_16x = Properties.Resources.neokylin_16x; public static Image notif_alerts_16 = Properties.Resources.notif_alerts_16; public static Image notif_events_16 = Properties.Resources.notif_events_16; public static Image notif_events_errors_16 = Properties.Resources.notif_events_errors_16; public static Image notif_none_16 = Properties.Resources.notif_none_16; public static Image notif_none_24 = Properties.Resources.notif_none_24; public static Image notif_updates_16 = Properties.Resources.notif_updates_16; public static Image objects_16 = Properties.Resources.objects_16; public static Image objects_16_textured = Properties.Resources.objects_16_textured; public static Image objects_24 = Properties.Resources.objects_24; public static Image oracle_16x = Properties.Resources.oracle_16x; public static Image org_view_16 = Properties.Resources.org_view_16; public static Image org_view_24 = Properties.Resources.org_view_24; public static Image padlock = Properties.Resources.padlock; public static Image paste_16 = Properties.Resources.paste_16; public static Image PausedDC_16 = Properties.Resources.PausedDC_16; public static Image PDChevronDown = Properties.Resources.PDChevronDown; public static Image PDChevronDownOver = Properties.Resources.PDChevronDownOver; public static Image PDChevronLeft = Properties.Resources.PDChevronLeft; public static Image PDChevronRight = Properties.Resources.PDChevronRight; public static Image PDChevronUp = Properties.Resources.PDChevronUp; public static Image PDChevronUpOver = Properties.Resources.PDChevronUpOver; public static Image pool_up_16 = Properties.Resources.pool_up_16; public static Image redhat_16x = Properties.Resources.redhat_16x; public static Image Refresh16 = Properties.Resources.Refresh16; public static Image RunningDC_16 = Properties.Resources.RunningDC_16; public static Image saved_searches_16 = Properties.Resources.saved_searches_16; public static Image saved_searches_24 = Properties.Resources.saved_searches_24; public static Image scilinux_16x = Properties.Resources.scilinux_16x; public static Image server_up_16 = Properties.Resources.server_up_16; public static Image sl_16 = Properties.Resources.sl_16; public static Image sl_add_storage_system_16 = Properties.Resources.sl_add_storage_system_16; public static Image sl_add_storage_system_32 = Properties.Resources.sl_add_storage_system_32; public static Image sl_add_storage_system_small_16 = Properties.Resources.sl_add_storage_system_small_16; public static Image sl_connected_16 = Properties.Resources.sl_connected_16; public static Image sl_connecting_16 = Properties.Resources.sl_connecting_16; public static Image sl_disconnected_16 = Properties.Resources.sl_disconnected_16; public static Image sl_lun_16 = Properties.Resources.sl_lun_16; public static Image sl_luns_16 = Properties.Resources.sl_luns_16; public static Image sl_pool_16 = Properties.Resources.sl_pool_16; public static Image sl_pools_16 = Properties.Resources.sl_pools_16; public static Image sl_system_16 = Properties.Resources.sl_system_16; public static Image SpinningFrame0 = Properties.Resources.SpinningFrame0; public static Image SpinningFrame1 = Properties.Resources.SpinningFrame1; public static Image SpinningFrame2 = Properties.Resources.SpinningFrame2; public static Image SpinningFrame3 = Properties.Resources.SpinningFrame3; public static Image SpinningFrame4 = Properties.Resources.SpinningFrame4; public static Image SpinningFrame5 = Properties.Resources.SpinningFrame5; public static Image SpinningFrame6 = Properties.Resources.SpinningFrame6; public static Image SpinningFrame7 = Properties.Resources.SpinningFrame7; public static Image StoppedDC_16 = Properties.Resources.StoppedDC_16; public static Image subscribe = Properties.Resources.subscribe; public static Image suse_16x = Properties.Resources.suse_16x; public static Image tools_notinstalled_16x = Properties.Resources.tools_notinstalled_16x; public static Image tools_outofdate_16x = Properties.Resources.tools_outofdate_16x; public static Image tools_uptodate_16x = Properties.Resources.tools_uptodate_16x; public static Image tree_minus = Properties.Resources.tree_minus; public static Image tree_plus = Properties.Resources.tree_plus; public static Image tshadowdown = Properties.Resources.tshadowdown; public static Image tshadowdownleft = Properties.Resources.tshadowdownleft; public static Image tshadowdownright = Properties.Resources.tshadowdownright; public static Image tshadowright = Properties.Resources.tshadowright; public static Image tshadowtopright = Properties.Resources.tshadowtopright; public static Image ubuntu_16x = Properties.Resources.ubuntu_16x; public static Image upsell_16 = Properties.Resources.upsell_16; public static Image usagebar_0 = Properties.Resources.usagebar_0; public static Image usagebar_1 = Properties.Resources.usagebar_1; public static Image usagebar_10 = Properties.Resources.usagebar_10; public static Image usagebar_2 = Properties.Resources.usagebar_2; public static Image usagebar_3 = Properties.Resources.usagebar_3; public static Image usagebar_4 = Properties.Resources.usagebar_4; public static Image usagebar_5 = Properties.Resources.usagebar_5; public static Image usagebar_6 = Properties.Resources.usagebar_6; public static Image usagebar_7 = Properties.Resources.usagebar_7; public static Image usagebar_8 = Properties.Resources.usagebar_8; public static Image usagebar_9 = Properties.Resources.usagebar_9; public static Image virtualstorage_snapshot_16 = Properties.Resources.virtualstorage_snapshot_16; public static Image vmBackground = Properties.Resources.vmBackground; public static Image vmBackgroundCurrent = Properties.Resources.vmBackgroundCurrent; public static Image VMTemplate_h32bit_32 = Properties.Resources.VMTemplate_h32bit_32; public static Image vnc_local_cursor = Properties.Resources.vnc_local_cursor; public static Image windows_h32bit_16 = Properties.Resources.windows_h32bit_16; public static Image wizard_background = Properties.Resources.wizard_background; public static Image WLB = Properties.Resources.WLB; public static Image XS = Properties.Resources.XS; } } }
65.937716
191
0.705237
[ "BSD-2-Clause" ]
GaborApatiNagy/xenadmin
XenAdmin/Images.cs
57,170
C#
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\d3dumddi.h(2625,13) using System; using System.Runtime.InteropServices; namespace DirectN { [StructLayout(LayoutKind.Sequential)] public partial struct _DDICERTIFICATEINFO { public _D3DDDI_CERTIFICATETYPE CertificateType; public _DDIAUTHENTICATEDCHANNELTYPE ChannelType; public Guid CryptoSessionType; } }
27.6
86
0.743961
[ "MIT" ]
bbday/DirectN
DirectN/DirectN/Generated/_DDICERTIFICATEINFO.cs
416
C#
namespace Panoukos41.Helpers.Services { /// <summary> /// A service that helps you change themes that implements <see cref="IThemeService"/>. /// </summary> public partial class ThemeService : IThemeService { private static IThemeService @default; /// <summary> /// It will return a single instance of <see cref="ThemeService"/>, /// you can also set your own implemented <see cref="IThemeService"/> class. /// This method can hold only one instance at a time. /// </summary> public static IThemeService Default { get => @default ??= new ThemeService(); set => @default = value; } /// <summary> /// Get the current theme. /// </summary> /// <returns></returns> public virtual AppTheme GetCurrentTheme() => PlatformGetCurrentTheme(); /// <summary> /// Set the provided theme. /// </summary> /// <param name="theme">The theme to set.</param> public virtual void SetTheme(AppTheme theme) => PlatformSetTheme(theme); } }
32.685714
91
0.566434
[ "MIT" ]
panoukos41/Helpers
src/Helpers/Abstractions/Services/ThemeService/ThemeService.cs
1,146
C#
/* Copyright (C) 2016 Alexey Lavrenchenko (http://prosecuritiestrading.com/) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using ProSecuritiesTrading.MOEX.FIX.Base.Group; namespace ProSecuritiesTrading.MOEX.FIX.Base.Message.ASTS { public class OrderCancelRejectData { public byte[] MessageBytes; public HeaderData Header; public string OrderID = null; public byte[] OrderIDBytes = null; public string ClOrdID = null; public byte[] ClOrdIDBytes = null; public string OrigClOrdID = null; public byte[] OrigClOrdIDBytes = null; /// <summary> /// Null: 0. /// </summary> public byte OrdStatus = 0; /// <summary> /// Null: 0. /// </summary> public byte CxlRejResponseTo = 0; /// <summary> /// Null: -1. /// </summary> public int CxlRejReason = -1; public string Text = null; /// <summary> /// Null: DateTime.MinValue. /// </summary> public DateTime TransactTime = DateTime.MinValue; /// <summary> /// Null: -1. /// </summary> public int OrigTime = -1; // <Trailer> public int CheckSum = -1; // </Trailer> public OrderCancelRejectData(byte[] buffer, HeaderData header) { this.MessageBytes = buffer; this.Header = header; } } }
29.402985
76
0.604569
[ "Apache-2.0" ]
AlexeyLA0509/PSTTrader
src/ProSecuritiesTrading.MOEX.FIX/Base/Message/ASTS/OrderCancelRejectData.cs
1,972
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ClipboardMonitoringSED.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
35.866667
151
0.586431
[ "Unlicense" ]
SED4906/clipboardmonitoring
Properties/Settings.Designer.cs
1,078
C#
namespace CustomCode.Core.Composition.SourceGenerator.Extensions { using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using System; /// <summary> /// Extension methods for the <see cref="AttributeSyntax"/> type. /// </summary> public static class AttributeSyntaxExtensions { #region Logic /// <summary> /// Parse the "lifetime" parameter of the given <paramref name="exportAttribute"/>. /// </summary> /// <param name="exportAttribute"> The attribute whose "lifetime" parameter should be parsed. </param> /// <returns> The value of the given <paramref name="exportAttribute"/>'s "lifetime" parameter. </returns> public static string? ParseLifetime(this AttributeSyntax exportAttribute) { var lifetimeValue = string.Empty; if (exportAttribute.ArgumentList != null) { var arguments = exportAttribute.ArgumentList.Arguments; foreach (var argument in arguments) { var name = argument.NameEquals?.Name.Identifier.ValueText ?? string.Empty; var value = argument.Expression?.NormalizeWhitespace().ToFullString() ?? string.Empty; if ("lifetime".Equals(name, StringComparison.OrdinalIgnoreCase) || (!"serviceName".Equals(name, StringComparison.OrdinalIgnoreCase) && value.StartsWith("Lifetime.", StringComparison.OrdinalIgnoreCase))) { lifetimeValue = value; break; } } } if (lifetimeValue.EndsWith("Lifetime.Singleton", StringComparison.OrdinalIgnoreCase)) { return "PerContainerLifetime"; } if (lifetimeValue.EndsWith("Lifetime.Scoped", StringComparison.OrdinalIgnoreCase)) { return "PerScopeLifetime"; } return null; } /// <summary> /// Parse the optional "ServiceName" parameter of the given <paramref name="exportAttribute"/>. /// </summary> /// <param name="exportAttribute"> The attribute whose "ServiceName" parameter should be parsed. </param> /// <returns> The value of the given <paramref name="exportAttribute"/>'s "ServiceName" parameter. </returns> public static string? ParseServiceName(this AttributeSyntax exportAttribute) { if (exportAttribute.ArgumentList != null) { var arguments = exportAttribute.ArgumentList.Arguments; foreach (var argument in arguments) { var name = argument.NameEquals?.Name.Identifier.ValueText ?? string.Empty; var value = argument.Expression?.NormalizeWhitespace().ToFullString() ?? string.Empty; if ("serviceName".Equals(name, StringComparison.OrdinalIgnoreCase)) { return value; } } } return null; } /// <summary> /// Parse the "serviceType" parameter of the given <paramref name="exportAttribute"/>. /// </summary> /// <param name="exportAttribute"> The attribute whose "serviceType" parameter should be parsed. </param> /// <returns> The value of the given <paramref name="exportAttribute"/>'s "serviceType" parameter. </returns> public static string? ParseServiceType(this AttributeSyntax exportAttribute) { var serviceTypeValue = (string?)null; if (exportAttribute.ArgumentList != null) { var arguments = exportAttribute.ArgumentList.Arguments; foreach (var argument in arguments) { var name = argument.NameEquals?.Name.Identifier.ValueText ?? string.Empty; var value = argument.Expression?.NormalizeWhitespace().ToFullString() ?? string.Empty; if ("serviceType".Equals(name, StringComparison.OrdinalIgnoreCase) || (!"serviceName".Equals(name, StringComparison.OrdinalIgnoreCase) && value.StartsWith("typeof(", StringComparison.OrdinalIgnoreCase))) { serviceTypeValue = value; break; } } } if (serviceTypeValue != null && serviceTypeValue.EndsWith(")", StringComparison.OrdinalIgnoreCase)) { return serviceTypeValue .Substring("typeof(".Length, serviceTypeValue.Length - "typeof(".Length - ")".Length) .Trim(); } return null; } #endregion } }
43.289474
117
0.561702
[ "MIT" ]
git-custom-code/Core-Composition
src/Core.Composition.SourceGenerator/Extensions/AttributeSyntaxExtensions.cs
4,935
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using Android.Content; using Android.OS; using Android.Views; using Android.Views.Animations; using Microsoft.Maui.Controls.Compatibility.Platform.Android.AppCompat; using Microsoft.Maui.Controls.Internals; using Microsoft.Maui.Controls.Platform; using Microsoft.Maui.Graphics; using AView = Android.Views.View; namespace Microsoft.Maui.Controls.Compatibility.Platform.Android { public class Platform : BindableObject, IPlatformLayout, INavigation { readonly Context _context; readonly PlatformRenderer _renderer; bool _disposed; bool _navAnimationInProgress; NavigationModel _navModel = new NavigationModel(); NavigationModel _previousNavModel = null; readonly bool _embedded; internal static string PackageName { get; private set; } internal static string GetPackageName() => PackageName; internal const string CloseContextActionsSignalName = "Xamarin.CloseContextActions"; internal static readonly BindableProperty RendererProperty = BindableProperty.CreateAttached("Renderer", typeof(IVisualElementRenderer), typeof(Platform), default(IVisualElementRenderer), propertyChanged: (bindable, oldvalue, newvalue) => { var view = bindable as VisualElement; if (view != null) view.IsPlatformEnabled = newvalue != null; if (bindable is IView mauiView) { if (mauiView.Handler == null && newvalue is IVisualElementRenderer ver) mauiView.Handler = new RendererToHandlerShim(ver); else if (mauiView.Handler != null && newvalue == null) mauiView.Handler = null; } }); internal Platform(Context context) : this(context, false) { } internal Platform(Context context, bool embedded) { _embedded = embedded; _context = context; PackageName = context?.PackageName; _renderer = new PlatformRenderer(context, this); var activity = _context.GetActivity(); if (embedded && activity != null) { // Set up handling of DisplayAlert/DisplayActionSheet/UpdateProgressBarVisibility if (_context == null) { // Can't show dialogs if it's not an activity return; } PopupManager.Subscribe(_context.GetActivity()); return; } FormsAppCompatActivity.BackPressed += HandleBackPressed; } internal bool NavAnimationInProgress { get { return _navAnimationInProgress; } set { if (_navAnimationInProgress == value) return; _navAnimationInProgress = value; if (value) MessagingCenter.Send(this, CloseContextActionsSignalName); } } Page Page { get; set; } IPageController CurrentPageController => _navModel.CurrentPage; internal void Dispose() { if (_disposed) return; _disposed = true; FormsAppCompatActivity.BackPressed -= HandleBackPressed; SetPage(null); var activity = _context?.GetActivity(); if (_embedded && activity != null) { PopupManager.Unsubscribe(activity); } } void INavigation.InsertPageBefore(Page page, Page before) { throw new InvalidOperationException("InsertPageBefore is not supported globally on Android, please use a NavigationPage."); } IReadOnlyList<Page> INavigation.ModalStack => _navModel.Modals.ToList(); IReadOnlyList<Page> INavigation.NavigationStack => new List<Page>(); Task<Page> INavigation.PopAsync() { return ((INavigation)this).PopAsync(true); } Task<Page> INavigation.PopAsync(bool animated) { throw new InvalidOperationException("PopAsync is not supported globally on Android, please use a NavigationPage."); } Task<Page> INavigation.PopModalAsync() { return ((INavigation)this).PopModalAsync(true); } Task<Page> INavigation.PopModalAsync(bool animated) { Page modal = _navModel.PopModal(); ((IPageController)modal).SendDisappearing(); var source = new TaskCompletionSource<Page>(); IVisualElementRenderer modalRenderer = GetRenderer(modal); if (modalRenderer != null) { var modalContainer = modalRenderer.View.Parent as ModalContainer; if (animated) { modalContainer.Animate().TranslationY(_renderer.Height).SetInterpolator(new AccelerateInterpolator(1)).SetDuration(300).SetListener(new GenericAnimatorListener { OnEnd = a => { modalContainer.RemoveFromParent(); modalContainer.Dispose(); source.TrySetResult(modal); CurrentPageController?.SendAppearing(); modalContainer = null; } }); } else { modalContainer.RemoveFromParent(); modalContainer.Dispose(); source.TrySetResult(modal); CurrentPageController?.SendAppearing(); } } UpdateAccessibilityImportance(CurrentPageController as Page, ImportantForAccessibility.Auto, true); return source.Task; } Task INavigation.PopToRootAsync() { return ((INavigation)this).PopToRootAsync(true); } Task INavigation.PopToRootAsync(bool animated) { throw new InvalidOperationException("PopToRootAsync is not supported globally on Android, please use a NavigationPage."); } Task INavigation.PushAsync(Page root) { return ((INavigation)this).PushAsync(root, true); } Task INavigation.PushAsync(Page root, bool animated) { throw new InvalidOperationException("PushAsync is not supported globally on Android, please use a NavigationPage."); } Task INavigation.PushModalAsync(Page modal) { return ((INavigation)this).PushModalAsync(modal, true); } async Task INavigation.PushModalAsync(Page modal, bool animated) { CurrentPageController?.SendDisappearing(); UpdateAccessibilityImportance(CurrentPageController as Page, ImportantForAccessibility.NoHideDescendants, false); _navModel.PushModal(modal); Task presentModal = PresentModal(modal, animated); await presentModal; UpdateAccessibilityImportance(modal, ImportantForAccessibility.Auto, true); // Verify that the modal is still on the stack if (_navModel.CurrentPage == modal) ((IPageController)modal).SendAppearing(); } void INavigation.RemovePage(Page page) { throw new InvalidOperationException("RemovePage is not supported globally on Android, please use a NavigationPage."); } public static SizeRequest GetNativeSize( IVisualElementRenderer visualElementRenderer, double widthConstraint, double heightConstraint) { var context = visualElementRenderer.View.Context; // negative numbers have special meanings to android they don't to us widthConstraint = widthConstraint <= -1 ? double.PositiveInfinity : context.ToPixels(widthConstraint); heightConstraint = heightConstraint <= -1 ? double.PositiveInfinity : context.ToPixels(heightConstraint); bool widthConstrained = !double.IsPositiveInfinity(widthConstraint); bool heightConstrained = !double.IsPositiveInfinity(heightConstraint); int widthMeasureSpec = widthConstrained ? MeasureSpecFactory.MakeMeasureSpec((int)widthConstraint, MeasureSpecMode.AtMost) : MeasureSpecFactory.MakeMeasureSpec(0, MeasureSpecMode.Unspecified); int heightMeasureSpec = heightConstrained ? MeasureSpecFactory.MakeMeasureSpec((int)heightConstraint, MeasureSpecMode.AtMost) : MeasureSpecFactory.MakeMeasureSpec(0, MeasureSpecMode.Unspecified); SizeRequest rawResult = visualElementRenderer.GetDesiredSize(widthMeasureSpec, heightMeasureSpec); if (rawResult.Minimum == Size.Zero) rawResult.Minimum = rawResult.Request; var result = new SizeRequest(new Size(context.FromPixels(rawResult.Request.Width), context.FromPixels(rawResult.Request.Height)), new Size(context.FromPixels(rawResult.Minimum.Width), context.FromPixels(rawResult.Minimum.Height))); if ((widthConstrained && result.Request.Width < widthConstraint) || (heightConstrained && result.Request.Height < heightConstraint)) { // Do a final exact measurement in case the native control needs to fill the container (visualElementRenderer as IViewRenderer)?.MeasureExactly(); } return result; } internal static SizeRequest GetNativeSize(VisualElement view, double widthConstraint, double heightConstraint) { Performance.Start(out string reference); IVisualElementRenderer visualElementRenderer = GetRenderer(view); SizeRequest returnValue; if (visualElementRenderer != null && !visualElementRenderer.View.IsAlive()) { returnValue = new SizeRequest(Size.Zero, Size.Zero); } else if ((visualElementRenderer == null || visualElementRenderer is HandlerToRendererShim) && view is IView iView) { returnValue = iView.Handler.GetDesiredSize(widthConstraint, heightConstraint); } else if (visualElementRenderer != null) { returnValue = GetNativeSize(visualElementRenderer, widthConstraint, heightConstraint); } else { returnValue = new SizeRequest(Size.Zero, Size.Zero); } Performance.Stop(reference); return returnValue; } public static void ClearRenderer(AView renderedView) { var element = (renderedView as IVisualElementRenderer)?.Element; var view = element as View; if (view != null) { var renderer = GetRenderer(view); if (renderer == renderedView) element.ClearValue(RendererProperty); renderer?.Dispose(); renderer = null; } var layout = view as IVisualElementRenderer; layout?.Dispose(); layout = null; } internal static IVisualElementRenderer CreateRenderer(VisualElement element, Context context) { IVisualElementRenderer renderer = null; // temporary hack to fix the following issues // https://github.com/xamarin/Microsoft.Maui.Controls.Compatibility/issues/13261 // https://github.com/xamarin/Microsoft.Maui.Controls.Compatibility/issues/12484 if (element is RadioButton tv && tv.ResolveControlTemplate() != null) { renderer = new DefaultRenderer(context); } // This code is duplicated across all platforms currently // So if any changes are made here please make sure to apply them to other platform.cs files if (renderer == null) { IViewHandler handler = null; //TODO: Handle this with AppBuilderHost try { handler = Forms.MauiContext.Handlers.GetHandler(element.GetType()) as IViewHandler; handler.SetMauiContext(Forms.MauiContext); } catch { // TODO define better catch response or define if this is needed? } if (handler == null) { renderer = Registrar.Registered.GetHandlerForObject<IVisualElementRenderer>(element, context) ?? new DefaultRenderer(context); } // This means the only thing registered is the RendererToHandlerShim // Which is only used when you are running a .NET MAUI app // This indicates that the user hasn't registered a specific handler for this given type else if (handler is RendererToHandlerShim shim) { renderer = shim.VisualElementRenderer; if (renderer == null) { renderer = Registrar.Registered.GetHandlerForObject<IVisualElementRenderer>(element, context) ?? new DefaultRenderer(context); } } else if (handler is IVisualElementRenderer ver) renderer = ver; else if (handler is INativeViewHandler vh) { renderer = new HandlerToRendererShim(vh); element.Handler = handler; SetRenderer(element, renderer); } } renderer.SetElement(element); return renderer; } internal static IVisualElementRenderer CreateRenderer(VisualElement element, AndroidX.Fragment.App.FragmentManager fragmentManager, Context context) { IVisualElementRenderer renderer = CreateRenderer(element, context); var managesFragments = renderer as IManageFragments; managesFragments?.SetFragmentManager(fragmentManager); renderer.SetElement(element); return renderer; } public static IVisualElementRenderer CreateRendererWithContext(VisualElement element, Context context) { // This is an interim method to allow public access to CreateRenderer(element, context), which we // can't make public yet because it will break the previewer return CreateRenderer(element, context); } public static IVisualElementRenderer GetRenderer(VisualElement bindable) { return (IVisualElementRenderer)bindable?.GetValue(RendererProperty); } public static void SetRenderer(VisualElement bindable, IVisualElementRenderer value) { bindable.SetValue(RendererProperty, value); } internal ViewGroup GetViewGroup() { return _renderer; } void IPlatformLayout.OnLayout(bool changed, int l, int t, int r, int b) { if (Page == null) return; if (changed) { LayoutRootPage(Page, r - l, b - t); } GetRenderer(Page)?.UpdateLayout(); for (var i = 0; i < _renderer.ChildCount; i++) { AView child = _renderer.GetChildAt(i); if (child is ModalContainer) { child.Measure(MeasureSpecFactory.MakeMeasureSpec(r - l, MeasureSpecMode.Exactly), MeasureSpecFactory.MakeMeasureSpec(t - b, MeasureSpecMode.Exactly)); child.Layout(l, t, r, b); } } } protected override void OnBindingContextChanged() { SetInheritedBindingContext(Page, BindingContext); base.OnBindingContextChanged(); } internal void SettingNewPage() { if (Page != null) { _previousNavModel = _navModel; _navModel = new NavigationModel(); } } internal void SetPage(Page newRoot) { if (Page == newRoot) { return; } if (Page != null) { var navModel = (_previousNavModel ?? _navModel); foreach (var rootPage in navModel.Roots) { if (GetRenderer(rootPage) is ILifeCycleState nr) nr.MarkedForDispose = true; } var viewsToRemove = new List<AView>(); var renderersToDispose = new List<IVisualElementRenderer>(); for (int i = 0; i < _renderer.ChildCount; i++) viewsToRemove.Add(_renderer.GetChildAt(i)); foreach (var root in navModel.Roots) renderersToDispose.Add(GetRenderer(root)); SetPageInternal(newRoot); Cleanup(viewsToRemove, renderersToDispose); } else { SetPageInternal(newRoot); } } void UpdateAccessibilityImportance(Page page, ImportantForAccessibility importantForAccessibility, bool forceFocus) { var pageRenderer = GetRenderer(page); if (pageRenderer?.View == null) return; pageRenderer.View.ImportantForAccessibility = importantForAccessibility; if (forceFocus) pageRenderer.View.SendAccessibilityEvent(global::Android.Views.Accessibility.EventTypes.ViewFocused); } void SetPageInternal(Page newRoot) { var layout = false; if (Page != null) { // if _previousNavModel has been set than _navModel has already been reinitialized if (_previousNavModel != null) { _previousNavModel = null; if (_navModel == null) _navModel = new NavigationModel(); } else _navModel = new NavigationModel(); layout = true; } if (newRoot == null) { Page = null; return; } _navModel.Push(newRoot, null); Page = newRoot; AddChild(Page, layout); Application.Current.NavigationProxy.Inner = this; } void Cleanup(List<AView> viewsToRemove, List<IVisualElementRenderer> renderersToDispose) { // If trigger by dispose, cleanup now, otherwise queue it for later if (_disposed) { DoCleanup(); } else { new Handler(Looper.MainLooper).Post(DoCleanup); } void DoCleanup() { for (int i = 0; i < viewsToRemove.Count; i++) { AView view = viewsToRemove[i]; _renderer?.RemoveView(view); } for (int i = 0; i < renderersToDispose.Count; i++) { IVisualElementRenderer rootRenderer = renderersToDispose[i]; rootRenderer?.Element.ClearValue(RendererProperty); rootRenderer?.Dispose(); } } } void AddChild(Page page, bool layout = false) { if (page == null) return; if (GetRenderer(page) != null) return; IVisualElementRenderer renderView = CreateRenderer(page, _context); SetRenderer(page, renderView); if (layout) LayoutRootPage(page, _renderer.Width, _renderer.Height); _renderer.AddView(renderView.View); } bool HandleBackPressed(object sender, EventArgs e) { if (NavAnimationInProgress) return true; Page root = _navModel.Roots.LastOrDefault(); bool handled = root?.SendBackButtonPressed() ?? false; return handled; } void LayoutRootPage(Page page, int width, int height) { page.Layout(new Rectangle(0, 0, _context.FromPixels(width), _context.FromPixels(height))); } Task PresentModal(Page modal, bool animated) { var modalContainer = new ModalContainer(_context, modal); _renderer.AddView(modalContainer); var source = new TaskCompletionSource<bool>(); NavAnimationInProgress = true; if (animated) { modalContainer.TranslationY = _renderer.Height; modalContainer.Animate().TranslationY(0).SetInterpolator(new DecelerateInterpolator(1)).SetDuration(300).SetListener(new GenericAnimatorListener { OnEnd = a => { source.TrySetResult(false); modalContainer = null; }, OnCancel = a => { source.TrySetResult(true); modalContainer = null; } }); } else { source.TrySetResult(true); } return source.Task.ContinueWith(task => NavAnimationInProgress = false); } sealed class ModalContainer : ViewGroup { AView _backgroundView; bool _disposed; Page _modal; IVisualElementRenderer _renderer; public ModalContainer(Context context, Page modal) : base(context) { _modal = modal; _backgroundView = new AView(context); UpdateBackgroundColor(); AddView(_backgroundView); _renderer = CreateRenderer(modal, context); SetRenderer(modal, _renderer); AddView(_renderer.View); Id = Platform.GenerateViewId(); _modal.PropertyChanged += OnModalPagePropertyChanged; } protected override void Dispose(bool disposing) { if (_disposed) return; if (disposing) { RemoveAllViews(); if (_renderer != null) { _renderer.Dispose(); _renderer = null; _modal.ClearValue(RendererProperty); _modal.PropertyChanged -= OnModalPagePropertyChanged; _modal = null; } if (_backgroundView != null) { _backgroundView.Dispose(); _backgroundView = null; } } _disposed = true; base.Dispose(disposing); } protected override void OnLayout(bool changed, int l, int t, int r, int b) { if (changed) { _modal.Layout(new Rectangle(0, 0, Context.FromPixels(r - l), Context.FromPixels(b - t))); _backgroundView.Layout(0, 0, r - l, b - t); } _renderer.UpdateLayout(); } void OnModalPagePropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == Page.BackgroundColorProperty.PropertyName) UpdateBackgroundColor(); } void UpdateBackgroundColor() { Color modalBkgndColor = _modal.BackgroundColor; if (modalBkgndColor == null) _backgroundView.SetWindowBackground(); else _backgroundView.SetBackgroundColor(modalBkgndColor.ToAndroid()); } } internal static int GenerateViewId() { // getting unique Id's is an art, and I consider myself the Jackson Pollock of the field if ((int)Forms.SdkInt >= 17) return global::Android.Views.View.GenerateViewId(); // Numbers higher than this range reserved for xml // If we roll over, it can be exceptionally problematic for the user if they are still retaining things, android's internal implementation is // basically identical to this except they do a lot of locking we don't have to because we know we only do this // from the UI thread if (s_id >= 0x00ffffff) s_id = 0x00000400; return s_id++; } static int s_id = 0x00000400; #region Statics public static implicit operator ViewGroup(Platform canvas) { return canvas._renderer; } #endregion internal class DefaultRenderer : VisualElementRenderer<View>, ILayoutChanges { public bool NotReallyHandled { get; private set; } IOnTouchListener _touchListener; bool _disposed; bool _hasLayoutOccurred; readonly MotionEventHelper _motionEventHelper = new MotionEventHelper(); public DefaultRenderer(Context context) : base(context) { ChildrenDrawingOrderEnabled = true; } internal void NotifyFakeHandling() { NotReallyHandled = true; } public override bool OnTouchEvent(MotionEvent e) { if (base.OnTouchEvent(e)) return true; return _motionEventHelper.HandleMotionEvent(Parent, e); } protected override void OnElementChanged(ElementChangedEventArgs<View> e) { base.OnElementChanged(e); _motionEventHelper.UpdateElement(e.NewElement); } public override bool DispatchTouchEvent(MotionEvent e) { #region Excessive explanation // Normally dispatchTouchEvent feeds the touch events to its children one at a time, top child first, // (and only to the children in the hit-test area of the event) stopping as soon as one of them has handled // the event. // But to be consistent across the platforms, we don't want this behavior; if an element is not input transparent // we don't want an event to "pass through it" and be handled by an element "behind/under" it. We just want the processing // to end after the first non-transparent child, regardless of whether the event has been handled. // This is only an issue for a couple of controls; the interactive controls (switch, button, slider, etc) already "handle" their touches // and the events don't propagate to other child controls. But for image, label, and box that doesn't happen. We can't have those controls // lie about their events being handled because then the events won't propagate to *parent* controls (e.g., a frame with a label in it would // never get a tap gesture from the label). In other words, we *want* parent propagation, but *do not want* sibling propagation. So we need to short-circuit // base.DispatchTouchEvent here, but still return "false". // Duplicating the logic of ViewGroup.dispatchTouchEvent and modifying it slightly for our purposes is a non-starter; the method is too // complex and does a lot of micro-optimization. Instead, we provide a signalling mechanism for the controls which don't already "handle" touch // events to tell us that they will be lying about handling their event; they then return "true" to short-circuit base.DispatchTouchEvent. // The container gets this message and after it gets the "handled" result from dispatchTouchEvent, // it then knows to ignore that result and return false/unhandled. This allows the event to propagate up the tree. #endregion NotReallyHandled = false; var result = base.DispatchTouchEvent(e); if (result && NotReallyHandled) { // If the child control returned true from its touch event handler but signalled that it was a fake "true", then we // don't consider the event truly "handled" yet. // Since a child control short-circuited the normal dispatchTouchEvent stuff, this layout never got the chance for // IOnTouchListener.OnTouch and the OnTouchEvent override to try handling the touches; we'll do that now // Any associated Touch Listeners are called from DispatchTouchEvents if all children of this view return false // So here we are simulating both calls that would have typically been called from inside DispatchTouchEvent // but were not called due to the fake "true" result = _touchListener?.OnTouch(this, e) ?? false; return result || OnTouchEvent(e); } return result; } public override void SetOnTouchListener(IOnTouchListener l) { _touchListener = l; base.SetOnTouchListener(l); } protected override void Dispose(bool disposing) { if (_disposed) { return; } _disposed = true; if (disposing) SetOnTouchListener(null); base.Dispose(disposing); } bool ILayoutChanges.HasLayoutOccurred => _hasLayoutOccurred; protected override void OnLayout(bool changed, int left, int top, int right, int bottom) { base.OnLayout(changed, left, top, right, bottom); _hasLayoutOccurred = true; } } internal static string ResolveMsAppDataUri(Uri uri) { if (uri.Scheme == "ms-appdata") { string filePath = string.Empty; if (uri.LocalPath.StartsWith("/local")) { filePath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), uri.LocalPath.Substring(7)); } else if (uri.LocalPath.StartsWith("/temp")) { filePath = System.IO.Path.Combine(System.IO.Path.GetTempPath(), uri.LocalPath.Substring(6)); } else { throw new ArgumentException("Invalid Uri", "Source"); } return filePath; } else { throw new ArgumentException("uri"); } } } }
29.025492
189
0.712523
[ "MIT" ]
3DSX/maui
src/Compatibility/Core/src/Android/AppCompat/Platform.cs
25,049
C#
using System; using TMPro; using UnityEngine; public class ItemButton : MonoBehaviour { public void ButtonPressed() { if (FilteredInventoryWindowPopUp.Instance.FilteredInventoryWindow.activeSelf) { Guid.TryParse(transform.GetComponentsInChildren<TextMeshProUGUI>(true)[2].text, out var itemToEquipId); var player = GameManager.Instance.Player; var itemToEquip = player.Inventory[itemToEquipId]; player.EquipItem(itemToEquip, FilteredInventoryWindowPopUp.Instance.EquipmentSlotFilter); FilteredInventoryWindowPopUp.Instance.Hide(); } else { Guid.TryParse(transform.GetComponentsInChildren<TextMeshProUGUI>(true)[2].text, out var itemToEquipId); var player = GameManager.Instance.Player; var item = player.Inventory[itemToEquipId]; EventMediator.Instance.Broadcast(GlobalHelper.ItemSelectedEventName, this, item); } } }
30.151515
115
0.683417
[ "Apache-2.0" ]
SchwiftyPython/PizzalikeRL
Assets/Resources/Scripts/UI/ItemButton.cs
997
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Backend.Entities; namespace Backend.DTO { public class MessageDTO { public int Id { get; set; } public int SenderId { get; set; } public string SenderUsername { get; set; } public string SenderPhotoUrl { get; set; } public int ReceiverId { get; set; } public string ReceiverUsername { get; set; } public string ReceiverPhotoUrl { get; set; } public string Content { get; set; } public DateTime MessageSent { get; set; } public DateTime? DateRead { get; set; } } }
28.695652
52
0.637879
[ "Apache-2.0" ]
jamil-source/GamerFind
Backend/DTO/MessageDTO.cs
660
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Drawing; #pragma warning disable CS1591, CS1572, CS1573 namespace Iot.Device.PiJuiceDevice.Models { /// <summary> /// Led configuration /// </summary> /// <param name="Led">Led designator</param> /// <param name="LedFunction">Led function type</param> /// <param name="Color">Color for Led. /// If LedFunction is ChargeStatus /// Red - parameter defines color component level of red below 15% /// Green - parameter defines color component charge level over 50% /// Blue - parameter defines color component for charging(blink) and fully charged states(constant) /// Red Led and Green Led will show the charge status between 15% - 50% /// </param> public record LedConfig(Led Led, LedFunction LedFunction, Color Color); }
38.583333
103
0.697624
[ "MIT" ]
HumJ0218/iot
src/devices/PiJuice/Models/LEDConfig.cs
928
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Specialized; using System.Net; using System.Threading.Tasks; using IdentityServer4.Configuration; using IdentityServer4.Endpoints.Results; using IdentityServer4.Extensions; using IdentityServer4.Hosting; using IdentityServer4.Services; using IdentityServer4.Validation; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Microsoft.IdentityModel.Protocols.OpenIdConnect; namespace Microsoft.AspNetCore.ApiAuthorization.IdentityServer { internal class AutoRedirectEndSessionEndpoint : IEndpointHandler { private readonly ILogger _logger; private readonly IUserSession _session; private readonly IOptions<IdentityServerOptions> _identityServerOptions; private readonly IEndSessionRequestValidator _requestvalidator; public AutoRedirectEndSessionEndpoint( ILogger<AutoRedirectEndSessionEndpoint> logger, IEndSessionRequestValidator requestValidator, IOptions<IdentityServerOptions> identityServerOptions, IUserSession session ) { _logger = logger; _session = session; _identityServerOptions = identityServerOptions; _requestvalidator = requestValidator; } public async Task<IEndpointResult> ProcessAsync(HttpContext ctx) { var validtionResult = ValidateRequest(ctx.Request); if (validtionResult != null) { return validtionResult; } var parameters = await GetParametersAsync(ctx.Request); var user = await _session.GetUserAsync(); var result = await _requestvalidator.ValidateAsync(parameters, user); if (result.IsError) { _logger.LogError( LoggerEventIds.EndingSessionFailed, "Error ending session {Error}", result.Error ); return new RedirectResult(_identityServerOptions.Value.UserInteraction.ErrorUrl); } var client = result.ValidatedRequest?.Client; if ( client != null && client.Properties.TryGetValue( ApplicationProfilesPropertyNames.Profile, out var type ) ) { var signInScheme = _identityServerOptions.Value.Authentication.CookieAuthenticationScheme; if (signInScheme != null) { await ctx.SignOutAsync(signInScheme); } else { await ctx.SignOutAsync(); } var postLogOutUri = result.ValidatedRequest.PostLogOutUri; if (result.ValidatedRequest.State != null) { postLogOutUri = QueryHelpers.AddQueryString( postLogOutUri, OpenIdConnectParameterNames.State, result.ValidatedRequest.State ); } return new RedirectResult(postLogOutUri); } else { return new RedirectResult(_identityServerOptions.Value.UserInteraction.LogoutUrl); } } private async Task<NameValueCollection> GetParametersAsync(HttpRequest request) { if (HttpMethods.IsGet(request.Method)) { return request.Query.AsNameValueCollection(); } else { var form = await request.ReadFormAsync(); return form.AsNameValueCollection(); } } private IEndpointResult ValidateRequest(HttpRequest request) { if (!HttpMethods.IsPost(request.Method) && !HttpMethods.IsGet(request.Method)) { return new StatusCodeResult(HttpStatusCode.BadRequest); } if ( HttpMethods.IsPost(request.Method) && !string.Equals( request.ContentType, "application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase ) ) { return new StatusCodeResult(HttpStatusCode.BadRequest); } return null; } internal class RedirectResult : IEndpointResult { public RedirectResult(string url) { Url = url; } public string Url { get; } public Task ExecuteAsync(HttpContext context) { context.Response.Redirect(Url); return Task.CompletedTask; } } } }
33.733766
111
0.574783
[ "Apache-2.0" ]
belav/aspnetcore
src/Identity/ApiAuthorization.IdentityServer/src/Extensions/AutoRedirectEndSessionEndpoint.cs
5,195
C#
using System; namespace Nez.Tweens { public interface ITweenable { /// <summary> /// called by TweenManager each frame like an internal Update /// </summary> bool tick(); /// <summary> /// called by TweenManager when a tween is removed. Subclasses can optionally recycle themself. Subclasses /// should first check the _shouldRecycleTween bool in their implementation! /// </summary> void recycleSelf(); /// <summary> /// checks to see if a tween is running /// </summary> /// <returns><c>true</c>, if running was ised, <c>false</c> otherwise.</returns> bool isRunning(); /// <summary> /// starts the tween /// </summary> void start(); /// <summary> /// pauses the tween /// </summary> void pause(); /// <summary> /// resumes the tween after a pause /// </summary> void resume(); /// <summary> /// stops the tween optionally bringing it to completion /// </summary> /// <param name="bringToCompletion">If set to <c>true</c> bring to completion.</param> void stop( bool bringToCompletion = false ); } }
22
108
0.639147
[ "MIT" ]
AlmostBearded/monogame-platformer
Platformer/Nez/Nez.Portable/Utils/Tweens/Interfaces/ITweenable.cs
1,080
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace ApprovalTests.Reporters { public class DotNet4Utilities { public static string GetFirstWorking(string path, string[] paths) { var fullPath = path; foreach (var p in paths) { fullPath = p + Path.DirectorySeparatorChar + path; if (File.Exists(fullPath)) { break; } } return fullPath; } public static string GetPathInProgramFilesX86(string path) { var paths = GetProgramFilesPaths(); return GetFirstWorking(path, paths); } public static string[] GetProgramFilesPaths() { var paths = new HashSet<string> { Environment.GetEnvironmentVariable("ProgramFiles(x86)"), Environment.GetEnvironmentVariable("ProgramFiles"), Environment.GetEnvironmentVariable("ProgramW6432") }; return paths.Where(p => p != null).ToArray(); } } }
28.642857
74
0.523691
[ "Apache-2.0" ]
RasheR666/ApprovalTests.Net
ApprovalTests/Reporters/DotNet4Utilities.cs
1,162
C#
// Copyright (c) 2022 AccelByte Inc. All Rights Reserved. // This is licensed software from AccelByte Inc, for limitations // and restrictions contact your company contract manager. // This code is generated by tool. DO NOT EDIT. using System.Net; using System.IO; using System.Text.Json; using AccelByte.Sdk.Api.Platform.Model; using AccelByte.Sdk.Core; using AccelByte.Sdk.Core.Util; namespace AccelByte.Sdk.Api.Platform.Operation { /// <summary> /// getUserEntitlementHistories /// /// Get user entitlement histories. /// /// Other detail info: /// /// * Required permission : resource="ADMIN:NAMESPACE:{namespace}:USER:{userId}:ENTITLEMENT", action=2 (READ) /// * Returns : list of entitlement history /// </summary> public class GetUserEntitlementHistories : AccelByte.Sdk.Core.Operation { #region Builder Part public static GetUserEntitlementHistoriesBuilder Builder = new GetUserEntitlementHistoriesBuilder(); public class GetUserEntitlementHistoriesBuilder : OperationBuilder<GetUserEntitlementHistoriesBuilder> { internal GetUserEntitlementHistoriesBuilder() { } public GetUserEntitlementHistories Build( string entitlementId, string namespace_, string userId ) { GetUserEntitlementHistories op = new GetUserEntitlementHistories(this, entitlementId, namespace_, userId ); op.PreferredSecurityMethod = PreferredSecurityMethod; return op; } } private GetUserEntitlementHistories(GetUserEntitlementHistoriesBuilder builder, string entitlementId, string namespace_, string userId ) { PathParams["entitlementId"] = entitlementId; PathParams["namespace"] = namespace_; PathParams["userId"] = userId; Securities.Add(AccelByte.Sdk.Core.Operation.SECURITY_BEARER); } #endregion public GetUserEntitlementHistories( string entitlementId, string namespace_, string userId ) { PathParams["entitlementId"] = entitlementId; PathParams["namespace"] = namespace_; PathParams["userId"] = userId; Securities.Add(AccelByte.Sdk.Core.Operation.SECURITY_BEARER); } public override string Path => "/platform/admin/namespaces/{namespace}/users/{userId}/entitlements/{entitlementId}/history"; public override HttpMethod Method => HttpMethod.Get; public override string[] Consumes => new string[] { }; public override string[] Produces => new string[] { "application/json" }; [Obsolete("Use 'Securities' property instead.")] public override string? Security { get; set; } = "Bearer"; public List<Model.EntitlementHistoryInfo>? ParseResponse(HttpStatusCode code, string contentType, Stream payload) { if (code == (HttpStatusCode)204) { return null; } else if (code == (HttpStatusCode)201) { return JsonSerializer.Deserialize<List<Model.EntitlementHistoryInfo>>(payload); } else if (code == (HttpStatusCode)200) { return JsonSerializer.Deserialize<List<Model.EntitlementHistoryInfo>>(payload); } var payloadString = Helper.ConvertInputStreamToString(payload); throw new HttpResponseException(code, payloadString); } } }
31.061069
132
0.565249
[ "MIT" ]
AccelByte/accelbyte-csharp-sdk
AccelByte.Sdk/Api/Platform/Operation/Entitlement/GetUserEntitlementHistories.cs
4,069
C#
using Xunit; namespace AspNet.WebApi.Server.Tests { /// <inheritdoc /> public partial class ServerTests { [Fact] public void ApiInfo() { var apiInfo = new Startup(null).ApiInfo; Assert.Equal("AspNet.WebApi.Server.Tests", apiInfo.AssemblyName); Assert.Equal("API Service base library for API Services.", apiInfo.Description); Assert.Equal("1.5.0.0", apiInfo.Version.ToString()); Assert.Equal("AspNet.WebApi.Server.Tests.v1", apiInfo.ServiceName); Assert.Equal("1.5", apiInfo.ApiVersion); Assert.Equal("AspNet.WebApi.Server.Tests", apiInfo.DisplayName); } } }
31.5
92
0.61039
[ "MIT" ]
LeonidEfremov/AspNet.WebApi.Server
AspNet.WebApi.Server.Tests/StartupTests.cs
695
C#
 namespace dqxEnthuse { partial class FullWindow { /// <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.SuspendLayout(); // // FullWindow // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.Black; this.ClientSize = new System.Drawing.Size(800, 450); this.DoubleBuffered = true; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FullWindow"; this.ShowIcon = false; this.ShowInTaskbar = false; this.Text = "FullWindow"; this.TopMost = true; this.Load += new System.EventHandler(this.FullWindow_Load); this.Paint += new System.Windows.Forms.PaintEventHandler(this.FullWindow_Paint); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.FullWindow_KeyDown); this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.FullWindow_MouseDown); this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.FullWindow_MouseMove); this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.FullWindow_MouseUp); this.ResumeLayout(false); } #endregion } }
37.688525
107
0.592431
[ "Unlicense" ]
john-guo/dqxEnthuse
dqxEnthuse/FullWindow.Designer.cs
2,301
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace firstwebapp.Areas.Identity.Pages.Account { [AllowAnonymous] public class ResetPasswordModel : PageModel { private readonly UserManager<IdentityUser> _userManager; public ResetPasswordModel(UserManager<IdentityUser> userManager) { _userManager = userManager; } [BindProperty] public InputModel Input { get; set; } public class InputModel { [Required] [EmailAddress] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } public string Code { get; set; } } public IActionResult OnGet(string code = null) { if (code == null) { return BadRequest("A code must be supplied for password reset."); } else { Input = new InputModel { Code = code }; return Page(); } } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } var user = await _userManager.FindByEmailAsync(Input.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToPage("./ResetPasswordConfirmation"); } var result = await _userManager.ResetPasswordAsync(user, Input.Code, Input.Password); if (result.Succeeded) { return RedirectToPage("./ResetPasswordConfirmation"); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } return Page(); } } }
29.685393
129
0.554883
[ "MIT" ]
Zeroks77/webapp
src/firstwebapp/Areas/Identity/Pages/Account/ResetPassword.cshtml.cs
2,644
C#
namespace Lpp.Dns.Data.Migrations { using Lpp.Dns.DTO.Security; using Lpp.Utilities; using System; using System.Data.Entity.Migrations; public partial class AddRequestTypeSecurity : DbMigration { public override void Up() { Sql("DROP TRIGGER AclRequestTypes_InsertItem"); Sql("DROP TRIGGER AclRequestTypes_UpdateItem"); Sql("DROP TRIGGER AclRequestTypes_DeleteItem"); Sql(MigrationHelpers.AddAclInsertScript("AclRequestTypes")); Sql(MigrationHelpers.AddAclUpdateScript("AclRequestTypes")); Sql(MigrationHelpers.AddAclDeleteScript("AclRequestTypes")); Sql("INSERT INTO Permissions (ID, [Name], [Description]) VALUES ('" + PermissionIdentifiers.RequestTypes.Delete.ID.ToString("D") + "', 'Delete Request Type', 'Allows the selected security group to delete the selected Request Type.')"); Sql("INSERT INTO PermissionLocations (PermissionID, Type) VALUES ('" + PermissionIdentifiers.RequestTypes.Delete.ID.ToString("D") + "', 0)");//Global Sql("INSERT INTO PermissionLocations (PermissionID, Type) VALUES ('" + PermissionIdentifiers.RequestTypes.Delete.ID.ToString("D") + "', 23)");//Templates Sql("INSERT INTO Permissions (ID, [Name], [Description]) VALUES ('" + PermissionIdentifiers.RequestTypes.Edit.ID.ToString("D") + "', 'Edit Request Type', 'Allows the selected security group to edit the selected Request Type.')"); Sql("INSERT INTO PermissionLocations (PermissionID, Type) VALUES ('" + PermissionIdentifiers.RequestTypes.Edit.ID.ToString("D") + "', 0)");//Global Sql("INSERT INTO PermissionLocations (PermissionID, Type) VALUES ('" + PermissionIdentifiers.RequestTypes.Edit.ID.ToString("D") + "', 23)");//Templates Sql("INSERT INTO Permissions (ID, [Name], [Description]) VALUES ('" + PermissionIdentifiers.RequestTypes.ManageSecurity.ID.ToString("D") + "', 'Manage Request Type Security', 'Allows the selected security group to manage security of the selected Request Type.')"); Sql("INSERT INTO PermissionLocations (PermissionID, Type) VALUES ('" + PermissionIdentifiers.RequestTypes.ManageSecurity.ID.ToString("D") + "', 0)");//Global Sql("INSERT INTO PermissionLocations (PermissionID, Type) VALUES ('" + PermissionIdentifiers.RequestTypes.ManageSecurity.ID.ToString("D") + "', 23)");//Templates Sql("INSERT INTO Permissions (ID, [Name], [Description]) VALUES ('" + PermissionIdentifiers.RequestTypes.View.ID.ToString("D") + "', 'View Request Type', 'Allows the selected security group to view the selected Request Type.')"); Sql("INSERT INTO PermissionLocations (PermissionID, Type) VALUES ('" + PermissionIdentifiers.RequestTypes.View.ID.ToString("D") + "', 0)");//Global Sql("INSERT INTO PermissionLocations (PermissionID, Type) VALUES ('" + PermissionIdentifiers.RequestTypes.View.ID.ToString("D") + "', 23)");//Templates } public override void Down() { } } }
73.452381
276
0.681037
[ "Apache-2.0" ]
Missouri-BMI/popmednet
Lpp.Dns.Data/Migrations/201410021843337_AddRequestTypeSecurity.cs
3,085
C#
using System; using System.Globalization; using ClearHl7.Extensions; using ClearHl7.Helpers; namespace ClearHl7.V281.Segments { /// <summary> /// HL7 Version 2 Segment RFI - Request For Information. /// </summary> public class RfiSegment : ISegment { /// <summary> /// Gets the ID for the Segment. This property is read-only. /// </summary> public string Id { get; } = "RFI"; /// <summary> /// Gets or sets the rank, or ordinal, which describes the place that this Segment resides in an ordered list of Segments. /// </summary> public int Ordinal { get; set; } /// <summary> /// RFI.1 - Request Date. /// </summary> public DateTime? RequestDate { get; set; } /// <summary> /// RFI.2 - Response Due Date. /// </summary> public DateTime? ResponseDueDate { get; set; } /// <summary> /// RFI.3 - Patient Consent. /// <para>Suggested: 0136 Yes/No Indicator -&gt; ClearHl7.Codes.V281.CodeYesNoIndicator</para> /// </summary> public string PatientConsent { get; set; } /// <summary> /// RFI.4 - Date Additional Information Was Submitted. /// </summary> public DateTime? DateAdditionalInformationWasSubmitted { get; set; } /// <summary> /// Initializes properties of this instance with values parsed from the given delimited string. Separators defined in the Configuration class are used to split the string. /// </summary> /// <param name="delimitedString">A string representation that will be deserialized into the object instance.</param> /// <exception cref="ArgumentException">delimitedString does not begin with the proper segment Id.</exception> public void FromDelimitedString(string delimitedString) { FromDelimitedString(delimitedString, null); } /// <summary> /// Initializes properties of this instance with values parsed from the given delimited string. The provided separators are used to split the string. /// </summary> /// <param name="delimitedString">A string representation that will be deserialized into the object instance.</param> /// <param name="separators">The separators to use for splitting the string.</param> /// <exception cref="ArgumentException">delimitedString does not begin with the proper segment Id.</exception> public void FromDelimitedString(string delimitedString, Separators separators) { Separators seps = separators ?? new Separators().UsingConfigurationValues(); string[] segments = delimitedString == null ? Array.Empty<string>() : delimitedString.Split(seps.FieldSeparator, StringSplitOptions.None); if (segments.Length > 0) { if (string.Compare(Id, segments[0], true, CultureInfo.CurrentCulture) != 0) { throw new ArgumentException($"{ nameof(delimitedString) } does not begin with the proper segment Id: '{ Id }{ seps.FieldSeparator }'.", nameof(delimitedString)); } } RequestDate = segments.Length > 1 && segments[1].Length > 0 ? segments[1].ToNullableDateTime() : null; ResponseDueDate = segments.Length > 2 && segments[2].Length > 0 ? segments[2].ToNullableDateTime() : null; PatientConsent = segments.Length > 3 && segments[3].Length > 0 ? segments[3] : null; DateAdditionalInformationWasSubmitted = segments.Length > 4 && segments[4].Length > 0 ? segments[4].ToNullableDateTime() : null; } /// <summary> /// Returns a delimited string representation of this instance. /// </summary> /// <returns>A string.</returns> public string ToDelimitedString() { CultureInfo culture = CultureInfo.CurrentCulture; return string.Format( culture, StringHelper.StringFormatSequence(0, 5, Configuration.FieldSeparator), Id, RequestDate.HasValue ? RequestDate.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, ResponseDueDate.HasValue ? ResponseDueDate.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null, PatientConsent, DateAdditionalInformationWasSubmitted.HasValue ? DateAdditionalInformationWasSubmitted.Value.ToString(Consts.DateTimeFormatPrecisionSecond, culture) : null ).TrimEnd(Configuration.FieldSeparator.ToCharArray()); } } }
48.44
187
0.609827
[ "MIT" ]
davebronson/clear-hl7-net
src/ClearHl7/V281/Segments/RfiSegment.cs
4,846
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics.CodeAnalysis; using System.Management.Automation; using System.Management.Automation.Internal; using System.Management.Automation.Host; using System.Threading; using System.Diagnostics; namespace Microsoft.PowerShell.ScheduledJob { /// <summary> /// This cmdlet disables triggers on a ScheduledJobDefinition object. /// </summary> [Cmdlet(VerbsLifecycle.Enable, "JobTrigger", SupportsShouldProcess = true, DefaultParameterSetName = EnableJobTriggerCommand.EnabledParameterSet, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=223917")] public sealed class EnableJobTriggerCommand : EnableDisableScheduledJobCmdletBase { #region Enabled Implementation /// <summary> /// Property to determine if trigger should be enabled or disabled. /// </summary> internal override bool Enabled { get { return true; } } #endregion } }
31.75
149
0.72266
[ "MIT" ]
DCtheGeek/PowerShell
src/Microsoft.PowerShell.ScheduledJob/commands/EnableJobTrigger.cs
1,143
C#
// <copyright file="BingTests.cs" company="Automate The Planet Ltd."> // Copyright 2016 Automate The Planet Ltd. // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Anton Angelov</author> // <site>http://automatetheplanet.com/</site> using FailedTestsAnalysisDecorator.Pages; using HybridTestFramework.UITests.Core; using HybridTestFramework.UITests.Core.Behaviours; using HybridTestFramework.UITests.Core.Behaviours.TestsEngine.Attributes; using HybridTestFramework.UITests.Core.Behaviours.TestsEngine.Enums; using HybridTestFramework.UITests.Core.Behaviours.VideoRecording.Attributes; using HybridTestFramework.UITests.Core.Behaviours.VideoRecording.Enums; using HybridTestFramework.UITests.Core.Utilities; using HybridTestFramework.UITests.Core.Utilities.ExceptionsAnalysis.Decorator; using HybridTestFramework.UITests.Core.Utilities.ExceptionsAnalysis.Decorator.Interfaces; using Microsoft.Practices.Unity; using Microsoft.VisualStudio.TestTools.UnitTesting; using System; namespace FailedTestsAnalysisDecorator { [TestClass, ExecutionEngineAttribute(ExecutionEngineType.TestStudio, Browsers.Firefox), VideoRecordingAttribute(VideoRecordingMode.DoNotRecord)] public class BingTests : BaseTest { public override void TestInit() { base.TestInit(); UnityContainerFactory.GetContainer().RegisterType<IExceptionAnalysationHandler, ServiceUnavailableExceptionHandler>(Guid.NewGuid().ToString()); UnityContainerFactory.GetContainer().RegisterType<IExceptionAnalysationHandler, FileNotFoundExceptionHandler>(Guid.NewGuid().ToString()); } [TestMethod] public void TryToLoginTelerik_Decorator() { var loginPage = this.Container.Resolve<LoginPage>(); loginPage.Navigate(); loginPage.Login(); loginPage.Logout(); } } }
46.096154
155
0.765957
[ "Apache-2.0" ]
pravrawa/AutomateThePlanet
Design-Architecture-Series/FailedTestsAnalysisDecorator/BingTests.cs
2,399
C#
#region License /* The MIT License * * Copyright (c) 2011 Red Badger Consulting * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #endregion namespace RedBadger.Xpf { public enum HorizontalAlignment { Stretch, Left, Center, Right } }
37.472222
81
0.716086
[ "MIT" ]
Halofreak1990/XPF
XPF/RedBadger.Xpf/HorizontalAlignment.cs
1,349
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Azure.Core; using Azure.Core.Pipeline; using Azure.Messaging.ServiceBus.Core; using Azure.Messaging.ServiceBus.Diagnostics; using Azure.Messaging.ServiceBus.Plugins; namespace Azure.Messaging.ServiceBus { /// <summary> /// The <see cref="ServiceBusSessionReceiver" /> is responsible for receiving <see cref="ServiceBusReceivedMessage" /> /// and settling messages from session-enabled Queues and Subscriptions. It is constructed by calling /// <see cref="ServiceBusClient.AcceptNextSessionAsync(string, string, ServiceBusSessionReceiverOptions, CancellationToken)"/>. /// </summary> public class ServiceBusSessionReceiver : ServiceBusReceiver { /// <summary> /// The Session Id associated with the receiver. /// </summary> public string SessionId => InnerReceiver.SessionId; /// <summary> /// Gets the <see cref="DateTimeOffset"/> that the receiver's session is locked until. /// </summary> public DateTimeOffset SessionLockedUntil => InnerReceiver.SessionLockedUntil; /// <summary> /// Creates a session receiver which can be used to interact with all messages with the same sessionId. /// </summary> /// /// <param name="entityPath">The name of the specific queue to associate the receiver with.</param> /// <param name="connection">The <see cref="ServiceBusConnection" /> connection to use for communication with the Service Bus service.</param> /// <param name="plugins">The set of plugins to apply to incoming messages.</param> /// <param name="options">A set of options to apply when configuring the receiver.</param> /// <param name="sessionId">The Session Id to receive from or null to receive from the next available session.</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// ///<returns>Returns a new instance of the <see cref="ServiceBusSessionReceiver"/> class.</returns> internal static async Task<ServiceBusSessionReceiver> CreateSessionReceiverAsync( string entityPath, ServiceBusConnection connection, IList<ServiceBusPlugin> plugins, ServiceBusSessionReceiverOptions options, string sessionId, CancellationToken cancellationToken) { var receiver = new ServiceBusSessionReceiver( connection: connection, entityPath: entityPath, plugins: plugins, options: options, sessionId: sessionId); try { await receiver.OpenLinkAsync(cancellationToken).ConfigureAwait(false); } catch (Exception ex) { receiver.Logger.ClientCreateException(typeof(ServiceBusSessionReceiver), receiver.FullyQualifiedNamespace, entityPath, ex); throw; } receiver.Logger.ClientCreateComplete(typeof(ServiceBusSessionReceiver), receiver.Identifier); return receiver; } /// <summary> /// Initializes a new instance of the <see cref="ServiceBusReceiver"/> class. /// </summary> /// /// <param name="connection">The <see cref="ServiceBusConnection" /> connection to use for communication with the Service Bus service.</param> /// <param name="entityPath"></param> /// <param name="plugins">The set of plugins to apply to incoming messages.</param> /// <param name="options">A set of options to apply when configuring the consumer.</param> /// <param name="sessionId">An optional session Id to receive from.</param> internal ServiceBusSessionReceiver( ServiceBusConnection connection, string entityPath, IList<ServiceBusPlugin> plugins, ServiceBusSessionReceiverOptions options, string sessionId = default) : base(connection, entityPath, true, plugins, options?.ToReceiverOptions(), sessionId) { } /// <summary> /// Initializes a new instance of the <see cref="ServiceBusReceiver"/> class for mocking. /// </summary> /// protected ServiceBusSessionReceiver() : base() { } /// <summary> /// Gets the session state. /// </summary> /// /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <returns>The session state as <see cref="BinaryData"/>.</returns> public virtual async Task<BinaryData> GetSessionStateAsync(CancellationToken cancellationToken = default) { Argument.AssertNotDisposed(IsClosed, nameof(ServiceBusSessionReceiver)); cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); Logger.GetSessionStateStart(Identifier, SessionId); using DiagnosticScope scope = ScopeFactory.CreateScope( DiagnosticProperty.GetSessionStateActivityName, DiagnosticProperty.ClientKind); scope.Start(); BinaryData sessionState; try { sessionState = await InnerReceiver.GetStateAsync(cancellationToken).ConfigureAwait(false); } catch (Exception exception) { Logger.GetSessionStateException(Identifier, exception.ToString()); scope.Failed(exception); throw; } Logger.GetSessionStateComplete(Identifier); return sessionState; } /// <summary> /// Set a custom state on the session which can be later retrieved using <see cref="GetSessionStateAsync"/> /// </summary> /// /// <param name="sessionState">A <see cref="BinaryData"/> of session state</param> /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <remarks>This state is stored on Service Bus forever unless you set an empty state on it.</remarks> /// /// <returns>A task to be resolved on when the operation has completed.</returns> public virtual async Task SetSessionStateAsync( BinaryData sessionState, CancellationToken cancellationToken = default) { Argument.AssertNotDisposed(IsClosed, nameof(ServiceBusSessionReceiver)); cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); Logger.SetSessionStateStart(Identifier, SessionId); using DiagnosticScope scope = ScopeFactory.CreateScope( DiagnosticProperty.SetSessionStateActivityName, DiagnosticProperty.ClientKind); scope.Start(); try { await InnerReceiver.SetStateAsync(sessionState, cancellationToken).ConfigureAwait(false); } catch (Exception exception) { Logger.SetSessionStateException(Identifier, exception.ToString()); scope.Failed(exception); throw; } Logger.SetSessionStateComplete(Identifier); } /// <summary> /// Renews the lock on the session specified by the <see cref="SessionId"/>. The lock will be renewed based on the setting specified on the entity. /// </summary> /// /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param> /// /// <remarks> /// <para> /// When you get session receiver, the session is locked for this receiver by the service for a duration as specified during the Queue/Subscription creation. /// If processing of the session requires longer than this duration, the session-lock needs to be renewed. /// For each renewal, it resets the time the session is locked by the LockDuration set on the Entity. /// </para> /// <para> /// Renewal of session renews all the messages in the session as well. Each individual message need not be renewed. /// </para> /// </remarks> public virtual async Task RenewSessionLockAsync(CancellationToken cancellationToken = default) { Argument.AssertNotDisposed(IsClosed, nameof(ServiceBusSessionReceiver)); cancellationToken.ThrowIfCancellationRequested<TaskCanceledException>(); Logger.RenewSessionLockStart(Identifier, SessionId); using DiagnosticScope scope = ScopeFactory.CreateScope( DiagnosticProperty.RenewSessionLockActivityName, DiagnosticProperty.ClientKind); scope.Start(); try { await InnerReceiver.RenewSessionLockAsync(cancellationToken).ConfigureAwait(false); } catch (Exception exception) { Logger.RenewSessionLockException(Identifier, exception.ToString()); scope.Failed(exception); throw; } Logger.RenewSessionLockComplete(Identifier); } } }
46.591346
165
0.63657
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/servicebus/Azure.Messaging.ServiceBus/src/Receiver/ServiceBusSessionReceiver.cs
9,693
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Compute.Models; using Azure.ResourceManager.Core; namespace Azure.ResourceManager.Compute { internal partial class VirtualMachineScaleSetExtensionsRestOperations { private Uri endpoint; private string apiVersion; private ClientDiagnostics _clientDiagnostics; private HttpPipeline _pipeline; private readonly string _userAgent; /// <summary> Initializes a new instance of VirtualMachineScaleSetExtensionsRestOperations. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="applicationId"> The application id to use for user agent. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> <paramref name="apiVersion"/> is null. </exception> public VirtualMachineScaleSetExtensionsRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) { this.endpoint = endpoint ?? new Uri("https://management.azure.com"); this.apiVersion = apiVersion ?? "2021-07-01"; _clientDiagnostics = clientDiagnostics; _pipeline = pipeline; _userAgent = Core.HttpMessageUtilities.GetUserAgentName(this, applicationId); } internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string vmScaleSetName, string vmssExtensionName, VirtualMachineScaleSetExtensionData extensionParameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Compute/virtualMachineScaleSets/", false); uri.AppendPath(vmScaleSetName, true); uri.AppendPath("/extensions/", false); uri.AppendPath(vmssExtensionName, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(extensionParameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> The operation to create or update an extension. </summary> /// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="vmScaleSetName"> The name of the VM scale set where the extension should be create or updated. </param> /// <param name="vmssExtensionName"> The name of the VM scale set extension. </param> /// <param name="extensionParameters"> Parameters supplied to the Create VM scale set Extension operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="vmScaleSetName"/>, <paramref name="vmssExtensionName"/>, or <paramref name="extensionParameters"/> is null. </exception> public async Task<Response> CreateOrUpdateAsync(string subscriptionId, string resourceGroupName, string vmScaleSetName, string vmssExtensionName, VirtualMachineScaleSetExtensionData extensionParameters, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (vmScaleSetName == null) { throw new ArgumentNullException(nameof(vmScaleSetName)); } if (vmssExtensionName == null) { throw new ArgumentNullException(nameof(vmssExtensionName)); } if (extensionParameters == null) { throw new ArgumentNullException(nameof(extensionParameters)); } using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, vmScaleSetName, vmssExtensionName, extensionParameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 201: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> The operation to create or update an extension. </summary> /// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="vmScaleSetName"> The name of the VM scale set where the extension should be create or updated. </param> /// <param name="vmssExtensionName"> The name of the VM scale set extension. </param> /// <param name="extensionParameters"> Parameters supplied to the Create VM scale set Extension operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="vmScaleSetName"/>, <paramref name="vmssExtensionName"/>, or <paramref name="extensionParameters"/> is null. </exception> public Response CreateOrUpdate(string subscriptionId, string resourceGroupName, string vmScaleSetName, string vmssExtensionName, VirtualMachineScaleSetExtensionData extensionParameters, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (vmScaleSetName == null) { throw new ArgumentNullException(nameof(vmScaleSetName)); } if (vmssExtensionName == null) { throw new ArgumentNullException(nameof(vmssExtensionName)); } if (extensionParameters == null) { throw new ArgumentNullException(nameof(extensionParameters)); } using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, vmScaleSetName, vmssExtensionName, extensionParameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 201: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateUpdateRequest(string subscriptionId, string resourceGroupName, string vmScaleSetName, string vmssExtensionName, VirtualMachineScaleSetExtensionUpdate extensionParameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Patch; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Compute/virtualMachineScaleSets/", false); uri.AppendPath(vmScaleSetName, true); uri.AppendPath("/extensions/", false); uri.AppendPath(vmssExtensionName, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(extensionParameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> The operation to update an extension. </summary> /// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="vmScaleSetName"> The name of the VM scale set where the extension should be updated. </param> /// <param name="vmssExtensionName"> The name of the VM scale set extension. </param> /// <param name="extensionParameters"> Parameters supplied to the Update VM scale set Extension operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="vmScaleSetName"/>, <paramref name="vmssExtensionName"/>, or <paramref name="extensionParameters"/> is null. </exception> public async Task<Response> UpdateAsync(string subscriptionId, string resourceGroupName, string vmScaleSetName, string vmssExtensionName, VirtualMachineScaleSetExtensionUpdate extensionParameters, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (vmScaleSetName == null) { throw new ArgumentNullException(nameof(vmScaleSetName)); } if (vmssExtensionName == null) { throw new ArgumentNullException(nameof(vmssExtensionName)); } if (extensionParameters == null) { throw new ArgumentNullException(nameof(extensionParameters)); } using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, vmScaleSetName, vmssExtensionName, extensionParameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 201: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> The operation to update an extension. </summary> /// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="vmScaleSetName"> The name of the VM scale set where the extension should be updated. </param> /// <param name="vmssExtensionName"> The name of the VM scale set extension. </param> /// <param name="extensionParameters"> Parameters supplied to the Update VM scale set Extension operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="vmScaleSetName"/>, <paramref name="vmssExtensionName"/>, or <paramref name="extensionParameters"/> is null. </exception> public Response Update(string subscriptionId, string resourceGroupName, string vmScaleSetName, string vmssExtensionName, VirtualMachineScaleSetExtensionUpdate extensionParameters, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (vmScaleSetName == null) { throw new ArgumentNullException(nameof(vmScaleSetName)); } if (vmssExtensionName == null) { throw new ArgumentNullException(nameof(vmssExtensionName)); } if (extensionParameters == null) { throw new ArgumentNullException(nameof(extensionParameters)); } using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, vmScaleSetName, vmssExtensionName, extensionParameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 201: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string vmScaleSetName, string vmssExtensionName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Compute/virtualMachineScaleSets/", false); uri.AppendPath(vmScaleSetName, true); uri.AppendPath("/extensions/", false); uri.AppendPath(vmssExtensionName, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> The operation to delete the extension. </summary> /// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="vmScaleSetName"> The name of the VM scale set where the extension should be deleted. </param> /// <param name="vmssExtensionName"> The name of the VM scale set extension. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="vmScaleSetName"/>, or <paramref name="vmssExtensionName"/> is null. </exception> public async Task<Response> DeleteAsync(string subscriptionId, string resourceGroupName, string vmScaleSetName, string vmssExtensionName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (vmScaleSetName == null) { throw new ArgumentNullException(nameof(vmScaleSetName)); } if (vmssExtensionName == null) { throw new ArgumentNullException(nameof(vmssExtensionName)); } using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, vmScaleSetName, vmssExtensionName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: case 204: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> The operation to delete the extension. </summary> /// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="vmScaleSetName"> The name of the VM scale set where the extension should be deleted. </param> /// <param name="vmssExtensionName"> The name of the VM scale set extension. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="vmScaleSetName"/>, or <paramref name="vmssExtensionName"/> is null. </exception> public Response Delete(string subscriptionId, string resourceGroupName, string vmScaleSetName, string vmssExtensionName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (vmScaleSetName == null) { throw new ArgumentNullException(nameof(vmScaleSetName)); } if (vmssExtensionName == null) { throw new ArgumentNullException(nameof(vmssExtensionName)); } using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, vmScaleSetName, vmssExtensionName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: case 204: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string vmScaleSetName, string vmssExtensionName, string expand) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Compute/virtualMachineScaleSets/", false); uri.AppendPath(vmScaleSetName, true); uri.AppendPath("/extensions/", false); uri.AppendPath(vmssExtensionName, true); if (expand != null) { uri.AppendQuery("$expand", expand, true); } uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> The operation to get the extension. </summary> /// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="vmScaleSetName"> The name of the VM scale set containing the extension. </param> /// <param name="vmssExtensionName"> The name of the VM scale set extension. </param> /// <param name="expand"> The expand expression to apply on the operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="vmScaleSetName"/>, or <paramref name="vmssExtensionName"/> is null. </exception> public async Task<Response<VirtualMachineScaleSetExtensionData>> GetAsync(string subscriptionId, string resourceGroupName, string vmScaleSetName, string vmssExtensionName, string expand = null, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (vmScaleSetName == null) { throw new ArgumentNullException(nameof(vmScaleSetName)); } if (vmssExtensionName == null) { throw new ArgumentNullException(nameof(vmssExtensionName)); } using var message = CreateGetRequest(subscriptionId, resourceGroupName, vmScaleSetName, vmssExtensionName, expand); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { VirtualMachineScaleSetExtensionData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = VirtualMachineScaleSetExtensionData.DeserializeVirtualMachineScaleSetExtensionData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((VirtualMachineScaleSetExtensionData)null, message.Response); default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> The operation to get the extension. </summary> /// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="vmScaleSetName"> The name of the VM scale set containing the extension. </param> /// <param name="vmssExtensionName"> The name of the VM scale set extension. </param> /// <param name="expand"> The expand expression to apply on the operation. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="vmScaleSetName"/>, or <paramref name="vmssExtensionName"/> is null. </exception> public Response<VirtualMachineScaleSetExtensionData> Get(string subscriptionId, string resourceGroupName, string vmScaleSetName, string vmssExtensionName, string expand = null, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (vmScaleSetName == null) { throw new ArgumentNullException(nameof(vmScaleSetName)); } if (vmssExtensionName == null) { throw new ArgumentNullException(nameof(vmssExtensionName)); } using var message = CreateGetRequest(subscriptionId, resourceGroupName, vmScaleSetName, vmssExtensionName, expand); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { VirtualMachineScaleSetExtensionData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = VirtualMachineScaleSetExtensionData.DeserializeVirtualMachineScaleSetExtensionData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((VirtualMachineScaleSetExtensionData)null, message.Response); default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListRequest(string subscriptionId, string resourceGroupName, string vmScaleSetName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.Compute/virtualMachineScaleSets/", false); uri.AppendPath(vmScaleSetName, true); uri.AppendPath("/extensions", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets a list of all extensions in a VM scale set. </summary> /// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="vmScaleSetName"> The name of the VM scale set containing the extension. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="vmScaleSetName"/> is null. </exception> public async Task<Response<VirtualMachineScaleSetExtensionListResult>> ListAsync(string subscriptionId, string resourceGroupName, string vmScaleSetName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (vmScaleSetName == null) { throw new ArgumentNullException(nameof(vmScaleSetName)); } using var message = CreateListRequest(subscriptionId, resourceGroupName, vmScaleSetName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { VirtualMachineScaleSetExtensionListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = VirtualMachineScaleSetExtensionListResult.DeserializeVirtualMachineScaleSetExtensionListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets a list of all extensions in a VM scale set. </summary> /// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="vmScaleSetName"> The name of the VM scale set containing the extension. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="vmScaleSetName"/> is null. </exception> public Response<VirtualMachineScaleSetExtensionListResult> List(string subscriptionId, string resourceGroupName, string vmScaleSetName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (vmScaleSetName == null) { throw new ArgumentNullException(nameof(vmScaleSetName)); } using var message = CreateListRequest(subscriptionId, resourceGroupName, vmScaleSetName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { VirtualMachineScaleSetExtensionListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = VirtualMachineScaleSetExtensionListResult.DeserializeVirtualMachineScaleSetExtensionListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string vmScaleSetName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets a list of all extensions in a VM scale set. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="vmScaleSetName"> The name of the VM scale set containing the extension. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="vmScaleSetName"/> is null. </exception> public async Task<Response<VirtualMachineScaleSetExtensionListResult>> ListNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string vmScaleSetName, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (vmScaleSetName == null) { throw new ArgumentNullException(nameof(vmScaleSetName)); } using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName, vmScaleSetName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { VirtualMachineScaleSetExtensionListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = VirtualMachineScaleSetExtensionListResult.DeserializeVirtualMachineScaleSetExtensionListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets a list of all extensions in a VM scale set. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> The name of the resource group. </param> /// <param name="vmScaleSetName"> The name of the VM scale set containing the extension. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="vmScaleSetName"/> is null. </exception> public Response<VirtualMachineScaleSetExtensionListResult> ListNextPage(string nextLink, string subscriptionId, string resourceGroupName, string vmScaleSetName, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (vmScaleSetName == null) { throw new ArgumentNullException(nameof(vmScaleSetName)); } using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName, vmScaleSetName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { VirtualMachineScaleSetExtensionListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = VirtualMachineScaleSetExtensionListResult.DeserializeVirtualMachineScaleSetExtensionListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } } }
56.982275
262
0.636519
[ "MIT" ]
lubaozhen/azure-sdk-for-net
sdk/compute/Azure.ResourceManager.Compute/src/Generated/RestOperations/VirtualMachineScaleSetExtensionsRestOperations.cs
38,577
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace AirBreath.Server.Migrations { public partial class InitialCreate : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "contacts", columns: table => new { id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), last_name = table.Column<string>(nullable: false), first_name = table.Column<string>(nullable: false), phone = table.Column<string>(nullable: true), email = table.Column<string>(maxLength: 30, nullable: true) }, constraints: table => { table.PrimaryKey("pk_contacts", x => x.id); }); migrationBuilder.CreateTable( name: "roles", columns: table => new { id = table.Column<string>(nullable: false), name = table.Column<string>(maxLength: 256, nullable: true), normalized_name = table.Column<string>(maxLength: 256, nullable: true), concurrency_stamp = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("pk_roles", x => x.id); }); migrationBuilder.CreateTable( name: "users", columns: table => new { id = table.Column<string>(nullable: false), user_name = table.Column<string>(maxLength: 256, nullable: true), normalized_user_name = table.Column<string>(maxLength: 256, nullable: true), email = table.Column<string>(maxLength: 256, nullable: true), normalized_email = table.Column<string>(maxLength: 256, nullable: true), email_confirmed = table.Column<bool>(nullable: false), password_hash = table.Column<string>(nullable: true), security_stamp = table.Column<string>(nullable: true), concurrency_stamp = table.Column<string>(nullable: true), phone_number = table.Column<string>(nullable: true), phone_number_confirmed = table.Column<bool>(nullable: false), two_factor_enabled = table.Column<bool>(nullable: false), lockout_end = table.Column<DateTimeOffset>(nullable: true), lockout_enabled = table.Column<bool>(nullable: false), access_failed_count = table.Column<int>(nullable: false), given_name = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("pk_users", x => x.id); }); migrationBuilder.CreateTable( name: "role_claims", columns: table => new { id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), role_id = table.Column<string>(nullable: false), claim_type = table.Column<string>(nullable: true), claim_value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("pk_role_claims", x => x.id); table.ForeignKey( name: "fk_role_claims_roles_role_id", column: x => x.role_id, principalTable: "roles", principalColumn: "id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "user_claims", columns: table => new { id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), user_id = table.Column<string>(nullable: false), claim_type = table.Column<string>(nullable: true), claim_value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("pk_user_claims", x => x.id); table.ForeignKey( name: "fk_user_claims_users_user_id", column: x => x.user_id, principalTable: "users", principalColumn: "id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "user_logins", columns: table => new { login_provider = table.Column<string>(nullable: false), provider_key = table.Column<string>(nullable: false), provider_display_name = table.Column<string>(nullable: true), user_id = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("pk_user_logins", x => new { x.login_provider, x.provider_key }); table.ForeignKey( name: "fk_user_logins_users_user_id", column: x => x.user_id, principalTable: "users", principalColumn: "id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "user_roles", columns: table => new { user_id = table.Column<string>(nullable: false), role_id = table.Column<string>(nullable: false) }, constraints: table => { table.PrimaryKey("pk_user_roles", x => new { x.user_id, x.role_id }); table.ForeignKey( name: "fk_user_roles_roles_role_id", column: x => x.role_id, principalTable: "roles", principalColumn: "id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "fk_user_roles_users_user_id", column: x => x.user_id, principalTable: "users", principalColumn: "id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "user_tokens", columns: table => new { user_id = table.Column<string>(nullable: false), login_provider = table.Column<string>(nullable: false), name = table.Column<string>(nullable: false), value = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("pk_user_tokens", x => new { x.user_id, x.login_provider, x.name }); table.ForeignKey( name: "fk_user_tokens_users_user_id", column: x => x.user_id, principalTable: "users", principalColumn: "id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "ix_role_claims_role_id", table: "role_claims", column: "role_id"); migrationBuilder.CreateIndex( name: "role_name_index", table: "roles", column: "normalized_name", unique: true); migrationBuilder.CreateIndex( name: "ix_user_claims_user_id", table: "user_claims", column: "user_id"); migrationBuilder.CreateIndex( name: "ix_user_logins_user_id", table: "user_logins", column: "user_id"); migrationBuilder.CreateIndex( name: "ix_user_roles_role_id", table: "user_roles", column: "role_id"); migrationBuilder.CreateIndex( name: "email_index", table: "users", column: "normalized_email"); migrationBuilder.CreateIndex( name: "user_name_index", table: "users", column: "normalized_user_name", unique: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "contacts"); migrationBuilder.DropTable( name: "role_claims"); migrationBuilder.DropTable( name: "user_claims"); migrationBuilder.DropTable( name: "user_logins"); migrationBuilder.DropTable( name: "user_roles"); migrationBuilder.DropTable( name: "user_tokens"); migrationBuilder.DropTable( name: "roles"); migrationBuilder.DropTable( name: "users"); } } }
41.302521
105
0.475381
[ "MIT" ]
krozhkov/airbreath
AirBreath.Server/Migrations/20200409095909_InitialCreate.cs
9,832
C#
using System; namespace problema2 { class Program { static void Main(string[] args) { Console.WriteLine("Avem triunghiul: "); triunghi t = new triunghi( p1: new Point(10, 10), p2: new Point(20, 20), p3: new Point(10, 30)); Console.WriteLine("Avem dreprunghiul: "); dreptunghi d = new dreptunghi( topLeft: new Point(10, 10), width: 10, height: 5); Console.WriteLine("Avem patratul : "); patrat p = new patrat( topLeft: new Point(10, 10), width: 10 ); t.Print(); d.Print(); p.Print(); Console.WriteLine("aria pentru : "); Console.WriteLine(GeometryUtils.GetAria(t,d,p)); Console.WriteLine("Facem move pentru triunghi , dreptungi si pentru patrat : "); GeometryUtils.Move(10, 10, t, d,p); t.Print(); d.Print(); p.Print(); Console.WriteLine("Facem rotate pentru triunghi , dreptungi si pentru patrat : "); GeometryUtils.Rotate(50.89, t, d, p); t.Print(); d.Print(); p.Print(); } } }
23.785714
94
0.458709
[ "MIT" ]
iuliki/problema2
problema2/problema2/Program.cs
1,334
C#
using UnityEngine; using System.Collections; public class WindowManager : MonoBehaviour { [HideInInspector] public GenericWindow[] windows; public int currentWindowID; public int defaultWindowID; public GenericWindow GetWindow(int value){ return windows [value]; } private void ToggleVisability(int value, bool closeAllOpen = true) { var total = windows.Length; if(closeAllOpen) { for (var i = 0; i < total; i++) { var window = windows[i]; if (window.gameObject.activeSelf) { window.Close(); } } } GetWindow(value).Open(); } public GenericWindow Open(int value, bool closeAllOpen = true) { if (value < 0 || value >= windows.Length) return null; currentWindowID = value; ToggleVisability (currentWindowID, closeAllOpen); return GetWindow (currentWindowID); } void Start(){ GenericWindow.manager = this; Open (defaultWindowID); } }
18.686275
67
0.660021
[ "MIT" ]
dparke/dragonstabbers
Assets/AdvancedUI/Scripts/Managers/WindowManager.cs
955
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.CognitiveServices.Vision.Face.Models { using Microsoft.Rest; using Newtonsoft.Json; using System.Linq; /// <summary> /// Request to update person face data. /// </summary> public partial class UpdatePersonFaceDataRequest { /// <summary> /// Initializes a new instance of the UpdatePersonFaceDataRequest /// class. /// </summary> public UpdatePersonFaceDataRequest() { CustomInit(); } /// <summary> /// Initializes a new instance of the UpdatePersonFaceDataRequest /// class. /// </summary> /// <param name="userData">User-provided data attached to the face. The /// size limit is 1KB</param> public UpdatePersonFaceDataRequest(string userData = default(string)) { UserData = userData; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets user-provided data attached to the face. The size /// limit is 1KB /// </summary> [JsonProperty(PropertyName = "userData")] public string UserData { get; set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (UserData != null) { if (UserData.Length > 1024) { throw new ValidationException(ValidationRules.MaxLength, "UserData", 1024); } } } } }
30
95
0.575342
[ "MIT" ]
AzureAutomationTeam/azure-sdk-for-net
src/SDKs/CognitiveServices/dataPlane/Vision/Vision/Generated/Face/Models/UpdatePersonFaceDataRequest.cs
2,190
C#
using System; using System.Net; using System.Net.Sockets; using System.Reactive.Subjects; using System.Threading; using System.Threading.Tasks; using NetworkMonitor.Framework.Logging; using NetworkMonitor.Models.Entities; using NLog; namespace NetworkMonitor.ViewModels.Services { internal class TcpTransmissionClient : ITransmissionClient { private readonly CompositionLogger Log = new CompositionLogger(); private static readonly ILogger LocalLogger = LogManager.GetLogger(nameof(TcpTransmissionClient)); private readonly Transmitter _transmitter; private TcpClient _tcpClient; private PipeAdapter _adapter; public TcpTransmissionClient(Transmitter transmitter, IInteractiveLogger log) { Log.AddLogger(LocalLogger.Wrap()); Log.AddLogger(log); _transmitter = transmitter; } public bool Execute() { try { _tcpClient = new TcpClient(); _tcpClient.Connect(CreateEndpoint()); _adapter = new PipeAdapter(_tcpClient.GetStream()); return true; } catch (Exception e) { Log.Error(e); return false; } } private IPEndPoint CreateEndpoint() { if (_transmitter.Broadcast) return new IPEndPoint(IPAddress.Any, _transmitter.PortNumber); return new IPEndPoint(IPAddress.Parse(_transmitter.IpAddress), _transmitter.PortNumber); } public void Terminate() { _adapter?.Dispose(); _tcpClient?.Close(); _tcpClient?.Dispose(); _tcpClient = null; } public async Task<int> SendAsync(byte[] bytes) { await _adapter.WriteAsync(bytes, CancellationToken.None).ConfigureAwait(false); return bytes.Length; } } }
23.75
100
0.741176
[ "MIT" ]
taori/Network-Monitor
src/NetworkMonitor/NetworkMonitor.ViewModels/Services/TcpTransmissionClient.cs
1,617
C#
using DCT.ILR.Model; using FluentAssertions; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace BusinessRules.POC.Tests { public class FileDataTests { [Fact] public void Populate_FilePreparationDate() { var fileData = new FileData.FileData(); var filePreparationDate = new DateTime(2018, 1, 5); var message = new Message() { Header = new MessageHeader() { CollectionDetails = new MessageHeaderCollectionDetails() { FilePreparationDate = filePreparationDate } } }; fileData.Populate(message); fileData.FilePreparationDate.Should().Be(filePreparationDate); } } }
24.078947
76
0.561749
[ "MIT" ]
SkillsFundingAgency/DC-Alpha-ValidationService-POC
src/DCT.ValidationService.POC/BusinessRules.POC.Tests/FileDataTests.cs
917
C#
using LWFramework.Core; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Xml; using UnityEditor; using UnityEditor.Compilation; using UnityEngine; public class DllBuild { /// <summary> /// 打包完成,返回一个bool表示成功还是失败 /// </summary> public Action<DllBuild, bool> onFinished; public string[] filterStrArray; string _outputDir; string _outputAssemblyPath; /// <summary> /// 代码地址 /// </summary> public string assemblyPath { get { return _outputAssemblyPath; } } public DllBuild(string outputDir) { _outputDir = outputDir; if (false == Directory.Exists(outputDir)) { Directory.CreateDirectory(outputDir); } _outputAssemblyPath = FileTool.CombinePaths(outputDir, LWUtility.HotfixFileName); } private static string define = @"XASSET;ILRUNTIME;DEBUG;TRACE;UNITY_5_3_OR_NEWER;UNITY_5_4_OR_NEWER;UNITY_5_5_OR_NEWER;UNITY_5_6_OR_NEWER;UNITY_2017_1_OR_NEWER;UNITY_2017_2_OR_NEWER;UNITY_2017_3_OR_NEWER;UNITY_2017_4_OR_NEWER;UNITY_2018_1_OR_NEWER;UNITY_2018_2_OR_NEWER;UNITY_2018_3_OR_NEWER;UNITY_2018_3_8;UNITY_2018_3;UNITY_2018;PLATFORM_ARCH_64;UNITY_64;UNITY_INCLUDE_TESTS;ENABLE_AUDIO;ENABLE_CACHING;ENABLE_CLOTH;ENABLE_DUCK_TYPING;ENABLE_MICROPHONE;ENABLE_MULTIPLE_DISPLAYS;ENABLE_PHYSICS;ENABLE_SPRITES;ENABLE_GRID;ENABLE_TILEMAP;ENABLE_TERRAIN;ENABLE_TEXTURE_STREAMING;ENABLE_DIRECTOR;ENABLE_UNET;ENABLE_LZMA;ENABLE_UNITYEVENTS;ENABLE_WEBCAM;ENABLE_WWW;ENABLE_CLOUD_SERVICES_COLLAB;ENABLE_CLOUD_SERVICES_COLLAB_SOFTLOCKS;ENABLE_CLOUD_SERVICES_ADS;ENABLE_CLOUD_HUB;ENABLE_CLOUD_PROJECT_ID;ENABLE_CLOUD_SERVICES_USE_WEBREQUEST;ENABLE_CLOUD_SERVICES_UNET;ENABLE_CLOUD_SERVICES_BUILD;ENABLE_CLOUD_LICENSE;ENABLE_EDITOR_HUB;ENABLE_EDITOR_HUB_LICENSE;ENABLE_WEBSOCKET_CLIENT;ENABLE_DIRECTOR_AUDIO;ENABLE_DIRECTOR_TEXTURE;ENABLE_TIMELINE;ENABLE_EDITOR_METRICS;ENABLE_EDITOR_METRICS_CACHING;ENABLE_MANAGED_JOBS;ENABLE_MANAGED_TRANSFORM_JOBS;ENABLE_MANAGED_ANIMATION_JOBS;INCLUDE_DYNAMIC_GI;INCLUDE_GI;ENABLE_MONO_BDWGC;PLATFORM_SUPPORTS_MONO;RENDER_SOFTWARE_CURSOR;INCLUDE_PUBNUB;ENABLE_VIDEO;ENABLE_CUSTOM_RENDER_TEXTURE;ENABLE_LOCALIZATION;PLATFORM_STANDALONE_WIN;PLATFORM_STANDALONE;UNITY_STANDALONE_WIN;UNITY_STANDALONE;ENABLE_SUBSTANCE;ENABLE_RUNTIME_GI;ENABLE_MOVIES;ENABLE_NETWORK;ENABLE_CRUNCH_TEXTURE_COMPRESSION;ENABLE_UNITYWEBREQUEST;ENABLE_CLOUD_SERVICES;ENABLE_CLOUD_SERVICES_ANALYTICS;ENABLE_CLOUD_SERVICES_PURCHASING;ENABLE_CLOUD_SERVICES_CRASH_REPORTING;ENABLE_OUT_OF_PROCESS_CRASH_HANDLER;ENABLE_EVENT_QUEUE;ENABLE_CLUSTER_SYNC;ENABLE_CLUSTERINPUT;ENABLE_VR;ENABLE_AR;ENABLE_WEBSOCKET_HOST;ENABLE_MONO;NET_4_6;ENABLE_PROFILER;UNITY_ASSERTIONS;ENABLE_UNITY_COLLECTIONS_CHECKS;ENABLE_BURST_AOT;UNITY_TEAM_LICENSE;UNITY_PRO_LICENSE;ODIN_INSPECTOR;UNITY_POST_PROCESSING_STACK_V2;CSHARP_7_OR_LATER;CSHARP_7_3_OR_NEWER"; public void Execute() { #region CS DLL引用搜集处理 List<string> csFiles = new List<string>(); csFiles = FindDLLByCSPROJ("Assembly-CSharp.csproj"); #if !ILRUNTIME var baseCs = csFiles.FindAll(f => !f.Contains("@hotfix") && !f.Contains("@h_Mono") && f.EndsWith(".cs")); #else var baseCs = csFiles.FindAll(f => !f.Contains("@hotfix") && f.EndsWith(".cs")); #endif var hotfixCs = csFiles.FindAll(f => f.Contains("@hotfix") && f.EndsWith(".cs")); #if !ILRUNTIME var hotfixMonoCs = csFiles.FindAll(f => f.Contains("@h_Mono") && f.EndsWith(".cs")); hotfixCs.AddRange(hotfixMonoCs); #endif #endregion //var scriptPaths = Directory.GetFiles(_sourcesDir, "*.cs", SearchOption.AllDirectories); var ab = new AssemblyBuilder(_outputAssemblyPath, hotfixCs.ToArray()); ab.compilerOptions = new ScriptCompilerOptions(); ab.flags = AssemblyBuilderFlags.DevelopmentBuild | AssemblyBuilderFlags.EditorAssembly; ab.additionalReferences = GetDepends(); ab.additionalDefines = define.Split(';'); ab.buildFinished += OnFinished; if (false == ab.Build()) { onFinished?.Invoke(this, false); onFinished = null; } } public void GetAllScripts() { } string[] GetDepends() { //依赖Assets下的DLL var assetDir = Application.dataPath; var dllList0 = Directory.GetFiles(assetDir, "*.dll", SearchOption.AllDirectories); //依赖Library/ScriptAssemblies下的DLL var projectDir = Directory.GetParent(assetDir).FullName; var dllList1 = Directory.GetFiles(FileTool.CombineDirs(true, projectDir, "Library", "ScriptAssemblies"), "*.dll", SearchOption.AllDirectories); //依赖Unity安装目录下的DLL var dir = FileTool.CombineDirs(true, EditorApplication.applicationContentsPath, "Managed", "UnityEngine"); var dllList2 = Directory.GetFiles(dir, "*.dll", SearchOption.AllDirectories); List<string> list0 = new List<string>(dllList0); for (int i = 0; i < list0.Count; i++) { for (int j = 0; j < filterStrArray.Length; j++) { if (list0[i].Contains(filterStrArray[j]) || list0[i].Contains(LWUtility.HotfixFileName)) { list0.RemoveAt(i); i--; } } } List<string> list1 = new List<string>(dllList1); List<string> list2 = new List<string>(dllList2); list1.AddRange(list2); list1.AddRange(list0); return list1.ToArray(); } /// <summary> /// 解析project中的dll /// </summary> /// <returns></returns> static List<string> FindDLLByCSPROJ(string projName) { //cs list List<string> csList = new List<string>(); var projpath = LWUtility.ProjectRoot + "/" + projName; XmlDocument xml = new XmlDocument(); xml.Load(projpath); XmlNode ProjectNode = null; foreach (XmlNode x in xml.ChildNodes) { if (x.Name == "Project") { ProjectNode = x; break; } } List<string> csprojList = new List<string>(); foreach (XmlNode childNode in ProjectNode.ChildNodes) { if (childNode.Name == "ItemGroup") { foreach (XmlNode item in childNode.ChildNodes) { if (item.Name == "Compile") //cs 引用 { var csproj = item.Attributes[0].Value; csList.Add(csproj); } else if (item.Name == "Reference") //DLL 引用 { var HintPath = item.FirstChild; var dir = HintPath.InnerText.Replace("/", "\\"); } else if (item.Name == "ProjectReference") //工程引用 { var csproj = item.Attributes[0].Value; csprojList.Add(csproj); } } } } //csproj也加入 foreach (var csproj in csprojList) { //有editor退出 if (csproj.ToLower().Contains("editor")) continue; //添加扫描到的dll FindDLLByCSPROJ(csproj); // var gendll = LWUtility.Library + "/ScriptAssemblies/" + csproj.Replace(".csproj", ".dll"); if (!File.Exists(gendll)) { Debug.LogError("不存在:" + gendll); } } return csList; } private void OnFinished(string path, CompilerMessage[] msgs) { bool isFail = false; foreach (var msg in msgs) { if (msg.type == CompilerMessageType.Error) { Debug.LogError(msg.message); isFail = true; } } if (isFail) { onFinished?.Invoke(this, false); } else { onFinished?.Invoke(this, true); } onFinished = null; } }
43.591398
2,004
0.639245
[ "Apache-2.0" ]
chen0123bin/MyTools
ToolsProject/Assets/Packages/LWFramework/Editor/BuildEditor/DllBuild.cs
8,250
C#
namespace Aviant.DDD.Infrastructure.Services { using MailKit.Net.Smtp; public interface ISmtpClientFactory { public SmtpClient GetSmtpClient(); } }
17.3
44
0.699422
[ "MIT" ]
panosru/Aviant.DDD
src/Infrastructure/Services/ISmtpClientFactory.cs
173
C#
using System; using System.Collections.Generic; using System.Reflection; using System.Linq; using System.Text; using ILRuntime.Runtime.Enviorment; namespace ILRuntime.Runtime.CLRBinding { static class MethodBindingGenerator { internal static string GenerateMethodRegisterCode(this Type type, MethodInfo[] methods, HashSet<MethodBase> excludes) { StringBuilder sb = new StringBuilder(); int idx = 0; bool isMethodsGot = false; foreach (var i in methods) { if (excludes != null && excludes.Contains(i)) continue; if (type.ShouldSkipMethod(i)) continue; if (i.IsGenericMethod) { if (!isMethodsGot) { sb.AppendLine(@" Dictionary<string, List<MethodInfo>> genericMethods = new Dictionary<string, List<MethodInfo>>(); List<MethodInfo> lst = null; foreach(var m in type.GetMethods()) { if(m.IsGenericMethodDefinition) { if (!genericMethods.TryGetValue(m.Name, out lst)) { lst = new List<MethodInfo>(); genericMethods[m.Name] = lst; } lst.Add(m); } }"); isMethodsGot = true; } var param = i.GetGenericArguments(); StringBuilder sb2 = new StringBuilder(); sb2.Append("{"); bool first = true; foreach (var j in param) { if (first) first = false; else sb2.Append(", "); sb2.Append("typeof("); string clsName, realClsName; bool isByRef; j.GetClassName(out clsName, out realClsName, out isByRef); sb2.Append(realClsName); sb2.Append(")"); if (isByRef) sb2.Append(".MakeByRefType()"); } sb2.Append("}"); sb.AppendLine(string.Format(" args = new Type[]{0};", sb2)); sb.AppendLine(string.Format(" if (genericMethods.TryGetValue(\"{0}\", out lst))", i.Name)); sb.Append(@" { foreach(var m in lst) { if(m.GetParameters().Length == "); sb.Append(i.GetParameters().Length.ToString()); sb.Append(@") { method = m.MakeGenericMethod(args); app.RegisterCLRMethodRedirection(method, "); sb.AppendLine(string.Format("{0}_{1});", i.Name, idx)); sb.AppendLine(@" break; } } }"); } else { var param = i.GetParameters(); StringBuilder sb2 = new StringBuilder(); sb2.Append("{"); bool first = true; foreach (var j in param) { if (first) first = false; else sb2.Append(", "); sb2.Append("typeof("); string clsName, realClsName; bool isByRef; j.ParameterType.GetClassName(out clsName, out realClsName, out isByRef); sb2.Append(realClsName); sb2.Append(")"); if (isByRef) sb2.Append(".MakeByRefType()"); } sb2.Append("}"); sb.AppendLine(string.Format(" args = new Type[]{0};", sb2)); sb.AppendLine(string.Format(" method = type.GetMethod(\"{0}\", flag, null, args, null);", i.Name)); sb.AppendLine(string.Format(" app.RegisterCLRMethodRedirection(method, {0}_{1});", i.Name, idx)); } idx++; } return sb.ToString(); } internal static string GenerateMethodWraperCode(this Type type, MethodInfo[] methods, string typeClsName, HashSet<MethodBase> excludes, List<Type> valueTypeBinders) { StringBuilder sb = new StringBuilder(); bool isMultiArr = type.IsArray && type.GetArrayRank() > 1; int idx = 0; foreach (var i in methods) { if (excludes != null && excludes.Contains(i)) continue; if (type.ShouldSkipMethod(i)) continue; bool isProperty = i.IsSpecialName; var param = i.GetParameters(); int paramCnt = param.Length; if (!i.IsStatic) paramCnt++; sb.AppendLine(string.Format(" static StackObject* {0}_{1}(ILIntepreter __intp, StackObject* __esp, IList<object> __mStack, CLRMethod __method, bool isNewObj)", i.Name, idx)); sb.AppendLine(" {"); sb.AppendLine(" ILRuntime.Runtime.Enviorment.AppDomain __domain = __intp.AppDomain;"); if (param.Length != 0 || !i.IsStatic) sb.AppendLine(" StackObject* ptr_of_this_method;"); sb.AppendLine(string.Format(" StackObject* __ret = ILIntepreter.Minus(__esp, {0});", paramCnt)); sb.AppendLine(); for (int j = param.Length; j > 0; j--) { var p = param[j - 1]; sb.AppendLine(string.Format(" ptr_of_this_method = ILIntepreter.Minus(__esp, {0});", param.Length - j + 1)); string clsName, realClsName; bool isByRef; p.ParameterType.GetClassName(out clsName, out realClsName, out isByRef); if (p.ParameterType.IsValueType && !p.ParameterType.IsPrimitive && valueTypeBinders != null && valueTypeBinders.Contains(p.ParameterType)) { if (isMultiArr) sb.AppendLine(string.Format(" {0} a{1} = new {0}();", realClsName, j)); else sb.AppendLine(string.Format(" {0} @{1} = new {0}();", realClsName, p.Name)); sb.AppendLine(string.Format(" if (ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder != null) {{", clsName)); if (isMultiArr) sb.AppendLine(string.Format(" a{0} = ILRuntime.Runtime.Generated.CLRBindings.s_{1}_Binder.ParseValue (__intp, ptr_of_this_method, __mStack);", j, clsName)); else sb.AppendLine(string.Format(" @{0} = ILRuntime.Runtime.Generated.CLRBindings.s_{1}_Binder.ParseValue (__intp, ptr_of_this_method, __mStack);", p.Name, clsName)); sb.AppendLine(" } else {"); if (isByRef) sb.AppendLine(" ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);"); if (isMultiArr) sb.AppendLine(string.Format(" a{0} = {1};", j, p.ParameterType.GetRetrieveValueCode(realClsName))); else sb.AppendLine(string.Format(" @{0} = {1};", p.Name, p.ParameterType.GetRetrieveValueCode(realClsName))); if (!isByRef && !p.ParameterType.IsPrimitive) sb.AppendLine(" __intp.Free(ptr_of_this_method);"); sb.AppendLine(" }"); } else { if (isByRef) sb.AppendLine(" ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);"); if (isMultiArr) sb.AppendLine(string.Format(" {0} a{1} = {2};", realClsName, j, p.ParameterType.GetRetrieveValueCode(realClsName))); else sb.AppendLine(string.Format(" {0} @{1} = {2};", realClsName, p.Name, p.ParameterType.GetRetrieveValueCode(realClsName))); if (!isByRef && !p.ParameterType.IsPrimitive) sb.AppendLine(" __intp.Free(ptr_of_this_method);"); } sb.AppendLine(); } if (!i.IsStatic) { sb.AppendLine(string.Format(" ptr_of_this_method = ILIntepreter.Minus(__esp, {0});", paramCnt)); if (type.IsPrimitive) sb.AppendLine(string.Format(" {0} instance_of_this_method = GetInstance(__domain, ptr_of_this_method, __mStack);", typeClsName)); else if (type.IsValueType && !type.IsPrimitive && valueTypeBinders != null && valueTypeBinders.Contains(type)) { string clsName, realClsName; bool isByRef; type.GetClassName(out clsName, out realClsName, out isByRef); sb.AppendLine(string.Format(" {0} instance_of_this_method = new {0}();", realClsName)); sb.AppendLine(string.Format(" if (ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder != null) {{", clsName)); sb.AppendLine(string.Format(" instance_of_this_method = ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder.ParseValue (__intp, ptr_of_this_method, __mStack);", clsName)); sb.AppendLine(" } else {"); if (type.IsValueType) sb.AppendLine(" ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);"); sb.AppendLine(string.Format(" instance_of_this_method = {0};", type.GetRetrieveValueCode(typeClsName))); if (!type.IsValueType) sb.AppendLine(" __intp.Free(ptr_of_this_method);"); sb.AppendLine(" }"); } else { if (type.IsValueType) sb.AppendLine(" ptr_of_this_method = ILIntepreter.GetObjectAndResolveReference(ptr_of_this_method);"); sb.AppendLine(string.Format(" {0} instance_of_this_method = {1};", typeClsName, type.GetRetrieveValueCode(typeClsName))); if (!type.IsValueType) sb.AppendLine(" __intp.Free(ptr_of_this_method);"); } } sb.AppendLine(); if (i.ReturnType != typeof(void)) { sb.Append(" var result_of_this_method = "); } else sb.Append(" "); string genericArguments = ""; if (i.IsGenericMethod) { var p = i.GetGenericArguments(); StringBuilder sb2 = new StringBuilder(); bool first = true; sb2.Append('<'); foreach (var j in p) { if (first) first = false; else sb2.Append(", "); string clsName, realClsName; bool isByRef; j.GetClassName(out clsName, out realClsName, out isByRef); sb2.Append(realClsName); } sb2.Append('>'); genericArguments = sb2.ToString(); } if (i.IsStatic) { if (isProperty) { string[] t = new string[2]; int firstUnderlineIndex = i.Name.IndexOf("_"); t[0] = i.Name.Substring(0, firstUnderlineIndex); t[1] = i.Name.Substring(firstUnderlineIndex + 1); string propType = t[0]; if (propType == "get") { bool isIndexer = param.Length > 0; if (isIndexer) { sb.AppendLine(string.Format("{1}[{0}];", param[0].Name, typeClsName)); } else sb.AppendLine(string.Format("{1}.{0};", t[1], typeClsName)); } else if (propType == "set") { bool isIndexer = param.Length > 1; if (isIndexer) { sb.AppendLine(string.Format("{2}[{0}] = {1};", param[0].Name, param[1].Name, typeClsName)); } else sb.AppendLine(string.Format("{2}.{0} = {1};", t[1], param[0].Name, typeClsName)); } else if (propType == "op") { switch (t[1]) { case "Equality": sb.AppendLine(string.Format("{0} == {1};", param[0].Name, param[1].Name)); break; case "Inequality": sb.AppendLine(string.Format("{0} != {1};", param[0].Name, param[1].Name)); break; case "Addition": sb.AppendLine(string.Format("{0} + {1};", param[0].Name, param[1].Name)); break; case "Subtraction": sb.AppendLine(string.Format("{0} - {1};", param[0].Name, param[1].Name)); break; case "Multiply": sb.AppendLine(string.Format("{0} * {1};", param[0].Name, param[1].Name)); break; case "Division": sb.AppendLine(string.Format("{0} / {1};", param[0].Name, param[1].Name)); break; case "GreaterThan": sb.AppendLine(string.Format("{0} > {1};", param[0].Name, param[1].Name)); break; case "GreaterThanOrEqual": sb.AppendLine(string.Format("{0} >= {1};", param[0].Name, param[1].Name)); break; case "LessThan": sb.AppendLine(string.Format("{0} < {1};", param[0].Name, param[1].Name)); break; case "LessThanOrEqual": sb.AppendLine(string.Format("{0} <= {1};", param[0].Name, param[1].Name)); break; case "UnaryNegation": sb.AppendLine(string.Format("-{0};", param[0].Name)); break; case "Implicit": case "Explicit": { string clsName, realClsName; bool isByRef; i.ReturnType.GetClassName(out clsName, out realClsName, out isByRef); sb.AppendLine(string.Format("({1}){0};", param[0].Name, realClsName)); } break; default: throw new NotImplementedException(i.Name); } } else throw new NotImplementedException(); } else { sb.Append(string.Format("{0}.{1}{2}(", typeClsName, i.Name, genericArguments)); param.AppendParameters(sb); sb.AppendLine(");"); } } else { if (isProperty) { string[] t = new string[2]; int firstUnderlineIndex = i.Name.IndexOf("_"); t[0] = i.Name.Substring(0, firstUnderlineIndex); t[1] = i.Name.Substring(firstUnderlineIndex + 1); string propType = t[0]; if (propType == "get") { bool isIndexer = param.Length > 0; if (isIndexer) { sb.AppendLine(string.Format("instance_of_this_method[{0}];", param[0].Name)); } else sb.AppendLine(string.Format("instance_of_this_method.{0};", t[1])); } else if (propType == "set") { bool isIndexer = param.Length > 1; if (isIndexer) { sb.AppendLine(string.Format("instance_of_this_method[{0}] = {1};", param[0].Name, param[1].Name)); } else sb.AppendLine(string.Format("instance_of_this_method.{0} = {1};", t[1], param[0].Name)); } else throw new NotImplementedException(); } else if (isMultiArr) { if (i.Name == "Get") { sb.Append("instance_of_this_method["); param.AppendParameters(sb, true); sb.AppendLine("];"); } else { sb.Append("instance_of_this_method["); param.AppendParameters(sb, true, 1); sb.Append("]"); sb.Append(" = a"); sb.Append(param.Length); sb.AppendLine(";"); } } else { sb.Append(string.Format("instance_of_this_method.{0}{1}(", i.Name, genericArguments)); param.AppendParameters(sb); sb.AppendLine(");"); } } sb.AppendLine(); if (!i.IsStatic && type.IsValueType && !type.IsPrimitive)//need to write back value type instance { if (valueTypeBinders != null && valueTypeBinders.Contains(type)) { string clsName, realClsName; bool isByRef; type.GetClassName(out clsName, out realClsName, out isByRef); sb.AppendLine(string.Format(" if (ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder != null) {{", clsName)); sb.AppendLine(string.Format(" ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder.WriteBackValue(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);", clsName)); sb.AppendLine(" } else {"); sb.AppendLine(" WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);"); sb.AppendLine(" }"); } else { sb.AppendLine(" WriteBackInstance(__domain, ptr_of_this_method, __mStack, ref instance_of_this_method);"); } sb.AppendLine(); } //Ref/Out for (int j = param.Length; j > 0; j--) { var p = param[j - 1]; if (!p.ParameterType.IsByRef) continue; string clsName, realClsName; bool isByRef; p.ParameterType.GetElementType().GetClassName(out clsName, out realClsName, out isByRef); sb.AppendLine(string.Format(" ptr_of_this_method = ILIntepreter.Minus(__esp, {0});", param.Length - j + 1)); sb.AppendLine(@" switch(ptr_of_this_method->ObjectType) { case ObjectTypes.StackObjectReference: { var ___dst = *(StackObject**)&ptr_of_this_method->Value;"); if (p.ParameterType.IsValueType && !p.ParameterType.IsPrimitive && valueTypeBinders != null && valueTypeBinders.Contains(p.ParameterType)) { sb.AppendLine(string.Format(" if (ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder != null) {{", clsName)); sb.AppendLine(string.Format(" ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder.WriteBackValue(__domain, ptr_of_this_method, __mStack, ref {1});", clsName, p.Name)); sb.AppendLine(" } else {"); p.ParameterType.GetElementType().GetRefWriteBackValueCode(sb, p.Name); sb.AppendLine(" }"); } else { p.ParameterType.GetElementType().GetRefWriteBackValueCode(sb, p.Name); } sb.Append(@" } break; case ObjectTypes.FieldReference: { var ___obj = __mStack[ptr_of_this_method->Value]; if(___obj is ILTypeInstance) { ((ILTypeInstance)___obj)[ptr_of_this_method->ValueLow] = "); sb.Append(p.Name); sb.Append(@"; } else { var ___type = __domain.GetType(___obj.GetType()) as CLRType; ___type.SetFieldValue(ptr_of_this_method->ValueLow, ref ___obj, "); sb.Append(p.Name); sb.Append(@"); } } break; case ObjectTypes.StaticFieldReference: { var ___type = __domain.GetType(ptr_of_this_method->Value); if(___type is ILType) { ((ILType)___type).StaticInstance[ptr_of_this_method->ValueLow] = "); sb.Append(p.Name); sb.Append(@"; } else { ((CLRType)___type).SetStaticFieldValue(ptr_of_this_method->ValueLow, "); sb.Append(p.Name); sb.Append(@"); } } break; case ObjectTypes.ArrayReference: { var instance_of_arrayReference = __mStack[ptr_of_this_method->Value] as "); sb.Append(realClsName); sb.Append(@"[]; instance_of_arrayReference[ptr_of_this_method->ValueLow] = "); sb.Append(p.Name); sb.AppendLine(@"; } break; }"); sb.AppendLine(); } if (i.ReturnType != typeof(void)) { if (i.ReturnType.IsValueType && !i.ReturnType.IsPrimitive && valueTypeBinders != null && valueTypeBinders.Contains(type)) { string clsName, realClsName; bool isByRef; i.ReturnType.GetClassName(out clsName, out realClsName, out isByRef); sb.AppendLine(string.Format(" if (ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder != null) {{", clsName)); sb.AppendLine(string.Format(" ILRuntime.Runtime.Generated.CLRBindings.s_{0}_Binder.PushValue(ref result_of_this_method, __intp, __ret, __mStack);", clsName)); sb.AppendLine(" return __ret + 1;"); sb.AppendLine(" } else {"); i.ReturnType.GetReturnValueCode(sb); sb.AppendLine(" }"); } else { i.ReturnType.GetReturnValueCode(sb); } } else sb.AppendLine(" return __ret;"); sb.AppendLine(" }"); sb.AppendLine(); idx++; } return sb.ToString(); } } }
50.104972
219
0.404528
[ "MIT" ]
AlunWorker/ET-
Unity/Assets/ThirdParty/ILRuntime/ILRuntime/Runtime/CLRBinding/MethodBindingGenerator.cs
27,209
C#
using System.Reflection; 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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NPS.Core")] [assembly: AssemblyTrademark("")] // 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("0fa75a5b-ab83-4fd0-b545-279774c01e87")]
41
84
0.775353
[ "MIT" ]
leonardo-buta/automated-nps
aspnet-core/src/NPS.Core/Properties/AssemblyInfo.cs
781
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public interface Buyable { int Price{ get; set; } }
17
33
0.757353
[ "MIT" ]
unagi11/project21
Assets/Scripts/Model/Buyable.cs
138
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.DeploymentManager.V20180901Preview { /// <summary> /// The resource representation of a service topology. /// </summary> public partial class ServiceTopology : Pulumi.CustomResource { /// <summary> /// The resource Id of the artifact source that contains the artifacts that can be referenced in the service units. /// </summary> [Output("artifactSourceId")] public Output<string?> ArtifactSourceId { get; private set; } = null!; /// <summary> /// The geo-location where the resource lives /// </summary> [Output("location")] public Output<string> Location { get; private set; } = null!; /// <summary> /// The name of the resource /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a ServiceTopology 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 ServiceTopology(string name, ServiceTopologyArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:deploymentmanager/v20180901preview:ServiceTopology", name, args ?? new ServiceTopologyArgs(), MakeResourceOptions(options, "")) { } private ServiceTopology(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:deploymentmanager/v20180901preview:ServiceTopology", 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:deploymentmanager/v20191101preview:ServiceTopology"}, }, }; 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 ServiceTopology 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 ServiceTopology Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new ServiceTopology(name, id, options); } } public sealed class ServiceTopologyArgs : Pulumi.ResourceArgs { /// <summary> /// The resource Id of the artifact source that contains the artifacts that can be referenced in the service units. /// </summary> [Input("artifactSourceId")] public Input<string>? ArtifactSourceId { get; set; } /// <summary> /// The geo-location where the resource lives /// </summary> [Input("location", required: true)] public Input<string> Location { get; set; } = null!; /// <summary> /// The name of the resource group. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the service topology . /// </summary> [Input("serviceTopologyName", required: true)] public Input<string> ServiceTopologyName { 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; } public ServiceTopologyArgs() { } } }
38.970803
161
0.60236
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/DeploymentManager/V20180901Preview/ServiceTopology.cs
5,339
C#
using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Text; using M8OU.Models; namespace M8OU.Data { public class ApplicationDbContext : IdentityDbContext { public DbSet<FormHistory> FormHistories { get; set; } public DbSet<Report> Reports { get; set; } public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } } }
24.809524
83
0.710173
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
NorthstarWang/GoogleFormSubmitter
Data/ApplicationDbContext.cs
521
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("WildtabAlt")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WildtabAlt")] [assembly: AssemblyCopyright("Copyright © 2020")] [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("2a51480c-712d-4ede-bdf8-77f5c671bbde")] // 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.513514
84
0.747118
[ "MIT" ]
krypt-lynx/PawnTableGrouped
Source/PawnTableGrouped/Properties/AssemblyInfo.cs
1,391
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101 { using Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Runtime.PowerShell; /// <summary>Authentication configuration information</summary> [System.ComponentModel.TypeConverter(typeof(ServiceAuthenticationConfigurationInfoTypeConverter))] public partial class ServiceAuthenticationConfigurationInfo { /// <summary> /// <c>AfterDeserializeDictionary</c> will be called after the deserialization has finished, allowing customization of the /// object before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> partial void AfterDeserializeDictionary(global::System.Collections.IDictionary content); /// <summary> /// <c>AfterDeserializePSObject</c> will be called after the deserialization has finished, allowing customization of the object /// before it is returned. Implement this method in a partial class to enable this behavior /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> partial void AfterDeserializePSObject(global::System.Management.Automation.PSObject content); /// <summary> /// <c>BeforeDeserializeDictionary</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializeDictionary(global::System.Collections.IDictionary content, ref bool returnNow); /// <summary> /// <c>BeforeDeserializePSObject</c> will be called before the deserialization has commenced, allowing complete customization /// of the object before it is deserialized. /// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter. /// Implement this method in a partial class to enable this behavior. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return /// instantly.</param> partial void BeforeDeserializePSObject(global::System.Management.Automation.PSObject content, ref bool returnNow); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.ServiceAuthenticationConfigurationInfo" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfo" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfo DeserializeFromDictionary(global::System.Collections.IDictionary content) { return new ServiceAuthenticationConfigurationInfo(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.ServiceAuthenticationConfigurationInfo" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> /// <returns> /// an instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfo" /// />. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfo DeserializeFromPSObject(global::System.Management.Automation.PSObject content) { return new ServiceAuthenticationConfigurationInfo(content); } /// <summary> /// Creates a new instance of <see cref="ServiceAuthenticationConfigurationInfo" />, deserializing the content from a json /// string. /// </summary> /// <param name="jsonText">a string containing a JSON serialized instance of this model.</param> /// <returns>an instance of the <see cref="className" /> model class.</returns> public static Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfo FromJsonString(string jsonText) => FromJson(Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Runtime.Json.JsonNode.Parse(jsonText)); /// <summary> /// Deserializes a <see cref="global::System.Collections.IDictionary" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.ServiceAuthenticationConfigurationInfo" /// />. /// </summary> /// <param name="content">The global::System.Collections.IDictionary content that should be used.</param> internal ServiceAuthenticationConfigurationInfo(global::System.Collections.IDictionary content) { bool returnNow = false; BeforeDeserializeDictionary(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("Authority")) { ((Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfoInternal)this).Authority = (string) content.GetValueForProperty("Authority",((Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfoInternal)this).Authority, global::System.Convert.ToString); } if (content.Contains("Audience")) { ((Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfoInternal)this).Audience = (string) content.GetValueForProperty("Audience",((Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfoInternal)this).Audience, global::System.Convert.ToString); } if (content.Contains("SmartProxyEnabled")) { ((Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfoInternal)this).SmartProxyEnabled = (bool?) content.GetValueForProperty("SmartProxyEnabled",((Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfoInternal)this).SmartProxyEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); } AfterDeserializeDictionary(content); } /// <summary> /// Deserializes a <see cref="global::System.Management.Automation.PSObject" /> into a new instance of <see cref="Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.ServiceAuthenticationConfigurationInfo" /// />. /// </summary> /// <param name="content">The global::System.Management.Automation.PSObject content that should be used.</param> internal ServiceAuthenticationConfigurationInfo(global::System.Management.Automation.PSObject content) { bool returnNow = false; BeforeDeserializePSObject(content, ref returnNow); if (returnNow) { return; } // actually deserialize if (content.Contains("Authority")) { ((Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfoInternal)this).Authority = (string) content.GetValueForProperty("Authority",((Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfoInternal)this).Authority, global::System.Convert.ToString); } if (content.Contains("Audience")) { ((Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfoInternal)this).Audience = (string) content.GetValueForProperty("Audience",((Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfoInternal)this).Audience, global::System.Convert.ToString); } if (content.Contains("SmartProxyEnabled")) { ((Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfoInternal)this).SmartProxyEnabled = (bool?) content.GetValueForProperty("SmartProxyEnabled",((Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Models.Api20211101.IServiceAuthenticationConfigurationInfoInternal)this).SmartProxyEnabled, (__y)=> (bool) global::System.Convert.ChangeType(__y, typeof(bool))); } AfterDeserializePSObject(content); } /// <summary>Serializes this instance to a json string.</summary> /// <returns>a <see cref="System.String" /> containing this model serialized to JSON text.</returns> public string ToJsonString() => ToJson(null, Microsoft.Azure.PowerShell.Cmdlets.HealthcareApis.Runtime.SerializationMode.IncludeAll)?.ToString(); } /// Authentication configuration information [System.ComponentModel.TypeConverter(typeof(ServiceAuthenticationConfigurationInfoTypeConverter))] public partial interface IServiceAuthenticationConfigurationInfo { } }
68.534161
431
0.706181
[ "MIT" ]
yifanz0/azure-powershell
src/HealthcareApis/generated/api/Models/Api20211101/ServiceAuthenticationConfigurationInfo.PowerShell.cs
10,874
C#
using System.Net.Http.Headers; namespace RabbitRelink.Serialization.Abstractions; public interface ISerializer { Task<byte[]?> SerializeAsync<T>(T? value, CancellationToken token = default) where T : class; Task<byte[]?> SerializeAsync(object? value, CancellationToken token = default); MediaTypeHeaderValue MediaType { get; } } public interface ISerializer<T> where T : class? { Task<byte[]?> SerializeAsync(T data, CancellationToken token = default); MediaTypeHeaderValue MediaType { get; } }
31.470588
98
0.721495
[ "MIT" ]
ijsgaus/rabbit-relink
src/RabbitRelink.Serialization.Abstractions/ISerializer.cs
521
C#
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon licenses this file to you under // the Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. // using System; using System.Collections.Generic; using System.Reflection; using Remotion.TypePipe.MutableReflection; using Remotion.TypePipe.MutableReflection.Implementation; namespace Remotion.TypePipe.Development.UnitTesting.ObjectMothers.MutableReflection.Implementation { public class TestableCustomPropertyInfo : CustomPropertyInfo { public TestableCustomPropertyInfo ( CustomType declaringType, string name, PropertyAttributes attributes, CustomMethodInfo getMethod, CustomMethodInfo setMethod) : base (declaringType, name, attributes, getMethod, setMethod) { } public IEnumerable<ICustomAttributeData> CustomAttributeDatas; public ParameterInfo[] IndexParameters; public override IEnumerable<ICustomAttributeData> GetCustomAttributeData () { return CustomAttributeDatas; } public override ParameterInfo[] GetIndexParameters () { return IndexParameters; } } }
34.64
98
0.750577
[ "ECL-2.0", "Apache-2.0" ]
bubdm/TypePipe
Development/UnitTesting/ObjectMothers/MutableReflection/Implementation/TestableCustomPropertyInfo.cs
1,732
C#
#pragma warning disable 0618 using System; using System.Linq; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEditor.EditorTools; using UnityEditor.Experimental.Rendering.Universal.Path2D.GUIFramework; using UnityObject = UnityEngine.Object; #if !UNITY_2020_2_OR_NEWER using ToolManager = UnityEditor.EditorTools.EditorTools; #endif namespace UnityEditor.Experimental.Rendering.Universal.Path2D { internal static class PathEditorToolContents { internal static readonly GUIContent shapeToolIcon = IconContent("ShapeTool", "Unlocks the shape to allow editing in the Scene View."); internal static readonly GUIContent shapeToolPro = IconContent("ShapeToolPro", "Unlocks the shape to allow editing in the Scene View."); internal static GUIContent IconContent(string name, string tooltip = null) { return new GUIContent(Resources.Load<Texture>(name), tooltip); } public static GUIContent icon { get { if (EditorGUIUtility.isProSkin) return shapeToolPro; return shapeToolIcon; } } } internal interface IDuringSceneGuiTool { void DuringSceneGui(SceneView sceneView); bool IsAvailable(); } [InitializeOnLoad] internal class EditorToolManager { private static List<IDuringSceneGuiTool> m_Tools = new List<IDuringSceneGuiTool>(); static EditorToolManager() { SceneView.duringSceneGui += DuringSceneGui; } internal static void Add(IDuringSceneGuiTool tool) { if (!m_Tools.Contains(tool) && tool is EditorTool) m_Tools.Add(tool); } internal static void Remove(IDuringSceneGuiTool tool) { if (m_Tools.Contains(tool)) m_Tools.Remove(tool); } internal static bool IsActiveTool<T>() where T : EditorTool { return ToolManager.activeToolType.Equals(typeof(T)); } internal static bool IsAvailable<T>() where T : EditorTool { var tool = GetEditorTool<T>(); if (tool != null) return tool.IsAvailable(); return false; } internal static T GetEditorTool<T>() where T : EditorTool { foreach (var tool in m_Tools) { if (tool.GetType().Equals(typeof(T))) return tool as T; } return null; } private static void DuringSceneGui(SceneView sceneView) { foreach (var tool in m_Tools) { if (tool.IsAvailable() && ToolManager.IsActiveTool(tool as EditorTool)) tool.DuringSceneGui(sceneView); } } } internal abstract class PathEditorTool<T> : EditorTool, IDuringSceneGuiTool where T : ScriptablePath { private Dictionary<UnityObject, T> m_Paths = new Dictionary<UnityObject, T>(); private IGUIState m_GUIState = new GUIState(); private Dictionary<UnityObject, GUISystem> m_GUISystems = new Dictionary<UnityObject, GUISystem>(); private Dictionary<UnityObject, SerializedObject> m_SerializedObjects = new Dictionary<UnityObject, SerializedObject>(); private MultipleEditablePathController m_Controller = new MultipleEditablePathController(); private PointRectSelector m_RectSelector = new PointRectSelector(); private bool m_IsActive = false; internal T[] paths { get { return m_Paths.Values.ToArray(); } } public bool enableSnapping { get { return m_Controller.enableSnapping; } set { m_Controller.enableSnapping = value; } } public override GUIContent toolbarIcon { get { return PathEditorToolContents.icon; } } public override bool IsAvailable() { return targets.Count() > 0; } public T GetPath(UnityObject targetObject) { var path = default(T); m_Paths.TryGetValue(targetObject, out path); return path; } public void SetPath(UnityObject target) { var path = GetPath(target); path.localToWorldMatrix = Matrix4x4.identity; var undoName = Undo.GetCurrentGroupName(); var serializedObject = GetSerializedObject(target); serializedObject.UpdateIfRequiredOrScript(); SetShape(path, serializedObject); Undo.SetCurrentGroupName(undoName); } private void RepaintInspectors() { var editorWindows = Resources.FindObjectsOfTypeAll<EditorWindow>(); foreach (var editorWindow in editorWindows) { if (editorWindow.titleContent.text == "Inspector") editorWindow.Repaint(); } } private void OnEnable() { m_IsActive = false; EditorToolManager.Add(this); SetupRectSelector(); HandleActivation(); ToolManager.activeToolChanged += HandleActivation; } private void OnDestroy() { EditorToolManager.Remove(this); ToolManager.activeToolChanged -= HandleActivation; UnregisterCallbacks(); } private void HandleActivation() { if (m_IsActive == false && ToolManager.IsActiveTool(this)) Activate(); else if (m_IsActive) Deactivate(); } private void Activate() { m_IsActive = true; RegisterCallbacks(); InitializeCache(); OnActivate(); } private void Deactivate() { OnDeactivate(); DestroyCache(); UnregisterCallbacks(); m_IsActive = false; } private void RegisterCallbacks() { UnregisterCallbacks(); Selection.selectionChanged += SelectionChanged; EditorApplication.playModeStateChanged += PlayModeStateChanged; Undo.undoRedoPerformed += UndoRedoPerformed; } private void UnregisterCallbacks() { Selection.selectionChanged -= SelectionChanged; EditorApplication.playModeStateChanged -= PlayModeStateChanged; Undo.undoRedoPerformed -= UndoRedoPerformed; } private void DestroyCache() { foreach (var pair in m_Paths) { var path = pair.Value; if (path != null) { Undo.ClearUndo(path); UnityObject.DestroyImmediate(path); } } m_Paths.Clear(); m_Controller.ClearPaths(); m_GUISystems.Clear(); m_SerializedObjects.Clear(); } private void UndoRedoPerformed() { ForEachTarget((target) => { var path = GetPath(target); if (!path.modified) InitializePath(target); }); } private void SelectionChanged() { InitializeCache(); } private void PlayModeStateChanged(PlayModeStateChange stateChange) { if (stateChange == PlayModeStateChange.EnteredEditMode) EditorApplication.delayCall += () => { InitializeCache(); }; //HACK: At this point target is null. Let's wait to next frame to refresh. } private void SetupRectSelector() { m_RectSelector.onSelectionBegin = BeginSelection; m_RectSelector.onSelectionChanged = UpdateSelection; m_RectSelector.onSelectionEnd = EndSelection; } private void ForEachTarget(Action<UnityObject> action) { foreach (var target in targets) { if (target == null) continue; action(target); } } private void InitializeCache() { m_Controller.ClearPaths(); ForEachTarget((target) => { var path = GetOrCreatePath(target); var pointCount = path.pointCount; InitializePath(target); if (pointCount != path.pointCount) path.selection.Clear(); CreateGUISystem(target); m_Controller.AddPath(path); }); } private void InitializePath(UnityObject target) { IShape shape = null; ControlPoint[] controlPoints = null; try { shape = GetShape(target); controlPoints = shape.ToControlPoints(); } catch (Exception e) { Debug.LogError(e.Message); } var path = GetPath(target); path.Clear(); if (shape != null && controlPoints != null) { path.localToWorldMatrix = Matrix4x4.identity; path.shapeType = shape.type; path.isOpenEnded = shape.isOpenEnded; foreach (var controlPoint in controlPoints) path.AddPoint(controlPoint); } Initialize(path, GetSerializedObject(target)); } private T GetOrCreatePath(UnityObject targetObject) { var path = GetPath(targetObject); if (path == null) { path = ScriptableObject.CreateInstance<T>(); path.owner = targetObject; m_Paths[targetObject] = path; } return path; } private GUISystem GetGUISystem(UnityObject target) { GUISystem guiSystem; m_GUISystems.TryGetValue(target, out guiSystem); return guiSystem; } private void CreateGUISystem(UnityObject target) { var guiSystem = new GUISystem(m_GUIState); var view = new EditablePathView(); view.controller = m_Controller; view.Install(guiSystem); m_GUISystems[target] = guiSystem; } private SerializedObject GetSerializedObject(UnityObject target) { var serializedObject = default(SerializedObject); if (!m_SerializedObjects.TryGetValue(target, out serializedObject)) { serializedObject = new SerializedObject(target); m_SerializedObjects[target] = serializedObject; } return serializedObject; } void IDuringSceneGuiTool.DuringSceneGui(SceneView sceneView) { if (m_GUIState.eventType == EventType.Layout) m_Controller.ClearClosestPath(); m_RectSelector.OnGUI(); bool changed = false; ForEachTarget((target) => { var path = GetPath(target); if (path != null) { path.localToWorldMatrix = GetLocalToWorldMatrix(target); path.forward = GetForward(target); path.up = GetUp(target); path.right = GetRight(target); m_Controller.editablePath = path; using (var check = new EditorGUI.ChangeCheckScope()) { GetGUISystem(target).OnGUI(); OnCustomGUI(path); changed |= check.changed; } } }); if (changed) { SetShapes(); RepaintInspectors(); } } private void BeginSelection(ISelector<Vector3> selector, bool isAdditive) { m_Controller.RegisterUndo("Selection"); if (isAdditive) { ForEachTarget((target) => { var path = GetPath(target); path.selection.BeginSelection(); }); } else { UpdateSelection(selector); } } private void UpdateSelection(ISelector<Vector3> selector) { var repaintInspectors = false; ForEachTarget((target) => { var path = GetPath(target); repaintInspectors |= path.Select(selector); }); if (repaintInspectors) RepaintInspectors(); } private void EndSelection(ISelector<Vector3> selector) { ForEachTarget((target) => { var path = GetPath(target); path.selection.EndSelection(true); }); } internal void SetShapes() { ForEachTarget((target) => { SetPath(target); }); } private Transform GetTransform(UnityObject target) { return (target as Component).transform; } private Matrix4x4 GetLocalToWorldMatrix(UnityObject target) { return GetTransform(target).localToWorldMatrix; } private Vector3 GetForward(UnityObject target) { return GetTransform(target).forward; } private Vector3 GetUp(UnityObject target) { return GetTransform(target).up; } private Vector3 GetRight(UnityObject target) { return GetTransform(target).right; } protected abstract IShape GetShape(UnityObject target); protected virtual void Initialize(T path, SerializedObject serializedObject) {} protected abstract void SetShape(T path, SerializedObject serializedObject); protected virtual void OnActivate() {} protected virtual void OnDeactivate() {} protected virtual void OnCustomGUI(T path) {} } } #pragma warning restore 0618
28.858
151
0.543142
[ "CC0-1.0" ]
CemCkrc/URP_BURGER_SHADER
Library/PackageCache/com.unity.render-pipelines.universal@11.0.0/Editor/2D/ShapeEditor/EditorTool/PathEditorTool.cs
14,429
C#
 namespace NumbersN1 { using System; class StartUp { static void Main(string[] args) { int num = int.Parse(Console.ReadLine()); for (int i = num; i >= 1; i--) { Console.WriteLine(i); } } } }
16.277778
52
0.423208
[ "MIT" ]
beinsaduno/SoftUni-Software-Engineering
C#/M01C#ProgrammingBasics/L04ForLoop/Lab/E02NumbersN1/StartUp.cs
295
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über die folgenden // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die mit einer Assembly verknüpft sind. [assembly: AssemblyTitle("gView.DataSources.MSSqlSpatial.UI")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("gView")] [assembly: AssemblyProduct("gView.DataSources.MSSqlSpatial.UI")] [assembly: AssemblyCopyright("Copyright © gView 2006")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Durch Festlegen von ComVisible auf "false" werden die Typen in dieser Assembly unsichtbar // für COM-Komponenten. Wenn Sie auf einen Typ in dieser Assembly von // COM zugreifen müssen, legen Sie das ComVisible-Attribut für diesen Typ auf "true" fest. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("0323ccac-53ea-44c1-a8d1-476aaf9ea6dc")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Revisions- und Buildnummern // übernehmen, indem Sie "*" eingeben: [assembly: AssemblyVersion("4.0.0.0")] [assembly: AssemblyFileVersion("4.0.0.0")]
41.638889
106
0.767845
[ "MIT" ]
chandusekhar/gViewGisOS
gView.DataSources.PostGIS.UI/Properties/AssemblyInfo.cs
1,517
C#
//////////////////////////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2009, Daniel Kollmann // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, are permitted // provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this list of conditions // and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, this list of // conditions and the following disclaimer in the documentation and/or other materials provided // with the distribution. // // - Neither the name of Daniel Kollmann nor the names of its contributors may be used to endorse // or promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND // FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY // WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // The above software in this distribution may have been modified by THL A29 Limited ("Tencent Modifications"). // // All Tencent Modifications are Copyright (C) 2015 THL A29 Limited. ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Drawing.Drawing2D; using Behaviac.Design.Nodes; namespace Behaviac.Design { public class NodeViewDataStyled : NodeViewData { private readonly static Pen __defaultCurrentBorderPen = new Pen(Brushes.GreenYellow, 3.0f); protected static Pen DefaultCurrentBorderPen { get { __defaultCurrentBorderPen.DashStyle = DashStyle.Dash; return __defaultCurrentBorderPen; } } protected readonly static Pen __defaultSelectedBorderPen = new Pen(Brushes.GreenYellow, 5.0f); protected readonly static Pen __highlightedBorderPen = new Pen(Brushes.Gold, 4.0f); protected readonly static Pen __updatedBorderPen = new Pen(Brushes.Gray, 4.0f); protected readonly static Pen __prefabBorderPen = new Pen(Brushes.Linen, 2.0f); protected readonly static Font __defaultLabelFont = new Font("Calibri,Arial", 8.0f, FontStyle.Regular); protected readonly static Font __profileLabelFont = new Font("Calibri,Arial", 6.0f, FontStyle.Regular); protected readonly static Font __profileLabelBoldFont = new Font("Calibri,Arial", 6.0f, FontStyle.Bold); public NodeViewDataStyled(NodeViewData parent, BehaviorNode rootBehavior, Node node, Pen borderPen, Brush backgroundBrush, string label, string description, int minWidth = 120, int minHeight = 35) : base(parent, rootBehavior, node, NodeShape.RoundedRectangle, new Style(backgroundBrush, null, Brushes.White), new Style(null, DefaultCurrentBorderPen, null), new Style(null, __defaultSelectedBorderPen, null), new Style(GetDraggedBrush(backgroundBrush), null, null), new Style(null, __highlightedBorderPen, null), new Style(null, __updatedBorderPen, null), new Style(null, __prefabBorderPen, null), label, __defaultLabelFont, __profileLabelFont, __profileLabelBoldFont, minWidth, minHeight, description) { } public NodeViewDataStyled(NodeViewData parent, BehaviorNode rootBehavior, Node node, Pen borderPen, Brush backgroundBrush, Brush draggedBackgroundBrush, string label, string description, int minWidth = 120, int minHeight = 35) : base(parent, rootBehavior, node, NodeShape.RoundedRectangle, new Style(backgroundBrush, null, Brushes.White), new Style(null, DefaultCurrentBorderPen, null), new Style(null, __defaultSelectedBorderPen, null), new Style(draggedBackgroundBrush, null, null), new Style(null, __highlightedBorderPen, null), new Style(null, __updatedBorderPen, null), new Style(null, __prefabBorderPen, null), label, __defaultLabelFont, __profileLabelFont, __profileLabelBoldFont, minWidth, minHeight, description) { } } }
57.086957
236
0.652704
[ "BSD-3-Clause" ]
Manistein/behaviac
tools/designer/BehaviacDesignerBase/NodeViewData/NodeViewDataStyled.cs
5,252
C#
using System; using UnityEngine; using WEngine; [Serializable] public class ContainerData { // Constants public AssetContainerData Asset; // Editor-assignable instances public UiContainerData Ui; // Pure instances public SceneContainerData Scene = new SceneContainerData(); }
17.941176
63
0.734426
[ "MIT" ]
wishfuldroplet/unity-projecta
Assets/Sources/Modules/GameData/ContainerData.cs
307
C#
using System.Windows; using ErikEJ.SqlCeToolbox.Helpers; namespace ErikEJ.SqlCeToolbox.Dialogs { public partial class RenameDialog { public string NewName { get; set; } // ReSharper disable once UnusedAutoPropertyAccessor.Global public bool DbRename { get; set; } public RenameDialog(string tableName) { Telemetry.TrackPageView(nameof(RenameDialog)); InitializeComponent(); Background = VsThemes.GetWindowBackground(); Title = "Rename " + tableName; ServerName.Text = tableName; } private void SaveButton_Click(object sender, RoutedEventArgs e) { DialogResult = true; SaveSettings(); Close(); } private void SaveSettings() { NewName = ServerName.Text; } private void CancelButton_Click(object sender, RoutedEventArgs e) { Close(); } private void Window_Loaded(object sender, RoutedEventArgs e) { ServerName.Focus(); if (DbRename) { Title = "Rename Connection"; } } } }
24.836735
73
0.556286
[ "Apache-2.0" ]
BekoSan/SqlCeToolbox
src/GUI/SSMSToolbox/Dialogs/RenameDialog.xaml.cs
1,219
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using Microsoft.ML.Runtime; using Microsoft.ML.Runtime.CommandLine; using Microsoft.ML.Runtime.Data; using Microsoft.ML.Runtime.EntryPoints; using Microsoft.ML.Runtime.Training; using Newtonsoft.Json.Linq; [assembly: LoadableClass(typeof(void), typeof(OneVersusAllMacro), null, typeof(SignatureEntryPointModule), "OneVersusAllMacro")] namespace Microsoft.ML.Runtime.EntryPoints { /// <summary> /// This macro entrypoint implements OVA. /// </summary> public static class OneVersusAllMacro { public sealed class SubGraphOutput { [Argument(ArgumentType.Required, HelpText = "The predictor model for the subgraph exemplar.", SortOrder = 1)] public Var<IPredictorModel> Model; } public sealed class Arguments : LearnerInputBaseWithWeight { // This is the subgraph that describes how to train a model for submodel. It should // accept one IDataView input and output one IPredictorModel output. [Argument(ArgumentType.Required, HelpText = "The subgraph for the binary trainer used to construct the OVA learner. This should be a TrainBinary node.", SortOrder = 1)] public JArray Nodes; [Argument(ArgumentType.Required, HelpText = "The training subgraph output.", SortOrder = 2)] public SubGraphOutput OutputForSubGraph = new SubGraphOutput(); [Argument(ArgumentType.AtMostOnce, HelpText = "Use probabilities in OVA combiner", SortOrder = 3)] public bool UseProbabilities = true; } public sealed class Output { [TlcModule.Output(Desc = "The trained multiclass model", SortOrder = 1)] public IPredictorModel PredictorModel; } private static Tuple<List<EntryPointNode>, Var<IPredictorModel>> ProcessClass(IHostEnvironment env, int k, string label, Arguments input, EntryPointNode node) { var macroNodes = new List<EntryPointNode>(); // Convert label into T,F based on k. var remapper = new ML.Transforms.LabelIndicator { ClassIndex = k, Column = new[] { new ML.Transforms.LabelIndicatorTransformColumn { ClassIndex = k, Name = label, Source = label } }, Data = { VarName = node.GetInputVariable(nameof(input.TrainingData)).ToJson() } }; var exp = new Experiment(env); var remapperOutNode = exp.Add(remapper); var subNodes = EntryPointNode.ValidateNodes(env, node.Context, exp.GetNodes(), node.Catalog); macroNodes.AddRange(subNodes); // Parse the nodes in input.Nodes into a temporary run context. var subGraphRunContext = new RunContext(env); var subGraphNodes = EntryPointNode.ValidateNodes(env, subGraphRunContext, input.Nodes, node.Catalog); // Rename all the variables such that they don't conflict with the ones in the outer run context. var mapping = new Dictionary<string, string>(); bool foundOutput = false; Var<IPredictorModel> predModelVar = null; foreach (var entryPointNode in subGraphNodes) { // Rename variables in input/output maps, and in subgraph context. entryPointNode.RenameAllVariables(mapping); foreach (var kvp in mapping) subGraphRunContext.RenameContextVariable(kvp.Key, kvp.Value); // Grab a hold of output model from this subgraph. if (entryPointNode.GetOutputVariableName("PredictorModel") is string mvn) { predModelVar = new Var<IPredictorModel> { VarName = mvn }; foundOutput = true; } // Connect label remapper output to wherever training data was expected within the input graph. if (entryPointNode.GetInputVariable(nameof(input.TrainingData)) is VariableBinding vb) vb.Rename(remapperOutNode.OutputData.VarName); // Change node to use the main context. entryPointNode.SetContext(node.Context); } // Move the variables from the subcontext to the main context. node.Context.AddContextVariables(subGraphRunContext); // Make sure we found the output variable for this model. if (!foundOutput) throw new Exception("Invalid input graph. Does not output predictor model."); // Add training subgraph to our context. macroNodes.AddRange(subGraphNodes); return new Tuple<List<EntryPointNode>, Var<IPredictorModel>>(macroNodes, predModelVar); } private static int GetNumberOfClasses(IHostEnvironment env, Arguments input, out string label) { var host = env.Register("OVA Macro GetNumberOfClasses"); using (var ch = host.Start("OVA Macro GetNumberOfClasses")) { // RoleMappedData creation ISchema schema = input.TrainingData.Schema; label = TrainUtils.MatchNameOrDefaultOrNull(ch, schema, nameof(Arguments.LabelColumn), input.LabelColumn, DefaultColumnNames.Label); var feature = TrainUtils.MatchNameOrDefaultOrNull(ch, schema, nameof(Arguments.FeatureColumn), input.FeatureColumn, DefaultColumnNames.Features); var weight = TrainUtils.MatchNameOrDefaultOrNull(ch, schema, nameof(Arguments.WeightColumn), input.WeightColumn, DefaultColumnNames.Weight); // Get number of classes var data = new RoleMappedData(input.TrainingData, label, feature, null, weight); data.CheckMultiClassLabel(out var numClasses); return numClasses; } } [TlcModule.EntryPoint(Desc = "One-vs-All macro (OVA)", Name = "Models.OneVersusAll", XmlInclude = new[] { @"<include file='../Microsoft.ML.StandardLearners/Standard/MultiClass/doc.xml' path='doc/members/member[@name=""OVA""]'/>" })] public static CommonOutputs.MacroOutput<Output> OVA( IHostEnvironment env, Arguments input, EntryPointNode node) { Contracts.CheckValue(env, nameof(env)); env.CheckValue(input, nameof(input)); env.Assert(input.Nodes.Count > 0); var numClasses = GetNumberOfClasses(env, input, out var label); var predModelVars = new Var<IPredictorModel>[numClasses]; // This will be the final resulting list of nodes that is returned from the macro. var macroNodes = new List<EntryPointNode>(); // Instantiate the subgraph for each label value. for (int k = 0; k < numClasses; k++) { var result = ProcessClass(env, k, label, input, node); predModelVars[k] = result.Item2; macroNodes.AddRange(result.Item1); } // Use OVA model combiner to combine these models into one. // Takes in array of models that are binary predictor models and // produces single multiclass predictor model. var macroExperiment = new Experiment(env); var combinerNode = new Models.OvaModelCombiner { ModelArray = new ArrayVar<IPredictorModel>(predModelVars), TrainingData = new Var<IDataView> { VarName = node.GetInputVariable(nameof(input.TrainingData)).VariableName }, Caching = (Models.CachingOptions)input.Caching, FeatureColumn = input.FeatureColumn, NormalizeFeatures = (Models.NormalizeOption)input.NormalizeFeatures, LabelColumn = input.LabelColumn, UseProbabilities = input.UseProbabilities }; // Get output model variable. if (!node.OutputMap.TryGetValue(nameof(Output.PredictorModel), out var outVariableName)) throw new Exception("Cannot find OVA model output."); // Map macro's output back to OVA combiner (so OVA combiner will set the value on our output variable). var combinerOutput = new Models.OvaModelCombiner.Output { PredictorModel = new Var<IPredictorModel> { VarName = outVariableName } }; // Add to experiment (must be done AFTER we assign variable name to output). macroExperiment.Add(combinerNode, combinerOutput); // Add nodes to main experiment. var nodes = macroExperiment.GetNodes(); var expNodes = EntryPointNode.ValidateNodes(env, node.Context, nodes, node.Catalog); macroNodes.AddRange(expNodes); return new CommonOutputs.MacroOutput<Output>() { Nodes = macroNodes }; } } }
47.670051
180
0.620275
[ "MIT" ]
SolyarA/machinelearning
src/Microsoft.ML/Runtime/EntryPoints/OneVersusAllMacro.cs
9,391
C#
using Appraiser.Data.Models; using Appraiser.DTOs; namespace Appraiser.Mapping { public class StaffMapper : Mapper<StaffDTO, Staff> { public StaffMapper(ChangeChecker<StaffDTO> checker) : base(checker) { } public override Staff ToModel(StaffDTO from, Staff to) { if (to == null) return null; _checker.Check("Logon", x => x.Logon, x => x.Logon, (f, t) => t.Logon = f.Logon, from, to); _checker.Check("Name", x => x.Name, x => x.Name, (f, t) => t.Name = f.Name, from, to); _checker.Check("Email", x => x.Email, x => x.Email, (f, t) => t.Email = f.Email, from, to); _checker.Check("Manager Id", x => x.ManagerId, x => x.ManagerId, (f, t) => t.ManagerId = f.ManagerId, from, to); return to; } public override StaffDTO ToDTO(Staff from, StaffDTO to) { to.Id = from.Id; to.Logon = from.Logon; to.Name = from.Name; to.Email = from.Email; to.ManagerId = from.ManagerId; if (from.Manager != null) to.Manager = ToDTO(from.Manager, to.Manager ?? new StaffDTO()); return to; } } }
31.725
124
0.515366
[ "MIT" ]
dominicshaw/Appraiser
Appraiser.Mapping/StaffMapper.cs
1,271
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 Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Structure; namespace Microsoft.CodeAnalysis.CSharp.Structure { internal class CSharpBlockStructureProvider : AbstractBlockStructureProvider { private static ImmutableDictionary<Type, ImmutableArray<AbstractSyntaxStructureProvider>> CreateDefaultNodeProviderMap() { var builder = ImmutableDictionary.CreateBuilder<Type, ImmutableArray<AbstractSyntaxStructureProvider>>(); builder.Add<AccessorDeclarationSyntax, AccessorDeclarationStructureProvider>(); builder.Add<AnonymousMethodExpressionSyntax, AnonymousMethodExpressionStructureProvider>(); builder.Add<ArrowExpressionClauseSyntax, ArrowExpressionClauseStructureProvider>(); builder.Add<BlockSyntax, BlockSyntaxStructureProvider>(); builder.Add<ClassDeclarationSyntax, TypeDeclarationStructureProvider, MetadataAsSource.MetadataTypeDeclarationStructureProvider>(); builder.Add<CompilationUnitSyntax, CompilationUnitStructureProvider>(); builder.Add<ConstructorDeclarationSyntax, ConstructorDeclarationStructureProvider, MetadataAsSource.MetadataConstructorDeclarationStructureProvider>(); builder.Add<ConversionOperatorDeclarationSyntax, ConversionOperatorDeclarationStructureProvider, MetadataAsSource.MetadataConversionOperatorDeclarationStructureProvider>(); builder.Add<DelegateDeclarationSyntax, DelegateDeclarationStructureProvider, MetadataAsSource.MetadataDelegateDeclarationStructureProvider>(); builder.Add<DestructorDeclarationSyntax, DestructorDeclarationStructureProvider, MetadataAsSource.MetadataDestructorDeclarationStructureProvider>(); builder.Add<DocumentationCommentTriviaSyntax, DocumentationCommentStructureProvider>(); builder.Add<EnumDeclarationSyntax, EnumDeclarationStructureProvider, MetadataAsSource.MetadataEnumDeclarationStructureProvider>(); builder.Add<EnumMemberDeclarationSyntax, MetadataAsSource.MetadataEnumMemberDeclarationStructureProvider>(); builder.Add<EventDeclarationSyntax, EventDeclarationStructureProvider, MetadataAsSource.MetadataEventDeclarationStructureProvider>(); builder.Add<EventFieldDeclarationSyntax, EventFieldDeclarationStructureProvider, MetadataAsSource.MetadataEventFieldDeclarationStructureProvider>(); builder.Add<FieldDeclarationSyntax, FieldDeclarationStructureProvider, MetadataAsSource.MetadataFieldDeclarationStructureProvider>(); builder.Add<IndexerDeclarationSyntax, IndexerDeclarationStructureProvider, MetadataAsSource.MetadataIndexerDeclarationStructureProvider>(); builder.Add<InitializerExpressionSyntax, InitializerExpressionStructureProvider>(); builder.Add<InterfaceDeclarationSyntax, TypeDeclarationStructureProvider, MetadataAsSource.MetadataTypeDeclarationStructureProvider>(); builder.Add<MethodDeclarationSyntax, MethodDeclarationStructureProvider, MetadataAsSource.MetadataMethodDeclarationStructureProvider>(); builder.Add<NamespaceDeclarationSyntax, NamespaceDeclarationStructureProvider>(); builder.Add<OperatorDeclarationSyntax, OperatorDeclarationStructureProvider, MetadataAsSource.MetadataOperatorDeclarationStructureProvider>(); builder.Add<ParenthesizedLambdaExpressionSyntax, ParenthesizedLambdaExpressionStructureProvider>(); builder.Add<PropertyDeclarationSyntax, PropertyDeclarationStructureProvider, MetadataAsSource.MetadataPropertyDeclarationStructureProvider>(); builder.Add<RegionDirectiveTriviaSyntax, RegionDirectiveStructureProvider, MetadataAsSource.MetadataRegionDirectiveStructureProvider>(); builder.Add<SimpleLambdaExpressionSyntax, SimpleLambdaExpressionStructureProvider>(); builder.Add<StructDeclarationSyntax, TypeDeclarationStructureProvider, MetadataAsSource.MetadataTypeDeclarationStructureProvider>(); builder.Add<SwitchStatementSyntax, SwitchStatementStructureProvider>(); builder.Add<LiteralExpressionSyntax, StringLiteralExpressionStructureProvider>(); builder.Add<InterpolatedStringExpressionSyntax, InterpolatedStringExpressionStructureProvider>(); return builder.ToImmutable(); } private static ImmutableDictionary<int, ImmutableArray<AbstractSyntaxStructureProvider>> CreateDefaultTriviaProviderMap() { var builder = ImmutableDictionary.CreateBuilder<int, ImmutableArray<AbstractSyntaxStructureProvider>>(); builder.Add((int)SyntaxKind.DisabledTextTrivia, ImmutableArray.Create<AbstractSyntaxStructureProvider>(new DisabledTextTriviaStructureProvider())); return builder.ToImmutable(); } internal CSharpBlockStructureProvider() : base(CreateDefaultNodeProviderMap(), CreateDefaultTriviaProviderMap()) { } } }
78.164179
184
0.801413
[ "Apache-2.0" ]
HenrikWM/roslyn
src/Features/CSharp/Portable/Structure/CSharpBlockStructureProvider.cs
5,239
C#
 namespace PlayDrone2SQL { using System.Collections.Generic; using Models; using System; public class CategoryLogger : IWriter<Category>, IReader { private IWriter<Category> writer; private IReader reader; private ILogger log; public CategoryLogger(IWriter<Category> writer, IReader reader, ILogger log) { this.writer = writer; this.log = log; this.reader = reader; } public void Save(Category category) { log.LogOperation(string.Format("Starting save of category: {0}.", category.Name)); writer.Save(category); log.LogOperation(string.Format("Finished save of category: {0}.", category.Name)); } public void SaveMany(List<Category> categories) { categories.ForEach(i => log.LogOperation(string.Format("Starting save of category: {0}.", i.Name))); writer.SaveMany(categories); categories.ForEach(i => log.LogOperation(string.Format("Finished save of category: {0}.", i.Name))); } public int Count() { return reader.Count(); } public Guid GetId(string name) { return reader.GetId(name); } public bool Exists(string name) { return reader.Exists(name); } } }
26.942308
112
0.569593
[ "MIT" ]
alexhyett/PlayDrone2SQL
PlayDrone2SQL/CategoryLogger.cs
1,403
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** 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.Databricks.Aws.Inputs { public sealed class MwsNetworksErrorMessageArgs : Pulumi.ResourceArgs { [Input("errorMessage")] public Input<string>? ErrorMessage { get; set; } [Input("errorType")] public Input<string>? ErrorType { get; set; } public MwsNetworksErrorMessageArgs() { } } }
26.307692
88
0.678363
[ "ECL-2.0", "Apache-2.0" ]
XBeg9/pulumi-databricks
sdk/dotnet/Aws/Inputs/MwsNetworksErrorMessageArgs.cs
684
C#
//----------------------------------------------------------------------- // <copyright file="TcpListener.cs" company="Akka.NET Project"> // Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com> // Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using System; using System.Net; using System.Net.Sockets; using Akka.Actor; using Akka.Dispatch; using Akka.Event; using Akka.Util.Internal; using System.Collections.Generic; using System.Linq; namespace Akka.IO { partial class TcpListener : ActorBase, IRequiresMessageQueue<IUnboundedMessageQueueSemantics> { private readonly TcpExt _tcp; private readonly IActorRef _bindCommander; private readonly Tcp.Bind _bind; private readonly Socket _socket; private readonly ILoggingAdapter _log = Context.GetLogger(); private int _acceptLimit; private SocketAsyncEventArgs[] _saeas; private int acceptLimit; /// <summary> /// TBD /// </summary> /// <param name="tcp">TBD</param> /// <param name="bindCommander">TBD</param> /// <param name="bind">TBD</param> public TcpListener(TcpExt tcp, IActorRef bindCommander, Tcp.Bind bind) { _tcp = tcp; _bindCommander = bindCommander; _bind = bind; Context.Watch(bind.Handler); _socket = new Socket(_bind.LocalAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { Blocking = false }; _acceptLimit = bind.PullMode ? 0 : _tcp.Settings.BatchAcceptLimit; try { bind.Options.ForEach(x => x.BeforeServerSocketBind(_socket)); _socket.Bind(bind.LocalAddress); _socket.Listen(bind.Backlog); _saeas = Accept(_acceptLimit).ToArray(); } catch (Exception e) { _bindCommander.Tell(bind.FailureMessage); _log.Error(e, "Bind failed for TCP channel on endpoint [{0}]", bind.LocalAddress); Context.Stop(Self); } bindCommander.Tell(new Tcp.Bound(_socket.LocalEndPoint)); } private IEnumerable<SocketAsyncEventArgs> Accept(int limit) { for(var i = 0; i < _acceptLimit; i++) { var self = Self; var saea = new SocketAsyncEventArgs(); saea.Completed += (s, e) => self.Tell(e); if (!_socket.AcceptAsync(saea)) Self.Tell(saea); yield return saea; } } protected override SupervisorStrategy SupervisorStrategy() { return Tcp.ConnectionSupervisorStrategy; } protected override bool Receive(object message) { if (message is SocketAsyncEventArgs) { var saea = message as SocketAsyncEventArgs; if (saea.SocketError == SocketError.Success) Context.ActorOf(Props.Create<TcpIncomingConnection>(_tcp, saea.AcceptSocket, _bind.Handler, _bind.Options, _bind.PullMode)); saea.AcceptSocket = null; if (!_socket.AcceptAsync(saea)) Self.Tell(saea); return true; } var resumeAccepting = message as Tcp.ResumeAccepting; if (resumeAccepting != null) { _acceptLimit = resumeAccepting.BatchSize; _saeas = Accept(_acceptLimit).ToArray(); return true; } if (message is Tcp.Unbind) { _log.Debug("Unbinding endpoint {0}", _bind.LocalAddress); _socket.Dispose(); Sender.Tell(Tcp.Unbound.Instance); _log.Debug("Unbound endpoint {0}, stopping listener", _bind.LocalAddress); Context.Stop(Self); return true; } return false; } /// <summary> /// TBD /// </summary> protected override void PostStop() { try { _socket.Dispose(); _saeas?.ForEach(x => x.Dispose()); } catch (Exception e) { _log.Debug("Error closing ServerSocketChannel: {0}", e); } } } }
33.933333
144
0.525431
[ "Apache-2.0" ]
DeepakArora76/akka.net
src/core/Akka/IO/TcpListener.cs
4,583
C#
using System; using System.Collections.Generic; namespace MinecraftClient.Mapping.EntityPalettes { public class EntityPalette1161 : EntityPalette { private static Dictionary<int, EntityType> mappings = new Dictionary<int, EntityType>(); static EntityPalette1161() { mappings[0] = EntityType.AreaEffectCloud; mappings[1] = EntityType.ArmorStand; mappings[2] = EntityType.Arrow; mappings[3] = EntityType.Bat; mappings[4] = EntityType.Bee; mappings[5] = EntityType.Blaze; mappings[6] = EntityType.Boat; mappings[7] = EntityType.Cat; mappings[8] = EntityType.CaveSpider; mappings[9] = EntityType.Chicken; mappings[10] = EntityType.Cod; mappings[11] = EntityType.Cow; mappings[12] = EntityType.Creeper; mappings[13] = EntityType.Dolphin; mappings[14] = EntityType.Donkey; mappings[15] = EntityType.DragonFireball; mappings[16] = EntityType.Drowned; mappings[17] = EntityType.ElderGuardian; mappings[18] = EntityType.EndCrystal; mappings[19] = EntityType.EnderDragon; mappings[20] = EntityType.Enderman; mappings[21] = EntityType.Endermite; mappings[22] = EntityType.Evoker; mappings[23] = EntityType.EvokerFangs; mappings[24] = EntityType.ExperienceOrb; mappings[25] = EntityType.EyeOfEnder; mappings[26] = EntityType.FallingBlock; mappings[27] = EntityType.FireworkRocket; mappings[28] = EntityType.Fox; mappings[29] = EntityType.Ghast; mappings[30] = EntityType.Giant; mappings[31] = EntityType.Guardian; mappings[32] = EntityType.Hoglin; mappings[33] = EntityType.Horse; mappings[34] = EntityType.Husk; mappings[35] = EntityType.Illusioner; mappings[36] = EntityType.IronGolem; mappings[37] = EntityType.Item; mappings[38] = EntityType.ItemFrame; mappings[39] = EntityType.Fireball; mappings[40] = EntityType.LeashKnot; mappings[41] = EntityType.LightningBolt; mappings[42] = EntityType.Llama; mappings[43] = EntityType.LlamaSpit; mappings[44] = EntityType.MagmaCube; mappings[45] = EntityType.Minecart; mappings[46] = EntityType.ChestMinecart; mappings[47] = EntityType.CommandBlockMinecart; mappings[48] = EntityType.FurnaceMinecart; mappings[49] = EntityType.HopperMinecart; mappings[50] = EntityType.SpawnerMinecart; mappings[51] = EntityType.TntMinecart; mappings[52] = EntityType.Mule; mappings[53] = EntityType.Mooshroom; mappings[54] = EntityType.Ocelot; mappings[55] = EntityType.Painting; mappings[56] = EntityType.Panda; mappings[57] = EntityType.Parrot; mappings[58] = EntityType.Phantom; mappings[59] = EntityType.Pig; mappings[60] = EntityType.Piglin; mappings[61] = EntityType.Pillager; mappings[62] = EntityType.PolarBear; mappings[63] = EntityType.Tnt; mappings[64] = EntityType.Pufferfish; mappings[65] = EntityType.Rabbit; mappings[66] = EntityType.Ravager; mappings[67] = EntityType.Salmon; mappings[68] = EntityType.Sheep; mappings[69] = EntityType.Shulker; mappings[70] = EntityType.ShulkerBullet; mappings[71] = EntityType.Silverfish; mappings[72] = EntityType.Skeleton; mappings[73] = EntityType.SkeletonHorse; mappings[74] = EntityType.Slime; mappings[75] = EntityType.SmallFireball; mappings[76] = EntityType.SnowGolem; mappings[77] = EntityType.Snowball; mappings[78] = EntityType.SpectralArrow; mappings[79] = EntityType.Spider; mappings[80] = EntityType.Squid; mappings[81] = EntityType.Stray; mappings[82] = EntityType.Strider; mappings[83] = EntityType.Egg; mappings[84] = EntityType.EnderPearl; mappings[85] = EntityType.ExperienceBottle; mappings[86] = EntityType.Potion; mappings[87] = EntityType.Trident; mappings[88] = EntityType.TraderLlama; mappings[89] = EntityType.TropicalFish; mappings[90] = EntityType.Turtle; mappings[91] = EntityType.Vex; mappings[92] = EntityType.Villager; mappings[93] = EntityType.Vindicator; mappings[94] = EntityType.WanderingTrader; mappings[95] = EntityType.Witch; mappings[96] = EntityType.Wither; mappings[97] = EntityType.WitherSkeleton; mappings[98] = EntityType.WitherSkull; mappings[99] = EntityType.Wolf; mappings[100] = EntityType.Zoglin; mappings[101] = EntityType.Zombie; mappings[102] = EntityType.ZombieHorse; mappings[103] = EntityType.ZombieVillager; mappings[104] = EntityType.ZombifiedPiglin; mappings[105] = EntityType.Player; mappings[106] = EntityType.FishingBobber; } protected override Dictionary<int, EntityType> GetDict() { return mappings; } } }
44.125984
96
0.590828
[ "MIT" ]
IsaacJuracich/Replay-MCBot
Mapping/EntityPalettes/EntityPalette1161.cs
5,604
C#
// Copyright 2007-2017 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Transports.InMemory { using System; using MassTransit.Topology; using Pipeline; public interface IInMemoryHost : IHost { IReceiveTransport GetReceiveTransport(string queueName, IReceivePipe receivePipe, IReceiveEndpointTopology topology); /// <summary> /// Create a receive endpoint on the host, with a separate handle for stopping/removing the endpoint /// </summary> /// <param name="queueName"></param> /// <param name="configure"></param> /// <returns></returns> HostReceiveEndpointHandle ConnectReceiveEndpoint(string queueName, Action<IInMemoryReceiveEndpointConfigurator> configure = null); } }
42.242424
139
0.694405
[ "Apache-2.0" ]
OriginalDeveloper/MassTransit
src/MassTransit/Transports/InMemory/IInMemoryHost.cs
1,396
C#
using System; using System.Collections.Generic; using System.Text; namespace Yunyong.Redis.Base { public interface ICache { bool Expire(TimeSpan validTimeSpan, params string[] key); bool Rename(string oldKey, string newKey); } }
19.923077
65
0.698842
[ "Apache-2.0" ]
yunyongtech/Yunyong
src/Yunyong/Yunyong.Redis/Base/ICache.cs
261
C#
using AutoMapper; using VISOKI_NAPON.Controllers.Resources; using VISOKI_NAPON.Questions; using VISOKI_NAPON.PlayersTopList; namespace VISOKI_NAPON.Mapping { public class MappingProfile : Profile { public MappingProfile() { CreateMap<Question, QuestionResource>(); CreateMap<TopList, TopListResource>(); } } }
24.1875
53
0.653747
[ "MIT" ]
goran-milenkovic/VisokiNapon
VisokiNapon/Mapping/MappingProfile.cs
387
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using UnityEngine; using UnityEngine.EventSystems; namespace Microsoft.MixedReality.Toolkit.Diagnostics { /// <summary> /// The default implementation of the <see cref="Microsoft.MixedReality.Toolkit.Diagnostics.IMixedRealityDiagnosticsSystem"/> /// </summary> [DocLink("https://microsoft.github.io/MixedRealityToolkit-Unity/Documentation/Diagnostics/DiagnosticsSystemGettingStarted.html")] public class MixedRealityDiagnosticsSystem : BaseCoreSystem, IMixedRealityDiagnosticsSystem { public MixedRealityDiagnosticsSystem( IMixedRealityServiceRegistrar registrar, MixedRealityDiagnosticsProfile profile) : base(registrar, profile) { } /// <summary> /// The parent object under which all visualization game objects will be placed. /// </summary> private GameObject diagnosticVisualizationParent = null; /// <summary> /// Creates the diagnostic visualizations and parents them so that the scene hierarchy does not get overly cluttered. /// </summary> private void CreateVisualizations() { diagnosticVisualizationParent = new GameObject("Diagnostics"); MixedRealityPlayspace.AddChild(diagnosticVisualizationParent.transform); diagnosticVisualizationParent.SetActive(ShowDiagnostics); // visual profiler settings visualProfiler = diagnosticVisualizationParent.AddComponent<MixedRealityToolkitVisualProfiler>(); visualProfiler.WindowParent = diagnosticVisualizationParent.transform; visualProfiler.IsVisible = ShowProfiler; visualProfiler.FrameInfoVisible = ShowFrameInfo; visualProfiler.MemoryStatsVisible = ShowMemoryStats; visualProfiler.FrameSampleRate = FrameSampleRate; visualProfiler.WindowAnchor = WindowAnchor; visualProfiler.WindowOffset = WindowOffset; visualProfiler.WindowScale = WindowScale; visualProfiler.WindowFollowSpeed = WindowFollowSpeed; } private MixedRealityToolkitVisualProfiler visualProfiler = null; #region IMixedRealityService /// <inheritdoc /> public override void Initialize() { if (!Application.isPlaying) { return; } MixedRealityDiagnosticsProfile profile = ConfigurationProfile as MixedRealityDiagnosticsProfile; if (profile == null) { return; } eventData = new DiagnosticsEventData(EventSystem.current); // Apply profile settings ShowDiagnostics = profile.ShowDiagnostics; ShowProfiler = profile.ShowProfiler; ShowFrameInfo = profile.ShowFrameInfo; ShowMemoryStats = profile.ShowMemoryStats; FrameSampleRate = profile.FrameSampleRate; WindowAnchor = profile.WindowAnchor; WindowOffset = profile.WindowOffset; WindowScale = profile.WindowScale; WindowFollowSpeed = profile.WindowFollowSpeed; CreateVisualizations(); } /// <inheritdoc /> public override void Destroy() { if (diagnosticVisualizationParent != null) { if (Application.isEditor) { Object.DestroyImmediate(diagnosticVisualizationParent); } else { diagnosticVisualizationParent.transform.DetachChildren(); Object.Destroy(diagnosticVisualizationParent); } diagnosticVisualizationParent = null; } } #endregion IMixedRealityService #region IMixedRealityDiagnosticsSystem private MixedRealityDiagnosticsProfile diagnosticsSystemProfile = null; /// <inheritdoc/> public MixedRealityDiagnosticsProfile DiagnosticsSystemProfile { get { if (diagnosticsSystemProfile == null) { diagnosticsSystemProfile = ConfigurationProfile as MixedRealityDiagnosticsProfile; } return diagnosticsSystemProfile; } } private bool showDiagnostics; /// <inheritdoc /> public bool ShowDiagnostics { get { return showDiagnostics; } set { if (value != showDiagnostics) { showDiagnostics = value; if (diagnosticVisualizationParent != null) { diagnosticVisualizationParent.SetActive(value); } } } } private bool showProfiler; /// <inheritdoc /> public bool ShowProfiler { get { return showProfiler; } set { if (value != showProfiler) { showProfiler = value; if (visualProfiler != null) { visualProfiler.IsVisible = value; } } } } private bool showFrameInfo; /// <inheritdoc /> public bool ShowFrameInfo { get { return showFrameInfo; } set { if (value != showFrameInfo) { showFrameInfo = value; if (visualProfiler != null) { visualProfiler.FrameInfoVisible = value; } } } } private bool showMemoryStats; /// <inheritdoc /> public bool ShowMemoryStats { get { return showMemoryStats; } set { if (value != showMemoryStats) { showMemoryStats = value; if (visualProfiler != null) { visualProfiler.MemoryStatsVisible = value; } } } } private float frameSampleRate = 0.1f; /// <inheritdoc /> public float FrameSampleRate { get { return frameSampleRate; } set { if (!Mathf.Approximately(frameSampleRate, value)) { frameSampleRate = value; if (visualProfiler != null) { visualProfiler.FrameSampleRate = frameSampleRate; } } } } #endregion IMixedRealityDiagnosticsSystem #region IMixedRealityEventSource private DiagnosticsEventData eventData; /// <inheritdoc /> public uint SourceId => (uint)SourceName.GetHashCode(); /// <inheritdoc /> public string SourceName => "Mixed Reality Diagnostics System"; /// <inheritdoc /> public new bool Equals(object x, object y) => false; /// <inheritdoc /> public int GetHashCode(object obj) => SourceName.GetHashCode(); private void RaiseDiagnosticsChanged() { eventData.Initialize(this); HandleEvent(eventData, OnDiagnosticsChanged); } /// <summary> /// Event sent whenever the diagnostics visualization changes. /// </summary> private static readonly ExecuteEvents.EventFunction<IMixedRealityDiagnosticsHandler> OnDiagnosticsChanged = delegate (IMixedRealityDiagnosticsHandler handler, BaseEventData eventData) { var diagnosticsEventsData = ExecuteEvents.ValidateEventData<DiagnosticsEventData>(eventData); handler.OnDiagnosticSettingsChanged(diagnosticsEventsData); }; #endregion IMixedRealityEventSource private TextAnchor windowAnchor = TextAnchor.LowerCenter; /// <summary> /// What part of the view port to anchor the window to. /// </summary> public TextAnchor WindowAnchor { get { return windowAnchor; } set { if (value != windowAnchor) { windowAnchor = value; if (visualProfiler != null) { visualProfiler.WindowAnchor = windowAnchor; } } } } private Vector2 windowOffset = new Vector2(0.1f, 0.1f); /// <summary> /// The offset from the view port center applied based on the window anchor selection. /// </summary> public Vector2 WindowOffset { get { return windowOffset; } set { if (value != windowOffset) { windowOffset = value; if (visualProfiler != null) { visualProfiler.WindowOffset = windowOffset; } } } } private float windowScale = 1.0f; /// <summary> /// Use to scale the window size up or down, can simulate a zooming effect. /// </summary> public float WindowScale { get { return windowScale; } set { if (value != windowScale) { windowScale = value; if (visualProfiler != null) { visualProfiler.WindowScale = windowScale; } } } } private float windowFollowSpeed = 5.0f; /// <summary> /// How quickly to interpolate the window towards its target position and rotation. /// </summary> public float WindowFollowSpeed { get { return windowFollowSpeed; } set { if (value != windowFollowSpeed) { windowFollowSpeed = value; if (visualProfiler != null) { visualProfiler.WindowFollowSpeed = windowFollowSpeed; } } } } } }
30.478873
133
0.524677
[ "MIT" ]
AdamMitchell-ms/MixedRealityToolkit-Unity
Assets/MixedRealityToolkit.Services/DiagnosticsSystem/MixedRealityDiagnosticsSystem.cs
10,822
C#
// ReSharper disable All namespace OpenTl.Schema { using System; using System.Collections; using System.Text; using OpenTl.Schema; using OpenTl.Schema.Serialization.Attributes; [Serialize(0x688a30aa)] public sealed class TUpdateNewStickerSet : IUpdate { [SerializationOrder(0)] public OpenTl.Schema.Messages.IStickerSet Stickerset {get; set;} } }
18.8
71
0.744681
[ "MIT" ]
zzz8415/OpenTl.Schema
src/OpenTl.Schema/_generated/_Entities/Update/TUpdateNewStickerSet.cs
378
C#
using Microsoft.Xrm.Sdk.Client; using System; namespace Handy.Crm.Powershell.Cmdlets.Helpers { public static class SecurityTokenResponseExtensions { public static bool HasExpired(this SecurityTokenResponse securityTokenResponse) { return securityTokenResponse == null || DateTime.UtcNow >= securityTokenResponse.Response.Lifetime.Expires; } } }
28.214286
119
0.726582
[ "MIT" ]
sergeytunnik/HandyCrmPS
Handy.Crm.Powershell.Cmdlets/Helpers/SecurityTokenResponseExtensions.cs
397
C#
using Tellma.Model.Common; namespace Tellma.Repository.Common { /// <summary> /// The .NET version of the user defined table type [dbo].[StringList]. /// </summary> public class StringListItem : EntityWithKey<string> { } }
19.230769
75
0.648
[ "Apache-2.0" ]
lulzzz/tellma
Tellma.Repository.Common/Dto/StringListItem.cs
252
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.IO; using Microsoft.Azure.WebJobs.Script.Config; namespace Microsoft.Azure.WebJobs.Script.WebHost { public class WebHostSettings { /// <summary> /// Gets or sets a value indicating whether the host is running /// outside of the normal Azure hosting environment. E.g. when running /// locally or via CLI. /// </summary> public bool IsSelfHost { get; set; } public string ScriptPath { get; set; } public string LogPath { get; set; } public string SecretsPath { get; set; } /// <summary> /// Gets or sets the path for storing test data /// This is used for function management operations where the client (portal) /// saves the last invocation test data for a given function /// </summary> public string TestDataPath { get; set; } internal static WebHostSettings CreateDefault(ScriptSettingsManager settingsManager) { WebHostSettings settings = new WebHostSettings { IsSelfHost = !settingsManager.IsAppServiceEnvironment && !settingsManager.IsLinuxContainerEnvironment }; if (settingsManager.IsAppServiceEnvironment) { // Running in App Service string home = settingsManager.GetSetting(EnvironmentSettingNames.AzureWebsiteHomePath); settings.ScriptPath = Path.Combine(home, "site", "wwwroot"); settings.LogPath = Path.Combine(home, "LogFiles", "Application", "Functions"); settings.SecretsPath = Path.Combine(home, "data", "Functions", "secrets"); settings.TestDataPath = Path.Combine(home, "data", "Functions", "sampledata"); } else { // Local hosting or Linux container scenarios settings.ScriptPath = settingsManager.GetSetting(EnvironmentSettingNames.AzureWebJobsScriptRoot); settings.LogPath = Path.Combine(Path.GetTempPath(), @"Functions"); settings.TestDataPath = Path.Combine(Path.GetTempPath(), @"FunctionsData"); // TODO: Revisit. We'll likely have to take an instance of an IHostingEnvironment here settings.SecretsPath = Path.Combine(AppContext.BaseDirectory, "Secrets"); } if (string.IsNullOrEmpty(settings.ScriptPath)) { throw new InvalidOperationException("Unable to determine function script root directory."); } return settings; } } }
41.402985
117
0.623648
[ "MIT" ]
Armandd123/azure-functions-host
src/WebJobs.Script.WebHost/WebHostSettings.cs
2,776
C#
using System.Text; using System.ServiceModel.Channels; using System.Xml; namespace WcfRestContrib.ServiceModel.Channels { public class BinaryBodyWriter : BodyWriter { private readonly byte[] _data; public BinaryBodyWriter(string data) : base(true) { _data = Encoding.UTF8.GetBytes(data); } public BinaryBodyWriter(byte[] data) : base(true) { _data = data; } protected override void OnWriteBodyContents(XmlDictionaryWriter writer) { writer.WriteStartElement(BinaryBodyReader.BinaryElementName); writer.WriteBase64(_data, 0, _data.Length); writer.WriteEndElement(); } } }
26.034483
80
0.603974
[ "MIT" ]
mikeobrien/WcfRestContrib
src/WcfRestContrib/ServiceModel/Channels/BinaryBodyWriter.cs
757
C#