content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// <copyright file="RealtimeRoomConfigBuilder.cs" company="Google Inc."> // Copyright (C) 2014 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> #if UNITY_ANDROID namespace GooglePlayGames.Native.PInvoke { using System; using System.Runtime.InteropServices; using C = GooglePlayGames.Native.Cwrapper.RealTimeRoomConfigBuilder; using Types = GooglePlayGames.Native.Cwrapper.Types; using Status = GooglePlayGames.Native.Cwrapper.CommonErrorStatus; internal class RealtimeRoomConfigBuilder : BaseReferenceHolder { internal RealtimeRoomConfigBuilder(IntPtr selfPointer) : base(selfPointer) { } internal RealtimeRoomConfigBuilder PopulateFromUIResponse(PlayerSelectUIResponse response) { C.RealTimeRoomConfig_Builder_PopulateFromPlayerSelectUIResponse(SelfPtr(), response.AsPointer()); return this; } internal RealtimeRoomConfigBuilder SetVariant(uint variantValue) { uint variant; unchecked { variant = variantValue == 0 ? (uint)-1 : variantValue; } C.RealTimeRoomConfig_Builder_SetVariant(SelfPtr(), variant); return this; } internal RealtimeRoomConfigBuilder AddInvitedPlayer(string playerId) { C.RealTimeRoomConfig_Builder_AddPlayerToInvite(SelfPtr(), playerId); return this; } internal RealtimeRoomConfigBuilder SetExclusiveBitMask(ulong bitmask) { C.RealTimeRoomConfig_Builder_SetExclusiveBitMask(SelfPtr(), bitmask); return this; } internal RealtimeRoomConfigBuilder SetMinimumAutomatchingPlayers(uint minimum) { C.RealTimeRoomConfig_Builder_SetMinimumAutomatchingPlayers(SelfPtr(), minimum); return this; } internal RealtimeRoomConfigBuilder SetMaximumAutomatchingPlayers(uint maximum) { C.RealTimeRoomConfig_Builder_SetMaximumAutomatchingPlayers(SelfPtr(), maximum); return this; } internal RealtimeRoomConfig Build() { return new RealtimeRoomConfig(C.RealTimeRoomConfig_Builder_Create(SelfPtr())); } protected override void CallDispose(HandleRef selfPointer) { C.RealTimeRoomConfig_Builder_Dispose(selfPointer); } internal static RealtimeRoomConfigBuilder Create() { return new RealtimeRoomConfigBuilder(C.RealTimeRoomConfig_Builder_Construct()); } } } #endif
33.431579
98
0.677897
[ "Apache-2.0" ]
BUR58rus/play-games-plugin-for-unity
source/PluginDev/Assets/GooglePlayGames/Platforms/Native/PInvoke/RealtimeRoomConfigBuilder.cs
3,176
C#
using Application.Interfaces.Cadastro; using Domain.Entities.Cadastro; using Domain.Interfaces.Services.Cadastro; using System.Collections.Generic; namespace Application.Applications.Cadastro { public class ClienteAppService : AppServiceBase<Cliente>, InterfaceClienteAppService { private readonly InterfaceClienteService _clienteService; public ClienteAppService(InterfaceClienteService clienteService) : base(clienteService) { _clienteService = clienteService; } public IEnumerable<Cliente> ObterClientesEspeciais() { return _clienteService.ObterClientesEspeciais(_clienteService.GetAll()); } } }
29.625
88
0.720113
[ "MIT" ]
PauloGaldino/SGFR_Identity
src/Application/Applications/Cadastro/ClienteAppService.cs
713
C#
using System; using System.Collections.Generic; using Android.App; using Android.Widget; using Android.OS; using Xamarin.Android.NUnitLite; namespace Xamarin.Android.BclTests { [Activity ( Label = "Xamarin.Android BCL Tests", MainLauncher = true, Name = "xamarin.android.bcltests.MainActivity")] public class MainActivity : TestSuiteActivity { public MainActivity () { GCAfterEachFixture = true; } protected override void OnCreate (Bundle bundle) { App.ExtractBclTestFiles (); foreach (var tests in App.GetTestAssemblies ()) { AddTest (tests); } // Once you called base.OnCreate(), you cannot add more assemblies. base.OnCreate (bundle); } protected override IEnumerable<string> GetExcludedCategories () { return App.GetExcludedCategories (); } protected override void UpdateFilter () { Filter = App.UpdateFilter (Filter); } } }
19.234043
70
0.709071
[ "BSD-3-Clause" ]
Acidburn0zzz/xamarin-android
tests/Xamarin.Android.Bcl-Tests/MainActivity.cs
906
C#
using System.Collections.Generic; using Xunit.v3; namespace Xunit.Sdk { /// <summary> /// Interface to be implemented by classes which are used to discover tests cases attached /// to test methods that are attributed with <see cref="FactAttribute"/> (or a subclass). /// </summary> public interface IXunitTestCaseDiscoverer { /// <summary> /// Discover test cases from a test method. /// </summary> /// <param name="discoveryOptions">The discovery options to be used.</param> /// <param name="testMethod">The test method the test cases belong to.</param> /// <param name="factAttribute">The fact attribute attached to the test method.</param> /// <returns>Returns zero or more test cases represented by the test method.</returns> IReadOnlyCollection<IXunitTestCase> Discover( _ITestFrameworkDiscoveryOptions discoveryOptions, _ITestMethod testMethod, _IAttributeInfo factAttribute ); } }
35.538462
91
0.734848
[ "Apache-2.0" ]
Xcodo/xun
src/xunit.v3.core/Sdk/IXunitTestCaseDiscoverer.cs
926
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Profiles.ORCID.Utilities.ProfilesRNSDLL.BLL.ORNG { public partial class AppRegistry { } }
16.666667
58
0.755
[ "BSD-3-Clause" ]
HSSC/ProfilesRNS
Website/SourceCode/Profiles/Profiles/ORCID/Utilities/ProfilesRNSDLL/BLL/ORNG/AppRegistry.cs
202
C#
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt. using Sce.Atf.Dom; namespace CircuitEditorSample { /// <summary> /// Adapts the circuit to IDocument and synchronizes URI and dirty bit changes to the /// ControlInfo instance used to register the viewing control in the UI</summary> public class CircuitDocument : Sce.Atf.Controls.Adaptable.Graphs.CircuitDocument { /// <summary> /// This property is obsolete as of ATF 3.9. It will probably be removed for ATF 3.10.</summary> protected override ChildInfo SubCircuitChildInfo { get { return Schema.circuitDocumentType.subCircuitChild; } } } }
35.9
105
0.672702
[ "Apache-2.0" ]
StirfireStudios/ATF
Samples/CircuitEditor/CircuitDocument.cs
702
C#
namespace Offeror.TelegramBot.Exceptions { public class FailDeleteCommandException : Exception { public FailDeleteCommandException() : this("Failed to free up resources occupied by commands") { } public FailDeleteCommandException(string? message) : base(message) { } } }
22.25
69
0.606742
[ "MIT" ]
TheWayToJunior/Offeror.TelegramBot
src/Offeror.TelegramBot/Offeror.TelegramBot/Exceptions/FailDeleteCommandException.cs
358
C#
namespace Example { using System; using System.Threading.Tasks; using FluentArgs; public static class Program { public static Task Main(string[] args) { return FluentArgsBuilder.New() .DefaultConfigsWithAppDescription("An app to convert png files to jpg files.") .Parameter("-i", "--input") .WithDescription("Input png file") .WithExamples("input.png") .IsRequired() .Parameter("-o", "--output") .WithDescription("Output jpg file") .WithExamples("output.jpg") .IsRequired() .Parameter<ushort>("-q", "--quality") .WithDescription("Quality of the conversion") .WithValidation(n => n >= 0 && n <= 100) .IsOptionalWithDefault(50) .Call(quality => outputFile => inputFile => { /* ... */ Console.WriteLine($"Convert {inputFile} to {outputFile} with quality {quality}..."); /* ... */ return Task.CompletedTask; }) .ParseAsync(args); } } }
35.583333
104
0.461358
[ "BSD-3-Clause" ]
kutoga/FluentArgs
doc/examples/Simple02.cs
1,281
C#
// $Id: StudentModel.cs 1043 2006-07-19 22:48:12Z julenka $ using System; namespace UW.ClassroomPresenter.Model.Network { [Serializable] public class StudentModel : RoleModel { public StudentModel(Guid id) : base(id) { } } }
22.166667
60
0.631579
[ "Apache-2.0" ]
ClassroomPresenter/CP3
UW.ClassroomPresenter/Model/Network/StudentModel.cs
266
C#
using System; using System.Net; using PingPong.Common.Dtos; using PingPong.Validation.Abstractions; namespace PingPong.CreationPolicy { public class IPAdressFactory { private readonly IAddressValidator _addressValidator; private readonly IPortValidator _portValidator; public IPAdressFactory(IAddressValidator addressValidator, IPortValidator portValidator) { _addressValidator = addressValidator; _portValidator = portValidator; } public IPAddressWithPort CreateAddress(string[] input) { if (input.Length == 2) { if (_addressValidator.TryParseAddress(input[0], out var address) && _portValidator.TryParsePort(input[1], out int port)) { return new IPAddressWithPort(new IPAddress(address), port); } } throw new Exception(); } } }
28.558824
96
0.61277
[ "Unlicense" ]
Electric1447/PingPong
PingPong/PingPong.CreationPolicy/IPAdressFactory.cs
973
C#
namespace FalseDotNet.Cli.SubCommandExtensions; public interface ISubCommand { Task<int> RunAsync(object opts); } public abstract class SubCommand<TOptions> : ISubCommand { public Task<int> RunAsync(object opts) { return RunAsync((TOptions)opts); } public abstract Task<int> RunAsync(TOptions opts); }
20.8125
56
0.720721
[ "MIT" ]
MixusMinimax/falsedotnet
FalseDotNet.Cli/SubCommandExtensions/ISubCommand.cs
335
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // La información general de un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie estos valores de atributo para modificar la información // asociada con un ensamblado. [assembly: AssemblyTitle("Edad")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Edad")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles // para los componentes COM. Si es necesario obtener acceso a un tipo en este ensamblado desde // COM, establezca el atributo ComVisible en true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM. [assembly: Guid("5bf6959f-1faf-4363-85be-fddc679d33bf")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o utilizar los números de compilación y de revisión predeterminados // mediante el carácter '*', como se muestra a continuación: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.459459
106
0.755511
[ "MIT" ]
Ricardo221604/Calculo-de-dias-vividos
Edad/Edad/Properties/AssemblyInfo.cs
1,515
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System.IO; using System.Linq; using System.Threading.Tasks; namespace MonicaBlazorZmqUI.Server.Controllers { [Route("[controller]")] [ApiController] public class UploadController : ControllerBase { private readonly IWebHostEnvironment environment; public UploadController(IWebHostEnvironment environment) { this.environment = environment; } [HttpPost] public async Task Post() { if (HttpContext.Request.Form.Files.Any()) { foreach (var file in HttpContext.Request.Form.Files) { var path = Path.Combine(environment.ContentRootPath, "Upload", file.FileName); using (var stream = new FileStream(path, FileMode.Create)) { await file.CopyToAsync(stream); } } } } } }
27.815789
98
0.576159
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
zalf-rpm/mas-infrastructure
src/csharp/MonicaBlazorZmqUI/Services/UploadController.cs
1,059
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Metadata; namespace AllReady.Migrations { public partial class RemovingEventSignups : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "EventSignup"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "EventSignup", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), AdditionalInfo = table.Column<string>(nullable: true), CheckinDateTime = table.Column<DateTime>(nullable: true), EventId = table.Column<int>(nullable: true), PreferredEmail = table.Column<string>(nullable: true), PreferredPhoneNumber = table.Column<string>(nullable: true), SignupDateTime = table.Column<DateTime>(nullable: false), UserId = table.Column<string>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_EventSignup", x => x.Id); table.ForeignKey( name: "FK_EventSignup_Event_EventId", column: x => x.EventId, principalTable: "Event", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_EventSignup_ApplicationUser_UserId", column: x => x.UserId, principalTable: "ApplicationUser", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_EventSignup_EventId", table: "EventSignup", column: "EventId"); migrationBuilder.CreateIndex( name: "IX_EventSignup_UserId", table: "EventSignup", column: "UserId"); } } }
40.533333
122
0.526316
[ "MIT" ]
7as8ydh/allReady
AllReadyApp/Web-App/AllReady/Migrations/20160901161922_RemovingEventSignups.cs
2,434
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Kusto.V20200614 { /// <summary> /// Class representing an data connection. /// </summary> [Obsolete(@"Please use one of the variants: EventGridDataConnection, EventHubDataConnection, IotHubDataConnection.")] [AzureNativeResourceType("azure-native:kusto/v20200614:DataConnection")] public partial class DataConnection : Pulumi.CustomResource { /// <summary> /// Kind of the endpoint for the data connection /// </summary> [Output("kind")] public Output<string> Kind { get; private set; } = null!; /// <summary> /// Resource location. /// </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> /// 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 DataConnection 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 DataConnection(string name, DataConnectionArgs args, CustomResourceOptions? options = null) : base("azure-native:kusto/v20200614:DataConnection", name, args ?? new DataConnectionArgs(), MakeResourceOptions(options, "")) { } private DataConnection(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:kusto/v20200614:DataConnection", 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:kusto/v20200614:DataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto:DataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto:DataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto/v20190121:DataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20190121:DataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto/v20190515:DataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20190515:DataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto/v20190907:DataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20190907:DataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto/v20191109:DataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20191109:DataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto/v20200215:DataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20200215:DataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto/v20200918:DataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20200918:DataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto/v20210101:DataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20210101:DataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto/v20210827:DataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20210827:DataConnection"}, }, }; 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 DataConnection 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 DataConnection Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new DataConnection(name, id, options); } } public sealed class DataConnectionArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the Kusto cluster. /// </summary> [Input("clusterName", required: true)] public Input<string> ClusterName { get; set; } = null!; /// <summary> /// The name of the data connection. /// </summary> [Input("dataConnectionName")] public Input<string>? DataConnectionName { get; set; } /// <summary> /// The name of the database in the Kusto cluster. /// </summary> [Input("databaseName", required: true)] public Input<string> DatabaseName { get; set; } = null!; /// <summary> /// Kind of the endpoint for the data connection /// </summary> [Input("kind", required: true)] public InputUnion<string, Pulumi.AzureNative.Kusto.V20200614.DataConnectionKind> Kind { get; set; } = null!; /// <summary> /// Resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The name of the resource group containing the Kusto cluster. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; public DataConnectionArgs() { } } }
45.357616
139
0.602278
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Kusto/V20200614/DataConnection.cs
6,849
C#
using System; namespace API.Entities { public sealed class Task { public Guid Id { get; set; } public bool IsDone { get; set; } public string Title { get; set; } public string Description { get; set; } public DateTime CreatedAt { get; set; } } }
23
47
0.578595
[ "MIT" ]
olaf-svenson/graphql-net-reproduction
graphql-demo/API/Entities/Task.cs
301
C#
// Copyright (c) 2016, SolidCP // SolidCP is distributed under the Creative Commons Share-alike license // // SolidCP is a fork of WebsitePanel: // Copyright (c) 2015, Outercurve Foundation. // 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 the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; namespace SolidCP.Providers.Virtualization { public class VirtualMachine : ServiceProviderItem { public VirtualMachine() { } // properties [Persistent] public string VirtualMachineId { get; set; } public string Hostname { get; set; } public string Domain { get; set; } [Persistent] public string Version { get; set; } public VirtualMachineState State { get; set; } public long Uptime { get; set; } public OperationalStatus Heartbeat { get; set; } [Persistent] public string CreationTime { get; set; } [Persistent] public string RootFolderPath { get; set; } [Persistent] public string[] VirtualHardDrivePath { get; set; } [Persistent] public string OperatingSystemTemplate { get; set; } [Persistent] public string OperatingSystemTemplatePath { get; set; } [Persistent] public string OperatingSystemTemplateDeployParams { get; set; } [Persistent] public string AdministratorPassword { get; set; } [Persistent] public string CurrentTaskId { get; set; } [Persistent] public VirtualMachineProvisioningStatus ProvisioningStatus { get; set; } [Persistent] public int CpuCores { get; set; } public int CpuUsage { get; set; } [Persistent] public int RamSize { get; set; } public int RamUsage { get; set; } [Persistent] public DynamicMemory DynamicMemory { get; set; } [Persistent] public int[] HddSize { get; set; } public LogicalDisk[] HddLogicalDisks { get; set; } [Persistent] public int HddMaximumIOPS { get; set; } [Persistent] public int HddMinimumIOPS { get; set; } [Persistent] public int SnapshotsNumber { get; set; } [Persistent] public bool DvdDriveInstalled { get; set; } [Persistent] public bool BootFromCD { get; set; } [Persistent] public bool NumLockEnabled { get; set; } [Persistent] public bool StartTurnOffAllowed { get; set; } [Persistent] public bool PauseResumeAllowed { get; set; } [Persistent] public bool RebootAllowed { get; set; } [Persistent] public bool ResetAllowed { get; set; } [Persistent] public bool ReinstallAllowed { get; set; } [Persistent] public bool LegacyNetworkAdapter { get; set; } [Persistent] public bool RemoteDesktopEnabled { get; set; } [Persistent] public bool ExternalNetworkEnabled { get; set; } [Persistent] public string ExternalNicMacAddress { get; set; } [Persistent] public string ExternalSwitchId { get; set; } [Persistent] public bool PrivateNetworkEnabled { get; set; } [Persistent] public string PrivateNicMacAddress { get; set; } [Persistent] public string PrivateSwitchId { get; set; } [Persistent] public int PrivateNetworkVlan { get; set; } [Persistent] public bool ManagementNetworkEnabled { get; set; } [Persistent] public string ManagementNicMacAddress { get; set; } [Persistent] public string ManagementSwitchId { get; set; } // for GetVirtualMachineEx used in import method public VirtualMachineNetworkAdapter[] Adapters { get; set; } [Persistent] public VirtualHardDiskInfo[] Disks { get; set; } [Persistent] public string Status { get; set; } public ReplicationState ReplicationState { get; set; } [Persistent] public int Generation { get; set; } [Persistent] public string SecureBootTemplate { get; set; } [Persistent] public bool EnableSecureBoot { get; set; } [Persistent] public int ProcessorCount { get; set; } [Persistent] public string ParentSnapshotId { get; set; } [Persistent] public int defaultaccessvlan { get; set; }//external network vlan public VirtualMachineIPAddress PrimaryIP { get; set; } public bool NeedReboot { get; set; } //give access to force reboot a server. [Persistent] public string CustomPrivateGateway { get; set; } [Persistent] public string CustomPrivateDNS1 { get; set; } [Persistent] public string CustomPrivateDNS2 { get; set; } [Persistent] public string CustomPrivateMask { get; set; } [Persistent] public string ClusterName { get; set; } public bool IsClustered { get; set; } } }
35.777174
84
0.638767
[ "BSD-3-Clause" ]
Alirexaa/SolidCP
SolidCP/Sources/SolidCP.Providers.Base/Virtualization/VirtualMachine.cs
6,583
C#
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir & xuri 2021 // // 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. // This file was automatically generated and should not be edited directly. using System.Runtime.InteropServices; namespace SharpVk.NVidia { /// <summary> /// </summary> [StructLayout(LayoutKind.Sequential)] public struct GraphicsShaderGroupCreateInfo { /// <summary> /// </summary> public PipelineShaderStageCreateInfo[] Stages { get; set; } /// <summary> /// </summary> public PipelineVertexInputStateCreateInfo? VertexInputState { get; set; } /// <summary> /// </summary> public PipelineTessellationStateCreateInfo? TessellationState { get; set; } /// <summary> /// </summary> /// <param name="pointer"> /// </param> internal unsafe void MarshalTo(SharpVk.Interop.NVidia.GraphicsShaderGroupCreateInfo* pointer) { pointer->SType = StructureType.GraphicsShaderGroupCreateInfo; pointer->Next = null; pointer->StageCount = (uint)(Interop.HeapUtil.GetLength(Stages)); if (Stages != null) { var fieldPointer = (SharpVk.Interop.PipelineShaderStageCreateInfo*)(Interop.HeapUtil.AllocateAndClear<SharpVk.Interop.PipelineShaderStageCreateInfo>(Stages.Length).ToPointer()); for(int index = 0; index < (uint)(Stages.Length); index++) { Stages[index].MarshalTo(&fieldPointer[index]); } pointer->Stages = fieldPointer; } else { pointer->Stages = null; } if (VertexInputState != null) { pointer->VertexInputState = (SharpVk.Interop.PipelineVertexInputStateCreateInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.PipelineVertexInputStateCreateInfo>()); VertexInputState.Value.MarshalTo(pointer->VertexInputState); } else { pointer->VertexInputState = default; } if (TessellationState != null) { pointer->TessellationState = (SharpVk.Interop.PipelineTessellationStateCreateInfo*)(Interop.HeapUtil.Allocate<SharpVk.Interop.PipelineTessellationStateCreateInfo>()); TessellationState.Value.MarshalTo(pointer->TessellationState); } else { pointer->TessellationState = default; } } } }
37.60396
193
0.615587
[ "MIT" ]
xuri02/SharpVk
src/SharpVk/NVidia/GraphicsShaderGroupCreateInfo.gen.cs
3,798
C#
namespace ClassifiedApp.WebApi.Areas.HelpPage.ModelDescriptions { public class DictionaryModelDescription : KeyValuePairModelDescription { } }
25.666667
74
0.798701
[ "MIT" ]
samibader/ClassifiedApp
ClassifiedApp.WebApi/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs
154
C#
using AutoMapper; using Microsoft.EntityFrameworkCore; using StoreManagement.Core.Dto; using StoreManagement.EF.Context; using StoreManagement.EF.Entities; using StoreManagement.Interface; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace StoreManagement.Service { public class ProductService : IProductService { protected readonly StoreManagementEfContext _context; protected readonly IMapper _mapper; public ProductService(StoreManagementEfContext context, IMapper mapper) { _context = context; _mapper = mapper; } public async Task<ProductDto> AddAsync(ProductDto entity) { var result = await _context.Set<Product>().AddAsync(_mapper.Map<Product>(entity)); await _context.SaveChangesAsync().ConfigureAwait(false); return _mapper.Map<ProductDto>(result); } public async Task<ProductDto> AddAsync(ProductDto entity, int storeId) { using (var transaction = _context.Database.BeginTransaction()) { try { var productValue = await _context.Set<Product>().AddAsync(_mapper.Map<Product>(entity)); await _context.SaveChangesAsync().ConfigureAwait(false); var store = await _context.FindAsync<Store>(storeId); if (store == null) { transaction.Rollback(); throw new NullReferenceException(nameof(storeId)); } var resultStoreProduct = await _context.Set<StoreProduct>() .AddAsync(new StoreProduct() { Product = productValue.Entity, Store = store }); await _context.SaveChangesAsync().ConfigureAwait(false); await transaction.CommitAsync().ConfigureAwait(false); return _mapper.Map<ProductDto>(productValue.Entity); } catch (Exception ex) { throw; } } } public async Task<bool> DeleteAsync(ProductDto entity) { _context.Set<Product>().Remove(_mapper.Map<Product>(entity)); return await _context.SaveChangesAsync().ConfigureAwait(false) > 0; } public async Task<List<ProductDto>> GetAllByIds(IEnumerable<int> ids) { var products = new List<Product>(); foreach (var id in ids) { products.Add(await _context.Products.FindAsync(id) .ConfigureAwait(false)); } return _mapper.Map<List<ProductDto>>(products); } public async Task<List<ProductDto>> GetAllByStoreId(int id) { var sp = await _context.StoresProducts .Where(sp => sp.StoreId == id) .Include(sp => sp.Product) .Select(sp => sp.Product) .ToListAsync() .ConfigureAwait(false); return _mapper.Map<List<ProductDto>>(sp); } public async Task<bool> UpdateAsync(ProductDto entity) { _context.Products.Update(_mapper.Map<Product>(entity)); return await _context.SaveChangesAsync().ConfigureAwait(false) > 0; } } }
34.305556
108
0.537922
[ "MIT" ]
TheHappiness/LightpointTask
StoreManagement.Service/ProductService.cs
3,707
C#
// NoRealm licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using NoRealm.ExpressionLite.Parser; using System; namespace NoRealm.ExpressionLite.Generator { /// <summary> /// Represent a generator which convert the expression tree into a runtime function /// </summary> public sealed class RuntimeMethodGenerator : IGenerator<Delegate> { /// <inheritdoc /> public Delegate Generate(IParsingResult parsingResult) => parsingResult.CreateExpression(parsingResult.Expression.StaticType).Compile(); /// <inheritdoc /> public Delegate Generate(IParsingResult result, Type input) => result.CreateExpression(input, result.Expression.StaticType).Compile(); /// <summary> /// Generate a runtime method which have a result of input type /// </summary> /// <typeparam name="T">result type, must be one of the primitive types</typeparam> /// <param name="parsingResult">the parsing results to use for generation</param> /// <returns>the runtime method which match input parser results</returns> public Func<T> Generate<T>(IParsingResult parsingResult) => (Func<T>)parsingResult.CreateExpression(typeof(T)).Compile(); /// <summary> /// Generate a runtime method which have a user input /// </summary> /// <typeparam name="T">user input type</typeparam> /// <typeparam name="TR">result type, must be one of the primitive types</typeparam> /// <param name="parsingResult">the parsing results to use for generation</param> /// <returns>the runtime method which match input parser results</returns> public Func<T, TR> Generate<T, TR>(IParsingResult parsingResult) => (Func<T, TR>)parsingResult.CreateExpression(typeof(T), typeof(TR)).Compile(); } }
45.857143
93
0.668744
[ "MIT" ]
norealm/expression-lite
src/lib/Generator/RuntimeMethodGenerator.cs
1,928
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable disable using System; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Linq; using System.Text; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; namespace ASPIdentity.Areas.Identity.Pages.Account.Manage { public class EnableAuthenticatorModel : PageModel { private readonly UserManager<IdentityUser> _userManager; private readonly ILogger<EnableAuthenticatorModel> _logger; private readonly UrlEncoder _urlEncoder; private const string AuthenticatorUriFormat = "otpauth://totp/{0}:{1}?secret={2}&issuer={0}&digits=6"; public EnableAuthenticatorModel( UserManager<IdentityUser> userManager, ILogger<EnableAuthenticatorModel> logger, UrlEncoder urlEncoder) { _userManager = userManager; _logger = logger; _urlEncoder = urlEncoder; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public string SharedKey { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public string AuthenticatorUri { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [TempData] public string[] RecoveryCodes { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [TempData] public string StatusMessage { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [BindProperty] public InputModel Input { get; set; } /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> public class InputModel { /// <summary> /// This API supports the ASP.NET Core Identity default UI infrastructure and is not intended to be used /// directly from your code. This API may change or be removed in future releases. /// </summary> [Required] [StringLength(7, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Text)] [Display(Name = "Verification Code")] public string Code { get; set; } } public async Task<IActionResult> OnGetAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } await LoadSharedKeyAndQrCodeUriAsync(user); return Page(); } public async Task<IActionResult> OnPostAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound($"Unable to load user with ID '{_userManager.GetUserId(User)}'."); } if (!ModelState.IsValid) { await LoadSharedKeyAndQrCodeUriAsync(user); return Page(); } // Strip spaces and hyphens var verificationCode = Input.Code.Replace(" ", string.Empty).Replace("-", string.Empty); var is2faTokenValid = await _userManager.VerifyTwoFactorTokenAsync( user, _userManager.Options.Tokens.AuthenticatorTokenProvider, verificationCode); if (!is2faTokenValid) { ModelState.AddModelError("Input.Code", "Verification code is invalid."); await LoadSharedKeyAndQrCodeUriAsync(user); return Page(); } await _userManager.SetTwoFactorEnabledAsync(user, true); var userId = await _userManager.GetUserIdAsync(user); _logger.LogInformation("User with ID '{UserId}' has enabled 2FA with an authenticator app.", userId); StatusMessage = "Your authenticator app has been verified."; if (await _userManager.CountRecoveryCodesAsync(user) == 0) { var recoveryCodes = await _userManager.GenerateNewTwoFactorRecoveryCodesAsync(user, 10); RecoveryCodes = recoveryCodes.ToArray(); return RedirectToPage("./ShowRecoveryCodes"); } else { return RedirectToPage("./TwoFactorAuthentication"); } } private async Task LoadSharedKeyAndQrCodeUriAsync(IdentityUser user) { // Load the authenticator key & QR code URI to display on the form var unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); if (string.IsNullOrEmpty(unformattedKey)) { await _userManager.ResetAuthenticatorKeyAsync(user); unformattedKey = await _userManager.GetAuthenticatorKeyAsync(user); } SharedKey = FormatKey(unformattedKey); var email = await _userManager.GetEmailAsync(user); AuthenticatorUri = GenerateQrCodeUri(email, unformattedKey); } private string FormatKey(string unformattedKey) { var result = new StringBuilder(); int currentPosition = 0; while (currentPosition + 4 < unformattedKey.Length) { result.Append(unformattedKey.AsSpan(currentPosition, 4)).Append(' '); currentPosition += 4; } if (currentPosition < unformattedKey.Length) { result.Append(unformattedKey.AsSpan(currentPosition)); } return result.ToString().ToLowerInvariant(); } private string GenerateQrCodeUri(string email, string unformattedKey) { return string.Format( CultureInfo.InvariantCulture, AuthenticatorUriFormat, _urlEncoder.Encode("Microsoft.AspNetCore.Identity.UI"), _urlEncoder.Encode(email), unformattedKey); } } }
39.587302
127
0.607191
[ "MIT" ]
mishelshaji/Asp-.Net-Core-Demo
ASPIdentity/Areas/Identity/Pages/Account/Manage/EnableAuthenticator.cshtml.cs
7,484
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class SpielprinzipMauMau : MonoBehaviour { public Kartenstapel stapel; public Karte offeneKarte; public GameObject spielerHandstapel; void Start() { stapel.mischeStapel(); GibKarten(5, spielerHandstapel); offeneKarte.setzeBeschreibung(stapel.hebeZufaelligeKarteAb(), false); } private void GibKarten(int anzahl, GameObject handstapel) { for(int i=0; i<anzahl ; i++) { Kartenbeschreibung karteAusStapel = stapel.hebeObersteKarteAb(); stapel.kartenContainer = handstapel; Karte karteInSzene = stapel.erzeugeKarteInSzene(); karteInSzene.setzeBeschreibung(karteAusStapel, true); karteInSzene.Umdrehen(); karteInSzene.GetComponent<Button>().onClick.AddListener(KlickAufHandStapelKarte); } } private void KlickAufHandStapelKarte() { Karte karteInSzene = EventSystem.current.currentSelectedGameObject.GetComponent<Karte>(); Debug.Log("Handstapelkarte angeklickt: "+karteInSzene.aktuelleBeschreibung()); if (Passt(karteInSzene)) LegeAb(karteInSzene); else Debug.Log("Die Karte "+karteInSzene+" passt NICHT auf "+offeneKarte); } private bool Passt(Karte karte) { return (karte.aktuelleBeschreibung().Farbe == offeneKarte.aktuelleBeschreibung().Farbe) || (karte.aktuelleBeschreibung().Wert == offeneKarte.aktuelleBeschreibung().Wert) ; } private void LegeAb(Karte handstapelkarteInSzene) { stapel.legeKarteZurueck(offeneKarte.aktuelleBeschreibung()); stapel.mischeStapel(); offeneKarte.setzeBeschreibung(handstapelkarteInSzene.aktuelleBeschreibung(), false); Destroy(handstapelkarteInSzene.gameObject); //Typischer Fehler: .gameObject vergessen } public void KlickAufKartenstapel() { GibKarten(1, spielerHandstapel); } }
31.25
97
0.673412
[ "MIT" ]
renebuehling/gamedev-profi.de_card-game
Teil 10 - MauMau/10a Basis vor Spielparteien/Scripts/SpielprinzipMauMau.cs
2,127
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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\General\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; namespace JIT.HardwareIntrinsics.General { public static partial class Program { private static void Vector128ToVector256() { bool succeeded = false; try { Vector256<bool> result = default(Vector128<bool>).ToVector256(); } catch (NotSupportedException) { succeeded = true; } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"Vector128ToVector256: RunNotSupportedScenario failed to throw NotSupportedException."); TestLibrary.TestFramework.LogInformation(string.Empty); throw new Exception("One or more scenarios did not complete as expected."); } } } }
36.772727
146
0.570457
[ "MIT" ]
06needhamt/runtime
src/coreclr/tests/src/JIT/HardwareIntrinsics/General/NotSupported/Vector128ToVector256.cs
1,618
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace Isaac.SampleMvc { public class RouteConfig { public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional } ); } } }
24.291667
99
0.588336
[ "MIT" ]
Isaac-Shen/Isaac.Infrastracture
Isaac.Infrastructure.Framework/Isaac.SampleMvc/App_Start/RouteConfig.cs
585
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Ultraschall.Data.Abstractions; using Ultraschall.Data.Entities; using Ultraschall.Domain.Abstractions; using Ultraschall.Domain.Models; namespace Ultraschall.Domain.Services { public class CategoriesService : ICategoriesService { private readonly ICategoriesRepository _repository; public CategoriesService(ICategoriesRepository repository) { _repository = repository ?? throw new ArgumentNullException(nameof(repository)); } public IEnumerable<CategoryModel> GetSubCategories(Guid id) { return _repository.GetSubCategories(id).Select(entity => MapEntityToModel(entity)).AsEnumerable(); } private CategoryModel MapEntityToModel(Category entity) { if (entity == null) return null; return new CategoryModel { Id = entity.Id, Name = entity.Name, Parent = entity.Parent == null ? null : new CategoryReferene { Id = entity.Parent.Id } }; } private Category MapModelToEntity(CategoryModel model) { return new Category { Id = model.Id, Name = model.Name }; } public IEnumerable<CategoryModel> GetAll() { return _repository.GetAll() .Select(e => MapEntityToModel(e)) .AsEnumerable(); } public async Task<CategoryModel> GetById(Guid id) { return MapEntityToModel(await _repository.GetById(id)); } public async Task Create(CategoryModel model) { await _repository.Create(MapModelToEntity(model)); } public async Task Update(Guid id, CategoryModel model) { await _repository.Update(id, MapModelToEntity(model)); } public async Task Delete(Guid id) { await _repository.Delete(id); } public async Task Patch(Guid id, CategoryPatchModel patchModel) { if (patchModel.Parent != Guid.Empty) { await _repository.SetParent(id, patchModel.Parent); } if (patchModel.Child != Guid.Empty) { await _repository.SetParent(id, patchModel.Child); } } } }
29.329412
110
0.580425
[ "MIT" ]
Ultraschall/ultraschall-playground
danlin/Ultraschall/Domain/Services/CategoriesService.cs
2,495
C#
using System; using System.Collections.Generic; using System.Text; using Entidades; namespace Persistencia.InterfazDao { public interface IAsistenciaDao { List<Asistencia> ListarAsistenciasPorSesionCurso(int idCurso, DateTime fechaActual); List<Asistencia> ListarAsistenciasPorSesion(int idSesion); void RegistrarAsistencia(Asistencia asistencia); bool EditarAsistencia(Asistencia asistencia); Asistencia BuscarAsistenciaPorID(int idAsistencia); } }
29.647059
92
0.761905
[ "MIT" ]
jonaav/Overseas5
Persistencia/InterfazDao/IAsistenciaDao.cs
506
C#
#region Copyright (c) 2009 S. van Deursen /* The CuttingEdge.Conditions library enables developers to validate pre- and postconditions in a fluent * manner. * * To contact me, please visit my blog at http://www.cuttingedge.it/blogs/steven/ * * Copyright (c) 2009 S. van Deursen * * 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 using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace CuttingEdge.Conditions.UnitTests.StringTests { /// <summary> /// Tests the ValidatorExtensions.DoesNotHaveLength method. /// </summary> [TestClass] public class StringDoesNotHaveLengthTests { [TestMethod] [ExpectedException(typeof(ArgumentException))] [Description("Calling DoesNotHaveLength on string x with 'x.Length = expected length' should fail.")] public void DoesNotHaveLengthTest01() { string a = "test"; Condition.Requires(a).DoesNotHaveLength(4); } [TestMethod] [ExpectedException(typeof(ArgumentException))] [Description("Calling DoesNotHaveLength on string x with 'x.Length = expected length = 1' should fail.")] public void DoesNotHaveLengthTest02() { string a = "t"; Condition.Requires(a).DoesNotHaveLength(1); } [TestMethod] [Description("Calling DoesNotHaveLength on string x with 'x.Length != expected length' should pass.")] public void DoesNotHaveLengthTest03() { string a = "test"; Condition.Requires(a).DoesNotHaveLength(3); } [TestMethod] [ExpectedException(typeof(ArgumentException))] [Description("Calling DoesNotHaveLength on string x with 'x.Length = expected length' should fail.")] public void DoesNotHaveLengthTest04() { string a = String.Empty; Condition.Requires(a).DoesNotHaveLength(0); } [TestMethod] [Description("Calling DoesNotHaveLength on string x with 'x.Length != expected length' should pass.")] public void DoesNotHaveLengthTest05() { string a = String.Empty; Condition.Requires(a).DoesNotHaveLength(1); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] [Description("Calling DoesNotHaveLength on string x with 'null = expected length' should fail.")] public void DoesNotHaveLengthTest06() { string a = null; // A null string is considered to have the length of 0. Condition.Requires(a).DoesNotHaveLength(0); } [TestMethod] [Description("Calling DoesNotHaveLength on string x with 'x.Length != expected length' should pass.")] public void DoesNotHaveLengthTest07() { string a = null; // A null string is considered to have the length of 0. Condition.Requires(a).DoesNotHaveLength(1); } [TestMethod] [Description("Calling DoesNotHaveLength with conditionDescription parameter should pass.")] public void DoesNotHaveLengthTest08() { string a = string.Empty; Condition.Requires(a).DoesNotHaveLength(1, string.Empty); } [TestMethod] [Description("Calling a failing DoesNotHaveLength should throw an Exception with an exception message that contains the given parameterized condition description argument.")] public void DoesNotHaveLengthTest09() { string a = null; try { Condition.Requires(a, "a").DoesNotHaveLength(0, "qwe {0} xyz"); Assert.Fail(); } catch (ArgumentException ex) { Assert.IsTrue(ex.Message.Contains("qwe a xyz")); } } [TestMethod] [Description("Calling DoesNotHaveLength on string x with 'x.Length = expected length' should succeed when exceptions are suppressed.")] public void DoesNotHaveLengthTest10() { string a = "test"; Condition.Requires(a).SuppressExceptionsForTest().DoesNotHaveLength(4); } } }
39.878788
182
0.651786
[ "MIT" ]
conditions/conditions
CuttingEdge.Conditions.UnitTests/StringTests/StringDoesNotHaveLengthTests.cs
5,264
C#
using System.Collections.Generic; namespace Pathoschild.Stardew.Automate.Framework.Models { /// <summary>The model for Automate's internal file containing data that can't be derived automatically.</summary> internal class DataModel { /// <summary>The name to use for each floor ID.</summary> public Dictionary<int, string> FloorNames { get; set; } } }
32.083333
118
0.706494
[ "MIT" ]
Alexhia/StardewMods
Automate/Framework/Models/DataModel.cs
385
C#
/* 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 Sys.Workflow.Engine { public interface IDynamicBpmnConstants { } }
36.166667
75
0.734255
[ "Apache-2.0" ]
18502079446/cusss
NActiviti/Sys.Bpm.Engine/Engine/IDynamicBpmnConstants.cs
653
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("04. Distance between Points")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("04. Distance between Points")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("530fec0f-7485-44e1-aed4-b311b9988aac")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.432432
84
0.747539
[ "MIT" ]
IvanKrivulev/Programming-Fundamentals
OBJECTS AND CLASSES/04. Distance between Points/Properties/AssemblyInfo.cs
1,425
C#
using System; using System.Collections.Generic; using Application.Models.Navigation; using Microsoft.AspNetCore.Mvc.Localization; using Microsoft.Extensions.Localization; namespace Application.Models.ViewModels { public interface ILocalizationViewModel : IViewModel { #region Properties INavigationNode Localizers { get; } IDictionary<string, string> Names { get; } IStringLocalizer SelectedLocalizer { get; } Exception SelectedLocalizerException { get; } #endregion #region Methods IDictionary<string, object> GetHtmlLocalizerInformation(IHtmlLocalizer htmlLocalizer); IDictionary<string, object> GetStringLocalizerInformation(IStringLocalizer stringLocalizer); #endregion } }
26.148148
94
0.807365
[ "MIT" ]
RegionOrebroLan/.NET-Localization-Extensions
Source/Samples/Shared-Mvc/Models/ViewModels/ILocalizationViewModel.cs
706
C#
#pragma warning disable CS0618 // Type or member is obsolete namespace Gu.Wpf.Reactive.Tests.Collections.MutableViews.FilterTests { using System; using Microsoft.Reactive.Testing; using NUnit.Framework; public class FilteredViewTestsBase : FilterTests { [SetUp] public override void SetUp() { base.SetUp(); this.Scheduler = new TestScheduler(); #pragma warning disable IDISP007 // Don't dispose injected. this.View?.Dispose(); #pragma warning restore IDISP007 // Don't dispose injected. this.View = new FilteredView<int>(this.Source, x => true, TimeSpan.Zero, this.Scheduler, leaveOpen: true); } } }
33.52381
118
0.660511
[ "MIT" ]
forki/Gu.Reactive
Gu.Wpf.Reactive.Tests/Collections/MutableViews/FilterTests/FilteredViewTestsBase.cs
704
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using VkNet.Enums.Filters; using VkNet.Enums.SafetyEnums; using VkNet.Model; using VkNet.Model.RequestParams; using VkNet.Model.RequestParams.Groups; using VkNet.Utils; namespace VkNet.Abstractions { /// <summary> /// Методы для работы с сообществами (группами). /// </summary> public interface IGroupsCategory : IGroupsCategoryAsync { /// <inheritdoc cref="IGroupsCategoryAsync.AddAddressAsync" /> AddressResult AddAddress(AddAddressParams @params); /// <inheritdoc cref="IGroupsCategoryAsync.EditAddressAsync" /> AddressResult EditAddress(EditAddressParams @params); /// <inheritdoc cref="IGroupsCategoryAsync.DeleteAddressAsync" /> bool DeleteAddress(ulong groupId, ulong addressId); /// <inheritdoc cref="IGroupsCategoryAsync.GetAddressesAsync" /> VkCollection<AddressResult> GetAddresses(GetAddressesParams @params); /// <inheritdoc cref="IGroupsCategoryAsync.JoinAsync" /> bool Join(long? groupId, bool? notSure = null); /// <inheritdoc cref="IGroupsCategoryAsync.LeaveAsync" /> bool Leave(long groupId); /// <inheritdoc cref="IGroupsCategoryAsync.GetAsync" /> VkCollection<Group> Get(GroupsGetParams @params, bool skipAuthorization = false); /// <inheritdoc cref="IGroupsCategoryAsync.GetByIdAsync" /> ReadOnlyCollection<Group> GetById(IEnumerable<string> groupIds, string groupId, GroupsFields fields, bool skipAuthorization = false); /// <inheritdoc cref="IGroupsCategoryAsync.GetMembersAsync" /> VkCollection<User> GetMembers(GroupsGetMembersParams @params, bool skipAuthorization = false); /// <inheritdoc cref="IGroupsCategoryAsync.IsMemberAsync" /> ReadOnlyCollection<GroupMember> IsMember(string groupId, long? userId, IEnumerable<long> userIds, bool? extended, bool skipAuthorization = false); /// <inheritdoc cref="IGroupsCategoryAsync.SearchAsync" /> VkCollection<Group> Search(GroupsSearchParams @params, bool skipAuthorization = false); /// <inheritdoc cref="IGroupsCategoryAsync.GetInvitesAsync" /> VkCollection<Group> GetInvites(long? count, long? offset, bool? extended = null); /// <inheritdoc cref="IGroupsCategoryAsync.BanUserAsync" /> bool BanUser(GroupsBanUserParams @params); /// <inheritdoc cref="IGroupsCategoryAsync.GetBannedAsync" /> VkCollection<GetBannedResult> GetBanned(long groupId, long? offset = null, long? count = null, GroupsFields fields = null, long? ownerId = null); /// <inheritdoc cref="IGroupsCategoryAsync.UnbanUserAsync" /> bool UnbanUser(long groupId, long userId); /// <inheritdoc cref="IGroupsCategoryAsync.EditManagerAsync" /> bool EditManager(GroupsEditManagerParams @params); /// <inheritdoc cref="IGroupsCategoryAsync.GetSettingsAsync" /> GroupsEditParams GetSettings(ulong groupId); /// <inheritdoc cref="IGroupsCategoryAsync.EditAsync" /> bool Edit(GroupsEditParams @params); /// <inheritdoc cref="IGroupsCategoryAsync.EditPlaceAsync" /> [Obsolete(ObsoleteText.Obsolete)] bool EditPlace(long groupId, Place place = null); /// <inheritdoc cref="IGroupsCategoryAsync.GetInvitedUsersAsync" /> VkCollection<User> GetInvitedUsers(long groupId, long? offset = null, long? count = null, UsersFields fields = null, NameCase nameCase = null); /// <inheritdoc cref="IGroupsCategoryAsync.InviteAsync" /> bool Invite(long groupId, long userId); [Obsolete(ObsoleteText.CaptchaNeeded, true)] bool Invite(long groupId, long userId, long? captchaSid = null, string captchaKey = null); /// <inheritdoc cref="IGroupsCategoryAsync.AddLinkAsync" /> ExternalLink AddLink(long groupId, Uri link, string text); /// <inheritdoc cref="IGroupsCategoryAsync.DeleteLinkAsync" /> bool DeleteLink(long groupId, ulong linkId); /// <inheritdoc cref="IGroupsCategoryAsync.EditLinkAsync" /> bool EditLink(long groupId, ulong linkId, string text); /// <inheritdoc cref="IGroupsCategoryAsync.ReorderLinkAsync" /> bool ReorderLink(long groupId, long linkId, long? after); /// <inheritdoc cref="IGroupsCategoryAsync.RemoveUserAsync" /> bool RemoveUser(long groupId, long userId); /// <inheritdoc cref="IGroupsCategoryAsync.ApproveRequestAsync" /> bool ApproveRequest(long groupId, long userId); /// <inheritdoc cref="IGroupsCategoryAsync.CreateAsync" /> Group Create(string title, string description = null, GroupType type = null, GroupSubType? subtype = null, uint? publicCategory = null); /// <inheritdoc cref="IGroupsCategoryAsync.GetRequestsAsync" /> VkCollection<User> GetRequests(long groupId, long? offset, long? count, UsersFields fields); /// <inheritdoc cref="IGroupsCategoryAsync.GetCatalogAsync" /> VkCollection<Group> GetCatalog(ulong? categoryId = null, ulong? subcategoryId = null); /// <inheritdoc cref="IGroupsCategoryAsync.GetCatalogInfoAsync" /> GroupsCatalogInfo GetCatalogInfo(bool? extended = null, bool? subcategories = null); /// <inheritdoc cref="IGroupsCategoryAsync.AddCallbackServerAsync" /> long AddCallbackServer(ulong groupId, string url, string title, string secretKey); /// <inheritdoc cref="IGroupsCategoryAsync.DeleteCallbackServerAsync" /> bool DeleteCallbackServer(ulong groupId, ulong serverId); /// <inheritdoc cref="IGroupsCategoryAsync.EditCallbackServerAsync" /> bool EditCallbackServer(ulong groupId, ulong serverId, string url, string title, string secretKey); /// <inheritdoc cref="IGroupsCategoryAsync.GetCallbackConfirmationCodeAsync" /> string GetCallbackConfirmationCode(ulong groupId); /// <inheritdoc cref="IGroupsCategoryAsync.GetCallbackServersAsync" /> VkCollection<CallbackServerItem> GetCallbackServers(ulong groupId, IEnumerable<ulong> serverIds = null); /// <inheritdoc cref="IGroupsCategoryAsync.GetCallbackSettingsAsync" /> CallbackSettings GetCallbackSettings(ulong groupId, ulong serverId); /// <inheritdoc cref="IGroupsCategoryAsync.SetCallbackSettingsAsync" /> bool SetCallbackSettings(CallbackServerParams @params); /// <inheritdoc cref="IGroupsCategoryAsync.GetLongPollServerAsync" /> LongPollServerResponse GetLongPollServer(ulong groupId); /// <inheritdoc cref="IGroupsCategoryAsync.DisableOnlineAsync" /> bool DisableOnline(ulong groupId); /// <inheritdoc cref="IGroupsCategoryAsync.EnableOnlineAsync" /> bool EnableOnline(ulong groupId); /// <inheritdoc cref="IGroupsCategoryAsync.GetBotsLongPollHistoryAsync" /> BotsLongPollHistoryResponse GetBotsLongPollHistory(BotsLongPollHistoryParams @params); /// <inheritdoc cref="IGroupsCategoryAsync.GetOnlineStatusAsync" /> OnlineStatus GetOnlineStatus(ulong groupId); /// <inheritdoc cref="IGroupsCategoryAsync.GetTokenPermissionsAsync" /> TokenPermissionsResult GetTokenPermissions(); /// <inheritdoc cref="IGroupsCategoryAsync.SetLongPollSettingsAsync" /> bool SetLongPollSettings(SetLongPollSettingsParams @params); /// <inheritdoc cref="IGroupsCategoryAsync.GetLongPollSettingsAsync" /> GetLongPollSettingsResult GetLongPollSettings(ulong groupId); } }
42.854545
124
0.76934
[ "MIT" ]
Azrael141/vk
VkNet/Abstractions/Category/IGroupsCategory.cs
7,107
C#
using Jane.Logging; using System.Threading.Tasks; namespace Jane.PushNotifications { public class NullPushNotificationService : IPushNotificationService { private readonly ILogger Logger; public NullPushNotificationService( ILoggerFactory loggerFactory ) { Logger = loggerFactory.Create(typeof(NullPushNotificationService)); } public Task<bool> SendToDeviceAsync(string deviceToken, string title, string body, string clickAction, dynamic data) { Logger.Warn("USING NullPushNotificationService!"); Logger.Debug("SendToDeviceAsync:"); Logger.Debug($"DeviceToken: {deviceToken}"); Logger.Debug($"Title: {title}"); Logger.Debug($"Body: {body}"); Logger.Debug($"ClickAction: {clickAction}"); Logger.Debug($"Data: {data}"); return Task.FromResult(false); } public Task<bool> SendToTopicAsync(string topic, string title, string body, string clickAction, dynamic data) { Logger.Warn("USING NullPushNotificationService!"); Logger.Debug("SendToTopicAsync:"); Logger.Debug($"Topic: {topic}"); Logger.Debug($"Title: {title}"); Logger.Debug($"Body: {body}"); Logger.Debug($"ClickAction: {clickAction}"); Logger.Debug($"Data: {data}"); return Task.FromResult(false); } } }
36.317073
124
0.599731
[ "Apache-2.0" ]
Caskia/Jane
src/Jane/PushNotifications/NullPushNotificationService.cs
1,491
C#
// CS1581: Invalid return type in XML comment cref attribute `explicit operator intp (Test)' // Line: 7 // Compiler options: -doc:dummy.xml -warnaserror -warn:1 using System; /// <seealso cref="explicit operator intp (Test)"/> public class Test { /// operator. public static explicit operator int (Test t) { return 0; } }
20.625
92
0.7
[ "Apache-2.0" ]
121468615/mono
mcs/errors/cs1581.cs
330
C#
using System.Reflection; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("InteractionsExercise")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("InteractionsExercise")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid("f315b2fb-85a6-4513-a156-59d0f574b097")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.944444
103
0.749661
[ "MIT" ]
tristanles/moq-exercise
InteractionsExercise/Properties/AssemblyInfo.cs
1,499
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Numeria.IO { internal class IndexNode { public const int FILENAME_SIZE = 41; // Size of file name string public const int FILE_EXTENSION_SIZE = 5; // Size of file extension string public const int INDEX_NODE_SIZE = 81; // Node Index size public Guid ID { get; set; } // 16 bytes public bool IsDeleted { get; set; } // 1 byte public IndexLink Right { get; set; } // 5 bytes public IndexLink Left { get; set; } // 5 bytes public uint DataPageID { get; set; } // 4 bytes // Info public string FileName { get; set; } // 41 bytes (file name + extension) public string FileExtension { get; set; } // 5 bytes (only extension without dot ".") public uint FileLength { get; set; } // 4 bytes public IndexPage IndexPage { get; set; } public IndexNode(IndexPage indexPage) { ID = Guid.Empty; IsDeleted = true; // Start with index node mark as deleted. Update this after save all stream on disk Right = new IndexLink(); Left = new IndexLink(); DataPageID = uint.MaxValue; IndexPage = indexPage; } public void UpdateFromEntry(EntryInfo entity) { ID = entity.ID; FileName = Path.GetFileNameWithoutExtension(entity.FileName); FileExtension = Path.GetExtension(entity.FileName).Replace(".", ""); FileLength = entity.FileLength; } } }
33.92
113
0.574882
[ "MIT" ]
ChristianGutman/FileDB
FileDB/Structure/IndexNode.cs
1,698
C#
// Copyright © 2017 Dmitry Sikorsky. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace starsky.foundation.database.Models.Account { public class Credential { /// <summary> /// Database Id /// </summary> public int Id { get; set; } /// <summary> /// The user id /// </summary> public int UserId { get; set; } public int CredentialTypeId { get; set; } /// <summary> /// Email address /// </summary> public string Identifier { get; set; } /// <summary> /// Password /// </summary> public string Secret { get; set; } /// <summary> /// Some hash /// </summary> public string Extra { get; set; } public User User { get; set; } public CredentialType CredentialType { get; set; } } }
26.891892
111
0.523618
[ "MIT" ]
qdraw/starsky
starsky/starsky.foundation.database/Models/Account/Credential.cs
998
C#
/* Copyright 2010-2015 MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading; using System.Threading.Tasks; namespace MongoDB.Driver.Linq { /// <summary> /// An implementation of <see cref="IQueryProvider" /> for MongoDB. /// </summary> internal interface IMongoQueryProvider : IQueryProvider { /// <summary> /// Executes the strongly-typed query represented by a specified expression tree. /// </summary> /// <typeparam name="TResult">The type of the result.</typeparam> /// <param name="expression">An expression tree that represents a LINQ query.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The value that results from executing the specified query.</returns> Task<TResult> ExecuteAsync<TResult>(Expression expression, CancellationToken cancellationToken = default(CancellationToken)); } }
38.341463
133
0.722646
[ "Apache-2.0" ]
InternationNova/MEANJS
src/MongoDB.Driver/Linq/IMongoQueryProvider.cs
1,572
C#
using ToDo.Domain.Entities; namespace ToDo.Domain.Models { public class Endereco { public int PessoaId { get; set; } public string Cep { get; set; } public string Logradouro { get; set; } public int Numero { get; set; } public string Bairro { get; set; } public string Complemento { get; set; } public int CidadeId { get; set; } public virtual Cidade Cidade { get; set; } public virtual Pessoa Pessoa { get; set; } public Endereco() { } public Endereco(int cidadeId, string cep, string logradouro, int numero, string bairro, string complemento) { CidadeId = cidadeId; Cep = cep; Logradouro = logradouro; Numero = numero; Bairro = bairro; Complemento = complemento; } public void Alterar(in int cidadeId, string cep, string logradouro, in int numero, string bairro, string complemento) { CidadeId = cidadeId; Cep = cep; Logradouro = logradouro; Numero = numero; Bairro = bairro; Complemento = complemento; } } }
28.159091
125
0.541566
[ "MIT" ]
Cristianotx/ewave-livraria-senior
ToDo-API/src/ToDo.Domain/Models/Endereco.cs
1,241
C#
using System; using System.Web.Http; using System.Configuration; using System.Collections.Generic; using System.Threading.Tasks; using System.Threading; using NNanomsg.Protocols; using Newtonsoft.Json; using System.Net.Http; using System.Net; namespace DBServer { public class DBController : ApiController { private static readonly PublishSocket _publishSocket = new PublishSocket(); private static readonly DBManager _db = new DBManager(); public DBController() { _publishSocket.Bind(Config.TCPConnection()); Thread.Sleep(500); // time to connect } ~DBController() { _publishSocket.Dispose(); } public class RequestPostParams { public string Command { get; set; } public string Key { get; set; } public string Value { get; set; } } public class ResponseContent { public bool KeyExists { get; set; } public string Value { get; set; } } public HttpResponseMessage Post([FromBody]RequestPostParams postParams) { return HandlePostParams(postParams); } private HttpResponseMessage HandlePostParams(RequestPostParams postParams) { var response = new HttpResponseMessage(HttpStatusCode.OK); if (postParams.Command == "get") { string value = _db.Get(postParams.Key); var responseContent = new ResponseContent { KeyExists = (value != null), Value = (value != null) ? value : "", }; response.Content = new StringContent(JsonConvert.SerializeObject(responseContent)); } else { if (!ProceedWrite(postParams.Command, postParams.Key, postParams.Value)) { response.StatusCode = HttpStatusCode.BadRequest; } } return response; } private bool ProceedWrite(string command, string key, string value) { var commandMessage = new DBUpdateMessage { Command = command, Key = key, Value = value, ServerId = Config.ServerId(), Version = _db.VersionForKey(key) + 1 }; if (!commandMessage.isValid()) { return false; } try { _publishSocket.Send(commandMessage.Encode()); return true; } catch { Console.WriteLine("Exception while trying to publish db updates"); return false; } } } }
28.58
99
0.525892
[ "MIT" ]
alisa-teplouhova/distributed_systems
distributedDB/DistributedDB/DBServer/DBController.cs
2,860
C#
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion: 4.0.30319.42000 // // Änderungen an dieser Datei können fehlerhaftes Verhalten verursachen und gehen verloren, wenn // der Code neu generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace myEVA.Properties { /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder-Klasse // über ein Tool wie ResGen oder Visual Studio automatisch generiert. // Um einen Member hinzuzufügen oder zu entfernen, bearbeiten Sie die .ResX-Datei und führen dann ResGen // mit der Option /str erneut aus, oder erstellen Sie Ihr VS-Projekt neu. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Gibt die zwischengespeicherte ResourceManager-Instanz zurück, die von dieser Klasse verwendet wird. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("myEVA.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// Ressourcenlookups, die diese stark typisierte Ressourcenklasse verwenden. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
41.069444
171
0.623943
[ "MIT" ]
MaikHo/myEVA
myEVA/Properties/Resources.Designer.cs
2,967
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using Microsoft.MixedReality.Toolkit.Editor; using System; using System.Collections.Generic; using UnityEditor; using UnityEngine; #if !UNITY_2019_3_OR_NEWER using System.IO; #endif // !UNITY_2019_3_OR_NEWER namespace Microsoft.MixedReality.Toolkit.Utilities.Editor { /// <summary> /// Utility class that provides methods to both check and configure Unity project for desired settings /// </summary> public class MixedRealityProjectConfigurator { private const int SpatialAwarenessDefaultLayer = 31; private const AndroidSdkVersions MinAndroidSdk = AndroidSdkVersions.AndroidApiLevel24; // Android 7.0 private const int RequirediOSArchitecture = 1; // Per https://docs.unity3d.com/ScriptReference/PlayerSettings.SetArchitecture.html, 1 == ARM64 private const float iOSMinOsVersion = 11.0f; private const string iOSCameraUsageDescription = "Required for augmented reality support."; /// <summary> /// Property used to indicate the currently selected audio spatializer when /// preparing to configure a Mixed Reality Toolkit project. /// </summary> public static string SelectedSpatializer { get; set; } /// <summary> /// List of available configurations to check and configure with this utility /// </summary> public enum Configurations { LatestScriptingRuntime = 1, ForceTextSerialization, VisibleMetaFiles, VirtualRealitySupported, [Obsolete("SinglePassInstancing is obsolete, use OptimalRenderingPath instead")] SinglePassInstancing = 5, OptimalRenderingPath = 5, // using the same value of SinglePassInstancing as a replacement SpatialAwarenessLayer, [Obsolete("EnableMSBuildForUnity is obsolete and is no longer honored.", true)] EnableMSBuildForUnity, AudioSpatializer = 8, // WSA Capabilities SpatialPerceptionCapability = 1000, MicrophoneCapability, InternetClientCapability, #if UNITY_2019_3_OR_NEWER EyeTrackingCapability, NewInputSystem, #endif // UNITY_2019_3_OR_NEWER // Android Settings AndroidMultiThreadedRendering = 2000, AndroidMinSdkVersion, // iOS Settings IOSMinOSVersion = 3000, IOSArchitecture, IOSCameraUsageDescription, #if UNITY_2019_3_OR_NEWER // A workaround for the Unity bug described in https://github.com/microsoft/MixedRealityToolkit-Unity/issues/8326. GraphicsJobWorkaround, #endif // UNITY_2019_3_OR_NEWER }; private class ConfigGetter { /// <summary> /// Array of build targets where the get action is valid /// </summary> public BuildTarget[] ValidTargets; /// <summary> /// Action to perform to determine if the current configuration is correctly enabled /// </summary> public Func<bool> GetAction; public ConfigGetter(Func<bool> get, BuildTarget target = BuildTarget.NoTarget) { GetAction = get; ValidTargets = new BuildTarget[] { target }; } public ConfigGetter(Func<bool> get, BuildTarget[] targets) { GetAction = get; ValidTargets = targets; } /// <summary> /// Returns true if the active build target is contained in the ValidTargets list or the list contains a BuildTarget.NoTarget entry, false otherwise /// </summary> public bool IsActiveBuildTargetValid() { foreach (var buildTarget in ValidTargets) { if (buildTarget == BuildTarget.NoTarget || buildTarget == EditorUserBuildSettings.activeBuildTarget) { return true; } } return false; } } // The check functions for each type of setting private static readonly Dictionary<Configurations, ConfigGetter> ConfigurationGetters = new Dictionary<Configurations, ConfigGetter>() { { Configurations.LatestScriptingRuntime, new ConfigGetter(IsLatestScriptingRuntime) }, { Configurations.ForceTextSerialization, new ConfigGetter(IsForceTextSerialization) }, { Configurations.VisibleMetaFiles, new ConfigGetter(IsVisibleMetaFiles) }, #if !UNITY_2019_3_OR_NEWER { Configurations.VirtualRealitySupported, new ConfigGetter(() => XRSettingsUtilities.LegacyXREnabled) }, #endif // !UNITY_2019_3_OR_NEWER { Configurations.OptimalRenderingPath, new ConfigGetter(MixedRealityOptimizeUtils.IsOptimalRenderingPath) }, { Configurations.SpatialAwarenessLayer, new ConfigGetter(HasSpatialAwarenessLayer) }, { Configurations.AudioSpatializer, new ConfigGetter(SpatializerUtilities.CheckSettings) }, // UWP Capabilities { Configurations.SpatialPerceptionCapability, new ConfigGetter(() => GetCapability(PlayerSettings.WSACapability.SpatialPerception), BuildTarget.WSAPlayer) }, { Configurations.MicrophoneCapability, new ConfigGetter(() => GetCapability(PlayerSettings.WSACapability.Microphone), BuildTarget.WSAPlayer) }, { Configurations.InternetClientCapability, new ConfigGetter(() => GetCapability(PlayerSettings.WSACapability.InternetClient), BuildTarget.WSAPlayer) }, #if UNITY_2019_3_OR_NEWER { Configurations.EyeTrackingCapability, new ConfigGetter(() => GetCapability(PlayerSettings.WSACapability.GazeInput), BuildTarget.WSAPlayer) }, #endif // UNITY_2019_3_OR_NEWER #if UNITY_2019_3_OR_NEWER { Configurations.NewInputSystem, new ConfigGetter(() => { SerializedObject settings = new SerializedObject(Unsupported.GetSerializedAssetInterfaceSingleton(nameof(PlayerSettings))); SerializedProperty newInputEnabledProp = settings?.FindProperty("activeInputHandler"); return newInputEnabledProp?.intValue != 1; }) }, #endif // UNITY_2019_3_OR_NEWER // Android Settings { Configurations.AndroidMultiThreadedRendering, new ConfigGetter(() => !PlayerSettings.GetMobileMTRendering(BuildTargetGroup.Android), BuildTarget.Android) }, { Configurations.AndroidMinSdkVersion, new ConfigGetter(() => PlayerSettings.Android.minSdkVersion >= MinAndroidSdk, BuildTarget.Android) }, // iOS Settings { Configurations.IOSMinOSVersion, new ConfigGetter(() => float.TryParse(PlayerSettings.iOS.targetOSVersionString, out float version) && version >= iOSMinOsVersion, BuildTarget.iOS) }, { Configurations.IOSArchitecture, new ConfigGetter(() => PlayerSettings.GetArchitecture(BuildTargetGroup.iOS) == RequirediOSArchitecture, BuildTarget.iOS) }, { Configurations.IOSCameraUsageDescription, new ConfigGetter(() => !string.IsNullOrWhiteSpace(PlayerSettings.iOS.cameraUsageDescription), BuildTarget.iOS) }, #if UNITY_2019_3_OR_NEWER { Configurations.GraphicsJobWorkaround, new ConfigGetter(() => !PlayerSettings.graphicsJobs, BuildTarget.WSAPlayer) }, #endif // UNITY_2019_3_OR_NEWER }; // The configure functions for each type of setting private static readonly Dictionary<Configurations, Action> ConfigurationSetters = new Dictionary<Configurations, Action>() { { Configurations.LatestScriptingRuntime, SetLatestScriptingRuntime }, { Configurations.ForceTextSerialization, SetForceTextSerialization }, { Configurations.VisibleMetaFiles, SetVisibleMetaFiles }, #if !UNITY_2019_3_OR_NEWER { Configurations.VirtualRealitySupported, () => XRSettingsUtilities.LegacyXREnabled = true }, #endif // !UNITY_2019_3_OR_NEWER { Configurations.OptimalRenderingPath, MixedRealityOptimizeUtils.SetOptimalRenderingPath }, { Configurations.SpatialAwarenessLayer, SetSpatialAwarenessLayer }, { Configurations.AudioSpatializer, SetAudioSpatializer }, // UWP Capabilities { Configurations.SpatialPerceptionCapability, () => PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.SpatialPerception, true) }, { Configurations.MicrophoneCapability, () => PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.Microphone, true) }, { Configurations.InternetClientCapability, () => PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.InternetClient, true) }, #if UNITY_2019_3_OR_NEWER { Configurations.EyeTrackingCapability, () => PlayerSettings.WSA.SetCapability(PlayerSettings.WSACapability.GazeInput, true) }, #endif // UNITY_2019_3_OR_NEWER #if UNITY_2019_3_OR_NEWER { Configurations.NewInputSystem, () => { if (EditorUtility.DisplayDialog("Unity editor restart required", "The Unity editor must be restarted for the input system change to take effect. Cancel or apply.", "Apply", "Cancel")) { SerializedObject settings = new SerializedObject(Unsupported.GetSerializedAssetInterfaceSingleton(nameof(PlayerSettings))); if (settings != null) { settings.Update(); SerializedProperty activeInputHandlerProperty = settings.FindProperty("activeInputHandler"); if (activeInputHandlerProperty != null) { activeInputHandlerProperty.intValue = 2; settings.ApplyModifiedProperties(); typeof(EditorApplication).GetMethod("RestartEditorAndRecompileScripts", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static)?.Invoke(null, null); } } }} }, #endif // UNITY_2019_3_OR_NEWER // Android Settings { Configurations.AndroidMultiThreadedRendering, () => PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Android, false) }, { Configurations.AndroidMinSdkVersion, () => PlayerSettings.Android.minSdkVersion = MinAndroidSdk }, // iOS Settings { Configurations.IOSMinOSVersion, () => PlayerSettings.iOS.targetOSVersionString = iOSMinOsVersion.ToString("n1") }, { Configurations.IOSArchitecture, () => PlayerSettings.SetArchitecture(BuildTargetGroup.iOS, RequirediOSArchitecture) }, { Configurations.IOSCameraUsageDescription, () => PlayerSettings.iOS.cameraUsageDescription = iOSCameraUsageDescription }, #if UNITY_2019_3_OR_NEWER { Configurations.GraphicsJobWorkaround, () => PlayerSettings.graphicsJobs = false }, #endif // UNITY_2019_3_OR_NEWER }; /// <summary> /// Checks whether the supplied setting type has been properly configured /// </summary> /// <param name="config">The setting configuration that needs to be checked</param> /// <returns>true if properly configured, false otherwise</returns> public static bool IsConfigured(Configurations config) { if (ConfigurationGetters.ContainsKey(config)) { var configGetter = ConfigurationGetters[config]; if (configGetter.IsActiveBuildTargetValid()) { return configGetter.GetAction.Invoke(); } } return false; } /// <summary> /// Configures the supplied setting type to the desired values for MRTK /// </summary> /// <param name="config">The setting configuration that needs to be checked</param> public static void Configure(Configurations config) { // We use the config getter to check to see if a configuration is valid for the current build target. if (ConfigurationGetters.ContainsKey(config)) { var configGetter = ConfigurationGetters[config]; if (configGetter.IsActiveBuildTargetValid() && ConfigurationSetters.ContainsKey(config)) { ConfigurationSetters[config].Invoke(); } } } /// <summary> /// Is this Unity project configured for all setting types properly /// </summary> /// <returns>true if entire project is configured as recommended, false otherwise</returns> public static bool IsProjectConfigured() { foreach (var configGetter in ConfigurationGetters) { if (configGetter.Value.IsActiveBuildTargetValid() && !configGetter.Value.GetAction.Invoke()) { return false; } } return true; } /// <summary> /// Configures the Unity project properly for the list of setting types provided. If null, configures all possibles setting types /// </summary> /// <param name="filter">List of setting types to target with configure action</param> public static void ConfigureProject(HashSet<Configurations> filter = null) { if (filter == null) { foreach (var setter in ConfigurationSetters) { Configure(setter.Key); } } else { foreach (var key in filter) { Configure(key); } } AssetDatabase.SaveAssets(); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); } /// <summary> /// Checks if current Unity project has latest scripting runtime /// </summary> public static bool IsLatestScriptingRuntime() { #if !UNITY_2019_3_OR_NEWER return PlayerSettings.scriptingRuntimeVersion == ScriptingRuntimeVersion.Latest; #else return true; #endif // UNITY_2019_3_OR_NEWER } /// <summary> /// Configures current Unity project to use latest scripting runtime and reloads project /// </summary> public static void SetLatestScriptingRuntime() { #if !UNITY_2019_3_OR_NEWER PlayerSettings.scriptingRuntimeVersion = ScriptingRuntimeVersion.Latest; EditorApplication.OpenProject(Directory.GetParent(Application.dataPath).ToString()); #endif // UNITY_2019_3_OR_NEWER } /// <summary> /// Checks if current Unity projects uses force text serialization /// </summary> public static bool IsForceTextSerialization() { return EditorSettings.serializationMode == SerializationMode.ForceText; } /// <summary> /// Configures current Unity project to force text serialization /// </summary> public static void SetForceTextSerialization() { EditorSettings.serializationMode = SerializationMode.ForceText; } /// <summary> /// Checks if current Unity project uses visible meta files /// </summary> public static bool IsVisibleMetaFiles() { #if UNITY_2020_1_OR_NEWER return VersionControlSettings.mode.Equals("Visible Meta Files"); #else return EditorSettings.externalVersionControl.Equals("Visible Meta Files"); #endif // UNITY_2020_1_OR_NEWER } /// <summary> /// Configures current Unity project to enabled visible meta files /// </summary> public static void SetVisibleMetaFiles() { #if UNITY_2020_1_OR_NEWER VersionControlSettings.mode = "Visible Meta Files"; #else EditorSettings.externalVersionControl = "Visible Meta Files"; #endif // UNITY_2020_1_OR_NEWER } /// <summary> /// Checks if current Unity project has the default Spatial Awareness layer set in the Layers settings /// </summary> public static bool HasSpatialAwarenessLayer() { return !string.IsNullOrEmpty(LayerMask.LayerToName(SpatialAwarenessDefaultLayer)); } /// <summary> /// Configures current Unity project to use the audio spatializer specified by the <see cref="SelectedSpatializer"/> property. /// </summary> public static void SetAudioSpatializer() { SpatializerUtilities.SaveSettings(SelectedSpatializer); } /// <summary> /// Configures current Unity project to contain the default Spatial Awareness layer set in the Layers settings /// </summary> public static void SetSpatialAwarenessLayer() { if (!HasSpatialAwarenessLayer()) { if (!EditorLayerExtensions.SetupLayer(SpatialAwarenessDefaultLayer, "Spatial Awareness")) { Debug.LogWarning(string.Format($"Can't modify project layers. It's possible the format of the layers and tags data has changed in this version of Unity. Set layer {SpatialAwarenessDefaultLayer} to \"Spatial Awareness\" manually via Project Settings > Tags and Layers window.")); } } } /// <summary> /// Discover and set the appropriate XR Settings for virtual reality supported for the current build target. /// </summary> /// <remarks>Has no effect on Unity 2020 or newer. Will be updated if a replacement API is provided by Unity.</remarks> public static void ApplyXRSettings() { #if !UNITY_2020_1_OR_NEWER // Ensure compatibility with the pre-2019.3 XR architecture for customers / platforms // with legacy requirements. #pragma warning disable 0618 BuildTargetGroup targetGroup = EditorUserBuildSettings.selectedBuildTargetGroup; List<string> targetSDKs = new List<string>(); foreach (string sdk in PlayerSettings.GetAvailableVirtualRealitySDKs(targetGroup)) { if (sdk.Contains("OpenVR") || sdk.Contains("Windows")) { targetSDKs.Add(sdk); } } if (targetSDKs.Count != 0) { PlayerSettings.SetVirtualRealitySDKs(targetGroup, targetSDKs.ToArray()); PlayerSettings.SetVirtualRealitySupported(targetGroup, true); } #pragma warning restore 0618 #endif // !UNITY_2020_1_OR_NEWER } private static bool GetCapability(PlayerSettings.WSACapability capability) { return !MixedRealityOptimizeUtils.IsBuildTargetUWP() || PlayerSettings.WSA.GetCapability(capability); } } }
45.234043
298
0.642782
[ "MIT" ]
AdrianaMusic/MixedRealityToolkit-Unity
Assets/MRTK/Core/Utilities/Editor/Setup/MixedRealityProjectConfigurator.cs
19,136
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("Chapter25Project")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Datasim Education BV")] [assembly: AssemblyProduct("Chapter25Project")] [assembly: AssemblyCopyright("Copyright © Datasim Education BV 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("15629d16-feac-456a-919e-3a2a661928f1")] // 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")]
40.027027
85
0.732613
[ "MIT" ]
jdm7dv/financial
windows/CsForFinancialMarketsPart2/Chapter25/Chapter25Project/Chapter25Project/Properties/AssemblyInfo.cs
1,484
C#
using ClientCore; using ClientCore.CnCNet5; using ClientGUI; using Microsoft.Xna.Framework; using Rampastring.XNAUI; using Rampastring.XNAUI.XNAControls; using System; using System.Collections.Generic; namespace DTAConfig.OptionPanels { class CnCNetOptionsPanel : XNAOptionsPanel { public CnCNetOptionsPanel(WindowManager windowManager, UserINISettings iniSettings, GameCollection gameCollection) : base(windowManager, iniSettings) { this.gameCollection = gameCollection; } XNAClientCheckBox chkPingUnofficialTunnels; XNAClientCheckBox chkWriteInstallPathToRegistry; XNAClientCheckBox chkPlaySoundOnGameHosted; XNAClientCheckBox chkNotifyOnUserListChange; XNAClientCheckBox chkSkipLoginWindow; XNAClientCheckBox chkPersistentMode; XNAClientCheckBox chkConnectOnStartup; XNAClientCheckBox chkDiscordIntegration; XNAClientCheckBox chkAllowGameInvitesFromFriendsOnly; GameCollection gameCollection; List<XNAClientCheckBox> followedGameChks = new List<XNAClientCheckBox>(); public override void Initialize() { base.Initialize(); Name = "CnCNetOptionsPanel"; chkPingUnofficialTunnels = new XNAClientCheckBox(WindowManager); chkPingUnofficialTunnels.Name = "chkPingUnofficialTunnels"; chkPingUnofficialTunnels.ClientRectangle = new Rectangle(12, 12, 0, 0); chkPingUnofficialTunnels.Text = "Ping unofficial CnCNet tunnels"; AddChild(chkPingUnofficialTunnels); chkWriteInstallPathToRegistry = new XNAClientCheckBox(WindowManager); chkWriteInstallPathToRegistry.Name = "chkWriteInstallPathToRegistry"; chkWriteInstallPathToRegistry.ClientRectangle = new Rectangle( chkPingUnofficialTunnels.X, chkPingUnofficialTunnels.Bottom + 12, 0, 0); chkWriteInstallPathToRegistry.Text = "Write game installation path to Windows" + Environment.NewLine + "Registry (makes it possible to join" + Environment.NewLine + "other games' game rooms on CnCNet)"; AddChild(chkWriteInstallPathToRegistry); chkPlaySoundOnGameHosted = new XNAClientCheckBox(WindowManager); chkPlaySoundOnGameHosted.Name = "chkPlaySoundOnGameHosted"; chkPlaySoundOnGameHosted.ClientRectangle = new Rectangle( chkPingUnofficialTunnels.X, chkWriteInstallPathToRegistry.Bottom + 12, 0, 0); chkPlaySoundOnGameHosted.Text = "Play sound when a game is hosted"; AddChild(chkPlaySoundOnGameHosted); chkNotifyOnUserListChange = new XNAClientCheckBox(WindowManager); chkNotifyOnUserListChange.Name = "chkNotifyOnUserListChange"; chkNotifyOnUserListChange.ClientRectangle = new Rectangle( chkPingUnofficialTunnels.X, chkPlaySoundOnGameHosted.Bottom + 12, 0, 0); chkNotifyOnUserListChange.Text = "Show player join / quit messages" + Environment.NewLine + "on CnCNet lobby"; AddChild(chkNotifyOnUserListChange); chkSkipLoginWindow = new XNAClientCheckBox(WindowManager); chkSkipLoginWindow.Name = "chkSkipLoginWindow"; chkSkipLoginWindow.ClientRectangle = new Rectangle( 276, 12, 0, 0); chkSkipLoginWindow.Text = "Skip login dialog"; chkSkipLoginWindow.CheckedChanged += ChkSkipLoginWindow_CheckedChanged; AddChild(chkSkipLoginWindow); chkPersistentMode = new XNAClientCheckBox(WindowManager); chkPersistentMode.Name = "chkPersistentMode"; chkPersistentMode.ClientRectangle = new Rectangle( chkSkipLoginWindow.X, chkSkipLoginWindow.Bottom + 12, 0, 0); chkPersistentMode.Text = "Stay connected outside of the CnCNet lobby"; chkPersistentMode.CheckedChanged += ChkPersistentMode_CheckedChanged; AddChild(chkPersistentMode); chkConnectOnStartup = new XNAClientCheckBox(WindowManager); chkConnectOnStartup.Name = "chkConnectOnStartup"; chkConnectOnStartup.ClientRectangle = new Rectangle( chkSkipLoginWindow.X, chkPersistentMode.Bottom + 12, 0, 0); chkConnectOnStartup.Text = "Connect automatically on client startup"; chkConnectOnStartup.AllowChecking = false; AddChild(chkConnectOnStartup); chkDiscordIntegration = new XNAClientCheckBox(WindowManager); chkDiscordIntegration.Name = "chkDiscordIntegration"; chkDiscordIntegration.ClientRectangle = new Rectangle( chkSkipLoginWindow.X, chkConnectOnStartup.Bottom + 12, 0, 0); chkDiscordIntegration.Text = "Show detailed game info in Discord status"; if (String.IsNullOrEmpty(ClientConfiguration.Instance.DiscordAppId)) { chkDiscordIntegration.AllowChecking = false; chkDiscordIntegration.Checked = false; } else { chkDiscordIntegration.AllowChecking = true; } AddChild(chkDiscordIntegration); chkAllowGameInvitesFromFriendsOnly = new XNAClientCheckBox(WindowManager); chkAllowGameInvitesFromFriendsOnly.Name = "chkAllowGameInvitesFromFriendsOnly"; chkAllowGameInvitesFromFriendsOnly.ClientRectangle = new Rectangle( chkDiscordIntegration.X, chkDiscordIntegration.Bottom + 12, 0, 0); chkAllowGameInvitesFromFriendsOnly.Text = "Only receive game invitations from friends"; AddChild(chkAllowGameInvitesFromFriendsOnly); var lblFollowedGames = new XNALabel(WindowManager); lblFollowedGames.Name = "lblFollowedGames"; lblFollowedGames.ClientRectangle = new Rectangle( chkNotifyOnUserListChange.X, chkNotifyOnUserListChange.Bottom + 24, 0, 0); lblFollowedGames.Text = "Show game rooms from the following games:"; AddChild(lblFollowedGames); int chkCount = 0; int chkCountPerColumn = 5; int nextColumnXOffset = 0; int columnXOffset = 0; foreach (CnCNetGame game in gameCollection.GameList) { if (!game.Supported || string.IsNullOrEmpty(game.GameBroadcastChannel)) continue; if (chkCount == chkCountPerColumn) { chkCount = 0; columnXOffset += nextColumnXOffset + 6; nextColumnXOffset = 0; } var panel = new XNAPanel(WindowManager); panel.Name = "panel" + game.InternalName; panel.ClientRectangle = new Rectangle(chkPingUnofficialTunnels.X + columnXOffset, lblFollowedGames.Bottom + 12 + chkCount * 22, 16, 16); panel.DrawBorders = false; panel.BackgroundTexture = game.Texture; var chkBox = new XNAClientCheckBox(WindowManager); chkBox.Name = game.InternalName.ToUpper(); chkBox.ClientRectangle = new Rectangle( panel.Right + 6, panel.Y, 0, 0); chkBox.Text = game.UIName; chkCount++; AddChild(panel); AddChild(chkBox); followedGameChks.Add(chkBox); if (chkBox.Right > nextColumnXOffset) nextColumnXOffset = chkBox.Right; } } private void ChkSkipLoginWindow_CheckedChanged(object sender, EventArgs e) { CheckConnectOnStartupAllowance(); } private void ChkPersistentMode_CheckedChanged(object sender, EventArgs e) { CheckConnectOnStartupAllowance(); } private void CheckConnectOnStartupAllowance() { if (!chkSkipLoginWindow.Checked || !chkPersistentMode.Checked) { chkConnectOnStartup.AllowChecking = false; chkConnectOnStartup.Checked = false; return; } chkConnectOnStartup.AllowChecking = true; } public override void Load() { base.Load(); chkPingUnofficialTunnels.Checked = IniSettings.PingUnofficialCnCNetTunnels; chkWriteInstallPathToRegistry.Checked = IniSettings.WritePathToRegistry; chkPlaySoundOnGameHosted.Checked = IniSettings.PlaySoundOnGameHosted; chkNotifyOnUserListChange.Checked = IniSettings.NotifyOnUserListChange; chkConnectOnStartup.Checked = IniSettings.AutomaticCnCNetLogin; chkSkipLoginWindow.Checked = IniSettings.SkipConnectDialog; chkPersistentMode.Checked = IniSettings.PersistentMode; chkDiscordIntegration.Checked = !String.IsNullOrEmpty(ClientConfiguration.Instance.DiscordAppId) && IniSettings.DiscordIntegration; chkAllowGameInvitesFromFriendsOnly.Checked = IniSettings.AllowGameInvitesFromFriendsOnly; string localGame = ClientConfiguration.Instance.LocalGame; foreach (var chkBox in followedGameChks) { if (chkBox.Name == localGame) { chkBox.AllowChecking = false; chkBox.Checked = true; IniSettings.SettingsIni.SetBooleanValue("Channels", localGame, true); continue; } chkBox.Checked = IniSettings.IsGameFollowed(chkBox.Name); } } public override bool Save() { bool restartRequired = base.Save(); IniSettings.PingUnofficialCnCNetTunnels.Value = chkPingUnofficialTunnels.Checked; IniSettings.WritePathToRegistry.Value = chkWriteInstallPathToRegistry.Checked; IniSettings.PlaySoundOnGameHosted.Value = chkPlaySoundOnGameHosted.Checked; IniSettings.NotifyOnUserListChange.Value = chkNotifyOnUserListChange.Checked; IniSettings.AutomaticCnCNetLogin.Value = chkConnectOnStartup.Checked; IniSettings.SkipConnectDialog.Value = chkSkipLoginWindow.Checked; IniSettings.PersistentMode.Value = chkPersistentMode.Checked; if (!String.IsNullOrEmpty(ClientConfiguration.Instance.DiscordAppId)) { restartRequired = IniSettings.DiscordIntegration != chkDiscordIntegration.Checked; IniSettings.DiscordIntegration.Value = chkDiscordIntegration.Checked; } IniSettings.AllowGameInvitesFromFriendsOnly.Value = chkAllowGameInvitesFromFriendsOnly.Checked; foreach (var chkBox in followedGameChks) { IniSettings.SettingsIni.SetBooleanValue("Channels", chkBox.Name, chkBox.Checked); } return restartRequired; } } }
42.547794
115
0.624125
[ "MIT" ]
Metadorius/xna-cncnet-client
DTAConfig/OptionPanels/CnCNetOptionsPanel.cs
11,304
C#
using System; using System.Text; using System.Collections; using System.Collections.Generic; using UnityEngine.Networking; #if UNITY_EDITOR using UnityEditor; #endif namespace IRT.Unity { public class UnityTransportGeneric<C>: IClientTransport<C> where C: class, IClientTransportContext { private const string CACHE_CONTROL_HEADER_KEY = "Cache-Control"; private const string CACHE_CONTROL_HEADER_VALUES = "private, max-age=0, no-cache, no-store"; private const string PRAGMA_HEADER_KEY = "Pragma"; private const string PRAGMA_HEADER_VALUES = "no-cache"; private IJsonMarshaller Marshaller; private string endpoint; public string Endpoint { get { return endpoint; } set { endpoint = value; if (!endpoint.EndsWith("\\") && !endpoint.EndsWith("/")) { endpoint += "/"; } } } public int ActiveRequests { get; private set; } public int Timeout; // In Seconds public IDictionary<string, string> HttpHeaders; #if !UNITY_EDITOR public Action<IEnumerator> CoroutineProcessor; #endif #if !UNITY_EDITOR public UnityTransportGeneric(string endpoint, IJsonMarshaller marshaller, Action<IEnumerator> coroutineProcessor, int timeout = 60) { Endpoint = endpoint; Marshaller = marshaller; Timeout = timeout; CoroutineProcessor = coroutineProcessor; ActiveRequests = 0; } #else public UnityTransportGeneric(string endpoint, IJsonMarshaller marshaller, int timeout = 60) { Endpoint = endpoint; Marshaller = marshaller; Timeout = timeout; ActiveRequests = 0; } #endif protected UnityWebRequest PrepareRequest<I>(string service, string method, I payload) { var request = new UnityWebRequest { downloadHandler = new DownloadHandlerBuffer(), url = string.Format("{0}/{1}/{2}", endpoint, service, method), method = payload == null ? "GET" : "POST" }; if (HttpHeaders != null) { foreach (KeyValuePair<string, string> kv in HttpHeaders) { request.SetRequestHeader(kv.Key, kv.Value); } } // API cached requests might be a pain, let's suppress that request.SetRequestHeader(CACHE_CONTROL_HEADER_KEY, CACHE_CONTROL_HEADER_VALUES); request.SetRequestHeader(PRAGMA_HEADER_KEY, PRAGMA_HEADER_VALUES); if (payload != null) { var data = Marshaller.Marshal<I>(payload); if (data == null) { throw new TransportException("UnityTransport only supports Marshallers which return a string."); } byte[] bytes = Encoding.UTF8.GetBytes(data); request.uploadHandler = new UploadHandlerRaw(bytes) { contentType = "application/json" }; } request.timeout = Timeout; return request; } public void Send<I, O>(string service, string method, I payload, ClientTransportCallback<O> callback, C ctx) { #if !UNITY_EDITOR if (CoroutineProcessor == null) { callback.Failure( new TransportException( "UnityTransport requires a coroutine processor to be present before any requests can be executed.") ); return; } #endif try { #if !UNITY_EDITOR CoroutineProcessor(ProcessRequest(PrepareRequest(service, method, payload), callback)); #else ProcessRequest(PrepareRequest(service, method, payload), callback); #endif } catch (Exception ex) { callback.Failure( new TransportException(string.Format("Unexpected exception {0}\n{1}", ex.Message, ex.StackTrace)) ); } } #if !UNITY_EDITOR protected IEnumerator ProcessRequest<O>(UnityWebRequest req, ClientTransportCallback<O> callback) { ActiveRequests++; yield return req.Send(); ActiveRequests--; if (req.isError) { callback.Failure(new TransportException("Request failed: " + req.error)); yield break; } ProcessResponse(req.downloadHandler.text, req.GetResponseHeaders(), callback); } #else protected void ProcessRequest<T>(UnityWebRequest request, ClientTransportCallback<T> callback) { Wait(() => !request.isDone, () => { if (request.isError) { callback.Failure(new TransportException("Request failed: " + request.error)); return; } ProcessResponse(request.downloadHandler.text, request.GetResponseHeaders(), callback); }); request.Send(); } #endif protected void ProcessResponse<O>(string text, Dictionary<string, string> headers, ClientTransportCallback<O> callback) { try { if (string.IsNullOrEmpty(text)) { throw new TransportException("Empty response."); } var data = Marshaller.Unmarshal<O>(text); callback.Success(data); } catch (Exception ex) { callback.Failure( new TransportException(string.Format("Unexpected exception {0}\n{1}", ex.Message, ex.StackTrace)) ); } } #if UNITY_EDITOR private class EditorHandler { public EditorApplication.CallbackFunction Callback; } private static void Wait(Func<bool> waitUntil, Action callback) { EditorHandler editorHandler = null; editorHandler = new EditorHandler { Callback = () => { if (waitUntil()) { return; } EditorApplication.update -= editorHandler.Callback; callback(); } }; EditorApplication.update += editorHandler.Callback; } #endif } public class UnityTransport : UnityTransportGeneric<IClientTransportContext> { #if !UNITY_EDITOR public UnityTransport(string endpoint, IJsonMarshaller marshaller, Action<IEnumerator> coroutineProcessor, int timeout = 60) : base(endpoint, marshaller, coroutineProcessor, timeout) { } #else public UnityTransport(string endpoint, IJsonMarshaller marshaller, int timeout = 60) : base(endpoint, marshaller, timeout) { } #endif } }
37.918033
123
0.571552
[ "BSD-2-Clause" ]
kaishh/izumi-r2
idealingua/idealingua-runtime-rpc-c-sharp/src/main/resources/runtime/csharp/irt/UnityTransport.cs
6,939
C#
namespace UniversalModels { public class Product { public int PartNumber { get; set; } public string PartName { get; set; } public string PartDescription { get; set; } public decimal UnitPrice { get; set; } public string UnitOfMeasure { get; set; } public decimal SalePercent { get; set; } public string ImageLink { get; set; } public string ImageCredit { get; set; } public int Inventory { get; set; } public Product(int partNumber, string partName, string partDescription, decimal unitPrice, string unitOfMeasure, decimal salePercent, string imageLink, string imageCredit, int inventory) { PartNumber = partNumber; PartName = partName; PartDescription = partDescription; UnitPrice = unitPrice; UnitOfMeasure = unitOfMeasure; SalePercent = salePercent; ImageLink = imageLink; ImageCredit = imageCredit; Inventory = inventory; } } }
36.965517
79
0.599813
[ "MIT" ]
03012021-dotnet-uta/MatthewGrimsley_p1
UniversalModels/Product.cs
1,072
C#
//This is a new class that represents a progress object. using System; using System.IO; using System.IO.Compression; public class ZipProgress { public ZipProgress(int total, int processed, string currentItem) { Total = total; Processed = processed; CurrentItem = currentItem; } public int Total { get; } public int Processed { get; } public string CurrentItem { get; } } public static class MyZipFileExtensions { public static void ExtractToDirectory(this ZipArchive source, string destinationDirectoryName, IProgress<ZipProgress> progress) { ExtractToDirectory(source, destinationDirectoryName, progress, overwrite: false); } public static void ExtractToDirectory(this ZipArchive source, string destinationDirectoryName, IProgress<ZipProgress> progress, bool overwrite) { if (source == null) throw new ArgumentNullException(nameof(source)); if (destinationDirectoryName == null) throw new ArgumentNullException(nameof(destinationDirectoryName)); // Rely on Directory.CreateDirectory for validation of destinationDirectoryName. // Note that this will give us a good DirectoryInfo even if destinationDirectoryName exists: DirectoryInfo di = Directory.CreateDirectory(destinationDirectoryName); string destinationDirectoryFullPath = di.FullName; int count = 0; foreach (ZipArchiveEntry entry in source.Entries) { count++; string fileDestinationPath = Path.GetFullPath(Path.Combine(destinationDirectoryFullPath, entry.FullName)); if (!fileDestinationPath.StartsWith(destinationDirectoryFullPath, StringComparison.OrdinalIgnoreCase)) throw new IOException("File is extracting to outside of the folder specified."); var zipProgress = new ZipProgress(source.Entries.Count, count, entry.FullName); progress.Report(zipProgress); if (Path.GetFileName(fileDestinationPath).Length == 0) { // If it is a directory: if (entry.Length != 0) throw new IOException("Directory entry with data."); Directory.CreateDirectory(fileDestinationPath); } else { // If it is a file: // Create containing directory: Directory.CreateDirectory(Path.GetDirectoryName(fileDestinationPath)); entry.ExtractToFile(fileDestinationPath, overwrite: overwrite); } } } }
36.732394
147
0.662193
[ "MIT" ]
nmxi/Unity_iMobileDeviceNet_ClientBuilder
Assets/Scripts/ZipProgress.cs
2,610
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Primitives; using Yarp.ReverseProxy.Configuration; using Yarp.ReverseProxy.Model; namespace Yarp.ReverseProxy.SessionAffinity { internal sealed class CustomHeaderSessionAffinityPolicy : BaseSessionAffinityPolicy<string> { public CustomHeaderSessionAffinityPolicy( IDataProtectionProvider dataProtectionProvider, ILogger<CustomHeaderSessionAffinityPolicy> logger) : base(dataProtectionProvider, logger) {} public override string Name => SessionAffinityConstants.Policies.CustomHeader; protected override string GetDestinationAffinityKey(DestinationState destination) { return destination.DestinationId; } protected override (string? Key, bool ExtractedSuccessfully) GetRequestAffinityKey(HttpContext context, ClusterState cluster, SessionAffinityConfig config) { var customHeaderName = config.AffinityKeyName; var keyHeaderValues = context.Request.Headers[customHeaderName]; if (StringValues.IsNullOrEmpty(keyHeaderValues)) { // It means affinity key is not defined that is a successful case return (Key: null, ExtractedSuccessfully: true); } if (keyHeaderValues.Count > 1) { // Multiple values is an ambiguous case which is considered a key extraction failure Log.RequestAffinityHeaderHasMultipleValues(Logger, customHeaderName, keyHeaderValues.Count); return (Key: null, ExtractedSuccessfully: false); } return Unprotect(keyHeaderValues[0]); } protected override void SetAffinityKey(HttpContext context, ClusterState cluster, SessionAffinityConfig config, string unencryptedKey) { context.Response.Headers.Append(config.AffinityKeyName, Protect(unencryptedKey)); } private static class Log { private static readonly Action<ILogger, string, int, Exception?> _requestAffinityHeaderHasMultipleValues = LoggerMessage.Define<string, int>( LogLevel.Error, EventIds.RequestAffinityHeaderHasMultipleValues, "The request affinity header `{headerName}` has `{valueCount}` values."); public static void RequestAffinityHeaderHasMultipleValues(ILogger logger, string headerName, int valueCount) { _requestAffinityHeaderHasMultipleValues(logger, headerName, valueCount, null); } } } }
40.623188
163
0.688191
[ "MIT" ]
BennyM/reverse-proxy
src/ReverseProxy/SessionAffinity/CustomHeaderSessionAffinityPolicy.cs
2,803
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.Nat.V2.Model { /// <summary> /// 创建DNAT规则的请求体。 /// </summary> public class CreateNatGatewayDnatRuleOption { /// <summary> /// /// </summary> [JsonProperty("dnat_rule", NullValueHandling = NullValueHandling.Ignore)] public CreateNatGatewayDnatOption DnatRule { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class CreateNatGatewayDnatRuleOption {\n"); sb.Append(" dnatRule: ").Append(DnatRule).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as CreateNatGatewayDnatRuleOption); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(CreateNatGatewayDnatRuleOption input) { if (input == null) return false; return ( this.DnatRule == input.DnatRule || (this.DnatRule != null && this.DnatRule.Equals(input.DnatRule)) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.DnatRule != null) hashCode = hashCode * 59 + this.DnatRule.GetHashCode(); return hashCode; } } } }
26.934211
81
0.521251
[ "Apache-2.0" ]
cnblogs/huaweicloud-sdk-net-v3
Services/Nat/V2/Model/CreateNatGatewayDnatRuleOption.cs
2,065
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; // II.25 File format extensions to PE sealed class FileFormat : ICanRead { public PEHeader PEHeader; public Section[] Sections; public CodeNode Read(Stream stream) { Singletons.Reset(); var node = new CodeNode { stream.ReadClass(ref PEHeader), }; Sections = PEHeader.SectionHeaders.Select(header => new Section(header, PEHeader.PEOptionalHeader.PEHeaderHeaderDataDirectories, PEHeader.PEOptionalHeader.PEHeaderStandardFields.EntryPointRVA)).ToArray(); node.Add(stream.ReadClasses(ref Sections)); for (var i = 0; i < Sections.Length; ++i) { Sections[i].CallBack(); } return node; } } // II.25.2 sealed class PEHeader : ICanRead { public DosHeader DosHeader; public PESignature PESignature; public PEFileHeader PEFileHeader; public PEOptionalHeader PEOptionalHeader; public SectionHeader[] SectionHeaders; public CodeNode Read(Stream stream) { var node = new CodeNode { stream.ReadStruct(out DosHeader), stream.ReadStruct(out PESignature), stream.ReadStruct(out PEFileHeader), stream.ReadClass(ref PEOptionalHeader), stream.ReadStructs(out SectionHeaders, PEFileHeader.NumberOfSections), }; node.GetChild("DosHeader").GetChild("LfaNew").Link = node.GetChild("PESignature"); return node; } } // II.25.2.1 [StructLayout(LayoutKind.Sequential, Pack = 1)] struct DosHeader { [Expected('M')] public char MagicM; [Expected('Z')] public char MagicZ; [Expected(0x90)] public ushort BytesOnLastPageOfFile; [Expected(3)] public ushort PagesInFile; [Expected(0)] public ushort Relocations; [Expected(4)] public ushort SizeOfHeaderInParagraphs; [Expected(0)] public ushort MinimumExtraParagraphsNeeded; [Expected(0xFFFF)] public ushort MaximumExtraParagraphsNeeded; [Expected(0)] public ushort InitialRelativeStackSegmentValue; [Expected(0xB8)] public ushort InitialSP; [Expected(0)] public ushort Checksum; [Expected(0)] public ushort InitialIP; [Expected(0)] public ushort InitialRelativeCS; [Expected(0x40)] [Description("Pointer to the Relocation Table, which is size 0.")] public ushort RawAddressOfRelocation; [Expected(0)] public ushort OverlayNumber; [Expected(0)] public ulong Reserved; [Expected(0)] public ushort OemIdentifier; [Expected(0)] public ushort OemInformation; [Expected(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})] [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] public byte[] Reserved2; [Expected(0x80)] public uint LfaNew; [Expected(new byte[] { 0x0E, 0x1F, 0xBA, 0x0E, 0x00, 0xB4, 0x09, 0xCD, 0x21, 0xb8, 0x01, 0x4C, 0xCD, 0x21 })] [MarshalAs(UnmanagedType.ByValArray, SizeConst = 14)] public byte[] DosCode; [Expected("This program cannot be run in DOS mode.\r\r\n$")] [MarshalAs(UnmanagedType.ByValArray, SizeConst = 43)] public char[] Message; [Expected(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 })] [MarshalAs(UnmanagedType.ByValArray, SizeConst = 7)] public byte[] Reserved3; } [StructLayout(LayoutKind.Sequential, Pack = 1)] struct PESignature { [Expected('P')] public char MagicP; [Expected('E')] public char MagicE; [Expected(0)] public ushort Reserved; } // II.25.2.2 [StructLayout(LayoutKind.Sequential, Pack = 1)] struct PEFileHeader { [Description("0x14c is I386.")] public MachineType Machine; [Description("Number of sections; indicates size of the Section Table, which immediately follows the headers.")] public ushort NumberOfSections; [Description("Time and date the file was created in seconds since January 1st 1970 00:00:00 or 0.")] public uint TimeDateStamp; [Description("Always 0 (§II.24.1).")] [Expected(0)] public uint PointerToSymbolTable; [Description("Always 0 (§II.24.1).")] [Expected(0)] public uint NumberOfSymbols; [Description("Size of the optional header, the format is described below.")] public ushort OptionalHeaderSize; [Description("Flags indicating attributes of the file, see §II.25.2.2.1.")] public ushort Characteristics; } enum MachineType : ushort { Unknown = 0x0, Am33 = 0x1d3, Amd64 = 0x8664, Arm = 0x1c0, Armnt = 0x1c4, Arm64 = 0xaa64, Ebc = 0xebc, I386 = 0x14c, Ia64 = 0x200, M32r = 0x9041, Mips16 = 0x266, Mipsfpu = 0x366, Mipsfpu16 = 0x466, Powerpc = 0x1f0, Powerpcfp = 0x1f1, R4000 = 0x166, Sh3 = 0x1a2, Sh3dsp = 0x1a3, Sh4 = 0x1a6, Sh5 = 0x1a8, Thumb = 0x1c2, Wcemipsv2 = 0x169 } // II.25.2.3 class PEOptionalHeader : ICanRead { //TODO(Descriptions) public PEHeaderStandardFields PEHeaderStandardFields; [Description("RVA of the data section. (This is a hint to the loader.) Only present in PE32, not PE32+")] public int? BaseOfData; public PEHeaderWindowsNtSpecificFields32? PEHeaderWindowsNtSpecificFields32; public PEHeaderWindowsNtSpecificFields64? PEHeaderWindowsNtSpecificFields64; public PEHeaderHeaderDataDirectories PEHeaderHeaderDataDirectories; public CodeNode Read(Stream stream) { var node = new CodeNode { stream.ReadStruct(out PEHeaderStandardFields), }; switch (PEHeaderStandardFields.Magic) { case PE32Magic.PE32: node.Add(stream.ReadStruct(out BaseOfData, nameof(BaseOfData))); node.Add(stream.ReadStruct(out PEHeaderWindowsNtSpecificFields32).Children.Single()); break; case PE32Magic.PE32plus: node.Add(stream.ReadStruct(out PEHeaderWindowsNtSpecificFields64).Children.Single()); break; default: throw new InvalidOperationException($"Magic not recognized: {PEHeaderStandardFields.Magic:X}"); } node.Add(stream.ReadStruct(out PEHeaderHeaderDataDirectories)); return node; } } // II.25.2.3.1 [StructLayout(LayoutKind.Sequential, Pack = 1)] struct PEHeaderStandardFields { [Description("Identifies version.")] public PE32Magic Magic; [Description("Spec says always 6, sometimes more (§II.24.1).")] public byte LMajor; [Description("Always 0 (§II.24.1).")] [Expected(0)] public byte LMinor; [Description("Size of the code (text) section, or the sum of all code sections if there are multiple sections.")] public uint CodeSize; [Description("Size of the initialized data section, or the sum of all such sections if there are multiple data sections.")] public uint InitializedDataSize; [Description("Size of the uninitialized data section, or the sum of all such sections if there are multiple unitinitalized data sections.")] public uint UninitializedDataSize; [Description("RVA of entry point , needs to point to bytes 0xFF 0x25 followed by the RVA in a section marked execute/read for EXEs or 0 for DLLs")] public uint EntryPointRVA; [Description("RVA of the code section. (This is a hint to the loader.)")] public uint BaseOfCode; } enum PE32Magic : ushort { PE32 = 0x10b, PE32plus = 0x20b, } // II.25.2.3.2 [StructLayout(LayoutKind.Sequential, Pack = 1)] struct PEHeaderWindowsNtSpecificFields<Tint> { [Description("Shall be a multiple of 0x10000.")] public Tint ImageBase; [Description("Shall be greater than File Alignment.")] public uint SectionAlignment; [Description("Should be 0x200 (§II.24.1).")] [Expected(0x200)] public uint FileAlignment; [Description("Should be 5 (§II.24.1).")] public ushort OSMajor; [Description("Should be 0 (§II.24.1).")] [Expected(0)] public ushort OSMinor; [Description("Should be 0 (§II.24.1).")] [Expected(0)] public ushort UserMajor; [Description("Should be 0 (§II.24.1).")] [Expected(0)] public ushort UserMinor; [Description("Should be 5 (§II.24.1).")] //[Expected(5)] public ushort SubSysMajor; [Description("Should be 0 (§II.24.1).")] [Expected(0)] public ushort SubSysMinor; [Description("Shall be zero")] [Expected(0)] public uint Reserved; [Description("Size, in bytes, of image, including all headers and padding; shall be a multiple of Section Alignment.")] public uint ImageSize; [Description("Combined size of MS-DOS Header, PE Header, PE Optional Header and padding; shall be a multiple of the file alignment.")] public uint HeaderSize; [Description("Should be 0 (§II.24.1).")] [Expected(0)] public uint FileChecksum; [Description("Subsystem required to run this image. Shall be either IMAGE_SUBSYSTEM_WINDOWS_CUI (0x3) or IMAGE_SUBSYSTEM_WINDOWS_GUI (0x2).")] public ushort SubSystem; [Description("Bits 0x100f shall be zero.")] public DllCharacteristics DLLFlags; [Description("Often 1Mb for x86 or 4Mb for x64 (§II.24.1).")] public Tint StackReserveSize; [Description("Often 4Kb for x86 or 16Kb for x64 (§II.24.1).")] public Tint StackCommitSize; [Description("Should be 0x100000 (1Mb) (§II.24.1).")] [Expected(0x100000)] public Tint HeapReserveSize; [Description("Often 4Kb for x86 or 8Kb for x64 (§II.24.1).")] public Tint HeapCommitSize; [Description("Shall be 0")] [Expected(0)] public uint LoaderFlags; [Description("Shall be 0x10")] [Expected(0x10)] public uint NumberOfDataDirectories; } // Generic structs aren't copyable by Marshal.PtrToStructure, so make non-generic "subclasses" [StructLayout(LayoutKind.Sequential, Pack = 1)] struct PEHeaderWindowsNtSpecificFields32 { public PEHeaderWindowsNtSpecificFields<uint> PEHeaderWindowsNtSpecificFields; } [StructLayout(LayoutKind.Sequential, Pack = 1)] struct PEHeaderWindowsNtSpecificFields64 { public PEHeaderWindowsNtSpecificFields<ulong> PEHeaderWindowsNtSpecificFields; } [Flags] enum DllCharacteristics : ushort { Reserved1 = 0x0001, Reserved2 = 0x0002, Reserved3 = 0x0004, Reserved4 = 0x0008, [Description("The DLL can be relocated at load time.")] DYNAMIC_BASE = 0x0040, [Description("Code integrity checks are forced. If you set this flag and a section contains only uninitialized data, set the PointerToRawData member of IMAGE_SECTION_HEADER for that section to zero; otherwise, the image will fail to load because the digital signature cannot be verified.")] FORCE_INTEGRITY = 0x0080, [Description("The image is compatible with data execution prevention (DEP).")] NX_COMPAT = 0x0100, [Description("The image is isolation aware, but should not be isolated.")] NO_ISOLATION = 0x0200, [Description("The image does not use structured exception handling (SEH). No handlers can be called in this image.")] NO_SEH = 0x0400, [Description("Do not bind the image. ")] NO_BIND = 0x0800, Reserved5 = 0x1000, [Description("A WDM driver. ")] WDM_DRIVER = 0x2000, Reserved6 = 0x4000, [Description("The image is terminal server aware.")] TERMINAL_SERVER_AWARE = 0x8000, } // II.25.2.3.3 [StructLayout(LayoutKind.Sequential, Pack = 1)] struct PEHeaderHeaderDataDirectories { //TODO(link) all Raw Address from understandingCIL //TODO(link) RVAandSize all [Description("Always 0 (§II.24.1).")] [Expected(0)] public ulong ExportTable; [Description("RVA and Size of Import Table, (§II.25.3.1).")] public RVAandSize ImportTable; [Description("Always 0, unless resources are compiled in (§II.24.1).")] public ulong ResourceTable; [Description("Always 0 (§II.24.1).")] [Expected(0)] public ulong ExceptionTable; [Description("Always 0 (§II.24.1).")] [Expected(0)] public ulong CertificateTable; [Description("Relocation Table; set to 0 if unused (§).")] public RVAandSize BaseRelocationTable; [Description("Always 0 (§II.24.1).")] //TODO(pedant) What's the right behavior? Multiple expected attributes? [Expected(0)] public ulong Debug; [Description("Always 0 (§II.24.1).")] [Expected(0)] public ulong Copyright; [Description("Always 0 (§II.24.1).")] [Expected(0)] public ulong GlobalPtr; [Description("Always 0 (§II.24.1).")] [Expected(0)] public ulong TLSTable; [Description("Always 0 (§II.24.1).")] [Expected(0)] public ulong LoadConfigTable; [Description("Always 0 (§II.24.1).")] [Expected(0)] public ulong BoundImport; [Description("RVA and Size of Import Address Table,(§II.25.3.1).")] public RVAandSize ImportAddressTable; [Description("Always 0 (§II.24.1).")] [Expected(0)] public ulong DelayImportDescriptor; [Description("CLI Header with directories for runtime data,(§II.25.3.1).")] public RVAandSize CLIHeader; [Description("Always 0 (§II.24.1)")] [Expected(0)] public ulong Reserved; } [StructLayout(LayoutKind.Sequential, Pack = 1)] struct RVAandSize { public uint RVA; public uint Size; } // II.25.3 [StructLayout(LayoutKind.Sequential, Pack = 1)] struct SectionHeader { [Description("An 8-byte, null-padded ASCII string. There is no terminating null if the string is exactly eight characters long.")] [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public char[] Name; [Description("Total size of the section in bytes. If this value is greater than SizeOfRawData, the section is zero-padded.")] public uint VirtualSize; [Description("For executable images this is the address of the first byte of the section, when loaded into memory, relative to the image base.")] public uint VirtualAddress; [Description("Size of the initialized data on disk in bytes, shall be a multiple of FileAlignment from the PE header. If this is less than VirtualSize the remainder of the section is zero filled. Because this field is rounded while the VirtualSize field is not it is possible for this to be greater than VirtualSize as well. When a section contains only uninitialized data, this field should be 0.")] public uint SizeOfRawData; [Description("Offset of section's first page within the PE file. This shall be a multiple of FileAlignment from the optional header. When a section contains only uninitialized data, this field should be 0.")] public uint PointerToRawData; [Description("Should be 0 (§II.24.1).")] [Expected(0)] public uint PointerToRelocations; [Description("Should be 0 (§II.24.1).")] [Expected(0)] public uint PointerToLinenumbers; [Description("Should be 0 (§II.24.1).")] [Expected(0)] public ushort NumberOfRelocations; [Description("Should be 0 (§II.24.1).")] [Expected(0)] public ushort NumberOfLinenumbers; [Description("Flags describing section’s characteristics.")] public SectionHeaderCharacteristics Characteristics; } [Flags] enum SectionHeaderCharacteristics : uint { ShouldNotBePadded = 0x00000008, ContainsCode = 0x00000020, ContainsInitializedData = 0x00000040, ContainsUninitializedData = 0x00000080, LinkContainsComments = 0x00000200, LinkShouldBeRemoved = 0x00000800, Link_COMDAT = 0x00001000, MemoryCanBeDiscarded = 0x02000000, MemoryCannotBeCached = 0x04000000, MemoryCannotBePaged = 0x08000000, MemoryCanBeShared = 0x10000000, MemoryCanBeExecutedAsCode = 0x20000000, MemoryCanBeRead = 0x40000000, MemoryCanBeWrittenTo = 0x80000000, } sealed class Section : ICanRead { int start; int end; int rva; string name; PEHeaderHeaderDataDirectories data; uint entryPointRVA; public CLIHeader CLIHeader; public MetadataRoot MetadataRoot; public ImportTable ImportTable; public ImportLookupTable ImportLookupTable; public ImportAddressHintNameTable ImportAddressHintNameTable; public NativeEntryPoint NativeEntryPoint; public ImportAddressTable ImportAddressTable; public Relocations Relocations; CodeNode node; public Dictionary<uint, Method> MethodsByRVA { get; } = new Dictionary<uint, Method>(); public Section(SectionHeader header, PEHeaderHeaderDataDirectories data, uint entryPointRVA) { start = (int)header.PointerToRawData; end = start + (int)header.SizeOfRawData; rva = (int)header.VirtualAddress; name = new string(header.Name); this.data = data; this.entryPointRVA = entryPointRVA; } //TODO(cleanup) reorder children in order public CodeNode Read(Stream stream) { node = new CodeNode { Description = name, }; foreach (var nr in data.GetType().GetFields() .Where(field => field.FieldType == typeof(RVAandSize)) .Select(field => new { name = field.Name, rva = (RVAandSize)field.GetValue(data) }) .Where(nr => nr.rva.RVA > 0) .Where(nr => rva <= nr.rva.RVA && nr.rva.RVA < rva + end - start) .OrderBy(nr => nr.rva.RVA)) { Reposition(stream, nr.rva.RVA); switch (nr.name) { case "CLIHeader": node.Add(stream.ReadStruct(out CLIHeader)); Reposition(stream, CLIHeader.MetaData.RVA); node.Add(stream.ReadClass(ref MetadataRoot)); foreach (var streamHeader in MetadataRoot.StreamHeaders.OrderBy(h => h.Name.IndexOf('~'))) // Read #~ after heaps { Reposition(stream, streamHeader.Offset + CLIHeader.MetaData.RVA); switch (streamHeader.Name) { case "#Strings": var stringHeap = new StringHeap((int)streamHeader.Size); Singletons.Instance.StringHeap = stringHeap; node.Add(stream.ReadClass(ref stringHeap)); break; case "#US": var userStringHeap = new UserStringHeap((int)streamHeader.Size); Singletons.Instance.UserStringHeap = userStringHeap; node.Add(stream.ReadClass(ref userStringHeap)); break; case "#Blob": var blobHeap = new BlobHeap((int)streamHeader.Size); Singletons.Instance.BlobHeap = blobHeap; node.Add(stream.ReadClass(ref blobHeap)); break; case "#GUID": var guidHeap = new GuidHeap((int)streamHeader.Size); Singletons.Instance.GuidHeap = guidHeap; node.Add(stream.ReadClass(ref guidHeap)); break; case "#~": var TildeStream = new TildeStream(this); Singletons.Instance.TildeStream = TildeStream; node.Add(stream.ReadClass(ref TildeStream)); var methods = new CodeNode { Name = "Methods", }; foreach (var rva in (TildeStream.MethodDefs ?? Array.Empty<MethodDef>()) .Select(def => def.RVA) .Where(rva => rva > 0) .Distinct() .OrderBy(rva => rva)) { Reposition(stream, rva); Method method = null; methods.Add(stream.ReadClass(ref method)); MethodsByRVA.Add(rva, method); } if (methods.Children.Any()) { node.Add(methods); } break; default: node.AddError("Unexpected stream name: " + streamHeader.Name); break; } } break; case "ImportTable": node.Add(stream.ReadStruct(out ImportTable)); Reposition(stream, ImportTable.ImportLookupTable); node.Add(stream.ReadStruct(out ImportLookupTable)); Reposition(stream, ImportLookupTable.HintNameTableRVA); node.Add(stream.ReadStruct(out ImportAddressHintNameTable)); Reposition(stream, ImportTable.Name); string RuntimeEngineName; node.Add(stream.ReadAnything(out RuntimeEngineName, StreamExtensions.ReadNullTerminated(Encoding.ASCII, 1), "RuntimeEngineName")); Reposition(stream, entryPointRVA); node.Add(stream.ReadStruct(out NativeEntryPoint)); break; case "ImportAddressTable": node.Add(stream.ReadStruct(out ImportAddressTable)); break; case "BaseRelocationTable": node.Add(stream.ReadClass(ref Relocations)); break; default: node.AddError("Unexpected data directory name: " + nr.name); break; } } foreach (var toRead in toReads) { node.Add(toRead(stream)); } return node; } List<Func<Stream, CodeNode>> toReads = new List<Func<Stream, CodeNode>>(); public void ReadNode(Func<Stream, CodeNode> read) => toReads.Add(read); public void Reposition(Stream stream, long dataRVA) => stream.Position = start + dataRVA - rva; public void CallBack() { node.Start = start; node.End = end; } } // II.25.3.1 [StructLayout(LayoutKind.Sequential, Pack = 1)] struct ImportTable { [Description("RVA of the Import Lookup Table")] public uint ImportLookupTable; [Description("Always 0 (§II.24.1).")] [Expected(0)] public uint DateTimeStamp; [Description("Always 0 (§II.24.1).")] [Expected(0)] public uint ForwarderChain; [Description("RVA of null-terminated ASCII string “mscoree.dll”.")] public uint Name; [Description("RVA of Import Address Table (this is the same as the RVA of the IAT descriptor in the optional header).")] public uint ImportAddressTableRVA; [Description("End of Import Table. Shall be filled with zeros.")] [Expected(new byte[] { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00})] [MarshalAs(UnmanagedType.ByValArray, SizeConst = 20)] public byte[] Reserved; } [StructLayout(LayoutKind.Sequential, Pack = 1)] struct ImportAddressTable { public uint HintNameTableRVA; [Expected(0)] public uint NullTerminated; } [StructLayout(LayoutKind.Sequential, Pack = 1)] struct ImportLookupTable { public uint HintNameTableRVA; [Expected(0)] public uint NullTerminated; } [StructLayout(LayoutKind.Sequential, Pack = 1)] struct ImportAddressHintNameTable { [Description("Shall be 0.")] [Expected(0)] public ushort Hint; [Description("Case sensitive, null-terminated ASCII string containing name to import. Shall be “_CorExeMain” for a.exe file and “_CorDllMain” for a.dll file.")] [MarshalAs(UnmanagedType.ByValArray, SizeConst = 12)] public char[] Message; } //It woul be nice to parse all x86 or other kind of assemblies like ARM or JAR, but that's probably out-of-scope [StructLayout(LayoutKind.Sequential, Pack = 1)] struct NativeEntryPoint { [Description("JMP op code in X86")] [Expected(0xFF)] public byte JMP; [Description("Specifies the jump is in absolute indirect mode")] [Expected(0x25)] public byte Mod; [Description("Jump target RVA.")] public uint JumpTarget; } // II.25.3.2 class Relocations : ICanRead { public BaseRelocationTable BaseRelocationTable; public Fixup[] Fixups; public CodeNode Read(Stream stream) { return new CodeNode { stream.ReadStruct(out BaseRelocationTable), stream.ReadClasses(ref Fixups, ((int)BaseRelocationTable.BlockSize - 8) / 2), }; } } [StructLayout(LayoutKind.Sequential, Pack = 1)] struct BaseRelocationTable { public uint PageRVA; public uint BlockSize; } class Fixup : ICanRead { //TODO(Descriptions) [Description("Stored in high 4 bits of word, type IMAGE_REL_BASED_HIGHLOW (0x3).")] public byte Type; [Description("Stored in remaining 12 bits of word. Offset from starting address specified in the Page RVA field for the block. This offset specifies where the fixup is to be applied.")] public short Offset; public CodeNode Read(Stream stream) { byte tmp = 0xCC; return new CodeNode { stream.ReadStruct(out Type, nameof(Type), (byte b) => { tmp = b; return (byte)(b >> 4); }), stream.ReadStruct(out Offset, nameof(Offset), (byte b) => { return (short)(((tmp << 8) & 0x0F00) | b); }), }; } } // II.25.3.3 [StructLayout(LayoutKind.Sequential, Pack = 1)] struct CLIHeader { [Description("Size of the header in bytes")] public uint Cb; [Description("The minimum version of the runtime required to run this program, currently 2.")] public ushort MajorRuntimeVersion; [Description("The minor portion of the version, currently 0.")] public ushort MinorRuntimeVersion; [Description("RVA and size of the physical metadata (§II.24).")] public RVAandSize MetaData; [Description("Flags describing this runtime image. (§II.25.3.3.1).")] public CliHeaderFlags Flags; [Description("Token for the MethodDef or File of the entry point for the image")] public uint EntryPointToken; [Description("RVA and size of implementation-specific resources.")] public RVAandSize Resources; [Description("RVA of the hash data for this PE file used by the CLI loader for binding and versioning")] public RVAandSize StrongNameSignature; [Description("Always 0 (§II.24.1).")] [Expected(0)] public ulong CodeManagerTable; [Description("RVA of an array of locations in the file that contain an array of function pointers (e.g., vtable slots), see below.")] public RVAandSize VTableFixups; [Description("Always 0 (§II.24.1).")] [Expected(0)] public ulong ExportAddressTableJumps; [Description("Always 0 (§II.24.1).")] [Expected(0)] public ulong ManagedNativeHeader; } [Flags] enum CliHeaderFlags : uint { ILOnly = 0x01, Required32Bit = 0x02, StrongNameSigned = 0x08, NativeEntryPoint = 0x10, TrackDebugData = 0x10000, } // II.25.4 sealed class Method : ICanRead, IHaveAName, IHaveLiteralValueNode { public byte Header; //TODO(pedant) ? enum public FatFormat FatFormat; public MethodDataSection[] DataSections; public InstructionStream CilOps; public string Name { get; } = $"{nameof(Method)}[{Singletons.Instance.MethodCount++}]"; public object Value => ""; //TODO(cleanup) clean up all "" Value. Should this just implement IHaveValue? How does that work with CodeNode.DelayedValueNode? public CodeNode Node { get; private set; } public CodeNode Read(Stream stream) { var header = stream.ReadStruct(out Header, nameof(Header)); Node = new CodeNode { header, }; int length; var moreSects = false; var type = (MethodHeaderType)(Header & 0x03); switch (type) { case MethodHeaderType.Tiny: length = Header >> 2; header.Description = $"Tiny Header, 0x{length:X} bytes long"; break; case MethodHeaderType.Fat: Node.Add(stream.ReadStruct(out FatFormat, nameof(FatFormat))); if ((FatFormat.FlagsAndSize & 0xF0) != 0x30) { Node.AddError("Expected upper bits of FlagsAndSize to be 3"); } length = (int)FatFormat.CodeSize; header.Description = $"Fat Header, 0x{length:X} bytes long"; moreSects = ((MethodHeaderType)Header).HasFlag(MethodHeaderType.MoreSects); break; default: throw new InvalidOperationException("Invalid MethodHeaderType " + type); } CilOps = new InstructionStream(length); Node.Add(stream.ReadClass(ref CilOps, nameof(CilOps))); if (moreSects) { while (stream.Position % 4 != 0) { var b = stream.ReallyReadByte(); } var dataSections = new List<MethodDataSection>(); var dataSectionNode = new CodeNode { Name = "MethodDataSection" }; MethodDataSection dataSection = null; do { dataSectionNode.Add(stream.ReadClass(ref dataSection, $"MethodDataSections[{dataSections.Count}]")); dataSections.Add(dataSection); } while (dataSection.Header.HasFlag(MethodHeaderSection.MoreSects)); DataSections = dataSections.ToArray(); Node.Add(dataSectionNode.Children.Count == 1 ? dataSectionNode.Children.Single() : dataSectionNode); } return Node; } } // II.25.4.1 and .4 enum MethodHeaderType : byte { Tiny = 0x02, Fat = 0x03, MoreSects = 0x08, InitLocals = 0x10, } // II.25.4.3 [StructLayout(LayoutKind.Sequential, Pack = 1)] struct FatFormat { [Description("Lower four bits is rest of Flags, Upper four bits is size of this header expressed as the count of 4-byte integers occupied (currently 3)")] public byte FlagsAndSize; [Description("Maximum number of items on the operand stack")] public ushort MaxStack; [Description("Size in bytes of the actual method body")] public uint CodeSize; [Description("Meta Data token for a signature describing the layout of the local variables for the method")] public uint LocalVarSigTok; } // II.25.4.5 sealed class MethodDataSection : ICanRead { public MethodHeaderSection Header; public LargeMethodHeader LargeMethodHeader; public SmallMethodHeader SmallMethodHeader; public CodeNode Read(Stream stream) { var node = new CodeNode { stream.ReadStruct(out Header, nameof(MethodHeaderSection)) }; if (!Header.HasFlag(MethodHeaderSection.EHTable)) { throw new InvalidOperationException("Only kind of section data is exception header"); } if (Header.HasFlag(MethodHeaderSection.FatFormat)) { node.Add(stream.ReadClass(ref LargeMethodHeader, nameof(LargeMethodHeader))); } else { node.Add(stream.ReadClass(ref SmallMethodHeader, nameof(SmallMethodHeader))); } return node; } } [Flags] enum MethodHeaderSection : byte { [Description("Exception handling data.")] EHTable = 0x1, [Description("Reserved, shall be 0.")] OptILTable = 0x2, [Description("Data format is of the fat variety, meaning there is a 3-byte length least-significant byte first format. If not set, the header is small with a 1-byte length")] FatFormat = 0x40, [Description("Another data section occurs after this current section")] MoreSects = 0x80, } sealed class SmallMethodHeader : ICanRead { [Description("Size of the data for the block, including the header, say n * 12 + 4.")] public byte DataSize; [Description("Padding, always 0.")] [Expected(0)] public ushort Reserved; public SmallExceptionHandlingClause[] Clauses; public CodeNode Read(Stream stream) { var node = new CodeNode { stream.ReadStruct(out DataSize, nameof(DataSize)), stream.ReadStruct(out Reserved, nameof(Reserved)), }; var n = (DataSize - 4) / 12; if (n * 12 + 4 != DataSize) { node.AddError("DataSize was not of the form n * 12 + 4"); } node.Add(stream.ReadStructs(out Clauses, n, nameof(Clauses))); return node; } } sealed class LargeMethodHeader : ICanRead { [Description("Size of the data for the block, including the header, say n * 24 + 4.")] public UInt24 DataSize; public SmallExceptionHandlingClause[] Clauses; public CodeNode Read(Stream stream) { var node = new CodeNode { stream.ReadClass(ref DataSize, nameof(DataSize)), }; var n = (DataSize.IntValue - 4) / 12; if (n * 24 + 4 != DataSize.IntValue) { node.AddError("DataSize was not of the form n * 24 + 4"); } node.Add(stream.ReadStructs(out Clauses, n, nameof(Clauses))); return node; } } // II.25.4.6 [StructLayout(LayoutKind.Sequential, Pack = 1)] struct SmallExceptionHandlingClause { [Description("Flags")] public ushort SmallExceptionClauseFlags; [Description("Offset in bytes of try block from start of method body.")] public ushort TryOffset; //TODO(links) [Description("Length in bytes of the try block")] public byte TryLength; [Description("Location of the handler for this try block")] public ushort HandlerOffset; [Description("Size of the handler code in bytes")] public byte HandlerLength; [Description("Meta data token for a type-based exception handler OR Offset in method body for filter-based exception handler")] public uint ClassTokenOrFilterOffset; //TODO(links) } [Flags] enum SmallExceptionClauseFlags : ushort { [Description("A typed exception clause")] Exception = 0x0000, [Description("An exception filter and handler clause")] Filter = 0x0001, [Description("A finally clause")] Finally = 0x0002, [Description("Fault clause (finally that is called on exception only)")] Fault = 0x0004, } [StructLayout(LayoutKind.Sequential, Pack = 1)] struct LargeExceptionHandlingClause { [Description("Flags.")] public uint LargeExceptionClauseFlags; [Description("Offset in bytes of try block from start of method body.")] public uint TryOffset; [Description("Length in bytes of the try block")] public uint TryLength; [Description("Location of the handler for this try block")] public uint HandlerOffset; [Description("Size of the handler code in bytes")] public uint HandlerLength; [Description("Meta data token for a type-based exception handler OR offset in method body for filter-based exception handler")] public uint ClassTokenOrFilterOffset; } [Flags] enum LargeExceptionClauseFlags : uint { [Description("A typed exception clause")] Exception = 0x0000, [Description("An exception filter and handler clause")] Filter = 0x0001, [Description("A finally clause")] Finally = 0x0002, [Description("Fault clause (finally that is called on exception only)")] Fault = 0x0004, } sealed class UInt24 : ICanRead, IHaveValue { public int IntValue { get; private set; } public object Value => IntValue; public CodeNode Read(Stream stream) { byte[] b; stream.ReadStructs(out b, 3); IntValue = (b[2] << 16) + (b[1] << 8) + b[0]; return new CodeNode(); } }
32.900198
402
0.693888
[ "MIT" ]
darthwalsh/dotNetBytes
Lib/FileFormat.cs
33,353
C#
using System; using System.Collections.Generic; using TechTalk.SpecFlow.Assist; namespace SpecFlowTests.Utils.Common.ValueRetrievers { public class StringToBoolValueRetriever : IValueRetriever { public bool GetValue(KeyValuePair<string, string> keyValuePair) { if (string.IsNullOrWhiteSpace(keyValuePair.Value)) throw new NotSupportedException($"Table row column '{keyValuePair.Key}' does not support empty entry."); return MapDriver.MapToBool(keyValuePair.Value); } public object Retrieve(KeyValuePair<string, string> keyValuePair, Type targetType, Type propertyType) { return GetValue(keyValuePair); } public bool CanRetrieve(KeyValuePair<string, string> keyValuePair, Type targetType, Type propertyType) { return propertyType == typeof(bool); } } }
32.321429
120
0.678453
[ "BSD-3-Clause" ]
techtalk/CodingDojos
SpecFlowCodingDojo/eShopOnWeb/tests/SpecFlowTests/Utils/Common/ValueRetrievers/StringToBoolValueRetriever.cs
907
C#
using System.Collections.Generic; using System.Threading.Tasks; namespace Logging.Services { public interface IService<T> { Task<T> GetItemAsync(string id); Task<IEnumerable<T>> GetItemsAsync(); } }
19.083333
45
0.681223
[ "Apache-2.0" ]
jasonmacduffie/GraphQL
Orders/Services/IService.cs
231
C#
namespace MyFirstABPProject.EntityFrameworkCore.Seed.Host { public class InitialHostDbBuilder { private readonly MyFirstABPProjectDbContext _context; public InitialHostDbBuilder(MyFirstABPProjectDbContext context) { _context = context; } public void Create() { new DefaultEditionCreator(_context).Create(); new DefaultLanguagesCreator(_context).Create(); new HostRoleAndUserCreator(_context).Create(); new DefaultSettingsCreator(_context).Create(); _context.SaveChanges(); } } }
27.086957
71
0.638844
[ "Apache-2.0" ]
HvaiY/MyCoreStudy
MyFirstABPProject/3.9.0/aspnet-core/src/MyFirstABPProject.EntityFrameworkCore/EntityFrameworkCore/Seed/Host/InitialHostDbBuilder.cs
625
C#
using UnityEngine; namespace toio.tutorial { public class SimUI : MonoBehaviour { private int updateCnt = 0; void Update() { if (CubeScanner.actualTypeOfAuto == ConnectType.Simulator) { if (updateCnt < 3) updateCnt++; if (updateCnt == 2){ // ステージを右に移動 var localPos = Camera.main.transform.localPosition; localPos.x = -0.15f; Camera.main.transform.localPosition = localPos; // キャンバスを左に移動 var canvasObj = GameObject.Find("Canvas"); var simCanvasObj = GameObject.Find("SimCanvas"); canvasObj.transform.SetParent(simCanvasObj.transform); canvasObj.transform.position = new Vector3(720/2 * canvasObj.transform.localScale.x * 0.8f, canvasObj.transform.position.y, canvasObj.transform.position.z); } } } } }
34.5
111
0.518841
[ "MIT" ]
comoc/toio-sdk-for-unity
toio-sdk-unity/Assets/toio-sdk/Tutorials/1.Basic/ex.Sample_UI/SimUI.cs
1,073
C#
using System; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Text; using System.IO; namespace YanZhiwei.DotNet2.Utilities.ValidateCode { /// <summary> /// 字体旋转(简单) /// </summary> public class ValidateCode_Style13 : ValidateCodeType { private Color backgroundColor = Color.White; private Color chaosColor = Color.FromArgb(170, 170, 0x33); private Color drawColor = Color.FromArgb(50, 0x99, 0xcc); private bool fontTextRenderingHint = true; private int validataCodeSize = 0x10; private string validateCodeFont = "Arial"; public override byte[] CreateImage(out string resultCode) { Bitmap bitmap; string formatString = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z"; GetRandom(formatString, 4, out resultCode); MemoryStream stream = new MemoryStream(); this.ImageBmp(out bitmap, resultCode); bitmap.Save(stream, ImageFormat.Png); bitmap.Dispose(); bitmap = null; stream.Close(); stream.Dispose(); return stream.GetBuffer(); } private void CreateImageBmp(ref Bitmap bitMap, string validateCode) { Graphics graphics = Graphics.FromImage(bitMap); if (this.fontTextRenderingHint) { graphics.TextRenderingHint = TextRenderingHint.AntiAlias; } else { graphics.TextRenderingHint = TextRenderingHint.SingleBitPerPixel; } Font font = new Font(this.validateCodeFont, (float)this.validataCodeSize, FontStyle.Regular); Brush brush = new SolidBrush(this.drawColor); Random random = new Random(); for (int i = 0; i < 4; i++) { Bitmap image = new Bitmap(30, 30); Graphics graphics2 = Graphics.FromImage(image); graphics2.TranslateTransform(4f, 0f); graphics2.RotateTransform((float)random.Next(20)); Point point = new Point(4, -2); graphics2.DrawString(validateCode[i].ToString(), font, brush, (PointF)point); graphics.DrawImage(image, i * 30, 0); graphics2.Dispose(); } graphics.Dispose(); } private void DisposeImageBmp(ref Bitmap bitmap) { Graphics graphics = Graphics.FromImage(bitmap); graphics.Clear(Color.White); Pen pen = new Pen(this.DrawColor, 1f); Random random = new Random(); pen = new Pen(this.ChaosColor, 1f); for (int i = 0; i < 40; i++) { int x = random.Next(bitmap.Width); int y = random.Next(bitmap.Height); graphics.DrawRectangle(pen, x, y, 1, 1); } graphics.Dispose(); } private static void GetRandom(string formatString, int len, out string codeString) { codeString = string.Empty; string[] strArray = formatString.Split(new char[] { ',' }); Random random = new Random(); for (int i = 0; i < len; i++) { int index = random.Next(0x186a0) % strArray.Length; codeString = codeString + strArray[index].ToString(); } } private void ImageBmp(out Bitmap bitMap, string validataCode) { bitMap = new Bitmap(120, 30); this.DisposeImageBmp(ref bitMap); this.CreateImageBmp(ref bitMap, validataCode); } public Color BackgroundColor { get { return this.backgroundColor; } set { this.backgroundColor = value; } } public Color ChaosColor { get { return this.chaosColor; } set { this.chaosColor = value; } } public Color DrawColor { get { return this.drawColor; } set { this.drawColor = value; } } private bool FontTextRenderingHint { get { return this.fontTextRenderingHint; } set { this.fontTextRenderingHint = value; } } public override string Name { get { return "字体旋转(简单)"; } } public int ValidataCodeSize { get { return this.validataCodeSize; } set { this.validataCodeSize = value; } } public string ValidateCodeFont { get { return this.validateCodeFont; } set { this.validateCodeFont = value; } } } }
29.083333
105
0.489207
[ "MIT" ]
wind2006/DotNet.Utilities
YanZhiwei.DotNet2.Utilities/ValidateCode/ValidateCode_Style13.cs
5,261
C#
using System; using System.Text; using System.Diagnostics; using System.Threading.Tasks; using WindowsGSM.Functions; using WindowsGSM.GameServer.Engine; using WindowsGSM.GameServer.Query; namespace WindowsGSM.Plugins { public class theforest : SteamCMDAgent // SteamCMDAgent is used because the_forest relies on SteamCMD for installation and update process { // - Plugin Details public Plugin Plugin = new Plugin { name = "WindowsGSM.theforest", // WindowsGSM.XXXX author = "Tempus Thales", description = "🧩 WindowsGSM plugin for The Forest Dedicated Server", version = "1.0", url = "https://github.com/tempusthales/WindowsGSM.theforest", // Github repository link (Best practice) color = "#0a7a04" // Color Hex }; // - Standard Constructor and properties public theforest(ServerConfig serverData) : base(serverData) => base.serverData = _serverData = serverData; private readonly ServerConfig _serverData; // Store server start metadata, such as start ip, port, start param, etc // - Settings properties for SteamCMD installer public override bool loginAnonymous => false; // the_forest requires to login steam account to install the server, so loginAnonymous = false public override string AppId => "556450"; // Game server appId, the_forest is 556450 // - Game server Fixed variables public override string StartPath => "TheForestDedicatedServer.exe"; // Game server start path, for the_forest, it is TheForestDedicatedServer.exe public string FullName = "The Forest Dedicated Server"; // Game server FullName public bool AllowsEmbedConsole = false; // Does this server support output redirect? public int PortIncrements = 2; // This tells WindowsGSM how many ports should skip after installation public object QueryMethod = new A2S(); // Query method should be use on current server type. Accepted value: null or new A2S() or new FIVEM() or new UT3() // - Game server default values public string Port = "27017"; // Default port public string CommunicationPort = "8766"; // Steam Communications Port public string QueryPort = "27016"; // Default query port public string Defaultmap = "empty"; // Default map name public string Maxplayers = "64"; // Default maxplayers public string Additional = "-profiles=the_forestHosts -config=server.cfg"; // Additional server start parameter // - Create a default cfg for the game server after installation public async void CreateServerCFG() { } // - Start server function, return its Process to WindowsGSM public async Task<Process> Start() { // Prepare start parameter var param = new StringBuilder(); param.Append(string.IsNullOrWhiteSpace(_serverData.ServerPort) ? string.Empty : $" -port={_serverData.ServerPort}"); param.Append(string.IsNullOrWhiteSpace(_serverData.ServerName) ? string.Empty : $" -name=\"{_serverData.ServerName}\""); param.Append(string.IsNullOrWhiteSpace(_serverData.ServerParam) ? string.Empty : $" {_serverData.ServerParam}"); // Prepare Process var p = new Process { StartInfo = { WindowStyle = ProcessWindowStyle.Minimized, UseShellExecute = false, WorkingDirectory = ServerPath.GetServersServerFiles(_serverData.ServerID), FileName = ServerPath.GetServersServerFiles(_serverData.ServerID, StartPath), Arguments = param.ToString() }, EnableRaisingEvents = true }; // Start Process try { p.Start(); return p; } catch (Exception e) { base.Error = e.Message; return null; // return null if fail to start } } // - Stop server function public async Task Stop(Process p) => await Task.Run(() => { p.Kill(); }); // I believe the_forest doesn't have a proper way to stop the server so just kill it } }
44.721649
166
0.631858
[ "MIT" ]
Inity949/WindowsGSM.theforest
theforest.cs/theforest.cs
4,341
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.Windows.Forms.Integration; using Advanced_Combat_Tracker; using FFXIV.Framework.Common; using FFXIV.Framework.Extensions; using FFXIV.Framework.FFXIVHelper; using TamanegiMage.FFXIV_MemoryReader.Model; namespace ACT.XIVLog { public class XIVLogPlugin : IActPluginV1, INotifyPropertyChanged { #region Singleton private static XIVLogPlugin instance; public static XIVLogPlugin Instance => instance; public XIVLogPlugin() => instance = this; #endregion Singleton #region IActPluginV1 private Label pluginLabel; public void InitPlugin( TabPage pluginScreenSpace, Label pluginStatusText) { pluginScreenSpace.Text = "XIVLog"; this.pluginLabel = pluginStatusText; var i = Config.Instance; // 設定Panelを追加する pluginScreenSpace.Controls.Add(new ElementHost() { Child = new ConfigView(), Dock = DockStyle.Fill, }); this.InitTask(); this.pluginLabel.Text = "Plugin Started"; } public void DeInitPlugin() { this.EndTask(); Config.Save(); this.pluginLabel.Text = "Plugin Exited"; GC.Collect(); } #endregion IActPluginV1 public string LogfileNameWithoutParent => Path.GetFileName(this.LogfileName); public string LogfileName => Path.Combine( Config.Instance.OutputDirectory, $"XIVLog.{DateTime.Now.ToString("yyyy-MM-dd")}.csv"); private volatile string currentLogfileName = string.Empty; private volatile string currentZoneName = string.Empty; private static readonly ConcurrentQueue<XIVLog> LogQueue = new ConcurrentQueue<XIVLog>(); private ThreadWorker dumpLogTask; private StreamWriter writter; private StringBuilder writeBuffer = new StringBuilder(5120); private DateTime lastFlushTimestamp = DateTime.MinValue; private void InitTask() { this.dumpLogTask = ThreadWorker.Run( doWork, TimeSpan.FromSeconds(Config.Instance.WriteInterval).TotalMilliseconds, "XIVLog Worker", ThreadPriority.Lowest); ActGlobals.oFormActMain.OnLogLineRead -= this.OnLogLineRead; ActGlobals.oFormActMain.OnLogLineRead += this.OnLogLineRead; void doWork() { var isNeedsFlush = false; if (string.IsNullOrEmpty(Config.Instance.OutputDirectory) || LogQueue.IsEmpty) { Thread.Sleep(TimeSpan.FromSeconds(Config.Instance.WriteInterval)); return; } if ((DateTime.Now - this.lastFlushTimestamp).TotalSeconds >= Config.Instance.FlushInterval) { isNeedsFlush = true; } if (this.currentLogfileName != this.LogfileName) { if (this.writter != null) { this.writter.Flush(); this.writter.Close(); this.writter.Dispose(); } if (!Directory.Exists(Config.Instance.OutputDirectory)) { Directory.CreateDirectory(Config.Instance.OutputDirectory); } this.writter = new StreamWriter( new FileStream( this.LogfileName, FileMode.Append, FileAccess.Write, FileShare.Read), new UTF8Encoding(false)); this.currentLogfileName = this.LogfileName; this.RaisePropertyChanged(nameof(this.LogfileName)); this.RaisePropertyChanged(nameof(this.LogfileNameWithoutParent)); } XIVLog.RefreshPCNameDictionary(); this.writeBuffer.Clear(); while (LogQueue.TryDequeue(out XIVLog xivlog)) { if (this.currentZoneName != xivlog.ZoneName) { this.currentZoneName = xivlog.ZoneName; isNeedsFlush = true; } this.writeBuffer.AppendLine(xivlog.ToCSVLine()); Thread.Yield(); } if (this.writeBuffer.Length > 0) { this.writter.Write(this.writeBuffer.ToString()); } if (isNeedsFlush) { this.lastFlushTimestamp = DateTime.Now; this.writter?.Flush(); } } } private void EndTask() { ActGlobals.oFormActMain.OnLogLineRead -= this.OnLogLineRead; if (dumpLogTask != null) { this.dumpLogTask.Abort(); this.dumpLogTask = null; } if (this.writter != null) { this.writter.Flush(); this.writter.Close(); this.writter.Dispose(); this.writter = null; } } private void OnLogLineRead( bool isImport, LogLineEventArgs logInfo) { if (string.IsNullOrEmpty(Config.Instance.OutputDirectory)) { return; } LogQueue.Enqueue(new XIVLog(isImport, logInfo)); if (!isImport) { this.OpenXIVLogAsync(logInfo.logLine); } } private string ConvertZoneNameToLog() { var result = this.currentZoneName; if (string.IsNullOrEmpty(result)) { result = "GLOBAL"; } else { // 無効な文字を置き換える result = string.Concat( result.Select(c => Path.GetInvalidFileNameChars().Contains(c) ? '_' : c)); } return result; } private Task OpenXIVLogAsync( string logLine) => Task.Run(() => { const string CommandKeyword = "/xivlog open"; if (string.IsNullOrEmpty(logLine)) { return; } if (!File.Exists(this.LogfileName)) { return; } if (logLine.ContainsIgnoreCase(CommandKeyword)) { Process.Start(this.LogfileName); } }); #region INotifyPropertyChanged [field: NonSerialized] public event PropertyChangedEventHandler PropertyChanged; public void RaisePropertyChanged( [CallerMemberName]string propertyName = null) { this.PropertyChanged?.Invoke( this, new PropertyChangedEventArgs(propertyName)); } protected virtual bool SetProperty<T>( ref T field, T value, [CallerMemberName]string propertyName = null) { if (Equals(field, value)) { return false; } field = value; this.PropertyChanged?.Invoke( this, new PropertyChangedEventArgs(propertyName)); return true; } #endregion INotifyPropertyChanged } public class XIVLog { public XIVLog( bool isImport, LogLineEventArgs logInfo) { if (logInfo == null || string.IsNullOrEmpty(logInfo.logLine)) { return; } this.IsImport = isImport; this.LogInfo = logInfo; // ログの書式の例 /* [08:20:19.383] 00:0000:clear stacks of Loading.... */ var line = this.LogInfo.logLine; // 18文字未満のログは書式エラーになるため無視する if (line.Length < 18) { return; } var timeString = line.Substring(1, 12); var timestampString = DateTime.Now.ToString("yyyy-MM-dd") + " " + timeString; DateTime d; if (DateTime.TryParse(timestampString, out d)) { this.Timestamp = d; } else { // タイムスタンプ書式が不正なものは無視する return; } this.LogType = line.Substring(15, 2); this.Log = line.Substring(15); this.ZoneName = !string.IsNullOrEmpty(logInfo.detectedZone) ? logInfo.detectedZone : "NO DATA"; if (currentNo >= int.MaxValue) { currentNo = 0; } currentNo++; this.No = currentNo; } private static volatile int currentNo = 0; public int No { get; private set; } public DateTime Timestamp { get; private set; } public bool IsImport { get; private set; } public string LogType { get; private set; } public string ZoneName { get; private set; } public string Log { get; private set; } public LogLineEventArgs LogInfo { get; set; } private static readonly Dictionary<string, Alias> PCNameDictionary = new Dictionary<string, Alias>(512); private static readonly string[] JobAliases = new[] { "Jackson", // 0 "Olivia", // 1 "Harry", // 2 "Lily", // 3 "Lucas", // 4 "Sophia", // 5 "Jack", // 6 "Emily", // 7 "Michael", // 8 "Amelia", // 9 }; public static void RefreshPCNameDictionary() { if (!Config.Instance.IsReplacePCName) { return; } var combatants = FFXIVPlugin.Instance?.GetCombatantList() .Where(x => x.type == ObjectType.PC); if (combatants == null) { return; } // 古くなったエントリを削除する var olds = PCNameDictionary.Where(x => (DateTime.Now - x.Value.Timestamp).TotalMinutes >= 10.0) .ToArray(); foreach (var toRemove in olds) { PCNameDictionary.Remove(toRemove.Key); Thread.Yield(); } foreach (var com in combatants) { var alias = new Alias( $"{com.AsJob()?.NameEN.Replace(" ", string.Empty) ?? "Unknown"} {JobAliases[com.Job % 10]}", DateTime.Now); PCNameDictionary[com.Name] = alias; PCNameDictionary[com.NameFI] = alias; PCNameDictionary[com.NameIF] = alias; Thread.Yield(); } } public string GetReplacedLog() { if (!Config.Instance.IsReplacePCName) { return this.Log; } var result = this.Log; foreach (var entry in PCNameDictionary) { var before = result; result = result.Replace(entry.Key, entry.Value.Replacement); if (result != before) { entry.Value.Timestamp = DateTime.Now; } Thread.Yield(); } return result; } public string ToCSVLine() => $"{this.No:000000000}," + $"{this.Timestamp:yyyy-MM-dd HH:mm:ss.fff}," + $"{(this.IsImport ? 1 : 0)}," + $"\"{this.LogType}\"," + $"\"{this.GetReplacedLog()}\"," + $"\"{this.ZoneName}\""; public class Alias { public Alias( string replacement, DateTime timestamp) { this.Replacement = replacement; this.Timestamp = timestamp; } public string Replacement { get; set; } public DateTime Timestamp { get; set; } } } }
29.284768
113
0.475124
[ "BSD-3-Clause" ]
sayakaanelli/ACT.Hojoring
source/ACT.XIVLog/XIVLogPlugin.cs
13,428
C#
using Shared.Application.Exceptions; using Modules.Todolist.Application.Commands.CreateTodoItem; using Modules.Todolist.Application.Commands.UpdateTodoItem; using Modules.Todolist.Application.Commands.UpdateTodoItemDetail; using Modules.Todolist.Application.Commands.CreateTodoList; using Modules.Todolist.Domain.Entities; using Modules.Todolist.Domain.Enums; using FluentAssertions; using System.Threading.Tasks; using NUnit.Framework; using System; namespace Modules.Todolist.Application.IntegrationTests.TodoItems.Commands { using static Testing; public class UpdateTodoItemDetailTests : TestBase { [Test] public void ShouldRequireValidTodoItemId() { var command = new UpdateTodoItemCommand { Id = 99, Title = "New Title" }; FluentActions.Invoking(() => SendAsync(command)).Should().Throw<NotFoundException>(); } [Test] public async Task ShouldUpdateTodoItem() { var userId = await RunAsDefaultUserAsync(); var listId = await SendAsync(new CreateTodoListCommand { Title = "New List" }); var itemId = await SendAsync(new CreateTodoItemCommand { ListId = listId, Title = "New Item" }); var command = new UpdateTodoItemDetailCommand { Id = itemId, ListId = listId, Note = "This is the note.", Priority = PriorityLevel.High }; await SendAsync(command); var item = await FindAsync<TodoItem>(itemId); item.ListId.Should().Be(command.ListId); item.Note.Should().Be(command.Note); item.Priority.Should().Be(command.Priority); item.LastModifiedBy.Should().NotBeNull(); item.LastModifiedBy.Should().Be(userId); item.LastModified.Should().NotBeNull(); item.LastModified.Should().BeCloseTo(DateTime.Now, 10000); } } }
30.514286
74
0.597846
[ "MIT" ]
tomaforn/clean-architecture
tests/Application.IntegrationTests/TodoItems/Commands/UpdateTodoItemDetailTests.cs
2,138
C#
using CUE4Parse.UE4.Readers; namespace CUE4Parse.UE4.Wwise.Objects { public abstract class AbstractHierarchy { public uint Id { get; } protected AbstractHierarchy(FArchive Ar) { Id = Ar.Read<uint>(); } } }
18.857143
48
0.590909
[ "MIT" ]
Mrzzbelladonna/ProSwapper
CUE4Parse/CUE4Parse/UE4/Wwise/Objects/AbstractHierarchy.cs
266
C#
// Copyright © Microsoft Corporation. All Rights Reserved. // This code released under the terms of the // Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.) // //Copyright (C) Microsoft Corporation. All rights reserved. using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Text; using System.Threading; namespace System.Linq.Dynamic { [Browsable(false)] public static class DynamicQueryable { public static bool Any(this IQueryable source) { if (source == null) throw new ArgumentNullException("source"); return (bool) source.Provider.Execute( Expression.Call( typeof (Queryable), "Any", new[] {source.ElementType}, source.Expression)); } public static int Count(this IQueryable source) { if (source == null) throw new ArgumentNullException("source"); return (int) source.Provider.Execute( Expression.Call( typeof (Queryable), "Count", new[] {source.ElementType}, source.Expression)); } public static IQueryable GroupBy(this IQueryable source, string keySelector, string elementSelector, params object[] values) { if (source == null) throw new ArgumentNullException("source"); if (keySelector == null) throw new ArgumentNullException("keySelector"); if (elementSelector == null) throw new ArgumentNullException("elementSelector"); LambdaExpression keyLambda = DynamicExpression.ParseLambda(source.ElementType, null, keySelector, values); LambdaExpression elementLambda = DynamicExpression.ParseLambda(source.ElementType, null, elementSelector, values); return source.Provider.CreateQuery( Expression.Call( typeof (Queryable), "GroupBy", new[] {source.ElementType, keyLambda.Body.Type, elementLambda.Body.Type}, source.Expression, Expression.Quote(keyLambda), Expression.Quote(elementLambda))); } public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, string ordering, params object[] values) { return (IQueryable<T>) OrderBy((IQueryable) source, ordering, values); } public static IQueryable OrderBy(this IQueryable source, string ordering, params object[] values) { if (source == null) throw new ArgumentNullException("source"); if (ordering == null) throw new ArgumentNullException("ordering"); ParameterExpression[] parameters = { Expression.Parameter(source.ElementType, "") }; ExpressionParser parser = new ExpressionParser(parameters, ordering, values); IEnumerable<DynamicOrdering> orderings = parser.ParseOrdering(); Expression queryExpr = source.Expression; string methodAsc = "OrderBy"; string methodDesc = "OrderByDescending"; foreach (DynamicOrdering o in orderings) { queryExpr = Expression.Call( typeof (Queryable), o.Ascending ? methodAsc : methodDesc, new[] {source.ElementType, o.Selector.Type}, queryExpr, Expression.Quote(Expression.Lambda(o.Selector, parameters))); methodAsc = "ThenBy"; methodDesc = "ThenByDescending"; } return source.Provider.CreateQuery(queryExpr); } public static IQueryable Select(this IQueryable source, string selector, params object[] values) { if (source == null) throw new ArgumentNullException("source"); if (selector == null) throw new ArgumentNullException("selector"); LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, null, selector, values); return source.Provider.CreateQuery( Expression.Call( typeof (Queryable), "Select", new[] {source.ElementType, lambda.Body.Type}, source.Expression, Expression.Quote(lambda))); } public static IQueryable Skip(this IQueryable source, int count) { if (source == null) throw new ArgumentNullException("source"); return source.Provider.CreateQuery( Expression.Call( typeof (Queryable), "Skip", new[] {source.ElementType}, source.Expression, Expression.Constant(count))); } public static IQueryable Take(this IQueryable source, int count) { if (source == null) throw new ArgumentNullException("source"); return source.Provider.CreateQuery( Expression.Call( typeof (Queryable), "Take", new[] {source.ElementType}, source.Expression, Expression.Constant(count))); } public static IQueryable<T> Where<T>(this IQueryable<T> source, string predicate, params object[] values) { return (IQueryable<T>) Where((IQueryable) source, predicate, values); } public static IQueryable Where(this IQueryable source, string predicate, params object[] values) { if (source == null) throw new ArgumentNullException("source"); if (predicate == null) throw new ArgumentNullException("predicate"); LambdaExpression lambda = DynamicExpression.ParseLambda(source.ElementType, typeof (bool), predicate, values); return source.Provider.CreateQuery( Expression.Call( typeof (Queryable), "Where", new[] {source.ElementType}, source.Expression, Expression.Quote(lambda))); } } [Browsable(false)] public abstract class DynamicClass { public override string ToString() { PropertyInfo[] props = GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public); StringBuilder sb = new StringBuilder(); sb.Append("{"); for (int i = 0; i < props.Length; i++) { if (i > 0) sb.Append(", "); sb.Append(props[i].Name); sb.Append("="); sb.Append(props[i].GetValue(this, null)); } sb.Append("}"); return sb.ToString(); } } [Browsable(false)] public class DynamicProperty { private readonly string name; private readonly Type type; public DynamicProperty(string name, Type type) { if (name == null) throw new ArgumentNullException("name"); if (type == null) throw new ArgumentNullException("type"); this.name = name; this.type = type; } public string Name { get { return name; } } public Type Type { get { return type; } } } [Browsable(false)] public static class DynamicExpression { public static Type CreateClass(params DynamicProperty[] properties) { return ClassFactory.Instance.GetDynamicClass(properties); } public static Type CreateClass(IEnumerable<DynamicProperty> properties) { return ClassFactory.Instance.GetDynamicClass(properties); } public static Expression Parse(Type resultType, string expression, params object[] values) { ExpressionParser parser = new ExpressionParser(null, expression, values); return parser.Parse(resultType); } public static LambdaExpression ParseLambda(Type itType, Type resultType, string expression, params object[] values) { return ParseLambda(new[] { Expression.Parameter(itType, "") }, resultType, expression, values); } public static LambdaExpression ParseLambda(ParameterExpression[] parameters, Type resultType, string expression, params object[] values) { ExpressionParser parser = new ExpressionParser(parameters, expression, values); return Expression.Lambda(parser.Parse(resultType), parameters); } public static Expression<Func<T, S>> ParseLambda<T, S>(string expression, params object[] values) { return (Expression<Func<T, S>>) ParseLambda(typeof (T), typeof (S), expression, values); } } [Browsable(false)] /// <summary> /// Access Modifier adjusted to public specifically for the InfoPath solution as it is now referenced outside the /// Dynamic.cs file /// </summary> public class DynamicOrdering { public bool Ascending; public Expression Selector; } [Browsable(false)] internal class Signature : IEquatable<Signature> { public int hashCode; public DynamicProperty[] properties; public Signature(IEnumerable<DynamicProperty> properties) { this.properties = properties.ToArray(); hashCode = 0; foreach (DynamicProperty p in properties) hashCode ^= p.Name.GetHashCode() ^ p.Type.GetHashCode(); } public bool Equals(Signature other) { if (properties.Length != other.properties.Length) return false; for (int i = 0; i < properties.Length; i++) if (properties[i].Name != other.properties[i].Name || properties[i].Type != other.properties[i].Type) return false; return true; } public override bool Equals(object obj) { return obj is Signature ? Equals((Signature) obj) : false; } public override int GetHashCode() { return hashCode; } } [Browsable(false)] internal class ClassFactory { public static readonly ClassFactory Instance = new ClassFactory(); private readonly Dictionary<Signature, Type> classes; private readonly ModuleBuilder module; private readonly ReaderWriterLock rwLock; private int classCount; static ClassFactory() { } // Trigger lazy initialization of static fields private ClassFactory() { AssemblyName name = new AssemblyName("DynamicClasses"); AssemblyBuilder assembly = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run); #if ENABLE_LINQ_PARTIAL_TRUST new ReflectionPermission(PermissionState.Unrestricted).Assert(); #endif try { module = assembly.DefineDynamicModule("Module"); } finally { #if ENABLE_LINQ_PARTIAL_TRUST PermissionSet.RevertAssert(); #endif } classes = new Dictionary<Signature, Type>(); rwLock = new ReaderWriterLock(); } private Type CreateDynamicClass(DynamicProperty[] properties) { LockCookie cookie = rwLock.UpgradeToWriterLock(Timeout.Infinite); try { string typeName = "DynamicClass" + (classCount + 1); #if ENABLE_LINQ_PARTIAL_TRUST new ReflectionPermission(PermissionState.Unrestricted).Assert(); #endif try { TypeBuilder tb = module.DefineType(typeName, TypeAttributes.Class | TypeAttributes.Public, typeof (DynamicClass)); FieldInfo[] fields = GenerateProperties(tb, properties); GenerateEquals(tb, fields); GenerateGetHashCode(tb, fields); Type result = tb.CreateType(); classCount++; return result; } finally { #if ENABLE_LINQ_PARTIAL_TRUST PermissionSet.RevertAssert(); #endif } } finally { rwLock.DowngradeFromWriterLock(ref cookie); } } private void GenerateEquals(TypeBuilder tb, FieldInfo[] fields) { MethodBuilder mb = tb.DefineMethod("Equals", MethodAttributes.Public | MethodAttributes.ReuseSlot | MethodAttributes.Virtual | MethodAttributes.HideBySig, typeof (bool), new[] {typeof (object)}); ILGenerator gen = mb.GetILGenerator(); LocalBuilder other = gen.DeclareLocal(tb); Label next = gen.DefineLabel(); gen.Emit(OpCodes.Ldarg_1); gen.Emit(OpCodes.Isinst, tb); gen.Emit(OpCodes.Stloc, other); gen.Emit(OpCodes.Ldloc, other); gen.Emit(OpCodes.Brtrue_S, next); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ret); gen.MarkLabel(next); foreach (FieldInfo field in fields) { Type ft = field.FieldType; Type ct = typeof (EqualityComparer<>).MakeGenericType(ft); next = gen.DefineLabel(); gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, field); gen.Emit(OpCodes.Ldloc, other); gen.Emit(OpCodes.Ldfld, field); gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("Equals", new[] {ft, ft}), null); gen.Emit(OpCodes.Brtrue_S, next); gen.Emit(OpCodes.Ldc_I4_0); gen.Emit(OpCodes.Ret); gen.MarkLabel(next); } gen.Emit(OpCodes.Ldc_I4_1); gen.Emit(OpCodes.Ret); } private void GenerateGetHashCode(TypeBuilder tb, FieldInfo[] fields) { MethodBuilder mb = tb.DefineMethod("GetHashCode", MethodAttributes.Public | MethodAttributes.ReuseSlot | MethodAttributes.Virtual | MethodAttributes.HideBySig, typeof (int), Type.EmptyTypes); ILGenerator gen = mb.GetILGenerator(); gen.Emit(OpCodes.Ldc_I4_0); foreach (FieldInfo field in fields) { Type ft = field.FieldType; Type ct = typeof (EqualityComparer<>).MakeGenericType(ft); gen.EmitCall(OpCodes.Call, ct.GetMethod("get_Default"), null); gen.Emit(OpCodes.Ldarg_0); gen.Emit(OpCodes.Ldfld, field); gen.EmitCall(OpCodes.Callvirt, ct.GetMethod("GetHashCode", new[] {ft}), null); gen.Emit(OpCodes.Xor); } gen.Emit(OpCodes.Ret); } private FieldInfo[] GenerateProperties(TypeBuilder tb, DynamicProperty[] properties) { FieldInfo[] fields = new FieldBuilder[properties.Length]; for (int i = 0; i < properties.Length; i++) { DynamicProperty dp = properties[i]; FieldBuilder fb = tb.DefineField("_" + dp.Name, dp.Type, FieldAttributes.Private); PropertyBuilder pb = tb.DefineProperty(dp.Name, PropertyAttributes.HasDefault, dp.Type, null); MethodBuilder mbGet = tb.DefineMethod("get_" + dp.Name, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, dp.Type, Type.EmptyTypes); ILGenerator genGet = mbGet.GetILGenerator(); genGet.Emit(OpCodes.Ldarg_0); genGet.Emit(OpCodes.Ldfld, fb); genGet.Emit(OpCodes.Ret); MethodBuilder mbSet = tb.DefineMethod("set_" + dp.Name, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, null, new[] {dp.Type}); ILGenerator genSet = mbSet.GetILGenerator(); genSet.Emit(OpCodes.Ldarg_0); genSet.Emit(OpCodes.Ldarg_1); genSet.Emit(OpCodes.Stfld, fb); genSet.Emit(OpCodes.Ret); pb.SetGetMethod(mbGet); pb.SetSetMethod(mbSet); fields[i] = fb; } return fields; } public Type GetDynamicClass(IEnumerable<DynamicProperty> properties) { rwLock.AcquireReaderLock(Timeout.Infinite); try { Signature signature = new Signature(properties); Type type; if (!classes.TryGetValue(signature, out type)) { type = CreateDynamicClass(signature.properties); classes.Add(signature, type); } return type; } finally { rwLock.ReleaseReaderLock(); } } } [Browsable(false)] public sealed class ParseException : Exception { private readonly int position; public ParseException(string message, int position) : base(message) { this.position = position; } public int Position { get { return position; } } public override string ToString() { return string.Format(Res.ParseExceptionFormat, Message, position); } } [Browsable(false)] public class ExpressionParser { private static readonly Type[] predefinedTypes = { typeof (Object), typeof (Boolean), typeof (Char), typeof (String), typeof (SByte), typeof (Byte), typeof (Int16), typeof (UInt16), typeof (Int32), typeof (UInt32), typeof (Int64), typeof (UInt64), typeof (Single), typeof (Double), typeof (Decimal), typeof (DateTime), typeof (TimeSpan), typeof (Guid), typeof (Math), typeof (Convert) }; private static readonly Expression trueLiteral = Expression.Constant(true); private static readonly Expression falseLiteral = Expression.Constant(false); private static readonly Expression nullLiteral = Expression.Constant(null); private static readonly string keywordIt = "it"; private static readonly string keywordIif = "iif"; private static readonly string keywordNew = "new"; private static Dictionary<string, object> keywords; private readonly Dictionary<Expression, string> literals; private readonly Dictionary<string, object> symbols; private readonly string text; private readonly int textLen; private char ch; private IDictionary<string, object> externals; private ParameterExpression it; private int textPos; private Token token; public ExpressionParser(ParameterExpression[] parameters, string expression, object[] values) { if (expression == null) throw new ArgumentNullException("expression"); if (keywords == null) keywords = CreateKeywords(); symbols = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); literals = new Dictionary<Expression, string>(); if (parameters != null) ProcessParameters(parameters); if (values != null) ProcessValues(values); text = expression; textLen = text.Length; SetTextPos(0); NextToken(); } private static void AddInterface(List<Type> types, Type type) { if (!types.Contains(type)) { types.Add(type); foreach (Type t in type.GetInterfaces()) AddInterface(types, t); } } private void AddSymbol(string name, object value) { if (symbols.ContainsKey(name)) throw ParseError(Res.DuplicateIdentifier, name); symbols.Add(name, value); } private void CheckAndPromoteOperand(Type signatures, string opName, ref Expression expr, int errorPos) { Expression[] args = {expr}; MethodBase method; if (FindMethod(signatures, "F", false, args, out method) != 1) throw ParseError(errorPos, Res.IncompatibleOperand, opName, GetTypeName(args[0].Type)); expr = args[0]; } private void CheckAndPromoteOperands(Type signatures, string opName, ref Expression left, ref Expression right, int errorPos) { Expression[] args = {left, right}; MethodBase method; if (FindMethod(signatures, "F", false, args, out method) != 1) throw IncompatibleOperandsError(opName, left, right, errorPos); left = args[0]; right = args[1]; } // Return 1 if s -> t1 is a better conversion than s -> t2 // Return -1 if s -> t2 is a better conversion than s -> t1 // Return 0 if neither conversion is better private static int CompareConversions(Type s, Type t1, Type t2) { if (t1 == t2) return 0; if (s == t1) return 1; if (s == t2) return -1; bool t1t2 = IsCompatibleWith(t1, t2); bool t2t1 = IsCompatibleWith(t2, t1); if (t1t2 && !t2t1) return 1; if (t2t1 && !t1t2) return -1; if (IsSignedIntegralType(t1) && IsUnsignedIntegralType(t2)) return 1; if (IsSignedIntegralType(t2) && IsUnsignedIntegralType(t1)) return -1; return 0; } private static Dictionary<string, object> CreateKeywords() { Dictionary<string, object> d = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); d.Add("true", trueLiteral); d.Add("false", falseLiteral); d.Add("null", nullLiteral); d.Add(keywordIt, keywordIt); d.Add(keywordIif, keywordIif); d.Add(keywordNew, keywordNew); foreach (Type type in predefinedTypes) d.Add(type.Name, type); return d; } private Expression CreateLiteral(object value, string text) { ConstantExpression expr = Expression.Constant(value); literals.Add(expr, text); return expr; } private int FindBestMethod(IEnumerable<MethodBase> methods, Expression[] args, out MethodBase method) { MethodData[] applicable = methods. Select(m => new MethodData {MethodBase = m, Parameters = m.GetParameters()}). Where(m => IsApplicable(m, args)). ToArray(); if (applicable.Length > 1) applicable = applicable. Where(m => applicable.All(n => m == n || IsBetterThan(args, m, n))). ToArray(); if (applicable.Length == 1) { MethodData md = applicable[0]; for (int i = 0; i < args.Length; i++) args[i] = md.Args[i]; method = md.MethodBase; } else method = null; return applicable.Length; } private static Type FindGenericType(Type generic, Type type) { while (type != null && type != typeof (object)) { if (type.IsGenericType && type.GetGenericTypeDefinition() == generic) return type; if (generic.IsInterface) foreach (Type intfType in type.GetInterfaces()) { Type found = FindGenericType(generic, intfType); if (found != null) return found; } type = type.BaseType; } return null; } private int FindIndexer(Type type, Expression[] args, out MethodBase method) { foreach (Type t in SelfAndBaseTypes(type)) { MemberInfo[] members = t.GetDefaultMembers(); if (members.Length != 0) { IEnumerable<MethodBase> methods = members. OfType<PropertyInfo>(). Select(p => (MethodBase) p.GetGetMethod()). Where(m => m != null); int count = FindBestMethod(methods, args, out method); if (count != 0) return count; } } method = null; return 0; } private int FindMethod(Type type, string methodName, bool staticAccess, Expression[] args, out MethodBase method) { BindingFlags flags = BindingFlags.Public | BindingFlags.DeclaredOnly | (staticAccess ? BindingFlags.Static : BindingFlags.Instance); foreach (Type t in SelfAndBaseTypes(type)) { MemberInfo[] members = t.FindMembers(MemberTypes.Method, flags, Type.FilterNameIgnoreCase, methodName); int count = FindBestMethod(members.Cast<MethodBase>(), args, out method); if (count != 0) return count; } method = null; return 0; } private MemberInfo FindPropertyOrField(Type type, string memberName, bool staticAccess) { BindingFlags flags = BindingFlags.Public | BindingFlags.DeclaredOnly | (staticAccess ? BindingFlags.Static : BindingFlags.Instance); foreach (Type t in SelfAndBaseTypes(type)) { MemberInfo[] members = t.FindMembers(MemberTypes.Property | MemberTypes.Field, flags, Type.FilterNameIgnoreCase, memberName); if (members.Length != 0) return members[0]; } return null; } private Expression GenerateAdd(Expression left, Expression right) { if (left.Type == typeof (string) && right.Type == typeof (string)) return GenerateStaticMethodCall("Concat", left, right); return Expression.Add(left, right); } private Expression GenerateConditional(Expression test, Expression expr1, Expression expr2, int errorPos) { if (test.Type != typeof (bool)) throw ParseError(errorPos, Res.FirstExprMustBeBool); if (expr1.Type != expr2.Type) { Expression expr1as2 = expr2 != nullLiteral ? PromoteExpression(expr1, expr2.Type, true) : null; Expression expr2as1 = expr1 != nullLiteral ? PromoteExpression(expr2, expr1.Type, true) : null; if (expr1as2 != null && expr2as1 == null) expr1 = expr1as2; else if (expr2as1 != null && expr1as2 == null) expr2 = expr2as1; else { string type1 = expr1 != nullLiteral ? expr1.Type.Name : "null"; string type2 = expr2 != nullLiteral ? expr2.Type.Name : "null"; if (expr1as2 != null && expr2as1 != null) throw ParseError(errorPos, Res.BothTypesConvertToOther, type1, type2); throw ParseError(errorPos, Res.NeitherTypeConvertsToOther, type1, type2); } } return Expression.Condition(test, expr1, expr2); } private Expression GenerateConversion(Expression expr, Type type, int errorPos) { Type exprType = expr.Type; if (exprType == type) return expr; if (exprType.IsValueType && type.IsValueType) { if ((IsNullableType(exprType) || IsNullableType(type)) && GetNonNullableType(exprType) == GetNonNullableType(type)) return Expression.Convert(expr, type); if ((IsNumericType(exprType) || IsEnumType(exprType)) && (IsNumericType(type)) || IsEnumType(type)) return Expression.ConvertChecked(expr, type); } if (exprType.IsAssignableFrom(type) || type.IsAssignableFrom(exprType) || exprType.IsInterface || type.IsInterface) return Expression.Convert(expr, type); throw ParseError(errorPos, Res.CannotConvertValue, GetTypeName(exprType), GetTypeName(type)); } private Expression GenerateEqual(Expression left, Expression right) { return Expression.Equal(left, right); } private Expression GenerateGreaterThan(Expression left, Expression right) { if (left.Type == typeof (string)) return Expression.GreaterThan( GenerateStaticMethodCall("Compare", left, right), Expression.Constant(0) ); return Expression.GreaterThan(left, right); } private Expression GenerateGreaterThanEqual(Expression left, Expression right) { if (left.Type == typeof (string)) return Expression.GreaterThanOrEqual( GenerateStaticMethodCall("Compare", left, right), Expression.Constant(0) ); return Expression.GreaterThanOrEqual(left, right); } private Expression GenerateLessThan(Expression left, Expression right) { if (left.Type == typeof (string)) return Expression.LessThan( GenerateStaticMethodCall("Compare", left, right), Expression.Constant(0) ); return Expression.LessThan(left, right); } private Expression GenerateLessThanEqual(Expression left, Expression right) { if (left.Type == typeof (string)) return Expression.LessThanOrEqual( GenerateStaticMethodCall("Compare", left, right), Expression.Constant(0) ); return Expression.LessThanOrEqual(left, right); } private Expression GenerateNotEqual(Expression left, Expression right) { return Expression.NotEqual(left, right); } private Expression GenerateStaticMethodCall(string methodName, Expression left, Expression right) { return Expression.Call(null, GetStaticMethod(methodName, left, right), new[] {left, right}); } private Expression GenerateStringConcat(Expression left, Expression right) { return Expression.Call( null, typeof (string).GetMethod("Concat", new[] {typeof (object), typeof (object)}), new[] {left, right}); } private Expression GenerateSubtract(Expression left, Expression right) { return Expression.Subtract(left, right); } private string GetIdentifier() { ValidateToken(TokenId.Identifier, Res.IdentifierExpected); string id = token.text; if (id.Length > 1 && id[0] == '@') id = id.Substring(1); return id; } /// <summary> /// Access Modifier adjusted to public specifically for the InfoPath solution as it is now referenced outside the /// Dynamic.cs file /// </summary> /// <param name="type"></param> /// <returns></returns> public static Type GetNonNullableType(Type type) { return IsNullableType(type) ? type.GetGenericArguments()[0] : type; } private static int GetNumericTypeKind(Type type) { type = GetNonNullableType(type); if (type.IsEnum) return 0; switch (Type.GetTypeCode(type)) { case TypeCode.Char: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return 1; case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: return 2; case TypeCode.Byte: case TypeCode.UInt16: case TypeCode.UInt32: case TypeCode.UInt64: return 3; default: return 0; } } private MethodInfo GetStaticMethod(string methodName, Expression left, Expression right) { return left.Type.GetMethod(methodName, new[] {left.Type, right.Type}); } private static string GetTypeName(Type type) { Type baseType = GetNonNullableType(type); string s = baseType.Name; if (type != baseType) s += '?'; return s; } private Exception IncompatibleOperandsError(string opName, Expression left, Expression right, int pos) { return ParseError(pos, Res.IncompatibleOperands, opName, GetTypeName(left.Type), GetTypeName(right.Type)); } private bool IsApplicable(MethodData method, Expression[] args) { if (method.Parameters.Length != args.Length) return false; Expression[] promotedArgs = new Expression[args.Length]; for (int i = 0; i < args.Length; i++) { ParameterInfo pi = method.Parameters[i]; if (pi.IsOut) return false; Expression promoted = PromoteExpression(args[i], pi.ParameterType, false); if (promoted == null) return false; promotedArgs[i] = promoted; } method.Args = promotedArgs; return true; } private static bool IsBetterThan(Expression[] args, MethodData m1, MethodData m2) { bool better = false; for (int i = 0; i < args.Length; i++) { int c = CompareConversions(args[i].Type, m1.Parameters[i].ParameterType, m2.Parameters[i].ParameterType); if (c < 0) return false; if (c > 0) better = true; } return better; } private static bool IsCompatibleWith(Type source, Type target) { if (source == target) return true; if (!target.IsValueType) return target.IsAssignableFrom(source); Type st = GetNonNullableType(source); Type tt = GetNonNullableType(target); if (st != source && tt == target) return false; TypeCode sc = st.IsEnum ? TypeCode.Object : Type.GetTypeCode(st); TypeCode tc = tt.IsEnum ? TypeCode.Object : Type.GetTypeCode(tt); switch (sc) { case TypeCode.SByte: switch (tc) { case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.Byte: switch (tc) { case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.Int16: switch (tc) { case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.UInt16: switch (tc) { case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.Int32: switch (tc) { case TypeCode.Int32: case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.UInt32: switch (tc) { case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.Int64: switch (tc) { case TypeCode.Int64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.UInt64: switch (tc) { case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: return true; } break; case TypeCode.Single: switch (tc) { case TypeCode.Single: case TypeCode.Double: return true; } break; default: if (st == tt) return true; break; } return false; } private static bool IsEnumType(Type type) { return GetNonNullableType(type).IsEnum; } private static bool IsNullableType(Type type) { return type.IsGenericType && type.GetGenericTypeDefinition() == typeof (Nullable<>); } private static bool IsNumericType(Type type) { return GetNumericTypeKind(type) != 0; } /// <summary> /// Access Modifier adjusted to public specifically for the InfoPath solution as it is now referenced outside the /// Dynamic.cs file /// </summary> /// <param name="type"></param> /// <returns></returns> public static bool IsPredefinedType(Type type) { foreach (Type t in predefinedTypes) if (t == type) return true; return false; } private static bool IsSignedIntegralType(Type type) { return GetNumericTypeKind(type) == 2; } private static bool IsUnsignedIntegralType(Type type) { return GetNumericTypeKind(type) == 3; } private void NextChar() { if (textPos < textLen) textPos++; ch = textPos < textLen ? text[textPos] : '\0'; } private void NextToken() { while (Char.IsWhiteSpace(ch)) NextChar(); TokenId t; int tokenPos = textPos; switch (ch) { case '!': NextChar(); if (ch == '=') { NextChar(); t = TokenId.ExclamationEqual; } else t = TokenId.Exclamation; break; case '%': NextChar(); t = TokenId.Percent; break; case '&': NextChar(); if (ch == '&') { NextChar(); t = TokenId.DoubleAmphersand; } else t = TokenId.Amphersand; break; case '(': NextChar(); t = TokenId.OpenParen; break; case ')': NextChar(); t = TokenId.CloseParen; break; case '*': NextChar(); t = TokenId.Asterisk; break; case '+': NextChar(); t = TokenId.Plus; break; case ',': NextChar(); t = TokenId.Comma; break; case '-': NextChar(); t = TokenId.Minus; break; case '.': NextChar(); t = TokenId.Dot; break; case '/': NextChar(); t = TokenId.Slash; break; case ':': NextChar(); t = TokenId.Colon; break; case '<': NextChar(); if (ch == '=') { NextChar(); t = TokenId.LessThanEqual; } else if (ch == '>') { NextChar(); t = TokenId.LessGreater; } else t = TokenId.LessThan; break; case '=': NextChar(); if (ch == '=') { NextChar(); t = TokenId.DoubleEqual; } else t = TokenId.Equal; break; case '>': NextChar(); if (ch == '=') { NextChar(); t = TokenId.GreaterThanEqual; } else t = TokenId.GreaterThan; break; case '?': NextChar(); t = TokenId.Question; break; case '[': NextChar(); t = TokenId.OpenBracket; break; case ']': NextChar(); t = TokenId.CloseBracket; break; case '|': NextChar(); if (ch == '|') { NextChar(); t = TokenId.DoubleBar; } else t = TokenId.Bar; break; case '"': case '\'': char quote = ch; do { NextChar(); while (textPos < textLen && ch != quote) NextChar(); if (textPos == textLen) throw ParseError(textPos, Res.UnterminatedStringLiteral); NextChar(); } while (ch == quote); t = TokenId.StringLiteral; break; default: if (Char.IsLetter(ch) || ch == '@' || ch == '_') { do { NextChar(); } while (Char.IsLetterOrDigit(ch) || ch == '_'); t = TokenId.Identifier; break; } if (Char.IsDigit(ch)) { t = TokenId.IntegerLiteral; do { NextChar(); } while (Char.IsDigit(ch)); if (ch == '.') { t = TokenId.RealLiteral; NextChar(); ValidateDigit(); do { NextChar(); } while (Char.IsDigit(ch)); } if (ch == 'E' || ch == 'e') { t = TokenId.RealLiteral; NextChar(); if (ch == '+' || ch == '-') NextChar(); ValidateDigit(); do { NextChar(); } while (Char.IsDigit(ch)); } if (ch == 'F' || ch == 'f') NextChar(); break; } if (textPos == textLen) { t = TokenId.End; break; } throw ParseError(textPos, Res.InvalidCharacter, ch); } token.id = t; token.text = text.Substring(tokenPos, textPos - tokenPos); token.pos = tokenPos; } public Expression Parse(Type resultType) { int exprPos = token.pos; Expression expr = ParseExpression(); if (resultType != null) if ((expr = PromoteExpression(expr, resultType, true)) == null) throw ParseError(exprPos, Res.ExpressionTypeMismatch, GetTypeName(resultType)); ValidateToken(TokenId.End, Res.SyntaxError); return expr; } // +, -, & operators private Expression ParseAdditive() { Expression left = ParseMultiplicative(); while (token.id == TokenId.Plus || token.id == TokenId.Minus || token.id == TokenId.Amphersand) { Token op = token; NextToken(); Expression right = ParseMultiplicative(); switch (op.id) { case TokenId.Plus: if (left.Type == typeof (string) || right.Type == typeof (string)) goto case TokenId.Amphersand; CheckAndPromoteOperands(typeof (IAddSignatures), op.text, ref left, ref right, op.pos); left = GenerateAdd(left, right); break; case TokenId.Minus: CheckAndPromoteOperands(typeof (ISubtractSignatures), op.text, ref left, ref right, op.pos); left = GenerateSubtract(left, right); break; case TokenId.Amphersand: left = GenerateStringConcat(left, right); break; } } return left; } private Expression ParseAggregate(Expression instance, Type elementType, string methodName, int errorPos) { ParameterExpression outerIt = it; ParameterExpression innerIt = Expression.Parameter(elementType, ""); it = innerIt; Expression[] args = ParseArgumentList(); it = outerIt; MethodBase signature; if (FindMethod(typeof (IEnumerableSignatures), methodName, false, args, out signature) != 1) throw ParseError(errorPos, Res.NoApplicableAggregate, methodName); Type[] typeArgs; if (signature.Name == "Min" || signature.Name == "Max") typeArgs = new[] {elementType, args[0].Type}; else typeArgs = new[] {elementType}; if (args.Length == 0) args = new[] {instance}; else args = new[] { instance, Expression.Lambda(args[0], innerIt) }; return Expression.Call(typeof (Enumerable), signature.Name, typeArgs, args); } private Expression[] ParseArgumentList() { ValidateToken(TokenId.OpenParen, Res.OpenParenExpected); NextToken(); Expression[] args = token.id != TokenId.CloseParen ? ParseArguments() : new Expression[0]; ValidateToken(TokenId.CloseParen, Res.CloseParenOrCommaExpected); NextToken(); return args; } private Expression[] ParseArguments() { List<Expression> argList = new List<Expression>(); while (true) { argList.Add(ParseExpression()); if (token.id != TokenId.Comma) break; NextToken(); } return argList.ToArray(); } // =, ==, !=, <>, >, >=, <, <= operators private Expression ParseComparison() { Expression left = ParseAdditive(); while (token.id == TokenId.Equal || token.id == TokenId.DoubleEqual || token.id == TokenId.ExclamationEqual || token.id == TokenId.LessGreater || token.id == TokenId.GreaterThan || token.id == TokenId.GreaterThanEqual || token.id == TokenId.LessThan || token.id == TokenId.LessThanEqual) { Token op = token; NextToken(); Expression right = ParseAdditive(); bool isEquality = op.id == TokenId.Equal || op.id == TokenId.DoubleEqual || op.id == TokenId.ExclamationEqual || op.id == TokenId.LessGreater; if (isEquality && !left.Type.IsValueType && !right.Type.IsValueType) { if (left.Type != right.Type) if (left.Type.IsAssignableFrom(right.Type)) right = Expression.Convert(right, left.Type); else if (right.Type.IsAssignableFrom(left.Type)) left = Expression.Convert(left, right.Type); else throw IncompatibleOperandsError(op.text, left, right, op.pos); } else if (IsEnumType(left.Type) || IsEnumType(right.Type)) { if (left.Type != right.Type) { Expression e; if ((e = PromoteExpression(right, left.Type, true)) != null) right = e; else if ((e = PromoteExpression(left, right.Type, true)) != null) left = e; else throw IncompatibleOperandsError(op.text, left, right, op.pos); } } else CheckAndPromoteOperands(isEquality ? typeof (IEqualitySignatures) : typeof (IRelationalSignatures), op.text, ref left, ref right, op.pos); switch (op.id) { case TokenId.Equal: case TokenId.DoubleEqual: left = GenerateEqual(left, right); break; case TokenId.ExclamationEqual: case TokenId.LessGreater: left = GenerateNotEqual(left, right); break; case TokenId.GreaterThan: left = GenerateGreaterThan(left, right); break; case TokenId.GreaterThanEqual: left = GenerateGreaterThanEqual(left, right); break; case TokenId.LessThan: left = GenerateLessThan(left, right); break; case TokenId.LessThanEqual: left = GenerateLessThanEqual(left, right); break; } } return left; } private Expression ParseElementAccess(Expression expr) { int errorPos = token.pos; ValidateToken(TokenId.OpenBracket, Res.OpenParenExpected); NextToken(); Expression[] args = ParseArguments(); ValidateToken(TokenId.CloseBracket, Res.CloseBracketOrCommaExpected); NextToken(); if (expr.Type.IsArray) { if (expr.Type.GetArrayRank() != 1 || args.Length != 1) throw ParseError(errorPos, Res.CannotIndexMultiDimArray); Expression index = PromoteExpression(args[0], typeof (int), true); if (index == null) throw ParseError(errorPos, Res.InvalidIndex); return Expression.ArrayIndex(expr, index); } MethodBase mb; switch (FindIndexer(expr.Type, args, out mb)) { case 0: throw ParseError(errorPos, Res.NoApplicableIndexer, GetTypeName(expr.Type)); case 1: return Expression.Call(expr, (MethodInfo) mb, args); default: throw ParseError(errorPos, Res.AmbiguousIndexerInvocation, GetTypeName(expr.Type)); } } private static object ParseEnum(string name, Type type) { if (type.IsEnum) { MemberInfo[] memberInfos = type.FindMembers(MemberTypes.Field, BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Static, Type.FilterNameIgnoreCase, name); if (memberInfos.Length != 0) return ((FieldInfo) memberInfos[0]).GetValue(null); } return null; } private Exception ParseError(string format, params object[] args) { return ParseError(token.pos, format, args); } private Exception ParseError(int pos, string format, params object[] args) { return new ParseException(string.Format(CultureInfo.CurrentCulture, format, args), pos); } // ?: operator private Expression ParseExpression() { int errorPos = token.pos; Expression expr = ParseLogicalOr(); if (token.id == TokenId.Question) { NextToken(); Expression expr1 = ParseExpression(); ValidateToken(TokenId.Colon, Res.ColonExpected); NextToken(); Expression expr2 = ParseExpression(); expr = GenerateConditional(expr, expr1, expr2, errorPos); } return expr; } private Expression ParseIdentifier() { ValidateToken(TokenId.Identifier); object value; if (keywords.TryGetValue(token.text, out value)) { if (value is Type) return ParseTypeAccess((Type) value); if (value == keywordIt) return ParseIt(); if (value == keywordIif) return ParseIif(); if (value == keywordNew) return ParseNew(); NextToken(); return (Expression) value; } if (symbols.TryGetValue(token.text, out value) || externals != null && externals.TryGetValue(token.text, out value)) { Expression expr = value as Expression; if (expr == null) expr = Expression.Constant(value); else { LambdaExpression lambda = expr as LambdaExpression; if (lambda != null) return ParseLambdaInvocation(lambda); } NextToken(); return expr; } if (it != null) return ParseMemberAccess(null, it); throw ParseError(Res.UnknownIdentifier, token.text); } private Expression ParseIif() { int errorPos = token.pos; NextToken(); Expression[] args = ParseArgumentList(); if (args.Length != 3) throw ParseError(errorPos, Res.IifRequiresThreeArgs); return GenerateConditional(args[0], args[1], args[2], errorPos); } private Expression ParseIntegerLiteral() { ValidateToken(TokenId.IntegerLiteral); string text = token.text; if (text[0] != '-') { ulong value; if (!UInt64.TryParse(text, out value)) throw ParseError(Res.InvalidIntegerLiteral, text); NextToken(); if (value <= Int32.MaxValue) return CreateLiteral((int) value, text); if (value <= UInt32.MaxValue) return CreateLiteral((uint) value, text); if (value <= Int64.MaxValue) return CreateLiteral((long) value, text); return CreateLiteral(value, text); } else { long value; if (!Int64.TryParse(text, out value)) throw ParseError(Res.InvalidIntegerLiteral, text); NextToken(); if (value >= Int32.MinValue && value <= Int32.MaxValue) return CreateLiteral((int) value, text); return CreateLiteral(value, text); } } private Expression ParseIt() { if (it == null) throw ParseError(Res.NoItInScope); NextToken(); return it; } private Expression ParseLambdaInvocation(LambdaExpression lambda) { int errorPos = token.pos; NextToken(); Expression[] args = ParseArgumentList(); MethodBase method; if (FindMethod(lambda.Type, "Invoke", false, args, out method) != 1) throw ParseError(errorPos, Res.ArgsIncompatibleWithLambda); return Expression.Invoke(lambda, args); } // &&, and operator private Expression ParseLogicalAnd() { Expression left = ParseComparison(); while (token.id == TokenId.DoubleAmphersand || TokenIdentifierIs("and")) { Token op = token; NextToken(); Expression right = ParseComparison(); CheckAndPromoteOperands(typeof (ILogicalSignatures), op.text, ref left, ref right, op.pos); left = Expression.AndAlso(left, right); } return left; } // ||, or operator private Expression ParseLogicalOr() { Expression left = ParseLogicalAnd(); while (token.id == TokenId.DoubleBar || TokenIdentifierIs("or")) { Token op = token; NextToken(); Expression right = ParseLogicalAnd(); CheckAndPromoteOperands(typeof (ILogicalSignatures), op.text, ref left, ref right, op.pos); left = Expression.OrElse(left, right); } return left; } private Expression ParseMemberAccess(Type type, Expression instance) { if (instance != null) type = instance.Type; int errorPos = token.pos; string id = GetIdentifier(); NextToken(); if (token.id == TokenId.OpenParen) { if (instance != null && type != typeof (string)) { Type enumerableType = FindGenericType(typeof (IEnumerable<>), type); if (enumerableType != null) { Type elementType = enumerableType.GetGenericArguments()[0]; return ParseAggregate(instance, elementType, id, errorPos); } } Expression[] args = ParseArgumentList(); MethodBase mb; switch (FindMethod(type, id, instance == null, args, out mb)) { case 0: throw ParseError(errorPos, Res.NoApplicableMethod, id, GetTypeName(type)); case 1: MethodInfo method = (MethodInfo) mb; if (!IsPredefinedType(method.DeclaringType)) throw ParseError(errorPos, Res.MethodsAreInaccessible, GetTypeName(method.DeclaringType)); if (method.ReturnType == typeof (void)) throw ParseError(errorPos, Res.MethodIsVoid, id, GetTypeName(method.DeclaringType)); return Expression.Call(instance, method, args); default: throw ParseError(errorPos, Res.AmbiguousMethodInvocation, id, GetTypeName(type)); } } MemberInfo member = FindPropertyOrField(type, id, instance == null); if (member == null) throw ParseError(errorPos, Res.UnknownPropertyOrField, id, GetTypeName(type)); return member is PropertyInfo ? Expression.Property(instance, (PropertyInfo) member) : Expression.Field(instance, (FieldInfo) member); } // *, /, %, mod operators private Expression ParseMultiplicative() { Expression left = ParseUnary(); while (token.id == TokenId.Asterisk || token.id == TokenId.Slash || token.id == TokenId.Percent || TokenIdentifierIs("mod")) { Token op = token; NextToken(); Expression right = ParseUnary(); CheckAndPromoteOperands(typeof (IArithmeticSignatures), op.text, ref left, ref right, op.pos); switch (op.id) { case TokenId.Asterisk: left = Expression.Multiply(left, right); break; case TokenId.Slash: left = Expression.Divide(left, right); break; case TokenId.Percent: case TokenId.Identifier: left = Expression.Modulo(left, right); break; } } return left; } private Expression ParseNew() { NextToken(); ValidateToken(TokenId.OpenParen, Res.OpenParenExpected); NextToken(); List<DynamicProperty> properties = new List<DynamicProperty>(); List<Expression> expressions = new List<Expression>(); while (true) { int exprPos = token.pos; Expression expr = ParseExpression(); string propName; if (TokenIdentifierIs("as")) { NextToken(); propName = GetIdentifier(); NextToken(); } else { MemberExpression me = expr as MemberExpression; if (me == null) throw ParseError(exprPos, Res.MissingAsClause); propName = me.Member.Name; } expressions.Add(expr); properties.Add(new DynamicProperty(propName, expr.Type)); if (token.id != TokenId.Comma) break; NextToken(); } ValidateToken(TokenId.CloseParen, Res.CloseParenOrCommaExpected); NextToken(); Type type = DynamicExpression.CreateClass(properties); MemberBinding[] bindings = new MemberBinding[properties.Count]; for (int i = 0; i < bindings.Length; i++) bindings[i] = Expression.Bind(type.GetProperty(properties[i].Name), expressions[i]); return Expression.MemberInit(Expression.New(type), bindings); } private static object ParseNumber(string text, Type type) { switch (Type.GetTypeCode(GetNonNullableType(type))) { case TypeCode.SByte: sbyte sb; if (sbyte.TryParse(text, out sb)) return sb; break; case TypeCode.Byte: byte b; if (byte.TryParse(text, out b)) return b; break; case TypeCode.Int16: short s; if (short.TryParse(text, out s)) return s; break; case TypeCode.UInt16: ushort us; if (ushort.TryParse(text, out us)) return us; break; case TypeCode.Int32: int i; if (int.TryParse(text, out i)) return i; break; case TypeCode.UInt32: uint ui; if (uint.TryParse(text, out ui)) return ui; break; case TypeCode.Int64: long l; if (long.TryParse(text, out l)) return l; break; case TypeCode.UInt64: ulong ul; if (ulong.TryParse(text, out ul)) return ul; break; case TypeCode.Single: float f; if (float.TryParse(text, out f)) return f; break; case TypeCode.Double: double d; if (double.TryParse(text, out d)) return d; break; case TypeCode.Decimal: decimal e; if (decimal.TryParse(text, out e)) return e; break; } return null; } #pragma warning disable 0219 /// <summary> /// Access Modifier adjusted to public specifically for the InfoPath solution as it is now referenced outside the /// Dynamic.cs file /// </summary> /// <returns></returns> public IEnumerable<DynamicOrdering> ParseOrdering() { List<DynamicOrdering> orderings = new List<DynamicOrdering>(); while (true) { Expression expr = ParseExpression(); bool ascending = true; if (TokenIdentifierIs("asc") || TokenIdentifierIs("ascending")) NextToken(); else if (TokenIdentifierIs("desc") || TokenIdentifierIs("descending")) { NextToken(); ascending = false; } orderings.Add(new DynamicOrdering {Selector = expr, Ascending = ascending}); if (token.id != TokenId.Comma) break; NextToken(); } ValidateToken(TokenId.End, Res.SyntaxError); return orderings; } #pragma warning restore 0219 private Expression ParseParenExpression() { ValidateToken(TokenId.OpenParen, Res.OpenParenExpected); NextToken(); Expression e = ParseExpression(); ValidateToken(TokenId.CloseParen, Res.CloseParenOrOperatorExpected); NextToken(); return e; } private Expression ParsePrimary() { Expression expr = ParsePrimaryStart(); while (true) if (token.id == TokenId.Dot) { NextToken(); expr = ParseMemberAccess(null, expr); } else if (token.id == TokenId.OpenBracket) expr = ParseElementAccess(expr); else break; return expr; } private Expression ParsePrimaryStart() { switch (token.id) { case TokenId.Identifier: return ParseIdentifier(); case TokenId.StringLiteral: return ParseStringLiteral(); case TokenId.IntegerLiteral: return ParseIntegerLiteral(); case TokenId.RealLiteral: return ParseRealLiteral(); case TokenId.OpenParen: return ParseParenExpression(); default: throw ParseError(Res.ExpressionExpected); } } private Expression ParseRealLiteral() { ValidateToken(TokenId.RealLiteral); string text = token.text; object value = null; char last = text[text.Length - 1]; if (last == 'F' || last == 'f') { float f; if (Single.TryParse(text.Substring(0, text.Length - 1), out f)) value = f; } else { double d; if (Double.TryParse(text, out d)) value = d; } if (value == null) throw ParseError(Res.InvalidRealLiteral, text); NextToken(); return CreateLiteral(value, text); } private Expression ParseStringLiteral() { ValidateToken(TokenId.StringLiteral); char quote = token.text[0]; string s = token.text.Substring(1, token.text.Length - 2); int start = 0; while (true) { int i = s.IndexOf(quote, start); if (i < 0) break; s = s.Remove(i, 1); start = i + 1; } if (quote == '\'') { if (s.Length != 1) throw ParseError(Res.InvalidCharacterLiteral); NextToken(); return CreateLiteral(s[0], s); } NextToken(); return CreateLiteral(s, s); } private Expression ParseTypeAccess(Type type) { int errorPos = token.pos; NextToken(); if (token.id == TokenId.Question) { if (!type.IsValueType || IsNullableType(type)) throw ParseError(errorPos, Res.TypeHasNoNullableForm, GetTypeName(type)); type = typeof (Nullable<>).MakeGenericType(type); NextToken(); } if (token.id == TokenId.OpenParen) { Expression[] args = ParseArgumentList(); MethodBase method; switch (FindBestMethod(type.GetConstructors(), args, out method)) { case 0: if (args.Length == 1) return GenerateConversion(args[0], type, errorPos); throw ParseError(errorPos, Res.NoMatchingConstructor, GetTypeName(type)); case 1: return Expression.New((ConstructorInfo) method, args); default: throw ParseError(errorPos, Res.AmbiguousConstructorInvocation, GetTypeName(type)); } } ValidateToken(TokenId.Dot, Res.DotOrOpenParenExpected); NextToken(); return ParseMemberAccess(type, null); } // -, !, not unary operators private Expression ParseUnary() { if (token.id == TokenId.Minus || token.id == TokenId.Exclamation || TokenIdentifierIs("not")) { Token op = token; NextToken(); if (op.id == TokenId.Minus && (token.id == TokenId.IntegerLiteral || token.id == TokenId.RealLiteral)) { token.text = "-" + token.text; token.pos = op.pos; return ParsePrimary(); } Expression expr = ParseUnary(); if (op.id == TokenId.Minus) { CheckAndPromoteOperand(typeof (INegationSignatures), op.text, ref expr, op.pos); expr = Expression.Negate(expr); } else { CheckAndPromoteOperand(typeof (INotSignatures), op.text, ref expr, op.pos); expr = Expression.Not(expr); } return expr; } return ParsePrimary(); } private void ProcessParameters(ParameterExpression[] parameters) { foreach (ParameterExpression pe in parameters) if (!String.IsNullOrEmpty(pe.Name)) AddSymbol(pe.Name, pe); if (parameters.Length == 1 && String.IsNullOrEmpty(parameters[0].Name)) it = parameters[0]; } private void ProcessValues(object[] values) { for (int i = 0; i < values.Length; i++) { object value = values[i]; if (i == values.Length - 1 && value is IDictionary<string, object>) externals = (IDictionary<string, object>) value; else AddSymbol("@" + i.ToString(CultureInfo.InvariantCulture), value); } } private Expression PromoteExpression(Expression expr, Type type, bool exact) { if (expr.Type == type) return expr; if (expr is ConstantExpression) { ConstantExpression ce = (ConstantExpression) expr; if (ce == nullLiteral) { if (!type.IsValueType || IsNullableType(type)) return Expression.Constant(null, type); } else { string text; if (literals.TryGetValue(ce, out text)) { Type target = GetNonNullableType(type); Object value = null; switch (Type.GetTypeCode(ce.Type)) { case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: value = ParseNumber(text, target); break; case TypeCode.Double: if (target == typeof (decimal)) value = ParseNumber(text, target); break; case TypeCode.String: value = ParseEnum(text, target); break; } if (value != null) return Expression.Constant(value, type); } } } if (IsCompatibleWith(expr.Type, type)) { if (type.IsValueType || exact) return Expression.Convert(expr, type); return expr; } return null; } private static IEnumerable<Type> SelfAndBaseClasses(Type type) { while (type != null) { yield return type; type = type.BaseType; } } private static IEnumerable<Type> SelfAndBaseTypes(Type type) { if (type.IsInterface) { List<Type> types = new List<Type>(); AddInterface(types, type); return types; } return SelfAndBaseClasses(type); } private void SetTextPos(int pos) { textPos = pos; ch = textPos < textLen ? text[textPos] : '\0'; } private bool TokenIdentifierIs(string id) { return token.id == TokenId.Identifier && String.Equals(id, token.text, StringComparison.OrdinalIgnoreCase); } private void ValidateDigit() { if (!Char.IsDigit(ch)) throw ParseError(textPos, Res.DigitExpected); } private void ValidateToken(TokenId t, string errorMessage) { if (token.id != t) throw ParseError(errorMessage); } private void ValidateToken(TokenId t) { if (token.id != t) throw ParseError(Res.SyntaxError); } [Browsable(false)] private interface IAddSignatures : IArithmeticSignatures { void F(DateTime x, TimeSpan y); void F(TimeSpan x, TimeSpan y); void F(DateTime? x, TimeSpan? y); void F(TimeSpan? x, TimeSpan? y); } [Browsable(false)] private interface IArithmeticSignatures { void F(int x, int y); void F(uint x, uint y); void F(long x, long y); void F(ulong x, ulong y); void F(float x, float y); void F(double x, double y); void F(decimal x, decimal y); void F(int? x, int? y); void F(uint? x, uint? y); void F(long? x, long? y); void F(ulong? x, ulong? y); void F(float? x, float? y); void F(double? x, double? y); void F(decimal? x, decimal? y); } [Browsable(false)] private interface IEnumerableSignatures { void All(bool predicate); void Any(); void Any(bool predicate); void Average(int selector); void Average(int? selector); void Average(long selector); void Average(long? selector); void Average(float selector); void Average(float? selector); void Average(double selector); void Average(double? selector); void Average(decimal selector); void Average(decimal? selector); void Count(); void Count(bool predicate); void Max(object selector); void Min(object selector); void Sum(int selector); void Sum(int? selector); void Sum(long selector); void Sum(long? selector); void Sum(float selector); void Sum(float? selector); void Sum(double selector); void Sum(double? selector); void Sum(decimal selector); void Sum(decimal? selector); void Where(bool predicate); } [Browsable(false)] private interface IEqualitySignatures : IRelationalSignatures { void F(bool x, bool y); void F(bool? x, bool? y); void F(Guid x, Guid y); void F(Guid? x, Guid? y); } [Browsable(false)] private interface ILogicalSignatures { void F(bool x, bool y); void F(bool? x, bool? y); } [Browsable(false)] private interface INegationSignatures { void F(int x); void F(long x); void F(float x); void F(double x); void F(decimal x); void F(int? x); void F(long? x); void F(float? x); void F(double? x); void F(decimal? x); } [Browsable(false)] private interface INotSignatures { void F(bool x); void F(bool? x); } [Browsable(false)] private interface IRelationalSignatures : IArithmeticSignatures { void F(string x, string y); void F(char x, char y); void F(DateTime x, DateTime y); void F(TimeSpan x, TimeSpan y); void F(char? x, char? y); void F(DateTime? x, DateTime? y); void F(TimeSpan? x, TimeSpan? y); } [Browsable(false)] private interface ISubtractSignatures : IAddSignatures { void F(DateTime x, DateTime y); void F(DateTime? x, DateTime? y); } [Browsable(false)] private class MethodData { public Expression[] Args; public MethodBase MethodBase; public ParameterInfo[] Parameters; } [Browsable(false)] private struct Token { public TokenId id; public int pos; public string text; } [Browsable(false)] private enum TokenId { Unknown, End, Identifier, StringLiteral, IntegerLiteral, RealLiteral, Exclamation, Percent, Amphersand, OpenParen, CloseParen, Asterisk, Plus, Comma, Minus, Dot, Slash, Colon, LessThan, Equal, GreaterThan, Question, OpenBracket, CloseBracket, Bar, ExclamationEqual, DoubleAmphersand, LessThanEqual, LessGreater, DoubleEqual, GreaterThanEqual, DoubleBar } } [Browsable(false)] internal static class Res { public const string DuplicateIdentifier = "The identifier '{0}' was defined more than once"; public const string ExpressionTypeMismatch = "Expression of type '{0}' expected"; public const string ExpressionExpected = "Expression expected"; public const string InvalidCharacterLiteral = "Character literal must contain exactly one character"; public const string InvalidIntegerLiteral = "Invalid integer literal '{0}'"; public const string InvalidRealLiteral = "Invalid real literal '{0}'"; public const string UnknownIdentifier = "Unknown identifier '{0}'"; public const string NoItInScope = "No 'it' is in scope"; public const string IifRequiresThreeArgs = "The 'iif' function requires three arguments"; public const string FirstExprMustBeBool = "The first expression must be of type 'Boolean'"; public const string BothTypesConvertToOther = "Both of the types '{0}' and '{1}' convert to the other"; public const string NeitherTypeConvertsToOther = "Neither of the types '{0}' and '{1}' converts to the other"; public const string MissingAsClause = "Expression is missing an 'as' clause"; public const string ArgsIncompatibleWithLambda = "Argument list incompatible with lambda expression"; public const string TypeHasNoNullableForm = "Type '{0}' has no nullable form"; public const string NoMatchingConstructor = "No matching constructor in type '{0}'"; public const string AmbiguousConstructorInvocation = "Ambiguous invocation of '{0}' constructor"; public const string CannotConvertValue = "A value of type '{0}' cannot be converted to type '{1}'"; public const string NoApplicableMethod = "No applicable method '{0}' exists in type '{1}'"; public const string MethodsAreInaccessible = "Methods on type '{0}' are not accessible"; public const string MethodIsVoid = "Method '{0}' in type '{1}' does not return a value"; public const string AmbiguousMethodInvocation = "Ambiguous invocation of method '{0}' in type '{1}'"; public const string UnknownPropertyOrField = "No property or field '{0}' exists in type '{1}'"; public const string NoApplicableAggregate = "No applicable aggregate method '{0}' exists"; public const string CannotIndexMultiDimArray = "Indexing of multi-dimensional arrays is not supported"; public const string InvalidIndex = "Array index must be an integer expression"; public const string NoApplicableIndexer = "No applicable indexer exists in type '{0}'"; public const string AmbiguousIndexerInvocation = "Ambiguous invocation of indexer in type '{0}'"; public const string IncompatibleOperand = "Operator '{0}' incompatible with operand type '{1}'"; public const string IncompatibleOperands = "Operator '{0}' incompatible with operand types '{1}' and '{2}'"; public const string UnterminatedStringLiteral = "Unterminated string literal"; public const string InvalidCharacter = "Syntax error '{0}'"; public const string DigitExpected = "Digit expected"; public const string SyntaxError = "Syntax error"; public const string TokenExpected = "{0} expected"; public const string ParseExceptionFormat = "{0} (at index {1})"; public const string ColonExpected = "':' expected"; public const string OpenParenExpected = "'(' expected"; public const string CloseParenOrOperatorExpected = "')' or operator expected"; public const string CloseParenOrCommaExpected = "')' or ',' expected"; public const string DotOrOpenParenExpected = "'.' or '(' expected"; public const string OpenBracketExpected = "'[' expected"; public const string CloseBracketOrCommaExpected = "']' or ',' expected"; public const string IdentifierExpected = "Identifier expected"; } }
37.008108
144
0.457512
[ "Apache-2.0" ]
superbee66/dcForm
dcForm/Util/Dynamic.cs
95,854
C#
using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.UI; public class SelectedUnitPanel : MonoBehaviour { private TextMeshProUGUI infoText, unitNameText, actionText; private Unit unit; public TextMeshProUGUI healthText; public Slider healthSlider; // Start is called before the first frame update void Awake() { unitNameText = GameObject.Find("UnitNameText").GetComponent<TextMeshProUGUI>(); infoText = GameObject.Find("InfoText").GetComponent<TextMeshProUGUI>(); actionText = GameObject.Find("ActionText").GetComponent<TextMeshProUGUI>(); } // Update is called once per frame void Update() { } public void RefreshPanel(GameObject selectedUnit) { unit = selectedUnit.GetComponent<Unit>(); unitNameText.text = unit.gameObject.name; healthSlider.value = unit.CurrentHealth / unit.Health; healthText.text = unit.CurrentHealth + "/" + unit.Health; SetInfoText(); } public void SetInfoText() { actionText.text = unit.Action.ToString(); if (unit.Action == Globals.ActionType.Move || unit.Action == Globals.ActionType.None) { infoText.text = "Chose a tile to move in the next turn. You can move " + unit.MoveRange + " tile. Action Phase: "+unit.MovePhase+""; } else if (unit.Action == Globals.ActionType.NormalAttack) { infoText.text = "Chose a tile to attack in the next turn. Range: "+unit.NormalAttcakRange+" Damage: "+unit.NormalAttcakDamage+ "Action Phase: "+ unit.NormalAttcakPhase + " Can Break Block: "+ unit.canBreakBlock; } else if (unit.Action == Globals.ActionType.QuickAttack) { infoText.text = "Chose a tile to attack in the next turn. Range: " + unit.QuickAttackRange + " Damage: " + unit.QuickAttackDamage + "Action Phase: " + unit.QuickAttackPhase; } } public void SetMove() { unit.TargetTile = null; unit.Action = Globals.ActionType.Move; unit.MarkAction(); SetInfoText(); } public void SetNormalAttack() { unit.TargetTile = null; unit.Action = Globals.ActionType.NormalAttack; unit.MarkAction(); SetInfoText(); } public void SetQuickAttack() { unit.TargetTile = null; unit.Action = Globals.ActionType.QuickAttack; unit.MarkAction(); SetInfoText(); } }
30.722892
223
0.633725
[ "CC0-1.0" ]
brainoverflow98/bandit-wars
src/Assets/Scripts/SelectedUnitPanel.cs
2,552
C#
using System; using System.Collections.Generic; using System.Text; namespace PizzaCalories { public static class DoughValidator { private static Dictionary<string, double> flourType = new Dictionary<string, double>(); private static Dictionary<string, double> bakingTech = new Dictionary<string, double>(); public static bool IsValidFlourType(string type) { Initialize(); if (!flourType.ContainsKey(type.ToLower())) { return false; } return true; } public static bool IsValidBakingTech(string type) { Initialize(); if (!bakingTech.ContainsKey(type.ToLower())) { return false; } return true; } private static void Initialize() { if (flourType.Count != 0 && bakingTech.Count != 0) { return; } //Initialize requirements about flour`s type.Where (d => double.Calories) flourType.Add("white", 1.5); flourType.Add("wholegrain", 1.0); //Initialize requirements about baking techniques.Where (the same above ) bakingTech.Add("crispy", 0.9); bakingTech.Add("chewy", 1.1); bakingTech.Add("homemade", 1); } public static double GetFlourModifier(string type) => flourType[type.ToLower()]; public static double GetTechModifier(string type) => bakingTech[type.ToLower()]; } }
29.849057
96
0.554994
[ "MIT" ]
tonkatawe/SoftUni-Advanced
OOP/Encapsulation - Exercise/PizzaCalories/DoughValidator.cs
1,584
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Controls; namespace Project.Validators { class AlphabetValidator: ValidationRule { public override ValidationResult Validate(object value, CultureInfo cultureInfo) { string input = value.ToString().Trim(); if (!Regex.IsMatch(input, (@"^[a-zA-Z ]+$"))) { return new ValidationResult(false, "Only Alphabets allowed!!"); } return ValidationResult.ValidResult; } } }
27.153846
89
0.630312
[ "MIT" ]
Harikodapaka/Pizza-ordering-system-WAP
Project/Validators/AlphabetValidator.cs
708
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests { [TestClass] public class ETests { const int TimeLimit = 2000; const double RelativeError = 1e-9; [TestMethod, Timeout(TimeLimit)] public void Test1() { const string input = @"3 3 ... .#. ..# #.# ### ... "; const string output = @"Yes "; Tester.InOutTest(Tasks.E.Solve, input, output); } [TestMethod, Timeout(TimeLimit)] public void Test2() { const string input = @"3 3 ... #.. #.# .#. .## ##. "; const string output = @"No "; Tester.InOutTest(Tasks.E.Solve, input, output); } [TestMethod, Timeout(TimeLimit)] public void Test3() { const string input = @"2 5 ..... ..#.. ..##. .###. "; const string output = @"Yes "; Tester.InOutTest(Tasks.E.Solve, input, output); } } }
16.896552
59
0.490816
[ "CC0-1.0" ]
AconCavy/AtCoder.Tasks.CS
PAST/PAST202012-OPEN/Tests/ETests.cs
980
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CalculadoraDoisPontoZero; namespace UsandoBibliotecaCalcExterna { class Program { static int valor1 = 0; static int valor2 = 0; static void Main(string[] args) { Calculadora cal = new Calculadora(); mostraMenu(); var escolha = Convert.ToInt32(Console.ReadLine()); int caseSwitch = escolha; switch (caseSwitch) { case 1: pede2numeros(); Console.WriteLine(cal.CalculadoraSomar(valor1, valor2)); Console.ReadLine(); break; case 2: pede2numeros(); Console.WriteLine(cal.CalculadoraDiminuir(valor1, valor2)); Console.ReadLine(); break; case 3: pede2numeros(); Console.WriteLine(cal.CalculadoraDuvidir(valor1, valor2)); Console.ReadLine(); break; case 4: pede2numeros(); Console.WriteLine(cal.CalculadoraMultiplicar(valor1, valor2)); Console.ReadLine(); break; case 5: Console.WriteLine("Digite a area do Circulo"); var area = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(cal.CalcularCirculo(area)); Console.ReadLine(); break; case 6: Console.WriteLine("Digite a base do retangulo (CM)"); var Base = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Digite a altura do retangulo (cm)"); var Altura = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(cal.CalcularRetangulo(Base, Altura)); Console.ReadLine(); break; case 7: Console.WriteLine("Digite a base do triangulo (CM)"); var BaseT = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Digite a altura do triangulo (cm)"); var AlturaT = Convert.ToInt32(Console.ReadLine()); Console.WriteLine(cal.CalcularRetangulo(BaseT, AlturaT)); Console.ReadLine(); break; } } public static void pede2numeros() { Console.WriteLine("Digite primeiro numero"); valor1 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Digite segundo numero"); valor2 = Convert.ToInt32(Console.ReadLine()); } public static void mostraMenu() { Console.WriteLine("Digite:|| 1 - Soma || 2-Subtrai || 3-Dividir|| 4-Multiplicar"); Console.WriteLine("Digite:|| 5 - Area Circulo || 6-Retangulo || 7-Triangulo ||"); } } }
32.040404
94
0.499685
[ "MIT" ]
Daneugoncalves/GitC
SQL, Listas,Primeiros Forms/UsandoBibliotecaCalcExterna/Program.cs
3,174
C#
using UnityEngine; namespace Mirror.Experimental { [DisallowMultipleComponent] [AddComponentMenu("Network/Experimental/NetworkTransformExperimental")] [HelpURL("https://mirror-networking.gitbook.io/docs/components/network-transform")] public class NetworkTransform : NetworkTransformBase { protected override Transform targetTransform => transform; } }
29.769231
87
0.762274
[ "MIT" ]
10allday/OpenMMO
Plugins/3rdParty/Mirror/Components/Experimental/NetworkTransform.cs
389
C#
namespace Craftsman.Builders { using Craftsman.Builders.Dtos; using Craftsman.Builders.Projects; using Craftsman.Helpers; using Craftsman.Models; using System; using System.IO; using System.IO.Abstractions; using AuthServer; using static Helpers.ConsoleWriter; public class SolutionBuilder { public static void BuildSolution(string solutionDirectory, string projectName, IFileSystem fileSystem) { try { fileSystem.Directory.CreateDirectory(solutionDirectory); Utilities.ExecuteProcess("dotnet", @$"new sln -n {projectName}", solutionDirectory); BuildSharedKernelProject(solutionDirectory, fileSystem); } catch (Exception e) { WriteError(e.Message); throw; // custom error that you must be using the .net 6 sdk? } } public static void AddProjects(string solutionDirectory, string srcDirectory, string testDirectory, string dbProvider, string dbName, string projectBaseName, bool addJwtAuth, IFileSystem fileSystem) { // add webapi first so it is default project BuildWebApiProject(solutionDirectory, srcDirectory, projectBaseName, addJwtAuth, dbProvider, dbName, fileSystem); BuildIntegrationTestProject(solutionDirectory, testDirectory, projectBaseName, addJwtAuth); BuildFunctionalTestProject(solutionDirectory, testDirectory, projectBaseName, addJwtAuth); BuildSharedTestProject(solutionDirectory, testDirectory, projectBaseName); BuildUnitTestProject(solutionDirectory, testDirectory, projectBaseName); } private static void BuildWebApiProject(string solutionDirectory, string srcDirectory, string projectBaseName, bool useJwtAuth, string dbProvider, string dbName, IFileSystem fileSystem) { var solutionFolder = srcDirectory.GetSolutionFolder(solutionDirectory); var webApiProjectClassPath = ClassPathHelper.WebApiProjectClassPath(srcDirectory, projectBaseName); WebApiCsProjBuilder.CreateWebApiCsProj(srcDirectory, projectBaseName, dbProvider); Utilities.ExecuteProcess("dotnet", $@"sln add ""{webApiProjectClassPath.FullClassPath}"" --solution-folder {solutionFolder}", solutionDirectory); // base folders Directory.CreateDirectory(ClassPathHelper.ControllerClassPath(srcDirectory, "", projectBaseName, "v1").ClassDirectory); Directory.CreateDirectory(ClassPathHelper.WebApiServiceExtensionsClassPath(srcDirectory, "", projectBaseName).ClassDirectory); Directory.CreateDirectory(ClassPathHelper.WebApiMiddlewareClassPath(srcDirectory, "", projectBaseName).ClassDirectory); // additional from what was other projects Directory.CreateDirectory(ClassPathHelper.DtoClassPath(solutionDirectory, "", "", projectBaseName).ClassDirectory); Directory.CreateDirectory(ClassPathHelper.ExceptionsClassPath(srcDirectory, "").ClassDirectory); Directory.CreateDirectory(ClassPathHelper.WrappersClassPath(srcDirectory, "", projectBaseName).ClassDirectory); Directory.CreateDirectory(ClassPathHelper.SharedDtoClassPath(solutionDirectory, "").ClassDirectory); Directory.CreateDirectory(ClassPathHelper.DbContextClassPath(srcDirectory, "", projectBaseName).ClassDirectory); Directory.CreateDirectory(ClassPathHelper.DummySeederClassPath(srcDirectory, "", projectBaseName).ClassDirectory); WebApiServiceExtensionsBuilder.CreateApiVersioningServiceExtension(srcDirectory, projectBaseName, fileSystem); WebApiServiceExtensionsBuilder.CreateCorsServiceExtension(srcDirectory, projectBaseName, fileSystem); WebApiServiceExtensionsBuilder.CreateWebApiServiceExtension(srcDirectory, projectBaseName, fileSystem); ErrorHandlerFilterAttributeBuilder.CreateErrorHandlerFilterAttribute(srcDirectory, projectBaseName, fileSystem); AppSettingsBuilder.CreateWebApiAppSettings(srcDirectory, dbName, projectBaseName); WebApiLaunchSettingsBuilder.CreateLaunchSettings(srcDirectory, projectBaseName, fileSystem); ProgramBuilder.CreateWebApiProgram(srcDirectory, projectBaseName, fileSystem); StartupBuilder.CreateWebApiStartup(srcDirectory, useJwtAuth, projectBaseName, fileSystem); LocalConfigBuilder.CreateLocalConfig(srcDirectory, projectBaseName, fileSystem); LoggingConfigurationBuilder.CreateConfigFile(srcDirectory, projectBaseName, fileSystem); InfrastructureServiceRegistrationBuilder.CreateInfrastructureServiceExtension(srcDirectory, projectBaseName, fileSystem); BasePaginationParametersBuilder.CreateBasePaginationParameters(solutionDirectory, projectBaseName, fileSystem); PagedListBuilder.CreatePagedList(srcDirectory, projectBaseName, fileSystem); CoreExceptionsBuilder.CreateExceptions(solutionDirectory, projectBaseName, fileSystem); Utilities.AddProjectReference(webApiProjectClassPath, @"..\..\..\SharedKernel\SharedKernel.csproj"); } private static void BuildIntegrationTestProject(string solutionDirectory, string testDirectory, string projectBaseName, bool addJwtAuth) { var solutionFolder = testDirectory.GetSolutionFolder(solutionDirectory); var testProjectClassPath = ClassPathHelper.IntegrationTestProjectRootClassPath(testDirectory, "", projectBaseName); IntegrationTestsCsProjBuilder.CreateTestsCsProj(testDirectory, projectBaseName, addJwtAuth); Utilities.ExecuteProcess("dotnet", $@"sln add ""{testProjectClassPath.FullClassPath}"" --solution-folder {solutionFolder}", solutionDirectory); } private static void BuildFunctionalTestProject(string solutionDirectory, string testDirectory, string projectBaseName, bool addJwtAuth) { var solutionFolder = testDirectory.GetSolutionFolder(solutionDirectory); var testProjectClassPath = ClassPathHelper.FunctionalTestProjectRootClassPath(testDirectory, "", projectBaseName); FunctionalTestsCsProjBuilder.CreateTestsCsProj(testDirectory, projectBaseName, addJwtAuth); Utilities.ExecuteProcess("dotnet", $@"sln add ""{testProjectClassPath.FullClassPath}"" --solution-folder {solutionFolder}", solutionDirectory); } private static void BuildSharedTestProject(string solutionDirectory, string testDirectory, string projectBaseName) { var solutionFolder = testDirectory.GetSolutionFolder(solutionDirectory); var testProjectClassPath = ClassPathHelper.SharedTestProjectRootClassPath(testDirectory, "", projectBaseName); SharedTestsCsProjBuilder.CreateTestsCsProj(testDirectory, projectBaseName); Utilities.ExecuteProcess("dotnet", $@"sln add ""{testProjectClassPath.FullClassPath}"" --solution-folder {solutionFolder}", solutionDirectory); } private static void BuildUnitTestProject(string solutionDirectory, string testDirectory, string projectBaseName) { var solutionFolder = testDirectory.GetSolutionFolder(solutionDirectory); var testProjectClassPath = ClassPathHelper.UnitTestProjectRootClassPath(testDirectory, "", projectBaseName); UnitTestsCsProjBuilder.CreateTestsCsProj(testDirectory, projectBaseName); Utilities.ExecuteProcess("dotnet", $@"sln add ""{testProjectClassPath.FullClassPath}"" --solution-folder {solutionFolder}", solutionDirectory); } public static void BuildSharedKernelProject(string solutionDirectory, IFileSystem fileSystem) { var projectExists = File.Exists(Path.Combine(solutionDirectory, "SharedKernel", "SharedKernel.csproj")); if (projectExists) return; var projectClassPath = ClassPathHelper.SharedKernelProjectRootClassPath(solutionDirectory, ""); SharedKernelCsProjBuilder.CreateMessagesCsProj(solutionDirectory, fileSystem); Utilities.ExecuteProcess("dotnet", $@"sln add ""{projectClassPath.FullClassPath}""", solutionDirectory); } public static void BuildAuthServerProject(string solutionDirectory, string authServerProjectName, IFileSystem fileSystem) { var projectExists = File.Exists(Path.Combine(solutionDirectory, authServerProjectName, $"{authServerProjectName}.csproj")); if (projectExists) return; var projectClassPath = ClassPathHelper.AuthServerProjectClassPath(solutionDirectory, authServerProjectName); AuthServerProjBuilder.CreateProject(solutionDirectory, authServerProjectName, fileSystem); Utilities.ExecuteProcess("dotnet", $@"sln add ""{projectClassPath.FullClassPath}""", solutionDirectory); } public static void BuildBffProject(string solutionDirectory, string projectName, int? proxyPort, IFileSystem fileSystem) { var projectExists = File.Exists(Path.Combine(solutionDirectory, projectName, $"{projectName}.csproj")); if (projectExists) return; var projectClassPath = ClassPathHelper.BffProjectClassPath(solutionDirectory, projectName); BffProjBuilder.CreateProject(solutionDirectory, projectName, proxyPort, fileSystem); Utilities.ExecuteProcess("dotnet", $@"sln add ""{projectClassPath.FullClassPath}""", solutionDirectory); } } public static class Extensions { public static string GetSolutionFolder(this string projectDir, string solutionDir) { var folder = projectDir.Replace(solutionDir, ""); return folder.Length > 0 ? folder.Substring(1) : folder; } } }
63.063291
206
0.731232
[ "MIT" ]
lukerogers/craftsman
Craftsman/Builders/SolutionBuilder.cs
9,966
C#
// // Swiss QR Bill Generator for .NET // Copyright (c) 2018 Manuel Bleichenbacher // Licensed under MIT License // https://opensource.org/licenses/MIT // using Codecrete.SwissQRBill.Generator; using Codecrete.SwissQRBill.Generator.Canvas; using System; using System.Reflection; using Xunit; namespace Codecrete.SwissQRBill.GeneratorTest { public class CleanupTest { [Fact] public void ClosePngFreesResources() { Type type = typeof(PNGCanvas); FieldInfo bitmapField = type.GetField("_bitmap", BindingFlags.NonPublic | BindingFlags.Instance); Assert.NotNull(bitmapField); PNGCanvas pngCanvas; using (PNGCanvas canvas = new PNGCanvas(QRBill.QrBillWidth, QRBill.QrBillHeight, 300, "Arial")) { pngCanvas = canvas; Assert.NotNull(bitmapField.GetValue(pngCanvas)); } Assert.Null(bitmapField.GetValue(pngCanvas)); } } }
27.5
109
0.648485
[ "MIT" ]
0xced/SwissQRBill.NET
GeneratorTest/CleanupTest.cs
992
C#
using System; namespace Chess { public class King : Piece { public King(){} public King(Space space, string color) : base (space, color){} public override bool CheckAll(int x, int y) { return true; } } }
17.846154
66
0.62069
[ "MIT" ]
TSiu88/chess
QueenAttack/King.cs
232
C#
namespace Steamworks { public enum EUGCMatchingUGCType { k_EUGCMatchingUGCType_Items = 0, k_EUGCMatchingUGCType_Items_Mtx = 1, k_EUGCMatchingUGCType_Items_ReadyToUse = 2, k_EUGCMatchingUGCType_Collections = 3, k_EUGCMatchingUGCType_Artwork = 4, k_EUGCMatchingUGCType_Videos = 5, k_EUGCMatchingUGCType_Screenshots = 6, k_EUGCMatchingUGCType_AllGuides = 7, k_EUGCMatchingUGCType_WebGuides = 8, k_EUGCMatchingUGCType_IntegratedGuides = 9, k_EUGCMatchingUGCType_UsableInGame = 10, k_EUGCMatchingUGCType_ControllerBindings = 11, k_EUGCMatchingUGCType_GameManagedItems = 12, k_EUGCMatchingUGCType_All = -1 } }
30.238095
48
0.820472
[ "MIT" ]
undancer/oni-data
Managed/firstpass/Steamworks/EUGCMatchingUGCType.cs
635
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.Azure.Commands.Resources { using Microsoft.Azure.Commands.Resources.Models; using Microsoft.Azure.Management.Resources.Models; using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using ProjectResources = Microsoft.Azure.Commands.Resources.Properties.Resources; /// <summary> /// Get an existing resource. /// </summary> [Cmdlet(VerbsCommon.Get, "AzureRmProviderOperation"), OutputType(typeof(PSResourceProviderOperation))] public class GetAzureProviderOperationCommand : ResourcesBaseCmdlet { private const string WildCardCharacter = "*"; private static readonly char Separator = '/'; /// <summary> /// Gets or sets the provider namespace /// </summary> [Parameter(Position = 0, Mandatory = true, ValueFromPipelineByPropertyName = false, ValueFromPipeline = true, HelpMessage = "The action string.")] [ValidateNotNullOrEmpty] public string OperationSearchString { get; set; } /// <summary> /// Executes the cmdlet /// </summary> public override void ExecuteCmdlet() { // remove leading and trailing whitespaces this.OperationSearchString = this.OperationSearchString.Trim(); ValidateActionSearchString(this.OperationSearchString); List<PSResourceProviderOperation> operationsToDisplay; if (this.OperationSearchString.Contains(WildCardCharacter)) { operationsToDisplay = this.ProcessProviderOperationsWithWildCard(OperationSearchString); } else { operationsToDisplay = this.ProcessProviderOperationsWithoutWildCard(OperationSearchString); } this.WriteObject(operationsToDisplay, enumerateCollection: true); } private static void ValidateActionSearchString(string actionSearchString) { if (actionSearchString.Contains("?")) { throw new ArgumentException(ProjectResources.ProviderOperationUnsupportedWildcard); } string[] parts = actionSearchString.Split(Separator); if (parts.Any(p => p.Contains(WildCardCharacter) && p.Length != 1)) { throw new ArgumentException(ProjectResources.OperationSearchStringInvalidWildcard); } if (parts.Length == 1 && parts[0] != WildCardCharacter) { throw new ArgumentException(string.Format(ProjectResources.OperationSearchStringInvalidProviderName, parts[0])); } } /// <summary> /// Get a list of Provider operations in the case that the Actionstring input contains a wildcard /// </summary> private List<PSResourceProviderOperation> ProcessProviderOperationsWithWildCard(string actionSearchString) { // Filter the list of all operation names to what matches the wildcard WildcardPattern wildcard = new WildcardPattern(actionSearchString, WildcardOptions.IgnoreCase | WildcardOptions.Compiled); List<ProviderOperationsMetadata> providers = new List<ProviderOperationsMetadata>(); string provider = this.OperationSearchString.Split(Separator).First(); if (provider.Equals(WildCardCharacter)) { // 'Get-AzureRmProviderOperation *' or 'Get-AzureRmProviderOperation */virtualmachines/*' // get operations for all providers providers.AddRange(this.ResourcesClient.ListProviderOperationsMetadata()); } else { // 'Get-AzureRmProviderOperation Microsoft.Compute/virtualmachines/*' or 'Get-AzureRmProviderOperation Microsoft.Sql/*' providers.Add(this.ResourcesClient.GetProviderOperationsMetadata(provider)); } return providers.SelectMany(p => GetPSOperationsFromProviderOperationsMetadata(p)).Where(operation => wildcard.IsMatch(operation.Operation)).ToList(); } /// <summary> /// Gets a list of Provider operations in the case that the Actionstring input does not contain a wildcard /// </summary> private List<PSResourceProviderOperation> ProcessProviderOperationsWithoutWildCard(string operationString) { string providerFullName = operationString.Split(Separator).First(); ProviderOperationsMetadata providerOperations = this.ResourcesClient.GetProviderOperationsMetadata(providerFullName); IEnumerable<PSResourceProviderOperation> flattenedProviderOperations = GetAzureProviderOperationCommand.GetPSOperationsFromProviderOperationsMetadata(providerOperations); return flattenedProviderOperations.Where(op => string.Equals(op.Operation, operationString, StringComparison.OrdinalIgnoreCase)).ToList(); } private static IEnumerable<PSResourceProviderOperation> GetPSOperationsFromProviderOperationsMetadata(ProviderOperationsMetadata providerOperationsMetadata) { IEnumerable<PSResourceProviderOperation> operations = providerOperationsMetadata.Operations.Where(op => GetAzureProviderOperationCommand.IsUserOperation(op)) .Select(op => ToPSResourceProviderOperation(op, providerOperationsMetadata.DisplayName)); if (providerOperationsMetadata.ResourceTypes != null) { operations = operations.Concat(providerOperationsMetadata.ResourceTypes.SelectMany(rt => rt.Operations.Where(op => GetAzureProviderOperationCommand.IsUserOperation(op)) .Select(op => ToPSResourceProviderOperation(op, providerOperationsMetadata.DisplayName, rt.DisplayName)))); } return operations; } private static bool IsUserOperation(Operation operation) { return operation.Origin == null || operation.Origin.Contains("user"); } private static PSResourceProviderOperation ToPSResourceProviderOperation(Operation operation, string provider, string resource = null) { PSResourceProviderOperation psOperation = new PSResourceProviderOperation(); psOperation.Operation = operation.Name; psOperation.OperationName = operation.DisplayName; psOperation.Description = operation.Description; psOperation.ProviderNamespace = provider; psOperation.ResourceName = resource ?? string.Empty; return psOperation; } /// <summary> /// Extracts the resource provider's full name - i.e portion of the non-wildcard prefix before the '/' /// Returns null if the nonWildCardPrefix does not contain a '/' /// </summary> private static string GetResourceProviderFullName(string nonWildCardPrefix) { int index = nonWildCardPrefix.IndexOf(Separator.ToString(), 0); return index > 0 ? nonWildCardPrefix.Substring(0, index) : string.Empty; } /// <summary> /// Extracts the portion of the actionstring before the first wildcard character (*) /// </summary> private static string GetNonWildcardPrefix(string actionString) { int index = actionString.IndexOf(WildCardCharacter); return index >= 0 ? actionString.Substring(0, index) : actionString; } } }
49.723529
185
0.653732
[ "MIT" ]
FosterMichelle/azure-powershell
src/ResourceManager/Resources/Commands.Resources/Providers/GetAzureProviderOperationCmdlet.cs
8,286
C#
using System; using Newtonsoft.Json; namespace Edison.ChatService.Models { /// <summary> /// Object that represents the channeldata for command EndConversation /// </summary> [Serializable] public class CommandEndConversation { [JsonProperty(PropertyName = "userId")] public string UserId { get; set; } } }
22.0625
74
0.66289
[ "MIT" ]
Mahesh1998/ProjectEdison
Edison.Web/Edison.Microservices.ChatService/Models/CommandEndConversation.cs
355
C#
using Actio.Common.Events; using Microsoft.Extensions.Logging; using System.Threading.Tasks; namespace Actio.Api.Handlers { public class UserAuthenticatedHandler : IEventHandler<UserAuthenticated> { private readonly ILogger<UserAuthenticatedHandler> _logger; public UserAuthenticatedHandler(ILogger<UserAuthenticatedHandler> logger) { _logger = logger; } public Task HandleAsync(UserAuthenticated @event) { _logger.LogInformation($"User autheniticated: {@event.Email}"); return Task.CompletedTask; } } }
26.608696
81
0.679739
[ "MIT" ]
msadeqsirjani/Actio
src/Actio.Api/Handlers/UserAuthenticatedHandler.cs
614
C#
/* Copyright (c) 2006 - 2008 The Open Toolkit library. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; namespace OpenTK.Mathematics { /// <summary> /// Represents a 2x2 matrix. /// </summary> public struct Matrix2d : IEquatable<Matrix2d> { /// <summary> /// Top row of the matrix. /// </summary> public Vector2d Row0; /// <summary> /// Bottom row of the matrix. /// </summary> public Vector2d Row1; /// <summary> /// The identity matrix. /// </summary> public static readonly Matrix2d Identity = new Matrix2d(Vector2d.UnitX, Vector2d.UnitY); /// <summary> /// The zero matrix. /// </summary> public static readonly Matrix2d Zero = new Matrix2d(Vector2d.Zero, Vector2d.Zero); /// <summary> /// Initializes a new instance of the <see cref="Matrix2d"/> struct. /// </summary> /// <param name="row0">Top row of the matrix.</param> /// <param name="row1">Bottom row of the matrix.</param> public Matrix2d(Vector2d row0, Vector2d row1) { Row0 = row0; Row1 = row1; } /// <summary> /// Initializes a new instance of the <see cref="Matrix2d"/> struct. /// </summary> /// <param name="m00">First item of the first row of the matrix.</param> /// <param name="m01">Second item of the first row of the matrix.</param> /// <param name="m10">First item of the second row of the matrix.</param> /// <param name="m11">Second item of the second row of the matrix.</param> [SuppressMessage("ReSharper", "SA1117", Justification = "For better readability of Matrix struct.")] public Matrix2d ( double m00, double m01, double m10, double m11 ) { Row0 = new Vector2d(m00, m01); Row1 = new Vector2d(m10, m11); } /// <summary> /// Gets the determinant of this matrix. /// </summary> public double Determinant { get { double m11 = Row0.X; double m12 = Row0.Y; double m21 = Row1.X; double m22 = Row1.Y; return (m11 * m22) - (m12 * m21); } } /// <summary> /// Gets or sets the first column of this matrix. /// </summary> public Vector2d Column0 { get => new Vector2d(Row0.X, Row1.X); set { Row0.X = value.X; Row1.X = value.Y; } } /// <summary> /// Gets or sets the second column of this matrix. /// </summary> public Vector2d Column1 { get => new Vector2d(Row0.Y, Row1.Y); set { Row0.Y = value.X; Row1.Y = value.Y; } } /// <summary> /// Gets or sets the value at row 1, column 1 of this instance. /// </summary> public double M11 { get => Row0.X; set => Row0.X = value; } /// <summary> /// Gets or sets the value at row 1, column 2 of this instance. /// </summary> public double M12 { get => Row0.Y; set => Row0.Y = value; } /// <summary> /// Gets or sets the value at row 2, column 1 of this instance. /// </summary> public double M21 { get => Row1.X; set => Row1.X = value; } /// <summary> /// Gets or sets the value at row 2, column 2 of this instance. /// </summary> public double M22 { get => Row1.Y; set => Row1.Y = value; } /// <summary> /// Gets or sets the values along the main diagonal of the matrix. /// </summary> public Vector2d Diagonal { get => new Vector2d(Row0.X, Row1.Y); set { Row0.X = value.X; Row1.Y = value.Y; } } /// <summary> /// Gets the trace of the matrix, the sum of the values along the diagonal. /// </summary> public double Trace => Row0.X + Row1.Y; /// <summary> /// Gets or sets the value at a specified row and column. /// </summary> /// <param name="rowIndex">The index of the row.</param> /// <param name="columnIndex">The index of the column.</param> /// <returns>The element at the given row and column index.</returns> public double this[int rowIndex, int columnIndex] { get { if (rowIndex == 0) { return Row0[columnIndex]; } if (rowIndex == 1) { return Row1[columnIndex]; } throw new IndexOutOfRangeException("You tried to access this matrix at: (" + rowIndex + ", " + columnIndex + ")"); } set { if (rowIndex == 0) { Row0[columnIndex] = value; } else if (rowIndex == 1) { Row1[columnIndex] = value; } else { throw new IndexOutOfRangeException("You tried to set this matrix at: (" + rowIndex + ", " + columnIndex + ")"); } } } /// <summary> /// Converts this instance to it's transpose. /// </summary> public void Transpose() { this = Transpose(this); } /// <summary> /// Converts this instance into its inverse. /// </summary> public void Invert() { this = Invert(this); } /// <summary> /// Builds a rotation matrix. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <param name="result">The resulting Matrix2d instance.</param> public static void CreateRotation(double angle, out Matrix2d result) { var cos = Math.Cos(angle); var sin = Math.Sin(angle); result.Row0.X = cos; result.Row0.Y = sin; result.Row1.X = -sin; result.Row1.Y = cos; } /// <summary> /// Builds a rotation matrix. /// </summary> /// <param name="angle">The counter-clockwise angle in radians.</param> /// <returns>The resulting Matrix2d instance.</returns> [Pure] public static Matrix2d CreateRotation(double angle) { CreateRotation(angle, out Matrix2d result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Single scale factor for the x, y, and z axes.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(double scale, out Matrix2d result) { result.Row0.X = scale; result.Row0.Y = 0; result.Row1.X = 0; result.Row1.Y = scale; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Single scale factor for the x and y axes.</param> /// <returns>A scale matrix.</returns> [Pure] public static Matrix2d CreateScale(double scale) { CreateScale(scale, out Matrix2d result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Scale factors for the x and y axes.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(Vector2d scale, out Matrix2d result) { result.Row0.X = scale.X; result.Row0.Y = 0; result.Row1.X = 0; result.Row1.Y = scale.Y; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="scale">Scale factors for the x and y axes.</param> /// <returns>A scale matrix.</returns> [Pure] public static Matrix2d CreateScale(Vector2d scale) { CreateScale(scale, out Matrix2d result); return result; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="x">Scale factor for the x axis.</param> /// <param name="y">Scale factor for the y axis.</param> /// <param name="result">A scale matrix.</param> public static void CreateScale(double x, double y, out Matrix2d result) { result.Row0.X = x; result.Row0.Y = 0; result.Row1.X = 0; result.Row1.Y = y; } /// <summary> /// Creates a scale matrix. /// </summary> /// <param name="x">Scale factor for the x axis.</param> /// <param name="y">Scale factor for the y axis.</param> /// <returns>A scale matrix.</returns> [Pure] public static Matrix2d CreateScale(double x, double y) { CreateScale(x, y, out Matrix2d result); return result; } /// <summary> /// Multiplies and instance by a scalar. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <param name="result">A new instance that is the result of the multiplication.</param> public static void Mult(in Matrix2d left, double right, out Matrix2d result) { result.Row0.X = left.Row0.X * right; result.Row0.Y = left.Row0.Y * right; result.Row1.X = left.Row1.X * right; result.Row1.Y = left.Row1.Y * right; } /// <summary> /// Multiplies and instance by a scalar. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <returns>A new instance that is the result of the multiplication.</returns> [Pure] public static Matrix2d Mult(Matrix2d left, double right) { Mult(in left, right, out Matrix2d result); return result; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <param name="result">A new instance that is the result of the multiplication.</param> public static void Mult(in Matrix2d left, in Matrix2d right, out Matrix2d result) { double leftM11 = left.Row0.X; double leftM12 = left.Row0.Y; double leftM21 = left.Row1.X; double leftM22 = left.Row1.Y; double rightM11 = right.Row0.X; double rightM12 = right.Row0.Y; double rightM21 = right.Row1.X; double rightM22 = right.Row1.Y; result.Row0.X = (leftM11 * rightM11) + (leftM12 * rightM21); result.Row0.Y = (leftM11 * rightM12) + (leftM12 * rightM22); result.Row1.X = (leftM21 * rightM11) + (leftM22 * rightM21); result.Row1.Y = (leftM21 * rightM12) + (leftM22 * rightM22); } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <returns>A new instance that is the result of the multiplication.</returns> [Pure] public static Matrix2d Mult(Matrix2d left, Matrix2d right) { Mult(in left, in right, out Matrix2d result); return result; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <param name="result">A new instance that is the result of the multiplication.</param> public static void Mult(in Matrix2d left, in Matrix2x3d right, out Matrix2x3d result) { double leftM11 = left.Row0.X; double leftM12 = left.Row0.Y; double leftM21 = left.Row1.X; double leftM22 = left.Row1.Y; double rightM11 = right.Row0.X; double rightM12 = right.Row0.Y; double rightM13 = right.Row0.Z; double rightM21 = right.Row1.X; double rightM22 = right.Row1.Y; double rightM23 = right.Row1.Z; result.Row0.X = (leftM11 * rightM11) + (leftM12 * rightM21); result.Row0.Y = (leftM11 * rightM12) + (leftM12 * rightM22); result.Row0.Z = (leftM11 * rightM13) + (leftM12 * rightM23); result.Row1.X = (leftM21 * rightM11) + (leftM22 * rightM21); result.Row1.Y = (leftM21 * rightM12) + (leftM22 * rightM22); result.Row1.Z = (leftM21 * rightM13) + (leftM22 * rightM23); } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <returns>A new instance that is the result of the multiplication.</returns> [Pure] public static Matrix2x3d Mult(Matrix2d left, Matrix2x3d right) { Mult(in left, in right, out Matrix2x3d result); return result; } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <param name="result">A new instance that is the result of the multiplication.</param> public static void Mult(in Matrix2d left, in Matrix2x4d right, out Matrix2x4d result) { double leftM11 = left.Row0.X; double leftM12 = left.Row0.Y; double leftM21 = left.Row1.X; double leftM22 = left.Row1.Y; double rightM11 = right.Row0.X; double rightM12 = right.Row0.Y; double rightM13 = right.Row0.Z; double rightM14 = right.Row0.W; double rightM21 = right.Row1.X; double rightM22 = right.Row1.Y; double rightM23 = right.Row1.Z; double rightM24 = right.Row1.W; result.Row0.X = (leftM11 * rightM11) + (leftM12 * rightM21); result.Row0.Y = (leftM11 * rightM12) + (leftM12 * rightM22); result.Row0.Z = (leftM11 * rightM13) + (leftM12 * rightM23); result.Row0.W = (leftM11 * rightM14) + (leftM12 * rightM24); result.Row1.X = (leftM21 * rightM11) + (leftM22 * rightM21); result.Row1.Y = (leftM21 * rightM12) + (leftM22 * rightM22); result.Row1.Z = (leftM21 * rightM13) + (leftM22 * rightM23); result.Row1.W = (leftM21 * rightM14) + (leftM22 * rightM24); } /// <summary> /// Multiplies two instances. /// </summary> /// <param name="left">The left operand of the multiplication.</param> /// <param name="right">The right operand of the multiplication.</param> /// <returns>A new instance that is the result of the multiplication.</returns> [Pure] public static Matrix2x4d Mult(Matrix2d left, Matrix2x4d right) { Mult(in left, in right, out Matrix2x4d result); return result; } /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The left operand of the addition.</param> /// <param name="right">The right operand of the addition.</param> /// <param name="result">A new instance that is the result of the addition.</param> public static void Add(in Matrix2d left, in Matrix2d right, out Matrix2d result) { result.Row0.X = left.Row0.X + right.Row0.X; result.Row0.Y = left.Row0.Y + right.Row0.Y; result.Row1.X = left.Row1.X + right.Row1.X; result.Row1.Y = left.Row1.Y + right.Row1.Y; } /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The left operand of the addition.</param> /// <param name="right">The right operand of the addition.</param> /// <returns>A new instance that is the result of the addition.</returns> [Pure] public static Matrix2d Add(Matrix2d left, Matrix2d right) { Add(in left, in right, out Matrix2d result); return result; } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The left operand of the subtraction.</param> /// <param name="right">The right operand of the subtraction.</param> /// <param name="result">A new instance that is the result of the subtraction.</param> public static void Subtract(in Matrix2d left, in Matrix2d right, out Matrix2d result) { result.Row0.X = left.Row0.X - right.Row0.X; result.Row0.Y = left.Row0.Y - right.Row0.Y; result.Row1.X = left.Row1.X - right.Row1.X; result.Row1.Y = left.Row1.Y - right.Row1.Y; } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The left operand of the subtraction.</param> /// <param name="right">The right operand of the subtraction.</param> /// <returns>A new instance that is the result of the subtraction.</returns> [Pure] public static Matrix2d Subtract(Matrix2d left, Matrix2d right) { Subtract(in left, in right, out Matrix2d result); return result; } /// <summary> /// Calculate the inverse of the given matrix. /// </summary> /// <param name="mat">The matrix to invert.</param> /// <param name="result">The inverse of the given matrix if it has one, or the input if it is singular.</param> /// <exception cref="InvalidOperationException">Thrown if the Matrix2d is singular.</exception> public static void Invert(in Matrix2d mat, out Matrix2d result) { var det = mat.Determinant; if (det == 0) { throw new InvalidOperationException("Matrix is singular and cannot be inverted."); } var invDet = 1f / det; result.Row0.X = mat.Row1.Y * invDet; result.Row0.Y = -mat.Row0.Y * invDet; result.Row1.X = -mat.Row1.X * invDet; result.Row1.Y = mat.Row0.X * invDet; } /// <summary> /// Calculate the inverse of the given matrix. /// </summary> /// <param name="mat">The matrix to invert.</param> /// <returns>The inverse of the given matrix.</returns> /// <exception cref="InvalidOperationException">Thrown if the Matrix2d is singular.</exception> /// <returns>The inverted copy.</returns> [Pure] public static Matrix2d Invert(Matrix2d mat) { Invert(in mat, out Matrix2d result); return result; } /// <summary> /// Calculate the transpose of the given matrix. /// </summary> /// <param name="mat">The matrix to transpose.</param> /// <param name="result">The transpose of the given matrix.</param> public static void Transpose(in Matrix2d mat, out Matrix2d result) { result.Row0.X = mat.Row0.X; result.Row0.Y = mat.Row1.X; result.Row1.X = mat.Row0.Y; result.Row1.Y = mat.Row1.Y; } /// <summary> /// Calculate the transpose of the given matrix. /// </summary> /// <param name="mat">The matrix to transpose.</param> /// <returns>The transpose of the given matrix.</returns> [Pure] public static Matrix2d Transpose(Matrix2d mat) { Transpose(in mat, out Matrix2d result); return result; } /// <summary> /// Scalar multiplication. /// </summary> /// <param name="left">left-hand operand.</param> /// <param name="right">right-hand operand.</param> /// <returns>A new Matrix2d which holds the result of the multiplication.</returns> [Pure] public static Matrix2d operator *(double left, Matrix2d right) { return Mult(right, left); } /// <summary> /// Scalar multiplication. /// </summary> /// <param name="left">left-hand operand.</param> /// <param name="right">right-hand operand.</param> /// <returns>A new Matrix2d which holds the result of the multiplication.</returns> [Pure] public static Matrix2d operator *(Matrix2d left, double right) { return Mult(left, right); } /// <summary> /// Matrix multiplication. /// </summary> /// <param name="left">left-hand operand.</param> /// <param name="right">right-hand operand.</param> /// <returns>A new Matrix2d which holds the result of the multiplication.</returns> [Pure] public static Matrix2d operator *(Matrix2d left, Matrix2d right) { return Mult(left, right); } /// <summary> /// Matrix multiplication. /// </summary> /// <param name="left">left-hand operand.</param> /// <param name="right">right-hand operand.</param> /// <returns>A new Matrix2x3d which holds the result of the multiplication.</returns> [Pure] public static Matrix2x3d operator *(Matrix2d left, Matrix2x3d right) { return Mult(left, right); } /// <summary> /// Matrix multiplication. /// </summary> /// <param name="left">left-hand operand.</param> /// <param name="right">right-hand operand.</param> /// <returns>A new Matrix2x4d which holds the result of the multiplication.</returns> [Pure] public static Matrix2x4d operator *(Matrix2d left, Matrix2x4d right) { return Mult(left, right); } /// <summary> /// Matrix addition. /// </summary> /// <param name="left">left-hand operand.</param> /// <param name="right">right-hand operand.</param> /// <returns>A new Matrix2d which holds the result of the addition.</returns> [Pure] public static Matrix2d operator +(Matrix2d left, Matrix2d right) { return Add(left, right); } /// <summary> /// Matrix subtraction. /// </summary> /// <param name="left">left-hand operand.</param> /// <param name="right">right-hand operand.</param> /// <returns>A new Matrix2d which holds the result of the subtraction.</returns> [Pure] public static Matrix2d operator -(Matrix2d left, Matrix2d right) { return Subtract(left, right); } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left equals right; false otherwise.</returns> [Pure] public static bool operator ==(Matrix2d left, Matrix2d right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left does not equal right; false otherwise.</returns> [Pure] public static bool operator !=(Matrix2d left, Matrix2d right) { return !left.Equals(right); } /// <summary> /// Returns a System.String that represents the current Matrix4. /// </summary> /// <returns>The string representation of the matrix.</returns> public override string ToString() { return $"{Row0}\n{Row1}"; } /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { unchecked { return (Row0.GetHashCode() * 397) ^ Row1.GetHashCode(); } } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> [Pure] public override bool Equals(object obj) { if (!(obj is Matrix2d)) { return false; } return Equals((Matrix2d)obj); } /// <summary> /// Indicates whether the current matrix is equal to another matrix. /// </summary> /// <param name="other">An matrix to compare with this matrix.</param> /// <returns>true if the current matrix is equal to the matrix parameter; otherwise, false.</returns> [Pure] public bool Equals(Matrix2d other) { return Row0 == other.Row0 && Row1 == other.Row1; } } }
36.370419
119
0.538597
[ "MIT" ]
Phyyl/opentk
src/OpenTK.Mathematics/Matrix/Matrix2d.cs
27,789
C#
using System; using System.Collections.Generic; using System.Text; namespace BoardGamer.BoardGameGeek.BoardGameGeekXmlApi2 { public class UserResponse { public UserResponse(User user) { this.Result = user; this.Succeeded = true; } public User Result { get; } public bool Succeeded { get; } public class User { public int Id { get; set; } public string Name { get; set; } public string TermsOfUse { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string AvatarLink { get; set; } public int YearRegistered { get; set; } public DateTime LastLogin { get; set; } public string StateOrProvince { get; set; } public string Country { get; set; } public string WebAddress { get; set; } public string XboxAccount { get; set; } public string WiiAccount { get; set; } public string PsnAccount { get; set; } public string BattleNetAccount { get; set; } public string SteamAccount { get; set; } public int TradeRating { get; set; } public int MarketRating { get; set; } public List<Buddy> Buddies { get; set; } public List<Guild> Guilds { get; set; } public List<Item> Top { get; set; } public List<Item> Hot { get; set; } } public class Buddy { public int Id { get; set; } public string Name { get; set; } } public class Guild { public int Id { get; set; } public string Name { get; set; } } public class Item { public int Rank { get; set; } public string Type { get; set; } public int Id { get; set; } public string Name { get; set; } } } }
30.530303
56
0.517618
[ "MIT" ]
Cobster/BoardGamer.BoardGameGeek
src/BoardGamer.BoardGameGeek/BoardGameGeekXmlApi2/UserResponse.cs
2,017
C#
using Caco.API.Models; using Microsoft.EntityFrameworkCore; namespace Caco.API.Persistence.Contexts { public class AppDbContext : DbContext { public DbSet<Board> Boards { get; set; } public DbSet<Column> Columns { get; set; } public DbSet<Card> Cards { get; set; } public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); builder.Entity<Board>().ToTable("Boards"); builder.Entity<Board>().HasKey(p => p.Id); builder.Entity<Board>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd(); builder.Entity<Board>().Property(p => p.Name).IsRequired().HasMaxLength(30); builder.Entity<Board>().HasMany(p => p.Columns).WithOne(p => p.Board).HasForeignKey(p => p.BoardId) .OnDelete(DeleteBehavior.Cascade); builder.Entity<Board>().HasData ( new Board { Id = 100, Name = "Dailies" }, new Board { Id = 101, Name = "Sprint Team 1" } ); builder.Entity<Column>().ToTable("Columns"); builder.Entity<Column>().HasKey(p => p.Id); builder.Entity<Column>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd(); builder.Entity<Column>().Property(p => p.Name).IsRequired().HasMaxLength(30); builder.Entity<Column>().HasMany(p => p.Cards).WithOne(p => p.Column).HasForeignKey(p => p.ColumnId) .OnDelete(DeleteBehavior.Cascade); builder.Entity<Column>().HasData ( new Column { Id = 100, Name = "Day 1", BoardId = 100 }, new Column { Id = 101, Name = "Day 2", BoardId = 100 }, new Column { Id = 102, Name = "Day 3", BoardId = 100 }, new Column { Id = 103, Name = "Sprint", BoardId = 101 }, new Column { Id = 104, Name = "Doing", BoardId = 101 }, new Column { Id = 105, Name = "Done", BoardId = 101 } ); builder.Entity<Card>().ToTable("Cards"); builder.Entity<Card>().HasKey(p => p.Id); builder.Entity<Card>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd(); builder.Entity<Card>().Property(p => p.Name).IsRequired().HasMaxLength(30); builder.Entity<Card>().Property(p => p.Description).HasMaxLength(4000); builder.Entity<Card>().HasData ( new Card { Id = 100, Name = "Attending daily", Description = "The only thing I did that day.", ColumnId = 100 }, new Card { Id = 101, Name = "Create todo app", Description = "We need more todo apps.", ColumnId = 103 }, new Card { Id = 102, Name = "Write TPS report", Description = "", ColumnId = 104 }, new Card { Id = 103, Name = "Buy cover sheets", Description = "", ColumnId = 105 }, new Card { Id = 104, Name = "Read memos", Description = "", ColumnId = 105 }, new Card { Id = 105, Name = "Buy ping pong table", Description = "", ColumnId = 103 } ); } } }
49.257576
128
0.551523
[ "Unlicense" ]
alutrin/caco
api/Persistence/Contexts/AppDbContext.cs
3,251
C#
namespace Game { using UnityEngine; public class SoundManager : MonoBehaviour { public static SoundManager instance { get; private set; } public SoundFx[] soundFx = new SoundFx[0]; public AudioClip actionMusic; public AudioClip quietMusic; public AudioSource backgroundPlayer; public AudioSource fxPlayer; public AudioSource loopingFxPlayer; [Range(0f, 1f)] public float backgroundVolume = .3f; [Range(0f, 1f)] public float fxVolume = 0.6f; [Range(0f, 1f)] public float announcerVolume = 1f; private AudioClip _nextTrack; private bool _actionMusic = false; private bool _fadingOut = false; private bool _fadingIn = false; private void Awake() { if (instance != null) { Debug.LogWarning(this.ToString() + " another SoundManager has already been registered, destroying this one"); GameObject.Destroy(this.gameObject); return; } instance = this; } private void Start() { backgroundPlayer.priority = 0; loopingFxPlayer.loop = true; } private void Update() { QueueNextTrack(); PlayTrack(); ManageFading(); } public void ToggleMusic() { _actionMusic = !_actionMusic; _fadingOut = true; } public void PlayFx(SoundFxType fx) { AudioClip[] clips = null; SoundFx sfx = GetSfx(fx); if(sfx != null) { clips = sfx.clips; } if (clips != null) { fxPlayer.PlayOneShot(GetRandomClip(clips), fxVolume); } } public void PlayAnnouncement(SoundFxType fx) { AudioClip[] clips = null; SoundFx sfx = GetSfx(fx); if(sfx != null) { clips = sfx.clips; } if (clips != null) { fxPlayer.PlayOneShot(GetRandomClip(clips), announcerVolume); } } private SoundFx GetSfx(SoundFxType fx) { // Currently only supports the first match. Don't be dumb ;-) for (int i = 0; i < soundFx.Length; i++) { var sfx = soundFx[i]; if (sfx.type == fx) { return sfx; } } return null; } private SoundFxType _currentLoopingSfxType = SoundFxType.None; public void StartFx(SoundFxType fx) { SoundFx sfx = GetSfx(fx); AudioClip clip = GetRandomClip(sfx.clips); if(clip != null) { loopingFxPlayer.clip = clip; loopingFxPlayer.Play(); _currentLoopingSfxType = fx; } } public void StopFx(SoundFxType fx) { if(_currentLoopingSfxType == fx) { loopingFxPlayer.Stop(); _currentLoopingSfxType = SoundFxType.None; } } private void PlayTrack() { if (!backgroundPlayer.isPlaying) { backgroundPlayer.clip = _nextTrack; backgroundPlayer.volume = backgroundVolume; backgroundPlayer.Play(); _nextTrack = null; } } private AudioClip GetRandomClip(AudioClip[] clips) { //TODO: Crazy logic here. if (clips.Length > 0) { int idx = Random.Range(0, clips.Length); return clips[idx]; } return null; } private void QueueNextTrack() { if (!_actionMusic) { _nextTrack = quietMusic; } else { _nextTrack = actionMusic; } } private void ManageFading() { if (_fadingIn || _fadingOut) { fadeOut(); if (backgroundPlayer.volume <= 0.1) { backgroundPlayer.clip = _nextTrack; backgroundPlayer.Play(); _fadingOut = false; _fadingIn = true; } fadeIn(); } } private void fadeIn() { if (backgroundPlayer.volume < backgroundVolume && _fadingIn) { backgroundPlayer.volume += 0.5f * Time.deltaTime; } else { _fadingIn = false; } } private void fadeOut() { if (backgroundPlayer.volume > 0.1f && _fadingOut) { backgroundPlayer.volume -= 0.5f * Time.deltaTime; } } } }
23.335025
125
0.509463
[ "MIT" ]
RamiAhmed/NGJ16
Assets/Scripts/SoundManager.cs
4,599
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by SpecFlow (http://www.specflow.org/). // SpecFlow Version:1.8.0.0 // SpecFlow Generator Version:1.8.0.0 // Runtime Version:4.0.30319.239 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #region Designer generated code using TechTalk.SpecFlow; #pragma warning disable namespace Pickles.Example.Features._00BasicGherkin { [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "1.8.0.0")] [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [NUnit.Framework.TestFixtureAttribute()] [NUnit.Framework.DescriptionAttribute("Showing basic gherkin syntax")] public partial class ShowingBasicGherkinSyntaxFeature { private static TechTalk.SpecFlow.ITestRunner testRunner; #line 1 "BasicGherkin.feature" #line hidden [NUnit.Framework.TestFixtureSetUpAttribute()] public virtual void FeatureSetup() { testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(); var featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Showing basic gherkin syntax", "In order to see that gherkin is a very simple langauge\r\nAs a SpecFlow evangelist\r" + "\nI want to show that basic syntax", ProgrammingLanguage.CSharp, ((string[]) (null))); testRunner.OnFeatureStart(featureInfo); } [NUnit.Framework.TestFixtureTearDownAttribute()] public virtual void FeatureTearDown() { testRunner.OnFeatureEnd(); testRunner = null; } [NUnit.Framework.SetUpAttribute()] public virtual void TestInitialize() { } [NUnit.Framework.TearDownAttribute()] public virtual void ScenarioTearDown() { testRunner.OnScenarioEnd(); } public virtual void ScenarioSetup(TechTalk.SpecFlow.ScenarioInfo scenarioInfo) { testRunner.OnScenarioStart(scenarioInfo); } public virtual void ScenarioCleanup() { testRunner.CollectScenarioErrors(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Simple GWT")] public virtual void SimpleGWT() { var scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Simple GWT", ((string[]) (null))); #line 6 this.ScenarioSetup(scenarioInfo); #line 7 testRunner.Given("the initial state of the application is Running"); #line 8 testRunner.When("I ask what the application state is"); #line 9 testRunner.Then("I should see Running as the answer"); #line hidden this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("Using And and But")] public virtual void UsingAndAndBut() { var scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("Using And and But", ((string[]) (null))); #line 11 this.ScenarioSetup(scenarioInfo); #line 12 testRunner.Given("the initial state of the application is Running"); #line 13 testRunner.And("I have authorization to ask application state"); #line 14 testRunner.When("I ask what the application state is"); #line 15 testRunner.Then("I should see Running as the answer"); #line 16 testRunner.And("I should see the time of the application"); #line 17 testRunner.But("the state of the application should not be Stopped"); #line hidden this.ScenarioCleanup(); } } } #pragma warning restore #endregion
36.155172
152
0.591082
[ "Apache-2.0" ]
madhudevops19/pickles
src/Pickles/Pickles.Example/Features/00BasicGherkin/BasicGherkin1.feature.cs
4,196
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Configuration; using System.Xml; using System.Windows.Forms; namespace Termo { public class TermoSettings { public int RowCnt=0; public int ColCnt=0; // public bool isAutoLoad = false; public TermoSettings() { } public bool SetDataGridInfo(DataGridView dg) { Configuration Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ClientSettingsSection Termosection = (ClientSettingsSection)Config.GetSectionGroup("Termo.InitFiles").Sections["Termo.Properties.Settings"]; if (Config != null) { dg.Rows.Clear(); dg.Columns.Clear(); RowCnt = Properties.Settings.Default.InitRowCount; ColCnt = Properties.Settings.Default.InitColumnCount; try { if (RowCnt > 0 && ColCnt > 0) { for (int k = 0; k <= ColCnt; k++) { dg.Columns.Add("col"+ Convert.ToString(k), "... K/min"); } for (int k = 0; k < RowCnt; k++) { dg.Rows.Add(new DataGridViewRow()); } bool flgset = false; //Termosection = (ClientSettingsSection)Config.GetSectionGroup("Termo.InitFiles").Sections["Termo.Properties.Settings"]; for (int k=0; k< RowCnt; k++) { for (int j=0; j<ColCnt; j++) { var C_str = Termosection.Settings.Get(Convert.ToString(k)+'_'+Convert.ToString(j)); if (C_str != null) { dg[j,k].Value= C_str.Value.ValueXml.InnerText; ;flgset = true; } } } return flgset; } else { ClearDataGrid(dg); return false; } } catch (Exception e) { ClearDataGrid(dg); return false; } } else { return false; } } public void ClearDataGrid(DataGridView dg) { Configuration Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ClientSettingsSection Termosection = (ClientSettingsSection)Config.GetSectionGroup("Termo.InitFiles").Sections["Termo.Properties.Settings"]; dg.Rows.Clear(); dg.Columns.Clear(); dg.Columns.Add("col0", "... K/min"); RowCnt = 0; Properties.Settings.Default.InitRowCount = RowCnt; ColCnt = 0; Properties.Settings.Default.InitColumnCount = ColCnt; Termosection.Settings.Clear(); Config.Save(); ConfigurationManager.RefreshSection("Termo.InitFiles/Termo.Properties.Settings"); } public void GetDataGridInfo(DataGridView dg) //cохраняет состояние DataGridView в .config { Configuration Config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ClientSettingsSection Termosection = (ClientSettingsSection)Config.GetSectionGroup("Termo.InitFiles").Sections["Termo.Properties.Settings"]; RowCnt = dg.Rows.Count - 1; ColCnt = dg.Columns.Count-1; Properties.Settings.Default.InitRowCount = RowCnt; Properties.Settings.Default.InitColumnCount = ColCnt; for (int i=0; i<dg.Rows.Count; i++) for (int j=0; j<dg.Columns.Count;j++) { if (dg[j,i].Value != null) { // получаем значение параметра Str string Key = Convert.ToString(i) + '_' + Convert.ToString(j); var C_str = Termosection.Settings.Get(Key); if (C_str != null) { Termosection.Settings.Remove(C_str); } // вручную создаем параметр с новым значением var newSetting = new SettingElement(Key, SettingsSerializeAs.String); newSetting.Value = new SettingValueElement(); newSetting.Value.ValueXml = new XmlDocument().CreateElement("value"); newSetting.Value.ValueXml.InnerText = (string)dg[j,i].Value; // заменяем старый параметр на новый Termosection.Settings.Add(newSetting); } } Config.Save(); ConfigurationManager.RefreshSection("Termo.InitFiles/Termo.Properties.Settings"); Properties.Settings.Default.Save(); } } }
39.864662
152
0.496982
[ "MIT" ]
VINEET1234-CH/Kinetic-calculation
src/TermoSettings.cs
5,413
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web; using System.Xml.Serialization; using NewLife; using NewLife.Data; using NewLife.Log; using NewLife.Model; using NewLife.Reflection; using NewLife.Threading; using NewLife.Web; using XCode; using XCode.Cache; using XCode.Configuration; using XCode.DataAccessLayer; using XCode.Membership; namespace IdentityServer4.XCode.Entities { /// <summary></summary> [ModelCheckMode(ModelCheckModes.CheckTableWhenFirstUse)] public partial class ApiSecrets : Entity<ApiSecrets> { #region 对象操作 static ApiSecrets() { // 累加字段 //var df = Meta.Factory.AdditionalFields; //df.Add(__.ApiResourceId); // 过滤器 UserModule、TimeModule、IPModule } /// <summary>验证数据,通过抛出异常的方式提示验证失败。</summary> /// <param name="isNew">是否插入</param> public override void Valid(Boolean isNew) { // 如果没有脏数据,则不需要进行任何处理 if (!HasDirty) return; // 这里验证参数范围,建议抛出参数异常,指定参数名,前端用户界面可以捕获参数异常并聚焦到对应的参数输入框 if (Created.IsNullOrEmpty()) throw new ArgumentNullException(nameof(Created), "Created不能为空!"); if (Value.IsNullOrEmpty()) throw new ArgumentNullException(nameof(Value), "Value不能为空!"); if (Type.IsNullOrEmpty()) throw new ArgumentNullException(nameof(Type), "Type不能为空!"); // 在新插入数据或者修改了指定字段时进行修正 } ///// <summary>首次连接数据库时初始化数据,仅用于实体类重载,用户不应该调用该方法</summary> //[EditorBrowsable(EditorBrowsableState.Never)] //protected override void InitData() //{ // // InitData一般用于当数据表没有数据时添加一些默认数据,该实体类的任何第一次数据库操作都会触发该方法,默认异步调用 // if (Meta.Session.Count > 0) return; // if (XTrace.Debug) XTrace.WriteLine("开始初始化ApiSecrets[ApiSecrets]数据……"); // var entity = new ApiSecrets(); // entity.Created = "abc"; // entity.Expiration = "abc"; // entity.Id = 0; // entity.Description = "abc"; // entity.Value = "abc"; // entity.Type = "abc"; // entity.ApiResourceId = 0; // entity.Insert(); // if (XTrace.Debug) XTrace.WriteLine("完成初始化ApiSecrets[ApiSecrets]数据!"); //} ///// <summary>已重载。基类先调用Valid(true)验证数据,然后在事务保护内调用OnInsert</summary> ///// <returns></returns> //public override Int32 Insert() //{ // return base.Insert(); //} ///// <summary>已重载。在事务保护范围内处理业务,位于Valid之后</summary> ///// <returns></returns> //protected override Int32 OnDelete() //{ // return base.OnDelete(); //} #endregion #region 扩展属性 #endregion #region 扩展查询 /// <summary>根据Id查找</summary> /// <param name="id">Id</param> /// <returns>实体对象</returns> public static ApiSecrets FindById(Int32 id) { if (id <= 0) return null; // 实体缓存 if (Meta.Session.Count < 1000) return Meta.Cache.Find(e => e.Id == id); // 单对象缓存 return Meta.SingleCache[id]; //return Find(_.Id == id); } /// <summary>根据ApiResourceId查找</summary> /// <param name="apiresourceid">ApiResourceId</param> /// <returns>实体列表</returns> public static IList<ApiSecrets> FindAllByApiResourceId(Int64 apiresourceid) { // 实体缓存 if (Meta.Session.Count < 1000) return Meta.Cache.FindAll(e => e.ApiResourceId == apiresourceid); return FindAll(_.ApiResourceId == apiresourceid); } #endregion #region 高级查询 #endregion #region 业务操作 #endregion } }
29.869231
108
0.588205
[ "MIT" ]
xxred/IdentityServer4.XCode
Entities/ApiSecrets.Biz.cs
4,547
C#
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.Drawing; using Duality; using Duality.Drawing; using Duality.Resources; using Duality.Editor.Plugins.CamView.CamViewStates; namespace Duality.Editor.Plugins.CamView.CamViewLayers { public class GridCamViewLayer : CamViewLayer { private RawList<VertexC1P3> vertexBuffer = null; public override string LayerName { get { return Properties.CamViewRes.CamViewLayer_Grid_Name; } } public override string LayerDesc { get { return Properties.CamViewRes.CamViewLayer_Grid_Desc; } } public override int Priority { get { return base.Priority - 10; } } public override bool MouseTracking { get { return true; } } protected internal override void OnCollectDrawcalls(Canvas canvas) { base.OnCollectDrawcalls(canvas); IDrawDevice device = canvas.DrawDevice; GridLayerData displayedData = default(GridLayerData); this.View.ActiveState.GetDisplayedGridData(Point.Empty, ref displayedData); float scaleTemp = 1.0f; Vector3 posTemp = Vector3.Zero; device.PreprocessCoords(ref posTemp, ref scaleTemp); if (posTemp.Z <= canvas.DrawDevice.NearZ) return; float alphaTemp = 0.5f; alphaTemp *= (float)Math.Min(1.0d, ((posTemp.Z - device.NearZ) / (device.NearZ * 5.0f))); if (alphaTemp <= 0.005f) return; ColorRgba gridColor = this.FgColor.WithAlpha(alphaTemp); float gridVisualMinSize = 50.0f; Vector2 gridBaseSize = displayedData.GridBaseSize; if (gridBaseSize.X <= 0.0f) gridBaseSize.X = 100.0f; if (gridBaseSize.Y <= 0.0f) gridBaseSize.Y = 100.0f; Vector2 adjustedGridBaseSize; adjustedGridBaseSize.X = gridBaseSize.X * MathF.NextPowerOfTwo((int)MathF.Ceiling(gridVisualMinSize / gridBaseSize.X)); adjustedGridBaseSize.Y = gridBaseSize.Y * MathF.NextPowerOfTwo((int)MathF.Ceiling(gridVisualMinSize / gridBaseSize.Y)); float scaleAdjustmentFactor = 4.0f * MathF.Pow(2.0f, -MathF.Round(1.0f - MathF.Log(1.0f / scaleTemp, 2.0f))); Vector2 adjustedGridSize; adjustedGridSize.X = MathF.Max(adjustedGridBaseSize.X * scaleAdjustmentFactor, gridBaseSize.X); adjustedGridSize.Y = MathF.Max(adjustedGridBaseSize.Y * scaleAdjustmentFactor, gridBaseSize.Y); Vector2 stepTemp = adjustedGridSize; Vector2 scaledStep = stepTemp * scaleTemp; float viewBoundRad = device.TargetSize.Length * 0.5f; int lineCountX = (2 + (int)MathF.Ceiling(viewBoundRad * 2 / scaledStep.X)) * 4; int lineCountY = (2 + (int)MathF.Ceiling(viewBoundRad * 2 / scaledStep.Y)) * 4; int vertexCount = (lineCountX * 2 + lineCountY * 2); if (this.vertexBuffer == null) this.vertexBuffer = new RawList<VertexC1P3>(vertexCount); this.vertexBuffer.Count = vertexCount; VertexC1P3[] vertices = this.vertexBuffer.Data; float beginPos; float pos; int lineIndex; int vertOff = 0; beginPos = posTemp.X % scaledStep.X - (lineCountX / 8) * scaledStep.X; pos = beginPos; lineIndex = 0; for (int x = 0; x < lineCountX; x++) { bool primaryLine = lineIndex % 4 == 0; bool secondaryLine = lineIndex % 4 == 2; vertices[vertOff + x * 2 + 0].Color = primaryLine ? gridColor : gridColor.WithAlpha(alphaTemp * (secondaryLine ? 0.5f : 0.25f)); vertices[vertOff + x * 2 + 0].Pos.X = pos; vertices[vertOff + x * 2 + 0].Pos.Y = -viewBoundRad; vertices[vertOff + x * 2 + 0].Pos.Z = posTemp.Z + 1; vertices[vertOff + x * 2 + 1] = vertices[vertOff + x * 2 + 0]; vertices[vertOff + x * 2 + 1].Pos.Y = viewBoundRad; pos += scaledStep.X / 4; lineIndex++; } vertOff += lineCountX * 2; beginPos = posTemp.Y % scaledStep.Y - (lineCountY / 8) * scaledStep.Y; pos = beginPos; lineIndex = 0; for (int y = 0; y < lineCountY; y++) { bool primaryLine = lineIndex % 4 == 0; bool secondaryLine = lineIndex % 4 == 2; vertices[vertOff + y * 2 + 0].Color = primaryLine ? gridColor : gridColor.WithAlpha(alphaTemp * (secondaryLine ? 0.5f : 0.25f)); vertices[vertOff + y * 2 + 0].Pos.X = -viewBoundRad; vertices[vertOff + y * 2 + 0].Pos.Y = pos; vertices[vertOff + y * 2 + 0].Pos.Z = posTemp.Z + 1; vertices[vertOff + y * 2 + 1] = vertices[vertOff + y * 2 + 0]; vertices[vertOff + y * 2 + 1].Pos.X = viewBoundRad; pos += scaledStep.Y / 4; lineIndex++; } vertOff += lineCountY * 2; device.AddVertices(new BatchInfo(DrawTechnique.Alpha, ColorRgba.White), VertexMode.Lines, vertices, this.vertexBuffer.Count); } protected internal override void OnCollectOverlayDrawcalls(Canvas canvas) { base.OnCollectOverlayDrawcalls(canvas); bool noActionText = string.IsNullOrEmpty(this.View.ActiveState.ActionText); bool mouseover = this.View.ActiveState.Mouseover; Point cursorPos = this.PointToClient(Cursor.Position); if (noActionText && mouseover && cursorPos.X > 0 && cursorPos.X < this.ClientSize.Width && cursorPos.Y > 0 && cursorPos.Y < this.ClientSize.Height) { GridLayerData displayedData = default(GridLayerData); this.View.ActiveState.GetDisplayedGridData(cursorPos, ref displayedData); cursorPos.X += 30; cursorPos.Y += 10; string[] text = new string[] { string.Format("X:{0,7:0}", displayedData.DisplayedGridPos.X), string.Format("Y:{0,7:0}", displayedData.DisplayedGridPos.Y) }; canvas.DrawText(text, cursorPos.X, cursorPos.Y, drawBackground: true); } } } }
36.917197
141
0.648896
[ "MIT" ]
LukasPirkl/duality
Source/Plugins/EditorModules/CamView/CamViewLayers/GridCamViewLayer.cs
5,798
C#
using System; using System.Windows.Controls; namespace WpfBasicOptionalLogin.Contracts.Services { public interface INavigationService { event EventHandler<string> Navigated; Frame Frame { get; } bool CanGoBack { get; } void Initialize(Frame shellFrame); bool NavigateTo(string pageKey, object parameter = null, bool clearNavigation = false); void GoBack(); void UnsubscribeNavigation(); } }
20.304348
95
0.668094
[ "MIT" ]
jpda/WpfForcedLogin
WpfBasicOptionalLogin/Contracts/Services/INavigationService.cs
469
C#
using System.Collections.Concurrent; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using OrchardCore.Environment.Shell; using OrchardCore.ResourceManagement; using OrchardCore.Settings; namespace OrchardCore.Resources { public class ResourceManagementOptionsConfiguration : IConfigureOptions<ResourceManagementOptions> { private readonly ISiteService _siteService; private readonly IHostEnvironment _env; private readonly IHttpContextAccessor _httpContextAccessor; private readonly string _tenantPrefix; private const string cloudflareUrl = "https://cdnjs.cloudflare.com/ajax/libs/"; // Versions private const string codeMirrorVersion = "5.64.0"; private const string monacoEditorVersion = "0.30.0"; // URLs private const string codeMirrorUrl = cloudflareUrl + "codemirror/" + codeMirrorVersion + "/"; public ResourceManagementOptionsConfiguration(ISiteService siteService, IHostEnvironment env, IHttpContextAccessor httpContextAccessor, ShellSettings shellSettings) { _siteService = siteService; _env = env; _httpContextAccessor = httpContextAccessor; _tenantPrefix = string.IsNullOrEmpty(shellSettings.RequestUrlPrefix) ? string.Empty : "/" + shellSettings.RequestUrlPrefix; } ResourceManifest BuildManifest() { var manifest = new ResourceManifest(); manifest .DefineScript("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/jquery.min.js", "~/OrchardCore.Resources/Scripts/jquery.js") .SetCdn("https://code.jquery.com/jquery-3.6.0.min.js", "https://code.jquery.com/jquery-3.6.0.js") .SetCdnIntegrity("sha384-vtXRMe3mGCbOeY7l30aIg8H9p3GdeSe4IFlP6G8JMa7o7lXvnz3GFKzPxzJdPfGK", "sha384-S58meLBGKxIiQmJ/pJ8ilvFUcGcqgla+mWH9EEKGm6i6rKxSTA2kpXJQJ8n7XK4w") .SetVersion("3.6.0"); manifest .DefineScript("jQuery.slim") .SetUrl("~/OrchardCore.Resources/Scripts/jquery.slim.min.js", "~/OrchardCore.Resources/Scripts/jquery.slim.js") .SetCdn("https://code.jquery.com/jquery-3.6.0.slim.min.js", "https://code.jquery.com/jquery-3.6.0.slim.js") .SetCdnIntegrity("sha384-Qg00WFl9r0Xr6rUqNLv1ffTSSKEFFCDCKVyHZ+sVt8KuvG99nWw5RNvbhuKgif9z", "sha384-fuUlMletgG/KCb0NwIZTW6aMv/YBbXe0Wt71nwLRreZZpesG/N/aURjEZCG6mtYn") .SetVersion("3.6.0"); manifest .DefineScript("jQuery") .SetUrl("~/OrchardCore.Resources/Vendor/jquery-3.5.1/jquery.min.js", "~/OrchardCore.Resources/Vendor/jquery-3.5.1/jquery.js") .SetCdn("https://code.jquery.com/jquery-3.5.1.min.js", "https://code.jquery.com/jquery-3.5.1.js") .SetCdnIntegrity("sha384-ZvpUoO/+PpLXR1lu4jmpXWu80pZlYUAfxl5NsBMWOEPSjUn/6Z/hRTt8+pR6L4N2", "sha384-/LjQZzcpTzaYn7qWqRIWYC5l8FWEZ2bIHIz0D73Uzba4pShEcdLdZyZkI4Kv676E") .SetVersion("3.5.1"); manifest .DefineScript("jQuery.slim") .SetUrl("~/OrchardCore.Resources/Vendor/jquery-3.5.1/jquery.slim.min.js", "~/OrchardCore.Resources/Vendor/jquery-3.5.1/jquery.slim.js") .SetCdn("https://code.jquery.com/jquery-3.5.1.slim.min.js", "https://code.jquery.com/jquery-3.5.1.slim.js") .SetCdnIntegrity("sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj", "sha384-x6NENSfxadikq2gB4e6/qompriNc+y1J3eqWg3hAAMNBs4dFU303XMTcU3uExJgZ") .SetVersion("3.5.1"); manifest .DefineScript("jQuery") .SetUrl("~/OrchardCore.Resources/Vendor/jquery-3.4.1/jquery.min.js", "~/OrchardCore.Resources/Vendor/jquery-3.4.1/jquery.js") .SetCdn("https://code.jquery.com/jquery-3.4.1.min.js", "https://code.jquery.com/jquery-3.4.1.js") .SetCdnIntegrity("sha384-vk5WoKIaW/vJyUAd9n/wmopsmNhiy+L2Z+SBxGYnUkunIxVxAv/UtMOhba/xskxh", "sha384-mlceH9HlqLp7GMKHrj5Ara1+LvdTZVMx4S1U43/NxCvAkzIo8WJ0FE7duLel3wVo") .SetVersion("3.4.1"); manifest .DefineScript("jQuery.slim") .SetUrl("~/OrchardCore.Resources/Vendor/jquery-3.4.1/jquery.slim.min.js", "~/OrchardCore.Resources/Vendor/jquery-3.4.1/jquery.slim.js") .SetCdn("https://code.jquery.com/jquery-3.4.1.slim.min.js", "https://code.jquery.com/jquery-3.4.1.slim.js") .SetCdnIntegrity("sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n", "sha384-teRaFq/YbXOM/9FZ1qTavgUgTagWUPsk6xapwcjkrkBHoWvKdZZuAeV8hhaykl+G") .SetVersion("3.4.1"); manifest .DefineScript("jQuery.easing") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/jquery.easing.min.js", "~/OrchardCore.Resources/Scripts/jquery.easing.js") .SetCdn("https://cdn.jsdelivr.net/npm/jquery.easing@1.4.1/jquery.easing.min.js", "https://cdn.jsdelivr.net/npm/jquery.easing@1.4.1/jquery.easing.js") .SetCdnIntegrity("sha384-leGYpHE9Tc4N9OwRd98xg6YFpB9shlc/RkilpFi0ljr3QD4tFoFptZvgnnzzwG4Q", "sha384-fwPA0FyfPOiDsglgAC4ZWmBGwpXSZNkq9IG+cM9HL4CkpNQo4xgCDkOIPdWypLMX") .SetVersion("1.4.1"); manifest .DefineScript("jQuery-ui") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/jquery-ui.min.js", "~/OrchardCore.Resources/Scripts/jquery-ui.js") .SetCdn("https://code.jquery.com/ui/1.12.1/jquery-ui.min.js", "https://code.jquery.com/ui/1.12.1/jquery-ui.js") .SetCdnIntegrity("sha384-Dziy8F2VlJQLMShA6FHWNul/veM9bCkRUaLqr199K94ntO5QUrLJBEbYegdSkkqX", "sha384-JPbtLYL10d/Z1crlc6GGGGM3PavCzzoUJ1UxH0bXHOfguWHQ6XAWrIzW+MBGGXe5") .SetVersion("1.12.1"); manifest .DefineStyle("jQuery-ui") .SetUrl("~/OrchardCore.Resources/Styles/jquery-ui.min.css", "~/OrchardCore.Resources/Styles/jquery-ui.css") .SetCdn("https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.min.css", "https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css") .SetCdnIntegrity("sha384-kcAOn9fN4XSd+TGsNu2OQKSuV5ngOwt7tg73O4EpaD91QXvrfgvf0MR7/2dUjoI6", "sha384-xewr6kSkq3dBbEtB6Z/3oFZmknWn7nHqhLVLrYgzEFRbU/DHSxW7K3B44yWUN60D") .SetVersion("1.12.1"); manifest .DefineScript("jQuery-ui-i18n") .SetDependencies("jQuery-ui") .SetUrl("~/OrchardCore.Resources/Scripts/jquery-ui-i18n.min.js", "~/OrchardCore.Resources/Scripts/jquery-ui-i18n.js") .SetCdn("https://code.jquery.com/ui/1.7.2/i18n/jquery-ui-i18n.min.js", "https://code.jquery.com/ui/1.7.2/i18n/jquery-ui-i18n.min.js") .SetCdnIntegrity("sha384-0rV7y4NH7acVmq+7Y9GM6evymvReojk9li+7BYb/ug61uqPSsXJ4uIScVY+N9qtd", "sha384-0rV7y4NH7acVmq+7Y9GM6evymvReojk9li+7BYb/ug61uqPSsXJ4uIScVY+N9qtd") .SetVersion("1.7.2"); manifest .DefineScript("bootstrap") .SetDependencies("jQuery") .SetCdn("https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js", "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.js") .SetCdnIntegrity("sha384-vhJnz1OVIdLktyixHY4Uk3OHEwdQqPppqYR8+5mjsauETgLOcEynD9oPHhhz18Nw", "sha384-it0Suwx+VjMafDIVf5t+ozEbrflmNjEddSX5LstI/Xdw3nv4qP/a4e8K4k5hH6l4") .SetVersion("3.4.0"); manifest .DefineStyle("bootstrap") .SetCdn("https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css", "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.css") .SetCdnIntegrity("sha384-PmY9l28YgO4JwMKbTvgaS7XNZJ30MK9FAZjjzXtlqyZCqBY6X6bXIkM++IkyinN+", "sha384-/5bQ8UYbZnrNY3Mfy6zo9QLgIQD/0CximLKk733r8/pQnXn2mgvhvKhcy43gZtJV") .SetVersion("3.4.0"); manifest .DefineStyle("bootstrap-theme") .SetCdn("https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap-theme.min.css", "https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap-theme.css") .SetCdnIntegrity("sha384-jzngWsPS6op3fgRCDTESqrEJwRKck+CILhJVO5VvaAZCq8JYf8HsR/HPpBOOPZfR", "sha384-RtiWe5OsslAYZ9AVyorBziI2VQL7E27rzWygBJh7wrZuVPyK5jeQLLytnJIpJqfD") .SetVersion("3.4.0"); manifest .DefineScript("popper") .SetUrl("~/OrchardCore.Resources/Vendor/popper-1.16.1/popper.min.js", "~/OrchardCore.Resources/Vendor/popper-1.16.1/popper.js") .SetCdn("https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js", "https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.js") .SetCdnIntegrity("sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN", "sha384-cpSm/ilDFOWiMuF2bj03ZzJinb48NO9IGCXcYDtUzdP5y64Ober65chnoOj1XFoA") .SetVersion("1.16.1"); manifest .DefineScript("bootstrap") .SetDependencies("jQuery", "popper") .SetUrl("~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.min.js", "~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.js") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js", "https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.js") .SetCdnIntegrity("sha256-SyTu6CwrfOhaznYZPoolVw2rxoY7lKYKQvqbtqN93HI=", "sha256-6+FBBJrY8QbYNs6AeCP3JSnzmmTX/+YFtN4iSOtYSKY=") .SetVersion("4.6.1"); manifest .DefineScript("bootstrap-bundle") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.bundle.min.js", "~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.bundle.js") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js", "https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.js") .SetCdnIntegrity("sha256-fgLAgv7fyCGopR/gBNq2iW3ZKIdqIcyshnUULC4vex8=", "sha256-eKb5bRTtGi7f8XfWkjxVGyJWtw9gS1X+9yqhNHklfWI=") .SetVersion("4.6.1"); manifest .DefineStyle("bootstrap") .SetUrl("~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.min.css", "~/OrchardCore.Resources/Vendor/bootstrap-4.6.1/bootstrap.css") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css", "https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.css") .SetCdnIntegrity("sha256-DF7Zhf293AJxJNTmh5zhoYYIMs2oXitRfBjY+9L//AY=", "sha256-YQxBfLfP0/QyffXZNTDFES5IFXrxv+hYE9b2NK5TGcw=") .SetVersion("4.6.1"); manifest .DefineScript("popperjs") .SetUrl("~/OrchardCore.Resources/Scripts/popper.min.js", "~/OrchardCore.Resources/Scripts/popper.js") .SetCdn("https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js", "https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.js") .SetCdnIntegrity("sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB", "sha384-7bLhHCLchQRw474eiNFHP0txk38fyqbVOG/RohbcYXnTrdd9mNPQrVkOcY14iscj") .SetVersion("2.10.2"); manifest .DefineScript("bootstrap") .SetDependencies("popperjs") .SetUrl("~/OrchardCore.Resources/Scripts/bootstrap.min.js", "~/OrchardCore.Resources/Scripts/bootstrap.js") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js", "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.js") .SetCdnIntegrity("sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13", "sha384-4S2sRpwEfE5rUaiRVP4sETrP8WMo4pOHkAoMmvuju/2ycHM/QW1J7YQOjrPNpd5h") .SetVersion("5.1.3"); manifest .DefineScript("bootstrap-bundle") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/bootstrap.bundle.min.js", "~/OrchardCore.Resources/Scripts/bootstrap.bundle.js") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js", "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.js") .SetCdnIntegrity("sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p", "sha384-8fq7CZc5BnER+jVlJI2Jafpbn4A9320TKhNJfYP33nneHep7sUg/OD30x7fK09pS") .SetVersion("5.1.3"); manifest .DefineStyle("bootstrap") .SetUrl("~/OrchardCore.Resources/Styles/bootstrap.min.css", "~/OrchardCore.Resources/Styles/bootstrap.css") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css", "https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.css") .SetCdnIntegrity("sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3", "sha384-BNKxVsQUv1K6rV5WJumgbzW1t/UsyFWm/uP4I8rr9T3PeBkcRGGApJv+rOjBpEdF") .SetVersion("5.1.3"); manifest .DefineStyle("bootstrap-select") .SetUrl("~/OrchardCore.Resources/Styles/bootstrap-select.min.css", "~/OrchardCore.Resources/Styles/bootstrap-select.css") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.18/dist/css/bootstrap-select.min.css", "https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.18/dist/css/bootstrap-select.css") .SetCdnIntegrity("sha384-dTqTc7d5t+FKhTIaMmda32pZNoXY/Y0ui0hRl5GzDQp4aARfEzbP1jzX6+KRuGKg", "sha384-OlTrhEtwZzUzVXapTUO8s6QryXzpD8mFyNVA8kyAi8KMgfOKSJYvielvExM+dNPR") .SetVersion("1.13.18"); manifest .DefineScript("bootstrap-select") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/bootstrap-select.min.js", "~/OrchardCore.Resources/Scripts/bootstrap-select.js") .SetCdn("https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.18/dist/js/bootstrap-select.min.js", "https://cdn.jsdelivr.net/npm/bootstrap-select@1.13.18/dist/js/bootstrap-select.js") .SetCdnIntegrity("sha384-x8fxIWvLdZnkRaCvkDXOlxd6UP+qga975FjnbRp6NRpL9jjXjY9TwF9y7z4AccxS", "sha384-6BZTOUHC4e3nWcy5gveLqAu52vwy5TX8zBIvvfZFVDzIjYDgprdXRMK/hsypxdpQ") .SetVersion("1.13.18"); manifest .DefineStyle("bootstrap-slider") .SetUrl("~/OrchardCore.Resources/Styles/bootstrap-slider.min.css", "~/OrchardCore.Resources/Styles/bootstrap-slider.css") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/11.0.2/css/bootstrap-slider.min.css", "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/11.0.2/css/bootstrap-slider.css") .SetCdnIntegrity("sha384-Ot7O5p8Ws9qngwQOA1DP7acHuGIfK63cYbVJRYzrrMXhT3syEYhEsg+uqPsPpRhZ", "sha384-x1BbAB1QrM4/ZjT+vJzuI/NdvRo4tINKqg7lTN9jCq0bWrr/nelp9KfroZWd3UJu") .SetVersion("11.0.2"); manifest .DefineScript("bootstrap-slider") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/bootstrap-slider.min.js", "~/OrchardCore.Resources/Scripts/bootstrap-slider.js") .SetCdn("https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/11.0.2/bootstrap-slider.min.js", "https://cdnjs.cloudflare.com/ajax/libs/bootstrap-slider/11.0.2/bootstrap-slider.js") .SetCdnIntegrity("sha384-lZLZ1uMNIkCnScGXQrJ+PzUR2utC/FgaxJLMMrQD3Fbra1AwGXvshEIedqCmqXTM", "sha384-3kfvdN8W/a8p/9S6Gy69uVsacwuNxyvFVJXxZa/Qe00tkNfZw63n/4snM1u646YU") .SetVersion("11.0.2"); manifest .DefineStyle("codemirror") .SetUrl("~/OrchardCore.Resources/Styles/codemirror/codemirror.min.css", "~/OrchardCore.Resources/Styles/codemirror/codemirror.css") .SetCdn(codeMirrorUrl + "codemirror.min.css", codeMirrorUrl + "codemirror.css") .SetCdnIntegrity("sha384-KoxwpPPg4NMA10DxiUgtUyRWwpky7/582Ua4fbpJj6bNHAOqOiqSJfRZ+GLArzSR", "sha384-CQoQE99ffnItQimoAYyaWSR3jOs54zfOQ/PUaS7dycVqenh7FJWKca5xa260ehrV") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/codemirror.min.js", "~/OrchardCore.Resources/Scripts/codemirror/codemirror.js") .SetCdn(codeMirrorUrl + "codemirror.min.js", codeMirrorUrl + "codemirror.js") .SetCdnIntegrity("sha384-EHgRfTYf/UVwKC7GZSYXRKe6qpHVG+k4h3ZFyCtnLSgDj54TTaQpruS8s28W61Ct", "sha384-ne0BPbnDkNs2i0EKuWMke0Q8NkB7XqFrDCxlHA1gO8VUa0+thFLqv7YL/y7fHfhF") .SetVersion(codeMirrorVersion); manifest .DefineStyle("codemirror-addon-display-fullscreen") .SetUrl("~/OrchardCore.Resources/Styles/codemirror/addon/display/fullscreen.min.css", "~/OrchardCore.Resources/Styles/codemirror/addon/display/fullscreen.css") .SetCdn(codeMirrorUrl + "addon/display/fullscreen.min.css", codeMirrorUrl + "addon/display/fullscreen.css") .SetCdnIntegrity("sha384-uuIczW2AGKADJpvg6YiNBJQWE7duDkgQDkndYEsbUGaLm8SPJZzlly6hcEo0aTlW", "sha384-+glu1jsbG+T5ocmkeMvIYh5w07IXKxmJZaCdkNbVfpEr3xi+M0gopFSR/oLKXxio") .SetVersion(codeMirrorVersion); manifest .DefineStyle("codemirror-addon-hint-show-hint") .SetUrl("~/OrchardCore.Resources/Styles/codemirror/addon/hint/show-hint.min.css", "~/OrchardCore.Resources/Styles/codemirror/addon/hint/show-hint.css") .SetCdn(codeMirrorUrl + "addon/hint/show-hint.min.css", codeMirrorUrl + "addon/hint/show-hint.css") .SetCdnIntegrity("sha384-qqTWkykzuDLx4yDYa7bVrwNwBHuqVvklDUMVaU4eezgNUEgGbP8Zv6i3u8OmtuWg", "sha384-ZZbLvEvLoXKrHo3Tkh7W8amMgoHFkDzWe8IAm1ZgxsG5y35H+fJCVMWwr0YBAEGA") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-addon-selection-active-line") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/selection/active-line.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/selection/active-line.js") .SetCdn(codeMirrorUrl + "addon/selection/active-line.min.js", codeMirrorUrl + "addon/selection/active-line.js") .SetCdnIntegrity("sha384-G0dW669yzC7wSAJf0Tqu4PyeHKXY0vAX9xZtaTPnK/+EHjtucblXS/5GHR55j1mx", "sha384-kKz13r+qZMgTNgXROGNHQ0/0/J1FtvIvRZ9yjOHo1YLUCd+KF8r9R+su/B+f6C0U") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-addon-display-autorefresh") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/display/autorefresh.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/display/autorefresh.js") .SetCdn(codeMirrorUrl + "addon/display/autorefresh.min.js", codeMirrorUrl + "addon/display/autorefresh.js") .SetCdnIntegrity("sha384-pn83o6MtS8kicn/sV6AhRaBqXQ5tau8NzA2ovcobkcc1uRFP7D8CMhRx231QwKST", "sha384-5wrQkkCzj5dJInF+DDDYjE1itTGaIxO+TL6gMZ2eZBo9OyWLczkjolFX8kixX/9X") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-addon-display-fullscreen") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/display/fullscreen.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/display/fullscreen.js") .SetCdn(codeMirrorUrl + "addon/display/fullscreen.min.js", codeMirrorUrl + "addon/display/fullscreen.js") .SetCdnIntegrity("sha384-3dGKkIriAGFyl5yMW9W6ogQCxVZgAR4oBBNPex1FNAl70+iLE0LpRwJCFCKkKl4l", "sha384-kuwHYEheDAp0NlPye2VXyxJ6J54CeVky9tH+e0mn6/gP4PJ50MF4FGKkrGAxIyCW") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-addon-edit-closetag") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/edit/closetag.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/display/fullscreen.js") .SetCdn(codeMirrorUrl + "addon/edit/closetag.min.js", codeMirrorUrl + "addon/edit/closetag.js") .SetCdnIntegrity("sha384-MWjKXjBsdRdF/BS6d0C/gumTxJxeqVUfriOb0LJTP2/NmkFYz8nSY/AJZppi+fRQ", "sha384-jR3Qxv7tHnv4TLLymC5s7Tl3aQGWNayqUHHBNxnnA/NjIyewLGSmNPQuDcMxnPKY") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-addon-hint-show-hint") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/hint/show-hint.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/hint/show-hint.js") .SetCdn(codeMirrorUrl + "addon/hint/show-hint.min.js", codeMirrorUrl + "addon/hint/show-hint.js") .SetCdnIntegrity("sha384-pFJF3GAZ6kaXHIeHTe2ecWeeBzFVuVF2QXccnazviREKim+uL3lm/voyytwY71bQ", "sha384-RzmY798hMmzDwNL4d5ZkSaygnsA6Rq2ROY7awxW1t9NV+8XPpnXivbcD+EI1r2Ij") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-addon-hint-sql-hint") .SetDependencies("codemirror-addon-hint-show-hint") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/hint/sql-hint.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/hint/sql-hint.js") .SetCdn(codeMirrorUrl + "addon/hint/sql-hint.min.js", codeMirrorUrl + "addon/hint/sql-hint.js") .SetCdnIntegrity("sha384-s+MbgbBZ249zyKdf4x7EwFAXXLbK0yk3eVVd+GpWeSsd4SjKiC/H1GxT/gMZB9Lx", "sha384-CnIooEvOzoAsliTWO+BYwoTVFeqhBCympzDuwlhTlP7TWeAHB2h4Q0OeOqVkL5dP") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-addon-mode-multiplex") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/mode/multiplex.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/mode/multiplex.js") .SetCdn(codeMirrorUrl + "addon/mode/multiplex.min.js", codeMirrorUrl + "addon/mode/multiplex.js") .SetCdnIntegrity("sha384-/JERLTKv3TwdPmZug8zm4X4NktLA8QsyjIybae/5aO9MeLkyzyP4NN3wpabXsbdq", "sha384-kZLDZbOp+G4qzGg8vy4P5DlIIPPnoSdO6G1puag9t/QjRDDfeANKKNIhMA+Yq+J1") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-addon-mode-simple") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/addon/mode/simple.min.js", "~/OrchardCore.Resources/Scripts/codemirror/addon/mode/simple.js") .SetCdn(codeMirrorUrl + "addon/mode/simple.min.js", codeMirrorUrl + "addon/mode/simple.js") .SetCdnIntegrity("sha384-EnymP1wIjc1AsZM6f29pxT0z5VkDoUJ22Jx34tiDzvRvy7OiqviBVtw/evVWEaT5", "sha384-Foc3817k/CG8PVkPQtWgpBPcO0w2Noaep609FulvP/EwVUhv4JqNakD8UAORWA/s") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-mode-css") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/css/css.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/css/css.js") .SetCdn(codeMirrorUrl + "mode/css/css.min.js", codeMirrorUrl + "mode/css/css.js") .SetCdnIntegrity("sha384-IkA5dwHN+lGrX/ZxO+sktNF+wGXL06QJAVUag0yEBb7QDNM59YKsI5qWYc7SKPtN", "sha384-bZYw0+OmoeFivaUT4/YNXLYKX7+hahkNA64LcETceaOhHFqbNqetu6c0vIhMPqXy") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-mode-htmlmixed") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/htmlmixed/htmlmixed.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/htmlmixed/htmlmixed.js") .SetCdn(codeMirrorUrl + "mode/htmlmixed/htmlmixed.min.js", codeMirrorUrl + "mode/htmlmixed/htmlmixed.js") .SetCdnIntegrity("sha384-C4oV1iL5nO+MmIRm+JoD2sZ03wIafv758LRO92kyg7AFvpvn8oQAra4g3mrw5+53", "sha384-vM5dpc39AxwLWe2WC/4ZNAw81WDwmu5CoPw9uw7XfDMLtUKrHFEsz4ofeaRWVIEP") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-mode-javascript") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/javascript/javascript.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/javascript/javascript.js") .SetCdn(codeMirrorUrl + "mode/javascript/javascript.min.js", codeMirrorUrl + "mode/javascript/javascript.js") .SetCdnIntegrity("sha384-vuxa41RhbUbqWstjjDqkCzQ5jZ9NybJWK0M1ntCoO8V5YVOPUjJ0Xz65kxAIkAnO", "sha384-//Bn5ksI7NmNsgwMl5TEImM0XBhLe/SAhg/OlWtAvE7anPJo3bDKN1adMUKG3qpg") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-mode-sql") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/sql/sql.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/sql/sql.js") .SetCdn(codeMirrorUrl + "mode/sql/sql.min.js", codeMirrorUrl + "mode/sql/sql.js") .SetCdnIntegrity("sha384-LnNQf6kxsWRUR1gIJto9AsloUow3HzeE1WLOBNFh2snAy3cTlGK8VFVw7v5TvFfN", "sha384-x+5PPG+/GfZmN/pSGwtvsFLaYMv8FnmX+xpWs1BTM3RNGrISCEMF9gatNn4tSuhl") .SetVersion(codeMirrorVersion); manifest .DefineScript("codemirror-mode-xml") .SetUrl("~/OrchardCore.Resources/Scripts/codemirror/mode/xml/xml.min.js", "~/OrchardCore.Resources/Scripts/codemirror/mode/xml/xml.js") .SetCdn(codeMirrorUrl + "mode/xml/xml.min.js", codeMirrorUrl + "mode/xml/xml.js") .SetCdnIntegrity("sha384-c3NXS9t3umqhEaScj8N4yz8EafssGBhJLbwjhLgON3PHr5AUoeKQWrdngj9sxoDJ", "sha384-fnrvkyvE4Ut04qDu6kFoulvy6uuBXr8YoD8rk13BCDTODAyMB5HTeBHKV+oq86Cl") .SetVersion(codeMirrorVersion); manifest .DefineStyle("font-awesome") .SetUrl("~/OrchardCore.Resources/Styles/font-awesome.min.css", "~/OrchardCore.Resources/Styles/font-awesome.css") .SetCdn("https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css", "https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css") .SetCdnIntegrity("sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN", "sha384-FckWOBo7yuyMS7In0aXZ0aoVvnInlnFMwCv77x9sZpFgOonQgnBj1uLwenWVtsEj") .SetVersion("4.7.0"); manifest .DefineStyle("font-awesome") .SetUrl("~/OrchardCore.Resources/Vendor/fontawesome-free/css/all.min.css", "~/OrchardCore.Resources/Vendor/fontawesome-free/css/all.css") .SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.min.css", "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/css/all.css") .SetCdnIntegrity("sha384-DyZ88mC6Up2uqS4h/KRgHuoeGwBcD4Ng9SiP4dIRy0EXTlnuz47vAwmeGwVChigm", "sha384-7rgjkhkxJ95zOzIjk97UrBOe14KgYpH9+zQm5BdgzjQELBU6kHf4WwoQzHfTx5sw") .SetVersion("5.15.4"); manifest .DefineScript("font-awesome") .SetUrl("~/OrchardCore.Resources/Vendor/fontawesome-free/js/all.min.js", "~/OrchardCore.Resources/Vendor/fontawesome-free/js/all.js") .SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/js/all.min.js", "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/js/all.js") .SetCdnIntegrity("sha384-rOA1PnstxnOBLzCLMcre8ybwbTmemjzdNlILg8O7z1lUkLXozs4DHonlDtnE7fpc", "sha384-HfU7cInvKb8zxQuLKtKr/suuRgcSH1OYsdJU+8lGA/t8nyNgdJF09UIkRzg1iefj") .SetVersion("5.15.4"); manifest .DefineScript("font-awesome-v4-shims") .SetUrl("~/OrchardCore.Resources/Vendor/fontawesome-free/js/v4-shims.min.js", "~/OrchardCore.Resources/Vendor/fontawesome-free/js/v4-shims.js") .SetCdn("https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/js/v4-shims.min.js", "https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.4/js/v4-shims.js") .SetCdnIntegrity("sha384-bx00wqJq+zY9QLCMa/zViZPu1f0GJ3VXwF4GSw3GbfjwO28QCFr4qadCrNmJQ/9N", "sha384-SGuqaGE4bcW7Xl5T06BsUPUA91qaNtT53uGOcGpavQMje3goIFJbDsC0VAwtgL5g") .SetVersion("5.15.4"); manifest .DefineScript("jquery-resizable") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/jquery-resizable.min.js", "~/OrchardCore.Resources/Scripts/jquery-resizable.js") .SetCdn("https://cdn.jsdelivr.net/npm/jquery-resizable-dom@0.35.0/dist/jquery-resizable.min.js") .SetCdnIntegrity("sha384-1LMjDEezsSgzlRgsyFIAvLW7FWSdFIHqBGjUa+ad5EqtK1FORC8XpTJ/pahxj5GB", "sha384-0yk9X0IG0cXxuN9yTTkps/3TNNI9ZcaKKhh8dgqOEAWGXxIYS5xaY2as6b32Ov3P") .SetVersion("0.35.0"); manifest .DefineStyle("trumbowyg") .SetUrl("~/OrchardCore.Resources/Styles/trumbowyg.min.css", "~/OrchardCore.Resources/Styles/trumbowyg.css") .SetCdn("https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/ui/trumbowyg.min.css", "https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/ui/trumbowyg.css") .SetCdnIntegrity("sha384-kTb2zOBw/Vng2V8SH/LF2llnbNnFpSMVTOrSN0W8Z0zzE8LMM+w/vFqhD9b+esLV", "sha384-qaIYw5IcvXvWBzXq2NPvCMucQerh0hReNg45Qas5X71KWzZmGuPp+VTW5zywbg0x") .SetVersion("2.25.1"); manifest .DefineScript("trumbowyg") .SetDependencies("jquery-resizable") .SetUrl("~/OrchardCore.Resources/Scripts/trumbowyg.min.js", "~/OrchardCore.Resources/Scripts/trumbowyg.js") .SetCdn("https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/trumbowyg.min.js", "https://cdn.jsdelivr.net/npm/trumbowyg@2.25.1/dist/trumbowyg.js") .SetCdnIntegrity("sha384-wwt6vSsdmnPNAuXp11Jjm37wAA+b/Rm33Jhd3QE/5E4oDLeNoCTLU3kxQYsdOtdW", "sha384-N2uP/HqSD9qptuEGY2J1Iq0G5jqaYUcuMGUnyWiS6giy4adYptw2Co8hT7LQJKcT") .SetVersion("2.25.1"); manifest .DefineScript("trumbowyg-shortcodes") .SetDependencies("trumbowyg") .SetUrl("~/OrchardCore.Resources/Scripts/trumbowyg.shortcodes.min.js", "~/OrchardCore.Resources/Scripts/trumbowyg.shortcodes.js") .SetVersion("1.0.0"); manifest .DefineStyle("trumbowyg-plugins") .SetDependencies("trumbowyg") .SetUrl("~/OrchardCore.Resources/Styles/trumbowyg-plugins.min.css", "~/OrchardCore.Resources/Styles/trumbowyg-plugins.css") .SetVersion("2.25.1"); manifest .DefineScript("trumbowyg-plugins") .SetDependencies("trumbowyg") .SetUrl("~/OrchardCore.Resources/Scripts/trumbowyg-plugins.min.js", "~/OrchardCore.Resources/Scripts/trumbowyg-plugins.js") .SetVersion("2.25.1"); manifest .DefineScript("vuejs") .SetUrl("~/OrchardCore.Resources/Scripts/vue.min.js", "~/OrchardCore.Resources/Scripts/vue.js") .SetCdn("https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js", "https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js") .SetCdnIntegrity("sha384-ULpZhk1pvhc/UK5ktA9kwb2guy9ovNSTyxPNHANnA35YjBQgdwI+AhLkixDvdlw4", "sha384-t1tHLsbM7bYMJCXlhr0//00jSs7ZhsAhxgm191xFsyzvieTMCbUWKMhFg9I6ci8q") .SetVersion("2.6.14"); manifest .DefineScript("vue-multiselect") .SetDependencies("vuejs") .SetUrl("~/OrchardCore.Resources/Scripts/vue-multiselect.min.js", "~/OrchardCore.Resources/Scripts/vue-multiselect.min.js") .SetCdn("https://cdn.jsdelivr.net/npm/vue-multiselect@2.1.6/dist/vue-multiselect.min.js", "https://cdn.jsdelivr.net/npm/vue-multiselect@2.1.6/dist/vue-multiselect.min.js") .SetCdnIntegrity("sha384-a4eXewRTYCwYdFtSnMCZTNtiXrfdul6aQdueRgHPAx2y1Ldp0QaFdCTpOx0ycsXU", "sha384-a4eXewRTYCwYdFtSnMCZTNtiXrfdul6aQdueRgHPAx2y1Ldp0QaFdCTpOx0ycsXU") .SetVersion("2.1.6"); manifest .DefineStyle("vue-multiselect") .SetUrl("~/OrchardCore.Resources/Styles/vue-multiselect.min.css", "~/OrchardCore.Resources/Styles/vue-multiselect.min.css") .SetCdn("https://cdn.jsdelivr.net/npm/vue-multiselect@2.1.6/dist/vue-multiselect.min.css", "https://cdn.jsdelivr.net/npm/vue-multiselect@2.1.6/dist/vue-multiselect.min.css") .SetCdnIntegrity("sha384-PPH/T7V86Z1+B4eMPef4FJXLD5fsTpObWoCoK3CiNtSX7aji+5qxpOCn1f2TDYAM", "sha384-PPH/T7V86Z1+B4eMPef4FJXLD5fsTpObWoCoK3CiNtSX7aji+5qxpOCn1f2TDYAM") .SetVersion("2.1.6"); manifest .DefineScript("Sortable") .SetUrl("~/OrchardCore.Resources/Scripts/Sortable.min.js", "~/OrchardCore.Resources/Scripts/Sortable.js") .SetCdn("https://cdn.jsdelivr.net/npm/sortablejs@1.14.0/Sortable.min.js", "https://cdn.jsdelivr.net/npm/sortablejs@1.14.0/Sortable.js") .SetCdnIntegrity("sha384-vxc713BCZYoMxC6DlBK6K4M+gLAS8+63q7TtgB2+KZVn8GNafLKZCJ7Wk2S6ZEl1", "sha384-6dbyp5R22OLsNh2CMeCLIc+s0ZPLpCtBG2f38vvi5ghQIfUvVHIzKpz2S3qLx83I") .SetVersion("1.14.0"); manifest .DefineScript("vuedraggable") .SetDependencies("vuejs", "Sortable") .SetUrl("~/OrchardCore.Resources/Scripts/vuedraggable.umd.min.js", "~/OrchardCore.Resources/Scripts/vuedraggable.umd.js") .SetCdn("https://cdn.jsdelivr.net/npm/vuedraggable@2.24.3/dist/vuedraggable.umd.min.js", "https://cdn.jsdelivr.net/npm/vuedraggable@2.24.3/dist/vuedraggable.umd.js") .SetCdnIntegrity("sha384-qUA1xXJiX23E4GOeW/XHtsBkV9MUcHLSjhi3FzO08mv8+W8bv5AQ1cwqLskycOTs", "sha384-+jB9vXc/EaIJTlNiZG2tv+TUpKm6GR9HCRZb3VkI3lscZWqrCYDbX2ZXffNJldL9") .SetVersion("2.24.3"); manifest .DefineScript("js-cookie") .SetDependencies("jQuery") .SetUrl("~/OrchardCore.Resources/Scripts/js.cookie.min.js", "~/OrchardCore.Resources/Scripts/js.cookie.js") .SetCdn("https://cdn.jsdelivr.net/npm/js-cookie@3.0.1/dist/js.cookie.min.js", "https://cdn.jsdelivr.net/npm/js-cookie@3.0.1/dist/js.cookie.js") .SetCdnIntegrity("sha384-ETDm/j6COkRSUfVFsGNM5WYE4WjyRgfDhy4Pf4Fsc8eNw/eYEMqYZWuxTzMX6FBa", "sha384-wAGdUDEOVO9JhMpvNh7mkYd0rL2EM0bLb1+VY5R+jDfVBxYFJNfzkinHfbRfxT2s") .SetVersion("3.0.1"); manifest .DefineScript("monaco-loader") .SetUrl("~/OrchardCore.Resources/Scripts/monaco/vs/loader.js") .SetPosition(ResourcePosition.Last) .SetVersion(monacoEditorVersion); manifest .DefineScript("monaco") .SetAttribute("data-tenant-prefix", _tenantPrefix) .SetUrl("~/OrchardCore.Resources/Scripts/monaco/ocmonaco.js") .SetDependencies("monaco-loader") .SetVersion(monacoEditorVersion); return manifest; } public void Configure(ResourceManagementOptions options) { options.ResourceManifests.Add(BuildManifest()); var settings = _siteService.GetSiteSettingsAsync().GetAwaiter().GetResult(); switch (settings.ResourceDebugMode) { case ResourceDebugMode.Enabled: options.DebugMode = true; break; case ResourceDebugMode.Disabled: options.DebugMode = false; break; case ResourceDebugMode.FromConfiguration: options.DebugMode = !_env.IsProduction(); break; } options.UseCdn = settings.UseCdn; options.CdnBaseUrl = settings.CdnBaseUrl; options.AppendVersion = settings.AppendVersion; options.ContentBasePath = _httpContextAccessor.HttpContext.Request.PathBase.Value; } } }
73.21
209
0.673624
[ "BSD-3-Clause" ]
Ranger1230/OrchardCore
src/OrchardCore.Modules/OrchardCore.Resources/ResourceManagementOptionsConfiguration.cs
36,605
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Remotion.Linq.Clauses; namespace Lucene.Net.Linq.Translation.ResultOperatorHandlers { internal abstract class ResultOperatorHandler { public abstract IEnumerable<Type> SupportedTypes { get; } public abstract void Accept(ResultOperatorBase resultOperator, LuceneQueryModel model); } internal abstract class ResultOperatorHandler<TOperator> : ResultOperatorHandler where TOperator : ResultOperatorBase { private readonly MethodInfo genericMethod; protected ResultOperatorHandler() { var methods = GetType().GetMethods(BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.NonPublic); genericMethod = methods.Single(m => m.Name == "AcceptInternal"); } public sealed override IEnumerable<Type> SupportedTypes { get { return new[] {typeof (TOperator)}; } } public sealed override void Accept(ResultOperatorBase resultOperator, LuceneQueryModel model) { genericMethod.Invoke(this, new object[] {resultOperator, model}); } protected abstract void AcceptInternal(TOperator resultOperator, LuceneQueryModel model); } }
35.210526
124
0.686846
[ "Apache-2.0" ]
tamasflamich/Lucene.Net.Linq
source/Lucene.Net.Linq/Translation/ResultOperatorHandlers/ResultOperatorHandler.cs
1,338
C#
//////////////////////////////////////////////////////////////////////////////// // ________ _____ __ // / _____/_______ _____ ____ ____ _/ ____\__ __ | | // / \ ___\_ __ \\__ \ _/ ___\_/ __ \\ __\| | \| | // \ \_\ \| | \/ / __ \_\ \___\ ___/ | | | | /| |__ // \______ /|__| (____ / \___ >\___ >|__| |____/ |____/ // \/ \/ \/ \/ // ============================================================================= // Designed & Developed by Brad Jones <brad @="bjc.id.au" /> // ============================================================================= //////////////////////////////////////////////////////////////////////////////// namespace Graceful.Tests.Models { [Connection(@"BOGUS CS - DONT WANT TO BE INCLUDED IN GLOBAL CTX!")] public class EqualityExpressionTest : Model<EqualityExpressionTest> { public string Foo { get; set; } } }
49.47619
80
0.290664
[ "MIT" ]
brad-jones/graceful
tests/Graceful.Tests/Models/EqualityExpressionTest.cs
1,039
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:2.0.50727.4952 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace cam_aforge1.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("cam_aforge1.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static System.Drawing.Bitmap fire_alarm_cartoon { get { object obj = ResourceManager.GetObject("fire-alarm-cartoon", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap fire_symbol { get { object obj = ResourceManager.GetObject("fire symbol", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap no_smoking_symbol { get { object obj = ResourceManager.GetObject("no_smoking_symbol", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } internal static System.Drawing.Bitmap suvialance { get { object obj = ResourceManager.GetObject("suvialance", resourceCulture); return ((System.Drawing.Bitmap)(obj)); } } } }
42.554348
178
0.578289
[ "MIT" ]
siddhesh-vartak98/Fire-Detection-Using-Infrared-Images
Backup/Properties/Resources.Designer.cs
3,917
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace SubitonAPI.Migrations { public partial class AddUsers : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Users", columns: table => new { Id = table.Column<int>(nullable: false) .Annotation("Sqlite:Autoincrement", true), Username = table.Column<string>(nullable: true), PasswordHash = table.Column<byte[]>(nullable: true), PasswordSalt = table.Column<byte[]>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_Users", x => x.Id); }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Users"); } } }
31.484848
72
0.514918
[ "MIT" ]
Oktawian-L/Subiton
SubitonAPI/SubitonAPI/Migrations/20191006133549_AddUsers.cs
1,041
C#
namespace SkillMap.EventBus.Events; public abstract record IntegrationEvent : IIntegrationEvent { public string IntegrationEventId { get; } public string DomainEventId { get; } public string OccurredOn { get; } protected IntegrationEvent() { } protected IntegrationEvent(string integrationEventId, string domainEventId, string occurredOn) { IntegrationEventId = integrationEventId ?? Guid.NewGuid().ToString(); DomainEventId = domainEventId ?? throw new ArgumentNullException(nameof(domainEventId)); OccurredOn = occurredOn ?? DateTime.Now.DateToString(); } public abstract string EventName(); }
30.227273
98
0.721805
[ "MIT" ]
beyondnetPeru/Beyondnet.Product.SkillMap
src/BuildingBlocks/EventBus/SkillMap.EventBus/Events/IntegrationEvent.cs
667
C#
namespace SoundFingerprinting.Tests.Unit.LCS { using System.Linq; using System.Threading.Tasks; using NUnit.Framework; using SoundFingerprinting.Data; using SoundFingerprinting.DAO; using SoundFingerprinting.DAO.Data; using SoundFingerprinting.Query; [TestFixture] public class GroupedQueryResultTest { [Test] public void ShouldAccumulateResults() { int runs = 1000; var groupedQueryResults = new GroupedQueryResults(5d); var references = new[] { 1, 2, 3, 4, 5 }.Select(id => new ModelReference<int>(id)).ToArray(); Parallel.For(0, runs, i => { var hashed = new HashedFingerprint(new int[0], (uint)i, i * 0.05f, new string[0]); var candidate = new SubFingerprintData(new int[0], (uint)i, i * 0.07f, Enumerable.Empty<string>(), new ModelReference<uint>((uint)i), references[i % references.Length]); groupedQueryResults.Add(hashed, candidate, i); }); Assert.IsTrue(groupedQueryResults.ContainsMatches); for(int i = 0; i < references.Length; ++i) { int perTrack = runs / references.Length; int ham = (perTrack - 1) * runs / 2 + perTrack * i; Assert.AreEqual(ham, groupedQueryResults.GetHammingSimilaritySumForTrack(references[i])); } var modelReferences = groupedQueryResults.GetTopTracksByHammingSimilarity(references.Length * 2).ToList(); for (int i = 0; i < references.Length; ++i) { Assert.AreEqual(references[references.Length - i - 1], modelReferences[i]); } var bestMatch = groupedQueryResults.GetBestMatchForTrack(references.Last()); Assert.AreEqual((runs - 1) * 0.05f, bestMatch.QueryMatchAt, 0.000001); Assert.AreEqual((runs - 1) * 0.07f, bestMatch.TrackMatchAt, 0.000001); for (int i = 0; i < references.Length; ++i) { var matchedWith = groupedQueryResults.GetMatchesForTrack(references[i]).ToList(); Assert.AreEqual(runs / references.Length, matchedWith.Count); } } [Test] public void MatchesShouldBeOrderedByQueryAt() { int runs = 1000; var groupedQueryResults = new GroupedQueryResults(5d); var reference = new ModelReference<int>(1); Parallel.For(0, runs, i => { var hashed = new HashedFingerprint(new int[0], (uint)i, i, new string[0]); var candidate = new SubFingerprintData(new int[0], (uint)i, runs - i, Enumerable.Empty<string>(), new ModelReference<uint>((uint)i), reference); groupedQueryResults.Add(hashed, candidate, i); }); var matchedWith = groupedQueryResults.GetMatchesForTrack(reference); var ordered = matchedWith.Select(with => (int)with.QueryMatchAt).ToList(); CollectionAssert.AreEqual(Enumerable.Range(0, runs), ordered); } } }
39.05
185
0.59411
[ "MIT" ]
Nekromancer/soundfingerprinting
src/SoundFingerprinting.Tests/Unit/LCS/GroupedQueryResultTest.cs
3,126
C#
using System; using System.Net.Http; using System.Net.Http.Headers; using Microsoft.Extensions.Options; using ZendeskApi.Client.Extensions; using ZendeskApi.Client.Options; namespace ZendeskApi.Client { public class ZendeskApiClient : IZendeskApiClient { private readonly Func<HttpMessageHandler> _httpMessageHandlerFactory; private readonly ZendeskOptions _options; public ZendeskApiClient(IOptions<ZendeskOptions> options, Func<HttpMessageHandler> httpMessageHandlerFactory) : this(options) { _httpMessageHandlerFactory = httpMessageHandlerFactory; } public ZendeskApiClient(IOptions<ZendeskOptions> options) { _options = options.Value; _httpMessageHandlerFactory = () => { var handler = new HttpClientHandler(); if (handler.SupportsAutomaticDecompression) { handler.AutomaticDecompression = System.Net.DecompressionMethods.GZip | System.Net.DecompressionMethods.Deflate; } return handler; }; } public HttpClient CreateClient(string resource = null) { resource = resource?.Trim('/'); if (!string.IsNullOrEmpty(resource)) { resource = resource + "/"; } var handler = _httpMessageHandlerFactory(); var client = new HttpClient(handler) { BaseAddress = new Uri($"{_options.EndpointUri}/{resource}"), }; var authorizationHeader = _options.GetAuthorizationHeader(); client.DefaultRequestHeaders.Add("Authorization", authorizationHeader); client.DefaultRequestHeaders .Accept .Add(new MediaTypeWithQualityHeaderValue("application/json")); if (_options.Timeout != null) { client.Timeout = _options.Timeout.Value; } return client; } } }
30.382353
132
0.597773
[ "Apache-2.0" ]
AOOlivares/ZendeskApiClient
src/ZendeskApi.Client/ZendeskApiClient.cs
2,066
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT license. using AuthJanitor.UI.Shared.Models; using AuthJanitor.EventSinks; using AuthJanitor.IdentityServices; using AuthJanitor.Providers; using AuthJanitor.SecureStorage; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; using AuthJanitor.DataStores; namespace AuthJanitor { public class TaskExecutionMetaService { private readonly IDataStore<ManagedSecret> _managedSecrets; private readonly IDataStore<RekeyingTask> _rekeyingTasks; private readonly IDataStore<Resource> _resources; private readonly ISecureStorage _secureStorageProvider; private readonly ILogger<TaskExecutionMetaService> _logger; private readonly IServiceProvider _serviceProvider; private readonly ProviderManagerService _providerManagerService; private readonly EventDispatcherService _eventDispatcherService; private readonly IIdentityService _identityService; private readonly AuthJanitorService _authJanitorService; public TaskExecutionMetaService( ILogger<TaskExecutionMetaService> logger, IServiceProvider serviceProvider, EventDispatcherService eventDispatcherService, IIdentityService identityService, ProviderManagerService providerManagerService, IDataStore<ManagedSecret> managedSecrets, IDataStore<RekeyingTask> rekeyingTasks, IDataStore<Resource> resources, ISecureStorage secureStorageProvider, AuthJanitorService authJanitorService) { _logger = logger; _serviceProvider = serviceProvider; _eventDispatcherService = eventDispatcherService; _identityService = identityService; _providerManagerService = providerManagerService; _managedSecrets = managedSecrets; _rekeyingTasks = rekeyingTasks; _resources = resources; _secureStorageProvider = secureStorageProvider; _authJanitorService = authJanitorService; } public async Task CacheBackCredentialsForTaskIdAsync(Guid taskId, CancellationToken cancellationToken) { var task = await _rekeyingTasks.GetOne(taskId, cancellationToken); if (task == null) throw new KeyNotFoundException("Task not found"); if (task.ConfirmationType != TaskConfirmationStrategies.AdminCachesSignOff) throw new InvalidOperationException("Task does not persist credentials"); if (_secureStorageProvider == null) throw new NotSupportedException("Must register an ISecureStorageProvider"); var credentialId = await _identityService.GetAccessTokenOnBehalfOfCurrentUserAsync() .ContinueWith(t => _secureStorageProvider.Persist(task.Expiry, t.Result)) .Unwrap(); task.PersistedCredentialId = credentialId; task.PersistedCredentialUser = _identityService.UserName; await _rekeyingTasks.Update(task, cancellationToken); } public async Task<AccessTokenCredential> GetTokenCredentialAsync(Guid taskId, CancellationToken cancellationToken) { var task = await _rekeyingTasks.GetOne(taskId, cancellationToken); // Retrieve credentials for Task AccessTokenCredential credential = null; try { if (task.ConfirmationType == TaskConfirmationStrategies.AdminCachesSignOff) { if (task.PersistedCredentialId == default) throw new KeyNotFoundException("Cached sign-off is preferred but no credentials were persisted!"); if (_secureStorageProvider == null) throw new NotSupportedException("Must register an ISecureStorageProvider"); credential = await _secureStorageProvider.Retrieve<AccessTokenCredential>(task.PersistedCredentialId); } else if (task.ConfirmationType == TaskConfirmationStrategies.AdminSignsOffJustInTime) credential = await _identityService.GetAccessTokenOnBehalfOfCurrentUserAsync(); else if (task.ConfirmationType.UsesServicePrincipal()) credential = await _identityService.GetAccessTokenForApplicationAsync(); else throw new NotSupportedException("No Access Tokens could be generated for this Task!"); if (credential == null || string.IsNullOrEmpty(credential.AccessToken)) throw new InvalidOperationException("Access Token was found, but was blank or invalid"); credential.DisplayUserName = credential.Username; credential.DisplayEmail = credential.Username; if (task.ConfirmationType.UsesOBOTokens()) { if (!string.IsNullOrEmpty(task.PersistedCredentialUser)) credential.DisplayUserName = task.PersistedCredentialUser; else { credential.DisplayUserName = _identityService.UserName; credential.DisplayEmail = _identityService.UserEmail; } } return credential; } catch (Exception ex) { await _eventDispatcherService.DispatchEvent(AuthJanitorSystemEvents.RotationTaskAttemptFailed, nameof(TaskExecutionMetaService.ExecuteTask), task); throw ex; } } private TProvider DuplicateProvider<TProvider>(TProvider provider) where TProvider : IAuthJanitorProvider => _providerManagerService.GetProviderInstance(provider); public async Task ExecuteTask(Guid taskId, CancellationToken cancellationToken) { // Prepare record _logger.LogInformation("Retrieving task {TaskId}", taskId); var task = await _rekeyingTasks.GetOne(taskId, cancellationToken); task.RekeyingInProgress = true; // Create task to perform regular updates to UI (every 15s) _logger.LogInformation("Starting log update task"); var logUpdateCancellationTokenSource = new CancellationTokenSource(); var logUpdateTask = Task.Run(async () => { while (task.RekeyingInProgress) { await Task.Delay(15 * 1000); await _rekeyingTasks.Update(task, cancellationToken); } }, logUpdateCancellationTokenSource.Token); // Retrieve the secret configuration and its resources var secret = await _managedSecrets.GetOne(task.ManagedSecretId, cancellationToken); _logger.LogInformation("Retrieving resources for secret {SecretId}", secret.ObjectId); var resources = await _resources.Get(r => secret.ResourceIds.Contains(r.ObjectId), cancellationToken); var workflowCollection = await _authJanitorService.ExecuteAsync( secret.ValidPeriod, async (pwac) => { if (!task.Attempts.Any(a => a.StartedExecution == pwac.StartedExecution)) { task.Attempts.Add(pwac); await _rekeyingTasks.Update(task, cancellationToken); } }, resources.Select(r => { TokenSources tokenSource = TokenSources.Unknown; string tokenParameter = string.Empty; switch (secret.TaskConfirmationStrategies) { case TaskConfirmationStrategies.AdminSignsOffJustInTime: tokenSource = TokenSources.OBO; break; case TaskConfirmationStrategies.AdminCachesSignOff: tokenSource = TokenSources.Persisted; tokenParameter = task.PersistedCredentialId.ToString(); break; case TaskConfirmationStrategies.AutomaticRekeyingAsNeeded: case TaskConfirmationStrategies.AutomaticRekeyingScheduled: case TaskConfirmationStrategies.ExternalSignal: tokenSource = TokenSources.ServicePrincipal; break; } return new ProviderExecutionParameters() { ProviderType = r.ProviderType, ProviderConfiguration = r.ProviderConfiguration, AgentId = secret.ExecutingAgentId, TokenSource = tokenSource, TokenParameter = tokenParameter }; }).ToArray()); // Update Task record _logger.LogInformation("Completing task record"); task.RekeyingInProgress = false; task.RekeyingCompleted = (workflowCollection?.HasBeenExecuted).GetValueOrDefault(); task.RekeyingCompleted = (workflowCollection?.HasBeenExecutedSuccessfully).GetValueOrDefault(); await _rekeyingTasks.Update(task, cancellationToken); if (workflowCollection.HasBeenExecutedSuccessfully) { if (task.ConfirmationType.UsesOBOTokens()) await _eventDispatcherService.DispatchEvent(AuthJanitorSystemEvents.RotationTaskCompletedManually, nameof(TaskExecutionMetaService.ExecuteTask), task); else await _eventDispatcherService.DispatchEvent(AuthJanitorSystemEvents.RotationTaskCompletedAutomatically, nameof(TaskExecutionMetaService.ExecuteTask), task); } else await _eventDispatcherService.DispatchEvent(AuthJanitorSystemEvents.RotationTaskAttemptFailed, nameof(TaskExecutionMetaService.ExecuteTask), task); } } }
48.27907
176
0.627842
[ "MIT" ]
ConnectionMaster/AuthJanitor
src/AuthJanitor.AspNet/TaskExecutionMetaService.cs
10,382
C#
using System; using System.Collections.Generic; using System.Data.Common; namespace RepoDb.Contexts.Execution { /// <summary> /// /// </summary> internal class MergeExecutionContext { /// <summary> /// /// </summary> public string CommandText { get; set; } /// <summary> /// /// </summary> public IEnumerable<DbField> InputFields { get; set; } /// <summary> /// /// </summary> public Action<DbCommand, object> ParametersSetterFunc { get; set; } /// <summary> /// /// </summary> public Action<object, object> IdentityPropertySetterFunc { get; set; } } }
21.666667
78
0.525874
[ "Apache-2.0" ]
RepoDb/RepoDb
RepoDb.Core/RepoDb/Contexts/Execution/MergeExecutionContext.cs
717
C#
//------------------------------------------------------------------------------ // <auto-generated> // 이 코드는 도구를 사용하여 생성되었습니다. // 런타임 버전:4.0.30319.42000 // // 파일 내용을 변경하면 잘못된 동작이 발생할 수 있으며, 코드를 다시 생성하면 // 이러한 변경 내용이 손실됩니다. // </auto-generated> //------------------------------------------------------------------------------ namespace Topmost.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.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; } } } }
37.333333
151
0.560516
[ "MIT" ]
RyuaNerin/Topmost
Properties/Settings.Designer.cs
1,144
C#
using System; using StoreModel; using StoreController; using System.Collections.Generic; using System.Collections; using StoreData; using Serilog; namespace StoreView.Menus { /// <summary> /// This class serves as a host for any search features involving products. /// This includes both general product searching to browse the catalog, as well as searching for products to add to a cart. /// </summary> public class ProductSearch : IProductSearch { private IProductBL _productBL; private ICartProductsBL _cartProductsBL; private IInventoryBL _inventoryBL; public ProductSearch(IProductBL productBL, ICartProductsBL cartProductsBL, IInventoryBL inventoryBL) { _productBL = productBL; _cartProductsBL = cartProductsBL; _inventoryBL = inventoryBL; } public void Start() { Console.Clear(); AsciiHeader.AsciiHead(); Boolean stay = true; Console.WriteLine("Welcome to the product search portal!"); do { Console.WriteLine("Enter a product name to view details about a specific product."); Console.WriteLine("Type in \"all\" to view a list of all products"); Console.WriteLine("Type in \"exit\" to return to the manager menu."); String userInput = Console.ReadLine(); switch (userInput) { case "exit": //return to manager menu - value "true" should still be assigned to manager menu loop. stay = false; Console.Clear(); break; case "all": //return a list of all customers - BUILD IN METHOD TO INTERACT WITH BL GetAllProducts(); break; default: //return specified string values of names retrieved from DB GetSearchedProducts(userInput); break; } } while (stay); } public void Start(Location location, int cartID, List<Inventory> inventories) { Console.Clear(); AsciiHeader.AsciiHead(); Boolean stay = true; do { Console.WriteLine("Enter a product name, or manufacturer to filter the list of products!."); Console.WriteLine("Once you find a product, specify quantity and confirm if you would like to add that product to the order."); Console.WriteLine("Type in \"all\" to view a list of all products"); Console.WriteLine("Type in \"exit\" to finish the product ordering process."); String userInput = Console.ReadLine(); switch (userInput) { case "exit": //return to manager menu - value "true" should still be assigned to manager menu loop. //we will process the cartproduct list here adn return?? stay = false; break; case "all": //return a list of all products GetAllProducts(); break; default: GetFilteredProductsForProcessing(userInput, cartID, inventories, location); break; } } while (stay); } public void GetAllProducts() { LineSeparator line = new LineSeparator(); List<Product> productList = _productBL.GetProduct(); foreach (Product product in productList) { line.LineSeparate(); Console.WriteLine(product); } line.LineSeparate(); } public void GetSearchedProducts(string searchTerm) { int tracker = 0; LineSeparator line = new LineSeparator(); List<Product> productList = _productBL.GetProduct(); foreach (Product product in productList) { if (product.ProductName.Contains(searchTerm) || product.Manufacturer.Contains(searchTerm) || product.ProductID.ToString().Contains(searchTerm)) { line.LineSeparate(); Console.WriteLine(product); tracker++; } } if (tracker == 0) { line.LineSeparate(); Console.WriteLine("No results found! Please double-check product spelling. \nThis system is Case Sensitive :)"); } line.LineSeparate(); } public void GetFilteredProductsForProcessing(string searchTerm, int cartID, List<Inventory> inventories, Location location) { //keeps track of the product if only 1 product is found Product foundProduct = new Product(); //tracks how many products have been found given the search int tracker = 0; LineSeparator line = new LineSeparator(); //retrieves a list of all products List<Product> productList = _productBL.GetProduct(); //new list intended to filter products down to only those that exist in inventories for our location List<Product> filteredByInventoryProducts = new List<Product>(); //our list of filtered inventories List<Inventory> filteredByLocationInventories = new List<Inventory>(); //filter inventories to only those at our location //if the location ID of this inventory matches our stored location ID, then add it to the list of filtered locations foreach(Inventory i in inventories){ if (i.Location.LocationID == location.LocationID){ filteredByLocationInventories.Add(i); } } //filter products to display only those that exist in one of the found inventories //for each product that we've retrieved, make sure that the product ID matches a product ID stored in an inventory foreach(Product p in productList) { foreach(Inventory i in filteredByLocationInventories){ if (i.ProductID == p.ProductID){ filteredByInventoryProducts.Add(p); } } } foreach (Product product in filteredByInventoryProducts) { if (product.ProductName.Contains(searchTerm) || product.Manufacturer.Contains(searchTerm) || product.ProductID.ToString().Contains(searchTerm)) { line.LineSeparate(); Console.WriteLine(product); tracker++; //for the first found customer, store in our foundcustomer object, but don't do it again if(tracker == 1){ foundProduct.ProductID = product.ProductID; foundProduct.ProductName = product.ProductName; foundProduct.ProductDescription = product.ProductDescription; foundProduct.Manufacturer = product.Manufacturer; foundProduct.ProductPrice = product.ProductPrice; } } } if (tracker == 0) { line.LineSeparate(); Console.WriteLine("No results found! Please double-check customer name spelling. \nReminder: This search system is Case Sensitive :)"); } //if the tracker only happened once, that means one customer with the matching value was found, so we pass that customer reference //back out to our manager system :) if (tracker == 1) { line.LineSeparate(); Console.WriteLine("We have found one product from your search. Please see the details displayed above."); Console.WriteLine("Would you like to add this product to your cart?"); Console.WriteLine("[0] Yes"); Console.WriteLine("[1] No"); switch (Console.ReadLine()) { case "0": CartProducts cartProduct = new CartProducts(); List<Inventory> inventoriesFiltered = new List<Inventory>(); //we need to check if the specified inventory has said product in stock for the amount desired foreach (Inventory i in inventories){ if(i.ProductID == foundProduct.ProductID && i.InventoryLocation == location.LocationID) { inventoriesFiltered.Add(i); } } Inventory realInventory = inventoriesFiltered[0]; Console.WriteLine($"We currently have {realInventory.ProductQuantity} of these in stock at the {location.LocationName} location!"); Console.WriteLine("Please enter how many you would like to order: "); cartProduct.ProductCount = Int32.Parse(Console.ReadLine()); if (realInventory.ProductQuantity < cartProduct.ProductCount) { Console.WriteLine($"Sorry, we only have {realInventory.ProductQuantity} left in stock at {location.LocationName}.\nPlease enter a lower quantity"); Console.WriteLine("Press enter to continue."); break; } if (cartProduct.ProductCount <= 0) { Console.WriteLine("Sorry, you've entered an invalid value. Please try again"); Console.WriteLine("Press enter to continue."); Console.ReadLine(); break; } cartProduct.CartID = cartID; cartProduct.ProductID = foundProduct.ProductID; realInventory.ProductQuantity = realInventory.ProductQuantity - cartProduct.ProductCount.Value; Console.WriteLine($"current inventory value: {realInventory.ProductQuantity}"); _cartProductsBL.AddCartProduct(cartProduct); _inventoryBL.UpdateInventory(realInventory); Log.Information($"product added to cart {cartProduct.ProductID}"); Console.WriteLine("Product added to cart successfully!"); Console.WriteLine("Press enter to continue."); Console.ReadLine(); break; case "1": Console.WriteLine("Okay, please search again to find a different product. \nPress enter to continue."); Console.ReadLine(); break; default: Console.WriteLine("This is not a valid menu option!"); break; } } line.LineSeparate(); } } }
40.031034
171
0.530537
[ "MIT" ]
210215-USF-NET/Weston_Davidson-P0
StoreView/Menus/ProductSearch.cs
11,609
C#
namespace Reportr.IoC { /// <summary> /// Defines a contract for a dependency registrar /// </summary> public interface IDependencyRegistrar { /// <summary> /// Registers an implementation type against a specified type /// </summary> /// <typeparam name="TType">The registered type</typeparam> /// <typeparam name="TImpl">The implementation type</typeparam> void Register<TType, TImpl>() where TType : class where TImpl : class, TType; /// <summary> /// Registers an instance of the type specified /// </summary> /// <typeparam name="TType">The instance type</typeparam> /// <param name="instance">The instance to register</param> void RegisterInstance<TType>(TType instance) where TType : class; } }
33.88
73
0.600945
[ "MIT" ]
craigbridges/Reportr
src/Reportr/IoC/IDependencyRegistrar.cs
849
C#
using Newtonsoft.Json; namespace PersonalCapital.Response { public class HeaderOnlyResponse { [JsonProperty(PropertyName = "spHeader")] public HeaderResponse Header { get; set; } } }
21.2
50
0.679245
[ "MIT" ]
pcartwright81/PersonalCapitalApi
PersonalCapital/Response/HeaderOnlyResponse.cs
214
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.Aws.ElasticLoadBalancing.Outputs { [OutputType] public sealed class GetLoadBalancerHealthCheckResult { public readonly int HealthyThreshold; public readonly int Interval; public readonly string Target; public readonly int Timeout; public readonly int UnhealthyThreshold; [OutputConstructor] private GetLoadBalancerHealthCheckResult( int healthyThreshold, int interval, string target, int timeout, int unhealthyThreshold) { HealthyThreshold = healthyThreshold; Interval = interval; Target = target; Timeout = timeout; UnhealthyThreshold = unhealthyThreshold; } } }
26.428571
88
0.651351
[ "ECL-2.0", "Apache-2.0" ]
JakeGinnivan/pulumi-aws
sdk/dotnet/ElasticLoadBalancing/Outputs/GetLoadBalancerHealthCheckResult.cs
1,110
C#
using UnityEditor; using UnityEngine; using UnityEngine.InputSystem; namespace DyrdaDev.FirstPersonController { #if UNITY_EDITOR [InitializeOnLoad] #endif public class DivideVector2ByDeltaTimeProcessor : InputProcessor<Vector2> { #if UNITY_EDITOR static DivideVector2ByDeltaTimeProcessor() { Initialize(); } #endif [RuntimeInitializeOnLoadMethod] private static void Initialize() { InputSystem.RegisterProcessor<DivideVector2ByDeltaTimeProcessor>(); } /// <summary> /// Divides the value by the delta time. This makes the frame rate dependent input frame rate independent. /// </summary> /// <param name="value"></param> /// <param name="control"></param> /// <returns></returns> public override Vector2 Process(Vector2 value, InputControl control) { return value / Time.deltaTime; } } }
26.27027
114
0.634774
[ "MIT" ]
SariusGH/first-person-controller-for-unity
Packages/dev.dyrda.first-person-controller/Runtime/Utility/DivideVector2ByDeltaTimeProcessor.cs
974
C#