content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Diagnostics; using System.Linq; using System.Text; using Iced.Intel; namespace KeePassHax.Injector.Injection { internal class FrameworkV2Injector : FrameworkInjector { protected override string ClrVersion => "v2.0.50727"; } internal abstract class FrameworkInjector { protected abstract string ClrVersion { get; } public Action<string> Log { private get; set; } = s => { }; public void Inject(int pid, in InjectionArguments args, bool x86) { var hProc = Native.OpenProcess(Native.ProcessAccessFlags.AllForDllInject, false, pid); if (hProc == IntPtr.Zero) throw new Exception("Couldn't open process"); Log("Handle: " + hProc.ToInt32().ToString("X8")); var bindToRuntimeAddr = GetCorBindToRuntimeExAddress(pid, hProc, x86); Log("CurBindToRuntimeEx: " + bindToRuntimeAddr.ToInt64().ToString("X8")); var instructions = CreateStub(hProc, args.Path, args.TypeFull, args.Method, args.Argument, bindToRuntimeAddr, x86, ClrVersion); Log("Instructions to be injected:\n" + string.Join("\n", instructions)); var hThread = CodeInjectionUtils.RunRemoteCode(hProc, instructions, x86); Log("Thread handle: " + hThread.ToInt32().ToString("X8")); // TODO: option to wait until injected function returns? /* var success = Native.GetExitCodeThread(hThread, out IntPtr exitCode); Log("GetExitCode success: " + success); Log("Exit code: " + exitCode.ToInt32().ToString("X8")); */ Native.CloseHandle(hProc); } private static IntPtr GetCorBindToRuntimeExAddress(int pid, IntPtr hProc, bool x86) { var proc = Process.GetProcessById(pid); var mod = proc.Modules.OfType<ProcessModule>().FirstOrDefault(m => m.ModuleName.Equals("mscoree.dll", StringComparison.InvariantCultureIgnoreCase)); if (mod is null) throw new Exception("Couldn't find MSCOREE.DLL, arch mismatch?"); int fnAddr = CodeInjectionUtils.GetExportAddress(hProc, mod.BaseAddress, "CorBindToRuntimeEx", x86); return mod.BaseAddress + fnAddr; } private InstructionList CreateStub(IntPtr hProc, string asmPath, string typeFullName, string methodName, string args, IntPtr fnAddr, bool x86, string clrVersion) { const string buildFlavor = "wks"; // WorkStation var clsidClrRuntimeHost = new Guid(0x90F1A06E, 0x7712, 0x4762, 0x86, 0xB5, 0x7A, 0x5E, 0xBA, 0x6B, 0xDB, 0x02); var iidIclrRuntimeHost = new Guid(0x90F1A06C, 0x7712, 0x4762, 0x86, 0xB5, 0x7A, 0x5E, 0xBA, 0x6B, 0xDB, 0x02); var ppv = Alloc(IntPtr.Size); var riid = AllocBytes(iidIclrRuntimeHost.ToByteArray()); var rcslid = AllocBytes(clsidClrRuntimeHost.ToByteArray()); var pwszBuildFlavor = AllocString(buildFlavor); var pwszVersion = AllocString(clrVersion); var pReturnValue = Alloc(4); var pwzArgument = AllocString(args); var pwzMethodName = AllocString(methodName); var pwzTypeName = AllocString(typeFullName); var pwzAssemblyPath = AllocString(asmPath); var instructions = new InstructionList(); void AddCallR(Register r, params object[] callArgs) => CodeInjectionUtils.AddCallStub(instructions, r, callArgs, x86); void AddCallP(IntPtr fn, params object[] callArgs) => CodeInjectionUtils.AddCallStub(instructions, fn, callArgs, x86); if (x86) { // call CorBindToRuntimeEx AddCallP(fnAddr, pwszVersion, pwszBuildFlavor, (byte)0, rcslid, riid, ppv); // call ICLRRuntimeHost::Start instructions.Add(Instruction.Create(Code.Mov_r32_rm32, Register.EDX, new MemoryOperand(Register.None, ppv.ToInt32()))); instructions.Add(Instruction.Create(Code.Mov_r32_rm32, Register.EAX, new MemoryOperand(Register.EDX))); instructions.Add(Instruction.Create(Code.Mov_r32_rm32, Register.EAX, new MemoryOperand(Register.EAX, 0x0C))); AddCallR(Register.EAX, Register.EDX); // call ICLRRuntimeHost::ExecuteInDefaultAppDomain instructions.Add(Instruction.Create(Code.Mov_r32_rm32, Register.EDX, new MemoryOperand(Register.None, ppv.ToInt32()))); instructions.Add(Instruction.Create(Code.Mov_r32_rm32, Register.EAX, new MemoryOperand(Register.EDX))); instructions.Add(Instruction.Create(Code.Mov_r32_rm32, Register.EAX, new MemoryOperand(Register.EAX, 0x2C))); AddCallR(Register.EAX, Register.EDX, pwzAssemblyPath, pwzTypeName, pwzMethodName, pwzArgument, pReturnValue); instructions.Add(Instruction.Create(Code.Retnd)); } else { const int maxStackIndex = 3; const int stackOffset = 0x20; instructions.Add(Instruction.Create(Code.Sub_rm64_imm8, Register.RSP, stackOffset + maxStackIndex * 8)); // call CorBindToRuntimeEx AddCallP(fnAddr, pwszVersion, pwszBuildFlavor, 0, rcslid, riid, ppv); // call pClrHost->Start(); instructions.Add(Instruction.Create(Code.Mov_r64_imm64, Register.RCX, ppv.ToInt64())); instructions.Add(Instruction.Create(Code.Mov_r64_rm64, Register.RCX, new MemoryOperand(Register.RCX))); instructions.Add(Instruction.Create(Code.Mov_r64_rm64, Register.RAX, new MemoryOperand(Register.RCX))); instructions.Add(Instruction.Create(Code.Mov_r64_rm64, Register.RDX, new MemoryOperand(Register.RAX, 0x18))); AddCallR(Register.RDX, Register.RCX); // call pClrHost->ExecuteInDefaultAppDomain() instructions.Add(Instruction.Create(Code.Mov_r64_imm64, Register.RCX, ppv.ToInt64())); instructions.Add(Instruction.Create(Code.Mov_r64_rm64, Register.RCX, new MemoryOperand(Register.RCX))); instructions.Add(Instruction.Create(Code.Mov_r64_rm64, Register.RAX, new MemoryOperand(Register.RCX))); instructions.Add(Instruction.Create(Code.Mov_r64_rm64, Register.RAX, new MemoryOperand(Register.RAX, 0x58))); AddCallR(Register.RAX, Register.RCX, pwzAssemblyPath, pwzTypeName, pwzMethodName, pwzArgument, pReturnValue); instructions.Add(Instruction.Create(Code.Add_rm64_imm8, Register.RSP, stackOffset + maxStackIndex * 8)); instructions.Add(Instruction.Create(Code.Retnq)); } return instructions; IntPtr Alloc(int size, int protection = 0x04) => Native.VirtualAllocEx(hProc, IntPtr.Zero, (uint)size, 0x1000, protection); void WriteBytes(IntPtr address, byte[] b) => Native.WriteProcessMemory(hProc, address, b, (uint)b.Length, out _); void WriteString(IntPtr address, string str) => WriteBytes(address, new UnicodeEncoding().GetBytes(str)); IntPtr AllocString(string str) { if (str is null) return IntPtr.Zero; var pString = Alloc(str.Length * 2 + 2); WriteString(pString, str); return pString; } IntPtr AllocBytes(byte[] buffer) { var pBuffer = Alloc(buffer.Length); WriteBytes(pBuffer, buffer); return pBuffer; } } } }
50.933333
169
0.640445
[ "MIT" ]
HoLLy-HaCKeR/KeePassHax
KeePassHax.Injector/Injection/FrameworkInjector.cs
7,640
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.EHPC.Transform; using Aliyun.Acs.EHPC.Transform.V20180412; namespace Aliyun.Acs.EHPC.Model.V20180412 { public class CreateClusterRequest : RpcAcsRequest<CreateClusterResponse> { public CreateClusterRequest() : base("EHPC", "2018-04-12", "CreateCluster", "ehs", "openAPI") { } private string sccClusterId; private string imageId; private List<AdditionalVolumes> additionalVolumess; private string ecsOrderManagerInstanceType; private string ehpcVersion; private string accountType; private string securityGroupId; private string description; private string keyPairName; private string securityGroupName; private string ecsOrderComputeInstanceType; private string jobQueue; private string accessKeyId; private string imageOwnerAlias; private string volumeType; private string deployMode; private int? ecsOrderManagerCount; private string resourceGroupId; private string password; private int? ecsOrderLoginCount; private string remoteVisEnable; private int? systemDiskSize; private string action; private string computeSpotPriceLimit; private int? autoRenewPeriod; private int? period; private string volumeProtocol; private string clientVersion; private string osTag; private string remoteDirectory; private int? ecsOrderComputeCount; private string computeSpotStrategy; private List<PostInstallScript> postInstallScripts; private string vSwitchId; private string periodUnit; private List<Application> applications; private string autoRenew; private string ecsChargeType; private string inputFileUrl; private string vpcId; private bool? haEnable; private string name; private string schedulerType; private string volumeId; private string volumeMountpoint; private string ecsOrderLoginInstanceType; private string zoneId; public string SccClusterId { get { return sccClusterId; } set { sccClusterId = value; DictionaryUtil.Add(QueryParameters, "SccClusterId", value); } } public string ImageId { get { return imageId; } set { imageId = value; DictionaryUtil.Add(QueryParameters, "ImageId", value); } } public List<AdditionalVolumes> AdditionalVolumess { get { return additionalVolumess; } set { additionalVolumess = value; for (int i = 0; i < additionalVolumess.Count; i++) { DictionaryUtil.Add(QueryParameters,"AdditionalVolumes." + (i + 1) + ".VolumeType", additionalVolumess[i].VolumeType); DictionaryUtil.Add(QueryParameters,"AdditionalVolumes." + (i + 1) + ".VolumeProtocol", additionalVolumess[i].VolumeProtocol); DictionaryUtil.Add(QueryParameters,"AdditionalVolumes." + (i + 1) + ".LocalDirectory", additionalVolumess[i].LocalDirectory); DictionaryUtil.Add(QueryParameters,"AdditionalVolumes." + (i + 1) + ".RemoteDirectory", additionalVolumess[i].RemoteDirectory); for (int j = 0; j < additionalVolumess[i].Roless.Count; j++) { DictionaryUtil.Add(QueryParameters,"AdditionalVolumes." + (i + 1) + ".Roles." +(j + 1), additionalVolumess[i].Roless[j]); } DictionaryUtil.Add(QueryParameters,"AdditionalVolumes." + (i + 1) + ".VolumeId", additionalVolumess[i].VolumeId); DictionaryUtil.Add(QueryParameters,"AdditionalVolumes." + (i + 1) + ".VolumeMountpoint", additionalVolumess[i].VolumeMountpoint); DictionaryUtil.Add(QueryParameters,"AdditionalVolumes." + (i + 1) + ".Location", additionalVolumess[i].Location); DictionaryUtil.Add(QueryParameters,"AdditionalVolumes." + (i + 1) + ".JobQueue", additionalVolumess[i].JobQueue); } } } public string EcsOrderManagerInstanceType { get { return ecsOrderManagerInstanceType; } set { ecsOrderManagerInstanceType = value; DictionaryUtil.Add(QueryParameters, "EcsOrder.Manager.InstanceType", value); } } public string EhpcVersion { get { return ehpcVersion; } set { ehpcVersion = value; DictionaryUtil.Add(QueryParameters, "EhpcVersion", value); } } public string AccountType { get { return accountType; } set { accountType = value; DictionaryUtil.Add(QueryParameters, "AccountType", value); } } public string SecurityGroupId { get { return securityGroupId; } set { securityGroupId = value; DictionaryUtil.Add(QueryParameters, "SecurityGroupId", value); } } public string Description { get { return description; } set { description = value; DictionaryUtil.Add(QueryParameters, "Description", value); } } public string KeyPairName { get { return keyPairName; } set { keyPairName = value; DictionaryUtil.Add(QueryParameters, "KeyPairName", value); } } public string SecurityGroupName { get { return securityGroupName; } set { securityGroupName = value; DictionaryUtil.Add(QueryParameters, "SecurityGroupName", value); } } public string EcsOrderComputeInstanceType { get { return ecsOrderComputeInstanceType; } set { ecsOrderComputeInstanceType = value; DictionaryUtil.Add(QueryParameters, "EcsOrder.Compute.InstanceType", value); } } public string JobQueue { get { return jobQueue; } set { jobQueue = value; DictionaryUtil.Add(QueryParameters, "JobQueue", value); } } public string AccessKeyId { get { return accessKeyId; } set { accessKeyId = value; DictionaryUtil.Add(QueryParameters, "AccessKeyId", value); } } public string ImageOwnerAlias { get { return imageOwnerAlias; } set { imageOwnerAlias = value; DictionaryUtil.Add(QueryParameters, "ImageOwnerAlias", value); } } public string VolumeType { get { return volumeType; } set { volumeType = value; DictionaryUtil.Add(QueryParameters, "VolumeType", value); } } public string DeployMode { get { return deployMode; } set { deployMode = value; DictionaryUtil.Add(QueryParameters, "DeployMode", value); } } public int? EcsOrderManagerCount { get { return ecsOrderManagerCount; } set { ecsOrderManagerCount = value; DictionaryUtil.Add(QueryParameters, "EcsOrder.Manager.Count", value.ToString()); } } public string ResourceGroupId { get { return resourceGroupId; } set { resourceGroupId = value; DictionaryUtil.Add(QueryParameters, "ResourceGroupId", value); } } public string Password { get { return password; } set { password = value; DictionaryUtil.Add(QueryParameters, "Password", value); } } public int? EcsOrderLoginCount { get { return ecsOrderLoginCount; } set { ecsOrderLoginCount = value; DictionaryUtil.Add(QueryParameters, "EcsOrder.Login.Count", value.ToString()); } } public string RemoteVisEnable { get { return remoteVisEnable; } set { remoteVisEnable = value; DictionaryUtil.Add(QueryParameters, "RemoteVisEnable", value); } } public int? SystemDiskSize { get { return systemDiskSize; } set { systemDiskSize = value; DictionaryUtil.Add(QueryParameters, "SystemDiskSize", value.ToString()); } } public string Action { get { return action; } set { action = value; DictionaryUtil.Add(QueryParameters, "Action", value); } } public string ComputeSpotPriceLimit { get { return computeSpotPriceLimit; } set { computeSpotPriceLimit = value; DictionaryUtil.Add(QueryParameters, "ComputeSpotPriceLimit", value); } } public int? AutoRenewPeriod { get { return autoRenewPeriod; } set { autoRenewPeriod = value; DictionaryUtil.Add(QueryParameters, "AutoRenewPeriod", value.ToString()); } } public int? Period { get { return period; } set { period = value; DictionaryUtil.Add(QueryParameters, "Period", value.ToString()); } } public string VolumeProtocol { get { return volumeProtocol; } set { volumeProtocol = value; DictionaryUtil.Add(QueryParameters, "VolumeProtocol", value); } } public string ClientVersion { get { return clientVersion; } set { clientVersion = value; DictionaryUtil.Add(QueryParameters, "ClientVersion", value); } } public string OsTag { get { return osTag; } set { osTag = value; DictionaryUtil.Add(QueryParameters, "OsTag", value); } } public string RemoteDirectory { get { return remoteDirectory; } set { remoteDirectory = value; DictionaryUtil.Add(QueryParameters, "RemoteDirectory", value); } } public int? EcsOrderComputeCount { get { return ecsOrderComputeCount; } set { ecsOrderComputeCount = value; DictionaryUtil.Add(QueryParameters, "EcsOrder.Compute.Count", value.ToString()); } } public string ComputeSpotStrategy { get { return computeSpotStrategy; } set { computeSpotStrategy = value; DictionaryUtil.Add(QueryParameters, "ComputeSpotStrategy", value); } } public List<PostInstallScript> PostInstallScripts { get { return postInstallScripts; } set { postInstallScripts = value; for (int i = 0; i < postInstallScripts.Count; i++) { DictionaryUtil.Add(QueryParameters,"PostInstallScript." + (i + 1) + ".Args", postInstallScripts[i].Args); DictionaryUtil.Add(QueryParameters,"PostInstallScript." + (i + 1) + ".Url", postInstallScripts[i].Url); } } } public string VSwitchId { get { return vSwitchId; } set { vSwitchId = value; DictionaryUtil.Add(QueryParameters, "VSwitchId", value); } } public string PeriodUnit { get { return periodUnit; } set { periodUnit = value; DictionaryUtil.Add(QueryParameters, "PeriodUnit", value); } } public List<Application> Applications { get { return applications; } set { applications = value; for (int i = 0; i < applications.Count; i++) { DictionaryUtil.Add(QueryParameters,"Application." + (i + 1) + ".Tag", applications[i].Tag); } } } public string AutoRenew { get { return autoRenew; } set { autoRenew = value; DictionaryUtil.Add(QueryParameters, "AutoRenew", value); } } public string EcsChargeType { get { return ecsChargeType; } set { ecsChargeType = value; DictionaryUtil.Add(QueryParameters, "EcsChargeType", value); } } public string InputFileUrl { get { return inputFileUrl; } set { inputFileUrl = value; DictionaryUtil.Add(QueryParameters, "InputFileUrl", value); } } public string VpcId { get { return vpcId; } set { vpcId = value; DictionaryUtil.Add(QueryParameters, "VpcId", value); } } public bool? HaEnable { get { return haEnable; } set { haEnable = value; DictionaryUtil.Add(QueryParameters, "HaEnable", value.ToString()); } } public string Name { get { return name; } set { name = value; DictionaryUtil.Add(QueryParameters, "Name", value); } } public string SchedulerType { get { return schedulerType; } set { schedulerType = value; DictionaryUtil.Add(QueryParameters, "SchedulerType", value); } } public string VolumeId { get { return volumeId; } set { volumeId = value; DictionaryUtil.Add(QueryParameters, "VolumeId", value); } } public string VolumeMountpoint { get { return volumeMountpoint; } set { volumeMountpoint = value; DictionaryUtil.Add(QueryParameters, "VolumeMountpoint", value); } } public string EcsOrderLoginInstanceType { get { return ecsOrderLoginInstanceType; } set { ecsOrderLoginInstanceType = value; DictionaryUtil.Add(QueryParameters, "EcsOrder.Login.InstanceType", value); } } public string ZoneId { get { return zoneId; } set { zoneId = value; DictionaryUtil.Add(QueryParameters, "ZoneId", value); } } public class AdditionalVolumes { private string volumeType; private string volumeProtocol; private string localDirectory; private string remoteDirectory; private List<Roles> roless; private string volumeId; private string volumeMountpoint; private string location; private string jobQueue; public string VolumeType { get { return volumeType; } set { volumeType = value; } } public string VolumeProtocol { get { return volumeProtocol; } set { volumeProtocol = value; } } public string LocalDirectory { get { return localDirectory; } set { localDirectory = value; } } public string RemoteDirectory { get { return remoteDirectory; } set { remoteDirectory = value; } } public List<Roles> Roless { get { return roless; } set { roless = value; } } public string VolumeId { get { return volumeId; } set { volumeId = value; } } public string VolumeMountpoint { get { return volumeMountpoint; } set { volumeMountpoint = value; } } public string Location { get { return location; } set { location = value; } } public string JobQueue { get { return jobQueue; } set { jobQueue = value; } } public class Roles { private string name; public string Name { get { return name; } set { name = value; } } } } public class PostInstallScript { private string args; private string url; public string Args { get { return args; } set { args = value; } } public string Url { get { return url; } set { url = value; } } } public class Application { private string tag; public string Tag { get { return tag; } set { tag = value; } } } public override CreateClusterResponse GetResponse(UnmarshallerContext unmarshallerContext) { return CreateClusterResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
17.410309
135
0.597999
[ "Apache-2.0" ]
bitType/aliyun-openapi-net-sdk
aliyun-net-sdk-ehpc/EHPC/Model/V20180412/CreateClusterRequest.cs
16,888
C#
using Newtonsoft.Json; namespace MatplotlibCS.PlotItems { public class Hline : Line2D { /// <summary> /// Y coord of a line /// </summary> [JsonProperty(PropertyName = "y")] public new double[] Y { get; set; } [JsonProperty(PropertyName = "xmin")] public double XMin { get; set; } [JsonProperty(PropertyName = "xmax")] public double XMax { get; set; } public Hline(string name, double[] y, double xmin, double xmax) : base(name) { Y = y; XMin = xmin; XMax = xmax; ShowLegend = false; } public Hline(string name, double y, double xmin, double xmax) : this(name, new[] { y }, xmin, xmax) { ShowLegend = false; } } }
23.885714
71
0.498804
[ "MIT" ]
longpshorn/MatplotlibCS
MatplotlibCS/PlotItems/Hline.cs
838
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("AWSSDK.FSx")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon FSx. Amazon FSx provides fully-managed third-party file systems optimized for a variety of enterprise and compute-intensive workloads.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon FSx. Amazon FSx provides fully-managed third-party file systems optimized for a variety of enterprise and compute-intensive workloads.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - Amazon FSx. Amazon FSx provides fully-managed third-party file systems optimized for a variety of enterprise and compute-intensive workloads.")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - Amazon FSx. Amazon FSx provides fully-managed third-party file systems optimized for a variety of enterprise and compute-intensive workloads.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.7.3.20")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
48.705882
233
0.772142
[ "Apache-2.0" ]
mikemissakian/aws-sdk-net
sdk/src/Services/FSx/Properties/AssemblyInfo.cs
2,484
C#
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web.UI; using System.Web.UI.WebControls; namespace Adxstudio.Xrm.Web.UI.CrmEntityFormView { /// <summary> /// The default template used when rendering an edit form. /// </summary> public class DefaultUpdateItemTemplate : ITemplate { internal static string DefaultUpdateButtonText = "Update"; private readonly string _validationGroup; private readonly string _submitButtonText; private readonly string _submitButtonCssClass; /// <summary> /// DefaultUpdateItemTemplate Class Initialization. /// </summary> /// <param name="validationGroup"></param> public DefaultUpdateItemTemplate(string validationGroup) { _validationGroup = validationGroup; } /// <summary> /// DefaultUpdateItemTemplate Class Initialization. /// </summary> /// <param name="validationGroup"></param> /// <param name="submitButtonText"></param> /// <param name="submitButtonCssClass"></param> public DefaultUpdateItemTemplate(string validationGroup, string submitButtonText, string submitButtonCssClass) { _validationGroup = validationGroup; _submitButtonText = submitButtonText; _submitButtonCssClass = submitButtonCssClass; } public void InstantiateIn(Control container) { var button = new Button { ID = string.Format("UpdateButton{0}", container.ID), CommandName = "Update", Text = string.IsNullOrWhiteSpace(_submitButtonText) ? DefaultUpdateButtonText : _submitButtonText, ValidationGroup = _validationGroup, CausesValidation = true, CssClass = string.IsNullOrWhiteSpace(_submitButtonCssClass) ? WebControls.CrmEntityFormView.DefaultSubmitButtonCssClass : _submitButtonCssClass, OnClientClick = "javascript:if(typeof Page_ClientValidate === 'function'){if(Page_ClientValidate()){clearIsDirty();}}else{clearIsDirty();}" }; if (string.IsNullOrEmpty(button.CssClass) || button.CssClass == "button submit" || button.CssClass == "btn btn-primary") { button.CssClass = "btn btn-primary navbar-btn button submit-btn"; } container.Controls.Add(button); } } }
32.527778
148
0.746798
[ "MIT" ]
Adoxio/xRM-Portals-Community-Edition
Framework/Adxstudio.Xrm/Web/UI/CrmEntityFormView/DefaultUpdateItemTemplate.cs
2,342
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace PinaColada { public interface ICache { Task<Result<T>> TryGet<T>(string cacheKey); Task Set<T>(string cacheKey, T obj, TimeSpan? ttl); } }
20.642857
60
0.653979
[ "MIT" ]
DanHarltey/Pina-Colada
src/PinaColada/ICache.cs
291
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the sagemaker-2017-07-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SageMaker.Model { /// <summary> /// Metadata for a step execution. /// </summary> public partial class PipelineExecutionStepMetadata { private CallbackStepMetadata _callback; private ClarifyCheckStepMetadata _clarifyCheck; private ConditionStepMetadata _condition; private EMRStepMetadata _emr; private LambdaStepMetadata _lambda; private ModelStepMetadata _model; private ProcessingJobStepMetadata _processingJob; private QualityCheckStepMetadata _qualityCheck; private RegisterModelStepMetadata _registerModel; private TrainingJobStepMetadata _trainingJob; private TransformJobStepMetadata _transformJob; private TuningJobStepMetaData _tuningJob; /// <summary> /// Gets and sets the property Callback. /// <para> /// The URL of the Amazon SQS queue used by this step execution, the pipeline generated /// token, and a list of output parameters. /// </para> /// </summary> public CallbackStepMetadata Callback { get { return this._callback; } set { this._callback = value; } } // Check to see if Callback property is set internal bool IsSetCallback() { return this._callback != null; } /// <summary> /// Gets and sets the property ClarifyCheck. /// <para> /// Container for the metadata for a Clarify check step. The configurations and outcomes /// of the check step execution. This includes: /// </para> /// <ul> <li> /// <para> /// The type of the check conducted, /// </para> /// </li> <li> /// <para> /// The Amazon S3 URIs of baseline constraints and statistics files to be used for the /// drift check. /// </para> /// </li> <li> /// <para> /// The Amazon S3 URIs of newly calculated baseline constraints and statistics. /// </para> /// </li> <li> /// <para> /// The model package group name provided. /// </para> /// </li> <li> /// <para> /// The Amazon S3 URI of the violation report if violations detected. /// </para> /// </li> <li> /// <para> /// The Amazon Resource Name (ARN) of check processing job initiated by the step execution. /// </para> /// </li> <li> /// <para> /// The boolean flags indicating if the drift check is skipped. /// </para> /// </li> <li> /// <para> /// If step property <code>BaselineUsedForDriftCheck</code> is set the same as <code>CalculatedBaseline</code>. /// </para> /// </li> </ul> /// </summary> public ClarifyCheckStepMetadata ClarifyCheck { get { return this._clarifyCheck; } set { this._clarifyCheck = value; } } // Check to see if ClarifyCheck property is set internal bool IsSetClarifyCheck() { return this._clarifyCheck != null; } /// <summary> /// Gets and sets the property Condition. /// <para> /// The outcome of the condition evaluation that was run by this step execution. /// </para> /// </summary> public ConditionStepMetadata Condition { get { return this._condition; } set { this._condition = value; } } // Check to see if Condition property is set internal bool IsSetCondition() { return this._condition != null; } /// <summary> /// Gets and sets the property EMR. /// <para> /// The configurations and outcomes of an EMR step execution. /// </para> /// </summary> public EMRStepMetadata EMR { get { return this._emr; } set { this._emr = value; } } // Check to see if EMR property is set internal bool IsSetEMR() { return this._emr != null; } /// <summary> /// Gets and sets the property Lambda. /// <para> /// The Amazon Resource Name (ARN) of the Lambda function that was run by this step execution /// and a list of output parameters. /// </para> /// </summary> public LambdaStepMetadata Lambda { get { return this._lambda; } set { this._lambda = value; } } // Check to see if Lambda property is set internal bool IsSetLambda() { return this._lambda != null; } /// <summary> /// Gets and sets the property Model. /// <para> /// The Amazon Resource Name (ARN) of the model that was created by this step execution. /// </para> /// </summary> public ModelStepMetadata Model { get { return this._model; } set { this._model = value; } } // Check to see if Model property is set internal bool IsSetModel() { return this._model != null; } /// <summary> /// Gets and sets the property ProcessingJob. /// <para> /// The Amazon Resource Name (ARN) of the processing job that was run by this step execution. /// </para> /// </summary> public ProcessingJobStepMetadata ProcessingJob { get { return this._processingJob; } set { this._processingJob = value; } } // Check to see if ProcessingJob property is set internal bool IsSetProcessingJob() { return this._processingJob != null; } /// <summary> /// Gets and sets the property QualityCheck. /// <para> /// The configurations and outcomes of the check step execution. This includes: /// </para> /// <ul> <li> /// <para> /// The type of the check conducted, /// </para> /// </li> <li> /// <para> /// The Amazon S3 URIs of baseline constraints and statistics files to be used for the /// drift check. /// </para> /// </li> <li> /// <para> /// The Amazon S3 URIs of newly calculated baseline constraints and statistics. /// </para> /// </li> <li> /// <para> /// The model package group name provided. /// </para> /// </li> <li> /// <para> /// The Amazon S3 URI of the violation report if violations detected. /// </para> /// </li> <li> /// <para> /// The Amazon Resource Name (ARN) of check processing job initiated by the step execution. /// </para> /// </li> <li> /// <para> /// The boolean flags indicating if the drift check is skipped. /// </para> /// </li> <li> /// <para> /// If step property <code>BaselineUsedForDriftCheck</code> is set the same as <code>CalculatedBaseline</code>. /// </para> /// </li> </ul> /// </summary> public QualityCheckStepMetadata QualityCheck { get { return this._qualityCheck; } set { this._qualityCheck = value; } } // Check to see if QualityCheck property is set internal bool IsSetQualityCheck() { return this._qualityCheck != null; } /// <summary> /// Gets and sets the property RegisterModel. /// <para> /// The Amazon Resource Name (ARN) of the model package the model was registered to by /// this step execution. /// </para> /// </summary> public RegisterModelStepMetadata RegisterModel { get { return this._registerModel; } set { this._registerModel = value; } } // Check to see if RegisterModel property is set internal bool IsSetRegisterModel() { return this._registerModel != null; } /// <summary> /// Gets and sets the property TrainingJob. /// <para> /// The Amazon Resource Name (ARN) of the training job that was run by this step execution. /// </para> /// </summary> public TrainingJobStepMetadata TrainingJob { get { return this._trainingJob; } set { this._trainingJob = value; } } // Check to see if TrainingJob property is set internal bool IsSetTrainingJob() { return this._trainingJob != null; } /// <summary> /// Gets and sets the property TransformJob. /// <para> /// The Amazon Resource Name (ARN) of the transform job that was run by this step execution. /// </para> /// </summary> public TransformJobStepMetadata TransformJob { get { return this._transformJob; } set { this._transformJob = value; } } // Check to see if TransformJob property is set internal bool IsSetTransformJob() { return this._transformJob != null; } /// <summary> /// Gets and sets the property TuningJob. /// <para> /// The Amazon Resource Name (ARN) of the tuning job that was run by this step execution. /// </para> /// </summary> public TuningJobStepMetaData TuningJob { get { return this._tuningJob; } set { this._tuningJob = value; } } // Check to see if TuningJob property is set internal bool IsSetTuningJob() { return this._tuningJob != null; } } }
32.08284
119
0.546016
[ "Apache-2.0" ]
pcameron-/aws-sdk-net
sdk/src/Services/SageMaker/Generated/Model/PipelineExecutionStepMetadata.cs
10,844
C#
// This file is part of the re-linq project (relinq.codeplex.com) // Copyright (C) 2005-2009 rubicon informationstechnologie gmbh, www.rubicon.eu // // re-linq is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License as published by the // Free Software Foundation; either version 2.1 of the License, // or (at your option) any later version. // // re-linq is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with re-linq; if not, see http://www.gnu.org/licenses. // using System; using System.Collections; using System.Linq; using System.Linq.Expressions; using Remotion.Linq.Clauses.StreamedData; using Remotion.Linq.Utilities; namespace Remotion.Linq.Clauses.ResultOperators { /// <summary> /// Represents a cast of the items returned by a query to a different type. /// This is a result operator, operating on the whole result set of a query. /// </summary> /// <example> /// In C#, "Cast" call in the following example corresponds to a <see cref="CastResultOperator"/>. /// <code> /// var query = (from s in Students /// select s.ID).Cast&lt;int&gt;(); /// </code> /// </example> public class CastResultOperator : SequenceFromSequenceResultOperatorBase { private Type _castItemType; public CastResultOperator (Type castItemType) // TODO 3207 { ArgumentUtility.CheckNotNull ("castItemType", castItemType); CastItemType = castItemType; } public Type CastItemType { get { return _castItemType; } set { ArgumentUtility.CheckNotNull ("value", value); _castItemType = value; } } public override ResultOperatorBase Clone (CloneContext cloneContext) { return new CastResultOperator (CastItemType); } public override StreamedSequence ExecuteInMemory<TInput> (StreamedSequence input) { ArgumentUtility.CheckNotNull ("input", input); var sequence = input.GetTypedSequence<TInput> (); var castMethod = typeof (Enumerable).GetMethod ("Cast", new[] { typeof (IEnumerable) }).MakeGenericMethod (CastItemType); var result = (IEnumerable) InvokeExecuteMethod (castMethod, sequence); return new StreamedSequence (result.AsQueryable(), (StreamedSequenceInfo) GetOutputDataInfo (input.DataInfo)); } public override IStreamedDataInfo GetOutputDataInfo (IStreamedDataInfo inputInfo) { var sequenceInfo = ArgumentUtility.CheckNotNullAndType<StreamedSequenceInfo> ("inputInfo", inputInfo); return new StreamedSequenceInfo ( typeof (IQueryable<>).MakeGenericType (CastItemType), GetNewItemExpression (sequenceInfo.ItemExpression)); } /// <inheritdoc /> public override void TransformExpressions (Func<Expression, Expression> transformation) { //nothing to do here } public override string ToString () { return "Cast<" + CastItemType + ">()"; } private UnaryExpression GetNewItemExpression (Expression inputItemExpression) { return Expression.Convert (inputItemExpression, CastItemType); } } }
35.206186
127
0.703953
[ "MIT" ]
rajcybage/BrightstarDB
src/portable/BrightstarDB.Portable/relinq/RelinqCore/Clauses/ResultOperators/CastResultOperator.cs
3,415
C#
// Copyright 2007-2018 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Context { using System; using System.Threading; using System.Threading.Tasks; using GreenPipes; using Internals.Extensions; /// <summary> /// Converts the object type message to the appropriate generic type and invokes the send method with that /// generic overload. /// </summary> /// <typeparam name="T"></typeparam> public class SendEndpointConverter<T> : ISendEndpointConverter where T : class { Task ISendEndpointConverter.Send(ISendEndpoint endpoint, object message, CancellationToken cancellationToken) { if (endpoint == null) throw new ArgumentNullException(nameof(endpoint)); if (message == null) throw new ArgumentNullException(nameof(message)); if (message is T msg) return endpoint.Send(msg, cancellationToken); throw new ArgumentException("Unexpected message type: " + message.GetType().GetTypeName()); } Task ISendEndpointConverter.Send(ISendEndpoint endpoint, object message, IPipe<SendContext> pipe, CancellationToken cancellationToken) { if (endpoint == null) throw new ArgumentNullException(nameof(endpoint)); if (message == null) throw new ArgumentNullException(nameof(message)); if (pipe == null) throw new ArgumentNullException(nameof(pipe)); if (message is T msg) return endpoint.Send(msg, pipe, cancellationToken); throw new ArgumentException("Unexpected message type: " + message.GetType().GetTypeName()); } } }
40.627119
143
0.642053
[ "Apache-2.0" ]
OriginalDeveloper/MassTransit
src/MassTransit/Context/SendEndpointConverter.cs
2,397
C#
namespace WpfAnalyzers.Test { using System; using System.Collections.Generic; using System.Linq; using Gu.Roslyn.AnalyzerExtensions; using Gu.Roslyn.Asserts; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using NUnit.Framework; public class ValidCodeWithAllAnalyzers { private static readonly IReadOnlyList<DiagnosticAnalyzer> AllAnalyzers = typeof(KnownSymbol) .Assembly.GetTypes() .Where(typeof(DiagnosticAnalyzer).IsAssignableFrom) .Select(t => (DiagnosticAnalyzer)Activator.CreateInstance(t)) .ToArray(); private static readonly Solution AnalyzerProjectSolution = CodeFactory.CreateSolution( ProjectFile.Find("WpfAnalyzers.csproj"), AllAnalyzers, RoslynAssert.MetadataReferences); private static readonly Solution ValidCodeProjectSln = CodeFactory.CreateSolution( ProjectFile.Find("ValidCode.csproj"), AllAnalyzers, RoslynAssert.MetadataReferences); [SetUp] public void Setup() { // The cache will be enabled when running in VS. // It speeds up the tests and makes them more realistic Cache<SyntaxTree, SemanticModel>.Begin(); } [TearDown] public void TearDown() { Cache<SyntaxTree, SemanticModel>.End(); } [Test] public void NotEmpty() { CollectionAssert.IsNotEmpty(AllAnalyzers); Assert.Pass($"Count: {AllAnalyzers.Count}"); } [TestCaseSource(nameof(AllAnalyzers))] public void ValidCodeProject(DiagnosticAnalyzer analyzer) { RoslynAssert.Valid(analyzer, ValidCodeProjectSln); } [TestCaseSource(nameof(AllAnalyzers))] public void AnalyzerProject(DiagnosticAnalyzer analyzer) { RoslynAssert.Valid(analyzer, AnalyzerProjectSolution); } } }
31.107692
100
0.635015
[ "MIT" ]
Insire/WpfAnalyzers
WpfAnalyzers.Test/ValidCodeWithAllAnalyzers.cs
2,022
C#
using System; using System.Collections.Generic; using System.Reflection; namespace LibraryManager.Shared.IoC { public interface IServiceContainer { void RegisterInstance<TServcie>(TServcie instance); void RegisterPerRequest<TService, TImpl>() where TImpl : TService; void RegisterPerRequest<TService>(); void RegisterPerRequest(Type servcieType); void RegisterSingleton<TService, TImpl>() where TImpl : TService; void RegisterSingleton<TServcie>(); void RegisterAssembly(Assembly assembly); void RegisterAssemblyPerRequest(Assembly assembly); T GetInstance<T>(); IEnumerable<T> GetAllInstances<T>(); } }
31.772727
74
0.705293
[ "MIT" ]
nikita-sky/LibraryManager
LibraryManager.Shared/IoC/IServiceContainer.cs
701
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("BitPacking")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BitPacking")] [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("daad79dc-30a3-4a9a-99f8-3ac4ae6d201f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.611111
84
0.740768
[ "MIT" ]
Cobo3/BitPacking
BitPacking/Properties/AssemblyInfo.cs
1,357
C#
namespace ImageFilter { public class ImageFilterSaturation : ImageFilterNoKernel { private const int Min = 0; private const int Max = 200; private const int Default = 100; private int factor = 0; public ImageFilterSaturation() : base() { this.MinValue = Min; this.MaxValue = Max; this.Value = Default; } public override bool HasEffect() => this.Value != Default; public override void Prepare() { this.factor = 65536 * this.Value / 100; } public override void RGB(ref byte r, ref byte g, ref byte b, byte[] kernel, int x, int y) { int lum = r * 19595 + g * 38470 + b * 7471; int lumrgb = lum >> 16; b = this.ClampByte(lum + (b - lumrgb) * this.factor >> 16); g = this.ClampByte(lum + (g - lumrgb) * this.factor >> 16); r = this.ClampByte(lum + (r - lumrgb) * this.factor >> 16); } } }
26.589744
97
0.513983
[ "MIT" ]
KirsonWorks/HalftoneFx
ImageFilter/Filters/ImageFilterSaturation.cs
1,039
C#
using System.Windows.Controls; namespace Leibit.Client.WPF.Windows.Display.Views { /// <summary> /// Interaction logic for PassengerInformation.xaml /// </summary> public partial class PassengerInformation : UserControl { public PassengerInformation() { InitializeComponent(); } } }
21.5625
59
0.637681
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
jannikbecker/leib
Leibit.Client.WPF/Windows/Display/Views/PassengerInformation.xaml.cs
347
C#
using System; namespace teste04_serviceLocator { public class Empresa { public int Id { get; set; } public String RazaoSocial { get; set; } //public Endereco Endereco { get; set; } //auto grau de acoplamento public IEndereco Endreco { get; private set; } //acoplamento minimizado public Empresa() { this.Endreco = Localizador.GetEndereco(); } } }
25.235294
79
0.599068
[ "Apache-2.0" ]
alansvieceli/4-depencendy-injection
teste04-serviceLocator/Empresa.cs
431
C#
#region license // Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) // 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 Ayende Rahien nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using Xunit; using Rhino.Mocks.Exceptions; using Rhino.Mocks.Impl; using Rhino.Mocks.Interfaces; namespace Rhino.Mocks.Tests.FieldsProblem { public class UsingEvents { MockRepository mocks; public UsingEvents() { mocks = new MockRepository(); } [Fact] public void VerifyingThatEventWasAttached() { IWithEvents events = (IWithEvents)mocks.StrictMock(typeof(IWithEvents)); events.Blah += new EventHandler(events_Blah); mocks.ReplayAll(); MethodThatSubscribeToEventBlah(events); mocks.VerifyAll(); } public void MethodThatSubscribeToEventBlah(IWithEvents events) { events.Blah += new EventHandler(events_Blah); } [Fact] public void VerifyingThatAnEventWasFired() { IEventSubscriber subscriber = (IEventSubscriber)mocks.StrictMock(typeof(IEventSubscriber)); IWithEvents events = new WithEvents(); // This doesn't create an expectation because no method is called on subscriber!! events.Blah += new EventHandler(subscriber.Hanlder); subscriber.Hanlder(events, EventArgs.Empty); mocks.ReplayAll(); events.RaiseEvent(); mocks.VerifyAll(); } [Fact] public void VerifyingThatAnEventWasFiredThrowsForDifferentArgument() { MockRepository mocks = new MockRepository(); IEventSubscriber subscriber = (IEventSubscriber)mocks.StrictMock(typeof(IEventSubscriber)); IWithEvents events = new WithEvents(); // This doesn't create an expectation because no method is called on subscriber!! events.Blah += new EventHandler(subscriber.Hanlder); subscriber.Hanlder(events, new EventArgs()); mocks.ReplayAll(); Assert.Throws<ExpectationViolationException>( "IEventSubscriber.Hanlder(Rhino.Mocks.Tests.FieldsProblem.WithEvents, System.EventArgs); Expected #0, Actual #1.\r\nIEventSubscriber.Hanlder(Rhino.Mocks.Tests.FieldsProblem.WithEvents, System.EventArgs); Expected #1, Actual #0.", () => events.RaiseEvent()); } [Fact] public void CanSetExpectationToUnsubscribeFromEvent() { IWithEvents events = (IWithEvents)mocks.StrictMock(typeof(IWithEvents)); events.Blah += new EventHandler(events_Blah); events.Blah -= new EventHandler(events_Blah); mocks.ReplayAll(); events.Blah += new EventHandler(events_Blah); events.Blah -= new EventHandler(events_Blah); mocks.VerifyAll(); } [Fact] public void VerifyingExceptionIfEventIsNotAttached() { IWithEvents events = (IWithEvents)mocks.StrictMock(typeof(IWithEvents)); events.Blah += new EventHandler(events_Blah); mocks.ReplayAll(); Assert.Throws<ExpectationViolationException>("IWithEvents.add_Blah(System.EventHandler); Expected #1, Actual #0.", () => mocks.VerifyAll()); } [Fact] public void VerifyingThatCanAttackOtherEvent() { IWithEvents events = (IWithEvents)mocks.StrictMock(typeof(IWithEvents)); events.Blah += new EventHandler(events_Blah); LastCall.IgnoreArguments(); mocks.ReplayAll(); events.Blah += new EventHandler(events_Blah_Other); mocks.VerifyAll(); } [Fact] public void BetterErrorMessageOnIncorrectParametersCount() { IWithEvents events = (IWithEvents)mocks.StrictMock(typeof(IWithEvents)); events.Blah += null; raiser = LastCall.IgnoreArguments().GetEventRaiser(); mocks.ReplayAll(); events.Blah += delegate { }; Assert.Throws<InvalidOperationException>( "You have called the event raiser with the wrong number of parameters. Expected 2 but was 0", () => raiser.Raise(null)); } [Fact] public void BetterErrorMessageOnIncorrectParameters() { IWithEvents events = (IWithEvents)mocks.StrictMock(typeof(IWithEvents)); events.Blah += null; raiser = LastCall.IgnoreArguments().GetEventRaiser(); mocks.ReplayAll(); events.Blah += delegate { }; Assert.Throws<InvalidOperationException>( "Parameter #2 is System.Int32 but should be System.EventArgs", () => raiser.Raise("", 1)); } private void events_Blah_Other(object sender, EventArgs e) { } private void events_Blah(object sender, EventArgs e) { } IEventRaiser raiser; [Fact] public void RaiseEvent() { IWithEvents eventHolder = (IWithEvents)mocks.StrictMock(typeof(IWithEvents)); eventHolder.Blah += null; LastCall.IgnoreArguments(); raiser = LastCall.GetEventRaiser(); eventHolder.RaiseEvent(); LastCall.Do(new System.Threading.ThreadStart(UseEventRaiser)); IEventSubscriber eventSubscriber = (IEventSubscriber)mocks.StrictMock(typeof(IEventSubscriber)); eventSubscriber.Hanlder(this, EventArgs.Empty); mocks.ReplayAll(); eventHolder.Blah += new EventHandler(eventSubscriber.Hanlder); eventHolder.RaiseEvent(); mocks.VerifyAll(); } [Fact] public void UsingEventRaiserCreate() { IWithEvents eventHolder = (IWithEvents)mocks.Stub(typeof(IWithEvents)); IEventRaiser eventRaiser = EventRaiser.Create(eventHolder, "Blah"); bool called = false; eventHolder.Blah += delegate { called = true; }; mocks.ReplayAll(); eventRaiser.Raise(this, EventArgs.Empty); mocks.VerifyAll(); Assert.True(called); } private void UseEventRaiser() { raiser.Raise(this, EventArgs.Empty); } #if DOTNET35 [Fact] public void RaiseEventUsingExtensionMethod() { IWithEvents eventHolder = (IWithEvents)mocks.Stub(typeof(IWithEvents)); bool called = false; eventHolder.Blah += delegate { called = true; }; eventHolder.Raise(stub => stub.Blah += null, this, EventArgs.Empty); Assert.True(called); } [Fact] public void UsingEventRaiserFromExtensionMethod() { IWithEvents eventHolder = (IWithEvents)mocks.Stub(typeof(IWithEvents)); IEventRaiser eventRaiser = eventHolder.GetEventRaiser(stub => stub.Blah += null); mocks.ReplayAll(); bool called = false; eventHolder.Blah += delegate { called = true; }; eventRaiser.Raise(this, EventArgs.Empty); mocks.VerifyAll(); Assert.True(called); } #endif } public interface IWithEvents { event EventHandler Blah; void RaiseEvent(); } public interface IEventSubscriber { void Hanlder(object sender, EventArgs e); } public class WithEvents : IWithEvents { #region IWithEvents Members public event System.EventHandler Blah; public void RaiseEvent() { if (Blah != null) Blah(this, EventArgs.Empty); } #endregion } }
30.446429
234
0.68305
[ "BSD-3-Clause" ]
Carolinehan/rhino-mocks
Rhino.Mocks.Tests/FieldsProblem/UsingEvents.cs
8,527
C#
using System; using System.Net.Http; using System.Threading.Tasks; using GFK.Time.API; namespace GFK.Image.DateTimeOffsetBuilder; internal class TimeApiDateTimeOffsetFactory : IDateTimeOffsetFactory { private readonly Uri _uri; public TimeApiDateTimeOffsetFactory(Uri uri) { _uri = uri; } public async Task<DateTimeOffset> Build(DateTime dateTime, float latitude, float longitude) { using var httpClient = new HttpClient { BaseAddress = _uri }; var timeApiClient = new TimeApiClient(httpClient); var currentTime = await timeApiClient.CoordinateAsync(latitude, longitude); if (currentTime.TimeZone == null) throw new Exception($"Could not get timezone for latitude {latitude} and longitude {longitude}"); var convertRequest = new ConvertRequest( dateTime.ToString("yyyy-MM-dd HH:mm:ss"), null, currentTime.TimeZone, "UTC"); var conversion = await timeApiClient.ConvertTimeZoneAsync(convertRequest); var offset = dateTime - conversion.ConversionResult.DateTime; return new DateTimeOffset(dateTime, offset); } }
31.210526
109
0.684654
[ "MIT" ]
GordonFreemanK/digikam-scripts
GFK.Image/DateTimeOffsetBuilder/TimeApiDateTimeOffsetFactory.cs
1,188
C#
//------------------------------------------------------------------------------ // <auto-generated> // Este código fue generado por una herramienta. // Versión de runtime: 4.0.30319.42000 // // Los cambios de este archivo pueden provocar un comportamiento inesperado y se perderán si // el código se vuelve a generar. // </auto-generated> //------------------------------------------------------------------------------ namespace _8switch_control_de_registro_de_estacionamiento.Properties { /// <summary> /// Clase de recurso fuertemente tipado para buscar cadenas traducidas, etc. /// </summary> // StronglyTypedResourceBuilder generó automáticamente esta clase // a través de una herramienta como ResGen o Visual Studio. // Para agregar o quitar un miembro, edite el archivo .ResX y, a continuación, vuelva a ejecutar ResGen // con la opción /str o recompile su proyecto de VS. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Devuelve la instancia ResourceManager almacenada en caché utilizada por esta clase. /// </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("_8switch_control_de_registro_de_estacionamiento.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Invalida la propiedad CurrentUICulture del subproceso actual para todas las /// búsquedas de recursos usando esta clase de recursos fuertemente tipados. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
41.388889
213
0.625839
[ "MIT" ]
mauriciogpro/e-dot-net
4_Cap/8switch_control_registro_de_estacionamiento/8switch_control_de_registro_de_estacionamiento/Properties/Resources.Designer.cs
2,993
C#
using System; using TwitchLib.Client.Models; namespace Twitcher.Controllers.Parameters { public class StringParameterProvider : IParameterProvider<string> { public string ParseParameter(string parameter, ChatMessage message) => parameter; } }
24.090909
90
0.758491
[ "MIT" ]
LiphiTC/Twitcher
src/Twitcher.Controllers/Twitcher.Controller.Parameters/StringParameterProvider.cs
265
C#
namespace UnitTests.RestAPI.FlowControl.Base { internal abstract class FlowController : RestBase { protected abstract bool TooManyTests(); public abstract void ControlFlow(); } } /* * Copyright Andrew Gray, SauceForge * Date: 12th July 2014 * */
25
55
0.690909
[ "MIT" ]
Sauceforge/Saucery3
UnitTests/RestAPI/FlowControl/Base/FlowController.cs
277
C#
using Godot; using Sulimn.Classes; using Sulimn.Scenes.Inventory; namespace Sulimn.Scenes.Battle { public class EnemyDetailsScene : Control { private Label LblName, LblLevel, LblExperience, LblGold, LblStrength, LblVitality, LblDexterity, LblWisdom, LblHealth, LblMagic; private GridEquipment EnemyEquipment; private GridInventory EnemyInventory; public override void _UnhandledInput(InputEvent @event) { if (@event is InputEventKey eventKey && eventKey.Pressed && eventKey.Scancode == (int)KeyList.Escape) GetTree().ChangeSceneTo(GameState.GoBack()); } /// <summary>Assigns all controls to something usable in code.</summary> private void AssignControls() { EnemyInventory = (GridInventory)GetNode("EnemyInventory"); EnemyEquipment = (GridEquipment)GetNode("EnemyEquipment"); LblName = (Label)GetNode("Info/LblName"); LblLevel = (Label)GetNode("Info/LblLevel"); LblExperience = (Label)GetNode("Info/LblExperience"); LblStrength = (Label)GetNode("Info/LblStrength"); LblVitality = (Label)GetNode("Info/LblVitality"); LblDexterity = (Label)GetNode("Info/LblDexterity"); LblWisdom = (Label)GetNode("Info/LblWisdom"); LblHealth = (Label)GetNode("Info/LblHealth"); LblMagic = (Label)GetNode("Info/LblMagic"); LblGold = (Label)GetNode("Info/LblGold"); EnemyInventory.SetUpInventory(GameState.CurrentEnemy.Inventory, true); EnemyEquipment.SetUpEquipment(GameState.CurrentEnemy.Equipment, 0, null, true); } /// <summary>Updates all the labels.</summary> public void UpdateLabels() { LblName.Text = GameState.CurrentEnemy.Name; LblLevel.Text = GameState.CurrentEnemy.LevelToString; LblExperience.Text = GameState.CurrentEnemy.ExperienceToStringWithText; LblStrength.Text = GameState.CurrentEnemy.Attributes.StrengthToStringWithText; LblVitality.Text = GameState.CurrentEnemy.Attributes.VitalityToStringWithText; LblDexterity.Text = GameState.CurrentEnemy.Attributes.DexterityToStringWithText; LblWisdom.Text = GameState.CurrentEnemy.Attributes.WisdomToStringWithText; LblHealth.Text = GameState.CurrentEnemy.Statistics.HealthToStringWithText; LblMagic.Text = GameState.CurrentEnemy.Statistics.MagicToStringWithText; LblGold.Text = GameState.CurrentEnemy.GoldToStringWithText; } // Called when the node enters the scene tree for the first time. public override void _Ready() { AssignControls(); UpdateLabels(); } private void _on_BtnReturn_pressed() => GetTree().ChangeSceneTo(GameState.GoBack()); } }
44.030303
136
0.66552
[ "MIT" ]
pfthroaway/GD_Sulimn
scenes/battle/EnemyDetailsScene.cs
2,906
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("Win_Relatorio_SQLServer01")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Win_Relatorio_SQLServer01")] [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("5fa98c7e-7a5a-4adf-b909-1eccfc3cf906")] // 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")]
39.432432
85
0.731323
[ "MIT" ]
antuniooh/exercises-computer-tech-ETEC
Desenvolvimento de Software/Aulas/Win_Relatorio_SQLServer01/Win_Relatorio_SQLServer01/Properties/AssemblyInfo.cs
1,462
C#
using System.Collections.Generic; namespace GraphQL.Language.AST { public class Directive : AbstractNode { public Directive(NameNode node) { NameNode = node; } public string Name => NameNode.Name; public NameNode NameNode { get; set; } public Arguments Arguments { get; set; } public override IEnumerable<INode> Children { get { yield return Arguments; } } public override string ToString() { return $"Directive{{name='{Name}',arguments={Arguments}}}"; } protected bool Equals(Directive other) { if (other == null) return false; return string.Equals(Name, other.Name); } public override bool IsEqualTo(INode obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != GetType()) return false; return Equals((Directive)obj); } } }
24.477273
71
0.545032
[ "MIT" ]
ChironShi/graphql-dotnet
src/GraphQL/Language/AST/Directive.cs
1,077
C#
// This code is part of the Fungus library (http://fungusgames.com) maintained by Chris Gregan (http://twitter.com/gofungus). // It is released for free under the MIT open source license (https://github.com/snozbot/fungus/blob/master/LICENSE) using UnityEngine; namespace Fungus { /// <summary> /// The block will execute when the player starts dragging an object. /// </summary> [EventHandlerInfo("Sprite", "Drag Started", "The block will execute when the player starts dragging an object.")] [AddComponentMenu("")] public class DragStarted : EventHandler { public class DragStartedEvent { public Draggable2D DraggableObject; public DragStartedEvent(Draggable2D draggableObject) { DraggableObject = draggableObject; } } [SerializeField] protected Draggable2D draggableObject; protected EventDispatcher eventDispatcher; protected virtual void OnEnable() { eventDispatcher = FungusManager.Instance.EventDispatcher; eventDispatcher.AddListener<DragStartedEvent>(OnDragStartedEvent); } protected virtual void OnDisable() { eventDispatcher.RemoveListener<DragStartedEvent>(OnDragStartedEvent); eventDispatcher = null; } void OnDragStartedEvent(DragStartedEvent evt) { OnDragStarted(evt.DraggableObject); } #region Public members /// <summary> /// Called by the Draggable2D object when the drag starts. /// </summary> public virtual void OnDragStarted(Draggable2D draggableObject) { if (draggableObject == this.draggableObject) { ExecuteBlock(); } } public override string GetSummary() { if (draggableObject != null) { return draggableObject.name; } return "None"; } #endregion } }
28.306667
125
0.586905
[ "MIT" ]
ACM-London-Game-Development/MinoTourPublic
Assets/Fungus/Scripts/EventHandlers/DragStarted.cs
2,125
C#
using System; using System.Collections.Generic; namespace Dio.Series.Interfaces { public interface IRepositorio<T> { List<T> Lista(); T RetornaPorId(int id); void Insere(T entidade); void Exclui(int id); void Atualiza(int id, T entidade); int ProximoId(); } }
19.764706
43
0.583333
[ "MIT" ]
EvaristoAlves/DigitalInovationOne
Dio.Series/Interfaces/IRepositorio.cs
336
C#
using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.Common; using System.Diagnostics.CodeAnalysis; using Havit.Business.Query; using Havit.Data.SqlServer; namespace Havit.Business { /// <summary> /// Reprezentuje sloupec v databázi, /// nese informace o daném sloupci a jeho vazbu na objektovou strukturu. /// </summary> public class FieldPropertyInfo : PropertyInfo, IFieldsBuilder, IOperand { /// <summary> /// Název sloupce v databázi. /// </summary> public string FieldName { get { CheckInitialization(); return fieldName; } } private string fieldName; /// <summary> /// Udává, zda je možné uložit null hodnotu. /// </summary> public bool Nullable { get { CheckInitialization(); return nullable; } } private bool nullable; /// <summary> /// Typ sloupce v databázi. /// </summary> public SqlDbType FieldType { get { CheckInitialization(); return fieldType; } } private SqlDbType fieldType; /// <summary> /// Udává, zda je sloupec primárním klíčem. /// </summary> public bool IsPrimaryKey { get { CheckInitialization(); return isPrimaryKey; } } private bool isPrimaryKey; /// <summary> /// Maximální délka řetězce (u typů varchar, nvarchar, apod.), případně velikost datového typu (u číselných typů). /// </summary> public int MaximumLength { get { CheckInitialization(); return maximumLength; } } private int maximumLength; /// <summary> /// Inicializuje instanci sloupce. /// </summary> /// <param name="owner">Nadřazený objectInfo.</param> /// <param name="propertyName">Název property.</param> /// <param name="fieldName">Název sloupce v databázy.</param> /// <param name="isPrimaryKey">Indikuje, zda je sloupec primárním klíčem</param> /// <param name="fieldType">Typ databázového sloupce.</param> /// <param name="nullable">Indukuje, zda je povolena hodnota null.</param> /// <param name="maximumLength">Maximální délka dat databázového sloupce.</param> [SuppressMessage("SonarLint", "S1117", Justification = "Není chybou mít parametr metody stejného jména ve třídě.")] public void Initialize(ObjectInfo owner, string propertyName, string fieldName, bool isPrimaryKey, SqlDbType fieldType, bool nullable, int maximumLength) { Initialize(owner, propertyName); this.fieldName = fieldName; this.nullable = nullable; this.fieldType = fieldType; this.isPrimaryKey = isPrimaryKey; this.maximumLength = maximumLength; } /// <summary> /// Vrátí řetězec pro vytažení daného sloupce z databáze. /// </summary> public virtual string GetSelectFieldStatement(DbCommand command) { CheckInitialization(); return "[" + fieldName + "]"; } string IOperand.GetCommandValue(DbCommand command, SqlServerPlatform sqlServerPlatform) { CheckInitialization(); return "[" + fieldName + "]"; } } }
24.636364
155
0.685005
[ "MIT" ]
havit/HavitFramework
Havit.Business/FieldPropertyInfo.cs
3,044
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.IO; using System.Windows.Input; using System.Windows.Media; using Microsoft.Templates.Core; using Microsoft.Templates.Core.Gen; using Microsoft.Templates.Core.PostActions.Catalog.Merge; using Microsoft.Templates.UI.Mvvm; using Microsoft.Templates.UI.Services; namespace Microsoft.Templates.UI.ViewModels.Common { public class NewItemFileViewModel : Selectable { private ICommand _moreDetailsCommand; public FileStatus FileStatus { get; private set; } public string Title { get; private set; } public string Description { get; private set; } public string Subject { get; } public string Icon { get; private set; } public Brush CircleColor { get; private set; } public FileExtension FileExtension { get; private set; } public Func<string, string> UpdateTextAction { get; } public string TempFile { get; private set; } public string ProjectFile { get; } public string FailedPostaction { get; private set; } public string MoreInfoLink => $"{Configuration.Current.GitHubDocsUrl}newitem.md"; public ICommand MoreDetailsCommand => _moreDetailsCommand ?? (_moreDetailsCommand = new RelayCommand(OnMoreDetails)); private NewItemFileViewModel() : base(false) { } private NewItemFileViewModel(FileStatus fileStatus, string subject, string tempFile, string projectFile, Func<string, string> updateTextAction = null) : base(false) { FileStatus = fileStatus; Icon = GetIcon(); CircleColor = GetCircleColor(); UpdateTextAction = updateTextAction; FileExtension = GetFileExtension(subject); Subject = subject; TempFile = tempFile; ProjectFile = projectFile; } public static NewItemFileViewModel NewFile(NewItemGenerationFileInfo file) { return new NewItemFileViewModel(FileStatus.NewFile, file.Name, file.NewItemGenerationFilePath, file.ProjectFilePath); } public static NewItemFileViewModel ModifiedFile(NewItemGenerationFileInfo file) { return new NewItemFileViewModel(FileStatus.ModifiedFile, file.Name, file.NewItemGenerationFilePath, file.ProjectFilePath); } public static NewItemFileViewModel ConflictingFile(NewItemGenerationFileInfo file) { return new NewItemFileViewModel(FileStatus.ConflictingFile, file.Name, file.NewItemGenerationFilePath, file.ProjectFilePath); } public static NewItemFileViewModel UnchangedFile(NewItemGenerationFileInfo file) { return new NewItemFileViewModel(FileStatus.UnchangedFile, file.Name, file.NewItemGenerationFilePath, file.ProjectFilePath); } public static NewItemFileViewModel CompositionToolFile(string filePath) { return new NewItemFileViewModel() { FileStatus = FileStatus.NewFile, TempFile = filePath, FileExtension = GetFileExtension(filePath), }; } public static NewItemFileViewModel ConflictingStylesFile(FailedMergePostActionInfo file) { return new NewItemFileViewModel(FileStatus.ConflictingStylesFile, file.FailedFileName, file.FilePath, string.Empty, AsUserFriendlyPostAction) { FailedPostaction = file.FailedFilePath, }; } public static NewItemFileViewModel WarningFile(FailedMergePostActionInfo file) { return new NewItemFileViewModel(FileStatus.WarningFile, file.FailedFileName, file.FailedFilePath, string.Empty, AsUserFriendlyPostAction) { Description = file.Description, }; } private void OnMoreDetails() => Process.Start(MoreInfoLink); private string GetIcon() { switch (FileExtension) { case FileExtension.CSharp: return "/SharedResources;component/Assets/FileExtensions/CSharp.png"; case FileExtension.Resw: return "/SharedResources;component/Assets/FileExtensions/Resw.png"; case FileExtension.Xaml: return "/SharedResources;component/Assets/FileExtensions/Xaml.png"; case FileExtension.Png: case FileExtension.Jpg: case FileExtension.Jpeg: return "/SharedResources;component/Assets/FileExtensions/Image.png"; case FileExtension.Csproj: return "/SharedResources;component/Assets/FileExtensions/Csproj.png"; case FileExtension.Json: return "/SharedResources;component/Assets/FileExtensions/Json.png"; case FileExtension.Vb: return "/SharedResources;component/Assets/FileExtensions/VisualBasic.png"; case FileExtension.Vbproj: return "/SharedResources;component/Assets/FileExtensions/VBProj.png"; default: return "/SharedResources;component/Assets/FileExtensions/DefaultFile.png"; } } private Brush GetCircleColor() { switch (FileStatus) { case FileStatus.NewFile: return UIStylesService.Instance.NewItemFileStatusNewFile; case FileStatus.ModifiedFile: return UIStylesService.Instance.NewItemFileStatusModifiedFile; case FileStatus.ConflictingFile: return UIStylesService.Instance.NewItemFileStatusConflictingFile; case FileStatus.ConflictingStylesFile: return UIStylesService.Instance.NewItemFileStatusConflictingStylesFile; case FileStatus.WarningFile: return UIStylesService.Instance.NewItemFileStatusWarningFile; case FileStatus.UnchangedFile: return UIStylesService.Instance.NewItemFileStatusUnchangedFile; default: return UIStylesService.Instance.ListItemText; } } private static FileExtension GetFileExtension(string subject) { switch (Path.GetExtension(subject)) { case ".cs": return FileExtension.CSharp; case ".xaml": return FileExtension.Xaml; case ".xml": return FileExtension.Xml; case ".resw": return FileExtension.Resw; case ".csproj": return FileExtension.Csproj; case ".appxmanifest": return FileExtension.AppXManifest; case ".json": return FileExtension.Json; case ".jpg": return FileExtension.Jpg; case ".jpeg": return FileExtension.Jpeg; case ".png": return FileExtension.Png; case ".vb": return FileExtension.Vb; case ".vbproj": return FileExtension.Vbproj; default: return FileExtension.Default; } } private static string AsUserFriendlyPostAction(string arg) => arg.AsUserFriendlyPostAction(); } }
40.494949
159
0.599651
[ "MIT" ]
Microsoft/WindowsTemplateStudio
code/SharedFunctionality.UI/ViewModels/Common/DataItems/NewItemFileViewModel.cs
7,823
C#
namespace VoiceBridge.Most.VoiceModel.Alexa.LanguageModel { public class Empty { } }
15.142857
58
0.641509
[ "MIT" ]
voicebridge/most
voicemodel/src/Alexa/LanguageModel/Empty.cs
108
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("RockPaperScissorsLizardSpock")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RockPaperScissorsLizardSpock")] [assembly: AssemblyCopyright("Copyright © 2019")] [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)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
42.928571
98
0.713394
[ "MIT" ]
Wei-Huang1302/RockPaperScissorsLizardSpock
RockPaperScissorsLizardSpock/Properties/AssemblyInfo.cs
2,407
C#
using Eqstra.BusinessLogic.Base; using Eqstra.BusinessLogic.Helpers; using SQLite; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Eqstra.BusinessLogic.Commercial { public class CGlass : BaseModel { public CGlass() { this.WindscreenImgList = new ObservableCollection<ImageCapture>(); this.RearGlassImgList = new ObservableCollection<ImageCapture>(); this.SideGlassImgList = new ObservableCollection<ImageCapture>(); this.HeadLightsImgList = new ObservableCollection<ImageCapture>(); this.TailLightsImgList = new ObservableCollection<ImageCapture>(); this.InductorLensesImgList = new ObservableCollection<ImageCapture>(); this.ExtRearViewMirrorImgList = new ObservableCollection<ImageCapture>(); } public async override Task<BaseModel> GetDataAsync(long vehicleInsRecID) { return await SqliteHelper.Storage.GetSingleRecordAsync<CGlass>(x => x.VehicleInsRecID == vehicleInsRecID); } private string windscreenComment; public string WindscreenComment { get { return windscreenComment; } set { SetProperty(ref windscreenComment, value); } } private bool isWindscreenDmg; public bool IsWindscreenDmg { get { return isWindscreenDmg; } set { if (SetProperty(ref isWindscreenDmg, value) && !this.IsWindscreenDmg) { this.WindscreenImgList.Clear(); } } } private ObservableCollection<ImageCapture> windscreenImgList; [Ignore, DamageSnapshotRequired("Wind screen snapshot(s) required", "IsWindscreenDmg")] public ObservableCollection<ImageCapture> WindscreenImgList { get { return windscreenImgList; } set { SetProperty(ref windscreenImgList, value); } } private string rearGlassComment; public string RearGlassComment { get { return rearGlassComment; } set { SetProperty(ref rearGlassComment, value); } } private bool isRearGlassDmg; public bool IsRearGlassDmg { get { return isRearGlassDmg; } set { if (SetProperty(ref isRearGlassDmg, value) && !this.IsRearGlassDmg) { this.RearGlassImgList.Clear(); } } } private ObservableCollection<ImageCapture> rearGlassImgList; [Ignore, DamageSnapshotRequired("Rear glass snapshot(s) required", "IsRearGlassDmg")] public ObservableCollection<ImageCapture> RearGlassImgList { get { return rearGlassImgList; } set { SetProperty(ref rearGlassImgList, value); } } private string sideGlassComment; public string SideGlassComment { get { return sideGlassComment; } set { SetProperty(ref sideGlassComment, value); } } private bool isSideGlassDmg; public bool IsSideGlassDmg { get { return isSideGlassDmg; } set { if (SetProperty(ref isSideGlassDmg, value) && !this.IsSideGlassDmg) { this.SideGlassImgList.Clear(); } } } private ObservableCollection<ImageCapture> sideGlassImgList; [Ignore, DamageSnapshotRequired("Side glass snapshot(s) required", "IsSideGlassDmg")] public ObservableCollection<ImageCapture> SideGlassImgList { get { return sideGlassImgList; } set { SetProperty(ref sideGlassImgList, value); } } private string headLightsComment; public string HeadLightsComment { get { return headLightsComment; } set { SetProperty(ref headLightsComment, value); } } private bool isHeadLightsDmg; public bool IsHeadLightsDmg { get { return isHeadLightsDmg; } set { if (SetProperty(ref isHeadLightsDmg, value) && !this.IsHeadLightsDmg) { this.HeadLightsImgList.Clear(); } } } private ObservableCollection<ImageCapture> headLightsImgList; [Ignore, DamageSnapshotRequired("Head lights snapshot(s) required", "IsHeadLightsDmg")] public ObservableCollection<ImageCapture> HeadLightsImgList { get { return headLightsImgList; } set { SetProperty(ref headLightsImgList, value); } } private string tailLightsComment; public string TailLightsComment { get { return tailLightsComment; } set { SetProperty(ref tailLightsComment, value); } } private bool isTailLightsDmg; public bool IsTailLightsDmg { get { return isTailLightsDmg; } set { if (SetProperty(ref isTailLightsDmg, value) && !this.IsTailLightsDmg) { this.TailLightsImgList.Clear(); } } } private ObservableCollection<ImageCapture> tailLightsImgList; [Ignore, DamageSnapshotRequired("Tail lights snapshot(s) required", "IsTailLightsDmg")] public ObservableCollection<ImageCapture> TailLightsImgList { get { return tailLightsImgList; } set { SetProperty(ref tailLightsImgList, value); } } private string inductorLensesComment; public string InductorLensesComment { get { return inductorLensesComment; } set { SetProperty(ref inductorLensesComment, value); } } private bool isInductorLensesDmg; public bool IsInductorLensesDmg { get { return isInductorLensesDmg; } set { if (SetProperty(ref isInductorLensesDmg, value) && !this.IsInductorLensesDmg) { this.InductorLensesImgList.Clear(); } } } private ObservableCollection<ImageCapture> inductorLensesImgList; [Ignore, DamageSnapshotRequired("Inductor lenses snapshot(s) required", "IsInductorLensesDmg")] public ObservableCollection<ImageCapture> InductorLensesImgList { get { return inductorLensesImgList; } set { SetProperty(ref inductorLensesImgList, value); } } private string extRearViewMirrorComment; public string ExtRearViewMirrorComment { get { return extRearViewMirrorComment; } set { SetProperty(ref extRearViewMirrorComment, value); } } private bool isExtRearViewMirrorDmg; public bool IsExtRearViewMirrorDmg { get { return isExtRearViewMirrorDmg; } set { if (SetProperty(ref isExtRearViewMirrorDmg, value) && !this.IsExtRearViewMirrorDmg) { this.ExtRearViewMirrorImgList.Clear(); } } } private ObservableCollection<ImageCapture> extRearViewMirrorImgList; [Ignore, DamageSnapshotRequired("Ext rear view mirror snapshot(s) required", "IsExtRearViewMirrorDmg")] public ObservableCollection<ImageCapture> ExtRearViewMirrorImgList { get { return extRearViewMirrorImgList; } set { SetProperty(ref extRearViewMirrorImgList, value); } } public string windscreenImgPathList; public string WindscreenImgPathList { get { return string.Join("~", WindscreenImgList.Select(x => x.ImagePath)); } set { SetProperty(ref windscreenImgPathList, value); } } public string rearGlassImgPathList; public string RearGlassImgPathList { get { return string.Join("~", RearGlassImgList.Select(x => x.ImagePath)); } set { SetProperty(ref rearGlassImgPathList, value); } } public string sideGlassImgPathList; public string SideGlassImgPathList { get { return string.Join("~", SideGlassImgList.Select(x => x.ImagePath)); } set { SetProperty(ref sideGlassImgPathList, value); } } public string headLightsImgPathList; public string HeadLightsImgPathList { get { return string.Join("~", HeadLightsImgList.Select(x => x.ImagePath)); } set { SetProperty(ref headLightsImgPathList, value); } } public string tailLightsImgPathList; public string TailLightsImgPathList { get { return string.Join("~", TailLightsImgList.Select(x => x.ImagePath)); } set { SetProperty(ref tailLightsImgPathList, value); } } public string inductorLensesImgPathList; public string InductorLensesImgPathList { get { return string.Join("~", InductorLensesImgList.Select(x => x.ImagePath)); } set { SetProperty(ref inductorLensesImgPathList, value); } } public string extRearViewMirrorImgPathList; public string ExtRearViewMirrorImgPathList { get { return string.Join("~", ExtRearViewMirrorImgList.Select(x => x.ImagePath)); } set { SetProperty(ref extRearViewMirrorImgPathList, value); } } } }
31.775974
118
0.597016
[ "MIT" ]
pithline/FMS
Pithline.FMS.BusinessLogic/Commercial/CGlass.cs
9,789
C#
#if WITH_GAME #if PLATFORM_32BITS using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace UnrealEngine { public partial class UWidgetAnimation { static readonly int OnAnimationStarted__Offset; public FMulticastScriptDelegate OnAnimationStarted { get{ CheckIsValid(); return ((FMulticastScriptDelegate)Marshal.PtrToStructure(_this.Get()+OnAnimationStarted__Offset, typeof(FMulticastScriptDelegate)));} set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+OnAnimationStarted__Offset, false);} } static readonly int OnAnimationFinished__Offset; public FMulticastScriptDelegate OnAnimationFinished { get{ CheckIsValid(); return ((FMulticastScriptDelegate)Marshal.PtrToStructure(_this.Get()+OnAnimationFinished__Offset, typeof(FMulticastScriptDelegate)));} set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+OnAnimationFinished__Offset, false);} } static readonly int MovieScene__Offset; public UMovieScene MovieScene { get{ CheckIsValid(); IntPtr v = Marshal.ReadIntPtr(_this.Get() + MovieScene__Offset); if (v == IntPtr.Zero)return null; UMovieScene retValue = new UMovieScene(); retValue._this = v; return retValue; } } static readonly int AnimationBindings__Offset; public TStructArray<FWidgetAnimationBinding> AnimationBindings { get{ CheckIsValid();return new TStructArray<FWidgetAnimationBinding>((FScriptArray)Marshal.PtrToStructure(_this.Get()+AnimationBindings__Offset, typeof(FScriptArray)));} set{ CheckIsValid();Marshal.StructureToPtr(value.InterArray, _this.Get()+AnimationBindings__Offset, false);} } static UWidgetAnimation() { IntPtr NativeClassPtr=GetNativeClassFromName("WidgetAnimation"); OnAnimationStarted__Offset=GetPropertyOffset(NativeClassPtr,"OnAnimationStarted"); OnAnimationFinished__Offset=GetPropertyOffset(NativeClassPtr,"OnAnimationFinished"); MovieScene__Offset=GetPropertyOffset(NativeClassPtr,"MovieScene"); AnimationBindings__Offset=GetPropertyOffset(NativeClassPtr,"AnimationBindings"); } } } #endif #endif
37.875
203
0.793494
[ "MIT" ]
RobertAcksel/UnrealCS
Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile_Game_32bits/UWidgetAnimation_FixSize.cs
2,121
C#
using Microsoft.EntityFrameworkCore; namespace Health.API.Models.Context { public class HealthContext : DbContext { public HealthContext(DbContextOptions<HealthContext> options) : base(options) { } public DbSet<Ailment> Ailments { get; set; } public DbSet<Patient> Patients { get; set; } public DbSet<Medication> Medications { get; set; } } // dotnet (.Net Core CLI) Visual Studio // --------------------------------------------------------------------- --------------------------------------- // dotnet-ef migrations add InitialCreate -o Models/Migrations Add-Migration InitialCreate // dotnet-ef database update Update-Database // dotnet ef migrations remove Remove-Migration // dotnet ef migrations script Script-Migration }
44.304348
118
0.473994
[ "MIT" ]
akiragothick/health-api
Health.API/Models/Context/HealthContext.cs
1,019
C#
namespace ShenNius.Share.Models.Dtos.Output.Sys { public class UserOutput { public int Id { get; set; } /// <summary> /// 登录账号 /// </summary> public string Name { get; set; } /// <summary> /// 真是姓名 /// </summary> public string TrueName { get; set; } public string Password { get; set; } ///// <summary> ///// 性别 ///// </summary> //public string Sex { get; set; } = "男"; /// <summary> /// 手机号码 /// </summary> public string Mobile { get; set; } //public bool Status { get; set; } /// <summary> /// 邮箱 /// </summary> public string Email { get; set; } /// <summary> /// 备注 /// </summary> public string Remark { get; set; } } }
20.023256
48
0.429733
[ "MIT" ]
realyrare/ShenNiusFramework
src/ShenNius.Share.Models/Dtos/Output/Sys/UserOutput.cs
901
C#
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace NAQRPD.Common.FastReflection { public interface IPropertyAccessor { object GetValue(object instance); void SetValue(object instance, object value); } public class PropertyAccessor : IPropertyAccessor { private Func<object, object> m_getter; private Action<object, object[]> m_setter; public static IPropertyAccessor Get(PropertyInfo propertyInfo) { return FastReflectionCaches.PropertyAccessorCache.Get(propertyInfo); } public PropertyInfo PropertyInfo { get; private set; } public PropertyAccessor(PropertyInfo propertyInfo) { this.PropertyInfo = propertyInfo; this.InitializeGet(propertyInfo); this.InitializeSet(propertyInfo); } private void InitializeGet(PropertyInfo propertyInfo) { if (!propertyInfo.CanRead) return; // Target: (object)(((TInstance)instance).Property) // preparing parameter, object type var instance = Expression.Parameter(typeof(object), "instance"); // non-instance for static method, or ((TInstance)instance) var instanceCast = propertyInfo.GetGetMethod(true).IsStatic ? null : Expression.Convert(instance, propertyInfo.ReflectedType); // ((TInstance)instance).Property var propertyAccess = Expression.Property(instanceCast, propertyInfo); // (object)(((TInstance)instance).Property) var castPropertyValue = Expression.Convert(propertyAccess, typeof(object)); // Lambda expression var lambda = Expression.Lambda<Func<object, object>>(castPropertyValue, instance); this.m_getter = lambda.Compile(); } private void InitializeSet(PropertyInfo propertyInfo) { if (!propertyInfo.CanWrite) return; MethodInfo methodInfo = propertyInfo.GetSetMethod(true); // Target: ((TInstance)instance).Method((T0)parameters[0], (T1)parameters[1], ...) // parameters to execute var instanceParameter = Expression.Parameter(typeof(object), "instance"); var parametersParameter = Expression.Parameter(typeof(object[]), "parameters"); // build parameter list var parameterExpressions = new List<Expression>(); var paramInfos = methodInfo.GetParameters(); for (int i = 0; i < paramInfos.Length; i++) { // (Ti)parameters[i] BinaryExpression valueObj = Expression.ArrayIndex( parametersParameter, Expression.Constant(i)); UnaryExpression valueCast = Expression.Convert( valueObj, paramInfos[i].ParameterType); parameterExpressions.Add(valueCast); } // non-instance for static method, or ((TInstance)instance) var instanceCast = methodInfo.IsStatic ? null : Expression.Convert(instanceParameter, methodInfo.ReflectedType); // static invoke or ((TInstance)instance).Method var methodCall = Expression.Call(instanceCast, methodInfo, parameterExpressions); // ((TInstance)instance).Method((T0)parameters[0], (T1)parameters[1], ...) var lambda = Expression.Lambda<Action<object, object[]>>( methodCall, instanceParameter, parametersParameter); m_setter = lambda.Compile(); } public object GetValue(object o) { if (this.m_getter == null) { throw new NotSupportedException("Get method is not defined for this property."); } return this.m_getter(o); } public void SetValue(object o, object value) { if (this.m_setter == null) { throw new NotSupportedException("Set method is not defined for this property."); } this.m_setter(o, new object[] { value }); } } }
36.336134
126
0.605689
[ "MIT" ]
xin2015/NAQRPD
NAQRPD/NAQRPD.Common/FastReflection/PropertyAccessor.cs
4,326
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Abstraction { class LokantaTokat : Lokanta { public LokantaTokat() { this._HarcMiktari = 2000.0D; } public override void HarcOde() { Console.WriteLine($"LokantaTokat Sınıfı: Harç Miktarı : {this._HarcMiktari}"); } } }
21.35
90
0.620609
[ "MIT" ]
baristutakli/NA-203-Notes
Abstraction/LokantaTokat.cs
434
C#
using Gizmox.WebGUI.Forms; using Gizmox.WebGUI.Common; namespace VWG.Community.NetSqlAzMan.ListViews { partial class StoreGroups { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Visual WebGui UserControl Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.toolBar = new Gizmox.WebGUI.Forms.ToolBar(); this.listView = new Gizmox.WebGUI.Forms.ListView(); this.SuspendLayout(); // // toolBar // this.toolBar.ButtonSize = new System.Drawing.Size(24, 24); this.toolBar.DragHandle = true; this.toolBar.DropDownArrows = true; this.toolBar.ImageSize = new System.Drawing.Size(16, 16); this.toolBar.Location = new System.Drawing.Point(0, 0); this.toolBar.MenuHandle = true; this.toolBar.Name = "toolBar"; this.toolBar.ShowToolTips = true; this.toolBar.Size = new System.Drawing.Size(391, 30); this.toolBar.TabIndex = 0; // // listView // this.listView.DataMember = null; this.listView.Location = new System.Drawing.Point(123, 113); this.listView.Name = "listView"; this.listView.Size = new System.Drawing.Size(100, 100); this.listView.TabIndex = 1; // // Storage // this.Controls.Add(this.listView); this.Controls.Add(this.toolBar); this.Size = new System.Drawing.Size(391, 306); this.Text = "Storage"; this.Load += new System.EventHandler(this.Storage_Load); this.ResumeLayout(false); } #endregion private ToolBar toolBar; private ListView listView; } }
33.592105
107
0.553075
[ "MIT" ]
paulusyeung/VWG.Community
VWG.Community.NetSqlAzMan/ListViews/StoreGroups.Designer.cs
2,553
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; namespace Pangea.Domain { /// <summary> /// Singleton for holding all registered currencies /// </summary> public static class Currencies { /// <summary> /// A private field to store a way to retrieve the Currencies instance. /// This allows the end user to store the Currencies instance for instance in an IoC-container /// </summary> private static Func<IReadOnlyCollection<Currency>> _instanceProvider; /// <summary> /// Set the way to retrieve the global instance of the registered Currencies. /// A func is used to allow the end user (developer) to store the actual instance within the /// IoC-container if applicable. /// </summary> /// <param name="functionToRetrieveTheInstance">The way to retrieve the instance</param> public static IReadOnlyCollection<Currency> SetProvider(Func<IReadOnlyCollection<Currency>> functionToRetrieveTheInstance) { if (functionToRetrieveTheInstance == null) throw new ArgumentNullException(nameof(functionToRetrieveTheInstance)); _instanceProvider = functionToRetrieveTheInstance; return _instanceProvider(); } /// <summary> /// The registered instance will be returned using the provider function. /// </summary> private static IReadOnlyCollection<Currency> Instance { get { if (_instanceProvider == null) { SetRegionInfoProvider(); } return _instanceProvider(); } } /// <summary> /// Initialize a new CurrencyCollection with the given currencies. /// These will be registered as a singleton as well as returned directly /// </summary> /// <param name="currencies">The currencies to register</param> /// <returns>The created Currency Collection</returns> public static IReadOnlyCollection<Currency> Initialize(params Currency[] currencies) { var instance = new CurrencyCollection(); instance.AddRange(currencies); SetProvider(() => instance); return instance; } /// <summary> /// Set the provider to use the region info's from standard .Net /// </summary> public static IReadOnlyCollection<Currency> SetRegionInfoProvider() { var currencies = CultureInfo .GetCultures(CultureTypes.AllCultures) .Where(culture => !culture.IsNeutralCulture) .Where(culture => culture.LCID != CultureInfo.InvariantCulture.LCID) .Select(culture => new RegionInfo(culture.LCID)) .Select(region => new Currency(region.ISOCurrencySymbol, region.CurrencySymbol)) .Distinct() .ToArray(); var instance = new CurrencyCollection(); instance.AddRange(currencies); SetProvider(() => instance); return instance; } /// <summary> /// Try to find the Currency within the registered currencies by the given code. /// </summary> /// <param name="code">the ISO 4217 code</param> /// <returns>Either the currency that is found, or null when the currency could not be found</returns> public static Currency Find(string code) { return Instance.FirstOrDefault(currency => currency.Code == code); } } }
38.510417
130
0.605897
[ "MIT" ]
rubenrorije/Pangea.Domain
Pangea.Domain/Currencies.cs
3,699
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the robomaker-2018-06-29.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.RoboMaker.Model { /// <summary> /// Container for the parameters to the UpdateWorldTemplate operation. /// Updates a world template. /// </summary> public partial class UpdateWorldTemplateRequest : AmazonRoboMakerRequest { private string _name; private string _template; private string _templateBody; private TemplateLocation _templateLocation; /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the template. /// </para> /// </summary> [AWSProperty(Min=0, Max=255)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Template. /// <para> /// The Amazon Resource Name (arn) of the world template to update. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=1224)] public string Template { get { return this._template; } set { this._template = value; } } // Check to see if Template property is set internal bool IsSetTemplate() { return this._template != null; } /// <summary> /// Gets and sets the property TemplateBody. /// <para> /// The world template body. /// </para> /// </summary> [AWSProperty(Min=1, Max=262144)] public string TemplateBody { get { return this._templateBody; } set { this._templateBody = value; } } // Check to see if TemplateBody property is set internal bool IsSetTemplateBody() { return this._templateBody != null; } /// <summary> /// Gets and sets the property TemplateLocation. /// <para> /// The location of the world template. /// </para> /// </summary> public TemplateLocation TemplateLocation { get { return this._templateLocation; } set { this._templateLocation = value; } } // Check to see if TemplateLocation property is set internal bool IsSetTemplateLocation() { return this._templateLocation != null; } } }
29.025424
107
0.586277
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/RoboMaker/Generated/Model/UpdateWorldTemplateRequest.cs
3,425
C#
using System; using System.Collections.Generic; using src.Interfaces; using src.Shared; namespace src.Core { public class ArgParser { public static (SortedList<int, ITask>, List<IOption>) Parse( string[] args, ITaskValidator taskValidator ) { // parse commands if (args.Length == 0) { ConsoleLog.WriteError($">> No arguments."); return (null, null); } var taskTypes = new List<TaskTypes>(); var options = new List<IOption>(); foreach( var arg in args) { var command = Commands.TryGetCommand( arg ); if ( command != null ) { taskTypes.Add( command.TaskType ); } else { var option = OptionFactory.Find(arg); if (option != null) { options.Add(option); } } } if ( !taskValidator.ValidateTasks(taskTypes) ) { throw new ArgumentException( $"Provided commands are invalid, check command line"); } return ( TaskFactory.CreateTasks(taskTypes, options), options ); } } }
28.142857
114
0.451777
[ "MIT" ]
vladlee098/img_tool
src/Core/ArgParser.cs
1,379
C#
using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; namespace Users.Infrastructure { public class LocationClaimsProvider : IClaimsTransformation { public Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal) { if (principal != null && !principal.HasClaim(c => c.Type == ClaimTypes.PostalCode)) { ClaimsIdentity identity = principal.Identity as ClaimsIdentity; if (identity != null && identity.IsAuthenticated && identity.Name != null) { if (identity.Name.ToLower() == "alice") { identity.AddClaims(new Claim[] { CreateClaim(ClaimTypes.PostalCode, "DC 20500"), CreateClaim(ClaimTypes.StateOrProvince, "DC") }); } else { identity.AddClaims(new Claim[] { CreateClaim(ClaimTypes.PostalCode, "NY 10036"), CreateClaim(ClaimTypes.StateOrProvince, "NY") }); } } } return Task.FromResult(principal); } private static Claim CreateClaim(string type, string value) => new Claim(type, value, ClaimValueTypes.String, "RemoteClaims"); } }
41.2
95
0.527046
[ "Unlicense" ]
Vladimir-Zakharenkov/AdamFreemanMVC2
Freeman A. projects with GitHub/30 - Advanced Identity/Users/Users/Infrastructure/LocationClaimsProvider.cs
1,444
C#
// The MIT License (MIT) // // Copyright (c) Andrew Armstrong/FacticiusVir 2018 // // 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; using System.Runtime.InteropServices; namespace SharpVk.Khronos { /// <summary> /// /// </summary> [StructLayout(LayoutKind.Sequential)] public partial struct DeviceGroupSwapchainCreateInfo { /// <summary> /// /// </summary> public SharpVk.Khronos.DeviceGroupPresentModeFlags Modes { get; set; } /// <summary> /// /// </summary> internal unsafe void MarshalTo(SharpVk.Interop.Khronos.DeviceGroupSwapchainCreateInfo* pointer) { pointer->SType = StructureType.DeviceGroupSwapchainCreateInfo; pointer->Next = null; pointer->Modes = this.Modes; } } }
35.625
103
0.685714
[ "MIT" ]
sebastianulm/SharpVk
src/SharpVk/Khronos/DeviceGroupSwapchainCreateInfo.gen.cs
1,995
C#
namespace MagicalLifeGUIWindows.GUI.MainMenu { /// <summary> /// Holds some constants used to render the main menu when at the 1920 by 1080 resolution. /// </summary> public static class MainMenuLayout1920x1080 { /// <summary> /// The x position at which the left part of the buttons on the main menu begin. /// </summary> public static readonly int ButtonX = 20; /// <summary> /// How wide the buttons are. /// </summary> public static readonly int ButtonWidth = 200; /// <summary> /// How tall the buttons are. /// </summary> public static readonly int ButtonHeight = 50; /// <summary> /// The y position of the top of the new game button. /// </summary> public static readonly int NewGameButtonY = 100; /// <summary> /// The y position of the top of the host game button. /// </summary> public static readonly int LoadGameButtonY = 200; /// <summary> /// The y position of the top of the join game button. /// </summary> public static readonly int JoinGameButtonY = 300; /// <summary> /// The y position of the top of the quit button. /// </summary> public static readonly int QuitButtonY = 400; } }
31.55814
94
0.57406
[ "MIT" ]
Lynngr/MagicalLife
MagicalLifeGUIWindows/GUI/MainMenu/MainMenuLayout1920x1080.cs
1,359
C#
namespace MvcFramework.HTTP.Enums { public enum HttpResponseStatusCode { Ok = 200, Created = 201, Found = 302, SeeOther = 303, BadRequest = 400, Unauthorized = 401, Forbidden = 403, NotFound = 404, InernalServerError = 500 } }
15.5625
35
0.674699
[ "MIT" ]
NaskoVasilev/CSharp-MVC-Framework
MvcFramework/MvcFramework.HTTP/Enums/HttpResponseStatusCode.cs
251
C#
using FrameworkTester.ViewModels.Interfaces; using WinBiometricDotNet; namespace FrameworkTester.ViewModels { public sealed class WinBioGetLogonSettingViewModel : WinBioPropertyViewModel, IWinBioGetLogonSettingViewModel { public override string Name => "WinBioGetLogonSetting"; protected override void GetValueAndSource(out bool value, out SettingSourceType source) { this.BiometricService.GetLogonSetting(out value, out source); } } }
27.157895
114
0.718992
[ "MIT" ]
poseidonjm/WinBiometricDotNet
examples/FrameworkTester/ViewModels/WinBioGetLogonSettingViewModel.cs
518
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class ChanceScene : MonoBehaviour { // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { } public void Click() { SceneManager.LoadScene("Juego"); } }
16.36
52
0.628362
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
monogawilmer/Drug-s-Clicker
Drug's Clicker/Assets/Scripts/ChanceScene.cs
411
C#
namespace Exprelsior.Tests.DynamicQuery.SimpleQueries.Guid { using System; using System.Linq; using Exprelsior.ExpressionBuilder; using Exprelsior.ExpressionBuilder.Enums; using Exprelsior.Tests.DynamicQuery.SimpleQueries.Guid.Contracts; using Exprelsior.Tests.Utilities; using Xunit; using Xunit.Abstractions; // ReSharper disable InconsistentNaming /// <summary> /// Unit tests for the dynamic query builder with tests focused on <see cref="Guid"/> type queries. /// </summary> public class DynamicQueryGuidTests : DynamicQueryTestBase, IDynamicQueryGuidTests { /// <summary> /// Initializes a new instance of the <see cref="DynamicQueryGuidTests"/> class. /// </summary> /// <param name="testOutput"> /// The class responsible for providing test output. /// </param> public DynamicQueryGuidTests(ITestOutputHelper testOutput) : base(testOutput) { } // Guid /// <summary> /// Asserts that an <see cref="Guid"/> <see cref="ExpressionOperator.Equal"/> expression is generated correctly. /// </summary> [Fact] public void Assert_Guid_Equality_Dynamic_Query_Expression_Is_Generated_Correctly() { // Arrange var randomHydra = Utilities.GetRandomItem(HydraArmy); var expression = ExpressionBuilder.CreateBinaryFromQuery<Hydra>(BuildQueryText(nameof(Hydra.Guid), randomHydra.Guid, ExpressionOperator.Equal)); // Act var result = HydraArmy.Where(expression.Compile()).ToList(); // Assert Assert.NotEmpty(result); Assert.Contains(result, t => t.Guid == randomHydra.Guid); Assert.DoesNotContain(result, t => t.Guid != randomHydra.Guid); } /// <summary> /// Asserts that an <see cref="Guid"/> <see cref="ExpressionOperator.NotEqual"/> expression is generated correctly. /// </summary> [Fact] public void Assert_Guid_Inequality_Dynamic_Query_Expression_Is_Generated_Correctly() { // Arrange var randomHydra = Utilities.GetRandomItem(HydraArmy); var expression = ExpressionBuilder.CreateBinaryFromQuery<Hydra>(BuildQueryText(nameof(Hydra.Guid), randomHydra.Guid, ExpressionOperator.NotEqual)); // Act var result = HydraArmy.Where(expression.Compile()).ToList(); // Assert Assert.NotEmpty(result); Assert.Contains(result, t => t.Guid != randomHydra.Guid); Assert.DoesNotContain(result, t => t.Guid == randomHydra.Guid); } /// <summary> /// Asserts that an <see cref="Guid"/> <see cref="ExpressionOperator.Contains"/> on value expression is generated correctly. /// </summary> [Fact] public void Assert_Guid_Contains_On_Value_Dynamic_Query_Expression_Is_Generated_Correctly() { // Arrange var randomGuids = Utilities.GetRandomItems(HydraArmy.Select(t => t.Guid)); var expression = ExpressionBuilder.CreateBinaryFromQuery<Hydra>(BuildQueryText(nameof(Hydra.Guid), randomGuids, ExpressionOperator.ContainsOnValue)); // Act var result = HydraArmy.Where(expression.Compile()).ToList(); // Assert Assert.NotEmpty(result); Assert.Contains(result, t => randomGuids.Contains(t.Guid)); Assert.DoesNotContain(result, t => !randomGuids.Contains(t.Guid)); } // Guid Array /// <summary> /// Asserts that an array of <see cref="Guid"/> <see cref="ExpressionOperator.Equal"/> expression is generated correctly. /// </summary> [Fact] public void Assert_Guid_Array_Equality_Dynamic_Query_Expression_Is_Generated_Correctly() { // Arrange var randomHydra = Utilities.GetRandomItem(HydraArmy); var expression = ExpressionBuilder.CreateBinaryFromQuery<Hydra>(BuildQueryText(nameof(Hydra.GuidArray), randomHydra.GuidArray, ExpressionOperator.Equal)); // Act var result = HydraArmy.Where(expression.Compile()).ToList(); // Assert Assert.NotEmpty(result); Assert.Contains(result, t => t.GuidArray.SequenceEqual(randomHydra.GuidArray)); Assert.DoesNotContain(result, t => !t.GuidArray.SequenceEqual(randomHydra.GuidArray)); } /// <summary> /// Asserts that an array of <see cref="Guid"/> <see cref="ExpressionOperator.NotEqual"/> expression is generated correctly. /// </summary> [Fact] public void Assert_Guid_Array_Inequality_Dynamic_Query_Expression_Is_Generated_Correctly() { // Arrange var randomHydra = Utilities.GetRandomItem(HydraArmy); var expression = ExpressionBuilder.CreateBinaryFromQuery<Hydra>(BuildQueryText(nameof(Hydra.GuidArray), randomHydra.GuidArray, ExpressionOperator.NotEqual)); // Act var result = HydraArmy.Where(expression.Compile()).ToList(); // Assert Assert.NotEmpty(result); Assert.Contains(result, t => !t.GuidArray.SequenceEqual(randomHydra.GuidArray)); Assert.DoesNotContain(result, t => t.GuidArray.SequenceEqual(randomHydra.GuidArray)); } /// <summary> /// Asserts that an array of <see cref="Guid"/> <see cref="ExpressionOperator.Equal"/> expression with an list of values is generated correctly. /// </summary> [Fact] public void Assert_Guid_Array_Equality_Expression_With_List_Value_Is_Generated_Correctly() { // Arrange var randomHydra = Utilities.GetRandomItem(HydraArmy); var expression = ExpressionBuilder.CreateBinaryFromQuery<Hydra>(BuildQueryText(nameof(Hydra.GuidArray), randomHydra.GuidArray.ToList(), ExpressionOperator.Equal)); // Act var result = HydraArmy.Where(expression.Compile()).ToList(); // Assert Assert.NotEmpty(result); Assert.Contains(result, t => t.GuidArray.SequenceEqual(randomHydra.GuidArray)); Assert.DoesNotContain(result, t => !t.GuidArray.SequenceEqual(randomHydra.GuidArray)); } /// <summary> /// Asserts that an array of <see cref="Guid"/> <see cref="ExpressionOperator.NotEqual"/> expression with an list of values is generated correctly. /// </summary> [Fact] public void Assert_Guid_Array_Inequality_Expression_With_List_Value_Is_Generated_Correctly() { // Arrange var randomHydra = Utilities.GetRandomItem(HydraArmy); var expression = ExpressionBuilder.CreateBinaryFromQuery<Hydra>(BuildQueryText(nameof(Hydra.GuidArray), randomHydra.GuidArray.ToList(), ExpressionOperator.NotEqual)); // Act var result = HydraArmy.Where(expression.Compile()).ToList(); // Assert Assert.NotEmpty(result); Assert.Contains(result, t => !t.GuidArray.SequenceEqual(randomHydra.GuidArray)); Assert.DoesNotContain(result, t => t.GuidArray.SequenceEqual(randomHydra.GuidArray)); } /// <summary> /// Asserts that an array of <see cref="Guid"/> <see cref="ExpressionOperator.Contains"/> single value expression is generated correctly. /// </summary> [Fact] public void Assert_Guid_Array_Contains_Single_Value_Dynamic_Query_Expression_Is_Generated_Correctly() { // Arrange var randomGuid = Utilities.GetRandomItem(HydraArmy.Select(t => t.GuidArray)).FirstOrDefault(); var expression = ExpressionBuilder.CreateBinaryFromQuery<Hydra>(BuildQueryText(nameof(Hydra.GuidArray), randomGuid, ExpressionOperator.Contains)); // Act var result = HydraArmy.Where(expression.Compile()).ToList(); // Assert Assert.NotEmpty(result); Assert.Contains(result, t => t.GuidArray.Contains(randomGuid)); Assert.DoesNotContain(result, t => !t.GuidArray.Contains(randomGuid)); } /// <summary> /// Asserts that an collection of <see cref="Guid"/> <see cref="ExpressionOperator.Equal"/> expression is generated correctly. /// </summary> [Fact] public void Assert_Guid_Collection_Equality_Dynamic_Query_Expression_Is_Generated_Correctly() { // Arrange var randomHydra = Utilities.GetRandomItem(HydraArmy); var expression = ExpressionBuilder.CreateBinaryFromQuery<Hydra>(BuildQueryText(nameof(Hydra.GuidCollection), randomHydra.GuidCollection, ExpressionOperator.Equal)); // Act var result = HydraArmy.Where(expression.Compile()).ToList(); // Assert Assert.NotEmpty(result); Assert.Contains(result, t => t.GuidCollection.SequenceEqual(randomHydra.GuidCollection)); Assert.DoesNotContain(result, t => !t.GuidCollection.SequenceEqual(randomHydra.GuidCollection)); } /// <summary> /// Asserts that an collection of <see cref="Guid"/> <see cref="ExpressionOperator.NotEqual"/> expression is generated correctly. /// </summary> [Fact] public void Assert_Guid_Collection_Inequality_Dynamic_Query_Expression_Is_Generated_Correctly() { // Arrange var randomHydra = Utilities.GetRandomItem(HydraArmy); var expression = ExpressionBuilder.CreateBinaryFromQuery<Hydra>(BuildQueryText(nameof(Hydra.GuidCollection), randomHydra.GuidCollection, ExpressionOperator.NotEqual)); // Act var result = HydraArmy.Where(expression.Compile()).ToList(); // Assert Assert.NotEmpty(result); Assert.Contains(result, t => !t.GuidCollection.SequenceEqual(randomHydra.GuidCollection)); Assert.DoesNotContain(result, t => t.GuidCollection.SequenceEqual(randomHydra.GuidCollection)); } /// <summary> /// Asserts that an collection of <see cref="Guid"/> <see cref="ExpressionOperator.Equal"/> expression with an array of values is generated correctly. /// </summary> [Fact] public void Assert_Guid_Collection_Equality_Expression_With_Array_Value_Is_Generated_Correctly() { // Arrange var randomHydra = Utilities.GetRandomItem(HydraArmy); var expression = ExpressionBuilder.CreateBinaryFromQuery<Hydra>(BuildQueryText(nameof(Hydra.GuidCollection), randomHydra.GuidCollection.ToArray(), ExpressionOperator.Equal)); // Act var result = HydraArmy.Where(expression.Compile()).ToList(); // Assert Assert.NotEmpty(result); Assert.Contains(result, t => t.GuidCollection.SequenceEqual(randomHydra.GuidCollection)); Assert.DoesNotContain(result, t => !t.GuidCollection.SequenceEqual(randomHydra.GuidCollection)); } /// <summary> /// Asserts that an collection of <see cref="Guid"/> <see cref="ExpressionOperator.NotEqual"/> expression with an array of values is generated correctly. /// </summary> [Fact] public void Assert_Guid_Collection_Inequality_Expression_With_Array_Value_Is_Generated_Correctly() { // Arrange var randomHydra = Utilities.GetRandomItem(HydraArmy); var expression = ExpressionBuilder.CreateBinaryFromQuery<Hydra>(BuildQueryText(nameof(Hydra.GuidCollection), randomHydra.GuidCollection.ToArray(), ExpressionOperator.NotEqual)); // Act var result = HydraArmy.Where(expression.Compile()).ToList(); // Assert Assert.NotEmpty(result); Assert.Contains(result, t => !t.GuidCollection.SequenceEqual(randomHydra.GuidCollection)); Assert.DoesNotContain(result, t => t.GuidCollection.SequenceEqual(randomHydra.GuidCollection)); } /// <summary> /// Asserts that an collection of <see cref="Guid"/> <see cref="ExpressionOperator.Contains"/> single value expression is generated correctly. /// </summary> [Fact] public void Assert_Guid_Collection_Contains_Single_Value_Dynamic_Query_Expression_Is_Generated_Correctly() { // Arrange var randomGuid = Utilities.GetRandomItem(HydraArmy.Select(t => t.GuidCollection)).FirstOrDefault(); var expression = ExpressionBuilder.CreateBinaryFromQuery<Hydra>(BuildQueryText(nameof(Hydra.GuidCollection), randomGuid, ExpressionOperator.Contains)); // Act var result = HydraArmy.Where(expression.Compile()).ToList(); // Assert Assert.NotEmpty(result); Assert.Contains(result, t => t.GuidCollection.Contains(randomGuid)); Assert.DoesNotContain(result, t => !t.GuidCollection.Contains(randomGuid)); } } }
46.879004
189
0.64784
[ "MIT" ]
alexmurari/Exprelsior
Exprelsior.Tests/DynamicQuery/SimpleQueries/Guid/DynamicQueryGuidTests.cs
13,175
C#
using Microsoft.EntityFrameworkCore.Metadata.Builders; using RecipeSocial.Domain.Entities; namespace RecipeSocial.Infrastructure.Database.Configuration.Mappers { public class RecipeTagMapper { public static void Map(EntityTypeBuilder<RecipeTag> builder) { builder.HasKey(recipeTag => new { recipeTag.RecipeId, recipeTag.TagId }); builder.HasOne(recipeTag => recipeTag.Recipe) .WithMany(recipe => recipe.RecipeTags) .HasForeignKey(recipeTag => recipeTag.RecipeId); builder.HasOne(recipeTag => recipeTag.Tag) .WithMany(recipe => recipe.RecipeTags) .HasForeignKey(recipeTag => recipeTag.TagId); } } }
33.545455
85
0.654472
[ "MIT" ]
jvalverdep/recipe-social
RecipeSocial.Infrastructure.Database/Configuration/Mappers/RecipeTagMapper.cs
740
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using Microsoft.AspNet.SignalR.Infrastructure; using Newtonsoft.Json.Serialization; namespace eFocus.Amar2000.API.ContractResolvers { public class SignalRContractResolver : IContractResolver { private readonly Assembly assembly; private readonly IContractResolver camelCaseContractResolver; private readonly IContractResolver defaultContractSerializer; public SignalRContractResolver() { defaultContractSerializer = new DefaultContractResolver(); camelCaseContractResolver = new CamelCasePropertyNamesContractResolver(); assembly = typeof(Connection).Assembly; } public JsonContract ResolveContract(Type type) { if (type.Assembly.Equals(assembly)) { return defaultContractSerializer.ResolveContract(type); } return camelCaseContractResolver.ResolveContract(type); } } }
29
85
0.703267
[ "MIT" ]
Physer/Amar2000
src/eFocus.Amar2000.API/ContractResolvers/SignalRContractResolver.cs
1,104
C#
/* * WebAPI - Area Management * * No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) * * OpenAPI spec version: management * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = IO.Swagger.Management.Client.SwaggerDateConverter; namespace IO.Swagger.Management.Model { /// <summary> /// Class for mail box folder information /// </summary> [DataContract] public partial class MailBoxFolderDTO : IEquatable<MailBoxFolderDTO>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="MailBoxFolderDTO" /> class. /// </summary> /// <param name="name">Folder name.</param> /// <param name="fullName">Folder path.</param> /// <param name="subFolders">Subfolders.</param> public MailBoxFolderDTO(string name = default(string), string fullName = default(string), List<MailBoxFolderDTO> subFolders = default(List<MailBoxFolderDTO>)) { this.Name = name; this.FullName = fullName; this.SubFolders = subFolders; } /// <summary> /// Folder name /// </summary> /// <value>Folder name</value> [DataMember(Name="name", EmitDefaultValue=false)] public string Name { get; set; } /// <summary> /// Folder path /// </summary> /// <value>Folder path</value> [DataMember(Name="fullName", EmitDefaultValue=false)] public string FullName { get; set; } /// <summary> /// Subfolders /// </summary> /// <value>Subfolders</value> [DataMember(Name="subFolders", EmitDefaultValue=false)] public List<MailBoxFolderDTO> SubFolders { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class MailBoxFolderDTO {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" FullName: ").Append(FullName).Append("\n"); sb.Append(" SubFolders: ").Append(SubFolders).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as MailBoxFolderDTO); } /// <summary> /// Returns true if MailBoxFolderDTO instances are equal /// </summary> /// <param name="input">Instance of MailBoxFolderDTO to be compared</param> /// <returns>Boolean</returns> public bool Equals(MailBoxFolderDTO input) { if (input == null) return false; return ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.FullName == input.FullName || (this.FullName != null && this.FullName.Equals(input.FullName)) ) && ( this.SubFolders == input.SubFolders || this.SubFolders != null && this.SubFolders.SequenceEqual(input.SubFolders) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); if (this.FullName != null) hashCode = hashCode * 59 + this.FullName.GetHashCode(); if (this.SubFolders != null) hashCode = hashCode * 59 + this.SubFolders.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
34.275
166
0.558169
[ "Apache-2.0" ]
zanardini/ARXivarNext-WebApi
ARXivarNext-ConsumingWebApi/IO.Swagger.Management/Model/MailBoxFolderDTO.cs
5,484
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.10 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ namespace XDA { public class XsDeviceConfigurationException : XsException { private global::System.Runtime.InteropServices.HandleRef swigCPtr; internal XsDeviceConfigurationException(global::System.IntPtr cPtr, bool cMemoryOwn) : base(xsensdeviceapiPINVOKE.XsDeviceConfigurationException_SWIGUpcast(cPtr), cMemoryOwn) { swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr); } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(XsDeviceConfigurationException obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } ~XsDeviceConfigurationException() { Dispose(); } public override void Dispose() { lock(this) { if (swigCPtr.Handle != global::System.IntPtr.Zero) { if (swigCMemOwn) { swigCMemOwn = false; xsensdeviceapiPINVOKE.delete_XsDeviceConfigurationException(swigCPtr); } swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero); } global::System.GC.SuppressFinalize(this); base.Dispose(); } } public XsDeviceConfigurationException() : this(xsensdeviceapiPINVOKE.new_XsDeviceConfigurationException(), true) { } } }
35.354167
178
0.661167
[ "MIT" ]
PoxyDoxy/EFAS
EFAS/EFAS/wrap_csharp64/XsDeviceConfigurationException.cs
1,697
C#
using System; using System.Collections.Generic; using System.Web; using System.Web.Mvc; using global::Microsoft.VisualStudio.TestTools.UnitTesting; using Telerik.Sitefinity.Data; using Telerik.Sitefinity.Frontend.Mvc.Controllers; using Telerik.Sitefinity.Frontend.Mvc.Infrastructure.Controllers; using Telerik.Sitefinity.Frontend.TestUtilities.Mvc.Controllers; using Telerik.Sitefinity.Services; using Telerik.Sitefinity.Web; using Telerik.Sitefinity.Web.UI; namespace Telerik.Sitefinity.Frontend.TestUnit.Mvc.Infrastructure.Controllers { /// <summary> /// The controller extensions tests. /// </summary> [TestClass] public class ControllerExtensionsTests { #region Public Methods and Operators /// <summary> /// Checks if AddCacheDependencies adds the given dependencies and keeps the existing keys. /// </summary> [TestMethod] [Owner("Boyko-Karadzhov")] [Description("Checks if AddCacheDependencies adds the given dependencies and keeps the existing keys.")] public void AddCacheDependencies_HasCacheItem_CreatesAndAddsNewList() { // Arrange var context = new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://tempuri.org/", null), new HttpResponse(null))); var prevDependencies = new List<CacheDependencyKey>(2); var prevKey1 = new CacheDependencyKey { Key = "prevKey1", Type = this.GetType() }; var prevKey2 = new CacheDependencyKey { Key = "prevKey2", Type = this.GetType() }; prevDependencies.Add(prevKey1); prevDependencies.Add(prevKey2); context.Items[PageCacheDependencyKeys.PageData] = prevDependencies; var controller = new DesignerController(); var dependencies = new List<CacheDependencyKey>(2); var depKey1 = new CacheDependencyKey { Key = "mykey1", Type = this.GetType() }; var depKey2 = new CacheDependencyKey { Key = "mykey2", Type = this.GetType() }; dependencies.Add(depKey1); dependencies.Add(depKey2); // Act SystemManager.RunWithHttpContext(context, () => { controller.AddCacheDependencies(dependencies); }); // Assert object cacheObject = context.Items[PageCacheDependencyKeys.PageData]; Assert.IsNotNull(cacheObject, "No cache object was set in the context."); Assert.IsTrue(cacheObject is IList<CacheDependencyKey>, "The cache object was not of the expected type."); var cacheList = (IList<CacheDependencyKey>)cacheObject; Assert.IsTrue(cacheList.Contains(prevKey1), "The first previous cache dependency was not found."); Assert.IsTrue(cacheList.Contains(prevKey2), "The second previous cache dependency was not found."); Assert.IsTrue(cacheList.Contains(depKey1), "The first new cache dependency was not added."); Assert.IsTrue(cacheList.Contains(depKey2), "The second new cache dependency was not added."); Assert.AreEqual(2 + dependencies.Count, cacheList.Count, "There is an unexpecred count of cache dependency keys."); } /// <summary> /// Checks if AddCacheDependencies adds the given dependencies to a new object when none is added before that. /// </summary> [TestMethod] [Owner("Boyko-Karadzhov")] [Description("Checks if AddCacheDependencies adds the given dependencies to a new object when none is added before that.")] public void AddCacheDependencies_NoCacheItem_CreatesAndAddsNewList() { // Arrange var context = new HttpContextWrapper(new HttpContext(new HttpRequest(null, "http://tempuri.org/", null), new HttpResponse(null))); var controller = new DesignerController(); var dependencies = new List<CacheDependencyKey>(); var depKey1 = new CacheDependencyKey { Key = "mykey1", Type = this.GetType() }; var depKey2 = new CacheDependencyKey { Key = "mykey2", Type = this.GetType() }; dependencies.Add(depKey1); dependencies.Add(depKey2); // Act SystemManager.RunWithHttpContext(context, () => controller.AddCacheDependencies(dependencies)); // Assert var cacheObject = context.Items[PageCacheDependencyKeys.PageData]; Assert.IsNotNull(cacheObject, "No cache object was set in the context."); Assert.IsTrue(cacheObject is IList<CacheDependencyKey>, "The cache object was not of the expected type."); var cacheList = (IList<CacheDependencyKey>)cacheObject; Assert.IsTrue(cacheList.Contains(depKey1), "The first cache dependency was not added."); Assert.IsTrue(cacheList.Contains(depKey2), "The second cache dependency was not added."); Assert.AreEqual(dependencies.Count, cacheList.Count, "There is an unexpected count of cache dependency keys."); } /// <summary> /// Checks if AddCacheDependencies method throws InvalidOperationException when the current HttpContext is null. /// </summary> [TestMethod] [Owner("Boyko-Karadzhov")] [Description("Checks if AddCacheDependencies method throws InvalidOperationException when the current HttpContext is null.")] [ExpectedException(typeof(InvalidOperationException))] public void AddCacheDependencies_NullContext_ThrowsInvalidOperationException() { Assert.IsNull(SystemManager.CurrentHttpContext, "Current HttpContext is expected to be null in unit tests but here it is not!"); Controller controller = new DesignerController(); controller.AddCacheDependencies(new CacheDependencyKey[0]); } /// <summary> /// Checks if AddCacheDepencies method throws ArgumentNullException when the controller is null. /// </summary> [TestMethod] [Owner("Boyko-Karadzhov")] [Description("Checks if AddCacheDepencies method throws ArgumentNullException when the controller is null.")] [ExpectedException(typeof(ArgumentNullException))] public void AddCacheDependencies_NullController_ThrowsArgumentNullException() { Controller controller = null; controller.AddCacheDependencies(new CacheDependencyKey[0]); } /// <summary> /// Checks if AddCacheDepencies method throws ArgumentNullException when the keys are null. /// </summary> [TestMethod] [Owner("Boyko-Karadzhov")] [Description("Checks if AddCacheDepencies method throws ArgumentNullException when the keys are null.")] [ExpectedException(typeof(ArgumentNullException))] public void AddCacheDependencies_NullKeys_ThrowsArgumentNullException() { Controller controller = new DesignerController(); /// TODO: fix always is null expression controller.AddCacheDependencies(null); } /// <summary> /// Checks if AddCacheDepencies method throws ArgumentNullException when the keys are null. /// </summary> [TestMethod] [Owner("Boyko-Karadzhov")] [Description("Checks if GetIndexRenderMode method throws ArgumentNullException when the controller is null.")] [ExpectedException(typeof(ArgumentNullException))] public void GetIndexRenderMode_NullController_ThrowsArgumentNullException() { Controller controller = null; controller.GetIndexRenderMode(); } /// <summary> /// Checks if GetIndexRenderMode method returns Normal for controllers without the attribute. /// </summary> [TestMethod] [Owner("Boyko-Karadzhov")] [Description("Checks if GetIndexRenderMode method returns Normal for controllers without the attribute.")] public void GetIndexRenderMode_NoAttributeController_ReturnsNormal() { var controller = new DummyController(); var result = controller.GetIndexRenderMode(); Assert.AreEqual(IndexRenderModes.Normal, result, "Default value for IndexRenderMode was not correct."); } /// <summary> /// Checks if GetIndexRenderMode method returns NoOutput for controllers with attribute and mode set to NoOutput. /// </summary> [TestMethod] [Owner("Boyko-Karadzhov")] [Description("Checks if GetIndexRenderMode method returns NoOutput for controllers with attribute and mode set to NoOutput.")] public void GetIndexRenderMode_AttributeNoOutputController_ReturnsNoOutput() { var controller = new DummyNoOutputInIndexingController(); var result = controller.GetIndexRenderMode(); Assert.AreEqual(IndexRenderModes.NoOutput, result, "IndexRenderMode was not retreived correctly."); } #endregion } }
48.213904
142
0.674357
[ "Apache-2.0" ]
jonathanread/feather
Tests/Telerik.Sitefinity.Frontend.TestUnit/Mvc/Infrastructure/Controllers/ControllerExtensionsTests.cs
9,018
C#
#if WITH_GAME #if PLATFORM_64BITS using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace UnrealEngine { public partial class UBodySetup { static readonly int AggGeom__Offset; public FKAggregateGeom AggGeom { get{ CheckIsValid();return (FKAggregateGeom)Marshal.PtrToStructure(_this.Get()+AggGeom__Offset, typeof(FKAggregateGeom));} set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+AggGeom__Offset, false);} } static readonly int BoneName__Offset; public FName BoneName { get{ CheckIsValid();return (FName)Marshal.PtrToStructure(_this.Get()+BoneName__Offset, typeof(FName));} set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+BoneName__Offset, false);} } static readonly int PhysicsType__Offset; public EPhysicsType PhysicsType { get{ CheckIsValid();return (EPhysicsType)Marshal.PtrToStructure(_this.Get()+PhysicsType__Offset, typeof(EPhysicsType));} set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+PhysicsType__Offset, false);} } static readonly int bAlwaysFullAnimWeight__Offset; public bool bAlwaysFullAnimWeight { get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bAlwaysFullAnimWeight__Offset, 1, 0, 1, 1);} } static readonly int bConsiderForBounds__Offset; public bool bConsiderForBounds { get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bConsiderForBounds__Offset, 1, 0, 2, 2);} set{ CheckIsValid();BoolWrap.Set(value,_this.Get(), bConsiderForBounds__Offset, 1,0,2,2);} } static readonly int bMeshCollideAll__Offset; public bool bMeshCollideAll { get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bMeshCollideAll__Offset, 1, 0, 4, 4);} } static readonly int bDoubleSidedGeometry__Offset; public bool bDoubleSidedGeometry { get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bDoubleSidedGeometry__Offset, 1, 0, 8, 8);} set{ CheckIsValid();BoolWrap.Set(value,_this.Get(), bDoubleSidedGeometry__Offset, 1,0,8,8);} } static readonly int bGenerateNonMirroredCollision__Offset; public bool bGenerateNonMirroredCollision { get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bGenerateNonMirroredCollision__Offset, 1, 0, 16, 16);} } static readonly int bSharedCookedData__Offset; public bool bSharedCookedData { get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bSharedCookedData__Offset, 1, 0, 32, 32);} } static readonly int bGenerateMirroredCollision__Offset; public bool bGenerateMirroredCollision { get{ CheckIsValid();return BoolWrap.Get(_this.Get(), bGenerateMirroredCollision__Offset, 1, 0, 64, 64);} } static readonly int PhysMaterial__Offset; public UPhysicalMaterial PhysMaterial { get{ CheckIsValid(); IntPtr v = Marshal.ReadIntPtr(_this.Get() + PhysMaterial__Offset); if (v == IntPtr.Zero)return null; UPhysicalMaterial retValue = new UPhysicalMaterial(); retValue._this = v; return retValue; } set{ CheckIsValid(); if (value == null)Marshal.WriteIntPtr(_this.Get() + PhysMaterial__Offset, IntPtr.Zero);else Marshal.WriteIntPtr(_this.Get() + PhysMaterial__Offset, value._this.Get()); } } static readonly int CollisionReponse__Offset; public EBodyCollisionResponse CollisionReponse { get{ CheckIsValid();return (EBodyCollisionResponse)Marshal.PtrToStructure(_this.Get()+CollisionReponse__Offset, typeof(EBodyCollisionResponse));} set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+CollisionReponse__Offset, false);} } static readonly int CollisionTraceFlag__Offset; public ECollisionTraceFlag CollisionTraceFlag { get{ CheckIsValid();return (ECollisionTraceFlag)Marshal.PtrToStructure(_this.Get()+CollisionTraceFlag__Offset, typeof(ECollisionTraceFlag));} set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+CollisionTraceFlag__Offset, false);} } static readonly int DefaultInstance__Offset; public FBodyInstance DefaultInstance { get{ CheckIsValid();return (FBodyInstance)Marshal.PtrToStructure(_this.Get()+DefaultInstance__Offset, typeof(FBodyInstance));} set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+DefaultInstance__Offset, false);} } static readonly int WalkableSlopeOverride__Offset; public FWalkableSlopeOverride WalkableSlopeOverride { get{ CheckIsValid();return (FWalkableSlopeOverride)Marshal.PtrToStructure(_this.Get()+WalkableSlopeOverride__Offset, typeof(FWalkableSlopeOverride));} set{ CheckIsValid();Marshal.StructureToPtr(value, _this.Get()+WalkableSlopeOverride__Offset, false);} } static readonly int BuildScale__Offset; public float BuildScale { get{ CheckIsValid();return (float)Marshal.PtrToStructure(_this.Get()+BuildScale__Offset, typeof(float));} } static readonly int BuildScale3D__Offset; public FVector BuildScale3D { get{ CheckIsValid();return (FVector)Marshal.PtrToStructure(_this.Get()+BuildScale3D__Offset, typeof(FVector));} } static UBodySetup() { IntPtr NativeClassPtr=GetNativeClassFromName("BodySetup"); AggGeom__Offset=GetPropertyOffset(NativeClassPtr,"AggGeom"); BoneName__Offset=GetPropertyOffset(NativeClassPtr,"BoneName"); PhysicsType__Offset=GetPropertyOffset(NativeClassPtr,"PhysicsType"); bAlwaysFullAnimWeight__Offset=GetPropertyOffset(NativeClassPtr,"bAlwaysFullAnimWeight"); bConsiderForBounds__Offset=GetPropertyOffset(NativeClassPtr,"bConsiderForBounds"); bMeshCollideAll__Offset=GetPropertyOffset(NativeClassPtr,"bMeshCollideAll"); bDoubleSidedGeometry__Offset=GetPropertyOffset(NativeClassPtr,"bDoubleSidedGeometry"); bGenerateNonMirroredCollision__Offset=GetPropertyOffset(NativeClassPtr,"bGenerateNonMirroredCollision"); bSharedCookedData__Offset=GetPropertyOffset(NativeClassPtr,"bSharedCookedData"); bGenerateMirroredCollision__Offset=GetPropertyOffset(NativeClassPtr,"bGenerateMirroredCollision"); PhysMaterial__Offset=GetPropertyOffset(NativeClassPtr,"PhysMaterial"); CollisionReponse__Offset=GetPropertyOffset(NativeClassPtr,"CollisionReponse"); CollisionTraceFlag__Offset=GetPropertyOffset(NativeClassPtr,"CollisionTraceFlag"); DefaultInstance__Offset=GetPropertyOffset(NativeClassPtr,"DefaultInstance"); WalkableSlopeOverride__Offset=GetPropertyOffset(NativeClassPtr,"WalkableSlopeOverride"); BuildScale__Offset=GetPropertyOffset(NativeClassPtr,"BuildScale"); BuildScale3D__Offset=GetPropertyOffset(NativeClassPtr,"BuildScale3D"); } } } #endif #endif
39.329341
217
0.779385
[ "MIT" ]
RobertAcksel/UnrealCS
Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile_Game_64bits/UBodySetup_FixSize.cs
6,568
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Serialization; namespace Workday.Admissions { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Student_External_Transcript_Student_Prospect_DataType : INotifyPropertyChanged { private StudentObjectType student_Prospect_ReferenceField; private Student_External_Transcript_Student_Prospect_Person_DataType[] student_Prospect_Person_DataField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlElement(Order = 0)] public StudentObjectType Student_Prospect_Reference { get { return this.student_Prospect_ReferenceField; } set { this.student_Prospect_ReferenceField = value; this.RaisePropertyChanged("Student_Prospect_Reference"); } } [XmlElement("Student_Prospect_Person_Data", Order = 1)] public Student_External_Transcript_Student_Prospect_Person_DataType[] Student_Prospect_Person_Data { get { return this.student_Prospect_Person_DataField; } set { this.student_Prospect_Person_DataField = value; this.RaisePropertyChanged("Student_Prospect_Person_Data"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
27.383333
136
0.786366
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.AdmissionsService/Student_External_Transcript_Student_Prospect_DataType.cs
1,643
C#
// Unity C# reference source // Copyright (c) Unity Technologies. For terms of use, see // https://unity3d.com/legal/licenses/Unity_Reference_Only_License using System; using System.Linq; using UnityEngine.Scripting; using System.Runtime.CompilerServices; using UnityEngine.Bindings; using System.Runtime.InteropServices; using Object = UnityEngine.Object; using UnityEngine; namespace UnityEditor { [NativeHeader("Editor/Src/EditorBuildSettings.h")] [NativeAsStruct] [StructLayout(LayoutKind.Sequential)] [UsedByNativeCode] public class EditorBuildSettingsScene : IComparable { [NativeName("enabled")] bool m_enabled; [NativeName("path")] string m_path; [NativeName("guid")] GUID m_guid; public EditorBuildSettingsScene() {} public EditorBuildSettingsScene(string path, bool enabled) { m_path = path.Replace("\\", "/"); m_enabled = enabled; GUID.TryParse(AssetDatabase.AssetPathToGUID(path), out m_guid); } public EditorBuildSettingsScene(GUID guid, bool enabled) { m_guid = guid; m_enabled = enabled; m_path = AssetDatabase.GUIDToAssetPath(guid.ToString()); } public bool enabled { get { return m_enabled; } set { m_enabled = value; } } public string path { get { return m_path; } set { m_path = value.Replace("\\", "/"); } } public GUID guid { get { return m_guid; } set { m_guid = value; } } public static string[] GetActiveSceneList(EditorBuildSettingsScene[] scenes) { return scenes.Where(scene => scene.enabled).Select(scene => scene.path).ToArray(); } public int CompareTo(object obj) { if (obj is EditorBuildSettingsScene) { EditorBuildSettingsScene temp = (EditorBuildSettingsScene)obj; return temp.path.CompareTo(path); } throw new ArgumentException("object is not a EditorBuildSettingsScene"); } } [NativeHeader("Editor/Src/EditorBuildSettings.h")] public partial class EditorBuildSettings : UnityEngine.Object { private EditorBuildSettings() {} public static event Action sceneListChanged; [RequiredByNativeCode] private static void SceneListChanged() { if (sceneListChanged != null) sceneListChanged(); } public static EditorBuildSettingsScene[] scenes { get { var result = GetEditorBuildSettingsScenes(); foreach (var scene in result) { if (scene.guid.Empty()) { scene.guid = new GUID(AssetDatabase.AssetPathToGUID(scene.path)); } else { scene.path = AssetDatabase.GUIDToAssetPath(scene.guid.ToString()); } } return result; } set { SetEditorBuildSettingsScenes(value); } } static extern EditorBuildSettingsScene[] GetEditorBuildSettingsScenes(); static extern void SetEditorBuildSettingsScenes(EditorBuildSettingsScene[] scenes); enum ConfigObjectResult { Succeeded, FailedEntryNotFound, FailedNullObj, FailedNonPersistedObj, FailedEntryExists, FailedTypeMismatch } [NativeMethod("AddConfigObject")] static extern ConfigObjectResult AddConfigObjectInternal(string name, Object obj, bool overwrite); public static extern bool RemoveConfigObject(string name); public static extern string[] GetConfigObjectNames(); static extern Object GetConfigObject(string name); public static void AddConfigObject(string name, Object obj, bool overwrite) { var result = AddConfigObjectInternal(name, obj, overwrite); if (result == ConfigObjectResult.Succeeded) return; switch (result) { case ConfigObjectResult.FailedEntryExists: throw new Exception("Config object with name '" + name + "' already exists."); case ConfigObjectResult.FailedNonPersistedObj: throw new Exception("Cannot add non-persisted config object with name '" + name + "'."); case ConfigObjectResult.FailedNullObj: throw new Exception("Cannot add null config object with name '" + name + "'."); } } public static bool TryGetConfigObject<T>(string name, out T result) where T : Object { result = GetConfigObject(name) as T; return result != null; } } }
36.022059
151
0.595428
[ "Unlicense" ]
HelloWindows/AccountBook
client/framework/UnityCsReference-master/Editor/Mono/EditorBuildSettings.bindings.cs
4,899
C#
 namespace CachedCrudLib { public interface ICacheable { string Key { get; } } }
14
33
0.602041
[ "MIT" ]
Williams-Forrest/CachedCRUD
CachedCrudLib/ICacheable.cs
100
C#
using System; using _06.TrafficLights.Contracts; namespace _06.TrafficLights.Models { public class TrafficLight : ITrafficLight { private Light light; public TrafficLight(string light) { this.Light = (Light)Enum.Parse(typeof(Light), light); } public Light Light { get => this.light; private set => this.light = value; } public void ChangeLights() { this.Light += 1; this.Light = (int)this.Light > 2 ? 0 : this.Light; //if ((int)this.Light > 2) //{ // this.Light = 0; //} } public override string ToString() { return $"{this.Light}"; } } }
20.153846
65
0.479644
[ "MIT" ]
anedyalkov/CSharp-OOP-Advanced
08.Reflection and Attributes-Exercises/P06_TrafficLights/Models/TrafficLight.cs
788
C#
// Code generated from gen/decArgs.rules; DO NOT EDIT. // generated with: cd gen; go run *.go // package ssa -- go2cs converted at 2020 October 09 05:32:56 UTC // import "cmd/compile/internal/ssa" ==> using ssa = go.cmd.compile.@internal.ssa_package // Original source: C:\Go\src\cmd\compile\internal\ssa\rewritedecArgs.go using static go.builtin; namespace go { namespace cmd { namespace compile { namespace @internal { public static partial class ssa_package { private static bool rewriteValuedecArgs(ptr<Value> _addr_v) { ref Value v = ref _addr_v.val; if (v.Op == OpArg) return rewriteValuedecArgs_OpArg(_addr_v); return false; } private static bool rewriteValuedecArgs_OpArg(ptr<Value> _addr_v) { ref Value v = ref _addr_v.val; var b = v.Block; var config = b.Func.Config; var fe = b.Func.fe; var typ = _addr_b.Func.Config.Types; // match: (Arg {n} [off]) // cond: v.Type.IsString() // result: (StringMake (Arg <typ.BytePtr> {n} [off]) (Arg <typ.Int> {n} [off+int32(config.PtrSize)])) while (true) { var off = auxIntToInt32(v.AuxInt); var n = auxToSym(v.Aux); if (!(v.Type.IsString())) { break; } v.reset(OpStringMake); var v0 = b.NewValue0(v.Pos, OpArg, typ.BytePtr); v0.AuxInt = int32ToAuxInt(off); v0.Aux = symToAux(n); var v1 = b.NewValue0(v.Pos, OpArg, typ.Int); v1.AuxInt = int32ToAuxInt(off + int32(config.PtrSize)); v1.Aux = symToAux(n); v.AddArg2(v0, v1); return true; } // match: (Arg {n} [off]) // cond: v.Type.IsSlice() // result: (SliceMake (Arg <v.Type.Elem().PtrTo()> {n} [off]) (Arg <typ.Int> {n} [off+int32(config.PtrSize)]) (Arg <typ.Int> {n} [off+2*int32(config.PtrSize)])) // match: (Arg {n} [off]) // cond: v.Type.IsSlice() // result: (SliceMake (Arg <v.Type.Elem().PtrTo()> {n} [off]) (Arg <typ.Int> {n} [off+int32(config.PtrSize)]) (Arg <typ.Int> {n} [off+2*int32(config.PtrSize)])) while (true) { off = auxIntToInt32(v.AuxInt); n = auxToSym(v.Aux); if (!(v.Type.IsSlice())) { break; } v.reset(OpSliceMake); v0 = b.NewValue0(v.Pos, OpArg, v.Type.Elem().PtrTo()); v0.AuxInt = int32ToAuxInt(off); v0.Aux = symToAux(n); v1 = b.NewValue0(v.Pos, OpArg, typ.Int); v1.AuxInt = int32ToAuxInt(off + int32(config.PtrSize)); v1.Aux = symToAux(n); var v2 = b.NewValue0(v.Pos, OpArg, typ.Int); v2.AuxInt = int32ToAuxInt(off + 2L * int32(config.PtrSize)); v2.Aux = symToAux(n); v.AddArg3(v0, v1, v2); return true; } // match: (Arg {n} [off]) // cond: v.Type.IsInterface() // result: (IMake (Arg <typ.Uintptr> {n} [off]) (Arg <typ.BytePtr> {n} [off+int32(config.PtrSize)])) // match: (Arg {n} [off]) // cond: v.Type.IsInterface() // result: (IMake (Arg <typ.Uintptr> {n} [off]) (Arg <typ.BytePtr> {n} [off+int32(config.PtrSize)])) while (true) { off = auxIntToInt32(v.AuxInt); n = auxToSym(v.Aux); if (!(v.Type.IsInterface())) { break; } v.reset(OpIMake); v0 = b.NewValue0(v.Pos, OpArg, typ.Uintptr); v0.AuxInt = int32ToAuxInt(off); v0.Aux = symToAux(n); v1 = b.NewValue0(v.Pos, OpArg, typ.BytePtr); v1.AuxInt = int32ToAuxInt(off + int32(config.PtrSize)); v1.Aux = symToAux(n); v.AddArg2(v0, v1); return true; } // match: (Arg {n} [off]) // cond: v.Type.IsComplex() && v.Type.Size() == 16 // result: (ComplexMake (Arg <typ.Float64> {n} [off]) (Arg <typ.Float64> {n} [off+8])) // match: (Arg {n} [off]) // cond: v.Type.IsComplex() && v.Type.Size() == 16 // result: (ComplexMake (Arg <typ.Float64> {n} [off]) (Arg <typ.Float64> {n} [off+8])) while (true) { off = auxIntToInt32(v.AuxInt); n = auxToSym(v.Aux); if (!(v.Type.IsComplex() && v.Type.Size() == 16L)) { break; } v.reset(OpComplexMake); v0 = b.NewValue0(v.Pos, OpArg, typ.Float64); v0.AuxInt = int32ToAuxInt(off); v0.Aux = symToAux(n); v1 = b.NewValue0(v.Pos, OpArg, typ.Float64); v1.AuxInt = int32ToAuxInt(off + 8L); v1.Aux = symToAux(n); v.AddArg2(v0, v1); return true; } // match: (Arg {n} [off]) // cond: v.Type.IsComplex() && v.Type.Size() == 8 // result: (ComplexMake (Arg <typ.Float32> {n} [off]) (Arg <typ.Float32> {n} [off+4])) // match: (Arg {n} [off]) // cond: v.Type.IsComplex() && v.Type.Size() == 8 // result: (ComplexMake (Arg <typ.Float32> {n} [off]) (Arg <typ.Float32> {n} [off+4])) while (true) { off = auxIntToInt32(v.AuxInt); n = auxToSym(v.Aux); if (!(v.Type.IsComplex() && v.Type.Size() == 8L)) { break; } v.reset(OpComplexMake); v0 = b.NewValue0(v.Pos, OpArg, typ.Float32); v0.AuxInt = int32ToAuxInt(off); v0.Aux = symToAux(n); v1 = b.NewValue0(v.Pos, OpArg, typ.Float32); v1.AuxInt = int32ToAuxInt(off + 4L); v1.Aux = symToAux(n); v.AddArg2(v0, v1); return true; } // match: (Arg <t>) // cond: t.IsStruct() && t.NumFields() == 0 && fe.CanSSA(t) // result: (StructMake0) // match: (Arg <t>) // cond: t.IsStruct() && t.NumFields() == 0 && fe.CanSSA(t) // result: (StructMake0) while (true) { var t = v.Type; if (!(t.IsStruct() && t.NumFields() == 0L && fe.CanSSA(t))) { break; } v.reset(OpStructMake0); return true; } // match: (Arg <t> {n} [off]) // cond: t.IsStruct() && t.NumFields() == 1 && fe.CanSSA(t) // result: (StructMake1 (Arg <t.FieldType(0)> {n} [off+int32(t.FieldOff(0))])) // match: (Arg <t> {n} [off]) // cond: t.IsStruct() && t.NumFields() == 1 && fe.CanSSA(t) // result: (StructMake1 (Arg <t.FieldType(0)> {n} [off+int32(t.FieldOff(0))])) while (true) { t = v.Type; off = auxIntToInt32(v.AuxInt); n = auxToSym(v.Aux); if (!(t.IsStruct() && t.NumFields() == 1L && fe.CanSSA(t))) { break; } v.reset(OpStructMake1); v0 = b.NewValue0(v.Pos, OpArg, t.FieldType(0L)); v0.AuxInt = int32ToAuxInt(off + int32(t.FieldOff(0L))); v0.Aux = symToAux(n); v.AddArg(v0); return true; } // match: (Arg <t> {n} [off]) // cond: t.IsStruct() && t.NumFields() == 2 && fe.CanSSA(t) // result: (StructMake2 (Arg <t.FieldType(0)> {n} [off+int32(t.FieldOff(0))]) (Arg <t.FieldType(1)> {n} [off+int32(t.FieldOff(1))])) // match: (Arg <t> {n} [off]) // cond: t.IsStruct() && t.NumFields() == 2 && fe.CanSSA(t) // result: (StructMake2 (Arg <t.FieldType(0)> {n} [off+int32(t.FieldOff(0))]) (Arg <t.FieldType(1)> {n} [off+int32(t.FieldOff(1))])) while (true) { t = v.Type; off = auxIntToInt32(v.AuxInt); n = auxToSym(v.Aux); if (!(t.IsStruct() && t.NumFields() == 2L && fe.CanSSA(t))) { break; } v.reset(OpStructMake2); v0 = b.NewValue0(v.Pos, OpArg, t.FieldType(0L)); v0.AuxInt = int32ToAuxInt(off + int32(t.FieldOff(0L))); v0.Aux = symToAux(n); v1 = b.NewValue0(v.Pos, OpArg, t.FieldType(1L)); v1.AuxInt = int32ToAuxInt(off + int32(t.FieldOff(1L))); v1.Aux = symToAux(n); v.AddArg2(v0, v1); return true; } // match: (Arg <t> {n} [off]) // cond: t.IsStruct() && t.NumFields() == 3 && fe.CanSSA(t) // result: (StructMake3 (Arg <t.FieldType(0)> {n} [off+int32(t.FieldOff(0))]) (Arg <t.FieldType(1)> {n} [off+int32(t.FieldOff(1))]) (Arg <t.FieldType(2)> {n} [off+int32(t.FieldOff(2))])) // match: (Arg <t> {n} [off]) // cond: t.IsStruct() && t.NumFields() == 3 && fe.CanSSA(t) // result: (StructMake3 (Arg <t.FieldType(0)> {n} [off+int32(t.FieldOff(0))]) (Arg <t.FieldType(1)> {n} [off+int32(t.FieldOff(1))]) (Arg <t.FieldType(2)> {n} [off+int32(t.FieldOff(2))])) while (true) { t = v.Type; off = auxIntToInt32(v.AuxInt); n = auxToSym(v.Aux); if (!(t.IsStruct() && t.NumFields() == 3L && fe.CanSSA(t))) { break; } v.reset(OpStructMake3); v0 = b.NewValue0(v.Pos, OpArg, t.FieldType(0L)); v0.AuxInt = int32ToAuxInt(off + int32(t.FieldOff(0L))); v0.Aux = symToAux(n); v1 = b.NewValue0(v.Pos, OpArg, t.FieldType(1L)); v1.AuxInt = int32ToAuxInt(off + int32(t.FieldOff(1L))); v1.Aux = symToAux(n); v2 = b.NewValue0(v.Pos, OpArg, t.FieldType(2L)); v2.AuxInt = int32ToAuxInt(off + int32(t.FieldOff(2L))); v2.Aux = symToAux(n); v.AddArg3(v0, v1, v2); return true; } // match: (Arg <t> {n} [off]) // cond: t.IsStruct() && t.NumFields() == 4 && fe.CanSSA(t) // result: (StructMake4 (Arg <t.FieldType(0)> {n} [off+int32(t.FieldOff(0))]) (Arg <t.FieldType(1)> {n} [off+int32(t.FieldOff(1))]) (Arg <t.FieldType(2)> {n} [off+int32(t.FieldOff(2))]) (Arg <t.FieldType(3)> {n} [off+int32(t.FieldOff(3))])) // match: (Arg <t> {n} [off]) // cond: t.IsStruct() && t.NumFields() == 4 && fe.CanSSA(t) // result: (StructMake4 (Arg <t.FieldType(0)> {n} [off+int32(t.FieldOff(0))]) (Arg <t.FieldType(1)> {n} [off+int32(t.FieldOff(1))]) (Arg <t.FieldType(2)> {n} [off+int32(t.FieldOff(2))]) (Arg <t.FieldType(3)> {n} [off+int32(t.FieldOff(3))])) while (true) { t = v.Type; off = auxIntToInt32(v.AuxInt); n = auxToSym(v.Aux); if (!(t.IsStruct() && t.NumFields() == 4L && fe.CanSSA(t))) { break; } v.reset(OpStructMake4); v0 = b.NewValue0(v.Pos, OpArg, t.FieldType(0L)); v0.AuxInt = int32ToAuxInt(off + int32(t.FieldOff(0L))); v0.Aux = symToAux(n); v1 = b.NewValue0(v.Pos, OpArg, t.FieldType(1L)); v1.AuxInt = int32ToAuxInt(off + int32(t.FieldOff(1L))); v1.Aux = symToAux(n); v2 = b.NewValue0(v.Pos, OpArg, t.FieldType(2L)); v2.AuxInt = int32ToAuxInt(off + int32(t.FieldOff(2L))); v2.Aux = symToAux(n); var v3 = b.NewValue0(v.Pos, OpArg, t.FieldType(3L)); v3.AuxInt = int32ToAuxInt(off + int32(t.FieldOff(3L))); v3.Aux = symToAux(n); v.AddArg4(v0, v1, v2, v3); return true; } // match: (Arg <t>) // cond: t.IsArray() && t.NumElem() == 0 // result: (ArrayMake0) // match: (Arg <t>) // cond: t.IsArray() && t.NumElem() == 0 // result: (ArrayMake0) while (true) { t = v.Type; if (!(t.IsArray() && t.NumElem() == 0L)) { break; } v.reset(OpArrayMake0); return true; } // match: (Arg <t> {n} [off]) // cond: t.IsArray() && t.NumElem() == 1 && fe.CanSSA(t) // result: (ArrayMake1 (Arg <t.Elem()> {n} [off])) // match: (Arg <t> {n} [off]) // cond: t.IsArray() && t.NumElem() == 1 && fe.CanSSA(t) // result: (ArrayMake1 (Arg <t.Elem()> {n} [off])) while (true) { t = v.Type; off = auxIntToInt32(v.AuxInt); n = auxToSym(v.Aux); if (!(t.IsArray() && t.NumElem() == 1L && fe.CanSSA(t))) { break; } v.reset(OpArrayMake1); v0 = b.NewValue0(v.Pos, OpArg, t.Elem()); v0.AuxInt = int32ToAuxInt(off); v0.Aux = symToAux(n); v.AddArg(v0); return true; } return false; } private static bool rewriteBlockdecArgs(ptr<Block> _addr_b) { ref Block b = ref _addr_b.val; switch (b.Kind) { } return false; } } }}}}
39.31694
252
0.436553
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/cmd/compile/internal/ssa/rewritedecArgs.cs
14,390
C#
using System; using System.Collections.Generic; using System.Linq; namespace Exceptionless { internal static class CollectionEqualityExtensions { public static bool CollectionEquals<T>(this IEnumerable<T> source, IEnumerable<T> other) { var sourceEnumerator = source.GetEnumerator(); var otherEnumerator = other.GetEnumerator(); while (sourceEnumerator.MoveNext()) { if (!otherEnumerator.MoveNext()) { // counts differ return false; } if (sourceEnumerator.Current.Equals(otherEnumerator.Current)) { // values aren't equal return false; } } if (otherEnumerator.MoveNext()) { // counts differ return false; } return true; } public static bool CollectionEquals<TValue>(this IDictionary<string, TValue> source, IDictionary<string, TValue> other) { if (source.Count != other.Count) { return false; } foreach (var key in source.Keys) { var sourceValue = source[key]; TValue otherValue; if (!other.TryGetValue(key, out otherValue)) { return false; } if (sourceValue.Equals(otherValue)) { return false; } } return true; } public static int GetCollectionHashCode<T>(this IEnumerable<T> source) { var assemblyQualifiedName = typeof(T).AssemblyQualifiedName; int hashCode = assemblyQualifiedName == null ? 0 : assemblyQualifiedName.GetHashCode(); foreach (var item in source) { if (item == null) continue; unchecked { hashCode = (hashCode * 397) ^ item.GetHashCode(); } } return hashCode; } public static int GetCollectionHashCode<TValue>(this IDictionary<string, TValue> source, IList<string> exclusions = null) { var assemblyQualifiedName = typeof(TValue).AssemblyQualifiedName; int hashCode = assemblyQualifiedName == null ? 0 : assemblyQualifiedName.GetHashCode(); var keyValuePairHashes = new List<int>(source.Keys.Count); foreach (var key in source.Keys.OrderBy(x => x)) { if (exclusions != null && exclusions.Contains(key)) continue; var item = source[key]; unchecked { var kvpHash = key.GetHashCode(); kvpHash = (kvpHash * 397) ^ (item == null ? 0 : item.GetHashCode()); keyValuePairHashes.Add(kvpHash); } } keyValuePairHashes.Sort(); foreach (var kvpHash in keyValuePairHashes) { unchecked { hashCode = (hashCode * 397) ^ kvpHash; } } return hashCode; } } }
34.075269
131
0.514673
[ "Apache-2.0" ]
PolitovArtyom/Exceptionless.Net
src/Exceptionless/Extensions/CollectionEqualityExtensions.cs
3,171
C#
namespace SimpleNotepad { partial class SimpleNotepad { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SimpleNotepad)); this.MenuStrip = new System.Windows.Forms.MenuStrip(); this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.NewToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.OpenToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.SaveToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.SaveAsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator(); this.CloseToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.CloseAllToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator(); this.ExitToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.editToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.undoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.redoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.formatToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.FontToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.EncodingToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ANSIToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.UTF8ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.settingsToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.themeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.DefaultToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.DarkModeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.PureBlackModeToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.BottomToolStrip = new System.Windows.Forms.ToolStrip(); this.TextLengthLabel = new System.Windows.Forms.ToolStripLabel(); this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator(); this.LineTotalLabel = new System.Windows.Forms.ToolStripLabel(); this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator(); this.TopToolStrip = new System.Windows.Forms.ToolStrip(); this.NewToolStripButton = new System.Windows.Forms.ToolStripButton(); this.OpenToolStripButton = new System.Windows.Forms.ToolStripButton(); this.SaveToolStripButton = new System.Windows.Forms.ToolStripButton(); this.SaveAsToolStripButton = new System.Windows.Forms.ToolStripButton(); this.CloseToolStripButton = new System.Windows.Forms.ToolStripButton(); this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator(); this.FontToolStripButton = new System.Windows.Forms.ToolStripButton(); this.Runtime = new System.Windows.Forms.Timer(this.components); this.TabbedNotepad = new System.Windows.Forms.TabControl(); this.EncodingLabel = new System.Windows.Forms.ToolStripLabel(); this.ASCIIToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.MenuStrip.SuspendLayout(); this.BottomToolStrip.SuspendLayout(); this.TopToolStrip.SuspendLayout(); this.SuspendLayout(); // // MenuStrip // this.MenuStrip.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240))))); this.MenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.fileToolStripMenuItem, this.editToolStripMenuItem, this.formatToolStripMenuItem, this.settingsToolStripMenuItem}); this.MenuStrip.Location = new System.Drawing.Point(0, 0); this.MenuStrip.Name = "MenuStrip"; this.MenuStrip.Size = new System.Drawing.Size(800, 24); this.MenuStrip.TabIndex = 0; this.MenuStrip.Text = "menuStrip1"; // // fileToolStripMenuItem // this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.NewToolStripMenuItem, this.OpenToolStripMenuItem, this.SaveToolStripMenuItem, this.SaveAsToolStripMenuItem, this.toolStripSeparator3, this.CloseToolStripMenuItem, this.CloseAllToolStripMenuItem, this.toolStripSeparator4, this.ExitToolStripMenuItem}); this.fileToolStripMenuItem.Name = "fileToolStripMenuItem"; this.fileToolStripMenuItem.Size = new System.Drawing.Size(37, 20); this.fileToolStripMenuItem.Text = "File"; // // NewToolStripMenuItem // this.NewToolStripMenuItem.Name = "NewToolStripMenuItem"; this.NewToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N))); this.NewToolStripMenuItem.Size = new System.Drawing.Size(197, 22); this.NewToolStripMenuItem.Text = "New"; this.NewToolStripMenuItem.ToolTipText = "New"; this.NewToolStripMenuItem.Click += new System.EventHandler(this.NewToolStripMenuItem_Click); // // OpenToolStripMenuItem // this.OpenToolStripMenuItem.Name = "OpenToolStripMenuItem"; this.OpenToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O))); this.OpenToolStripMenuItem.Size = new System.Drawing.Size(197, 22); this.OpenToolStripMenuItem.Text = "Open..."; this.OpenToolStripMenuItem.ToolTipText = "Open"; this.OpenToolStripMenuItem.Click += new System.EventHandler(this.OpenToolStripMenuItem_Click); // // SaveToolStripMenuItem // this.SaveToolStripMenuItem.Name = "SaveToolStripMenuItem"; this.SaveToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S))); this.SaveToolStripMenuItem.Size = new System.Drawing.Size(197, 22); this.SaveToolStripMenuItem.Text = "Save"; this.SaveToolStripMenuItem.ToolTipText = "Save"; this.SaveToolStripMenuItem.Click += new System.EventHandler(this.SaveToolStripMenuItem_Click); // // SaveAsToolStripMenuItem // this.SaveAsToolStripMenuItem.Name = "SaveAsToolStripMenuItem"; this.SaveAsToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Alt) | System.Windows.Forms.Keys.S))); this.SaveAsToolStripMenuItem.Size = new System.Drawing.Size(197, 22); this.SaveAsToolStripMenuItem.Text = "Save As..."; this.SaveAsToolStripMenuItem.ToolTipText = "Save As"; this.SaveAsToolStripMenuItem.Click += new System.EventHandler(this.SaveAsToolStripMenuItem_Click); // // toolStripSeparator3 // this.toolStripSeparator3.Name = "toolStripSeparator3"; this.toolStripSeparator3.Size = new System.Drawing.Size(194, 6); // // CloseToolStripMenuItem // this.CloseToolStripMenuItem.Name = "CloseToolStripMenuItem"; this.CloseToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.W))); this.CloseToolStripMenuItem.Size = new System.Drawing.Size(197, 22); this.CloseToolStripMenuItem.Text = "Close"; this.CloseToolStripMenuItem.ToolTipText = "Close"; this.CloseToolStripMenuItem.Click += new System.EventHandler(this.CloseToolStripMenuItem_Click); // // CloseAllToolStripMenuItem // this.CloseAllToolStripMenuItem.Name = "CloseAllToolStripMenuItem"; this.CloseAllToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift) | System.Windows.Forms.Keys.W))); this.CloseAllToolStripMenuItem.Size = new System.Drawing.Size(197, 22); this.CloseAllToolStripMenuItem.Text = "Close All"; this.CloseAllToolStripMenuItem.ToolTipText = "Close All"; this.CloseAllToolStripMenuItem.Click += new System.EventHandler(this.CloseAllToolStripMenuItem_Click); // // toolStripSeparator4 // this.toolStripSeparator4.Name = "toolStripSeparator4"; this.toolStripSeparator4.Size = new System.Drawing.Size(194, 6); // // ExitToolStripMenuItem // this.ExitToolStripMenuItem.Name = "ExitToolStripMenuItem"; this.ExitToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F4))); this.ExitToolStripMenuItem.Size = new System.Drawing.Size(197, 22); this.ExitToolStripMenuItem.Text = "Exit"; this.ExitToolStripMenuItem.Click += new System.EventHandler(this.ExitToolStripMenuItem_Click); // // editToolStripMenuItem // this.editToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.undoToolStripMenuItem, this.redoToolStripMenuItem}); this.editToolStripMenuItem.Name = "editToolStripMenuItem"; this.editToolStripMenuItem.Size = new System.Drawing.Size(39, 20); this.editToolStripMenuItem.Text = "Edit"; // // undoToolStripMenuItem // this.undoToolStripMenuItem.Name = "undoToolStripMenuItem"; this.undoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Z))); this.undoToolStripMenuItem.Size = new System.Drawing.Size(174, 22); this.undoToolStripMenuItem.Text = "Undo"; this.undoToolStripMenuItem.Click += new System.EventHandler(this.UndoToolStripMenuItem_Click); // // redoToolStripMenuItem // this.redoToolStripMenuItem.Name = "redoToolStripMenuItem"; this.redoToolStripMenuItem.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift) | System.Windows.Forms.Keys.Z))); this.redoToolStripMenuItem.Size = new System.Drawing.Size(174, 22); this.redoToolStripMenuItem.Text = "Redo"; this.redoToolStripMenuItem.Click += new System.EventHandler(this.RedoToolStripMenuItem_Click); // // formatToolStripMenuItem // this.formatToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.FontToolStripMenuItem, this.EncodingToolStripMenuItem}); this.formatToolStripMenuItem.Name = "formatToolStripMenuItem"; this.formatToolStripMenuItem.Size = new System.Drawing.Size(57, 20); this.formatToolStripMenuItem.Text = "Format"; // // FontToolStripMenuItem // this.FontToolStripMenuItem.Name = "FontToolStripMenuItem"; this.FontToolStripMenuItem.Size = new System.Drawing.Size(180, 22); this.FontToolStripMenuItem.Text = "Font..."; this.FontToolStripMenuItem.Click += new System.EventHandler(this.FontToolStripMenuItem_Click); // // EncodingToolStripMenuItem // this.EncodingToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.ANSIToolStripMenuItem, this.ASCIIToolStripMenuItem, this.UTF8ToolStripMenuItem}); this.EncodingToolStripMenuItem.Name = "EncodingToolStripMenuItem"; this.EncodingToolStripMenuItem.Size = new System.Drawing.Size(180, 22); this.EncodingToolStripMenuItem.Text = "Encoding"; // // ANSIToolStripMenuItem // this.ANSIToolStripMenuItem.Name = "ANSIToolStripMenuItem"; this.ANSIToolStripMenuItem.Size = new System.Drawing.Size(180, 22); this.ANSIToolStripMenuItem.Text = "ANSI"; this.ANSIToolStripMenuItem.Click += new System.EventHandler(this.SetEncodingToolStripMenuItem_Click); // // UTF8ToolStripMenuItem // this.UTF8ToolStripMenuItem.Checked = true; this.UTF8ToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.UTF8ToolStripMenuItem.Name = "UTF8ToolStripMenuItem"; this.UTF8ToolStripMenuItem.Size = new System.Drawing.Size(180, 22); this.UTF8ToolStripMenuItem.Text = "UTF-8"; this.UTF8ToolStripMenuItem.Click += new System.EventHandler(this.SetEncodingToolStripMenuItem_Click); // // settingsToolStripMenuItem // this.settingsToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.themeToolStripMenuItem}); this.settingsToolStripMenuItem.Name = "settingsToolStripMenuItem"; this.settingsToolStripMenuItem.Size = new System.Drawing.Size(61, 20); this.settingsToolStripMenuItem.Text = "Settings"; // // themeToolStripMenuItem // this.themeToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.DefaultToolStripMenuItem, this.DarkModeToolStripMenuItem, this.PureBlackModeToolStripMenuItem}); this.themeToolStripMenuItem.Name = "themeToolStripMenuItem"; this.themeToolStripMenuItem.Size = new System.Drawing.Size(180, 22); this.themeToolStripMenuItem.Text = "Theme"; // // DefaultToolStripMenuItem // this.DefaultToolStripMenuItem.Checked = true; this.DefaultToolStripMenuItem.CheckState = System.Windows.Forms.CheckState.Checked; this.DefaultToolStripMenuItem.Name = "DefaultToolStripMenuItem"; this.DefaultToolStripMenuItem.Size = new System.Drawing.Size(165, 22); this.DefaultToolStripMenuItem.Text = "Default"; this.DefaultToolStripMenuItem.Click += new System.EventHandler(this.SetDefaultThemeToolStripMenuItem_Click); // // DarkModeToolStripMenuItem // this.DarkModeToolStripMenuItem.Name = "DarkModeToolStripMenuItem"; this.DarkModeToolStripMenuItem.Size = new System.Drawing.Size(165, 22); this.DarkModeToolStripMenuItem.Text = "Dark Mode"; this.DarkModeToolStripMenuItem.Click += new System.EventHandler(this.SetDefaultThemeToolStripMenuItem_Click); // // PureBlackModeToolStripMenuItem // this.PureBlackModeToolStripMenuItem.Name = "PureBlackModeToolStripMenuItem"; this.PureBlackModeToolStripMenuItem.Size = new System.Drawing.Size(165, 22); this.PureBlackModeToolStripMenuItem.Text = "Pure-Black Mode"; this.PureBlackModeToolStripMenuItem.Click += new System.EventHandler(this.SetDefaultThemeToolStripMenuItem_Click); // // BottomToolStrip // this.BottomToolStrip.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240))))); this.BottomToolStrip.Dock = System.Windows.Forms.DockStyle.Bottom; this.BottomToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.BottomToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.TextLengthLabel, this.toolStripSeparator1, this.LineTotalLabel, this.toolStripSeparator2, this.EncodingLabel}); this.BottomToolStrip.Location = new System.Drawing.Point(0, 425); this.BottomToolStrip.Name = "BottomToolStrip"; this.BottomToolStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; this.BottomToolStrip.Size = new System.Drawing.Size(800, 25); this.BottomToolStrip.TabIndex = 3; this.BottomToolStrip.Text = "toolStrip2"; // // TextLengthLabel // this.TextLengthLabel.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.TextLengthLabel.Name = "TextLengthLabel"; this.TextLengthLabel.Size = new System.Drawing.Size(56, 22); this.TextLengthLabel.Text = "Length: 0"; // // toolStripSeparator1 // this.toolStripSeparator1.Name = "toolStripSeparator1"; this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25); // // LineTotalLabel // this.LineTotalLabel.Name = "LineTotalLabel"; this.LineTotalLabel.Size = new System.Drawing.Size(46, 22); this.LineTotalLabel.Text = "Lines: 0"; // // toolStripSeparator2 // this.toolStripSeparator2.Name = "toolStripSeparator2"; this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25); // // TopToolStrip // this.TopToolStrip.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(240)))), ((int)(((byte)(240)))), ((int)(((byte)(240))))); this.TopToolStrip.GripMargin = new System.Windows.Forms.Padding(0); this.TopToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.TopToolStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.NewToolStripButton, this.OpenToolStripButton, this.SaveToolStripButton, this.SaveAsToolStripButton, this.CloseToolStripButton, this.toolStripSeparator5, this.FontToolStripButton}); this.TopToolStrip.Location = new System.Drawing.Point(0, 24); this.TopToolStrip.Name = "TopToolStrip"; this.TopToolStrip.RenderMode = System.Windows.Forms.ToolStripRenderMode.System; this.TopToolStrip.Size = new System.Drawing.Size(800, 25); this.TopToolStrip.TabIndex = 5; this.TopToolStrip.Text = "toolStrip2"; // // NewToolStripButton // this.NewToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.NewToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("NewToolStripButton.Image"))); this.NewToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.NewToolStripButton.Name = "NewToolStripButton"; this.NewToolStripButton.Size = new System.Drawing.Size(35, 22); this.NewToolStripButton.Text = "New"; this.NewToolStripButton.Click += new System.EventHandler(this.NewToolStripButton_Click); // // OpenToolStripButton // this.OpenToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.OpenToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("OpenToolStripButton.Image"))); this.OpenToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.OpenToolStripButton.Name = "OpenToolStripButton"; this.OpenToolStripButton.Size = new System.Drawing.Size(49, 22); this.OpenToolStripButton.Text = "Open..."; this.OpenToolStripButton.Click += new System.EventHandler(this.OpenToolStripButton_Click); // // SaveToolStripButton // this.SaveToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.SaveToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("SaveToolStripButton.Image"))); this.SaveToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.SaveToolStripButton.Name = "SaveToolStripButton"; this.SaveToolStripButton.Size = new System.Drawing.Size(35, 22); this.SaveToolStripButton.Text = "Save"; this.SaveToolStripButton.Click += new System.EventHandler(this.SaveToolStripButton_Click); // // SaveAsToolStripButton // this.SaveAsToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.SaveAsToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("SaveAsToolStripButton.Image"))); this.SaveAsToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.SaveAsToolStripButton.Name = "SaveAsToolStripButton"; this.SaveAsToolStripButton.Size = new System.Drawing.Size(60, 22); this.SaveAsToolStripButton.Text = "Save As..."; this.SaveAsToolStripButton.Click += new System.EventHandler(this.SaveAsToolStripButton_Click); // // CloseToolStripButton // this.CloseToolStripButton.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.CloseToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.CloseToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("CloseToolStripButton.Image"))); this.CloseToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.CloseToolStripButton.Name = "CloseToolStripButton"; this.CloseToolStripButton.Size = new System.Drawing.Size(23, 22); this.CloseToolStripButton.Text = "X"; this.CloseToolStripButton.ToolTipText = "Close"; this.CloseToolStripButton.Click += new System.EventHandler(this.CloseToolStripButton_Click); this.CloseToolStripButton.MouseHover += new System.EventHandler(this.CloseToolStripButton_MouseHover); // // toolStripSeparator5 // this.toolStripSeparator5.Name = "toolStripSeparator5"; this.toolStripSeparator5.Size = new System.Drawing.Size(6, 25); // // FontToolStripButton // this.FontToolStripButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Text; this.FontToolStripButton.Image = ((System.Drawing.Image)(resources.GetObject("FontToolStripButton.Image"))); this.FontToolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.FontToolStripButton.Name = "FontToolStripButton"; this.FontToolStripButton.Size = new System.Drawing.Size(44, 22); this.FontToolStripButton.Text = "Font..."; this.FontToolStripButton.Click += new System.EventHandler(this.FontToolStripButton_Click); // // Runtime // this.Runtime.Enabled = true; this.Runtime.Tick += new System.EventHandler(this.Runtime_Tick); // // TabbedNotepad // this.TabbedNotepad.Dock = System.Windows.Forms.DockStyle.Fill; this.TabbedNotepad.DrawMode = System.Windows.Forms.TabDrawMode.OwnerDrawFixed; this.TabbedNotepad.Location = new System.Drawing.Point(0, 49); this.TabbedNotepad.Name = "TabbedNotepad"; this.TabbedNotepad.Padding = new System.Drawing.Point(0, 0); this.TabbedNotepad.SelectedIndex = 0; this.TabbedNotepad.ShowToolTips = true; this.TabbedNotepad.Size = new System.Drawing.Size(800, 376); this.TabbedNotepad.SizeMode = System.Windows.Forms.TabSizeMode.Fixed; this.TabbedNotepad.TabIndex = 6; this.TabbedNotepad.TabStop = false; this.TabbedNotepad.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.TabbedNotepad_DrawItem); this.TabbedNotepad.TabIndexChanged += new System.EventHandler(this.TabbedNotepad_TabIndexChanged); this.TabbedNotepad.Click += new System.EventHandler(this.TabbedNotepad_Click); this.TabbedNotepad.MouseDown += new System.Windows.Forms.MouseEventHandler(this.TabbedNotepad_MouseDown); // // EncodingLabel // this.EncodingLabel.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right; this.EncodingLabel.Name = "EncodingLabel"; this.EncodingLabel.Size = new System.Drawing.Size(38, 22); this.EncodingLabel.Text = "UTF-8"; // // ASCIIToolStripMenuItem // this.ASCIIToolStripMenuItem.Name = "ASCIIToolStripMenuItem"; this.ASCIIToolStripMenuItem.Size = new System.Drawing.Size(180, 22); this.ASCIIToolStripMenuItem.Text = "ASCII"; this.ASCIIToolStripMenuItem.Click += new System.EventHandler(this.SetEncodingToolStripMenuItem_Click); // // SimpleNotepad // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.TabbedNotepad); this.Controls.Add(this.TopToolStrip); this.Controls.Add(this.MenuStrip); this.Controls.Add(this.BottomToolStrip); this.MainMenuStrip = this.MenuStrip; this.Name = "SimpleNotepad"; this.Text = "SimpleNotepad"; this.Load += new System.EventHandler(this.SimpleNotepad_Load); this.MenuStrip.ResumeLayout(false); this.MenuStrip.PerformLayout(); this.BottomToolStrip.ResumeLayout(false); this.BottomToolStrip.PerformLayout(); this.TopToolStrip.ResumeLayout(false); this.TopToolStrip.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.MenuStrip MenuStrip; private System.Windows.Forms.ToolStripMenuItem fileToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem NewToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem OpenToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem SaveToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem SaveAsToolStripMenuItem; private System.Windows.Forms.ToolStrip BottomToolStrip; private System.Windows.Forms.ToolStripLabel TextLengthLabel; private System.Windows.Forms.ToolStrip TopToolStrip; private System.Windows.Forms.ToolStripSeparator toolStripSeparator1; private System.Windows.Forms.ToolStripLabel LineTotalLabel; private System.Windows.Forms.ToolStripMenuItem editToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem undoToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem redoToolStripMenuItem; private System.Windows.Forms.ToolStripButton NewToolStripButton; private System.Windows.Forms.ToolStripButton OpenToolStripButton; private System.Windows.Forms.ToolStripButton SaveToolStripButton; private System.Windows.Forms.ToolStripButton SaveAsToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator2; private System.Windows.Forms.Timer Runtime; private System.Windows.Forms.TabControl TabbedNotepad; private System.Windows.Forms.ToolStripButton CloseToolStripButton; private System.Windows.Forms.ToolStripSeparator toolStripSeparator3; private System.Windows.Forms.ToolStripMenuItem CloseToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem CloseAllToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem settingsToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator4; private System.Windows.Forms.ToolStripMenuItem ExitToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem formatToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem FontToolStripMenuItem; private System.Windows.Forms.ToolStripSeparator toolStripSeparator5; private System.Windows.Forms.ToolStripButton FontToolStripButton; private System.Windows.Forms.ToolStripMenuItem themeToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem DarkModeToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem PureBlackModeToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem DefaultToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem EncodingToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem ANSIToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem UTF8ToolStripMenuItem; private System.Windows.Forms.ToolStripLabel EncodingLabel; private System.Windows.Forms.ToolStripMenuItem ASCIIToolStripMenuItem; } }
59.356061
158
0.663401
[ "Apache-2.0" ]
mullak99/SimpleNotepad
SimpleNotepad/SimpleNotepad.Designer.cs
31,342
C#
namespace TraktNet.Objects.Get.Tests.Episodes.Json.Reader { using FluentAssertions; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Trakt.NET.Tests.Utility.Traits; using TraktNet.Objects.Get.Episodes; using TraktNet.Objects.Json; using Xunit; [Category("Objects.Get.Episodes.JsonReader")] public partial class EpisodeTranslationArrayJsonReader_Tests { [Fact] public async Task Test_EpisodeTranslationArrayJsonReader_ReadArray_From_JsonReader_Empty_Array() { var traktJsonReader = new ArrayJsonReader<ITraktEpisodeTranslation>(); using (var reader = new StringReader(JSON_EMPTY_ARRAY)) using (var jsonReader = new JsonTextReader(reader)) { var traktEpisodeTranslations = await traktJsonReader.ReadArrayAsync(jsonReader); traktEpisodeTranslations.Should().NotBeNull().And.BeEmpty(); } } [Fact] public async Task Test_EpisodeTranslationArrayJsonReader_ReadArray_From_JsonReader_Complete() { var traktJsonReader = new ArrayJsonReader<ITraktEpisodeTranslation>(); using (var reader = new StringReader(JSON_COMPLETE)) using (var jsonReader = new JsonTextReader(reader)) { var traktEpisodeTranslations = await traktJsonReader.ReadArrayAsync(jsonReader); traktEpisodeTranslations.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3); var translations = traktEpisodeTranslations.ToArray(); translations[0].Title.Should().Be("Translation 1"); translations[0].Overview.Should().Be("Translation Overview 1"); translations[0].LanguageCode.Should().Be("Translation Language 1"); translations[1].Title.Should().Be("Translation 2"); translations[1].Overview.Should().Be("Translation Overview 2"); translations[1].LanguageCode.Should().Be("Translation Language 2"); translations[2].Title.Should().Be("Translation 3"); translations[2].Overview.Should().Be("Translation Overview 3"); translations[2].LanguageCode.Should().Be("Translation Language 3"); } } [Fact] public async Task Test_EpisodeTranslationArrayJsonReader_ReadArray_From_JsonReader_Incomplete_1() { var traktJsonReader = new ArrayJsonReader<ITraktEpisodeTranslation>(); using (var reader = new StringReader(JSON_INCOMPLETE_1)) using (var jsonReader = new JsonTextReader(reader)) { var traktEpisodeTranslations = await traktJsonReader.ReadArrayAsync(jsonReader); traktEpisodeTranslations.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3); var translations = traktEpisodeTranslations.ToArray(); translations[0].Title.Should().BeNull(); translations[0].Overview.Should().Be("Translation Overview 1"); translations[0].LanguageCode.Should().Be("Translation Language 1"); translations[1].Title.Should().Be("Translation 2"); translations[1].Overview.Should().Be("Translation Overview 2"); translations[1].LanguageCode.Should().Be("Translation Language 2"); translations[2].Title.Should().Be("Translation 3"); translations[2].Overview.Should().Be("Translation Overview 3"); translations[2].LanguageCode.Should().Be("Translation Language 3"); } } [Fact] public async Task Test_EpisodeTranslationArrayJsonReader_ReadArray_From_JsonReader_Incomplete_2() { var traktJsonReader = new ArrayJsonReader<ITraktEpisodeTranslation>(); using (var reader = new StringReader(JSON_INCOMPLETE_2)) using (var jsonReader = new JsonTextReader(reader)) { var traktEpisodeTranslations = await traktJsonReader.ReadArrayAsync(jsonReader); traktEpisodeTranslations.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3); var translations = traktEpisodeTranslations.ToArray(); translations[0].Title.Should().Be("Translation 1"); translations[0].Overview.Should().Be("Translation Overview 1"); translations[0].LanguageCode.Should().Be("Translation Language 1"); translations[1].Title.Should().Be("Translation 2"); translations[1].Overview.Should().BeNull(); translations[1].LanguageCode.Should().Be("Translation Language 2"); translations[2].Title.Should().Be("Translation 3"); translations[2].Overview.Should().Be("Translation Overview 3"); translations[2].LanguageCode.Should().Be("Translation Language 3"); } } [Fact] public async Task Test_EpisodeTranslationArrayJsonReader_ReadArray_From_JsonReader_Incomplete_3() { var traktJsonReader = new ArrayJsonReader<ITraktEpisodeTranslation>(); using (var reader = new StringReader(JSON_INCOMPLETE_3)) using (var jsonReader = new JsonTextReader(reader)) { var traktEpisodeTranslations = await traktJsonReader.ReadArrayAsync(jsonReader); traktEpisodeTranslations.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3); var translations = traktEpisodeTranslations.ToArray(); translations[0].Title.Should().Be("Translation 1"); translations[0].Overview.Should().Be("Translation Overview 1"); translations[0].LanguageCode.Should().Be("Translation Language 1"); translations[1].Title.Should().Be("Translation 2"); translations[1].Overview.Should().Be("Translation Overview 2"); translations[1].LanguageCode.Should().Be("Translation Language 2"); translations[2].Title.Should().Be("Translation 3"); translations[2].Overview.Should().Be("Translation Overview 3"); translations[2].LanguageCode.Should().BeNull(); } } [Fact] public async Task Test_EpisodeTranslationArrayJsonReader_ReadArray_From_JsonReader_Incomplete_4() { var traktJsonReader = new ArrayJsonReader<ITraktEpisodeTranslation>(); using (var reader = new StringReader(JSON_INCOMPLETE_4)) using (var jsonReader = new JsonTextReader(reader)) { var traktEpisodeTranslations = await traktJsonReader.ReadArrayAsync(jsonReader); traktEpisodeTranslations.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3); var translations = traktEpisodeTranslations.ToArray(); translations[0].Title.Should().Be("Translation 1"); translations[0].Overview.Should().BeNull(); translations[0].LanguageCode.Should().BeNull(); translations[1].Title.Should().Be("Translation 2"); translations[1].Overview.Should().Be("Translation Overview 2"); translations[1].LanguageCode.Should().Be("Translation Language 2"); translations[2].Title.Should().Be("Translation 3"); translations[2].Overview.Should().Be("Translation Overview 3"); translations[2].LanguageCode.Should().Be("Translation Language 3"); } } [Fact] public async Task Test_EpisodeTranslationArrayJsonReader_ReadArray_From_JsonReader_Incomplete_5() { var traktJsonReader = new ArrayJsonReader<ITraktEpisodeTranslation>(); using (var reader = new StringReader(JSON_INCOMPLETE_5)) using (var jsonReader = new JsonTextReader(reader)) { var traktEpisodeTranslations = await traktJsonReader.ReadArrayAsync(jsonReader); traktEpisodeTranslations.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3); var translations = traktEpisodeTranslations.ToArray(); translations[0].Title.Should().Be("Translation 1"); translations[0].Overview.Should().Be("Translation Overview 1"); translations[0].LanguageCode.Should().Be("Translation Language 1"); translations[1].Title.Should().BeNull(); translations[1].Overview.Should().Be("Translation Overview 2"); translations[1].LanguageCode.Should().BeNull(); translations[2].Title.Should().Be("Translation 3"); translations[2].Overview.Should().Be("Translation Overview 3"); translations[2].LanguageCode.Should().Be("Translation Language 3"); } } [Fact] public async Task Test_EpisodeTranslationArrayJsonReader_ReadArray_From_JsonReader_Incomplete_6() { var traktJsonReader = new ArrayJsonReader<ITraktEpisodeTranslation>(); using (var reader = new StringReader(JSON_INCOMPLETE_6)) using (var jsonReader = new JsonTextReader(reader)) { var traktEpisodeTranslations = await traktJsonReader.ReadArrayAsync(jsonReader); traktEpisodeTranslations.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3); var translations = traktEpisodeTranslations.ToArray(); translations[0].Title.Should().Be("Translation 1"); translations[0].Overview.Should().Be("Translation Overview 1"); translations[0].LanguageCode.Should().Be("Translation Language 1"); translations[1].Title.Should().Be("Translation 2"); translations[1].Overview.Should().Be("Translation Overview 2"); translations[1].LanguageCode.Should().Be("Translation Language 2"); translations[2].Title.Should().BeNull(); translations[2].Overview.Should().BeNull(); translations[2].LanguageCode.Should().Be("Translation Language 3"); } } [Fact] public async Task Test_EpisodeTranslationArrayJsonReader_ReadArray_From_JsonReader_Not_Valid_1() { var traktJsonReader = new ArrayJsonReader<ITraktEpisodeTranslation>(); using (var reader = new StringReader(JSON_NOT_VALID_1)) using (var jsonReader = new JsonTextReader(reader)) { var traktEpisodeTranslations = await traktJsonReader.ReadArrayAsync(jsonReader); traktEpisodeTranslations.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3); var translations = traktEpisodeTranslations.ToArray(); translations[0].Title.Should().BeNull(); translations[0].Overview.Should().Be("Translation Overview 1"); translations[0].LanguageCode.Should().Be("Translation Language 1"); translations[1].Title.Should().Be("Translation 2"); translations[1].Overview.Should().Be("Translation Overview 2"); translations[1].LanguageCode.Should().Be("Translation Language 2"); translations[2].Title.Should().Be("Translation 3"); translations[2].Overview.Should().Be("Translation Overview 3"); translations[2].LanguageCode.Should().Be("Translation Language 3"); } } [Fact] public async Task Test_EpisodeTranslationArrayJsonReader_ReadArray_From_JsonReader_Not_Valid_2() { var traktJsonReader = new ArrayJsonReader<ITraktEpisodeTranslation>(); using (var reader = new StringReader(JSON_NOT_VALID_2)) using (var jsonReader = new JsonTextReader(reader)) { var traktEpisodeTranslations = await traktJsonReader.ReadArrayAsync(jsonReader); traktEpisodeTranslations.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3); var translations = traktEpisodeTranslations.ToArray(); translations[0].Title.Should().Be("Translation 1"); translations[0].Overview.Should().Be("Translation Overview 1"); translations[0].LanguageCode.Should().Be("Translation Language 1"); translations[1].Title.Should().Be("Translation 2"); translations[1].Overview.Should().BeNull(); translations[1].LanguageCode.Should().Be("Translation Language 2"); translations[2].Title.Should().Be("Translation 3"); translations[2].Overview.Should().Be("Translation Overview 3"); translations[2].LanguageCode.Should().Be("Translation Language 3"); } } [Fact] public async Task Test_EpisodeTranslationArrayJsonReader_ReadArray_From_JsonReader_Not_Valid_3() { var traktJsonReader = new ArrayJsonReader<ITraktEpisodeTranslation>(); using (var reader = new StringReader(JSON_NOT_VALID_3)) using (var jsonReader = new JsonTextReader(reader)) { var traktEpisodeTranslations = await traktJsonReader.ReadArrayAsync(jsonReader); traktEpisodeTranslations.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3); var translations = traktEpisodeTranslations.ToArray(); translations[0].Title.Should().Be("Translation 1"); translations[0].Overview.Should().Be("Translation Overview 1"); translations[0].LanguageCode.Should().Be("Translation Language 1"); translations[1].Title.Should().Be("Translation 2"); translations[1].Overview.Should().Be("Translation Overview 2"); translations[1].LanguageCode.Should().Be("Translation Language 2"); translations[2].Title.Should().Be("Translation 3"); translations[2].Overview.Should().Be("Translation Overview 3"); translations[2].LanguageCode.Should().BeNull(); } } [Fact] public async Task Test_EpisodeTranslationArrayJsonReader_ReadArray_From_JsonReader_Not_Valid_4() { var traktJsonReader = new ArrayJsonReader<ITraktEpisodeTranslation>(); using (var reader = new StringReader(JSON_NOT_VALID_4)) using (var jsonReader = new JsonTextReader(reader)) { var traktEpisodeTranslations = await traktJsonReader.ReadArrayAsync(jsonReader); traktEpisodeTranslations.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(3); var translations = traktEpisodeTranslations.ToArray(); translations[0].Title.Should().BeNull(); translations[0].Overview.Should().Be("Translation Overview 1"); translations[0].LanguageCode.Should().Be("Translation Language 1"); translations[1].Title.Should().Be("Translation 2"); translations[1].Overview.Should().BeNull(); translations[1].LanguageCode.Should().Be("Translation Language 2"); translations[2].Title.Should().Be("Translation 3"); translations[2].Overview.Should().Be("Translation Overview 3"); translations[2].LanguageCode.Should().BeNull(); } } [Fact] public async Task Test_EpisodeTranslationArrayJsonReader_ReadArray_From_JsonReader_Null() { var traktJsonReader = new ArrayJsonReader<ITraktEpisodeTranslation>(); Func<Task<IEnumerable<ITraktEpisodeTranslation>>> traktEpisodeTranslations = () => traktJsonReader.ReadArrayAsync(default(JsonTextReader)); await traktEpisodeTranslations.Should().ThrowAsync<ArgumentNullException>(); } [Fact] public async Task Test_EpisodeTranslationArrayJsonReader_ReadArray_From_JsonReader_Empty() { var traktJsonReader = new ArrayJsonReader<ITraktEpisodeTranslation>(); using (var reader = new StringReader(string.Empty)) using (var jsonReader = new JsonTextReader(reader)) { var traktEpisodeTranslations = await traktJsonReader.ReadArrayAsync(jsonReader); traktEpisodeTranslations.Should().BeNull(); } } } }
47.605714
151
0.628976
[ "MIT" ]
henrikfroehling/Trakt.NET
Source/Tests/Trakt.NET.Objects.Get.Tests/Episodes/Json/Reader/EpisodeTranslationArrayJsonReader/EpisodeTranslationArrayJsonReader_Reader_Tests.cs
16,664
C#
using Microsoft.JSInterop; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GoogleMapsComponents.Maps { /// <summary> /// A polyline is a linear overlay of connected line segments on the map. /// </summary> public class Polyline : ListableEntityBase<PolylineOptions>, IDisposable { /// <summary> /// Create a polyline using the passed PolylineOptions, which specify both the path of the polyline and the stroke style to use when drawing the polyline. /// </summary> public async static Task<Polyline> CreateAsync(IJSRuntime jsRuntime, PolylineOptions opts = null) { var jsObjectRef = await JsObjectRef.CreateAsync(jsRuntime, "google.maps.Polyline", opts); var obj = new Polyline(jsObjectRef, opts); return obj; } /// <summary> /// Constructor for use in ListableEntityListBase. Must be the first constructor! /// </summary> internal Polyline(JsObjectRef jsObjectRef) :base(jsObjectRef) { } /// <summary> /// Create a polyline using the passed PolylineOptions, which specify both the path of the polyline and the stroke style to use when drawing the polyline. /// </summary> private Polyline(JsObjectRef jsObjectRef, PolylineOptions opts) :this(jsObjectRef) { } /// <summary> /// Returns whether this shape can be dragged by the user. /// </summary> /// <returns></returns> public Task<bool> GetDraggable() { return _jsObjectRef.InvokeAsync<bool>( "getDraggable"); } /// <summary> /// Returns whether this shape can be edited by the user. /// </summary> /// <returns></returns> public Task<bool> GetEditable() { return _jsObjectRef.InvokeAsync<bool>( "getEditable"); } /// <summary> /// Retrieves the path. /// </summary> /// <returns></returns> public Task<IEnumerable<LatLngLiteral>> GetPath() { return _jsObjectRef.InvokeAsync<IEnumerable<LatLngLiteral>>("getPath"); } /// <summary> /// Returns whether this poly is visible on the map. /// </summary> /// <returns></returns> public Task<bool> GetVisible() { return _jsObjectRef.InvokeAsync<bool>( "getVisible"); } /// <summary> /// If set to true, the user can drag this shape over the map. /// The geodesic property defines the mode of dragging. /// </summary> /// <param name="draggable"></param> /// <returns></returns> public Task SetDraggable(bool draggable) { return _jsObjectRef.InvokeAsync( "setDraggable", draggable); } /// <summary> /// If set to true, the user can edit this shape by dragging the control points shown at the vertices and on each segment. /// </summary> /// <param name="editable"></param> /// <returns></returns> public Task SetEditable(bool editable) { return _jsObjectRef.InvokeAsync( "setEditable", editable); } public Task SetOptions(PolylineOptions options) { return _jsObjectRef.InvokeAsync( "setOptions", options); } /// <summary> /// Sets the path. /// </summary> /// <param name="path"></param> /// <returns></returns> public Task SetPath(IEnumerable<LatLngLiteral> path) { return _jsObjectRef.InvokeAsync( "setPath", path); } /// <summary> /// Hides this poly if set to false. /// </summary> /// <param name="visible"></param> /// <returns></returns> public Task SetVisible(bool visible) { return _jsObjectRef.InvokeAsync( "setVisible", visible); } } }
30.535714
162
0.546199
[ "MIT" ]
Enritski/BlazorGoogleMaps
GoogleMapsComponents/Maps/Polyline.cs
4,277
C#
using System; using NBitcoin.BouncyCastle.Crypto.Utilities; using NBitcoin.BouncyCastle.Utilities; namespace NBitcoin.BouncyCastle.Crypto.Digests { /** * Draft FIPS 180-2 implementation of SHA-256. <b>Note:</b> As this is * based on a draft this implementation is subject to change. * * <pre> * block word digest * SHA-1 512 32 160 * SHA-256 512 32 256 * SHA-384 1024 64 384 * SHA-512 1024 64 512 * </pre> */ internal class Sha256Digest : GeneralDigest { private const int DigestLength = 32; private uint H1, H2, H3, H4, H5, H6, H7, H8; private uint[] X = new uint[64]; private int xOff; public Sha256Digest() { initHs(); } /** * Copy constructor. This will copy the state of the provided * message digest. */ public Sha256Digest(Sha256Digest t) : base(t) { CopyIn(t); } private void CopyIn(Sha256Digest t) { base.CopyIn(t); H1 = t.H1; H2 = t.H2; H3 = t.H3; H4 = t.H4; H5 = t.H5; H6 = t.H6; H7 = t.H7; H8 = t.H8; Array.Copy(t.X, 0, X, 0, t.X.Length); xOff = t.xOff; } public override string AlgorithmName { get { return "SHA-256"; } } public override int GetDigestSize() { return DigestLength; } internal override void ProcessWord( byte[] input, int inOff) { X[xOff] = Pack.BE_To_UInt32(input, inOff); if(++xOff == 16) { ProcessBlock(); } } internal override void ProcessLength( long bitLength) { if(xOff > 14) { ProcessBlock(); } X[14] = (uint)((ulong)bitLength >> 32); X[15] = (uint)((ulong)bitLength); } public override int DoFinal( byte[] output, int outOff) { Finish(); Pack.UInt32_To_BE((uint)H1, output, outOff); Pack.UInt32_To_BE((uint)H2, output, outOff + 4); Pack.UInt32_To_BE((uint)H3, output, outOff + 8); Pack.UInt32_To_BE((uint)H4, output, outOff + 12); Pack.UInt32_To_BE((uint)H5, output, outOff + 16); Pack.UInt32_To_BE((uint)H6, output, outOff + 20); Pack.UInt32_To_BE((uint)H7, output, outOff + 24); Pack.UInt32_To_BE((uint)H8, output, outOff + 28); Reset(); return DigestLength; } /** * reset the chaining variables */ public override void Reset() { base.Reset(); initHs(); xOff = 0; Array.Clear(X, 0, X.Length); } private void initHs() { /* SHA-256 initial hash value * The first 32 bits of the fractional parts of the square roots * of the first eight prime numbers */ H1 = 0x6a09e667; H2 = 0xbb67ae85; H3 = 0x3c6ef372; H4 = 0xa54ff53a; H5 = 0x510e527f; H6 = 0x9b05688c; H7 = 0x1f83d9ab; H8 = 0x5be0cd19; } internal override void ProcessBlock() { // // expand 16 word block into 64 word blocks. // for(int ti = 16; ti <= 63; ti++) { X[ti] = Theta1(X[ti - 2]) + X[ti - 7] + Theta0(X[ti - 15]) + X[ti - 16]; } // // set up working variables. // uint a = H1; uint b = H2; uint c = H3; uint d = H4; uint e = H5; uint f = H6; uint g = H7; uint h = H8; int t = 0; for(int i = 0; i < 8; ++i) { // t = 8 * i h += Sum1Ch(e, f, g) + K[t] + X[t]; d += h; h += Sum0Maj(a, b, c); ++t; // t = 8 * i + 1 g += Sum1Ch(d, e, f) + K[t] + X[t]; c += g; g += Sum0Maj(h, a, b); ++t; // t = 8 * i + 2 f += Sum1Ch(c, d, e) + K[t] + X[t]; b += f; f += Sum0Maj(g, h, a); ++t; // t = 8 * i + 3 e += Sum1Ch(b, c, d) + K[t] + X[t]; a += e; e += Sum0Maj(f, g, h); ++t; // t = 8 * i + 4 d += Sum1Ch(a, b, c) + K[t] + X[t]; h += d; d += Sum0Maj(e, f, g); ++t; // t = 8 * i + 5 c += Sum1Ch(h, a, b) + K[t] + X[t]; g += c; c += Sum0Maj(d, e, f); ++t; // t = 8 * i + 6 b += Sum1Ch(g, h, a) + K[t] + X[t]; f += b; b += Sum0Maj(c, d, e); ++t; // t = 8 * i + 7 a += Sum1Ch(f, g, h) + K[t] + X[t]; e += a; a += Sum0Maj(b, c, d); ++t; } H1 += a; H2 += b; H3 += c; H4 += d; H5 += e; H6 += f; H7 += g; H8 += h; // // reset the offset and clean out the word buffer. // xOff = 0; Array.Clear(X, 0, 16); } private static uint Sum1Ch( uint x, uint y, uint z) { // return Sum1(x) + Ch(x, y, z); return (((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7))) + ((x & y) ^ ((~x) & z)); } private static uint Sum0Maj( uint x, uint y, uint z) { // return Sum0(x) + Maj(x, y, z); return (((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10))) + ((x & y) ^ (x & z) ^ (y & z)); } // /* SHA-256 functions */ // private static uint Ch( // uint x, // uint y, // uint z) // { // return ((x & y) ^ ((~x) & z)); // } // // private static uint Maj( // uint x, // uint y, // uint z) // { // return ((x & y) ^ (x & z) ^ (y & z)); // } // // private static uint Sum0( // uint x) // { // return ((x >> 2) | (x << 30)) ^ ((x >> 13) | (x << 19)) ^ ((x >> 22) | (x << 10)); // } // // private static uint Sum1( // uint x) // { // return ((x >> 6) | (x << 26)) ^ ((x >> 11) | (x << 21)) ^ ((x >> 25) | (x << 7)); // } private static uint Theta0( uint x) { return ((x >> 7) | (x << 25)) ^ ((x >> 18) | (x << 14)) ^ (x >> 3); } private static uint Theta1( uint x) { return ((x >> 17) | (x << 15)) ^ ((x >> 19) | (x << 13)) ^ (x >> 10); } /* SHA-256 Constants * (represent the first 32 bits of the fractional parts of the * cube roots of the first sixty-four prime numbers) */ private static readonly uint[] K = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; public override IMemoable Copy() { return new Sha256Digest(this); } public override void Reset(IMemoable other) { Sha256Digest d = (Sha256Digest)other; CopyIn(d); } } }
27.795796
104
0.38159
[ "MIT" ]
MIPPL/StratisBitcoinFullNode
src/NBitcoin/BouncyCastle/crypto/digests/Sha256Digest.cs
9,256
C#
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by Brian Nelson 2016. * * See license in repo for more information * * https://github.com/sharpHDF/sharpHDF * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #define HDF5_VER1_10 using System; namespace sharpHDF.Library.Structs { public struct Hdf5Identifier { #if HDF5_VER1_10 public Hdf5Identifier(long _value) { Value = _value; } public Int64 Value; #else public Hdf5Identifier(int _value) { Value = _value; } public readonly int Value; #endif public bool Equals(Hdf5Identifier _other) { return Value == _other.Value; } public override int GetHashCode() { return Value.GetHashCode(); } } }
24.166667
79
0.419704
[ "MIT" ]
Hakan77/sharpHDF
src/sharpHDF/Structs/Hdf5Identifier.cs
1,017
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using RetailDemo.Infrastructure.Data; namespace RetailDemo.Infrastructure.Migrations { [DbContext(typeof(AppDbContext))] [Migration("20190501085022_InitialCreate")] partial class InitialCreate { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.4-servicing-10062") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("RetailDemo.Core.Entities.Body", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("BodyId"); b.Property<string>("Dest_img"); b.Property<int>("ImageEventId"); b.Property<string>("MessageId"); b.Property<string>("ModuleId"); b.Property<string>("Src_img"); b.HasKey("Id"); b.HasIndex("ImageEventId") .IsUnique(); b.ToTable("Body"); }); modelBuilder.Entity("RetailDemo.Core.Entities.DetectionBox", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("DetectionBoxId"); b.Property<int?>("DetectionBoxesId"); b.Property<double>("Detection_box"); b.HasKey("Id"); b.HasIndex("DetectionBoxesId"); b.ToTable("DetectionBox"); }); modelBuilder.Entity("RetailDemo.Core.Entities.DetectionBoxes", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("DetectionBoxesId"); b.Property<int?>("ResultId"); b.HasKey("Id"); b.HasIndex("ResultId"); b.ToTable("DetectionBoxes"); }); modelBuilder.Entity("RetailDemo.Core.Entities.DetectionClass", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("DetectionClassId"); b.Property<int>("Detection_class"); b.Property<int?>("ResultId"); b.HasKey("Id"); b.HasIndex("ResultId"); b.ToTable("DetectionClass"); }); modelBuilder.Entity("RetailDemo.Core.Entities.DetectionScore", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("DetectionScoreId"); b.Property<double>("Detection_score"); b.Property<int?>("ResultId"); b.HasKey("Id"); b.HasIndex("ResultId"); b.ToTable("DetectionScore"); }); modelBuilder.Entity("RetailDemo.Core.Entities.EdgeDevice", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("EdgeDeviceId"); b.Property<string>("EdgeDeviceName"); b.HasKey("Id"); b.ToTable("EdgeDevices"); }); modelBuilder.Entity("RetailDemo.Core.Entities.ImageEvent", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTimeOffset>("CaptureTime"); b.Property<string>("EdgeDeviceName"); b.Property<byte[]>("EncodedImage"); b.Property<int>("ImageEventId"); b.Property<string>("Name"); b.Property<string>("RequestId"); b.Property<string>("Source"); b.Property<DateTimeOffset>("TimeRecieved"); b.Property<string>("Type"); b.HasKey("Id"); b.ToTable("ImageEvents"); }); modelBuilder.Entity("RetailDemo.Core.Entities.Result", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("BodyId"); b.Property<int>("Num_detections"); b.Property<int>("ResultId"); b.HasKey("Id"); b.HasIndex("BodyId") .IsUnique(); b.ToTable("Result"); }); modelBuilder.Entity("RetailDemo.Core.Entities.Size", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Height"); b.Property<int>("ResultId"); b.Property<int>("SizeId"); b.Property<string>("Width"); b.HasKey("Id"); b.HasIndex("ResultId") .IsUnique(); b.ToTable("Size"); }); modelBuilder.Entity("RetailDemo.Core.Entities.ToDoItem", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Description"); b.Property<bool>("IsDone"); b.Property<string>("Title"); b.HasKey("Id"); b.ToTable("ToDoItems"); }); modelBuilder.Entity("RetailDemo.Core.Entities.Body", b => { b.HasOne("RetailDemo.Core.Entities.ImageEvent", "ImageEvent") .WithOne("Body") .HasForeignKey("RetailDemo.Core.Entities.Body", "ImageEventId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("RetailDemo.Core.Entities.DetectionBox", b => { b.HasOne("RetailDemo.Core.Entities.DetectionBoxes") .WithMany("Detection_boxes") .HasForeignKey("DetectionBoxesId"); }); modelBuilder.Entity("RetailDemo.Core.Entities.DetectionBoxes", b => { b.HasOne("RetailDemo.Core.Entities.Result") .WithMany("Detection_boxes") .HasForeignKey("ResultId"); }); modelBuilder.Entity("RetailDemo.Core.Entities.DetectionClass", b => { b.HasOne("RetailDemo.Core.Entities.Result") .WithMany("Detection_classes") .HasForeignKey("ResultId"); }); modelBuilder.Entity("RetailDemo.Core.Entities.DetectionScore", b => { b.HasOne("RetailDemo.Core.Entities.Result") .WithMany("Detection_scores") .HasForeignKey("ResultId"); }); modelBuilder.Entity("RetailDemo.Core.Entities.Result", b => { b.HasOne("RetailDemo.Core.Entities.Body", "Body") .WithOne("Result") .HasForeignKey("RetailDemo.Core.Entities.Result", "BodyId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("RetailDemo.Core.Entities.Size", b => { b.HasOne("RetailDemo.Core.Entities.Result", "Result") .WithOne("Size") .HasForeignKey("RetailDemo.Core.Entities.Size", "ResultId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
34.907801
125
0.495022
[ "MIT" ]
AurelianoBuendia/azure-intelligent-edge-patterns
edge-ai-void-detection/modules/apiserver/src/RetailDemo.Infrastructure/Migrations/20190501085022_InitialCreate.Designer.cs
9,846
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("otopark")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("otopark")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("25d6e532-0d06-4274-abf5-e0df1921669b")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.486486
84
0.743331
[ "MIT" ]
nrkdrk/Parking-Lot-Automation
otopark/otopark/Properties/AssemblyInfo.cs
1,390
C#
//------------------------------------------------------------------------------ // Microsoft Windows Presentation Foudnation // Copyright (c) Microsoft Corporation, 2009 // // Description: // Definition of the ICyclicBrush interface used to interact with Brush // objects whose content can point back into the Visual tree. // //------------------------------------------------------------------------------ using System; using System.Windows.Media; using System.Windows.Media.Composition; namespace System.Windows.Media { internal interface ICyclicBrush { void FireOnChanged(); void RenderForCyclicBrush(DUCE.Channel channel, bool skipChannelCheck); } }
28.875
80
0.5671
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/wpf/src/Core/CSharp/System/Windows/Media/ICyclicBrush.cs
693
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class KeepUpright : MonoBehaviour { private void Update () { // Keep self upright transform.rotation = Quaternion.identity; } }
18.384615
49
0.707113
[ "MIT" ]
denniscarr/dfc291_CodeLab1_final
Static/Assets/Scripts/KeepUpright.cs
241
C#
//---------------------------------------------- // MeshBaker // Copyright © 2011-2012 Ian Deane //---------------------------------------------- using UnityEngine; using System.Collections; using System.IO; using System; using System.Collections.Specialized; using System.Collections.Generic; using System.Text.RegularExpressions; using DigitalOpus.MB.Core; using UnityEditor; namespace DigitalOpus.MB.Core{ public class MB3_TextureBakerEditorInternal{ //add option to exclude skinned mesh renderer and mesh renderer in filter //example scenes for multi material private static GUIContent insertContent = new GUIContent("+", "add a material"); private static GUIContent deleteContent = new GUIContent("-", "delete a material"); private static GUILayoutOption buttonWidth = GUILayout.MaxWidth(20f); public static GUIContent noneContent = new GUIContent(""); //private SerializedObject textureBaker; private SerializedProperty logLevel, textureBakeResults, maxTilingBakeSize, maxAtlasSize, doMultiMaterial, doMultiMaterialSplitAtlasesIfTooBig, doMultiMaterialIfOBUVs, considerMeshUVs, resultMaterial, resultMaterials, atlasPadding, resizePowerOfTwoTextures, customShaderProperties, objsToMesh, texturePackingAlgorithm, forcePowerOfTwoAtlas, considerNonTextureProperties, sortOrderAxis; bool resultMaterialsFoldout = true; bool showInstructions = false; bool showContainsReport = true; GUIStyle multipleMaterialBackgroundStyle = new GUIStyle(); GUIStyle multipleMaterialBackgroundStyleDarker = new GUIStyle(); GUIStyle editorBoxBackgroundStyle = new GUIStyle(); Texture2D multipleMaterialBackgroundColor; Texture2D multipleMaterialBackgroundColorDarker; Texture2D editorBoxBackgroundColor; Color buttonColor = new Color(.8f,.8f,1f,1f); private static GUIContent createPrefabAndMaterialLabelContent = new GUIContent("Create Empty Assets For Combined Material", "Creates a material asset and a 'MB2_TextureBakeResult' asset. You should set the shader on the material. Mesh Baker uses the Texture properties on the material to decide what atlases need to be created. The MB2_TextureBakeResult asset should be used in the 'Texture Bake Result' field."), logLevelContent = new GUIContent("Log Level"), openToolsWindowLabelContent = new GUIContent("Open Tools For Adding Objects", "Use these tools to find out what can be combined, discover possible problems with meshes, and quickly add objects."), fixOutOfBoundsGUIContent = new GUIContent("Consider Mesh UVs", "(Was called 'fix out of bounds UVs') The textures will be sampled based on mesh uv rectangle as well as material tiling. This can have two effects:\n\n" + "1) If the mesh only uses a small rectangle of it's source material (atlas). Only that small rectangle will be baked into the atlas.\n\n" + "2) If the mesh has uvs outside the 0,1 range (tiling) then this tiling will be baked into the atlas."), resizePowerOfTwoGUIContent = new GUIContent("Resize Power-Of-Two Textures", "Shrinks textures so they have a clear border of width 'Atlas Padding' around them. Improves texture packing efficiency."), customShaderPropertyNamesGUIContent = new GUIContent("Custom Shader Propert Names", "Mesh Baker has a list of common texture properties that it looks for in shaders to generate atlases. Custom shaders may have texture properties not on this list. Add them here and Meshbaker will generate atlases for them."), combinedMaterialsGUIContent = new GUIContent("Combined Materials", "Use the +/- buttons to add multiple combined materials. You will also need to specify which materials on the source objects map to each combined material."), maxTilingBakeSizeGUIContent = new GUIContent("Max Tiling Bake Size","This is the maximum size tiling textures will be baked to."), maxAtlasSizeGUIContent = new GUIContent("Max Atlas Size","This is the maximum size of the atlas. If the atlas is larger than this textures being added will be shrunk."), objectsToCombineGUIContent = new GUIContent("Objects To Be Combined","These can be prefabs or scene objects. They must be game objects with Renderer components, not the parent objects. Materials on these objects will baked into the combined material(s)"), textureBakeResultsGUIContent = new GUIContent("Texture Bake Result","This asset contains a mapping of materials to UV rectangles in the atlases. It is needed to create combined meshes or adjust meshes so they can use the combined material(s). Create it using 'Create Empty Assets For Combined Material'. Drag it to the 'Texture Bake Result' field to use it."), texturePackingAgorithmGUIContent = new GUIContent("Texture Packer", "Unity's PackTextures: Atlases are always a power of two. Can crash when trying to generate large atlases. \n\n " + "Mesh Baker Texture Packer: Atlases will be most efficient size and shape (not limited to a power of two). More robust for large atlases. \n\n"+ "Mesh Baker Texture Packer Fast: Same as Mesh Baker Texture Packer but creates atlases on the graphics card using RenderTextures instead of the CPU. Source textures can be compressed. May not be pixel perfect. \n\n" + "Mesh Baker Texture Packer Horizontal (Experimental): Packs all images vertically to allow horizontal-only UV-tiling. Best used without 'Consider Mesh UVs'\n\n" + "Mesh Baker Texture Packer Vertical (Experimental): Packs all images horizontally other to allow vertical-only UV-tiling. Best used without 'Consider Mesh UVs'\n\n"), configMultiMatFromObjsContent = new GUIContent("Build Source To Combined Mapping From \n Objects To Be Combined", "This will group the materials on your source objects by shader and create one source to combined mapping for each shader found. For example if combining trees then all the materials with the same bark shader will be grouped togther and all the materials with the same leaf material will be grouped together. You can adjust the results afterwards. \n\nIf fix out-of-bounds UVs is NOT checked then submeshes with UVs outside 0,0..1,1 will be mapped to their own submesh regardless of shader."), forcePowerOfTwoAtlasContent = new GUIContent("Force Power-Of-Two Atlas","Forces atlas x and y dimensions to be powers of two with aspect ratio 1:1,1:2 or 2:1. Unity recommends textures be a power of two for everything but GUI textures."), considerNonTexturePropertiesContent = new GUIContent("Blend Non-Texture Properties","Will blend non-texture properties such as _Color, _Glossiness with the textures. Objects with different non-texture property values will be copied into different parts of the atlas even if they use the same textures. This feature requires that TextureBlenders " + "exist for the result material shader. It is easy to extend Mesh Baker by writing custom TextureBlenders. Default TextureBlenders exist for: \n" + " - Standard \n" + " - Diffuse \n" + " - Bump Diffuse\n"), gc_SortAlongAxis = new GUIContent("Sort Along Axis", "Transparent materials often require that triangles be rendered in a certain order. This will sort Game Objects along the specified axis. Triangles will be added to the combined mesh in this order."), gc_DoMultiMaterialSplitAtlasesIfTooBig = new GUIContent("Split Atlases If Textures Don't Fit", ""), gc_DoMultiMaterialSplitAtlasesIfOBUVs = new GUIContent("Put Meshes With Out Of Bounds UV On Submesh", ""); [MenuItem("GameObject/Create Other/Mesh Baker/TextureBaker",false,100)] public static void CreateNewTextureBaker(){ MB3_TextureBaker[] mbs = (MB3_TextureBaker[]) Editor.FindObjectsOfType(typeof(MB3_TextureBaker)); Regex regex = new Regex(@"\((\d+)\)$", RegexOptions.Compiled | RegexOptions.CultureInvariant); int largest = 0; try{ for (int i = 0; i < mbs.Length; i++){ Match match = regex.Match(mbs[i].name); if (match.Success){ int val = Convert.ToInt32(match.Groups[1].Value); if (val >= largest) largest = val + 1; } } } catch(Exception e){ if (e == null) e = null; //Do nothing supress compiler warning } GameObject nmb = new GameObject("TextureBaker (" + largest + ")"); nmb.transform.position = Vector3.zero; nmb.AddComponent<MB3_MeshBakerGrouper>(); MB3_TextureBaker tb = nmb.AddComponent<MB3_TextureBaker>(); tb.packingAlgorithm = MB2_PackingAlgorithmEnum.MeshBakerTexturePacker; } void _init(SerializedObject textureBaker) { //textureBaker = new SerializedObject(target); logLevel = textureBaker.FindProperty("LOG_LEVEL"); doMultiMaterial = textureBaker.FindProperty("_doMultiMaterial"); doMultiMaterialSplitAtlasesIfTooBig = textureBaker.FindProperty("_doMultiMaterialSplitAtlasesIfTooBig"); doMultiMaterialIfOBUVs = textureBaker.FindProperty("_doMultiMaterialSplitAtlasesIfOBUVs"); considerMeshUVs = textureBaker.FindProperty("_fixOutOfBoundsUVs"); resultMaterial = textureBaker.FindProperty("_resultMaterial"); resultMaterials = textureBaker.FindProperty("resultMaterials"); atlasPadding = textureBaker.FindProperty("_atlasPadding"); resizePowerOfTwoTextures = textureBaker.FindProperty("_resizePowerOfTwoTextures"); customShaderProperties= textureBaker.FindProperty("_customShaderProperties"); objsToMesh = textureBaker.FindProperty("objsToMesh"); maxTilingBakeSize = textureBaker.FindProperty("_maxTilingBakeSize"); maxAtlasSize = textureBaker.FindProperty("_maxAtlasSize"); textureBakeResults = textureBaker.FindProperty("_textureBakeResults"); texturePackingAlgorithm = textureBaker.FindProperty("_packingAlgorithm"); forcePowerOfTwoAtlas = textureBaker.FindProperty("_meshBakerTexturePackerForcePowerOfTwo"); considerNonTextureProperties = textureBaker.FindProperty("_considerNonTextureProperties"); sortOrderAxis = textureBaker.FindProperty("sortAxis"); } public void OnEnable(SerializedObject textureBaker) { _init(textureBaker); bool isPro = EditorGUIUtility.isProSkin; Color backgroundColor = isPro ? new Color32(35, 35, 35, 255) : new Color32(174, 174, 174, 255); multipleMaterialBackgroundColor = MB3_MeshBakerEditorFunctions.MakeTex(8, 8, backgroundColor); backgroundColor = isPro ? new Color32(50, 50, 50, 255) : new Color32(160, 160, 160, 255); multipleMaterialBackgroundColorDarker = MB3_MeshBakerEditorFunctions.MakeTex(8, 8, backgroundColor); backgroundColor = isPro ? new Color32(35, 35, 35, 255) : new Color32(174, 174, 174, 255); editorBoxBackgroundColor = MB3_MeshBakerEditorFunctions.MakeTex(8,8,backgroundColor); multipleMaterialBackgroundStyle.normal.background = multipleMaterialBackgroundColor; multipleMaterialBackgroundStyleDarker.normal.background = multipleMaterialBackgroundColorDarker; editorBoxBackgroundStyle.normal.background = editorBoxBackgroundColor; editorBoxBackgroundStyle.border = new RectOffset(0, 0, 0, 0); editorBoxBackgroundStyle.margin = new RectOffset(5, 5, 5, 5); editorBoxBackgroundStyle.padding = new RectOffset(10, 10, 10, 10); } public void OnDisable() { if (multipleMaterialBackgroundColor != null) GameObject.DestroyImmediate(multipleMaterialBackgroundColor); if (multipleMaterialBackgroundColorDarker != null) GameObject.DestroyImmediate(multipleMaterialBackgroundColorDarker); if (editorBoxBackgroundColor != null) GameObject.DestroyImmediate(editorBoxBackgroundColor); } public void DrawGUI(SerializedObject textureBaker, MB3_TextureBaker momm, System.Type editorWindow) { if (textureBaker == null) { return; } textureBaker.Update(); showInstructions = EditorGUILayout.Foldout(showInstructions, "Instructions:"); if (showInstructions) { EditorGUILayout.HelpBox("1. Add scene objects or prefabs to combine. For best results these should use the same shader as result material.\n\n" + "2. Create Empty Assets For Combined Material(s)\n\n" + "3. Check that shader on result material(s) are correct.\n\n" + "4. Bake materials into combined material(s).\n\n" + "5. Look at warnings/errors in console. Decide if action needs to be taken.\n\n" + "6. You are now ready to build combined meshs or adjust meshes to use the combined material(s).", UnityEditor.MessageType.None); } //mom.LOG_LEVEL = (MB2_LogLevel) EditorGUILayout.EnumPopup("Log Level", mom.LOG_LEVEL); EditorGUILayout.PropertyField(logLevel, logLevelContent); EditorGUILayout.Separator(); EditorGUILayout.BeginVertical(editorBoxBackgroundStyle); EditorGUILayout.LabelField("Objects To Be Combined", EditorStyles.boldLabel); if (GUILayout.Button(openToolsWindowLabelContent)) { MB3_MeshBakerEditorWindowInterface mmWin = (MB3_MeshBakerEditorWindowInterface)EditorWindow.GetWindow(editorWindow); mmWin.target = (MB3_MeshBakerRoot)momm; } EditorGUILayout.PropertyField(objsToMesh, objectsToCombineGUIContent, true); EditorGUILayout.Separator(); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("Select Objects In Scene")) { Selection.objects = momm.GetObjectsToCombine().ToArray(); if (momm.GetObjectsToCombine().Count > 0) { SceneView.lastActiveSceneView.pivot = momm.GetObjectsToCombine()[0].transform.position; } } if (GUILayout.Button(gc_SortAlongAxis)) { MB3_MeshBakerRoot.ZSortObjects sorter = new MB3_MeshBakerRoot.ZSortObjects(); sorter.sortAxis = sortOrderAxis.vector3Value; sorter.SortByDistanceAlongAxis(momm.GetObjectsToCombine()); } EditorGUILayout.PropertyField(sortOrderAxis, GUIContent.none); EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); EditorGUILayout.Separator(); EditorGUILayout.LabelField("Output", EditorStyles.boldLabel); if (GUILayout.Button(createPrefabAndMaterialLabelContent)) { string newPrefabPath = EditorUtility.SaveFilePanelInProject("Asset name", "", "asset", "Enter a name for the baked texture results"); if (newPrefabPath != null) { CreateCombinedMaterialAssets(momm, newPrefabPath); } } EditorGUILayout.PropertyField(textureBakeResults, textureBakeResultsGUIContent); if (textureBakeResults.objectReferenceValue != null) { showContainsReport = EditorGUILayout.Foldout(showContainsReport, "Shaders & Materials Contained"); if (showContainsReport) { EditorGUILayout.HelpBox(((MB2_TextureBakeResults)textureBakeResults.objectReferenceValue).GetDescription(), MessageType.Info); } } EditorGUILayout.PropertyField(doMultiMaterial, new GUIContent("Multiple Combined Materials")); if (momm.doMultiMaterial) { EditorGUILayout.BeginVertical(multipleMaterialBackgroundStyle); EditorGUILayout.LabelField("Source Material To Combined Mapping", EditorStyles.boldLabel); float oldLabelWidth = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = 300; EditorGUILayout.PropertyField(doMultiMaterialIfOBUVs, gc_DoMultiMaterialSplitAtlasesIfOBUVs); EditorGUILayout.PropertyField(doMultiMaterialSplitAtlasesIfTooBig, gc_DoMultiMaterialSplitAtlasesIfTooBig); EditorGUIUtility.labelWidth = oldLabelWidth; if (GUILayout.Button(configMultiMatFromObjsContent)) { ConfigureMutiMaterialsFromObjsToCombine(momm, resultMaterials, textureBaker); } EditorGUILayout.BeginHorizontal(); resultMaterialsFoldout = EditorGUILayout.Foldout(resultMaterialsFoldout, combinedMaterialsGUIContent); if (GUILayout.Button(insertContent, EditorStyles.miniButtonLeft, buttonWidth)) { if (resultMaterials.arraySize == 0) { momm.resultMaterials = new MB_MultiMaterial[1]; momm.resultMaterials[0].considerMeshUVs = momm.fixOutOfBoundsUVs; } else { int idx = resultMaterials.arraySize - 1; resultMaterials.InsertArrayElementAtIndex(idx); resultMaterials.GetArrayElementAtIndex(idx + 1).FindPropertyRelative("considerMeshUVs").boolValue = momm.fixOutOfBoundsUVs; } } if (GUILayout.Button(deleteContent, EditorStyles.miniButtonRight, buttonWidth)) { resultMaterials.DeleteArrayElementAtIndex(resultMaterials.arraySize - 1); } EditorGUILayout.EndHorizontal(); if (resultMaterialsFoldout) { for (int i = 0; i < resultMaterials.arraySize; i++) { EditorGUILayout.Separator(); if (i % 2 == 1) { EditorGUILayout.BeginVertical(multipleMaterialBackgroundStyle); } else { EditorGUILayout.BeginVertical(multipleMaterialBackgroundStyleDarker); } string s = ""; if (i < momm.resultMaterials.Length && momm.resultMaterials[i] != null && momm.resultMaterials[i].combinedMaterial != null) s = momm.resultMaterials[i].combinedMaterial.shader.ToString(); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("---------- submesh:" + i + " " + s, EditorStyles.boldLabel); if (GUILayout.Button(deleteContent, EditorStyles.miniButtonRight, buttonWidth)) { resultMaterials.DeleteArrayElementAtIndex(i); } EditorGUILayout.EndHorizontal(); if (i < resultMaterials.arraySize) { EditorGUILayout.Separator(); SerializedProperty resMat = resultMaterials.GetArrayElementAtIndex(i); EditorGUILayout.PropertyField(resMat.FindPropertyRelative("combinedMaterial")); EditorGUILayout.PropertyField(resMat.FindPropertyRelative("considerMeshUVs")); SerializedProperty sourceMats = resMat.FindPropertyRelative("sourceMaterials"); EditorGUILayout.PropertyField(sourceMats, true); } EditorGUILayout.EndVertical(); } } EditorGUILayout.EndVertical(); } else { EditorGUILayout.PropertyField(resultMaterial, new GUIContent("Combined Mesh Material")); } int labelWidth = 200; EditorGUILayout.Separator(); EditorGUILayout.BeginVertical(editorBoxBackgroundStyle); EditorGUILayout.LabelField("Material Bake Options", EditorStyles.boldLabel); DrawPropertyFieldWithLabelWidth(atlasPadding, new GUIContent("Atlas Padding"), labelWidth); DrawPropertyFieldWithLabelWidth(maxAtlasSize, maxAtlasSizeGUIContent, labelWidth); DrawPropertyFieldWithLabelWidth(resizePowerOfTwoTextures, resizePowerOfTwoGUIContent, labelWidth); DrawPropertyFieldWithLabelWidth(maxTilingBakeSize, maxTilingBakeSizeGUIContent, labelWidth); EditorGUI.BeginDisabledGroup(momm.doMultiMaterial); DrawPropertyFieldWithLabelWidth(considerMeshUVs, fixOutOfBoundsGUIContent, labelWidth); EditorGUI.EndDisabledGroup(); if (texturePackingAlgorithm.intValue == (int)MB2_PackingAlgorithmEnum.MeshBakerTexturePacker || texturePackingAlgorithm.intValue == (int)MB2_PackingAlgorithmEnum.MeshBakerTexturePacker_Fast) { DrawPropertyFieldWithLabelWidth(forcePowerOfTwoAtlas, forcePowerOfTwoAtlasContent, labelWidth); } DrawPropertyFieldWithLabelWidth(considerNonTextureProperties, considerNonTexturePropertiesContent, labelWidth); if (texturePackingAlgorithm.intValue == (int)MB2_PackingAlgorithmEnum.UnitysPackTextures) { EditorGUILayout.HelpBox("Unity's texture packer has memory problems and frequently crashes the editor.", MessageType.Warning); } EditorGUILayout.PropertyField(texturePackingAlgorithm, texturePackingAgorithmGUIContent); EditorGUILayout.PropertyField(customShaderProperties, customShaderPropertyNamesGUIContent, true); EditorGUILayout.EndVertical(); EditorGUILayout.Separator(); Color oldColor = GUI.backgroundColor; GUI.color = buttonColor; if (GUILayout.Button("Bake Materials Into Combined Material")) { momm.CreateAtlases(updateProgressBar, true, new MB3_EditorMethods()); EditorUtility.ClearProgressBar(); if (momm.textureBakeResults != null) EditorUtility.SetDirty(momm.textureBakeResults); } GUI.backgroundColor = oldColor; textureBaker.ApplyModifiedProperties(); if (GUI.changed) { textureBaker.SetIsDifferentCacheDirty(); } } public void DrawPropertyFieldWithLabelWidth(SerializedProperty prop, GUIContent content, int labelWidth) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField(content, GUILayout.Width(labelWidth)); EditorGUILayout.PropertyField(prop, noneContent); EditorGUILayout.EndHorizontal(); } public void updateProgressBar(string msg, float progress){ EditorUtility.DisplayProgressBar("Combining Meshes", msg, progress); } /* tried to see if the MultiMaterialConfig could be done using the GroupBy filters. Saddly it didn't work */ public static void ConfigureMutiMaterialsFromObjsToCombine2(MB3_TextureBaker mom, SerializedProperty resultMaterials, SerializedObject textureBaker) { if (mom.GetObjectsToCombine().Count == 0) { Debug.LogError("You need to add some objects to combine before building the multi material list."); return; } if (resultMaterials.arraySize > 0) { Debug.LogError("You already have some source to combined material mappings configured. You must remove these before doing this operation."); return; } if (mom.textureBakeResults == null) { Debug.LogError("Texture Bake Result asset must be set before using this operation."); return; } //validate that the objects to be combined are valid for (int i = 0; i < mom.GetObjectsToCombine().Count; i++) { GameObject go = mom.GetObjectsToCombine()[i]; if (go == null) { Debug.LogError("Null object in list of objects to combine at position " + i); return; } Renderer r = go.GetComponent<Renderer>(); if (r == null || (!(r is MeshRenderer) && !(r is SkinnedMeshRenderer))) { Debug.LogError("GameObject at position " + i + " in list of objects to combine did not have a renderer"); return; } if (r.sharedMaterial == null) { Debug.LogError("GameObject at position " + i + " in list of objects to combine has a null material"); return; } } IGroupByFilter[] filters = new IGroupByFilter[3]; filters[0] = new GroupByOutOfBoundsUVs(); filters[1] = new GroupByShader(); filters[2] = new MB3_GroupByStandardShaderType(); List<GameObjectFilterInfo> gameObjects = new List<GameObjectFilterInfo>(); HashSet<GameObject> objectsAlreadyIncludedInBakers = new HashSet<GameObject>(); for (int i = 0; i < mom.GetObjectsToCombine().Count; i++) { GameObjectFilterInfo goaw = new GameObjectFilterInfo(mom.GetObjectsToCombine()[i], objectsAlreadyIncludedInBakers, filters); if (goaw.materials.Length > 0) //don't consider renderers with no materials { gameObjects.Add(goaw); } } //analyse meshes Dictionary<int, MB_Utility.MeshAnalysisResult> meshAnalysisResultCache = new Dictionary<int, MB_Utility.MeshAnalysisResult>(); int totalVerts = 0; for (int i = 0; i < gameObjects.Count; i++) { //string rpt = String.Format("Processing {0} [{1} of {2}]", gameObjects[i].go.name, i, gameObjects.Count); //EditorUtility.DisplayProgressBar("Analysing Scene", rpt + " A", .6f); Mesh mm = MB_Utility.GetMesh(gameObjects[i].go); int nVerts = 0; if (mm != null) { nVerts += mm.vertexCount; MB_Utility.MeshAnalysisResult mar; if (!meshAnalysisResultCache.TryGetValue(mm.GetInstanceID(), out mar)) { //EditorUtility.DisplayProgressBar("Analysing Scene", rpt + " Check Out Of Bounds UVs", .6f); MB_Utility.hasOutOfBoundsUVs(mm, ref mar); //Rect dummy = mar.uvRect; MB_Utility.doSubmeshesShareVertsOrTris(mm, ref mar); meshAnalysisResultCache.Add(mm.GetInstanceID(), mar); } if (mar.hasOutOfBoundsUVs) { int w = (int)mar.uvRect.width; int h = (int)mar.uvRect.height; gameObjects[i].outOfBoundsUVs = true; gameObjects[i].warning += " [WARNING: has uvs outside the range (0,1) tex is tiled " + w + "x" + h + " times]"; } if (mar.hasOverlappingSubmeshVerts) { gameObjects[i].submeshesOverlap = true; gameObjects[i].warning += " [WARNING: Submeshes share verts or triangles. 'Multiple Combined Materials' feature may not work.]"; } } totalVerts += nVerts; //EditorUtility.DisplayProgressBar("Analysing Scene", rpt + " Validate OBuvs Multi Material", .6f); Renderer mr = gameObjects[i].go.GetComponent<Renderer>(); if (!MB_Utility.AreAllSharedMaterialsDistinct(mr.sharedMaterials)) { gameObjects[i].warning += " [WARNING: Object uses same material on multiple submeshes. This may produce poor results when used with multiple materials or fix out of bounds uvs.]"; } } List<GameObjectFilterInfo> objsNotAddedToBaker = new List<GameObjectFilterInfo>(); Dictionary<GameObjectFilterInfo, List<List<GameObjectFilterInfo>>> gs2bakeGroupMap = MB3_MeshBakerEditorWindow.sortIntoBakeGroups3(gameObjects, objsNotAddedToBaker, filters, false, mom.maxAtlasSize); mom.resultMaterials = new MB_MultiMaterial[gs2bakeGroupMap.Keys.Count]; string pth = AssetDatabase.GetAssetPath(mom.textureBakeResults); string baseName = Path.GetFileNameWithoutExtension(pth); string folderPath = pth.Substring(0, pth.Length - baseName.Length - 6); int k = 0; foreach (GameObjectFilterInfo m in gs2bakeGroupMap.Keys) { MB_MultiMaterial mm = mom.resultMaterials[k] = new MB_MultiMaterial(); mm.sourceMaterials = new List<Material>(); mm.sourceMaterials.Add(m.materials[0]); string matName = folderPath + baseName + "-mat" + k + ".mat"; Material newMat = new Material(Shader.Find("Diffuse")); MB3_TextureBaker.ConfigureNewMaterialToMatchOld(newMat, m.materials[0]); AssetDatabase.CreateAsset(newMat, matName); mm.combinedMaterial = (Material)AssetDatabase.LoadAssetAtPath(matName, typeof(Material)); k++; } MBVersionEditor.UpdateIfDirtyOrScript(textureBaker); } public class MultiMatSubmeshInfo{ public Shader shader; public GameObjectFilterInfo.StandardShaderBlendMode stdBlendMode = GameObjectFilterInfo.StandardShaderBlendMode.NotApplicable; public MultiMatSubmeshInfo(Shader s, Material m) { shader = s; if (m.shader.name.StartsWith("Standard") && m.HasProperty("_Mode")) { stdBlendMode = (GameObjectFilterInfo.StandardShaderBlendMode) m.GetFloat("_Mode"); } else { stdBlendMode = GameObjectFilterInfo.StandardShaderBlendMode.NotApplicable; } } public override bool Equals(object obj) { MultiMatSubmeshInfo b = (MultiMatSubmeshInfo)obj; return (stdBlendMode == b.stdBlendMode && shader == b.shader); } public override int GetHashCode() { return shader.GetHashCode() ^ (int) stdBlendMode; } } //posibilities // using fixOutOfBoundsUVs or not // public static void ConfigureMutiMaterialsFromObjsToCombine(MB3_TextureBaker mom, SerializedProperty resultMaterials, SerializedObject textureBaker){ if (mom.GetObjectsToCombine().Count == 0){ Debug.LogError("You need to add some objects to combine before building the multi material list."); return; } if (resultMaterials.arraySize > 0){ Debug.LogError("You already have some source to combined material mappings configured. You must remove these before doing this operation."); return; } if (mom.textureBakeResults == null){ Debug.LogError("Texture Bake Result asset must be set before using this operation."); return; } Dictionary<MultiMatSubmeshInfo, List<List<Material>>> shader2Material_map = new Dictionary<MultiMatSubmeshInfo, List<List<Material>>>(); Dictionary<Material,Mesh> obUVobject2mesh_map = new Dictionary<Material,Mesh>(); //validate that the objects to be combined are valid for (int i = 0; i < mom.GetObjectsToCombine().Count; i++){ GameObject go = mom.GetObjectsToCombine()[i]; if (go == null) { Debug.LogError("Null object in list of objects to combine at position " + i); return; } Renderer r = go.GetComponent<Renderer>(); if (r == null || (!(r is MeshRenderer) && !(r is SkinnedMeshRenderer))){ Debug.LogError("GameObject at position " + i + " in list of objects to combine did not have a renderer"); return; } if (r.sharedMaterial == null){ Debug.LogError("GameObject at position " + i + " in list of objects to combine has a null material"); return; } } //first pass put any meshes with obUVs on their own submesh if not fixing OB uvs if (mom.doMultiMaterialSplitAtlasesIfOBUVs){ for (int i = 0; i < mom.GetObjectsToCombine().Count; i++){ GameObject go = mom.GetObjectsToCombine()[i]; Mesh m = MB_Utility.GetMesh(go); MB_Utility.MeshAnalysisResult dummyMar = new MB_Utility.MeshAnalysisResult(); Renderer r = go.GetComponent<Renderer>(); for (int j = 0; j < r.sharedMaterials.Length; j++){ if (MB_Utility.hasOutOfBoundsUVs(m, ref dummyMar, j)){ if (!obUVobject2mesh_map.ContainsKey(r.sharedMaterials[j])){ Debug.LogWarning("Object " + go + " submesh " + j + " uses UVs outside the range 0,0..1,1 to generate tiling. This object has been mapped to its own submesh in the combined mesh. It can share a submesh with other objects that use different materials if you use the fix out of bounds UVs feature which will bake the tiling"); obUVobject2mesh_map.Add(r.sharedMaterials[j],m); } } } } } //second pass put other materials without OB uvs in a shader to material map for (int i = 0; i < mom.GetObjectsToCombine().Count; i++){ Renderer r = mom.GetObjectsToCombine()[i].GetComponent<Renderer>(); for (int j = 0; j < r.sharedMaterials.Length; j++){ if (!obUVobject2mesh_map.ContainsKey(r.sharedMaterials[j])) { //if not already added if (r.sharedMaterials[j] == null) continue; List<List<Material>> binsOfMatsThatUseShader = null; MultiMatSubmeshInfo newKey = new MultiMatSubmeshInfo(r.sharedMaterials[j].shader, r.sharedMaterials[j]); if (!shader2Material_map.TryGetValue(newKey, out binsOfMatsThatUseShader)){ binsOfMatsThatUseShader = new List<List<Material>>(); binsOfMatsThatUseShader.Add(new List<Material>()); shader2Material_map.Add(newKey, binsOfMatsThatUseShader); } if (!binsOfMatsThatUseShader[0].Contains(r.sharedMaterials[j])) binsOfMatsThatUseShader[0].Add(r.sharedMaterials[j]); } } } int numResMats = shader2Material_map.Count; //third pass for each shader grouping check how big the atlas would be and group into bins that would fit in an atlas if (mom.doMultiMaterialSplitAtlasesIfTooBig) { numResMats = 0; foreach (MultiMatSubmeshInfo sh in shader2Material_map.Keys) { List<List<Material>> binsOfMatsThatUseShader = shader2Material_map[sh]; List<Material> allMatsThatUserShader = binsOfMatsThatUseShader[0];//at this point everything is in the same list binsOfMatsThatUseShader.RemoveAt(0); MB3_TextureCombiner combiner = mom.CreateAndConfigureTextureCombiner(); combiner.saveAtlasesAsAssets = false; if (allMatsThatUserShader.Count > 1) combiner.fixOutOfBoundsUVs = mom.fixOutOfBoundsUVs; else combiner.fixOutOfBoundsUVs = false; // Do the texture pack List<AtlasPackingResult> packingResults = new List<AtlasPackingResult>(); Material tempMat = new Material(sh.shader); combiner.CombineTexturesIntoAtlases(null, null, tempMat, mom.GetObjectsToCombine(), allMatsThatUserShader, null, packingResults, true); for (int i = 0; i < packingResults.Count; i++) { List<MatsAndGOs> matsData = (List<MatsAndGOs>) packingResults[i].data; List<Material> mats = new List<Material>(); for (int j = 0; j < matsData.Count; j++) { for (int kk = 0; kk < matsData[j].mats.Count; kk++) { if (!mats.Contains(matsData[j].mats[kk].mat)) { mats.Add(matsData[j].mats[kk].mat); } } } binsOfMatsThatUseShader.Add(mats); } numResMats += binsOfMatsThatUseShader.Count; } } //build the result materials if (shader2Material_map.Count == 0 && obUVobject2mesh_map.Count == 0) Debug.LogError("Found no materials in list of objects to combine"); mom.resultMaterials = new MB_MultiMaterial[numResMats + obUVobject2mesh_map.Count]; string pth = AssetDatabase.GetAssetPath(mom.textureBakeResults); string baseName = Path.GetFileNameWithoutExtension(pth); string folderPath = pth.Substring(0,pth.Length - baseName.Length - 6); int k = 0; foreach(MultiMatSubmeshInfo sh in shader2Material_map.Keys){ foreach (List<Material> matsThatUse in shader2Material_map[sh]) { MB_MultiMaterial mm = mom.resultMaterials[k] = new MB_MultiMaterial(); mm.sourceMaterials = matsThatUse; if (mm.sourceMaterials.Count == 1) { mm.considerMeshUVs = false; } else { mm.considerMeshUVs = mom.fixOutOfBoundsUVs; } string matName = folderPath + baseName + "-mat" + k + ".mat"; Material newMat = new Material(Shader.Find("Diffuse")); if (matsThatUse.Count > 0 && matsThatUse[0] != null) { MB3_TextureBaker.ConfigureNewMaterialToMatchOld(newMat, matsThatUse[0]); } AssetDatabase.CreateAsset(newMat, matName); mm.combinedMaterial = (Material)AssetDatabase.LoadAssetAtPath(matName, typeof(Material)); k++; } } foreach(Material m in obUVobject2mesh_map.Keys){ MB_MultiMaterial mm = mom.resultMaterials[k] = new MB_MultiMaterial(); mm.sourceMaterials = new List<Material>(); mm.sourceMaterials.Add(m); mm.considerMeshUVs = false; string matName = folderPath + baseName + "-mat" + k + ".mat"; Material newMat = new Material(Shader.Find("Diffuse")); MB3_TextureBaker.ConfigureNewMaterialToMatchOld(newMat,m); AssetDatabase.CreateAsset(newMat, matName); mm.combinedMaterial = (Material) AssetDatabase.LoadAssetAtPath(matName,typeof(Material)); k++; } MBVersionEditor.UpdateIfDirtyOrScript(textureBaker); } public static void CreateCombinedMaterialAssets(MB3_TextureBaker target, string pth){ MB3_TextureBaker mom = (MB3_TextureBaker) target; string baseName = Path.GetFileNameWithoutExtension(pth); if (baseName == null || baseName.Length == 0) return; string folderPath = pth.Substring(0,pth.Length - baseName.Length - 6); List<string> matNames = new List<string>(); if (mom.doMultiMaterial){ for (int i = 0; i < mom.resultMaterials.Length; i++){ matNames.Add( folderPath + baseName + "-mat" + i + ".mat" ); AssetDatabase.CreateAsset(new Material(Shader.Find("Diffuse")), matNames[i]); mom.resultMaterials[i].combinedMaterial = (Material) AssetDatabase.LoadAssetAtPath(matNames[i],typeof(Material)); } }else{ matNames.Add( folderPath + baseName + "-mat.mat" ); Material newMat = null; if (mom.GetObjectsToCombine().Count > 0 && mom.GetObjectsToCombine()[0] != null){ Renderer r = mom.GetObjectsToCombine()[0].GetComponent<Renderer>(); if (r == null){ Debug.LogWarning("Object " + mom.GetObjectsToCombine()[0] + " does not have a Renderer on it."); } else { if (r.sharedMaterial != null){ newMat = new Material(r.sharedMaterial); //newMat.shader = r.sharedMaterial.shader; MB3_TextureBaker.ConfigureNewMaterialToMatchOld(newMat,r.sharedMaterial); } } } else { Debug.Log("If you add objects to be combined before creating the Combined Material Assets. Then Mesh Baker will create a result material that is a duplicate of the material on the first object to be combined. This saves time configuring the shader."); } if (newMat == null){ newMat = new Material(Shader.Find("Diffuse")); } AssetDatabase.CreateAsset(newMat, matNames[0]); mom.resultMaterial = (Material) AssetDatabase.LoadAssetAtPath(matNames[0],typeof(Material)); } //create the MB2_TextureBakeResults AssetDatabase.CreateAsset(ScriptableObject.CreateInstance<MB2_TextureBakeResults>(),pth); mom.textureBakeResults = (MB2_TextureBakeResults) AssetDatabase.LoadAssetAtPath(pth, typeof(MB2_TextureBakeResults)); AssetDatabase.Refresh(); } } }
59.448753
611
0.619682
[ "Apache-2.0" ]
lmj921/PerformanceExample
PerformanceExample/Assets/MeshBaker/scripts/Editor/MB3_TextureBakerEditorInternal.cs
42,923
C#
using System; using System.Linq; using LinqToDB.Data; using NUnit.Framework; namespace Tests.xUpdate { using LinqToDB; using Model; public partial class MergeTests { [Test, MergeUpdateWithDeleteDataContextSource] public void SameSourceUpdateWithDelete(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var rows = table .Merge() .Using(GetSource1(db)) .On((t, s) => s.Id == 3) .UpdateWhenMatchedThenDelete((t, s) => t.Id == 4) .Merge(); var result = table.OrderBy(_ => _.Id).ToList(); AssertRowCount(4, rows, context); Assert.AreEqual(3, result.Count); Assert.AreEqual(1, result[0].Id); Assert.IsNull(result[0].Field1); Assert.AreEqual(3, result[0].Field2); Assert.IsNull(result[0].Field3); Assert.IsNull(result[0].Field4); Assert.IsNull(result[0].Field5); Assert.AreEqual(2, result[1].Id); Assert.IsNull(result[1].Field1); Assert.AreEqual(3, result[1].Field2); Assert.IsNull(result[1].Field3); Assert.IsNull(result[1].Field4); Assert.IsNull(result[1].Field5); Assert.AreEqual(3, result[2].Id); Assert.IsNull(result[2].Field1); Assert.AreEqual(3, result[2].Field2); Assert.IsNull(result[2].Field3); Assert.AreEqual(203, result[2].Field4); Assert.IsNull(result[2].Field5); } } [Test, MergeUpdateWithDeleteDataContextSource] public void UpdateWithDeletePartialSourceProjection_KnownFieldsInDefaultSetter(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var rows = table .Merge() .Using(GetSource1(db) .Select(s => new TestMapping1() { Id = s.Id, Field1 = s.Field1, Field2 = s.Field2, Field3 = s.Field3 })) .On((t, s) => s.Id == 3) .UpdateWhenMatchedThenDelete((t, s) => t.Id == 4) .Merge(); var result = table.OrderBy(_ => _.Id).ToList(); AssertRowCount(4, rows, context); Assert.AreEqual(3, result.Count); Assert.AreEqual(1, result[0].Id); Assert.IsNull(result[0].Field1); Assert.AreEqual(3, result[0].Field2); Assert.IsNull(result[0].Field3); Assert.IsNull(result[0].Field4); Assert.IsNull(result[0].Field5); Assert.AreEqual(2, result[1].Id); Assert.IsNull(result[1].Field1); Assert.AreEqual(3, result[1].Field2); Assert.IsNull(result[1].Field3); Assert.IsNull(result[1].Field4); Assert.IsNull(result[1].Field5); Assert.AreEqual(3, result[2].Id); Assert.IsNull(result[2].Field1); Assert.AreEqual(3, result[2].Field2); Assert.IsNull(result[2].Field3); Assert.AreEqual(203, result[2].Field4); Assert.IsNull(result[2].Field5); } } [Test, MergeUpdateWithDeleteDataContextSource] public void SameSourceUpdateWithDeleteWithPredicate(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var rows = table .Merge() .Using(GetSource1(db)) .OnTargetKey() .UpdateWhenMatchedAndThenDelete((t, s) => s.Id == 4 || s.Id == 3, (t, s) => t.Id == 3) .Merge(); var result = table.OrderBy(_ => _.Id).ToList(); AssertRowCount(2, rows, context); Assert.AreEqual(3, result.Count); AssertRow(InitialTargetData[0], result[0], null, null); AssertRow(InitialTargetData[1], result[1], null, null); Assert.AreEqual(4, result[2].Id); Assert.AreEqual(5, result[2].Field1); Assert.AreEqual(7, result[2].Field2); Assert.IsNull(result[2].Field3); Assert.IsNull(result[2].Field4); Assert.IsNull(result[2].Field5); } } [Test, MergeUpdateWithDeleteDataContextSource] public void SameSourceUpdateWithDeleteWithUpdate(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var rows = table .Merge() .Using(GetSource1(db)) .OnTargetKey() .UpdateWhenMatchedThenDelete( (t, s) => new TestMapping1() { Field1 = t.Field1 + s.Field1, Field2 = t.Field2 + s.Field2, Field3 = t.Field3 + s.Field3, Field4 = t.Field4 + s.Field4, Field5 = t.Field5 + s.Field5 }, (t, s) => t.Field1 == 10) .Merge(); var result = table.OrderBy(_ => _.Id).ToList(); AssertRowCount(2, rows, context); Assert.AreEqual(3, result.Count); AssertRow(InitialTargetData[0], result[0], null, null); AssertRow(InitialTargetData[1], result[1], null, null); Assert.AreEqual(3, result[2].Id); Assert.IsNull(result[2].Field1); Assert.AreEqual(6, result[2].Field2); Assert.IsNull(result[2].Field3); Assert.IsNull(result[2].Field4); Assert.IsNull(result[2].Field5); } } [Test, MergeUpdateWithDeleteDataContextSource] public void SameSourceUpdateWithDeleteWithPredicateAndUpdate(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var rows = table .Merge() .Using(GetSource1(db)) .OnTargetKey() .UpdateWhenMatchedAndThenDelete( (t, s) => s.Id == 3 || t.Id == 4, (t, s) => new TestMapping1() { Field1 = t.Field1 + s.Field5, Field2 = t.Field2 + s.Field4, Field3 = t.Field3 + s.Field3, Field4 = t.Field4 + s.Field2, Field5 = t.Field5 + s.Field1 }, (t, s) => s.Id == 3) .Merge(); var result = table.OrderBy(_ => _.Id).ToList(); AssertRowCount(2, rows, context); Assert.AreEqual(3, result.Count); AssertRow(InitialTargetData[0], result[0], null, null); AssertRow(InitialTargetData[1], result[1], null, null); Assert.AreEqual(4, result[2].Id); Assert.IsNull(result[2].Field1); Assert.AreEqual(220, result[2].Field2); Assert.IsNull(result[2].Field3); Assert.IsNull(result[2].Field4); Assert.IsNull(result[2].Field5); } } [Test, MergeUpdateWithDeleteDataContextSource] public void UpdateWithDeletePartialSourceProjection_KnownFieldInUpdateCondition(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var rows = table .Merge() .Using(GetSource1(db) .Select(s => new TestMapping1() { Id = s.Id, Field2 = s.Field2, Field5 = s.Field5 })) .OnTargetKey() .UpdateWhenMatchedAndThenDelete( (t, s) => s.Field2 == 3, (t, s) => new TestMapping1() { Field1 = t.Field1 + s.Field5 }, (t, s) => s.Id == 3) .Merge(); var result = table.OrderBy(_ => _.Id).ToList(); AssertRowCount(1, rows, context); Assert.AreEqual(3, result.Count); AssertRow(InitialTargetData[0], result[0], null, null); AssertRow(InitialTargetData[1], result[1], null, null); Assert.AreEqual(4, result[2].Id); Assert.AreEqual(5, result[2].Field1); Assert.AreEqual(6, result[2].Field2); Assert.IsNull(result[2].Field3); Assert.IsNull(result[2].Field4); Assert.IsNull(result[2].Field5); } } [Test, MergeUpdateWithDeleteDataContextSource] public void OtherSourceUpdateWithDelete(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var rows = table .Merge() .Using(GetSource2(db)) .On((t, s) => t.Id == s.OtherId) .UpdateWhenMatchedThenDelete( (t, s) => new TestMapping1() { Field1 = s.OtherField1, Field2 = s.OtherField2, Field3 = s.OtherField3, Field4 = s.OtherField4, Field5 = s.OtherField5 }, (t, s) => s.OtherId == 4) .Merge(); var result = table.OrderBy(_ => _.Id).ToList(); AssertRowCount(2, rows, context); Assert.AreEqual(3, result.Count); AssertRow(InitialTargetData[0], result[0], null, null); AssertRow(InitialTargetData[1], result[1], null, null); Assert.AreEqual(3, result[2].Id); Assert.IsNull(result[2].Field1); Assert.AreEqual(3, result[2].Field2); Assert.IsNull(result[2].Field3); Assert.IsNull(result[2].Field4); Assert.IsNull(result[2].Field5); } } [Test, MergeUpdateWithDeleteDataContextSource] public void UpdateWithDeletePartialSourceProjection_KnownFieldInDeleteCondition(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var rows = table .Merge() .Using(GetSource2(db) .Select(s => new TestMapping2() { OtherId = s.OtherId, OtherField1 = s.OtherField1, OtherField2 = s.OtherField2 })) .On((t, s) => t.Id == s.OtherId) .UpdateWhenMatchedThenDelete( (t, s) => new TestMapping1() { Field1 = s.OtherField1, Field2 = s.OtherField2 }, (t, s) => s.OtherId == 4) .Merge(); var result = table.OrderBy(_ => _.Id).ToList(); AssertRowCount(2, rows, context); Assert.AreEqual(3, result.Count); AssertRow(InitialTargetData[0], result[0], null, null); AssertRow(InitialTargetData[1], result[1], null, null); Assert.AreEqual(3, result[2].Id); Assert.IsNull(result[2].Field1); Assert.AreEqual(3, result[2].Field2); Assert.IsNull(result[2].Field3); Assert.AreEqual(203, result[2].Field4); Assert.IsNull(result[2].Field5); } } [Test, MergeUpdateWithDeleteDataContextSource] public void OtherSourceUpdateWithDeleteWithPredicate(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var rows = table .Merge() .Using(GetSource2(db)) .On((t, s) => t.Id == s.OtherId) .UpdateWhenMatchedAndThenDelete( (t, s) => s.OtherField4 == 214 || t.Id == 3, (t, s) => new TestMapping1() { Field1 = s.OtherField1, Field2 = s.OtherField2, Field3 = s.OtherField3, Field4 = s.OtherField4, Field5 = s.OtherField5 }, (t, s) => t.Id == 3) .Merge(); var result = table.OrderBy(_ => _.Id).ToList(); AssertRowCount(2, rows, context); Assert.AreEqual(3, result.Count); AssertRow(InitialTargetData[0], result[0], null, null); AssertRow(InitialTargetData[1], result[1], null, null); Assert.AreEqual(4, result[2].Id); Assert.AreEqual(5, result[2].Field1); Assert.AreEqual(7, result[2].Field2); Assert.IsNull(result[2].Field3); Assert.AreEqual(214, result[2].Field4); Assert.IsNull(result[2].Field5); } } [Test, MergeUpdateWithDeleteDataContextSource] public void AnonymousSourceUpdateWithDeleteWithPredicate(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var rows = table .Merge() .Using(GetSource2(db).Select(_ => new { Key = _.OtherId, Field01 = _.OtherField1, Field02 = _.OtherField2, Field03 = _.OtherField3, Field04 = _.OtherField4, Field05 = _.OtherField5, })) .On((t, s) => t.Id == s.Key) .UpdateWhenMatchedAndThenDelete( (t, s) => s.Field04 == 214 || t.Id == 3, (t, s) => new TestMapping1() { Field1 = s.Field01, Field2 = s.Field02, Field3 = s.Field03, Field4 = s.Field04, Field5 = s.Field05 }, (t, s) => s.Key == 3) .Merge(); var result = table.OrderBy(_ => _.Id).ToList(); AssertRowCount(2, rows, context); Assert.AreEqual(3, result.Count); AssertRow(InitialTargetData[0], result[0], null, null); AssertRow(InitialTargetData[1], result[1], null, null); Assert.AreEqual(4, result[2].Id); Assert.AreEqual(5, result[2].Field1); Assert.AreEqual(7, result[2].Field2); Assert.IsNull(result[2].Field3); Assert.AreEqual(214, result[2].Field4); Assert.IsNull(result[2].Field5); } } [Test, MergeUpdateWithDeleteDataContextSource] public void AnonymousListSourceUpdateWithDeleteWithPredicate(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var rows = table .Merge() .Using(GetSource2(db).ToList().Select(_ => new { Key = _.OtherId, Field01 = _.OtherField1, Field02 = _.OtherField2, Field03 = _.OtherField3, Field04 = _.OtherField4, Field05 = _.OtherField5, })) .On((t, s) => t.Id == s.Key) .UpdateWhenMatchedAndThenDelete( (t, s) => s.Field04 == 214 || s.Key == 3, (t, s) => new TestMapping1() { Field1 = s.Field01, Field2 = s.Field02, Field3 = s.Field03, Field4 = s.Field04, Field5 = s.Field05 }, (t, s) => s.Key == 3) .Merge(); var result = table.OrderBy(_ => _.Id).ToList(); AssertRowCount(2, rows, context); Assert.AreEqual(3, result.Count); AssertRow(InitialTargetData[0], result[0], null, null); AssertRow(InitialTargetData[1], result[1], null, null); Assert.AreEqual(4, result[2].Id); Assert.AreEqual(5, result[2].Field1); Assert.AreEqual(7, result[2].Field2); Assert.IsNull(result[2].Field3); Assert.AreEqual(214, result[2].Field4); Assert.IsNull(result[2].Field5); } } [Test, MergeUpdateWithDeleteDataContextSource] public void UpdateWithDeleteReservedAndCaseNames(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var rows = table .Merge() .Using(GetSource2(db).Select(_ => new { order = _.OtherId, delete = _.OtherField1, Delete1 = _.OtherField2, Field = _.OtherField3, field1 = _.OtherField4, As = _.OtherField5, })) .On((t, s) => t.Id == s.order) .UpdateWhenMatchedAndThenDelete( (t, s) => s.field1 == 214 || s.order == 3, (t, s) => new TestMapping1() { Field1 = s.delete, Field2 = s.Delete1, Field3 = s.Field, Field4 = s.field1, Field5 = s.As }, (t, s) => t.Id == 3) .Merge(); var result = table.OrderBy(_ => _.Id).ToList(); AssertRowCount(2, rows, context); Assert.AreEqual(3, result.Count); AssertRow(InitialTargetData[0], result[0], null, null); AssertRow(InitialTargetData[1], result[1], null, null); Assert.AreEqual(4, result[2].Id); Assert.AreEqual(5, result[2].Field1); Assert.AreEqual(7, result[2].Field2); Assert.IsNull(result[2].Field3); Assert.AreEqual(214, result[2].Field4); Assert.IsNull(result[2].Field5); } } [Test, MergeUpdateWithDeleteDataContextSource] public void UpdateWithDeleteReservedAndCaseNamesFromList(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var rows = table .Merge() .Using(GetSource2(db).ToList().Select(_ => new { @in = _.OtherId, join = _.OtherField1, outer = _.OtherField2, inner = _.OtherField3, with = _.OtherField4, left = _.OtherField5, })) .On((t, s) => t.Id == s.@in) .UpdateWhenMatchedAndThenDelete( (t, s) => s.with == 214 || t.Id == 3, (t, s) => new TestMapping1() { Field1 = s.join, Field2 = s.outer, Field3 = s.inner, Field4 = s.with, Field5 = s.left }, (t, s) => t.Id == 3) .Merge(); var result = table.OrderBy(_ => _.Id).ToList(); AssertRowCount(2, rows, context); Assert.AreEqual(3, result.Count); AssertRow(InitialTargetData[0], result[0], null, null); AssertRow(InitialTargetData[1], result[1], null, null); Assert.AreEqual(4, result[2].Id); Assert.AreEqual(5, result[2].Field1); Assert.AreEqual(7, result[2].Field2); Assert.IsNull(result[2].Field3); Assert.AreEqual(214, result[2].Field4); Assert.IsNull(result[2].Field5); } } [Test, MergeUpdateWithDeleteDataContextSource] public void UpdateWithDeleteDeleteByConditionOnUpdatedField(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var rows = table .Merge() .Using(GetSource2(db)) .On((t, s) => t.Id == s.OtherId) .UpdateWhenMatchedThenDelete( (t, s) => new TestMapping1() { Field1 = t.Field1 + s.OtherField1 + 345 }, (t, s) => t.Field1 == 355) .Merge(); var result = table.OrderBy(_ => _.Id).ToList(); AssertRowCount(2, rows, context); Assert.AreEqual(3, result.Count); AssertRow(InitialTargetData[0], result[0], null, null); AssertRow(InitialTargetData[1], result[1], null, null); AssertRow(InitialTargetData[2], result[2], null, 203); } } [Test, MergeUpdateWithDeleteDataContextSource] public void UpdateThenDeleteFromPartialSourceProjection_UnknownFieldInDeleteCondition(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var exception = Assert.Catch( () => table .Merge() .Using(table.Select(_ => new TestMapping1() { Id = _.Id, Field1 = _.Field1 })) .OnTargetKey() .UpdateWhenMatchedThenDelete( (t, s) => new TestMapping1() { Id = s.Id, Field1 = s.Field1 }, (t, s) => t.Field2 == s.Field2) .Merge()); Assert.IsInstanceOf<LinqToDBException>(exception); Assert.AreEqual("Column Field2 doesn't exist in source", exception.Message); } } [Test, MergeUpdateWithDeleteDataContextSource] public void UpdateThenDeleteFromPartialSourceProjection_UnknownFieldInSetter(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var exception = Assert.Catch( () => table .Merge() .Using(table.Select(_ => new TestMapping1() { Id = _.Id })) .OnTargetKey() .UpdateWhenMatchedThenDelete( (t, s) => new TestMapping1() { Id = s.Id, Field1 = s.Field2 }, (t, s) => t.Field2 == s.Field1) .Merge()); Assert.IsInstanceOf<LinqToDBException>(exception); Assert.AreEqual("Column Field2 doesn't exist in source", exception.Message); } } [Test, MergeUpdateWithDeleteDataContextSource] public void UpdateThenDeleteFromPartialSourceProjection_UnknownFieldInDefaultSetter(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var exception = Assert.Catch( () => table .Merge() .Using(table.Select(_ => new TestMapping1() { Id = _.Id, Field1 = _.Field1 })) .OnTargetKey() .UpdateWhenMatchedThenDelete((t, s) => t.Field2 == s.Field1) .Merge()); Assert.IsInstanceOf<LinqToDBException>(exception); Assert.AreEqual("Column Field2 doesn't exist in source", exception.Message); } } [Test, MergeUpdateWithDeleteDataContextSource] public void UpdateThenDeleteFromPartialSourceProjection_UnknownFieldInSearchCondition(string context) { using (var db = new TestDataConnection(context)) { PrepareData(db); var table = GetTarget(db); var exception = Assert.Catch( () => table .Merge() .Using(table.Select(_ => new TestMapping1() { Id = _.Id, Field1 = _.Field1 })) .OnTargetKey() .UpdateWhenMatchedAndThenDelete( (t, s) => t.Field2 == s.Field2, (t, s) => new TestMapping1() { Id = s.Id, Field1 = s.Field1 }, (t, s) => t.Field2 == s.Field1) .Merge()); Assert.IsInstanceOf<LinqToDBException>(exception); Assert.AreEqual("Column Field2 doesn't exist in source", exception.Message); } } } }
26.236531
103
0.618151
[ "MIT" ]
BlackballSoftware/linq2db
Tests/Linq/Update/MergeTests.Operations.UpdateWithDelete.cs
19,968
C#
// <copyright file="Benchmark1.cs" company="Endjin Limited"> // Copyright (c) Endjin Limited. All rights reserved. // </copyright> #pragma warning disable namespace FormatDraft201909Feature.ValidationOfIRs { using System.Threading.Tasks; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Diagnosers; using Corvus.JsonSchema.Benchmarking.Benchmarks; /// <summary> /// Additional properties benchmark. /// </summary> [MemoryDiagnoser] public class Benchmark1 : BenchmarkBase { /// <summary> /// Global setup. /// </summary> /// <returns>A <see cref="Task"/> which completes once setup is complete.</returns> [GlobalSetup] public Task GlobalSetup() { return this.GlobalSetup("draft2019-09\\format.json", "#/12/schema", "#/012/tests/001/data", true); } /// <summary> /// Validates using the Corvus types. /// </summary> [Benchmark] public void ValidateCorvus() { this.ValidateCorvusCore<FormatDraft201909Feature.ValidationOfIRs.Schema>(); } /// <summary> /// Validates using the Newtonsoft types. /// </summary> [Benchmark] public void ValidateNewtonsoft() { this.ValidateNewtonsoftCore(); } } }
30.772727
110
0.604136
[ "Apache-2.0" ]
corvus-dotnet/Corvus.JsonSchema
Solutions/Corvus.JsonSchema.Benchmarking/201909/FormatDraft201909/ValidationOfIRs/Benchmark1.cs
1,354
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System.Collections.Generic; using Azure.Core; namespace Microsoft.Marketplace.SaaS.Models { /// <summary> The PlanComponents. </summary> public partial class PlanComponents { /// <summary> Initializes a new instance of PlanComponents. </summary> internal PlanComponents() { RecurrentBillingTerms = new ChangeTrackingList<RecurrentBillingTerm>(); MeteringDimensions = new ChangeTrackingList<MeteringDimension>(); } /// <summary> Initializes a new instance of PlanComponents. </summary> /// <param name="recurrentBillingTerms"> . </param> /// <param name="meteringDimensions"> . </param> internal PlanComponents(IReadOnlyList<RecurrentBillingTerm> recurrentBillingTerms, IReadOnlyList<MeteringDimension> meteringDimensions) { RecurrentBillingTerms = recurrentBillingTerms; MeteringDimensions = meteringDimensions; } public IReadOnlyList<RecurrentBillingTerm> RecurrentBillingTerms { get; } public IReadOnlyList<MeteringDimension> MeteringDimensions { get; } } }
35.194444
143
0.695343
[ "MIT" ]
Azure/commercial-marketplace-client-dotnet
src/Microsoft.Marketplace.SaaS/Generated/Models/PlanComponents.cs
1,267
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Aspose" file="Resolution.cs"> // Copyright (c) 2018 Aspose.BarCode for Cloud // </copyright> // <summary> // 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. // </summary> // -------------------------------------------------------------------------------------------------------------------- using System; namespace Aspose.BarCode.Cloud.Sdk.Model { using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using System.Text; /// <summary> /// Represents resolutions of barcode. /// </summary> public class Resolution { /// <summary> /// Gets or sets resolution along X axis. /// </summary> public double? ResolutionX { get; set; } /// <summary> /// Gets or sets resolution along Y axis. /// </summary> public double? ResolutionY { get; set; } /// <summary> /// Get the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class Resolution {\n"); sb.Append(" ResolutionX: ").Append(this.ResolutionX).Append("\n"); sb.Append(" ResolutionY: ").Append(this.ResolutionY).Append("\n"); sb.Append("}\n"); return sb.ToString(); } } }
40.384615
119
0.594286
[ "MIT" ]
mmsajjad-aspose/aspose-barcode-cloud-dotnet
src/Model/Resolution.cs
2,625
C#
namespace System { [Serializable()] public class NullReferenceException : SystemException { public NullReferenceException() : base() { } public NullReferenceException(String message) : base(message) { } public NullReferenceException(String message, Exception innerException) : base(message, innerException) { } } }
19.416667
80
0.532189
[ "Apache-2.0" ]
AustinWise/Netduino-Micro-Framework
Framework/Subset_of_CorLib/System/NullReferenceException.cs
466
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace WebAppWithWebJobsVS.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
19.533333
67
0.569966
[ "Apache-2.0" ]
appveyor-tests/package-web-app-with-web-jobs
WebAppWithWebJobsVS/Controllers/HomeController.cs
588
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Engine.Editing { public class CallbackEditableProperty<T> : EditableProperty { private String name; private Func<T> getGenericValue; private Action<T> setGenericValue; private Func<String, bool> canParseStringToValue; private Func<String, T> parseStringToValue; public CallbackEditableProperty(String name, Func<T> getGenericValue, Action<T> setGenericValue, Func<String, bool> canParseStringToValue, Func<String, T> parseStringToValue) { this.name = name; this.getGenericValue = getGenericValue; this.setGenericValue = setGenericValue; this.canParseStringToValue = canParseStringToValue; this.parseStringToValue = parseStringToValue; } public bool Advanced { get { return false; } } public bool canParseString(int column, string value, out string errorMessage) { if (canParseStringToValue(value)) { errorMessage = null; return true; } errorMessage = "Cannot parse."; return false; } public Browser getBrowser(int column, EditUICallback uiCallback) { return null; } public Type getPropertyType(int column) { switch (column) { case 0: return typeof(String); case 1: return typeof(T); default: return typeof(String); } } public object getRealValue(int column) { switch (column) { case 0: return name; case 1: return getGenericValue(); default: return null; } } public string getValue(int column) { switch (column) { case 0: return name; case 1: return getGenericValue().ToString(); default: return null; } } public bool hasBrowser(int column) { return false; } public bool readOnly(int column) { return column == 0; } public void setValue(int column, object value) { if (column == 1) { setGenericValue((T)value); } } public void setValueStr(int column, string value) { if (column == 1) { setGenericValue(parseStringToValue(value)); } } } }
26.586207
183
0.46725
[ "MIT" ]
AnomalousMedical/Engine
Engine/Editing/CallbackEditableProperty.cs
3,086
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the lex-models-2017-04-19.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.LexModelBuildingService.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.LexModelBuildingService.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for GetBotVersions operation /// </summary> public class GetBotVersionsResponseUnmarshaller : JsonResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { GetBotVersionsResponse response = new GetBotVersionsResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("bots", targetDepth)) { var unmarshaller = new ListUnmarshaller<BotMetadata, BotMetadataUnmarshaller>(BotMetadataUnmarshaller.Instance); response.Bots = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("nextToken", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.NextToken = unmarshaller.Unmarshall(context); continue; } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context); if (errorResponse.Code != null && errorResponse.Code.Equals("BadRequestException")) { return new BadRequestException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("InternalFailureException")) { return new InternalFailureException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceededException")) { return new LimitExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } if (errorResponse.Code != null && errorResponse.Code.Equals("NotFoundException")) { return new NotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } return new AmazonLexModelBuildingServiceException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static GetBotVersionsResponseUnmarshaller _instance = new GetBotVersionsResponseUnmarshaller(); internal static GetBotVersionsResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static GetBotVersionsResponseUnmarshaller Instance { get { return _instance; } } } }
41.394958
178
0.655298
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/LexModelBuildingService/Generated/Model/Internal/MarshallTransformations/GetBotVersionsResponseUnmarshaller.cs
4,926
C#
using System; using System.Runtime.CompilerServices; using static ZstdSharp.UnsafeHelper; namespace ZstdSharp.Unsafe { public static unsafe partial class Methods { public static void ZSTD_fillHashTable(ZSTD_matchState_t* ms, void* end, ZSTD_dictTableLoadMethod_e dtlm) { ZSTD_compressionParameters* cParams = &ms->cParams; uint* hashTable = ms->hashTable; uint hBits = cParams->hashLog; uint mls = cParams->minMatch; byte* @base = ms->window.@base; byte* ip = @base + ms->nextToUpdate; byte* iend = ((byte*)(end)) - 8; uint fastHashFillStep = 3; for (; ip + fastHashFillStep < iend + 2; ip += fastHashFillStep) { uint curr = (uint)(ip - @base); nuint hash0 = ZSTD_hashPtr((void*)ip, hBits, mls); hashTable[hash0] = curr; if (dtlm == ZSTD_dictTableLoadMethod_e.ZSTD_dtlm_fast) { continue; } { uint p; for (p = 1; p < fastHashFillStep; ++p) { nuint hash = ZSTD_hashPtr((void*)(ip + p), hBits, mls); if (hashTable[hash] == 0) { hashTable[hash] = curr + p; } } } } } /** * If you squint hard enough (and ignore repcodes), the search operation at any * given position is broken into 4 stages: * * 1. Hash (map position to hash value via input read) * 2. Lookup (map hash val to index via hashtable read) * 3. Load (map index to value at that position via input read) * 4. Compare * * Each of these steps involves a memory read at an address which is computed * from the previous step. This means these steps must be sequenced and their * latencies are cumulative. * * Rather than do 1->2->3->4 sequentially for a single position before moving * onto the next, this implementation interleaves these operations across the * next few positions: * * R = Repcode Read & Compare * H = Hash * T = Table Lookup * M = Match Read & Compare * * Pos | Time --> * ----+------------------- * N | ... M * N+1 | ... TM * N+2 | R H T M * N+3 | H TM * N+4 | R H T M * N+5 | H ... * N+6 | R ... * * This is very much analogous to the pipelining of execution in a CPU. And just * like a CPU, we have to dump the pipeline when we find a match (i.e., take a * branch). * * When this happens, we throw away our current state, and do the following prep * to re-enter the loop: * * Pos | Time --> * ----+------------------- * N | H T * N+1 | H * * This is also the work we do at the beginning to enter the loop initially. */ [MethodImpl(MethodImplOptions.AggressiveInlining)] [InlineMethod.Inline] private static nuint ZSTD_compressBlock_fast_noDict_generic(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize, uint mls, uint hasStep) { ZSTD_compressionParameters* cParams = &ms->cParams; uint* hashTable = ms->hashTable; uint hlog = cParams->hashLog; nuint stepSize = hasStep != 0 ? (cParams->targetLength + (uint)((cParams->targetLength) == 0 ? 1 : 0) + 1) : 2; byte* @base = ms->window.@base; byte* istart = (byte*)(src); uint endIndex = (uint)((nuint)(istart - @base) + srcSize); uint prefixStartIndex = ZSTD_getLowestPrefixIndex(ms, endIndex, cParams->windowLog); byte* prefixStart = @base + prefixStartIndex; byte* iend = istart + srcSize; byte* ilimit = iend - 8; byte* anchor = istart; byte* ip0 = istart; byte* ip1; byte* ip2; byte* ip3; uint current0; uint rep_offset1 = rep[0]; uint rep_offset2 = rep[1]; uint offsetSaved = 0; nuint hash0; nuint hash1; uint idx; uint mval; uint offcode; byte* match0; nuint mLength; nuint step; byte* nextStep; nuint kStepIncr = (nuint)((1 << (8 - 1))); ip0 += ((ip0 == prefixStart) ? 1 : 0); { uint curr = (uint)(ip0 - @base); uint windowLow = ZSTD_getLowestPrefixIndex(ms, curr, cParams->windowLog); uint maxRep = curr - windowLow; if (rep_offset2 > maxRep) { offsetSaved = rep_offset2; rep_offset2 = 0; } if (rep_offset1 > maxRep) { offsetSaved = rep_offset1; rep_offset1 = 0; } } _start: step = stepSize; nextStep = ip0 + kStepIncr; ip1 = ip0 + 1; ip2 = ip0 + step; ip3 = ip2 + 1; if (ip3 >= ilimit) { goto _cleanup; } hash0 = ZSTD_hashPtr((void*)ip0, hlog, mls); hash1 = ZSTD_hashPtr((void*)ip1, hlog, mls); idx = hashTable[hash0]; do { uint rval = MEM_read32((void*)(ip2 - rep_offset1)); current0 = (uint)(ip0 - @base); hashTable[hash0] = current0; if (((MEM_read32((void*)ip2) == rval) && (rep_offset1 > 0))) { ip0 = ip2; match0 = ip0 - rep_offset1; mLength = ((ip0[-1] == match0[-1]) ? 1U : 0U); ip0 -= mLength; match0 -= mLength; offcode = 0; mLength += 4; goto _match; } if (idx >= prefixStartIndex) { mval = MEM_read32((void*)(@base + idx)); } else { mval = MEM_read32((void*)ip0) ^ 1; } if (MEM_read32((void*)ip0) == mval) { goto _offset; } idx = hashTable[hash1]; hash0 = hash1; hash1 = ZSTD_hashPtr((void*)ip2, hlog, mls); ip0 = ip1; ip1 = ip2; ip2 = ip3; current0 = (uint)(ip0 - @base); hashTable[hash0] = current0; if (idx >= prefixStartIndex) { mval = MEM_read32((void*)(@base + idx)); } else { mval = MEM_read32((void*)ip0) ^ 1; } if (MEM_read32((void*)ip0) == mval) { goto _offset; } idx = hashTable[hash1]; hash0 = hash1; hash1 = ZSTD_hashPtr((void*)ip2, hlog, mls); ip0 = ip1; ip1 = ip2; ip2 = ip0 + step; ip3 = ip1 + step; if (ip2 >= nextStep) { step++; Prefetch0((void*)(ip1 + 64)); Prefetch0((void*)(ip1 + 128)); nextStep += kStepIncr; } } while (ip3 < ilimit); _cleanup: rep[0] = rep_offset1 != 0 ? rep_offset1 : offsetSaved; rep[1] = rep_offset2 != 0 ? rep_offset2 : offsetSaved; return (nuint)(iend - anchor); _offset: match0 = @base + idx; rep_offset2 = rep_offset1; rep_offset1 = (uint)(ip0 - match0); offcode = rep_offset1 + (uint)((3 - 1)); mLength = 4; while ((((ip0 > anchor) && (match0 > prefixStart))) && (ip0[-1] == match0[-1])) { ip0--; match0--; mLength++; } _match: mLength += ZSTD_count(ip0 + mLength, match0 + mLength, iend); ZSTD_storeSeq(seqStore, (nuint)(ip0 - anchor), anchor, iend, offcode, mLength - 3); ip0 += mLength; anchor = ip0; if (ip1 < ip0) { hashTable[hash1] = (uint)(ip1 - @base); } if (ip0 <= ilimit) { assert(@base + current0 + 2 > istart); hashTable[ZSTD_hashPtr((void*)(@base + current0 + 2), hlog, mls)] = current0 + 2; hashTable[ZSTD_hashPtr((void*)(ip0 - 2), hlog, mls)] = (uint)(ip0 - 2 - @base); if (rep_offset2 > 0) { while ((ip0 <= ilimit) && (MEM_read32((void*)ip0) == MEM_read32((void*)(ip0 - rep_offset2)))) { nuint rLength = ZSTD_count(ip0 + 4, ip0 + 4 - rep_offset2, iend) + 4; { uint tmpOff = rep_offset2; rep_offset2 = rep_offset1; rep_offset1 = tmpOff; } hashTable[ZSTD_hashPtr((void*)ip0, hlog, mls)] = (uint)(ip0 - @base); ip0 += rLength; ZSTD_storeSeq(seqStore, 0, anchor, iend, 0, rLength - 3); anchor = ip0; continue; } } } goto _start; } private static nuint ZSTD_compressBlock_fast_noDict_4_1(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { return ZSTD_compressBlock_fast_noDict_generic(ms, seqStore, rep, src, srcSize, 4, 1); } private static nuint ZSTD_compressBlock_fast_noDict_5_1(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { return ZSTD_compressBlock_fast_noDict_generic(ms, seqStore, rep, src, srcSize, 5, 1); } private static nuint ZSTD_compressBlock_fast_noDict_6_1(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { return ZSTD_compressBlock_fast_noDict_generic(ms, seqStore, rep, src, srcSize, 6, 1); } private static nuint ZSTD_compressBlock_fast_noDict_7_1(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { return ZSTD_compressBlock_fast_noDict_generic(ms, seqStore, rep, src, srcSize, 7, 1); } private static nuint ZSTD_compressBlock_fast_noDict_4_0(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { return ZSTD_compressBlock_fast_noDict_generic(ms, seqStore, rep, src, srcSize, 4, 0); } private static nuint ZSTD_compressBlock_fast_noDict_5_0(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { return ZSTD_compressBlock_fast_noDict_generic(ms, seqStore, rep, src, srcSize, 5, 0); } private static nuint ZSTD_compressBlock_fast_noDict_6_0(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { return ZSTD_compressBlock_fast_noDict_generic(ms, seqStore, rep, src, srcSize, 6, 0); } private static nuint ZSTD_compressBlock_fast_noDict_7_0(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { return ZSTD_compressBlock_fast_noDict_generic(ms, seqStore, rep, src, srcSize, 7, 0); } public static nuint ZSTD_compressBlock_fast(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { uint mls = ms->cParams.minMatch; assert(ms->dictMatchState == null); if (ms->cParams.targetLength > 1) { switch (mls) { default: case 4: { return ZSTD_compressBlock_fast_noDict_4_1(ms, seqStore, rep, src, srcSize); } case 5: { return ZSTD_compressBlock_fast_noDict_5_1(ms, seqStore, rep, src, srcSize); } case 6: { return ZSTD_compressBlock_fast_noDict_6_1(ms, seqStore, rep, src, srcSize); } case 7: { return ZSTD_compressBlock_fast_noDict_7_1(ms, seqStore, rep, src, srcSize); } } } else { switch (mls) { default: case 4: { return ZSTD_compressBlock_fast_noDict_4_0(ms, seqStore, rep, src, srcSize); } case 5: { return ZSTD_compressBlock_fast_noDict_5_0(ms, seqStore, rep, src, srcSize); } case 6: { return ZSTD_compressBlock_fast_noDict_6_0(ms, seqStore, rep, src, srcSize); } case 7: { return ZSTD_compressBlock_fast_noDict_7_0(ms, seqStore, rep, src, srcSize); } } } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private static nuint ZSTD_compressBlock_fast_dictMatchState_generic(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize, uint mls, uint hasStep) { ZSTD_compressionParameters* cParams = &ms->cParams; uint* hashTable = ms->hashTable; uint hlog = cParams->hashLog; uint stepSize = cParams->targetLength + (uint)((cParams->targetLength) == 0 ? 1 : 0); byte* @base = ms->window.@base; byte* istart = (byte*)(src); byte* ip = istart; byte* anchor = istart; uint prefixStartIndex = ms->window.dictLimit; byte* prefixStart = @base + prefixStartIndex; byte* iend = istart + srcSize; byte* ilimit = iend - 8; uint offset_1 = rep[0], offset_2 = rep[1]; uint offsetSaved = 0; ZSTD_matchState_t* dms = ms->dictMatchState; ZSTD_compressionParameters* dictCParams = &dms->cParams; uint* dictHashTable = dms->hashTable; uint dictStartIndex = dms->window.dictLimit; byte* dictBase = dms->window.@base; byte* dictStart = dictBase + dictStartIndex; byte* dictEnd = dms->window.nextSrc; uint dictIndexDelta = prefixStartIndex - (uint)(dictEnd - dictBase); uint dictAndPrefixLength = (uint)(ip - prefixStart + dictEnd - dictStart); uint dictHLog = dictCParams->hashLog; uint maxDistance = 1U << (int)cParams->windowLog; uint endIndex = (uint)((nuint)(ip - @base) + srcSize); assert(endIndex - prefixStartIndex <= maxDistance); assert(prefixStartIndex >= (uint)(dictEnd - dictBase)); ip += ((dictAndPrefixLength == 0) ? 1 : 0); assert(offset_1 <= dictAndPrefixLength); assert(offset_2 <= dictAndPrefixLength); while (ip < ilimit) { nuint mLength; nuint h = ZSTD_hashPtr((void*)ip, hlog, mls); uint curr = (uint)(ip - @base); uint matchIndex = hashTable[h]; byte* match = @base + matchIndex; uint repIndex = curr + 1 - offset_1; byte* repMatch = (repIndex < prefixStartIndex) ? dictBase + (repIndex - dictIndexDelta) : @base + repIndex; hashTable[h] = curr; if (((uint)((prefixStartIndex - 1) - repIndex) >= 3) && (MEM_read32((void*)repMatch) == MEM_read32((void*)(ip + 1)))) { byte* repMatchEnd = repIndex < prefixStartIndex ? dictEnd : iend; mLength = ZSTD_count_2segments(ip + 1 + 4, repMatch + 4, iend, repMatchEnd, prefixStart) + 4; ip++; ZSTD_storeSeq(seqStore, (nuint)(ip - anchor), anchor, iend, 0, mLength - 3); } else if ((matchIndex <= prefixStartIndex)) { nuint dictHash = ZSTD_hashPtr((void*)ip, dictHLog, mls); uint dictMatchIndex = dictHashTable[dictHash]; byte* dictMatch = dictBase + dictMatchIndex; if (dictMatchIndex <= dictStartIndex || MEM_read32((void*)dictMatch) != MEM_read32((void*)ip)) { assert(stepSize >= 1); ip += (ulong)((ip - anchor) >> 8) + stepSize; continue; } else { uint offset = (uint)(curr - dictMatchIndex - dictIndexDelta); mLength = ZSTD_count_2segments(ip + 4, dictMatch + 4, iend, dictEnd, prefixStart) + 4; while ((((ip > anchor) && (dictMatch > dictStart))) && (ip[-1] == dictMatch[-1])) { ip--; dictMatch--; mLength++; } offset_2 = offset_1; offset_1 = offset; ZSTD_storeSeq(seqStore, (nuint)(ip - anchor), anchor, iend, offset + (uint)((3 - 1)), mLength - 3); } } else if (MEM_read32((void*)match) != MEM_read32((void*)ip)) { assert(stepSize >= 1); ip += (ulong)((ip - anchor) >> 8) + stepSize; continue; } else { uint offset = (uint)(ip - match); mLength = ZSTD_count(ip + 4, match + 4, iend) + 4; while ((((ip > anchor) && (match > prefixStart))) && (ip[-1] == match[-1])) { ip--; match--; mLength++; } offset_2 = offset_1; offset_1 = offset; ZSTD_storeSeq(seqStore, (nuint)(ip - anchor), anchor, iend, offset + (uint)((3 - 1)), mLength - 3); } ip += mLength; anchor = ip; if (ip <= ilimit) { assert(@base + curr + 2 > istart); hashTable[ZSTD_hashPtr((void*)(@base + curr + 2), hlog, mls)] = curr + 2; hashTable[ZSTD_hashPtr((void*)(ip - 2), hlog, mls)] = (uint)(ip - 2 - @base); while (ip <= ilimit) { uint current2 = (uint)(ip - @base); uint repIndex2 = current2 - offset_2; byte* repMatch2 = repIndex2 < prefixStartIndex ? dictBase - dictIndexDelta + repIndex2 : @base + repIndex2; if (((uint)((prefixStartIndex - 1) - (uint)(repIndex2)) >= 3) && (MEM_read32((void*)repMatch2) == MEM_read32((void*)ip))) { byte* repEnd2 = repIndex2 < prefixStartIndex ? dictEnd : iend; nuint repLength2 = ZSTD_count_2segments(ip + 4, repMatch2 + 4, iend, repEnd2, prefixStart) + 4; uint tmpOffset = offset_2; offset_2 = offset_1; offset_1 = tmpOffset; ZSTD_storeSeq(seqStore, 0, anchor, iend, 0, repLength2 - 3); hashTable[ZSTD_hashPtr((void*)ip, hlog, mls)] = current2; ip += repLength2; anchor = ip; continue; } break; } } } rep[0] = offset_1 != 0 ? offset_1 : offsetSaved; rep[1] = offset_2 != 0 ? offset_2 : offsetSaved; return (nuint)(iend - anchor); } private static nuint ZSTD_compressBlock_fast_dictMatchState_4_0(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { return ZSTD_compressBlock_fast_dictMatchState_generic(ms, seqStore, rep, src, srcSize, 4, 0); } private static nuint ZSTD_compressBlock_fast_dictMatchState_5_0(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { return ZSTD_compressBlock_fast_dictMatchState_generic(ms, seqStore, rep, src, srcSize, 5, 0); } private static nuint ZSTD_compressBlock_fast_dictMatchState_6_0(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { return ZSTD_compressBlock_fast_dictMatchState_generic(ms, seqStore, rep, src, srcSize, 6, 0); } private static nuint ZSTD_compressBlock_fast_dictMatchState_7_0(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { return ZSTD_compressBlock_fast_dictMatchState_generic(ms, seqStore, rep, src, srcSize, 7, 0); } public static nuint ZSTD_compressBlock_fast_dictMatchState(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { uint mls = ms->cParams.minMatch; assert(ms->dictMatchState != null); switch (mls) { default: case 4: { return ZSTD_compressBlock_fast_dictMatchState_4_0(ms, seqStore, rep, src, srcSize); } case 5: { return ZSTD_compressBlock_fast_dictMatchState_5_0(ms, seqStore, rep, src, srcSize); } case 6: { return ZSTD_compressBlock_fast_dictMatchState_6_0(ms, seqStore, rep, src, srcSize); } case 7: { return ZSTD_compressBlock_fast_dictMatchState_7_0(ms, seqStore, rep, src, srcSize); } } } private static nuint ZSTD_compressBlock_fast_extDict_generic(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize, uint mls, uint hasStep) { ZSTD_compressionParameters* cParams = &ms->cParams; uint* hashTable = ms->hashTable; uint hlog = cParams->hashLog; uint stepSize = cParams->targetLength + (uint)((cParams->targetLength) == 0 ? 1 : 0); byte* @base = ms->window.@base; byte* dictBase = ms->window.dictBase; byte* istart = (byte*)(src); byte* ip = istart; byte* anchor = istart; uint endIndex = (uint)((nuint)(istart - @base) + srcSize); uint lowLimit = ZSTD_getLowestMatchIndex(ms, endIndex, cParams->windowLog); uint dictStartIndex = lowLimit; byte* dictStart = dictBase + dictStartIndex; uint dictLimit = ms->window.dictLimit; uint prefixStartIndex = dictLimit < lowLimit ? lowLimit : dictLimit; byte* prefixStart = @base + prefixStartIndex; byte* dictEnd = dictBase + prefixStartIndex; byte* iend = istart + srcSize; byte* ilimit = iend - 8; uint offset_1 = rep[0], offset_2 = rep[1]; if (prefixStartIndex == dictStartIndex) { return ZSTD_compressBlock_fast(ms, seqStore, rep, src, srcSize); } while (ip < ilimit) { nuint h = ZSTD_hashPtr((void*)ip, hlog, mls); uint matchIndex = hashTable[h]; byte* matchBase = matchIndex < prefixStartIndex ? dictBase : @base; byte* match = matchBase + matchIndex; uint curr = (uint)(ip - @base); uint repIndex = curr + 1 - offset_1; byte* repBase = repIndex < prefixStartIndex ? dictBase : @base; byte* repMatch = repBase + repIndex; hashTable[h] = curr; if (((((uint)((prefixStartIndex - 1) - repIndex) >= 3) && (offset_1 <= curr + 1 - dictStartIndex))) && (MEM_read32((void*)repMatch) == MEM_read32((void*)(ip + 1)))) { byte* repMatchEnd = repIndex < prefixStartIndex ? dictEnd : iend; nuint rLength = ZSTD_count_2segments(ip + 1 + 4, repMatch + 4, iend, repMatchEnd, prefixStart) + 4; ip++; ZSTD_storeSeq(seqStore, (nuint)(ip - anchor), anchor, iend, 0, rLength - 3); ip += rLength; anchor = ip; } else { if ((matchIndex < dictStartIndex) || (MEM_read32((void*)match) != MEM_read32((void*)ip))) { assert(stepSize >= 1); ip += (ulong)((ip - anchor) >> 8) + stepSize; continue; } { byte* matchEnd = matchIndex < prefixStartIndex ? dictEnd : iend; byte* lowMatchPtr = matchIndex < prefixStartIndex ? dictStart : prefixStart; uint offset = curr - matchIndex; nuint mLength = ZSTD_count_2segments(ip + 4, match + 4, iend, matchEnd, prefixStart) + 4; while ((((ip > anchor) && (match > lowMatchPtr))) && (ip[-1] == match[-1])) { ip--; match--; mLength++; } offset_2 = offset_1; offset_1 = offset; ZSTD_storeSeq(seqStore, (nuint)(ip - anchor), anchor, iend, offset + (uint)((3 - 1)), mLength - 3); ip += mLength; anchor = ip; } } if (ip <= ilimit) { hashTable[ZSTD_hashPtr((void*)(@base + curr + 2), hlog, mls)] = curr + 2; hashTable[ZSTD_hashPtr((void*)(ip - 2), hlog, mls)] = (uint)(ip - 2 - @base); while (ip <= ilimit) { uint current2 = (uint)(ip - @base); uint repIndex2 = current2 - offset_2; byte* repMatch2 = repIndex2 < prefixStartIndex ? dictBase + repIndex2 : @base + repIndex2; if (((((uint)((prefixStartIndex - 1) - repIndex2) >= 3) && (offset_2 <= curr - dictStartIndex))) && (MEM_read32((void*)repMatch2) == MEM_read32((void*)ip))) { byte* repEnd2 = repIndex2 < prefixStartIndex ? dictEnd : iend; nuint repLength2 = ZSTD_count_2segments(ip + 4, repMatch2 + 4, iend, repEnd2, prefixStart) + 4; { uint tmpOffset = offset_2; offset_2 = offset_1; offset_1 = tmpOffset; } ZSTD_storeSeq(seqStore, 0, anchor, iend, 0, repLength2 - 3); hashTable[ZSTD_hashPtr((void*)ip, hlog, mls)] = current2; ip += repLength2; anchor = ip; continue; } break; } } } rep[0] = offset_1; rep[1] = offset_2; return (nuint)(iend - anchor); } private static nuint ZSTD_compressBlock_fast_extDict_4_0(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { return ZSTD_compressBlock_fast_extDict_generic(ms, seqStore, rep, src, srcSize, 4, 0); } private static nuint ZSTD_compressBlock_fast_extDict_5_0(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { return ZSTD_compressBlock_fast_extDict_generic(ms, seqStore, rep, src, srcSize, 5, 0); } private static nuint ZSTD_compressBlock_fast_extDict_6_0(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { return ZSTD_compressBlock_fast_extDict_generic(ms, seqStore, rep, src, srcSize, 6, 0); } private static nuint ZSTD_compressBlock_fast_extDict_7_0(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { return ZSTD_compressBlock_fast_extDict_generic(ms, seqStore, rep, src, srcSize, 7, 0); } public static nuint ZSTD_compressBlock_fast_extDict(ZSTD_matchState_t* ms, seqStore_t* seqStore, uint* rep, void* src, nuint srcSize) { uint mls = ms->cParams.minMatch; switch (mls) { default: case 4: { return ZSTD_compressBlock_fast_extDict_4_0(ms, seqStore, rep, src, srcSize); } case 5: { return ZSTD_compressBlock_fast_extDict_5_0(ms, seqStore, rep, src, srcSize); } case 6: { return ZSTD_compressBlock_fast_extDict_6_0(ms, seqStore, rep, src, srcSize); } case 7: { return ZSTD_compressBlock_fast_extDict_7_0(ms, seqStore, rep, src, srcSize); } } } } }
41.119363
181
0.476551
[ "MIT" ]
CHeavyarms/ZstdSharp
src/ZstdSharp/Unsafe/ZstdFast.cs
31,004
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Text; using Avalonia.Data.Converters; namespace WalletWasabi.Gui.Converters { public class ShouldDisplayValueConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (value is int integer && integer <= 0) { return false; } return true; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotSupportedException(); } } }
21.259259
97
0.745645
[ "MIT" ]
21isenough/WalletWasabi
WalletWasabi.Gui/Converters/ShouldDisplayValueConverter.cs
576
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using sanjigen.Engine.MathHelpers; namespace sanjigen.Engine { public class Camera { public Vector3 Position { get; set; } public Vector3 Target { get; set; } } }
19.3125
45
0.702265
[ "MIT" ]
azunyuuuuuuu/sanjigen
Engine/Camera.cs
311
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Network { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// ExpressRouteLinksOperations operations. /// </summary> internal partial class ExpressRouteLinksOperations : IServiceOperations<NetworkManagementClient>, IExpressRouteLinksOperations { /// <summary> /// Initializes a new instance of the ExpressRouteLinksOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ExpressRouteLinksOperations(NetworkManagementClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the NetworkManagementClient /// </summary> public NetworkManagementClient Client { get; private set; } /// <summary> /// Retrieves the specified ExpressRouteLink resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='expressRoutePortName'> /// The name of the ExpressRoutePort resource. /// </param> /// <param name='linkName'> /// The name of the ExpressRouteLink resource. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<ExpressRouteLink>> GetWithHttpMessagesAsync(string resourceGroupName, string expressRoutePortName, string linkName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (expressRoutePortName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "expressRoutePortName"); } if (linkName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "linkName"); } string apiVersion = "2021-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("expressRoutePortName", expressRoutePortName); tracingParameters.Add("linkName", linkName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}/links/{linkName}").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{expressRoutePortName}", System.Uri.EscapeDataString(expressRoutePortName)); _url = _url.Replace("{linkName}", System.Uri.EscapeDataString(linkName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<ExpressRouteLink>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<ExpressRouteLink>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve the ExpressRouteLink sub-resources of the specified /// ExpressRoutePort resource. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='expressRoutePortName'> /// The name of the ExpressRoutePort resource. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ExpressRouteLink>>> ListWithHttpMessagesAsync(string resourceGroupName, string expressRoutePortName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (expressRoutePortName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "expressRoutePortName"); } string apiVersion = "2021-03-01"; // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("apiVersion", apiVersion); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("expressRoutePortName", expressRoutePortName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/ExpressRoutePorts/{expressRoutePortName}/links").ToString(); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{expressRoutePortName}", System.Uri.EscapeDataString(expressRoutePortName)); List<string> _queryParameters = new List<string>(); if (apiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(apiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ExpressRouteLink>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteLink>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Retrieve the ExpressRouteLink sub-resources of the specified /// ExpressRoutePort resource. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<ExpressRouteLink>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<ExpressRouteLink>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<ExpressRouteLink>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
45.414673
285
0.565198
[ "MIT" ]
Cardsareus/azure-sdk-for-net
sdk/network/Microsoft.Azure.Management.Network/src/Generated/ExpressRouteLinksOperations.cs
28,475
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Text; using System.Xml.Schema; using System.Xml.XPath; using System.Diagnostics; using System.Globalization; using System.Collections; using System.Collections.Generic; using System.Runtime.Versioning; namespace System.Xml { internal delegate void CachingEventHandler(XsdCachingReader cachingReader); internal class AttributePSVIInfo { internal string localName; internal string namespaceUri; internal object typedAttributeValue; internal XmlSchemaInfo attributeSchemaInfo; internal AttributePSVIInfo() { attributeSchemaInfo = new XmlSchemaInfo(); } internal void Reset() { typedAttributeValue = null; localName = string.Empty; namespaceUri = string.Empty; attributeSchemaInfo.Clear(); } } internal partial class XsdValidatingReader : XmlReader, IXmlSchemaInfo, IXmlLineInfo, IXmlNamespaceResolver { private enum ValidatingReaderState { None = 0, Init = 1, Read = 2, OnDefaultAttribute = -1, OnReadAttributeValue = -2, OnAttribute = 3, ClearAttributes = 4, ParseInlineSchema = 5, ReadAhead = 6, OnReadBinaryContent = 7, ReaderClosed = 8, EOF = 9, Error = 10, } //Validation private XmlReader _coreReader; private readonly IXmlNamespaceResolver _coreReaderNSResolver; private readonly IXmlNamespaceResolver _thisNSResolver; private XmlSchemaValidator _validator; private readonly XmlResolver _xmlResolver; private readonly ValidationEventHandler _validationEvent; private ValidatingReaderState _validationState; private XmlValueGetter _valueGetter; // namespace management private readonly XmlNamespaceManager _nsManager; private readonly bool _manageNamespaces; private readonly bool _processInlineSchema; private bool _replayCache; //Current Node handling private ValidatingReaderNodeData _cachedNode; //Used to cache current node when looking ahead or default attributes private AttributePSVIInfo _attributePSVI; //Attributes private int _attributeCount; //Total count of attributes including default private int _coreReaderAttributeCount; private int _currentAttrIndex; private AttributePSVIInfo[] _attributePSVINodes; private ArrayList _defaultAttributes; //Inline Schema private Parser _inlineSchemaParser = null; //Typed Value & PSVI private object _atomicValue; private XmlSchemaInfo _xmlSchemaInfo; // original string of the atomic value private string _originalAtomicValueString; //cached coreReader information private readonly XmlNameTable _coreReaderNameTable; private XsdCachingReader _cachingReader; //ReadAttributeValue TextNode private ValidatingReaderNodeData _textNode; //To avoid SchemaNames creation private string _nsXmlNs; private string _nsXs; private string _nsXsi; private string _xsiType; private string _xsiNil; private string _xsdSchema; private string _xsiSchemaLocation; private string _xsiNoNamespaceSchemaLocation; //Underlying reader's IXmlLineInfo private IXmlLineInfo _lineInfo; // helpers for Read[Element]ContentAs{Base64,BinHex} methods private ReadContentAsBinaryHelper _readBinaryHelper; private ValidatingReaderState _savedState; //Constants private const int InitialAttributeCount = 8; private static volatile Type s_typeOfString; //Constructor internal XsdValidatingReader(XmlReader reader, XmlResolver xmlResolver, XmlReaderSettings readerSettings, XmlSchemaObject partialValidationType) { _coreReader = reader; _coreReaderNSResolver = reader as IXmlNamespaceResolver; _lineInfo = reader as IXmlLineInfo; _coreReaderNameTable = _coreReader.NameTable; if (_coreReaderNSResolver == null) { _nsManager = new XmlNamespaceManager(_coreReaderNameTable); _manageNamespaces = true; } _thisNSResolver = this as IXmlNamespaceResolver; _xmlResolver = xmlResolver; _processInlineSchema = (readerSettings.ValidationFlags & XmlSchemaValidationFlags.ProcessInlineSchema) != 0; Init(); SetupValidator(readerSettings, reader, partialValidationType); _validationEvent = readerSettings.GetEventHandler(); } internal XsdValidatingReader(XmlReader reader, XmlResolver xmlResolver, XmlReaderSettings readerSettings) : this(reader, xmlResolver, readerSettings, null) { } private void Init() { _validationState = ValidatingReaderState.Init; _defaultAttributes = new ArrayList(); _currentAttrIndex = -1; _attributePSVINodes = new AttributePSVIInfo[InitialAttributeCount]; _valueGetter = new XmlValueGetter(GetStringValue); s_typeOfString = typeof(string); _xmlSchemaInfo = new XmlSchemaInfo(); //Add common strings to be compared to NameTable _nsXmlNs = _coreReaderNameTable.Add(XmlReservedNs.NsXmlNs); _nsXs = _coreReaderNameTable.Add(XmlReservedNs.NsXs); _nsXsi = _coreReaderNameTable.Add(XmlReservedNs.NsXsi); _xsiType = _coreReaderNameTable.Add("type"); _xsiNil = _coreReaderNameTable.Add("nil"); _xsiSchemaLocation = _coreReaderNameTable.Add("schemaLocation"); _xsiNoNamespaceSchemaLocation = _coreReaderNameTable.Add("noNamespaceSchemaLocation"); _xsdSchema = _coreReaderNameTable.Add("schema"); } private void SetupValidator(XmlReaderSettings readerSettings, XmlReader reader, XmlSchemaObject partialValidationType) { _validator = new XmlSchemaValidator(_coreReaderNameTable, readerSettings.Schemas, _thisNSResolver, readerSettings.ValidationFlags); _validator.XmlResolver = _xmlResolver; _validator.SourceUri = XmlConvert.ToUri(reader.BaseURI); //Not using XmlResolver.ResolveUri as it checks for relative Uris,reader.BaseURI will be absolute file paths or string.Empty _validator.ValidationEventSender = this; _validator.ValidationEventHandler += readerSettings.GetEventHandler(); _validator.LineInfoProvider = _lineInfo; if (_validator.ProcessSchemaHints) { _validator.SchemaSet.ReaderSettings.DtdProcessing = readerSettings.DtdProcessing; } _validator.SetDtdSchemaInfo(reader.DtdInfo); if (partialValidationType != null) { _validator.Initialize(partialValidationType); } else { _validator.Initialize(); } } // Settings public override XmlReaderSettings Settings { get { XmlReaderSettings settings = _coreReader.Settings; if (null != settings) settings = settings.Clone(); if (settings == null) { settings = new XmlReaderSettings(); } settings.Schemas = _validator.SchemaSet; settings.ValidationType = ValidationType.Schema; settings.ValidationFlags = _validator.ValidationFlags; settings.ReadOnly = true; return settings; } } // Node Properties // Gets the type of the current node. public override XmlNodeType NodeType { get { if ((int)_validationState < 0) { return _cachedNode.NodeType; } else { XmlNodeType nodeType = _coreReader.NodeType; //Check for significant whitespace if (nodeType == XmlNodeType.Whitespace && (_validator.CurrentContentType == XmlSchemaContentType.TextOnly || _validator.CurrentContentType == XmlSchemaContentType.Mixed)) { return XmlNodeType.SignificantWhitespace; } return nodeType; } } } // Gets the name of the current node, including the namespace prefix. public override string Name { get { if (_validationState == ValidatingReaderState.OnDefaultAttribute) { string prefix = _validator.GetDefaultAttributePrefix(_cachedNode.Namespace); if (prefix != null && prefix.Length != 0) { return prefix + ":" + _cachedNode.LocalName; } return _cachedNode.LocalName; } return _coreReader.Name; } } // Gets the name of the current node without the namespace prefix. public override string LocalName { get { if ((int)_validationState < 0) { return _cachedNode.LocalName; } return _coreReader.LocalName; } } // Gets the namespace URN (as defined in the W3C Namespace Specification) of the current namespace scope. public override string NamespaceURI { get { if ((int)_validationState < 0) { return _cachedNode.Namespace; } return _coreReader.NamespaceURI; } } // Gets the namespace prefix associated with the current node. public override string Prefix { get { if ((int)_validationState < 0) { return _cachedNode.Prefix; } return _coreReader.Prefix; } } // Gets a value indicating whether the current node can have a non-empty Value public override bool HasValue { get { if ((int)_validationState < 0) { return true; } return _coreReader.HasValue; } } // Gets the text value of the current node. public override string Value { get { if ((int)_validationState < 0) { return _cachedNode.RawValue; } return _coreReader.Value; } } // Gets the depth of the current node in the XML element stack. public override int Depth { get { if ((int)_validationState < 0) { return _cachedNode.Depth; } return _coreReader.Depth; } } // Gets the base URI of the current node. public override string BaseURI { get { return _coreReader.BaseURI; } } // Gets a value indicating whether the current node is an empty element (for example, <MyElement/>). public override bool IsEmptyElement { get { return _coreReader.IsEmptyElement; } } // Gets a value indicating whether the current node is an attribute that was generated from the default value defined // in the DTD or schema. public override bool IsDefault { get { if (_validationState == ValidatingReaderState.OnDefaultAttribute) { //XSD default attributes return true; } return _coreReader.IsDefault; //This is DTD Default attribute } } // Gets the quotation mark character used to enclose the value of an attribute node. public override char QuoteChar { get { return _coreReader.QuoteChar; } } // Gets the current xml:space scope. public override XmlSpace XmlSpace { get { return _coreReader.XmlSpace; } } // Gets the current xml:lang scope. public override string XmlLang { get { return _coreReader.XmlLang; } } public override IXmlSchemaInfo SchemaInfo { get { return this as IXmlSchemaInfo; } } public override System.Type ValueType { get { switch (NodeType) { case XmlNodeType.Element: case XmlNodeType.EndElement: if (_xmlSchemaInfo.ContentType == XmlSchemaContentType.TextOnly) { return _xmlSchemaInfo.SchemaType.Datatype.ValueType; } goto default; case XmlNodeType.Attribute: if (_attributePSVI != null && AttributeSchemaInfo.ContentType == XmlSchemaContentType.TextOnly) { return AttributeSchemaInfo.SchemaType.Datatype.ValueType; } goto default; default: return s_typeOfString; } } } public override object ReadContentAsObject() { if (!CanReadContentAs(this.NodeType)) { throw CreateReadContentAsException(nameof(ReadContentAsObject)); } return InternalReadContentAsObject(true); } public override bool ReadContentAsBoolean() { if (!CanReadContentAs(this.NodeType)) { throw CreateReadContentAsException(nameof(ReadContentAsBoolean)); } object typedValue = InternalReadContentAsObject(); XmlSchemaType xmlType = NodeType == XmlNodeType.Attribute ? AttributeXmlType : ElementXmlType; try { if (xmlType != null) { return xmlType.ValueConverter.ToBoolean(typedValue); } else { return XmlUntypedConverter.Untyped.ToBoolean(typedValue); } } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Boolean", e, this as IXmlLineInfo); } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Boolean", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Boolean", e, this as IXmlLineInfo); } } public override DateTime ReadContentAsDateTime() { if (!CanReadContentAs(this.NodeType)) { throw CreateReadContentAsException(nameof(ReadContentAsDateTime)); } object typedValue = InternalReadContentAsObject(); XmlSchemaType xmlType = NodeType == XmlNodeType.Attribute ? AttributeXmlType : ElementXmlType; try { if (xmlType != null) { return xmlType.ValueConverter.ToDateTime(typedValue); } else { return XmlUntypedConverter.Untyped.ToDateTime(typedValue); } } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "DateTime", e, this as IXmlLineInfo); } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "DateTime", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "DateTime", e, this as IXmlLineInfo); } } public override double ReadContentAsDouble() { if (!CanReadContentAs(this.NodeType)) { throw CreateReadContentAsException(nameof(ReadContentAsDouble)); } object typedValue = InternalReadContentAsObject(); XmlSchemaType xmlType = NodeType == XmlNodeType.Attribute ? AttributeXmlType : ElementXmlType; try { if (xmlType != null) { return xmlType.ValueConverter.ToDouble(typedValue); } else { return XmlUntypedConverter.Untyped.ToDouble(typedValue); } } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Double", e, this as IXmlLineInfo); } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Double", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Double", e, this as IXmlLineInfo); } } public override float ReadContentAsFloat() { if (!CanReadContentAs(this.NodeType)) { throw CreateReadContentAsException(nameof(ReadContentAsFloat)); } object typedValue = InternalReadContentAsObject(); XmlSchemaType xmlType = NodeType == XmlNodeType.Attribute ? AttributeXmlType : ElementXmlType; try { if (xmlType != null) { return xmlType.ValueConverter.ToSingle(typedValue); } else { return XmlUntypedConverter.Untyped.ToSingle(typedValue); } } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Float", e, this as IXmlLineInfo); } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Float", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Float", e, this as IXmlLineInfo); } } public override decimal ReadContentAsDecimal() { if (!CanReadContentAs(this.NodeType)) { throw CreateReadContentAsException(nameof(ReadContentAsDecimal)); } object typedValue = InternalReadContentAsObject(); XmlSchemaType xmlType = NodeType == XmlNodeType.Attribute ? AttributeXmlType : ElementXmlType; try { if (xmlType != null) { return xmlType.ValueConverter.ToDecimal(typedValue); } else { return XmlUntypedConverter.Untyped.ToDecimal(typedValue); } } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Decimal", e, this as IXmlLineInfo); } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Decimal", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Decimal", e, this as IXmlLineInfo); } } public override int ReadContentAsInt() { if (!CanReadContentAs(this.NodeType)) { throw CreateReadContentAsException(nameof(ReadContentAsInt)); } object typedValue = InternalReadContentAsObject(); XmlSchemaType xmlType = NodeType == XmlNodeType.Attribute ? AttributeXmlType : ElementXmlType; try { if (xmlType != null) { return xmlType.ValueConverter.ToInt32(typedValue); } else { return XmlUntypedConverter.Untyped.ToInt32(typedValue); } } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Int", e, this as IXmlLineInfo); } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Int", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Int", e, this as IXmlLineInfo); } } public override long ReadContentAsLong() { if (!CanReadContentAs(this.NodeType)) { throw CreateReadContentAsException(nameof(ReadContentAsLong)); } object typedValue = InternalReadContentAsObject(); XmlSchemaType xmlType = NodeType == XmlNodeType.Attribute ? AttributeXmlType : ElementXmlType; try { if (xmlType != null) { return xmlType.ValueConverter.ToInt64(typedValue); } else { return XmlUntypedConverter.Untyped.ToInt64(typedValue); } } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Long", e, this as IXmlLineInfo); } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Long", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Long", e, this as IXmlLineInfo); } } public override string ReadContentAsString() { if (!CanReadContentAs(this.NodeType)) { throw CreateReadContentAsException(nameof(ReadContentAsString)); } object typedValue = InternalReadContentAsObject(); XmlSchemaType xmlType = NodeType == XmlNodeType.Attribute ? AttributeXmlType : ElementXmlType; try { if (xmlType != null) { return xmlType.ValueConverter.ToString(typedValue); } else { return typedValue as string; } } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo); } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo); } } public override object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) { if (!CanReadContentAs(this.NodeType)) { throw CreateReadContentAsException(nameof(ReadContentAs)); } string originalStringValue; object typedValue = InternalReadContentAsObject(false, out originalStringValue); XmlSchemaType xmlType = NodeType == XmlNodeType.Attribute ? AttributeXmlType : ElementXmlType; try { if (xmlType != null) { // special-case convertions to DateTimeOffset; typedValue is by default a DateTime // which cannot preserve time zone, so we need to convert from the original string if (returnType == typeof(DateTimeOffset) && xmlType.Datatype is Datatype_dateTimeBase) { typedValue = originalStringValue; } return xmlType.ValueConverter.ChangeType(typedValue, returnType); } else { return XmlUntypedConverter.Untyped.ChangeType(typedValue, returnType, namespaceResolver); } } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo); } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo); } } public override object ReadElementContentAsObject() { if (this.NodeType != XmlNodeType.Element) { throw CreateReadElementContentAsException(nameof(ReadElementContentAsObject)); } XmlSchemaType xmlType; return InternalReadElementContentAsObject(out xmlType, true); } public override bool ReadElementContentAsBoolean() { if (this.NodeType != XmlNodeType.Element) { throw CreateReadElementContentAsException(nameof(ReadElementContentAsBoolean)); } XmlSchemaType xmlType; object typedValue = InternalReadElementContentAsObject(out xmlType); try { if (xmlType != null) { return xmlType.ValueConverter.ToBoolean(typedValue); } else { return XmlUntypedConverter.Untyped.ToBoolean(typedValue); } } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Boolean", e, this as IXmlLineInfo); } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Boolean", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Boolean", e, this as IXmlLineInfo); } } public override DateTime ReadElementContentAsDateTime() { if (this.NodeType != XmlNodeType.Element) { throw CreateReadElementContentAsException(nameof(ReadElementContentAsDateTime)); } XmlSchemaType xmlType; object typedValue = InternalReadElementContentAsObject(out xmlType); try { if (xmlType != null) { return xmlType.ValueConverter.ToDateTime(typedValue); } else { return XmlUntypedConverter.Untyped.ToDateTime(typedValue); } } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "DateTime", e, this as IXmlLineInfo); } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "DateTime", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "DateTime", e, this as IXmlLineInfo); } } public override double ReadElementContentAsDouble() { if (this.NodeType != XmlNodeType.Element) { throw CreateReadElementContentAsException(nameof(ReadElementContentAsDouble)); } XmlSchemaType xmlType; object typedValue = InternalReadElementContentAsObject(out xmlType); try { if (xmlType != null) { return xmlType.ValueConverter.ToDouble(typedValue); } else { return XmlUntypedConverter.Untyped.ToDouble(typedValue); } } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Double", e, this as IXmlLineInfo); } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Double", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Double", e, this as IXmlLineInfo); } } public override float ReadElementContentAsFloat() { if (this.NodeType != XmlNodeType.Element) { throw CreateReadElementContentAsException(nameof(ReadElementContentAsFloat)); } XmlSchemaType xmlType; object typedValue = InternalReadElementContentAsObject(out xmlType); try { if (xmlType != null) { return xmlType.ValueConverter.ToSingle(typedValue); } else { return XmlUntypedConverter.Untyped.ToSingle(typedValue); } } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Float", e, this as IXmlLineInfo); } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Float", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Float", e, this as IXmlLineInfo); } } public override decimal ReadElementContentAsDecimal() { if (this.NodeType != XmlNodeType.Element) { throw CreateReadElementContentAsException(nameof(ReadElementContentAsDecimal)); } XmlSchemaType xmlType; object typedValue = InternalReadElementContentAsObject(out xmlType); try { if (xmlType != null) { return xmlType.ValueConverter.ToDecimal(typedValue); } else { return XmlUntypedConverter.Untyped.ToDecimal(typedValue); } } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Decimal", e, this as IXmlLineInfo); } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Decimal", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Decimal", e, this as IXmlLineInfo); } } public override int ReadElementContentAsInt() { if (this.NodeType != XmlNodeType.Element) { throw CreateReadElementContentAsException(nameof(ReadElementContentAsInt)); } XmlSchemaType xmlType; object typedValue = InternalReadElementContentAsObject(out xmlType); try { if (xmlType != null) { return xmlType.ValueConverter.ToInt32(typedValue); } else { return XmlUntypedConverter.Untyped.ToInt32(typedValue); } } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Int", e, this as IXmlLineInfo); } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Int", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Int", e, this as IXmlLineInfo); } } public override long ReadElementContentAsLong() { if (this.NodeType != XmlNodeType.Element) { throw CreateReadElementContentAsException(nameof(ReadElementContentAsLong)); } XmlSchemaType xmlType; object typedValue = InternalReadElementContentAsObject(out xmlType); try { if (xmlType != null) { return xmlType.ValueConverter.ToInt64(typedValue); } else { return XmlUntypedConverter.Untyped.ToInt64(typedValue); } } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Long", e, this as IXmlLineInfo); } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Long", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "Long", e, this as IXmlLineInfo); } } public override string ReadElementContentAsString() { if (this.NodeType != XmlNodeType.Element) { throw CreateReadElementContentAsException(nameof(ReadElementContentAsString)); } XmlSchemaType xmlType; object typedValue = InternalReadElementContentAsObject(out xmlType); try { if (xmlType != null && typedValue != null) { return xmlType.ValueConverter.ToString(typedValue); } else { return typedValue as string ?? string.Empty; } } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo); } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, "String", e, this as IXmlLineInfo); } } public override object ReadElementContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) { if (this.NodeType != XmlNodeType.Element) { throw CreateReadElementContentAsException(nameof(ReadElementContentAs)); } XmlSchemaType xmlType; string originalStringValue; object typedValue = InternalReadElementContentAsObject(out xmlType, false, out originalStringValue); try { if (xmlType != null) { // special-case convertions to DateTimeOffset; typedValue is by default a DateTime // which cannot preserve time zone, so we need to convert from the original string if (returnType == typeof(DateTimeOffset) && xmlType.Datatype is Datatype_dateTimeBase) { typedValue = originalStringValue; } return xmlType.ValueConverter.ChangeType(typedValue, returnType, namespaceResolver); } else { return XmlUntypedConverter.Untyped.ChangeType(typedValue, returnType, namespaceResolver); } } catch (FormatException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo); } catch (InvalidCastException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo); } catch (OverflowException e) { throw new XmlException(SR.Xml_ReadContentAsFormatException, returnType.ToString(), e, this as IXmlLineInfo); } } // Attribute Accessors // The number of attributes on the current node. public override int AttributeCount { get { return _attributeCount; } } // Gets the value of the attribute with the specified Name. public override string GetAttribute(string name) { string attValue = _coreReader.GetAttribute(name); if (attValue == null && _attributeCount > 0) { //Could be default attribute ValidatingReaderNodeData defaultNode = GetDefaultAttribute(name, false); if (defaultNode != null) { //Default found attValue = defaultNode.RawValue; } } return attValue; } // Gets the value of the attribute with the specified LocalName and NamespaceURI. public override string GetAttribute(string name, string namespaceURI) { string attValue = _coreReader.GetAttribute(name, namespaceURI); if (attValue == null && _attributeCount > 0) { //Could be default attribute namespaceURI = (namespaceURI == null) ? string.Empty : _coreReaderNameTable.Get(namespaceURI); name = _coreReaderNameTable.Get(name); if (name == null || namespaceURI == null) { //Attribute not present since we did not see it return null; } ValidatingReaderNodeData attNode = GetDefaultAttribute(name, namespaceURI, false); if (attNode != null) { return attNode.RawValue; } } return attValue; } // Gets the value of the attribute with the specified index. public override string GetAttribute(int i) { if (_attributeCount == 0) { return null; } if (i < _coreReaderAttributeCount) { return _coreReader.GetAttribute(i); } else { int defaultIndex = i - _coreReaderAttributeCount; ValidatingReaderNodeData attNode = (ValidatingReaderNodeData)_defaultAttributes[defaultIndex]; Debug.Assert(attNode != null); return attNode.RawValue; } } // Moves to the attribute with the specified Name public override bool MoveToAttribute(string name) { if (_coreReader.MoveToAttribute(name)) { _validationState = ValidatingReaderState.OnAttribute; _attributePSVI = GetAttributePSVI(name); goto Found; } else if (_attributeCount > 0) { //Default attribute ValidatingReaderNodeData defaultNode = GetDefaultAttribute(name, true); if (defaultNode != null) { _validationState = ValidatingReaderState.OnDefaultAttribute; _attributePSVI = defaultNode.AttInfo; _cachedNode = defaultNode; goto Found; } } return false; Found: if (_validationState == ValidatingReaderState.OnReadBinaryContent) { _readBinaryHelper.Finish(); _validationState = _savedState; } return true; } // Moves to the attribute with the specified LocalName and NamespaceURI public override bool MoveToAttribute(string name, string ns) { //Check atomized local name and ns name = _coreReaderNameTable.Get(name); ns = ns != null ? _coreReaderNameTable.Get(ns) : string.Empty; if (name == null || ns == null) { //Name or ns not found in the nameTable, then attribute is not found return false; } if (_coreReader.MoveToAttribute(name, ns)) { _validationState = ValidatingReaderState.OnAttribute; if (_inlineSchemaParser == null) { _attributePSVI = GetAttributePSVI(name, ns); Debug.Assert(_attributePSVI != null); } else { //Parsing inline schema, no PSVI for schema attributes _attributePSVI = null; } goto Found; } else { //Default attribute ValidatingReaderNodeData defaultNode = GetDefaultAttribute(name, ns, true); if (defaultNode != null) { _attributePSVI = defaultNode.AttInfo; _cachedNode = defaultNode; _validationState = ValidatingReaderState.OnDefaultAttribute; goto Found; } } return false; Found: if (_validationState == ValidatingReaderState.OnReadBinaryContent) { _readBinaryHelper.Finish(); _validationState = _savedState; } return true; } // Moves to the attribute with the specified index public override void MoveToAttribute(int i) { if (i < 0 || i >= _attributeCount) { throw new ArgumentOutOfRangeException(nameof(i)); } _currentAttrIndex = i; if (i < _coreReaderAttributeCount) { //reader attribute _coreReader.MoveToAttribute(i); if (_inlineSchemaParser == null) { _attributePSVI = _attributePSVINodes[i]; } else { _attributePSVI = null; } _validationState = ValidatingReaderState.OnAttribute; } else { //default attribute int defaultIndex = i - _coreReaderAttributeCount; _cachedNode = (ValidatingReaderNodeData)_defaultAttributes[defaultIndex]; _attributePSVI = _cachedNode.AttInfo; _validationState = ValidatingReaderState.OnDefaultAttribute; } if (_validationState == ValidatingReaderState.OnReadBinaryContent) { _readBinaryHelper.Finish(); _validationState = _savedState; } } // Moves to the first attribute. public override bool MoveToFirstAttribute() { if (_coreReader.MoveToFirstAttribute()) { _currentAttrIndex = 0; if (_inlineSchemaParser == null) { _attributePSVI = _attributePSVINodes[0]; } else { _attributePSVI = null; } _validationState = ValidatingReaderState.OnAttribute; goto Found; } else if (_defaultAttributes.Count > 0) { //check for default _cachedNode = (ValidatingReaderNodeData)_defaultAttributes[0]; _attributePSVI = _cachedNode.AttInfo; _currentAttrIndex = 0; _validationState = ValidatingReaderState.OnDefaultAttribute; goto Found; } return false; Found: if (_validationState == ValidatingReaderState.OnReadBinaryContent) { _readBinaryHelper.Finish(); _validationState = _savedState; } return true; } // Moves to the next attribute. public override bool MoveToNextAttribute() { if (_currentAttrIndex + 1 < _coreReaderAttributeCount) { bool moveTo = _coreReader.MoveToNextAttribute(); Debug.Assert(moveTo); _currentAttrIndex++; if (_inlineSchemaParser == null) { _attributePSVI = _attributePSVINodes[_currentAttrIndex]; } else { _attributePSVI = null; } _validationState = ValidatingReaderState.OnAttribute; goto Found; } else if (_currentAttrIndex + 1 < _attributeCount) { //default attribute int defaultIndex = ++_currentAttrIndex - _coreReaderAttributeCount; _cachedNode = (ValidatingReaderNodeData)_defaultAttributes[defaultIndex]; _attributePSVI = _cachedNode.AttInfo; _validationState = ValidatingReaderState.OnDefaultAttribute; goto Found; } return false; Found: if (_validationState == ValidatingReaderState.OnReadBinaryContent) { _readBinaryHelper.Finish(); _validationState = _savedState; } return true; } // Moves to the element that contains the current attribute node. public override bool MoveToElement() { if (_coreReader.MoveToElement() || (int)_validationState < 0) { //states OnDefaultAttribute or OnReadAttributeValue _currentAttrIndex = -1; _validationState = ValidatingReaderState.ClearAttributes; return true; } return false; } // Reads the next node from the stream/TextReader. public override bool Read() { switch (_validationState) { case ValidatingReaderState.Read: if (_coreReader.Read()) { ProcessReaderEvent(); return true; } else { _validator.EndValidation(); if (_coreReader.EOF) { _validationState = ValidatingReaderState.EOF; } return false; } case ValidatingReaderState.ParseInlineSchema: ProcessInlineSchema(); return true; case ValidatingReaderState.OnAttribute: case ValidatingReaderState.OnDefaultAttribute: case ValidatingReaderState.ClearAttributes: case ValidatingReaderState.OnReadAttributeValue: ClearAttributesInfo(); if (_inlineSchemaParser != null) { _validationState = ValidatingReaderState.ParseInlineSchema; goto case ValidatingReaderState.ParseInlineSchema; } else { _validationState = ValidatingReaderState.Read; goto case ValidatingReaderState.Read; } case ValidatingReaderState.ReadAhead: //Will enter here on calling Skip() ClearAttributesInfo(); ProcessReaderEvent(); _validationState = ValidatingReaderState.Read; return true; case ValidatingReaderState.OnReadBinaryContent: _validationState = _savedState; _readBinaryHelper.Finish(); return Read(); case ValidatingReaderState.Init: _validationState = ValidatingReaderState.Read; if (_coreReader.ReadState == ReadState.Interactive) { //If the underlying reader is already positioned on a ndoe, process it ProcessReaderEvent(); return true; } else { goto case ValidatingReaderState.Read; } case ValidatingReaderState.ReaderClosed: case ValidatingReaderState.EOF: return false; default: return false; } } // Gets a value indicating whether XmlReader is positioned at the end of the stream/TextReader. public override bool EOF { get { return _coreReader.EOF; } } // Closes the stream, changes the ReadState to Closed, and sets all the properties back to zero. public override void Close() { _coreReader.Close(); _validationState = ValidatingReaderState.ReaderClosed; } // Returns the read state of the XmlReader. public override ReadState ReadState { get { return (_validationState == ValidatingReaderState.Init) ? ReadState.Initial : _coreReader.ReadState; } } // Skips to the end tag of the current element. public override void Skip() { int startDepth = Depth; switch (NodeType) { case XmlNodeType.Element: if (_coreReader.IsEmptyElement) { break; } bool callSkipToEndElem = true; //If union and unionValue has been parsed till EndElement, then validator.ValidateEndElement has been called //Hence should not call SkipToEndElement as the current context has already been popped in the validator if ((_xmlSchemaInfo.IsUnionType || _xmlSchemaInfo.IsDefault) && _coreReader is XsdCachingReader) { callSkipToEndElem = false; } _coreReader.Skip(); _validationState = ValidatingReaderState.ReadAhead; if (callSkipToEndElem) { _validator.SkipToEndElement(_xmlSchemaInfo); } break; case XmlNodeType.Attribute: MoveToElement(); goto case XmlNodeType.Element; } //For all other NodeTypes Skip() same as Read() Read(); return; } // Gets the XmlNameTable associated with this implementation. public override XmlNameTable NameTable { get { return _coreReaderNameTable; } } // Resolves a namespace prefix in the current element's scope. public override string LookupNamespace(string prefix) { return _thisNSResolver.LookupNamespace(prefix); } // Resolves the entity reference for nodes of NodeType EntityReference. public override void ResolveEntity() { throw new InvalidOperationException(); } // Parses the attribute value into one or more Text and/or EntityReference node types. public override bool ReadAttributeValue() { if (_validationState == ValidatingReaderState.OnReadBinaryContent) { _readBinaryHelper.Finish(); _validationState = _savedState; } if (NodeType == XmlNodeType.Attribute) { if (_validationState == ValidatingReaderState.OnDefaultAttribute) { _cachedNode = CreateDummyTextNode(_cachedNode.RawValue, _cachedNode.Depth + 1); _validationState = ValidatingReaderState.OnReadAttributeValue; return true; } return _coreReader.ReadAttributeValue(); } return false; } public override bool CanReadBinaryContent { get { return true; } } public override int ReadContentAsBase64(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return 0; } // init ReadContentAsBinaryHelper when called first time if (_validationState != ValidatingReaderState.OnReadBinaryContent) { _readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this); _savedState = _validationState; } // restore original state in order to have a normal Read() behavior when called from readBinaryHelper _validationState = _savedState; // call to the helper int readCount = _readBinaryHelper.ReadContentAsBase64(buffer, index, count); // set OnReadBinaryContent state again and return _savedState = _validationState; _validationState = ValidatingReaderState.OnReadBinaryContent; return readCount; } public override int ReadContentAsBinHex(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return 0; } // init ReadContentAsBinaryHelper when called first time if (_validationState != ValidatingReaderState.OnReadBinaryContent) { _readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this); _savedState = _validationState; } // restore original state in order to have a normal Read() behavior when called from readBinaryHelper _validationState = _savedState; // call to the helper int readCount = _readBinaryHelper.ReadContentAsBinHex(buffer, index, count); // set OnReadBinaryContent state again and return _savedState = _validationState; _validationState = ValidatingReaderState.OnReadBinaryContent; return readCount; } public override int ReadElementContentAsBase64(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return 0; } // init ReadContentAsBinaryHelper when called first time if (_validationState != ValidatingReaderState.OnReadBinaryContent) { _readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this); _savedState = _validationState; } // restore original state in order to have a normal Read() behavior when called from readBinaryHelper _validationState = _savedState; // call to the helper int readCount = _readBinaryHelper.ReadElementContentAsBase64(buffer, index, count); // set OnReadBinaryContent state again and return _savedState = _validationState; _validationState = ValidatingReaderState.OnReadBinaryContent; return readCount; } public override int ReadElementContentAsBinHex(byte[] buffer, int index, int count) { if (ReadState != ReadState.Interactive) { return 0; } // init ReadContentAsBinaryHelper when called first time if (_validationState != ValidatingReaderState.OnReadBinaryContent) { _readBinaryHelper = ReadContentAsBinaryHelper.CreateOrReset(_readBinaryHelper, this); _savedState = _validationState; } // restore original state in order to have a normal Read() behavior when called from readBinaryHelper _validationState = _savedState; // call to the helper int readCount = _readBinaryHelper.ReadElementContentAsBinHex(buffer, index, count); // set OnReadBinaryContent state again and return _savedState = _validationState; _validationState = ValidatingReaderState.OnReadBinaryContent; return readCount; } // // IXmlSchemaInfo interface // bool IXmlSchemaInfo.IsDefault { get { switch (NodeType) { case XmlNodeType.Element: if (!_coreReader.IsEmptyElement) { GetIsDefault(); } return _xmlSchemaInfo.IsDefault; case XmlNodeType.EndElement: return _xmlSchemaInfo.IsDefault; case XmlNodeType.Attribute: if (_attributePSVI != null) { return AttributeSchemaInfo.IsDefault; } break; default: break; } return false; } } bool IXmlSchemaInfo.IsNil { get { switch (NodeType) { case XmlNodeType.Element: case XmlNodeType.EndElement: return _xmlSchemaInfo.IsNil; default: break; } return false; } } XmlSchemaValidity IXmlSchemaInfo.Validity { get { switch (NodeType) { case XmlNodeType.Element: if (_coreReader.IsEmptyElement) { return _xmlSchemaInfo.Validity; } if (_xmlSchemaInfo.Validity == XmlSchemaValidity.Valid) { //It might be valid for unions since we read ahead, but report notknown for consistency return XmlSchemaValidity.NotKnown; } return _xmlSchemaInfo.Validity; case XmlNodeType.EndElement: return _xmlSchemaInfo.Validity; case XmlNodeType.Attribute: if (_attributePSVI != null) { return AttributeSchemaInfo.Validity; } break; } return XmlSchemaValidity.NotKnown; } } XmlSchemaSimpleType IXmlSchemaInfo.MemberType { get { switch (NodeType) { case XmlNodeType.Element: if (!_coreReader.IsEmptyElement) { GetMemberType(); } return _xmlSchemaInfo.MemberType; case XmlNodeType.EndElement: return _xmlSchemaInfo.MemberType; case XmlNodeType.Attribute: if (_attributePSVI != null) { return AttributeSchemaInfo.MemberType; } return null; default: return null; //Text, PI, Comment etc } } } XmlSchemaType IXmlSchemaInfo.SchemaType { get { switch (NodeType) { case XmlNodeType.Element: case XmlNodeType.EndElement: return _xmlSchemaInfo.SchemaType; case XmlNodeType.Attribute: if (_attributePSVI != null) { return AttributeSchemaInfo.SchemaType; } return null; default: return null; //Text, PI, Comment etc } } } XmlSchemaElement IXmlSchemaInfo.SchemaElement { get { if (NodeType == XmlNodeType.Element || NodeType == XmlNodeType.EndElement) { return _xmlSchemaInfo.SchemaElement; } return null; } } XmlSchemaAttribute IXmlSchemaInfo.SchemaAttribute { get { if (NodeType == XmlNodeType.Attribute) { if (_attributePSVI != null) { return AttributeSchemaInfo.SchemaAttribute; } } return null; } } // // IXmlLineInfo members // public bool HasLineInfo() { return true; } public int LineNumber { get { if (_lineInfo != null) { return _lineInfo.LineNumber; } return 0; } } public int LinePosition { get { if (_lineInfo != null) { return _lineInfo.LinePosition; } return 0; } } // // IXmlNamespaceResolver members // IDictionary<string, string> IXmlNamespaceResolver.GetNamespacesInScope(XmlNamespaceScope scope) { if (_coreReaderNSResolver != null) { return _coreReaderNSResolver.GetNamespacesInScope(scope); } else { return _nsManager.GetNamespacesInScope(scope); } } string IXmlNamespaceResolver.LookupNamespace(string prefix) { if (_coreReaderNSResolver != null) { return _coreReaderNSResolver.LookupNamespace(prefix); } else { return _nsManager.LookupNamespace(prefix); } } string IXmlNamespaceResolver.LookupPrefix(string namespaceName) { if (_coreReaderNSResolver != null) { return _coreReaderNSResolver.LookupPrefix(namespaceName); } else { return _nsManager.LookupPrefix(namespaceName); } } //Internal / Private methods private object GetStringValue() { return _coreReader.Value; } private XmlSchemaType ElementXmlType { get { return _xmlSchemaInfo.XmlType; } } private XmlSchemaType AttributeXmlType { get { if (_attributePSVI != null) { return AttributeSchemaInfo.XmlType; } return null; } } private XmlSchemaInfo AttributeSchemaInfo { get { Debug.Assert(_attributePSVI != null); return _attributePSVI.attributeSchemaInfo; } } private void ProcessReaderEvent() { if (_replayCache) { //if in replay mode, do nothing since nodes have been validated already //If NodeType == XmlNodeType.EndElement && if manageNamespaces, may need to pop namespace scope, since scope is not popped in ReadAheadForMemberType return; } switch (_coreReader.NodeType) { case XmlNodeType.Element: ProcessElementEvent(); break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: _validator.ValidateWhitespace(GetStringValue); break; case XmlNodeType.Text: // text inside a node case XmlNodeType.CDATA: // <![CDATA[...]]> _validator.ValidateText(GetStringValue); break; case XmlNodeType.EndElement: ProcessEndElementEvent(); break; case XmlNodeType.EntityReference: throw new InvalidOperationException(); case XmlNodeType.DocumentType: #if TEMP_HACK_FOR_SCHEMA_INFO validator.SetDtdSchemaInfo((SchemaInfo)coreReader.DtdInfo); #else _validator.SetDtdSchemaInfo(_coreReader.DtdInfo); #endif break; default: break; } } private void ProcessElementEvent() { if (_processInlineSchema && IsXSDRoot(_coreReader.LocalName, _coreReader.NamespaceURI) && _coreReader.Depth > 0) { _xmlSchemaInfo.Clear(); _attributeCount = _coreReaderAttributeCount = _coreReader.AttributeCount; if (!_coreReader.IsEmptyElement) { //If its not empty schema, then parse else ignore _inlineSchemaParser = new Parser(SchemaType.XSD, _coreReaderNameTable, _validator.SchemaSet.GetSchemaNames(_coreReaderNameTable), _validationEvent); _inlineSchemaParser.StartParsing(_coreReader, null); _inlineSchemaParser.ParseReaderNode(); _validationState = ValidatingReaderState.ParseInlineSchema; } else { _validationState = ValidatingReaderState.ClearAttributes; } } else { //Validate element //Clear previous data _atomicValue = null; _originalAtomicValueString = null; _xmlSchemaInfo.Clear(); if (_manageNamespaces) { _nsManager.PushScope(); } //Find Xsi attributes that need to be processed before validating the element string xsiSchemaLocation = null; string xsiNoNamespaceSL = null; string xsiNil = null; string xsiType = null; if (_coreReader.MoveToFirstAttribute()) { do { string objectNs = _coreReader.NamespaceURI; string objectName = _coreReader.LocalName; if (Ref.Equal(objectNs, _nsXsi)) { if (Ref.Equal(objectName, _xsiSchemaLocation)) { xsiSchemaLocation = _coreReader.Value; } else if (Ref.Equal(objectName, _xsiNoNamespaceSchemaLocation)) { xsiNoNamespaceSL = _coreReader.Value; } else if (Ref.Equal(objectName, _xsiType)) { xsiType = _coreReader.Value; } else if (Ref.Equal(objectName, _xsiNil)) { xsiNil = _coreReader.Value; } } if (_manageNamespaces && Ref.Equal(_coreReader.NamespaceURI, _nsXmlNs)) { _nsManager.AddNamespace(_coreReader.Prefix.Length == 0 ? string.Empty : _coreReader.LocalName, _coreReader.Value); } } while (_coreReader.MoveToNextAttribute()); _coreReader.MoveToElement(); } _validator.ValidateElement(_coreReader.LocalName, _coreReader.NamespaceURI, _xmlSchemaInfo, xsiType, xsiNil, xsiSchemaLocation, xsiNoNamespaceSL); ValidateAttributes(); _validator.ValidateEndOfAttributes(_xmlSchemaInfo); if (_coreReader.IsEmptyElement) { ProcessEndElementEvent(); } _validationState = ValidatingReaderState.ClearAttributes; } } private void ProcessEndElementEvent() { _atomicValue = _validator.ValidateEndElement(_xmlSchemaInfo); _originalAtomicValueString = GetOriginalAtomicValueStringOfElement(); if (_xmlSchemaInfo.IsDefault) { //The atomicValue returned is a default value Debug.Assert(_atomicValue != null); int depth = _coreReader.Depth; _coreReader = GetCachingReader(); _cachingReader.RecordTextNode(_xmlSchemaInfo.XmlType.ValueConverter.ToString(_atomicValue), _originalAtomicValueString, depth + 1, 0, 0); _cachingReader.RecordEndElementNode(); _cachingReader.SetToReplayMode(); _replayCache = true; } else if (_manageNamespaces) { _nsManager.PopScope(); } } private void ValidateAttributes() { _attributeCount = _coreReaderAttributeCount = _coreReader.AttributeCount; AttributePSVIInfo attributePSVI; int attIndex = 0; bool attributeInvalid = false; if (_coreReader.MoveToFirstAttribute()) { do { string localName = _coreReader.LocalName; string ns = _coreReader.NamespaceURI; attributePSVI = AddAttributePSVI(attIndex); attributePSVI.localName = localName; attributePSVI.namespaceUri = ns; if ((object)ns == (object)_nsXmlNs) { attIndex++; continue; } attributePSVI.typedAttributeValue = _validator.ValidateAttribute(localName, ns, _valueGetter, attributePSVI.attributeSchemaInfo); if (!attributeInvalid) { attributeInvalid = attributePSVI.attributeSchemaInfo.Validity == XmlSchemaValidity.Invalid; } attIndex++; } while (_coreReader.MoveToNextAttribute()); } _coreReader.MoveToElement(); if (attributeInvalid) { //If any of the attributes are invalid, Need to report element's validity as invalid _xmlSchemaInfo.Validity = XmlSchemaValidity.Invalid; } _validator.GetUnspecifiedDefaultAttributes(_defaultAttributes, true); _attributeCount += _defaultAttributes.Count; } private void ClearAttributesInfo() { _attributeCount = 0; _coreReaderAttributeCount = 0; _currentAttrIndex = -1; _defaultAttributes.Clear(); _attributePSVI = null; } private AttributePSVIInfo GetAttributePSVI(string name) { if (_inlineSchemaParser != null) { //Parsing inline schema, no PSVI for schema attributes return null; } string attrLocalName; string attrPrefix; string ns; ValidateNames.SplitQName(name, out attrPrefix, out attrLocalName); attrPrefix = _coreReaderNameTable.Add(attrPrefix); attrLocalName = _coreReaderNameTable.Add(attrLocalName); if (attrPrefix.Length == 0) { //empty prefix, not qualified ns = string.Empty; } else { ns = _thisNSResolver.LookupNamespace(attrPrefix); } return GetAttributePSVI(attrLocalName, ns); } private AttributePSVIInfo GetAttributePSVI(string localName, string ns) { Debug.Assert(_coreReaderNameTable.Get(localName) != null); Debug.Assert(_coreReaderNameTable.Get(ns) != null); AttributePSVIInfo attInfo = null; for (int i = 0; i < _coreReaderAttributeCount; i++) { attInfo = _attributePSVINodes[i]; if (attInfo != null) { //Will be null for invalid attributes if (Ref.Equal(localName, attInfo.localName) && Ref.Equal(ns, attInfo.namespaceUri)) { _currentAttrIndex = i; return attInfo; } } } return null; } private ValidatingReaderNodeData GetDefaultAttribute(string name, bool updatePosition) { string attrLocalName; string attrPrefix; ValidateNames.SplitQName(name, out attrPrefix, out attrLocalName); //Atomize attrPrefix = _coreReaderNameTable.Add(attrPrefix); attrLocalName = _coreReaderNameTable.Add(attrLocalName); string ns; if (attrPrefix.Length == 0) { ns = string.Empty; } else { ns = _thisNSResolver.LookupNamespace(attrPrefix); } return GetDefaultAttribute(attrLocalName, ns, updatePosition); } private ValidatingReaderNodeData GetDefaultAttribute(string attrLocalName, string ns, bool updatePosition) { Debug.Assert(_coreReaderNameTable.Get(attrLocalName) != null); Debug.Assert(_coreReaderNameTable.Get(ns) != null); ValidatingReaderNodeData defaultNode = null; for (int i = 0; i < _defaultAttributes.Count; i++) { defaultNode = (ValidatingReaderNodeData)_defaultAttributes[i]; if (Ref.Equal(defaultNode.LocalName, attrLocalName) && Ref.Equal(defaultNode.Namespace, ns)) { if (updatePosition) { _currentAttrIndex = _coreReader.AttributeCount + i; } return defaultNode; } } return null; } private AttributePSVIInfo AddAttributePSVI(int attIndex) { Debug.Assert(attIndex <= _attributePSVINodes.Length); AttributePSVIInfo attInfo = _attributePSVINodes[attIndex]; if (attInfo != null) { attInfo.Reset(); return attInfo; } if (attIndex >= _attributePSVINodes.Length - 1) { //reached capacity of PSVIInfo array, Need to increase capacity to twice the initial AttributePSVIInfo[] newPSVINodes = new AttributePSVIInfo[_attributePSVINodes.Length * 2]; Array.Copy(_attributePSVINodes, 0, newPSVINodes, 0, _attributePSVINodes.Length); _attributePSVINodes = newPSVINodes; } attInfo = _attributePSVINodes[attIndex]; if (attInfo == null) { attInfo = new AttributePSVIInfo(); _attributePSVINodes[attIndex] = attInfo; } return attInfo; } private bool IsXSDRoot(string localName, string ns) { return Ref.Equal(ns, _nsXs) && Ref.Equal(localName, _xsdSchema); } private void ProcessInlineSchema() { Debug.Assert(_inlineSchemaParser != null); if (_coreReader.Read()) { if (_coreReader.NodeType == XmlNodeType.Element) { _attributeCount = _coreReaderAttributeCount = _coreReader.AttributeCount; } else { //Clear attributes info if nodeType is not element ClearAttributesInfo(); } if (!_inlineSchemaParser.ParseReaderNode()) { _inlineSchemaParser.FinishParsing(); XmlSchema schema = _inlineSchemaParser.XmlSchema; _validator.AddSchema(schema); _inlineSchemaParser = null; _validationState = ValidatingReaderState.Read; } } } private object InternalReadContentAsObject() { return InternalReadContentAsObject(false); } private object InternalReadContentAsObject(bool unwrapTypedValue) { string str; return InternalReadContentAsObject(unwrapTypedValue, out str); } private object InternalReadContentAsObject(bool unwrapTypedValue, out string originalStringValue) { XmlNodeType nodeType = this.NodeType; if (nodeType == XmlNodeType.Attribute) { originalStringValue = this.Value; if (_attributePSVI != null && _attributePSVI.typedAttributeValue != null) { if (_validationState == ValidatingReaderState.OnDefaultAttribute) { XmlSchemaAttribute schemaAttr = _attributePSVI.attributeSchemaInfo.SchemaAttribute; originalStringValue = (schemaAttr.DefaultValue != null) ? schemaAttr.DefaultValue : schemaAttr.FixedValue; } return ReturnBoxedValue(_attributePSVI.typedAttributeValue, AttributeSchemaInfo.XmlType, unwrapTypedValue); } else { //return string value return this.Value; } } else if (nodeType == XmlNodeType.EndElement) { if (_atomicValue != null) { originalStringValue = _originalAtomicValueString; return _atomicValue; } else { originalStringValue = string.Empty; return string.Empty; } } else { //Positioned on text, CDATA, PI, Comment etc if (_validator.CurrentContentType == XmlSchemaContentType.TextOnly) { //if current element is of simple type object value = ReturnBoxedValue(ReadTillEndElement(), _xmlSchemaInfo.XmlType, unwrapTypedValue); originalStringValue = _originalAtomicValueString; return value; } else { XsdCachingReader cachingReader = _coreReader as XsdCachingReader; if (cachingReader != null) { originalStringValue = cachingReader.ReadOriginalContentAsString(); } else { originalStringValue = InternalReadContentAsString(); } return originalStringValue; } } } private object InternalReadElementContentAsObject(out XmlSchemaType xmlType) { return InternalReadElementContentAsObject(out xmlType, false); } private object InternalReadElementContentAsObject(out XmlSchemaType xmlType, bool unwrapTypedValue) { string tmpString; return InternalReadElementContentAsObject(out xmlType, unwrapTypedValue, out tmpString); } private object InternalReadElementContentAsObject(out XmlSchemaType xmlType, bool unwrapTypedValue, out string originalString) { Debug.Assert(this.NodeType == XmlNodeType.Element); object typedValue = null; xmlType = null; //If its an empty element, can have default/fixed value if (this.IsEmptyElement) { if (_xmlSchemaInfo.ContentType == XmlSchemaContentType.TextOnly) { typedValue = ReturnBoxedValue(_atomicValue, _xmlSchemaInfo.XmlType, unwrapTypedValue); } else { typedValue = _atomicValue; } originalString = _originalAtomicValueString; xmlType = ElementXmlType; //Set this for default values this.Read(); return typedValue; } // move to content and read typed value this.Read(); if (this.NodeType == XmlNodeType.EndElement) { //If IsDefault is true, the next node will be EndElement if (_xmlSchemaInfo.IsDefault) { if (_xmlSchemaInfo.ContentType == XmlSchemaContentType.TextOnly) { typedValue = ReturnBoxedValue(_atomicValue, _xmlSchemaInfo.XmlType, unwrapTypedValue); } else { //anyType has default value typedValue = _atomicValue; } originalString = _originalAtomicValueString; } else { //Empty content typedValue = string.Empty; originalString = string.Empty; } } else if (this.NodeType == XmlNodeType.Element) { //the first child is again element node throw new XmlException(SR.Xml_MixedReadElementContentAs, string.Empty, this as IXmlLineInfo); } else { typedValue = InternalReadContentAsObject(unwrapTypedValue, out originalString); // ReadElementContentAsXXX cannot be called on mixed content, if positioned on node other than EndElement, Error if (this.NodeType != XmlNodeType.EndElement) { throw new XmlException(SR.Xml_MixedReadElementContentAs, string.Empty, this as IXmlLineInfo); } } xmlType = ElementXmlType; //Set this as we are moving ahead to the next node // move to next node this.Read(); return typedValue; } private object ReadTillEndElement() { if (_atomicValue == null) { while (_coreReader.Read()) { if (_replayCache) { //If replaying nodes in the cache, they have already been validated continue; } switch (_coreReader.NodeType) { case XmlNodeType.Element: ProcessReaderEvent(); goto breakWhile; case XmlNodeType.Text: case XmlNodeType.CDATA: _validator.ValidateText(GetStringValue); break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: _validator.ValidateWhitespace(GetStringValue); break; case XmlNodeType.Comment: case XmlNodeType.ProcessingInstruction: break; case XmlNodeType.EndElement: _atomicValue = _validator.ValidateEndElement(_xmlSchemaInfo); _originalAtomicValueString = GetOriginalAtomicValueStringOfElement(); if (_manageNamespaces) { _nsManager.PopScope(); } goto breakWhile; } continue; breakWhile: break; } } else { //atomicValue != null, meaning already read ahead - Switch reader if (_atomicValue == this) { //switch back invalid marker; dont need it since coreReader moved to endElement _atomicValue = null; } SwitchReader(); } return _atomicValue; } private void SwitchReader() { XsdCachingReader cachingReader = _coreReader as XsdCachingReader; if (cachingReader != null) { //Switch back without going over the cached contents again. _coreReader = cachingReader.GetCoreReader(); } Debug.Assert(_coreReader.NodeType == XmlNodeType.EndElement); _replayCache = false; } private void ReadAheadForMemberType() { while (_coreReader.Read()) { switch (_coreReader.NodeType) { case XmlNodeType.Element: Debug.Fail("Should not happen as the caching reader does not cache elements in simple content"); break; case XmlNodeType.Text: case XmlNodeType.CDATA: _validator.ValidateText(GetStringValue); break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: _validator.ValidateWhitespace(GetStringValue); break; case XmlNodeType.Comment: case XmlNodeType.ProcessingInstruction: break; case XmlNodeType.EndElement: _atomicValue = _validator.ValidateEndElement(_xmlSchemaInfo); //?? pop namespaceManager scope _originalAtomicValueString = GetOriginalAtomicValueStringOfElement(); if (_atomicValue == null) { //Invalid marker _atomicValue = this; } else if (_xmlSchemaInfo.IsDefault) { //The atomicValue returned is a default value _cachingReader.SwitchTextNodeAndEndElement(_xmlSchemaInfo.XmlType.ValueConverter.ToString(_atomicValue), _originalAtomicValueString); } goto breakWhile; } continue; breakWhile: break; } } private void GetIsDefault() { XsdCachingReader cachedReader = _coreReader as XsdCachingReader; if (cachedReader == null && _xmlSchemaInfo.HasDefaultValue) { //Get Isdefault _coreReader = GetCachingReader(); if (_xmlSchemaInfo.IsUnionType && !_xmlSchemaInfo.IsNil) { //If it also union, get the memberType as well ReadAheadForMemberType(); } else { if (_coreReader.Read()) { switch (_coreReader.NodeType) { case XmlNodeType.Element: Debug.Fail("Should not happen as the caching reader does not cache elements in simple content"); break; case XmlNodeType.Text: case XmlNodeType.CDATA: _validator.ValidateText(GetStringValue); break; case XmlNodeType.Whitespace: case XmlNodeType.SignificantWhitespace: _validator.ValidateWhitespace(GetStringValue); break; case XmlNodeType.Comment: case XmlNodeType.ProcessingInstruction: break; case XmlNodeType.EndElement: _atomicValue = _validator.ValidateEndElement(_xmlSchemaInfo); //?? pop namespaceManager scope _originalAtomicValueString = GetOriginalAtomicValueStringOfElement(); if (_xmlSchemaInfo.IsDefault) { //The atomicValue returned is a default value _cachingReader.SwitchTextNodeAndEndElement(_xmlSchemaInfo.XmlType.ValueConverter.ToString(_atomicValue), _originalAtomicValueString); } break; default: break; } } } _cachingReader.SetToReplayMode(); _replayCache = true; } } private void GetMemberType() { if (_xmlSchemaInfo.MemberType != null || _atomicValue == this) { return; } XsdCachingReader cachedReader = _coreReader as XsdCachingReader; if (cachedReader == null && _xmlSchemaInfo.IsUnionType && !_xmlSchemaInfo.IsNil) { _coreReader = GetCachingReader(); ReadAheadForMemberType(); _cachingReader.SetToReplayMode(); _replayCache = true; } } private object ReturnBoxedValue(object typedValue, XmlSchemaType xmlType, bool unWrap) { if (typedValue != null) { if (unWrap) { //convert XmlAtomicValue[] to object[] for list of unions; The other cases return typed value of the valueType anyway Debug.Assert(xmlType != null && xmlType.Datatype != null); if (xmlType.Datatype.Variety == XmlSchemaDatatypeVariety.List) { Datatype_List listType = xmlType.Datatype as Datatype_List; if (listType.ItemType.Variety == XmlSchemaDatatypeVariety.Union) { typedValue = xmlType.ValueConverter.ChangeType(typedValue, xmlType.Datatype.ValueType, _thisNSResolver); } } } return typedValue; } else { //return the original string value of the element or attribute Debug.Assert(NodeType != XmlNodeType.Attribute); typedValue = _validator.GetConcatenatedValue(); } return typedValue; } private XsdCachingReader GetCachingReader() { if (_cachingReader == null) { _cachingReader = new XsdCachingReader(_coreReader, _lineInfo, new CachingEventHandler(CachingCallBack)); } else { _cachingReader.Reset(_coreReader); } _lineInfo = _cachingReader as IXmlLineInfo; return _cachingReader; } internal ValidatingReaderNodeData CreateDummyTextNode(string attributeValue, int depth) { if (_textNode == null) { _textNode = new ValidatingReaderNodeData(XmlNodeType.Text); } _textNode.Depth = depth; _textNode.RawValue = attributeValue; return _textNode; } internal void CachingCallBack(XsdCachingReader cachingReader) { _coreReader = cachingReader.GetCoreReader(); //re-switch the core-reader after caching reader is done _lineInfo = cachingReader.GetLineInfo(); _replayCache = false; } private string GetOriginalAtomicValueStringOfElement() { if (_xmlSchemaInfo.IsDefault) { XmlSchemaElement schemaElem = _xmlSchemaInfo.SchemaElement; if (schemaElem != null) { return (schemaElem.DefaultValue != null) ? schemaElem.DefaultValue : schemaElem.FixedValue; } } else { return _validator.GetConcatenatedValue(); } return string.Empty; } } }
36.736782
193
0.520206
[ "MIT" ]
939481896/dotnet-corefx
src/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs
96,581
C#
using System; using System.Collections.Generic; using System.Threading; using Cosmos.TestRunner.Core; namespace Cosmos.TestRunner.UI { partial class MainWindowHandler { private Thread TestEngineThread = null; public void RunTestEngine() { TestEngineThread = new Thread(TestEngineThreadMain); TestEngineThread.Start(); } private void TestEngineThreadMain() { var xEngine = new Engine(); DefaultEngineConfiguration.Apply(xEngine); var xOutputXml = new OutputHandlerXml(); xEngine.OutputHandler = new MultiplexingOutputHandler( xOutputXml, this); xEngine.Execute(); } } }
23.71875
66
0.604743
[ "BSD-3-Clause" ]
mmkhmmkh/Cosmos
Tests/Cosmos.TestRunner.UI/MainWindowHandler.TestEngine.cs
761
C#
/* * The MIT License (MIT) * Copyright (c) Arturo Rodriguez All rights reserved. * 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.Collections.Generic; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Extensions.DependencyInjection; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Authentication.AzureADB2C.UI; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; // Lets Encrypt using Certes; using FluffySpoon.AspNet.LetsEncrypt; using FluffySpoon.AspNet.LetsEncrypt.Certes; using FluffySpoon.AspNet.LetsEncrypt.Persistence; using System.Security.Cryptography.X509Certificates; // Identity Server 4 using IdentityModel; using IdentityServer4; using IdentityServer4.Models; using IdentityServer4.Stores; using IdentityServer4.AccessTokenValidation; using IdentityServer4.Services; using CoFlows.Server.IdentityServer; using CoFlows.Server.Realtime; using NLog; namespace CoFlows.Server { public class Certificate { public string Key { get; set; } public string Data { get; set; } } public class Challenge { public string Token { get; set; } public string Response { get; set; } public string Domains { get; set; } } public class Startup<T> { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var logger = LogManager.GetCurrentClassLogger(); services.AddCors(options => { options.AddPolicy("AllowAllOrigins", builder => { builder.AllowAnyOrigin(); }); }); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(); // Register the Swagger generator, defining 1 or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Version = "v1", Title = "CoFlows Community Edition", Description = "CoFlows CE (Community Edition) is a Containerized Polyglot Runtime that simplifies the development, hosting and deployment of powerful data-centric workflows. CoFlows enables developers to create rich Web-APIs with almost zero boiler plate and scheduled / reactive processes through a range of languages including CoreCLR (C#, F# and VB), JVM (Java and Scala), Python and Javascript. Furthermore, functions written in any of these languages can call each other within the same process with full interop.", TermsOfService = new Uri("https://github.com/CoFlows/CoFlows-CE#license"), Contact = new OpenApiContact { Name = "CoFlows Community", Email = "arturo@coflows.com", Url = new Uri("https://www.coflows.com"), }, License = new OpenApiLicense { Name = "Use under MIT", Url = new Uri("https://github.com/CoFlows/CoFlows-CE#license"), } }); var filePath = System.IO.Path.Combine(System.AppContext.BaseDirectory, "CoFlows.Server.lnx.xml"); c.IncludeXmlComments(filePath); }); services .AddMvc(option => option.EnableEndpointRouting = false) .AddNewtonsoftJson(options => { options.SerializerSettings.ContractResolver = new Newtonsoft.Json.Serialization.DefaultContractResolver(); options.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented; }); services.Configure<ForwardedHeadersOptions>(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; }); if(Program.config["Server"]["OAuth"] != null && Program.config["Server"]["OAuth"]["AzureAdB2C"] != null) { services .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = "coflows-ce", ValidAudience = "coflows-ce", IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Program.jwtKey)) }; }) .AddAzureADB2CBearer(options => { options.Instance = Program.config["Server"]["OAuth"]["AzureAdB2C"]["Instance"].ToString(); options.ClientId = Program.config["Server"]["OAuth"]["AzureAdB2C"]["ClientId"].ToString(); options.Domain = Program.config["Server"]["OAuth"]["AzureAdB2C"]["Domain"].ToString(); options.SignUpSignInPolicyId = Program.config["Server"]["OAuth"]["AzureAdB2C"]["SignUpSignInPolicyId"].ToString(); }); services.AddAuthorization(options => { var defaultAuthorizationPolicyBuilder = new Microsoft.AspNetCore.Authorization.AuthorizationPolicyBuilder( JwtBearerDefaults.AuthenticationScheme, AzureADB2CDefaults.BearerAuthenticationScheme) .RequireAuthenticatedUser(); options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build(); }); } // else // { // services // .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) // .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options => // { // options.TokenValidationParameters = new TokenValidationParameters // { // ValidateIssuer = true, // ValidateAudience = true, // ValidateLifetime = true, // ValidateIssuerSigningKey = true, // ValidIssuer = "coflows-ce", // ValidAudience = "coflows-ce", // IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(Program.jwtKey)) // }; // }); // } services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); services.AddSingleton<RTDSocketManager>(); if(Program.hostName.ToLower() != "localhost" && !string.IsNullOrWhiteSpace(Program.letsEncryptEmail)) { services.AddFluffySpoonLetsEncrypt(new LetsEncryptOptions() { Email = Program.letsEncryptEmail, UseStaging = Program.letsEncryptStaging, Domains = new[] { Program.hostName }, TimeUntilExpiryBeforeRenewal = TimeSpan.FromDays(30), CertificateSigningRequest = new CsrInfo() { CountryName = "Multiverse", Locality = "Universe", Organization = "GetStuffDone", OrganizationUnit = "ImportantStuffDone", State = "MilkyWay" } }); services.AddFluffySpoonLetsEncryptCertificatePersistence( async (key, bytes) => { var mKey = "---LetsEncrypt--" + Program.hostName + "." + Program.letsEncryptEmail + "." + (Program.letsEncryptStaging ? "Staging" : "Production") + ".certificate_" + key; var m = QuantApp.Kernel.M.Base(mKey); var resList = m[x => QuantApp.Kernel.M.V<string>(x, "Key") == key.ToString()]; if(resList != null && resList.Count > 0) { var strData = System.Convert.ToBase64String(bytes); m.Exchange(resList[0], new Certificate(){ Key = key.ToString(), Data = strData }); logger.Info("LetsEncrypt certificate UPDATED..."); } else { var strData = System.Convert.ToBase64String(bytes); m += new Certificate(){ Key = key.ToString(), Data = strData }; logger.Info("LetsEncrypt certificate CREATED..."); } m.Save(); }, async (key) => { var mKey = "---LetsEncrypt--" + Program.hostName + "." + Program.letsEncryptEmail + "." + (Program.letsEncryptStaging ? "Staging" : "Production") + ".certificate_" + key; try { var m = QuantApp.Kernel.M.Base(mKey); var resList = m[x => QuantApp.Kernel.M.V<string>(x, "Key") == key.ToString()]; if(resList != null && resList.Count > 0) { var data = QuantApp.Kernel.M.V<string>(resList[0], "Data"); var bytes = System.Convert.FromBase64String(data); logger.Info("LetsEncrypt found certificate..."); return bytes; } logger.Info("LetsEncrypt didn't find a certificate, attempting to create one..."); return null; } catch (System.Exception e) { return null; } }); services.AddFluffySpoonLetsEncryptFileChallengePersistence(); } SetIdentityServer4(services, GetCertificate()); } private ECDsaSecurityKey GetCertificate(int count = 0) { var logger = LogManager.GetCurrentClassLogger(); var sslFlag = CoFlows.Server.Program.hostName.ToLower() != "localhost" && !string.IsNullOrWhiteSpace(CoFlows.Server.Program.letsEncryptEmail); if(!sslFlag && Program.hostName.ToLower() != "localhost") return null; var throwExction = false; try { var mKey = "---LetsEncrypt--" + Program.hostName + "." + Program.letsEncryptEmail + "." + (Program.letsEncryptStaging ? "Staging" : "Production") + ".certificate_" + CertificateType.Site; var m = QuantApp.Kernel.M.Base(mKey); var resList = m[x => QuantApp.Kernel.M.V<string>(x, "Key") == CertificateType.Site.ToString()]; if(resList != null && resList.Count > 0) { var data = QuantApp.Kernel.M.V<string>(resList[0], "Data"); var bytes = System.Convert.FromBase64String(data); X509Certificate2 x509 = new X509Certificate2(bytes, nameof(FluffySpoon)); var mess = "\n------------------------------------\n"; mess += "Subject: " + x509.Subject + "\n"; mess += "Issuer: " + x509.Issuer + "\n"; mess += "Version: " + x509.Version + "\n"; mess += "Valid Date: " + x509.NotBefore + "\n"; mess += "Expiry Date: " + x509.NotAfter + "\n"; mess += "Thumbprint: " + x509.Thumbprint + "\n"; mess += "Serial Number: " + x509.SerialNumber + "\n"; mess += "Friendly Name: " + x509.PublicKey.Oid.FriendlyName + "\n"; mess += "Public Key Format: " + x509.PublicKey.EncodedKeyValue.Format(true) + "\n"; mess += "Raw Data Length: " + x509.RawData.Length + "\n"; mess += "Certificate to string: " + x509.ToString(true) + "\n"; mess += "------------------------------------"; logger.Debug(mess); var ecdsa = x509.GetECDsaPrivateKey(); var securityKey = new ECDsaSecurityKey(ecdsa) { KeyId = CryptoRandom.CreateUniqueId(16, CryptoRandom.OutputFormat.Hex) }; return securityKey; } else { throwExction = true; } return null; } catch(Exception e) { logger.Error(e); if(throwExction) { // Wait 30sec before throwing an exception to restart the server. // This should leave enough time for LetsEncrypt to issue a new certificate and save. System.Threading.Thread.Sleep(1000 * 30); if(count < 2) return GetCertificate(count++); } return null; } } private void SetIdentityServer4(IServiceCollection services, ECDsaSecurityKey certificate) { IEnumerable<ApiResource> Apis = new List<ApiResource> { new ApiResource("resourceapi", "Resource API") { Scopes = {new Scope("api.read")} } }; IEnumerable<Client> Clients = new List<Client> { new Client { ClientId = "jwt_token", ClientName = "JWT Token", AccessTokenLifetime = 60 * 60 * 24, AllowedGrantTypes = GrantTypes.ResourceOwnerPassword, RequireClientSecret = false, AllowAccessTokensViaBrowser = true, AllowedScopes = new List<string> { "resourceapi" } } }; if(certificate == null) services.AddIdentityServer() .AddDeveloperSigningCredential() .AddInMemoryApiResources(Apis) .AddInMemoryClients(Clients) .AddCustomUserStore(); else { services.AddIdentityServer() .AddSigningCredential(certificate, "ES256") .AddInMemoryApiResources(Apis) .AddInMemoryClients(Clients) .AddCustomUserStore(); } var sslFlag = CoFlows.Server.Program.hostName.ToLower() != "localhost" && !string.IsNullOrWhiteSpace(CoFlows.Server.Program.letsEncryptEmail); var hostName = (sslFlag ? "https://" : "http://") + CoFlows.Server.Program.hostName.ToLower(); services.AddAuthorization(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddIdentityServerAuthentication( options => { options.Authority = hostName; options.ApiName = "resourceapi"; options.RequireHttpsMetadata = false; }); services.AddSingleton<ICorsPolicyService>((container) => { var logger = container.GetRequiredService<ILogger<DefaultCorsPolicyService>>(); return new DefaultCorsPolicyService(logger) { AllowAll = true }; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. // public void Configure(IApplicationBuilder app, IHostingEnvironment env) public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.Use(async (httpContext, next) => { httpContext.Response.Headers[Microsoft.Net.Http.Headers.HeaderNames.CacheControl] = "no-cache"; await next(); }); if(Program.hostName.ToLower() != "localhost" && !string.IsNullOrWhiteSpace(Program.letsEncryptEmail)) { app.UseFluffySpoonLetsEncrypt(); if(!Program.letsEncryptStaging) app.UseHsts(); app.UseHttpsRedirection(); } app.UseForwardedHeaders(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "CoFlows API V1"); }); app.UseStatusCodePagesWithReExecute("/"); app.UseDefaultFiles(); app.UseStaticFiles(); app.UseCors(x => x .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader() ); app.UseWebSockets(); app.UseMiddleware<T>(); // Identity Server 4 app.UseIdentityServer(); app.UseAuthentication(); app.UseMvc(); } } }
45.890951
540
0.525203
[ "MIT" ]
CoFlows-Quant/CoFlows-Quant
CoFlows.Server/Startup.cs
19,781
C#
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace CookieAuthenticationAndValidation.Controllers { public class HomeController : Controller { [AllowAnonymous] public IActionResult Index() { return View(); } [Authorize(Roles = "NoSuchRoleExists")] public IActionResult FailAuthorization() { return View(); } [Authorize] public IActionResult MustBeAuthenticated() { return View(); } } }
20.962963
55
0.588339
[ "Apache-2.0" ]
blowdart/devIntersectionEurope2016
src/CookieAuthenticationAndValidation/Controllers/HomeController.cs
568
C#
using System; using System.ComponentModel; namespace Nuclear.TestSite.TestSuites.Base { #pragma warning disable CS1591 // Missing XML comment for publicly visible type or member [EditorBrowsable(EditorBrowsableState.Never)] public class TestSuite { #region methods [EditorBrowsable(EditorBrowsableState.Never)] public override Boolean Equals(Object obj) => throw new MethodAccessException("This method is currently out of order."); [EditorBrowsable(EditorBrowsableState.Never)] public override Int32 GetHashCode() => throw new MethodAccessException("This method is currently out of order."); [EditorBrowsable(EditorBrowsableState.Never)] public override String ToString() => throw new MethodAccessException("This method is currently out of order."); [EditorBrowsable(EditorBrowsableState.Never)] public new Type GetType() => throw new MethodAccessException("This method is currently out of order."); #endregion } #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member }
36.933333
128
0.736462
[ "MIT" ]
MikeLimaSierra/Nuclear.TestSite
src/Nuclear.TestSite/TestSuites/Base/TestSuite.cs
1,110
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Globalization; /// <summary> /// Clone /// </summary> public class DateTimeFormatInfoClone { #region Public Methods public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; return retVal; } #region Positive Test Cases public bool PosTest1() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest1: Call Clone method on a instance created from Ctor"); try { DateTimeFormatInfo expected = new DateTimeFormatInfo(); retVal = VerificationHelper(expected, expected.Clone(), "001.1") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("001.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest2: Call Clone method on a instance created from several cultures"); try { DateTimeFormatInfo expected = new CultureInfo("en-us").DateTimeFormat; retVal = VerificationHelper(expected, expected.Clone(), "002.1") && retVal; expected = new CultureInfo("fr-FR").DateTimeFormat; retVal = VerificationHelper(expected, expected.Clone(), "002.2") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } public bool PosTest3() { bool retVal = true; TestLibrary.TestFramework.BeginScenario("PosTest3: Call Clone method on a readonly instance created from several cultures"); try { DateTimeFormatInfo expected = CultureInfo.InvariantCulture.DateTimeFormat; retVal = VerificationHelper(expected, expected.Clone(), "003.1") && retVal; } catch (Exception e) { TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e); TestLibrary.TestFramework.LogInformation(e.StackTrace); retVal = false; } return retVal; } #endregion #endregion public static int Main() { DateTimeFormatInfoClone test = new DateTimeFormatInfoClone(); TestLibrary.TestFramework.BeginTestCase("DateTimeFormatInfoClone"); if (test.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } #region Private Methods private bool VerificationHelper(DateTimeFormatInfo expected, Object obj, string errorno) { bool retval = true; if (!(obj is DateTimeFormatInfo)) { TestLibrary.TestFramework.LogError(errorno + ".1", "Calling Clone method does not return an DateTimeFormatInfo copy"); retval = false; } DateTimeFormatInfo actual = obj as DateTimeFormatInfo; if ( actual.IsReadOnly ) { TestLibrary.TestFramework.LogError(errorno + ".2", "Calling Clone method makes DateTimeFormatInfo copy read only"); retval = false; } retval = IsEquals(actual.AbbreviatedDayNames, expected.AbbreviatedDayNames, errorno + ".3") && IsEquals(actual.AbbreviatedMonthGenitiveNames, expected.AbbreviatedMonthGenitiveNames, errorno + ".4") && IsEquals(actual.AbbreviatedMonthNames, expected.AbbreviatedMonthNames, errorno + ".5") && IsEquals(actual.DayNames, expected.DayNames, errorno + ".6") && IsEquals(actual.MonthGenitiveNames, expected.MonthGenitiveNames, errorno + ".7") && IsEquals(actual.MonthNames, expected.MonthNames, errorno + ".8") && IsEquals(actual.ShortestDayNames, expected.ShortestDayNames, errorno + ".9") && IsEquals(actual.AMDesignator, expected.AMDesignator, errorno + ".10") && //DateTimeFormatInfo.DateSeparator property has been removed IsEquals(actual.FullDateTimePattern, expected.FullDateTimePattern, errorno + ".12") && IsEquals(actual.LongDatePattern, expected.LongDatePattern, errorno + ".13") && IsEquals(actual.LongTimePattern, expected.LongTimePattern, errorno + ".14") && IsEquals(actual.MonthDayPattern, expected.MonthDayPattern, errorno + ".15") && IsEquals(actual.PMDesignator, expected.PMDesignator, errorno + ".17") && IsEquals(actual.RFC1123Pattern, expected.RFC1123Pattern, errorno + ".18") && IsEquals(actual.ShortDatePattern, expected.ShortDatePattern, errorno + ".19") && IsEquals(actual.ShortTimePattern, expected.ShortTimePattern, errorno + ".20") && IsEquals(actual.SortableDateTimePattern, expected.SortableDateTimePattern, errorno + ".21") && //DateTimeFormatInfo.TimeSeparator property has been removed IsEquals(actual.UniversalSortableDateTimePattern, expected.UniversalSortableDateTimePattern, errorno + ".23") && IsEquals(actual.YearMonthPattern, expected.YearMonthPattern, errorno + ".24") && IsEquals(actual.CalendarWeekRule, expected.CalendarWeekRule, errorno + ".25") && IsEquals(actual.FirstDayOfWeek, expected.FirstDayOfWeek, errorno + ".26") && retval; return retval; } private bool IsEquals(string str1, string str2, string errorno) { bool retVal = true; if (str1 != str2) { TestLibrary.TestFramework.LogError(errorno, "Two string are not equal"); TestLibrary.TestFramework.LogInformation("WARNING[LOCAL VARIABLES] str1 = " + str1 + ", str2 = " + str2); retVal = false; } return retVal; } private bool IsEquals(DayOfWeek value1, DayOfWeek value2, string errorno) { bool retVal = true; if (value1 != value2) { TestLibrary.TestFramework.LogError(errorno, "Two values are not equal"); TestLibrary.TestFramework.LogInformation("WARNING[LOCAL VARIABLES] value1 = " + value1 + ", value2 = " + value2); retVal = false; } return retVal; } private bool IsEquals(CalendarWeekRule value1, CalendarWeekRule value2, string errorno) { bool retVal = true; if (value1 != value2) { TestLibrary.TestFramework.LogError(errorno, "Two values are not equal"); TestLibrary.TestFramework.LogInformation("WARNING[LOCAL VARIABLES] value1 = " + value1 + ", value2 = " + value2); retVal = false; } return retVal; } private bool IsEquals(string[] array1, string[] array2, string errorno) { bool retval = true; if ((array1 == null) && (array2 == null)) { return true; } if ((array1 == null) && (array2 != null)) { return false; } if ((array1 != null) && (array2 == null)) { return false; } if (array1.Length != array2.Length) { return false; } for (int i = 0; i < array1.Length; i++) { if (array1[i] != array2[i]) { TestLibrary.TestFramework.LogError(errorno, "Two arrays are not equal"); TestLibrary.TestFramework.LogInformation("WARNING[LOCAL VARIABLES] array1[i] = " + array1[i] + ", array2[i] = " + array2[i] + ", i = " + i); retval = false; break; } } return retval; } #endregion }
35.129167
156
0.606097
[ "MIT" ]
Rayislandstyle/dotnet-coreclr
tests/src/CoreMangLib/cti/system/globalization/datetimeformatinfo/datetimeformatinfoclone.cs
8,431
C#
using System; using System.Text; using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using SharePointPnP.Modernization.Framework.Transform; using SharePointPnP.Modernization.Framework.Telemetry.Observers; using Microsoft.SharePoint.Client; namespace SharePointPnP.Modernization.Framework.Tests.Transform.CommonTests { /// <summary> /// Summary description for CommonSP_WebPartPageTests /// </summary> [TestClass] public class CommonSPWebPartPageTests { public CommonSPWebPartPageTests() { // // TODO: Add constructor logic here // } private TestContext testContextInstance; /// <summary> ///Gets or sets the test context which provides ///information about and functionality for the current test run. ///</summary> public TestContext TestContext { get { return testContextInstance; } set { testContextInstance = value; } } #region Additional test attributes // // You can use the following additional attributes as you write your tests: // // Use ClassInitialize to run code before running the first test in the class // [ClassInitialize()] // public static void MyClassInitialize(TestContext testContext) { } // // Use ClassCleanup to run code after all tests in a class have run // [ClassCleanup()] // public static void MyClassCleanup() { } // // Use TestInitialize to run code before running each test // [TestInitialize()] // public void MyTestInitialize() { } // // Use TestCleanup to run code after each test has run // [TestCleanup()] // public void MyTestCleanup() { } // #endregion #region SharePoint 2010 Tests [TestCategory(TestCategories.SP2010)] [TestMethod] public void AllCommonWebPartPages_SP2010() { TransformPage(SPPlatformVersion.SP2010); } #endregion #region SharePoint 2013 Tests [TestCategory(TestCategories.SP2013)] [TestMethod] public void AllCommonWebPartPages_SP2013() { TransformPage(SPPlatformVersion.SP2013); } #endregion #region SharePoint 2016 Tests [TestCategory(TestCategories.SP2016)] [TestMethod] public void AllCommonWebPartPages_SP2016() { TransformPage(SPPlatformVersion.SP2016); } #endregion #region SharePoint 2019 Tests [TestCategory(TestCategories.SP2019)] [TestMethod] public void AllCommonWebPartPages_SP2019() { TransformPage(SPPlatformVersion.SP2019); } #endregion #region SharePoint Online Tests [TestCategory(TestCategories.SPO)] [TestMethod] public void AllCommonWikiPages_SPO() { TransformPage(SPPlatformVersion.SPO); } #endregion #region Code for Tests /// <summary> /// Different page same test conditions /// </summary> /// <param name="pageName"></param> private void TransformPage(SPPlatformVersion version, string pageNameStartsWith = "Common-WebPartPage") { using (var targetClientContext = TestCommon.CreateClientContext(TestCommon.AppSetting("SPOTargetSiteUrl"))) { using (var sourceClientContext = TestCommon.CreateSPPlatformClientContext(version, TransformType.WebPartPage)) { var pageTransformator = new PageTransformator(sourceClientContext, targetClientContext); pageTransformator.RegisterObserver(new MarkdownObserver(folder: "c:\\temp", includeVerbose: true)); pageTransformator.RegisterObserver(new UnitTestLogObserver()); var pages = sourceClientContext.Web.GetPages(pageNameStartsWith); pages.FailTestIfZero(); foreach (var page in pages) { var pageName = page.FieldValues["FileLeafRef"].ToString(); PageTransformationInformation pti = new PageTransformationInformation(page) { // If target page exists, then overwrite it Overwrite = true, // Don't log test runs SkipTelemetry = true, //Permissions are unlikely to work given cross domain KeepPageSpecificPermissions = false, //Update target to include SP version TargetPageName = TestCommon.UpdatePageToIncludeVersion(version, pageName) }; pti.MappingProperties["SummaryLinksToQuickLinks"] = "true"; pti.MappingProperties["UseCommunityScriptEditor"] = "true"; var result = pageTransformator.Transform(pti); Assert.IsTrue(!string.IsNullOrEmpty(result)); } pageTransformator.FlushObservers(); } } } #endregion } }
31.19209
126
0.573266
[ "MIT" ]
CaPa-Creative-Ltd/sp-dev-modernization
Tools/SharePoint.Modernization/SharePointPnP.Modernization.Framework.Tests/Transform/CommonTests/CommonSPWebPartPageTests.cs
5,523
C#
using UnityEngine; using System.Collections; public class SimpleFollow : MonoBehaviour { [SerializeField] bool trackX; [SerializeField] bool trackY; [SerializeField] bool trackZ; public float xOffset; public float yOffset; public float zOffset; public GameObject target; private void LateUpdate() { if(target != null) { Vector3 newPos = this.transform.position; if (trackX) newPos.x = target.transform.position.x + xOffset; if(trackY) newPos.y = target.transform.position.y + yOffset; if(trackZ) newPos.z = target.transform.position.z + zOffset; this.transform.position = newPos; } } }
19.272727
53
0.713836
[ "Apache-2.0" ]
takemurakimio/missing-part-1
Assets/_scripts/Tools/SimpleFollow.cs
638
C#
using System.ComponentModel; using PrtgAPI.Attributes; namespace PrtgAPI { enum HtmlFunction { [Undocumented] [Description("controls/channeledit.htm")] ChannelEdit, [Undocumented] [Description("controls/objectdata.htm")] ObjectData, [Undocumented] [Description("editsettings")] EditSettings, [Undocumented] [Description("deletesub.htm")] RemoveSubObject, /// <summary> /// Contains the content returned by a request for additional device information from <see cref="CommandFunction.AddSensor2"/>. /// </summary> [Undocumented] [Description("addsensor4.htm")] AddSensor4, [Undocumented] [Description("controls/editnotification.htm")] EditNotification } }
23.361111
135
0.611177
[ "MIT" ]
loftwah/PrtgAPI
src/PrtgAPI/Enums/Functions/HtmlFunction.cs
843
C#
using System; using CommandLine; using CommandLine.Text; namespace Hillinworks.Utilities.GetTime { internal class Options { [ValueOption(0)] [Option(HelpText = "The base time, could be an absolute time, or 'now'(default), 'next-second', 'tomorrow' etc.", DefaultValue = "now")] public string Base { get; set; } [Option('a', "add", HelpText = "Offset the current time", MutuallyExclusiveSet = "Add")] public TimeSpan Offset { get; set; } [Option("add-milliseconds", HelpText = "Offset the current time by specified milliseconds", MutuallyExclusiveSet = "Add")] public double OffsetMilliseconds { get; set; } [Option("add-seconds", HelpText = "Offset the current time by specified seconds", MutuallyExclusiveSet = "Add")] public double OffsetSeconds { get; set; } [Option("add-minutes", HelpText = "Offset the current time by specified minutes", MutuallyExclusiveSet = "Add")] public double OffsetMinutes { get; set; } [Option("add-hours", HelpText = "Offset the current time by specified hours", MutuallyExclusiveSet = "Add")] public double OffsetHours { get; set; } [Option("add-days", HelpText = "Offset the current time by specified days", MutuallyExclusiveSet = "Add")] public double OffsetDays { get; set; } [Option("add-weeks", HelpText = "Offset the current time by specified weeks", MutuallyExclusiveSet = "Add")] public double OffsetWeeks { get; set; } [Option("add-months", HelpText = "Offset the current time by specified months", MutuallyExclusiveSet = "Add")] public double OffsetMonths { get; set; } [Option("add-years", HelpText = "Offset the current time by specified years", MutuallyExclusiveSet = "Add")] public double OffsetYears { get; set; } [Option("add-decades", HelpText = "Offset the current time by specified decades", MutuallyExclusiveSet = "Add")] public double OffsetDecades { get; set; } [Option("add-centuries", HelpText = "Offset the current time by specified years", MutuallyExclusiveSet = "Add")] public double OffsetCenturies{ get; set; } [Option('f', "format", HelpText = "Specify the output format. See https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx for details.", MutuallyExclusiveSet = "Format")] public string OutputFormat { get; set; } [Option('l', "long", HelpText = "Output in long format", MutuallyExclusiveSet = "Format")] public bool LongFormat { get; set; } [Option('s', "short", HelpText = "Output in short format", MutuallyExclusiveSet = "Format")] public bool ShortFormat { get; set; } [Option('u', "unix", HelpText = "Output in Unix time format", MutuallyExclusiveSet = "Format")] public bool UnixFormat { get; set; } [Option('m', "mode", HelpText = "Output date or time", DefaultValue = DateTimeMode.Auto)] public DateTimeMode DateTimeMode { get; set; } // todo: support time-zone //[Option('z', "time-zone", HelpText ="Time zone of input and output time. Could be overridden by input-time-zone and output-time-zone")] //public string TimeZone { get; set; } //[Option("input-time-zone", HelpText = "Time zone of input time")] //public string InputTimeZone { get; set; } //[Option("output-time-zone", HelpText = "Time zone of output time")] //public string OutputTimeZone { get; set; } [HelpOption] public string GetUsage() { return HelpText.AutoBuild(this, current => HelpText.DefaultParsingErrorsHandler(this, current)); } } }
55.737705
181
0.709412
[ "MIT" ]
hillin/gettime
Source/Options.cs
3,402
C#
#region License Statement // Copyright (c) L.A.B.Soft. All rights reserved. // // The use and distribution terms for this software are covered by the // Common Public License 1.0 (http://opensource.org/licenses/cpl.php) // which can be found in the file CPL.TXT at the root of this distribution. // By using this software in any fashion, you are agreeing to be bound by // the terms of this license. // // You must not remove this notice, or any other, from this software. #endregion #region Using Statements using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; #endregion namespace Textile.States { /// <summary> /// Formatting state for a bulleted list. /// </summary> [FormatterState(ListFormatterState.PatternBegin + @"\*+" + ListFormatterState.PatternEnd)] public class UnorderedListFormatterState : ListFormatterState { public UnorderedListFormatterState() { } protected override void WriteIndent() { Formatter.Output.WriteLine("<ul" + FormattedStylesAndAlignment() + ">"); } protected override void WriteOutdent() { Formatter.Output.WriteLine("</ul>"); } protected override bool IsMatchForMe(string input, int minNestingDepth, int maxNestingDepth) { return Regex.IsMatch(input, @"^\s*[\*]{" + minNestingDepth + @"," + maxNestingDepth + @"}" + TextileGlobals.BlockModifiersPattern + @"\s"); } protected override bool IsMatchForOthers(string input, int minNestingDepth, int maxNestingDepth) { return Regex.IsMatch(input, @"^\s*[#]{" + minNestingDepth + @"," + maxNestingDepth + @"}" + TextileGlobals.BlockModifiersPattern + @"\s"); } } }
32.833333
152
0.672871
[ "Apache-2.0" ]
dotnetprojects/textile.net
Textile/States/UnorderedListFormatterState.cs
1,773
C#
using System; using EfsTools.Qualcomm.QcdmCommands; using EfsTools.Qualcomm.QcdmCommands.Requests.Efs; using EfsTools.Qualcomm.QcdmCommands.Responses.Efs; namespace EfsTools.Qualcomm.QcdmManagers { internal class QcdmEfsManager { private readonly WeakReference<QcdmManager> _manager; private HelloInfo _helloInfo; public QcdmEfsManager(QcdmManager manager) { _manager = new WeakReference<QcdmManager>(manager); } public QueryInfo EfsInfo { get { InitializeIfNeed(); if (_manager.TryGetTarget(out var manager)) { if (manager.IsOpen) { var request = new EfsQueryCommandRequest(); var response = manager.ExecuteQcdmCommandRequest<EfsQueryCommandResponse>(request); if (response != null) { return response.Info; } } } return null; } } public EfsDeviceInfo DeviceInfo { get { InitializeIfNeed(); if (_manager.TryGetTarget(out var manager)) { if (manager.IsOpen) { var request = new EfsDeviceInfoCommandRequest(); var response = manager.ExecuteQcdmCommandRequest<EfsDeviceInfoResponse>(request); if (response != null) { return response.DeviceInfo; } } } return null; } } public HelloInfo HelloInfo { get { InitializeIfNeed(); return _helloInfo; } } public QcdmEfsFileStream OpenFile(string filePath, EfsFileFlag flags, int permission) { if (_manager.TryGetTarget(out var manager)) { var file = new QcdmEfsFileStream(manager, filePath, flags, permission); file.Open(); return file; } return null; } public bool FileExists(string path) { InitializeIfNeed(); try { if (_manager.TryGetTarget(out var manager)) { if (manager.IsOpen) { var request = new EfsStatFileCommandRequest(path); var response = manager.ExecuteQcdmCommandRequest<EfsStatFileCommandResponse>(request); if (response != null) { var stat = response.Stat; if (stat.Size > 0 || stat.LinkCount > 0) { return true; } } } } return false; } catch { return false; } } public void RenameFile(string path, string newPath) { InitializeIfNeed(); if (_manager.TryGetTarget(out var manager)) { if (manager.IsOpen) { var request = new EfsRenameFileCommandRequest(path, newPath); var response = manager.ExecuteQcdmCommandRequest<EfsRenameFileCommandResponse>(request); if (response != null) { QcdmEfsErrorsUtils.ThrowQcdmEfsErrorsIfNeed(response.Error); } } } } public FileStat FileStat(string path) { InitializeIfNeed(); if (_manager.TryGetTarget(out var manager)) { if (manager.IsOpen) { var request = new EfsStatFileCommandRequest(path); var response = manager.ExecuteQcdmCommandRequest<EfsStatFileCommandResponse>(request); if (response != null) { return response.Stat; } } } return null; } public void CheckAccess(string path, byte permissionBits) { InitializeIfNeed(); if (_manager.TryGetTarget(out var manager)) { if (manager.IsOpen) { var request = new EfsAccessCommandRequest(path, permissionBits); var response = manager.ExecuteQcdmCommandRequest<EfsAccessCommandResponse>(request); if (response != null) { QcdmEfsErrorsUtils.ThrowQcdmEfsErrorsIfNeed(response.Error); } } } } public QcdmEfsDirectory OpenDirectory(string path) { InitializeIfNeed(); if (_manager.TryGetTarget(out var manager)) { var directory = new QcdmEfsDirectory(manager, path); directory.Open(); return directory; } return null; } public void CreateDirectory(string path, ushort mode) { InitializeIfNeed(); if (_manager.TryGetTarget(out var manager)) { var request = new EfsMakeDirectoryCommandRequest(mode, path); var response = manager.ExecuteQcdmCommandRequest<EfsMakeDirectoryCommandResponse>(request); if (response != null) { if (response.Error != QcdmEfsErrors.DirectoryExist) { QcdmEfsErrorsUtils.ThrowQcdmEfsErrorsIfNeed(response.Error); } } } } public void DeleteDirectory(string path) { InitializeIfNeed(); if (_manager.TryGetTarget(out var manager)) { var request = new EfsRemoveDirectoryCommandRequest(path); var response = manager.ExecuteQcdmCommandRequest<EfsRemoveDirectoryCommandResponse>(request); if (response != null) { QcdmEfsErrorsUtils.ThrowQcdmEfsErrorsIfNeed(response.Error); } } } public void DeleteFile(string path) { InitializeIfNeed(); if (_manager.TryGetTarget(out var manager)) { var request = new EfsUnlinkFileCommandRequest(path); var response = manager.ExecuteQcdmCommandRequest<EfsUnlinkFileCommandResponse>(request); if (response != null) { QcdmEfsErrorsUtils.ThrowQcdmEfsErrorsIfNeed(response.Error); } } } public void SyncNoWait(string path, ushort sequence) { InitializeIfNeed(); if (_manager.TryGetTarget(out var manager)) { if (manager.IsOpen) { var request = new EfsSyncNoWaitCommandRequest(path, sequence); var response = manager.ExecuteQcdmCommandRequest<EfsSyncNoWaitCommandResponse>(request); if (response != null) { QcdmEfsErrorsUtils.ThrowQcdmEfsErrorsIfNeed(response.Error); } } } } public void PutItemFile(string path, EfsFileFlag flags, int permission, byte[] data) { InitializeIfNeed(); if (_manager.TryGetTarget(out var manager)) { if (manager.IsOpen) { var request = new EfsPutItemFileCommandRequest(path, flags, permission, data); var response = manager.ExecuteQcdmCommandRequest<EfsPutItemFileCommandResponse>(request); if (response != null) { QcdmEfsErrorsUtils.ThrowQcdmEfsErrorsIfNeed(response.Error); } } } } private void InitializeIfNeed() { if (_helloInfo == null) { if (_manager.TryGetTarget(out var manager)) { if (manager.IsOpen) { var request = new EfsHelloCommandRequest(); var response = manager.ExecuteQcdmCommandRequest<EfsHelloCommandResponse>(request); if (response != null) { _helloInfo = response.Info; } } } } } } }
34.017986
111
0.450037
[ "MIT" ]
AndroPlus-org/EfsTools
EfsTools/Qualcomm/QcdmManagers/QcdmEfsManager.cs
9,459
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Chocolatey" file="ProgressService.cs"> // Copyright 2014 - Present Rob Reynolds, the maintainers of Chocolatey, and RealDimensions Software, LLC // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Threading; using System.Threading.Tasks; using System.Windows; using Caliburn.Micro; using ChocolateyGui.Base; using ChocolateyGui.Controls; using ChocolateyGui.Controls.Dialogs; using ChocolateyGui.Models; using ChocolateyGui.Utilities.Extensions; using ChocolateyGui.Views; using MahApps.Metro.Controls.Dialogs; using Microsoft.VisualStudio.Threading; using Serilog; using Serilog.Events; namespace ChocolateyGui.Services { public class ProgressService : ObservableBase, IProgressService { private readonly AsyncSemaphore _lock; private CancellationTokenSource _cst; private int _loadingItems; private ChocolateyDialogController _progressController; public ProgressService() { IsLoading = false; _loadingItems = 0; Output = new ObservableRingBufferCollection<PowerShellOutputLine>(100); _lock = new AsyncSemaphore(1); } public ShellView ShellView { get; set; } public double Progress { get; private set; } public bool IsLoading { get; private set; } public ObservableRingBufferCollection<PowerShellOutputLine> Output { get; } public CancellationToken GetCancellationToken() { if (!IsLoading) { throw new InvalidOperationException("There's no current operation in process."); } return _cst.Token; } public void Report(double value) { Progress = value; if (_progressController != null) { if (value < 0) { Execute.OnUIThread(() => _progressController.SetIndeterminate()); } else { Execute.OnUIThread(() => _progressController.SetProgress(Math.Min(Progress / 100.0f, 100))); } } NotifyPropertyChanged("Progress"); } public async Task<MessageDialogResult> ShowMessageAsync(string title, string message) { using (await _lock.EnterAsync()) { if (ShellView != null) { return await RunOnUIAsync(() => ShellView.ShowMessageAsync(title, message)); } return MessageBox.Show(message, title) == MessageBoxResult.OK ? MessageDialogResult.Affirmative : MessageDialogResult.Negative; } } public async Task StartLoading(string title = null, bool isCancelable = false) { using (await _lock.EnterAsync()) { var currentCount = Interlocked.Increment(ref _loadingItems); if (currentCount == 1) { await RunOnUIAsync(async () => { _progressController = await ShellView.ShowChocolateyDialogAsync(title, isCancelable); _progressController.SetIndeterminate(); if (isCancelable) { _cst = new CancellationTokenSource(); _progressController.OnCanceled += dialog => { if (_cst != null) { _cst.Cancel(); } }; } Output.Clear(); IsLoading = true; NotifyPropertyChanged("IsLoading"); }); } } } public async Task StopLoading() { using (await _lock.EnterAsync()) { var currentCount = Interlocked.Decrement(ref _loadingItems); if (currentCount == 0) { await RunOnUIAsync(() => _progressController.CloseAsync()); _progressController = null; Report(0); IsLoading = false; NotifyPropertyChanged("IsLoading"); } } } public void WriteMessage( string message, PowerShellLineType type = PowerShellLineType.Output, bool newLine = true) { // Don't show debug events when not running in debug. if (type == PowerShellLineType.Debug && !Log.IsEnabled(LogEventLevel.Debug)) { return; } Execute.BeginOnUIThread(() => Output.Add(new PowerShellOutputLine(message, type, newLine))); } private static Task RunOnUIAsync(Func<Task> action) { return action.RunOnUIThreadAsync(); } private static Task<T> RunOnUIAsync<T>(Func<Task<T>> action) { return action.RunOnUIThreadAsync(); } } }
33.393939
120
0.500907
[ "Apache-2.0" ]
dhtdht020/ChocolateyGUI
Source/ChocolateyGui/Services/ProgressService.cs
5,512
C#
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using QuickLogger.Extensions.NetCore.Configuration; using QuickLogger.Extensions.Wrapper.Application.Services; using System; using System.Net; namespace QuickLogger.Extensions.NetCore { public static class QuickLoggerExtensions { internal static ILoggingBuilder AddLogger(ILoggingBuilder builder, ILoggerService loggerService) { builder.AddProvider(new QuickLoggerProvider(loggerService)); return builder; } public static IServiceCollection AddQuickLogger(this IServiceCollection serviceCollection) { serviceCollection.AddSingleton<ILoggerSettingsPathFinder, CoreConfigPathFinder>(); serviceCollection.AddSingleton<ILoggerService, QuickLoggerService>(); serviceCollection.AddLogging(x => AddLogger(x, serviceCollection.BuildServiceProvider().GetService<ILoggerService>())); return serviceCollection; } } }
38.407407
143
0.737705
[ "Apache-2.0" ]
JTOne123/QuickLogger
library/wrappers/dotnet/QuickLogger/QuickLogger.Extensions.NetCore/QuickLoggerExtensions.cs
1,039
C#
namespace BoardGameGeekIntegration.Models { public class SimilarBoardGame { public int Id { get; set; } public string Name { get; set; } public string ImageUrl { get; set; } } }
23.777778
44
0.61215
[ "MIT" ]
WTobor/BoardGamesNook
BoardGameGeekIntegration/Models/SimilarBoardGame.cs
216
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ActionReload : ActionInfo { // Start is called before the first frame update protected override void OnAttack() { base.OnAttack(); if (SourceEqp != null) { Reload((EqpWeapon)SourceEqp, m_charBase.GetComponent<InventoryHolder>()); } } protected void Reload(EqpWeapon wep, InventoryHolder ih) { int bulletsToReload = wep.ClipSize - wep.CurrentAmmo; int rem = ih.RemoveItem(wep.AmmoType.GetComponent<Item>(), bulletsToReload); wep.CurrentAmmo += rem; } }
25.8
85
0.655814
[ "MIT" ]
sdasd30/TSSG
Assets/Scripts/Entity/CharacterActions/Actions/ActionReload.cs
647
C#
using System; using College_GeneratorAccounts.Services; namespace College_GeneratorAccounts.Model { public class Account { public Guid Id { get; set; } public string Username { get; init; } public string Email { get; init; } public string Password { get; init; } public string Firstname { get; init; } public string LastName { get; init; } public string Cohort1 { get; init; } /// <summary> /// Для сериализации в xml /// </summary> public Account() { } public Account(string login, string email, string password, string name, string lastName, string group) { Username = login ?? throw new ArgumentNullException(nameof(login)); Email = email ?? throw new ArgumentNullException(nameof(email)); Password = password ?? throw new ArgumentNullException(nameof(password)); Firstname = name ?? throw new ArgumentNullException(nameof(name)); LastName = lastName ?? throw new ArgumentNullException(nameof(lastName)); Cohort1 = group ?? throw new ArgumentNullException(nameof(group)); } /// <summary> /// Сгенерировать аккаунт /// </summary> /// <param name="info">Полное имя</param> /// <param name="fileName">Путь к файлу</param> /// <returns>Аккаунт</returns> public static Account GetnerateAccount(string info, string fileName) { string[] infoArray = info.Replace(" ", " ").Split(); string nameToLatin = Generator.GetCollectionTranslitToLatin(info).Replace(" ", " "); string year = fileName.Split('_')[2].Remove(0,2); try { var login = Generator.GenerateLogin(nameToLatin, year); return new Account(login, Generator.GenerateEmails(login), $"{Generator.GeneratePassword()}#", infoArray[1], infoArray[0], $"{infoArray[3].Replace('_','-')}({year})"); } catch (IndexOutOfRangeException ex) { throw new IndexOutOfRangeException(ex.Message); } } /// <summary> /// Возвращает строку, представляющую текущий объект для csv /// </summary> /// <returns> Cтроку, представляющую текущий объект для csv</returns> public string ToStringCsv() => $"{Username};{Password};{Firstname};{LastName};{Email};{Cohort1}\n"; public override string ToString() => $"LastName: {LastName}\nName: {Firstname}\nLogin: {Username}\nPassword: {Password}\nEmail: {Email}\nGroup: {Cohort1}\n"; } }
36.822581
171
0.689882
[ "MIT" ]
BlaynerProgramm/Generate-Account-for-Moodle
College_GeneratorAccounts/Model/Account.cs
2,428
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using ContactsApi.Models; using ContactsApi.Repository; // For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 namespace ContactsApi.Controllers { [Route("api/[controller]")] public class ContactController : Controller { public IContactRepository ContactsRepo { get; set; } public ContactController(IContactRepository _repo) { ContactsRepo = _repo; } [HttpGet] public IEnumerable<Contact> GetAll() { return ContactsRepo.GetAll(); } [HttpGet("{id}", Name = "GetContacts")] public IActionResult GetById(string id) { var item = ContactsRepo.Find(id); if (item == null) { return NotFound(); } return new ObjectResult(item); } [HttpPost] public IActionResult Create([FromBody] Contact item) { if (item == null) { return BadRequest(); } ContactsRepo.Add(item); return CreatedAtRoute("GetContacts", new { Controller = "Contacts", id = item.MobilePhone }, item); } [HttpPut("{id}")] public IActionResult Update(string id, [FromBody] Contact item) { if (item == null) { return BadRequest(); } var contactObj = ContactsRepo.Find(id); if (contactObj == null) { return NotFound(); } ContactsRepo.Update(item); return new NoContentResult(); } [HttpDelete("{id}")] public void Delete(string id) { ContactsRepo.Remove(id); } } }
26.337838
115
0.539251
[ "MIT" ]
godwinlarry/contact-mvc-webapi
ContactsApi/src/ContactsApi/Controllers/ContactController.cs
1,951
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Build.UnitTests.OM.ObjectModelRemoting { using System; using System.Collections.Generic; using System.Runtime.CompilerServices; using System.Xml; using Microsoft.Build.Construction; using Microsoft.Build.ObjectModelRemoting; /// <summary> /// We need to know the actual type of ProjectElements in order to do a proper remoting. /// Unless we do some explicit ProjectElement.GetXMLType() thing we need to use heuristic. /// /// Most of the types has a single implementation, but few has a wrapper classes. They are also internal for MSbuild. /// </summary> internal static class ProjectElemetExportHelper { delegate MockProjectElementLinkRemoter ExporterFactory(ProjectCollectionLinker exporter, ProjectElement xml); private class ElementInfo { public static ElementInfo New<T, RMock>() where RMock : MockProjectElementLinkRemoter, new() { return new ElementInfo(typeof(T), IsOfType<T>, Export<RMock>); } public ElementInfo(Type type, Func<ProjectElement, bool> checker, ExporterFactory factory) { this.CanonicalType = type; this.Checker = checker; this.ExportFactory = factory; } public ElementInfo(Func<ProjectElement, bool> checker, ExporterFactory factory) { this.Checker = checker; this.ExportFactory = factory; } public Type CanonicalType { get; } public Func<ProjectElement, bool> Checker { get; } public ExporterFactory ExportFactory { get; } } private static List<ElementInfo> canonicalTypes = new List<ElementInfo>() { ElementInfo.New<ProjectRootElement , MockProjectRootElementLinkRemoter>(), ElementInfo.New<ProjectChooseElement , MockProjectChooseElementLinkRemoter>(), ElementInfo.New<ProjectExtensionsElement , MockProjectExtensionsElementLinkRemoter>(), ElementInfo.New<ProjectImportElement , MockProjectImportElementLinkRemoter>(), ElementInfo.New<ProjectImportGroupElement , MockProjectImportGroupElementLinkRemoter>(), ElementInfo.New<ProjectItemDefinitionGroupElement, MockProjectItemDefinitionGroupElementLinkRemoter>(), ElementInfo.New<ProjectItemElement , MockProjectItemElementLinkRemoter>(), ElementInfo.New<ProjectItemGroupElement , MockProjectItemGroupElementLinkRemoter>(), ElementInfo.New<ProjectMetadataElement , MockProjectMetadataElementLinkRemoter>(), ElementInfo.New<ProjectOnErrorElement , MockProjectOnErrorElementLinkRemoter>(), ElementInfo.New<ProjectOtherwiseElement , MockProjectOtherwiseElementLinkRemoter>(), ElementInfo.New<ProjectOutputElement , MockProjectOutputElementLinkRemoter>(), ElementInfo.New<ProjectPropertyElement , MockProjectPropertyElementLinkRemoter>(), ElementInfo.New<ProjectPropertyGroupElement , MockProjectPropertyGroupElementLinkRemoter>(), ElementInfo.New<ProjectSdkElement , MockProjectSdkElementLinkRemoter>(), ElementInfo.New<ProjectTargetElement , MockProjectTargetElementLinkRemoter>(), ElementInfo.New<ProjectTaskElement , MockProjectTaskElementLinkRemoter>(), ElementInfo.New<ProjectUsingTaskBodyElement , MockProjectUsingTaskBodyElementLinkRemoter>(), ElementInfo.New<ProjectItemDefinitionElement , MockProjectItemDefinitionElementLinkRemoter>(), ElementInfo.New<ProjectUsingTaskElement , MockProjectUsingTaskElementLinkRemoter>(), ElementInfo.New<ProjectUsingTaskParameterElement , MockProjectUsingTaskParameterElementLinkRemoter>(), ElementInfo.New<ProjectWhenElement , MockProjectWhenElementLinkRemoter>(), ElementInfo.New<UsingTaskParameterGroupElement , MockUsingTaskParameterGroupElementLinkRemoter>(), }; private static MockProjectElementLinkRemoter Export<RMock>(ProjectCollectionLinker exporter, ProjectElement xml) where RMock : MockProjectElementLinkRemoter, new() { return exporter.Export<ProjectElement, RMock>(xml); } private static bool IsOfType<T> (ProjectElement xml) { return xml is T; } private static Dictionary<Type, ExporterFactory> knownTypes = new Dictionary<Type, ExporterFactory>(); static ProjectElemetExportHelper() { foreach (var v in canonicalTypes) { knownTypes.Add(v.CanonicalType, v.ExportFactory); } } private static MockProjectElementLinkRemoter NotImplemented(ProjectCollectionLinker exporter, ProjectElement xml) { throw new NotImplementedException(); } public static MockProjectElementLinkRemoter ExportElement(this ProjectCollectionLinker exporter, ProjectElement xml) { if (xml == null) { return null; } var implType = xml.GetType(); if (knownTypes.TryGetValue(implType, out var factory)) { return factory(exporter, xml); } factory = NotImplemented; foreach (var t in canonicalTypes) { if (t.Checker(xml)) { factory = t.ExportFactory; break; } } lock (knownTypes) { var newKnown = new Dictionary<Type, ExporterFactory>(knownTypes); newKnown[implType] = factory; knownTypes = newKnown; } return factory(exporter, xml); } } }
45.830882
124
0.639339
[ "MIT" ]
Youssef1313/msbuild
src/Build.OM.UnitTests/ObjectModelRemoting/RemoteProjectsProviderMock/ConstructionLinkMocks/ProjectElemetExportHelper.cs
6,235
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Security.Permissions.IBuiltInPermission.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Security.Permissions { internal partial interface IBuiltInPermission { #region Methods and constructors int GetTokenIndex(); #endregion } }
45.1875
463
0.777778
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Contracts/MsCorlib/Sources/System.Security.Permissions.IBuiltInPermission.cs
2,169
C#