content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Copyright (c) Microsoft Corporation. // // Licensed under the MIT license. using Shouldly; using System; using System.Collections.Generic; using System.IO; using System.Linq; using Xunit; namespace Microsoft.VisualStudio.SlnGen.UnitTests { public class SlnHierarchyTests { [Fact] public void HierarchyIgnoresCase() { SlnProject[] projects = new[] { new SlnProject { FullPath = Path.Combine(@"E:\Code", "ProjectA", "ProjectA.csproj"), Name = "ProjectA", ProjectGuid = Guid.NewGuid(), ProjectTypeGuid = SlnProject.DefaultLegacyProjectTypeGuid, }, new SlnProject { FullPath = Path.Combine(@"E:\code", "ProjectB", "ProjectB.csproj"), Name = "ProjectB", ProjectGuid = Guid.NewGuid(), ProjectTypeGuid = SlnProject.DefaultLegacyProjectTypeGuid, }, }; SlnHierarchy hierarchy = new SlnHierarchy(projects); hierarchy.Folders.Select(i => i.FullPath).ShouldBe(new[] { @"E:\Code\ProjectA", @"E:\code\ProjectB", @"E:\Code", }); } [Fact] public void HierarchyIsCorrectlyFormed() { DummyFolder root = DummyFolder.CreateRoot(@"D:\zoo\foo"); DummyFolder bar = root.AddSubDirectory("bar"); bar.AddProjectWithDirectory("baz"); bar.AddProjectWithDirectory("baz1"); bar.AddProjectWithDirectory("baz2"); root.AddProjectWithDirectory("bar1"); List<SlnProject> projects = root.GetAllProjects(); SlnHierarchy hierarchy = new SlnHierarchy(projects); hierarchy.Folders.Select(i => i.FullPath).OrderBy(s => s) .ShouldBe(root.GetAllFolders().Select(f => f.FullPath).OrderBy(s => s)); foreach (SlnProject project in projects) { hierarchy .Folders .First(i => i.FullPath.Equals(Path.GetDirectoryName(project.FullPath))) .Projects.ShouldHaveSingleItem() .ShouldBe(project); } } [Fact] public void HierarchyWithCollapsedFoldersIsCorrectlyFormed() { DummyFolder root = DummyFolder.CreateRoot(@"D:\zoo\foo"); DummyFolder bar = root.AddSubDirectory("bar"); DummyFolder qux = bar.AddSubDirectory("qux"); SlnProject baz = qux.AddProjectWithDirectory("baz"); SlnProject baz1 = qux.AddProjectWithDirectory("baz1"); SlnProject baz2 = qux.AddProjectWithDirectory("baz2"); SlnProject bar1 = root.AddProjectWithDirectory("bar1"); SlnProject baz3 = root .AddSubDirectory("foo1") .AddSubDirectory("foo2") .AddProjectWithDirectory("baz3"); DummyFolder rootExpected = DummyFolder.CreateRoot(@"D:\zoo\foo"); DummyFolder barQuxExpected = rootExpected.AddSubDirectory($"bar {SlnHierarchy.Separator} qux"); barQuxExpected.Projects.Add(baz); barQuxExpected.Projects.Add(baz1); barQuxExpected.Projects.Add(baz2); rootExpected.Projects.Add(bar1); rootExpected.AddSubDirectory($"foo1 {SlnHierarchy.Separator} foo2 {SlnHierarchy.Separator} baz3").Projects.Add(baz3); SlnHierarchy hierarchy = new SlnHierarchy(root.GetAllProjects(), collapseFolders: true); SlnFolder[] resultFolders = hierarchy.Folders.OrderBy(f => f.FullPath).ToArray(); DummyFolder[] expectedFolders = rootExpected.GetAllFolders().OrderBy(f => f.FullPath).ToArray(); resultFolders.Length.ShouldBe(expectedFolders.Length); for (int i = 0; i < resultFolders.Length; i++) { SlnFolder resultFolder = resultFolders[i]; DummyFolder expectedFolder = expectedFolders[i]; resultFolder.Name.ShouldBe(expectedFolder.Name); // Verify that expected and results projects match resultFolder.Projects.Count.ShouldBe(expectedFolder.Projects.Count); resultFolder.Projects.ShouldAllBe(p => expectedFolder.Projects.Contains(p)); // Verify that expected and results child folders match resultFolder.Folders.Count.ShouldBe(expectedFolder.Folders.Count); resultFolder.Folders.ShouldAllBe(p => expectedFolder.Folders.Exists(f => f.Name == p.Name)); } } private class DummyFolder { private DummyFolder(string path) { FileInfo fileInfo = new FileInfo(path); Folders = new List<DummyFolder>(); Projects = new List<SlnProject>(); FullPath = path; Name = fileInfo.Name; } public List<DummyFolder> Folders { get; } public string FullPath { get; } public string Name { get; } public List<SlnProject> Projects { get; } public static DummyFolder CreateRoot(string rootPath) { return new DummyFolder(rootPath); } public SlnProject AddProjectWithDirectory(string name) { return AddSubDirectory(name).AddProject(name); } public DummyFolder AddSubDirectory(string folderName) { string path = Path.Combine(FullPath, folderName); DummyFolder childFolder = new DummyFolder(path); Folders.Add(childFolder); return childFolder; } public List<DummyFolder> GetAllFolders() { List<DummyFolder> folders = Folders .SelectMany(f => f.GetAllFolders()) .ToList(); folders.Add(this); return folders; } public List<SlnProject> GetAllProjects() { List<SlnProject> projects = Folders .SelectMany(f => f.GetAllProjects()) .ToList(); projects.AddRange(Projects); return projects; } private SlnProject AddProject(string name) { SlnProject project = new SlnProject { FullPath = Path.Combine(FullPath, name) + ".csproj", Name = name, ProjectGuid = Guid.NewGuid(), ProjectTypeGuid = SlnProject.DefaultLegacyProjectTypeGuid, }; Projects.Add(project); return project; } } } }
34.880597
129
0.545429
[ "MIT" ]
ViktorHofer/slngen
src/Microsoft.VisualStudio.SlnGen.UnitTests/SlnHierarchyTests.cs
7,013
C#
// Copyright © 2010 onwards, Andrew Whewell // All rights reserved. // // Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // * Neither the name of the author nor the names of the program's 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 AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Linq; using System.Text; using InterfaceFactory; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Test.Framework; using VirtualRadar.Interface; using VirtualRadar.Interface.StandingData; using VirtualRadar.Library; namespace Test.VirtualRadar.WebSite { [TestClass] public class AircraftComparerTests { #region TestContext, fields, TestInitialise public TestContext TestContext { get; set; } private IAircraftComparer _Comparer; private IAircraft _Lhs; private IAircraft _Rhs; [TestInitialize] public void TestInitialise() { _Comparer = Factory.Resolve<IAircraftComparer>(); _Lhs = new Mock<IAircraft>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties().Object; _Rhs = new Mock<IAircraft>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties().Object; } #endregion #region InitialiseAircraft /// <summary> /// Sets the appropriate column on the aircraft passed across to either a high or low value, depending on the parameters. /// </summary> /// <param name="aircraft"></param> /// <param name="columnName"></param> /// <param name="setLowValue"></param> private void InitialiseAircraft(IAircraft aircraft, string columnName, bool setLowValue) { switch(columnName) { case AircraftComparerColumn.Altitude: aircraft.Altitude = setLowValue ? 100 : 200; break; case AircraftComparerColumn.Callsign: aircraft.Callsign = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.Destination: aircraft.Destination = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.DistanceFromHere: aircraft.Latitude = aircraft.Longitude = setLowValue ? 1F : 2F; break; case AircraftComparerColumn.FirstSeen: aircraft.FirstSeen = setLowValue ? new DateTime(2001, 1, 2, 10, 20, 21, 100) : new DateTime(2001, 1, 2, 10, 20, 21, 200); break; case AircraftComparerColumn.FlightsCount: aircraft.FlightsCount = setLowValue ? 100 : 200; break; case AircraftComparerColumn.GroundSpeed: aircraft.GroundSpeed = setLowValue ? 100 : 200; break; case AircraftComparerColumn.Icao24: aircraft.Icao24 = setLowValue ? "123456" : "ABCDEF"; break; case AircraftComparerColumn.Icao24Country: aircraft.Icao24Country = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.Model: aircraft.Model = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.NumberOfEngines: aircraft.NumberOfEngines = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.Operator: aircraft.Operator = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.OperatorIcao: aircraft.OperatorIcao = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.Origin: aircraft.Origin = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.Registration: aircraft.Registration = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.Species: aircraft.Species = setLowValue ? Species.Amphibian : Species.Landplane; break; case AircraftComparerColumn.Squawk: aircraft.Squawk = setLowValue ? 5 : 5000; break; case AircraftComparerColumn.Type: aircraft.Type = setLowValue ? "ABC" : "XYZ"; break; case AircraftComparerColumn.VerticalRate: aircraft.VerticalRate = setLowValue ? 100 : 200; break; case AircraftComparerColumn.WakeTurbulenceCategory: aircraft.WakeTurbulenceCategory = setLowValue ? WakeTurbulenceCategory.Light : WakeTurbulenceCategory.Heavy; break; default: throw new NotImplementedException(); } } #endregion #region Constructor and Properties [TestMethod] public void AircraftComparer_Constructor_Initialises_To_Known_State_And_Properties_Work() { Assert.AreEqual(0, _Comparer.SortBy.Count); Assert.AreEqual(0, _Comparer.PrecalculatedDistances.Count); TestUtilities.TestProperty(_Comparer, "BrowserLocation", null, new Coordinate(1, 2)); } #endregion #region Compare [TestMethod] public void AircraftComparer_Compare_Returns_Correct_Sort_Order_On_Single_Column() { foreach(var columnField in typeof(AircraftComparerColumn).GetFields()) { var columnName = (string)columnField.GetValue(null); for(int sortOrder = 0;sortOrder < 2;++sortOrder) { TestInitialise(); _Comparer.BrowserLocation = new Coordinate(0, 0); bool sortAscending = sortOrder == 0; _Comparer.SortBy.Add(new KeyValuePair<string,bool>(columnName, sortAscending)); var nullAircraft1 = new Mock<IAircraft>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties().Object; var nullAircraft2 = new Mock<IAircraft>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties().Object; var lowAircraft = new Mock<IAircraft>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties().Object; var highAircraft = new Mock<IAircraft>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties().Object; var lowAgain = new Mock<IAircraft>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties().Object; InitialiseAircraft(lowAircraft, columnName, true); InitialiseAircraft(highAircraft, columnName, false); InitialiseAircraft(lowAgain, columnName, true); Assert.AreEqual(0, _Comparer.Compare(nullAircraft1, nullAircraft2), columnName); Assert.AreEqual(0, _Comparer.Compare(lowAircraft, lowAircraft), columnName); Assert.AreEqual(0, _Comparer.Compare(highAircraft, highAircraft), columnName); Assert.AreEqual(0, _Comparer.Compare(lowAircraft, lowAgain), columnName); if(sortAscending) { Assert.IsTrue(_Comparer.Compare(lowAircraft, highAircraft) < 0, columnName); Assert.IsTrue(_Comparer.Compare(highAircraft, lowAircraft) > 0, columnName); Assert.IsTrue(_Comparer.Compare(nullAircraft1, lowAircraft) < 0, columnName); Assert.IsTrue(_Comparer.Compare(lowAircraft, nullAircraft1) > 0, columnName); } else { Assert.IsTrue(_Comparer.Compare(lowAircraft, highAircraft) > 0, columnName); Assert.IsTrue(_Comparer.Compare(highAircraft, lowAircraft) < 0, columnName); Assert.IsTrue(_Comparer.Compare(nullAircraft1, lowAircraft) > 0, columnName); Assert.IsTrue(_Comparer.Compare(lowAircraft, nullAircraft1) < 0, columnName); } } } } [TestMethod] public void AircraftComparer_Compare_Returns_Correct_Sort_Order_On_Many_Columns() { _Comparer.SortBy.Add(new KeyValuePair<string,bool>(AircraftComparerColumn.Registration, true)); _Comparer.SortBy.Add(new KeyValuePair<string,bool>(AircraftComparerColumn.Altitude, false)); _Lhs.Registration = _Rhs.Registration = null; _Lhs.Altitude = 10000; _Rhs.Altitude = 20000; Assert.IsTrue(_Comparer.Compare(_Lhs, _Rhs) > 0); _Rhs.Registration = "G-VWEB"; Assert.IsTrue(_Comparer.Compare(_Lhs, _Rhs) < 0); } [TestMethod] public void AircraftComparer_Compare_Copes_When_Comparing_Distances_For_Unknown_Browser_Location() { _Comparer.SortBy.Add(new KeyValuePair<string,bool>(AircraftComparerColumn.DistanceFromHere, true)); _Comparer.BrowserLocation = null; _Lhs.Latitude = _Lhs.Longitude = 1; _Rhs.Latitude = _Rhs.Longitude = 2; Assert.AreEqual(0, _Comparer.Compare(_Lhs, _Rhs)); } [TestMethod] public void AircraftComparer_Compare_Treats_Unknown_Sort_Columns_As_FirstSeen() { _Comparer.SortBy.Add(new KeyValuePair<string,bool>("THIS IS GIBBERISH", true)); _Comparer.BrowserLocation = null; _Lhs.FirstSeen = new DateTime(2001, 12, 31); _Rhs.FirstSeen = new DateTime(1999, 12, 31); Assert.IsTrue(_Comparer.Compare(_Lhs, _Rhs) > 0); Assert.IsTrue(_Comparer.Compare(_Rhs, _Lhs) < 0); } [TestMethod] public void AircraftComparer_Compare_Uses_PrecalculatedDistances_When_Available() { _Comparer.SortBy.Add(new KeyValuePair<string,bool>(AircraftComparerColumn.DistanceFromHere, true)); _Comparer.BrowserLocation = new Coordinate(0, 0); _Lhs.UniqueId = 1; _Rhs.UniqueId = 2; _Lhs.Latitude = _Lhs.Longitude = 1; // about 157 km _Rhs.Latitude = _Rhs.Longitude = 2; // about 314 km Assert.IsTrue(_Comparer.Compare(_Lhs, _Rhs) < 0); _Comparer.PrecalculatedDistances.Add(_Rhs.UniqueId, 100); Assert.IsTrue(_Comparer.Compare(_Lhs, _Rhs) > 0); _Comparer.PrecalculatedDistances.Add(_Lhs.UniqueId, null); Assert.IsTrue(_Comparer.Compare(_Lhs, _Rhs) < 0); _Comparer.PrecalculatedDistances[_Rhs.UniqueId] = null; Assert.IsTrue(_Comparer.Compare(_Lhs, _Rhs) == 0); } [TestMethod] public void AircraftComparer_Compare_NumberOfEngines_Sorts_By_Engine_Type_When_Equal() { _Comparer.SortBy.Add(new KeyValuePair<string,bool>(AircraftComparerColumn.NumberOfEngines, true)); _Lhs.EngineType = EngineType.Electric; _Rhs.EngineType = EngineType.Jet; Assert.IsTrue(_Comparer.Compare(_Lhs, _Rhs) < 0); Assert.IsTrue(_Comparer.Compare(_Rhs, _Lhs) > 0); _Comparer.SortBy[0] = new KeyValuePair<string,bool>(AircraftComparerColumn.NumberOfEngines, false); Assert.IsTrue(_Comparer.Compare(_Lhs, _Rhs) > 0); Assert.IsTrue(_Comparer.Compare(_Rhs, _Lhs) < 0); _Rhs.EngineType = EngineType.Electric; Assert.AreEqual(0, _Comparer.Compare(_Lhs, _Rhs)); } #endregion } }
57.261261
750
0.636407
[ "BSD-3-Clause" ]
AlexAX135/vrs
Test/Test.VirtualRadar.Library/AircraftComparerTests.cs
12,715
C#
using OpenAC.Net.DFe.Core.Common; namespace OpenAC.Net.NFSe.Test { public class SetupOpenNFSe { #region Fields private static OpenNFSe ginfes; private static OpenNFSe sigiss; #endregion Fields #region Properties public static OpenNFSe Ginfes => ginfes ?? (ginfes = GetGinfes()); public static OpenNFSe Sigiss => sigiss ?? (sigiss = GetSigiss()); #endregion Properties #region Setup private static OpenNFSe GetGinfes() { var openNFSe = new OpenNFSe(); //Salvar os arquivos openNFSe.Configuracoes.Geral.Salvar = true; openNFSe.Configuracoes.Arquivos.Salvar = true; //webservices //Configure os dados da cidade e do Certificado aqui openNFSe.Configuracoes.WebServices.Ambiente = DFeTipoAmbiente.Homologacao; openNFSe.Configuracoes.WebServices.CodigoMunicipio = 3543402; openNFSe.Configuracoes.Certificados.Certificado = "4E009FA5F9CABB8F"; openNFSe.Configuracoes.Certificados.Senha = ""; openNFSe.Configuracoes.PrestadorPadrao.CpfCnpj = "03514896000115"; openNFSe.Configuracoes.PrestadorPadrao.InscricaoMunicipal = "85841"; return openNFSe; } private static OpenNFSe GetSigiss() { var openNFSe = new OpenNFSe(); //Salvar os arquivos openNFSe.Configuracoes.Geral.Salvar = false; openNFSe.Configuracoes.Arquivos.Salvar = false; //prestador openNFSe.Configuracoes.PrestadorPadrao.CpfCnpj = "37761587000161"; //webservices //Configure os dados da cidade e do Certificado aqui openNFSe.Configuracoes.WebServices.Ambiente = DFeTipoAmbiente.Producao; openNFSe.Configuracoes.WebServices.CodigoMunicipio = 3529005; openNFSe.Configuracoes.WebServices.Usuario = "888888";//USUARIO openNFSe.Configuracoes.WebServices.Senha = "123456";//SENHA return openNFSe; } #endregion Setup } }
30.571429
86
0.631308
[ "MIT" ]
Desenv5DigiByte/OpenAC.Net.NFSe
src/OpenAC.Net.NFSe.Test/SetupOpenNFSe.cs
2,142
C#
 public interface IInventory { long TotalAgilityBonus { get; } long TotalDamageBonus { get; } long TotalHitPointsBonus { get; } long TotalIntelligenceBonus { get; } long TotalStrengthBonus { get; } void AddCommonItem(IItem item); void AddRecipeItem(IRecipe recipe); }
22.923077
40
0.697987
[ "MIT" ]
BorislavBarov/OOP-Advanced-With-C-Sharp
ExamPreparation/HellExam16Aug2017/Hell/Interfaces/IInventory.cs
300
C#
using Xunit; namespace Silk.NET.Vulkan.Tests; public class TestChainExtensionsAny { [Fact] public unsafe void TestAddNextUnchecked() { var accelerationStructureFeatures = new PhysicalDeviceAccelerationStructureFeaturesKHR(); accelerationStructureFeatures .AddNextAny(out PhysicalDeviceDescriptorIndexingFeatures indexingFeatures) .AddNextAny(out DeviceCreateInfo deviceCreateInfo); // Ensure all pointers set correctly Assert.Equal((nint) (&indexingFeatures), (nint) accelerationStructureFeatures.PNext); Assert.Equal((nint) (&deviceCreateInfo), (nint) indexingFeatures.PNext); Assert.Equal(0, (nint) deviceCreateInfo.PNext); // Ensure all STypes set correctly Assert.Equal(StructureType.PhysicalDeviceAccelerationStructureFeaturesKhr, accelerationStructureFeatures.SType); Assert.Equal(StructureType.PhysicalDeviceDescriptorIndexingFeatures, indexingFeatures.SType); Assert.Equal(StructureType.DeviceCreateInfo, deviceCreateInfo.SType); // Check indices Assert.Equal(1, accelerationStructureFeatures.IndexOfAny(ref indexingFeatures)); Assert.Equal(2, accelerationStructureFeatures.IndexOfAny(ref deviceCreateInfo)); } }
42.366667
120
0.75059
[ "MIT" ]
Ar37-rs/Silk.NET
src/Vulkan/Silk.NET.Vulkan.Tests/TestChainExtensionsAny.cs
1,273
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.XR; public class disableSteamVR : MonoBehaviour { // Start is called before the first frame update void Start() { XRSettings.LoadDeviceByName(""); XRSettings.enabled = false; } // Update is called once per frame void Update() { } }
18.52381
52
0.652956
[ "Unlicense" ]
3632741/AR-Registration-Framework
OST Registration/Server/disableSteamVR.cs
391
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using AutoMapper; using Microsoft.Azure.Commands.Common.Authentication; using Microsoft.Azure.Commands.Common.Authentication.Models; using Microsoft.Azure.Commands.Compute.Common; using Microsoft.Azure.Commands.Compute.Extension.AEM; using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Azure.Management.Storage; using Microsoft.Azure.Management.Storage.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using System.Text.RegularExpressions; namespace Microsoft.Azure.Commands.Compute { [Cmdlet( "Test", ProfileNouns.VirtualMachineAEMExtension)] [OutputType(typeof(AEMTestResult))] public class TestAzureRmVMAEMExtension : VirtualMachineExtensionBaseCmdlet { private AEMHelper _Helper = null; [Parameter( Mandatory = true, Position = 0, ValueFromPipelineByPropertyName = true, HelpMessage = "The resource group name.")] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Alias("ResourceName")] [Parameter( Mandatory = true, Position = 1, ValueFromPipelineByPropertyName = true, HelpMessage = "The virtual machine name.")] [ValidateNotNullOrEmpty] public string VMName { get; set; } [Parameter( Mandatory = false, Position = 2, ValueFromPipelineByPropertyName = false, HelpMessage = "Operating System Type of the virtual machines. Possible values: Windows | Linux")] public string OSType { get; set; } [Parameter( Mandatory = false, Position = 3, ValueFromPipelineByPropertyName = false, HelpMessage = "Time that should be waited for the Strorage Metrics or Diagnostics data to be available in minutes. Default is 15 minutes")] public int WaitTimeInMinutes { get; set; } [Parameter( Mandatory = false, Position = 4, ValueFromPipelineByPropertyName = false, HelpMessage = "Disables the test for table content")] public SwitchParameter SkipStorageCheck { get; set; } public TestAzureRmVMAEMExtension() { this.WaitTimeInMinutes = 15; } public override void ExecuteCmdlet() { this._Helper = new AEMHelper((err) => this.WriteError(err), (msg) => this.WriteVerbose(msg), (msg) => this.WriteWarning(msg), this.CommandRuntime.Host.UI, AzureSession.ClientFactory.CreateArmClient<StorageManagementClient>(DefaultProfile.Context, AzureEnvironment.Endpoint.ResourceManager), this.DefaultContext.Subscription); this._Helper.WriteVerbose("Starting TestAzureRmVMAEMExtension"); base.ExecuteCmdlet(); ExecuteClientAction(() => { AEMTestResult rootResult = new AEMTestResult(); rootResult.TestName = "Azure Enhanced Monitoring Test"; //################################################# //# Check if VM exists //################################################# this._Helper.WriteHost("VM Existance check for {0} ...", false, this.VMName); var selectedVM = this.ComputeClient.ComputeManagementClient.VirtualMachines.Get(this.ResourceGroupName, this.VMName); var selectedVMStatus = this.ComputeClient.ComputeManagementClient.VirtualMachines.GetWithInstanceView(this.ResourceGroupName, this.VMName).Body.InstanceView; if (selectedVM == null) { rootResult.PartialResults.Add(new AEMTestResult("VM Existance check for {0}", false, this.VMName)); this._Helper.WriteHost("NOT OK ", ConsoleColor.Red); return; } else { rootResult.PartialResults.Add(new AEMTestResult("VM Existance check for {0}", true, this.VMName)); this._Helper.WriteHost("OK ", ConsoleColor.Green); } //################################################# //################################################# var osdisk = selectedVM.StorageProfile.OsDisk; if (String.IsNullOrEmpty(this.OSType)) { this.OSType = osdisk.OsType.ToString(); } if (String.IsNullOrEmpty(this.OSType)) { this._Helper.WriteError("Could not determine Operating System of the VM. Please provide the Operating System type ({0} or {1}) via parameter OSType", AEMExtensionConstants.OSTypeWindows, AEMExtensionConstants.OSTypeLinux); return; } //################################################# //# Check for Guest Agent //################################################# this._Helper.WriteHost("VM Guest Agent check...", false); var vmAgentStatus = false; //# It is not possible to detect if VM Agent is installed on ARM vmAgentStatus = true; if (!vmAgentStatus) { rootResult.PartialResults.Add(new AEMTestResult("VM Guest Agent check", false)); this._Helper.WriteHost("NOT OK ", ConsoleColor.Red); this._Helper.WriteWarning(AEMExtensionConstants.MissingGuestAgentWarning); return; } else { rootResult.PartialResults.Add(new AEMTestResult("VM Guest Agent check", true)); this._Helper.WriteHost("OK ", ConsoleColor.Green); } //################################################# //################################################# //################################################# //# Check for Azure Enhanced Monitoring Extension for SAP //################################################# this._Helper.WriteHost("Azure Enhanced Monitoring Extension for SAP Installation check...", false); string monPublicConfig = null; var monExtension = this._Helper.GetExtension(selectedVM, AEMExtensionConstants.AEMExtensionType[this.OSType], AEMExtensionConstants.AEMExtensionPublisher[this.OSType]); if (monExtension != null) { monPublicConfig = monExtension.Settings.ToString(); } if (monExtension == null || String.IsNullOrEmpty(monPublicConfig)) { rootResult.PartialResults.Add(new AEMTestResult("Azure Enhanced Monitoring Extension for SAP Installation check", false)); this._Helper.WriteHost("NOT OK ", ConsoleColor.Red); } else { rootResult.PartialResults.Add(new AEMTestResult("Azure Enhanced Monitoring Extension for SAP Installation check", true)); this._Helper.WriteHost("OK ", ConsoleColor.Green); } //################################################# //################################################# var accounts = new List<string>(); //var osdisk = selectedVM.StorageProfile.OsDisk; var osaccountName = String.Empty; if (osdisk.ManagedDisk == null) { var accountName = this._Helper.GetStorageAccountFromUri(osdisk.Vhd.Uri); osaccountName = accountName; accounts.Add(accountName); } else { this._Helper.WriteWarning("[WARN] Managed Disks are not yet supported. Extension will be installed but no disk metrics will be available."); } var dataDisks = selectedVM.StorageProfile.DataDisks; foreach (var disk in dataDisks) { if (disk.ManagedDisk != null) { this._Helper.WriteWarning("[WARN] Managed Disks are not yet supported. Extension will be installed but no disk metrics will be available."); continue; } var accountName = this._Helper.GetStorageAccountFromUri(disk.Vhd.Uri); if (!accounts.Contains(accountName)) { accounts.Add(accountName); } } //################################################# //# Check storage metrics //################################################# this._Helper.WriteHost("Storage Metrics check..."); var metricsResult = new AEMTestResult("Storage Metrics check"); rootResult.PartialResults.Add(metricsResult); if (!this.SkipStorageCheck.IsPresent) { foreach (var account in accounts) { var accountResult = new AEMTestResult("Storage Metrics check for {0}", account); metricsResult.PartialResults.Add(accountResult); this._Helper.WriteHost("\tStorage Metrics check for {0}...", account); var storage = this._Helper.GetStorageAccountFromCache(account); if (!this._Helper.IsPremiumStorageAccount(storage)) { this._Helper.WriteHost("\t\tStorage Metrics configuration check for {0}...", false, account); var currentConfig = this._Helper.GetStorageAnalytics(account); bool storageConfigOk = false; if (!this._Helper.CheckStorageAnalytics(account, currentConfig)) { accountResult.PartialResults.Add(new AEMTestResult("Storage Metrics configuration check for {0}", false, account)); this._Helper.WriteHost("NOT OK ", ConsoleColor.Red); } else { accountResult.PartialResults.Add(new AEMTestResult("Storage Metrics configuration check for {0}", true, account)); this._Helper.WriteHost("OK ", ConsoleColor.Green); storageConfigOk = true; } this._Helper.WriteHost("\t\tStorage Metrics data check for {0}...", false, account); var filterMinute = Microsoft.WindowsAzure.Storage.Table.TableQuery. GenerateFilterConditionForDate("Timestamp", "gt", DateTime.Now.AddMinutes(AEMExtensionConstants.ContentAgeInMinutes * -1)); if (storageConfigOk && this._Helper.CheckTableAndContent(account, "$MetricsMinutePrimaryTransactionsBlob", filterMinute, ".", false, this.WaitTimeInMinutes)) { this._Helper.WriteHost("OK ", ConsoleColor.Green); accountResult.PartialResults.Add(new AEMTestResult("Storage Metrics data check for {0}", true, account)); } else { accountResult.PartialResults.Add(new AEMTestResult("Storage Metrics data check for {0}", false, account)); this._Helper.WriteHost("NOT OK ", ConsoleColor.Red); } } else { accountResult.PartialResults.Add(new AEMTestResult("Storage Metrics not available for Premium Storage account {0}", true, account)); this._Helper.WriteHost("\t\tStorage Metrics not available for Premium Storage account {0}...", false, account); this._Helper.WriteHost("OK ", ConsoleColor.Green); } } } else { metricsResult.Result = true; this._Helper.WriteHost("Skipped ", ConsoleColor.Yellow); } //################################################# //################################################# //################################################# //# Check Azure Enhanced Monitoring Extension for SAP Configuration //################################################# this._Helper.WriteHost("Azure Enhanced Monitoring Extension for SAP public configuration check...", false); var aemConfigResult = new AEMTestResult("Azure Enhanced Monitoring Extension for SAP public configuration check"); rootResult.PartialResults.Add(aemConfigResult); JObject sapmonPublicConfig = null; if (monExtension != null) { this._Helper.WriteHost(""); //New Line sapmonPublicConfig = JsonConvert.DeserializeObject(monPublicConfig) as JObject; StorageAccount storage = null; var osaccountIsPremium = false; if (!String.IsNullOrEmpty(osaccountName)) { storage = this._Helper.GetStorageAccountFromCache(osaccountName); osaccountIsPremium = this._Helper.IsPremiumStorageAccount(osaccountName); } var vmSize = selectedVM.HardwareProfile.VmSize; this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Size", "vmsize", sapmonPublicConfig, vmSize, aemConfigResult); this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Memory", "vm.memory.isovercommitted", sapmonPublicConfig, 0, aemConfigResult); this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM CPU", "vm.cpu.isovercommitted", sapmonPublicConfig, 0, aemConfigResult); this._Helper.MonitoringPropertyExists("Azure Enhanced Monitoring Extension for SAP public configuration check: Script Version", "script.version", sapmonPublicConfig, aemConfigResult); var vmSLA = this._Helper.GetVMSLA(selectedVM); if (vmSLA.HasSLA) { this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM SLA IOPS", "vm.sla.iops", sapmonPublicConfig, vmSLA.IOPS, aemConfigResult); this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM SLA Throughput", "vm.sla.throughput", sapmonPublicConfig, vmSLA.TP, aemConfigResult); } int wadEnabled; if (this._Helper.GetMonPropertyValue("wad.isenabled", sapmonPublicConfig, out wadEnabled)) { if (wadEnabled == 1) { this._Helper.MonitoringPropertyExists("Azure Enhanced Monitoring Extension for SAP public configuration check: WAD name", "wad.name", sapmonPublicConfig, aemConfigResult); this._Helper.MonitoringPropertyExists("Azure Enhanced Monitoring Extension for SAP public configuration check: WAD URI", "wad.uri", sapmonPublicConfig, aemConfigResult); } else { this._Helper.MonitoringPropertyExists("Azure Enhanced Monitoring Extension for SAP public configuration check: WAD name", "wad.name", sapmonPublicConfig, aemConfigResult, false); this._Helper.MonitoringPropertyExists("Azure Enhanced Monitoring Extension for SAP public configuration check: WAD URI", "wad.uri", sapmonPublicConfig, aemConfigResult, false); } } else { string message = "Azure Enhanced Monitoring Extension for SAP public configuration check:"; aemConfigResult.PartialResults.Add(new AEMTestResult(message, false)); this._Helper.WriteHost(message + "...", false); this._Helper.WriteHost("NOT OK ", ConsoleColor.Red); } if (!osaccountIsPremium && storage != null) { var endpoint = this._Helper.GetAzureSAPTableEndpoint(storage); var minuteUri = endpoint + "$MetricsMinutePrimaryTransactionsBlob"; this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS disk URI Key", "osdisk.connminute", sapmonPublicConfig, osaccountName + ".minute", aemConfigResult); //# TODO: check uri config this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS disk URI Value", osaccountName + ".minute.uri", sapmonPublicConfig, minuteUri, aemConfigResult); this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS disk URI Name", osaccountName + ".minute.name", sapmonPublicConfig, osaccountName, aemConfigResult); this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS Disk Type", "osdisk.type", sapmonPublicConfig, AEMExtensionConstants.DISK_TYPE_STANDARD, aemConfigResult); } else if (storage != null) { var sla = this._Helper.GetDiskSLA(osdisk); this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS Disk Type", "osdisk.type", sapmonPublicConfig, AEMExtensionConstants.DISK_TYPE_PREMIUM, aemConfigResult); this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS Disk SLA IOPS", "osdisk.sla.throughput", sapmonPublicConfig, sla.TP, aemConfigResult); this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS Disk SLA Throughput", "osdisk.sla.iops", sapmonPublicConfig, sla.IOPS, aemConfigResult); } else { this._Helper.WriteWarning("[WARN] Managed Disks are not yet supported. Extension will be installed but no disk metrics will be available."); } if (osdisk.ManagedDisk == null) { this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM OS disk name", "osdisk.name", sapmonPublicConfig, this._Helper.GetDiskName(osdisk.Vhd.Uri), aemConfigResult); } var diskNumber = 1; foreach (var disk in dataDisks) { if (disk.ManagedDisk != null) { this._Helper.WriteWarning("[WARN] Managed Disks are not yet supported. Extension will be installed but no disk metrics will be available."); continue; } var accountName = this._Helper.GetStorageAccountFromUri(disk.Vhd.Uri); storage = this._Helper.GetStorageAccountFromCache(accountName); var accountIsPremium = this._Helper.IsPremiumStorageAccount(storage); this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " LUN", "disk.lun." + diskNumber, sapmonPublicConfig, disk.Lun, aemConfigResult); if (!accountIsPremium) { var endpoint = this._Helper.GetAzureSAPTableEndpoint(storage); var minuteUri = endpoint + "$MetricsMinutePrimaryTransactionsBlob"; this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " URI Key", "disk.connminute." + diskNumber, sapmonPublicConfig, accountName + ".minute", aemConfigResult); this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " URI Value", accountName + ".minute.uri", sapmonPublicConfig, minuteUri, aemConfigResult); this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " URI Name", accountName + ".minute.name", sapmonPublicConfig, accountName, aemConfigResult); this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " Type", "disk.type." + diskNumber, sapmonPublicConfig, AEMExtensionConstants.DISK_TYPE_STANDARD, aemConfigResult); } else { var sla = this._Helper.GetDiskSLA(disk); this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " Type", "disk.type." + diskNumber, sapmonPublicConfig, AEMExtensionConstants.DISK_TYPE_PREMIUM, aemConfigResult); this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " SLA IOPS", "disk.sla.throughput." + diskNumber, sapmonPublicConfig, sla.TP, aemConfigResult); this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " SLA Throughput", "disk.sla.iops." + diskNumber, sapmonPublicConfig, sla.IOPS, aemConfigResult); } this._Helper.CheckMonitoringProperty("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disk " + diskNumber + " name", "disk.name." + diskNumber, sapmonPublicConfig, this._Helper.GetDiskName(disk.Vhd.Uri), aemConfigResult); diskNumber += 1; } if (dataDisks.Count == 0) { aemConfigResult.PartialResults.Add(new AEMTestResult("Azure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disks", true)); this._Helper.WriteHost("\tAzure Enhanced Monitoring Extension for SAP public configuration check: VM Data Disks ", false); this._Helper.WriteHost("OK ", ConsoleColor.Green); } } else { aemConfigResult.Result = false; this._Helper.WriteHost("NOT OK ", ConsoleColor.Red); } //################################################# //################################################# //################################################# //# Check WAD Configuration //################################################# int iswadEnabled; if (this._Helper.GetMonPropertyValue("wad.isenabled", sapmonPublicConfig, out iswadEnabled) && iswadEnabled == 1) { var wadConfigResult = new AEMTestResult("IaaSDiagnostics check"); rootResult.PartialResults.Add(wadConfigResult); string wadPublicConfig = null; var wadExtension = this._Helper.GetExtension(selectedVM, AEMExtensionConstants.WADExtensionType[this.OSType], AEMExtensionConstants.WADExtensionPublisher[this.OSType]); if (wadExtension != null) { wadPublicConfig = wadExtension.Settings.ToString(); } this._Helper.WriteHost("IaaSDiagnostics check...", false); if (wadExtension != null) { this._Helper.WriteHost(""); //New Line this._Helper.WriteHost("\tIaaSDiagnostics configuration check...", false); var currentJSONConfig = JsonConvert.DeserializeObject(wadPublicConfig) as Newtonsoft.Json.Linq.JObject; var base64 = currentJSONConfig["xmlCfg"] as Newtonsoft.Json.Linq.JValue; System.Xml.XmlDocument currentConfig = new System.Xml.XmlDocument(); currentConfig.LoadXml(Encoding.UTF8.GetString(System.Convert.FromBase64String(base64.Value.ToString()))); if (!this._Helper.CheckWADConfiguration(currentConfig)) { wadConfigResult.PartialResults.Add(new AEMTestResult("IaaSDiagnostics configuration check", false)); this._Helper.WriteHost("NOT OK ", ConsoleColor.Red); } else { wadConfigResult.PartialResults.Add(new AEMTestResult("IaaSDiagnostics configuration check", true)); this._Helper.WriteHost("OK ", ConsoleColor.Green); } this._Helper.WriteHost("\tIaaSDiagnostics performance counters check..."); var wadPerfCountersResult = new AEMTestResult("IaaSDiagnostics performance counters check"); wadConfigResult.PartialResults.Add(wadPerfCountersResult); foreach (var perfCounter in AEMExtensionConstants.PerformanceCounters[this.OSType]) { this._Helper.WriteHost("\t\tIaaSDiagnostics performance counters " + (perfCounter.counterSpecifier) + "check...", false); var currentCounter = currentConfig.SelectSingleNode("/WadCfg/DiagnosticMonitorConfiguration/PerformanceCounters/PerformanceCounterConfiguration[@counterSpecifier = '" + perfCounter.counterSpecifier + "']"); if (currentCounter != null) { wadPerfCountersResult.PartialResults.Add(new AEMTestResult("IaaSDiagnostics performance counters " + (perfCounter.counterSpecifier) + "check...", true)); this._Helper.WriteHost("OK ", ConsoleColor.Green); } else { wadPerfCountersResult.PartialResults.Add(new AEMTestResult("IaaSDiagnostics performance counters " + (perfCounter.counterSpecifier) + "check...", false)); this._Helper.WriteHost("NOT OK ", ConsoleColor.Red); } } string wadstorage; if (!this._Helper.GetMonPropertyValue<string>("wad.name", sapmonPublicConfig, out wadstorage)) { wadstorage = null; } this._Helper.WriteHost("\tIaaSDiagnostics data check...", false); var deploymentId = String.Empty; var roleName = String.Empty; var extStatuses = this._Helper.GetExtension(selectedVM, selectedVMStatus, AEMExtensionConstants.AEMExtensionType[this.OSType], AEMExtensionConstants.AEMExtensionPublisher[this.OSType]); InstanceViewStatus aemStatus = null; if (extStatuses != null && extStatuses.Statuses != null) { aemStatus = extStatuses.Statuses.FirstOrDefault(stat => Regex.Match(stat.Message, "deploymentId=(\\S*) roleInstance=(\\S*)").Success); } if (aemStatus != null) { var match = Regex.Match(aemStatus.Message, "deploymentId=(\\S*) roleInstance=(\\S*)"); deploymentId = match.Groups[1].Value; roleName = match.Groups[2].Value; } else { this._Helper.WriteWarning("DeploymentId and RoleInstanceName could not be parsed from extension status"); } var ok = false; if (!this.SkipStorageCheck.IsPresent && (!String.IsNullOrEmpty(deploymentId)) && (!String.IsNullOrEmpty(roleName)) && (!String.IsNullOrEmpty(wadstorage))) { if (this.OSType.Equals(AEMExtensionConstants.OSTypeLinux, StringComparison.InvariantCultureIgnoreCase)) { ok = this._Helper.CheckDiagnosticsTable(wadstorage, deploymentId, selectedVM.OsProfile.ComputerName, ".", this.OSType, this.WaitTimeInMinutes); } else { string filterMinute = "Role eq '" + AEMExtensionConstants.ROLECONTENT + "' and DeploymentId eq '" + deploymentId + "' and RoleInstance eq '" + roleName + "' and PartitionKey gt '0" + DateTime.UtcNow.AddMinutes(AEMExtensionConstants.ContentAgeInMinutes * -1).Ticks + "'"; ok = this._Helper.CheckTableAndContent(wadstorage, AEMExtensionConstants.WadTableName, filterMinute, ".", false, this.WaitTimeInMinutes); } } if (ok && !this.SkipStorageCheck.IsPresent) { wadConfigResult.PartialResults.Add(new AEMTestResult("IaaSDiagnostics data check", true)); this._Helper.WriteHost("OK ", ConsoleColor.Green); } else if (!this.SkipStorageCheck.IsPresent) { wadConfigResult.PartialResults.Add(new AEMTestResult("IaaSDiagnostics data check", false)); this._Helper.WriteHost("NOT OK ", ConsoleColor.Red); } else { this._Helper.WriteHost("Skipped ", ConsoleColor.Yellow); } } else { wadConfigResult.Result = false; this._Helper.WriteHost("NOT OK ", ConsoleColor.Red); } } //################################################# //################################################# if (!rootResult.Result) { this._Helper.WriteHost("The script found some configuration issues. Please run the Set-AzureRmVMExtension commandlet to update the configuration of the virtual machine!"); } this._Helper.WriteVerbose("TestAzureRmVMAEMExtension Done (" + rootResult.Result + ")"); var result = Mapper.Map<AEMTestResult>(rootResult); WriteObject(result); }); } } }
60.478947
284
0.530415
[ "MIT" ]
NonStatic2014/azure-powershell
src/ResourceManager/Compute/Commands.Compute/Extension/AEM/TestAzureRmVMAEMExtension.cs
33,906
C#
using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; namespace KonoeStudio.Libs.Hid { public interface IHidDevice : IDisposable { IHidDeviceInfo DeviceInfo { get; } bool IsReadOpened { get; } bool IsWriteOpened { get; } Task<byte[]> ReadRawDataAsync(); Task<byte[]> ReadRawDataAsync(CancellationToken token); Task WriteRawDataAsync(byte[] data); Task WriteRawDataAsync(byte[] data, CancellationToken token); bool ReadOpen(); bool WriteOpen(); void ReadClose(); void WriteClose(); } }
27.652174
69
0.65566
[ "MIT" ]
18konoe/KonoeStudio.Libs.Hid
KonoeStudio.Libs.Hid/IHidDevice.cs
638
C#
namespace MyFirstGetAPI.Areas.HelpPage.ModelDescriptions { public class SimpleTypeModelDescription : ModelDescription { } }
22.5
62
0.777778
[ "MIT" ]
JKafka97/MyFirstProject-C_Sharp
MyFirstGetAPI/Areas/HelpPage/ModelDescriptions/SimpleTypeModelDescription.cs
135
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. namespace Cake.Common.Tools.ReportGenerator; /// <summary> /// Represents ReportGenerator's logging verbosity. /// </summary> public enum ReportGeneratorVerbosity { /// <summary> /// Verbosity: Verbose. /// </summary> Verbose = 1, /// <summary> /// Verbosity: Info. /// </summary> Info = 2, /// <summary> /// Verbosity: Error. /// </summary> Error = 3 }
23.423077
71
0.638752
[ "MIT" ]
ecampidoglio/cake
src/Cake.Common/Tools/ReportGenerator/ReportGeneratorVerbosity.cs
611
C#
using System.Collections.Generic; using System.Linq; namespace MarkEmbling.Grammar.Rules { /// <summary> /// Basic rule which ensures uncountable words do not get swapped or modified. /// </summary> public class PluralUncountableCasesRule : IGrammarTransformRule { private readonly string[] _uncountables = new [] { "deer", "sheep" }; public bool CanTransform(string input) { return _uncountables.Contains(input.ToLowerInvariant()); } public string Transform(string input) { return input; } } }
27.863636
82
0.619902
[ "MIT" ]
markembling/MarkEmbling.Grammar
src/MarkEmbling.Grammar/Rules/PluralUncountableCasesRule.cs
613
C#
using System; using System.Runtime.InteropServices; using static QuickJS.Native.QuickJSNativeApi; namespace QuickJS.Native { /// <summary> /// Represents a pointer to a native JSContext /// </summary> [StructLayout(LayoutKind.Sequential)] public struct JSContext { private unsafe void* _context; /// <summary> /// A read-only field that represents a null pointer to the native JSContext. /// </summary> public static readonly JSContext Null = default; /// <summary> /// Throws the actual exception that is stored in the native JSContext. /// </summary> /// <remarks> /// If there is no pending exception in the context, the method returns /// without creating or throwing an exception. /// </remarks> public unsafe void ThrowPendingException() { if (_context == null) return; JSValue exceptionVal = JS_GetException(this); if (exceptionVal.Tag == JSTag.Null) return; try { if (ErrorInfo.TryCreate(this, exceptionVal, out ErrorInfo errorInfo)) throw new QuickJSException(errorInfo); throw new QuickJSException(exceptionVal.ToString(this)); } finally { JS_FreeValue(this, exceptionVal); } } internal unsafe void ThrowPendingException(Exception innerException) { if (_context == null) return; JSValue exceptionVal = JS_GetException(this); if (exceptionVal.Tag == JSTag.Null) return; try { if (ErrorInfo.TryCreate(this, exceptionVal, out ErrorInfo errorInfo)) throw new QuickJSException(errorInfo, innerException); throw new QuickJSException(exceptionVal.ToString(this)); } finally { JS_FreeValue(this, exceptionVal); } } /// <inheritdoc/> public unsafe override int GetHashCode() { return new IntPtr(_context).GetHashCode(); } /// <inheritdoc/> public unsafe override bool Equals(object obj) { if (obj is JSContext a) return a._context == _context; return false; } /// <summary> /// Converts the value of this instance to a pointer to a an /// unspecified type. /// </summary> /// <returns> /// A pointer to <see cref="void"/>; that is, a pointer to memory /// containing data of an unspecified type. /// </returns> public unsafe void* ToPointer() { return _context; } /// <summary> /// Compares two <see cref="JSContext"/> objects. The result specifies /// whether the values of the two <see cref="JSContext"/> objects are /// equal. /// </summary> /// <param name="left">A <see cref="JSContext"/> to compare.</param> /// <param name="right">A <see cref="JSContext"/> to compare.</param> /// <returns> /// true if <paramref name="left"/> and <paramref name="right"/> are /// equal; otherwise, false. /// </returns> public static unsafe bool operator ==(JSContext left, JSContext right) { return left._context == right._context; } /// <summary> /// Compares two <see cref="JSContext"/> objects. The result specifies /// whether the values of the two <see cref="JSContext"/> objects are /// unequal. /// </summary> /// <param name="left">A <see cref="JSContext"/> to compare.</param> /// <param name="right">A <see cref="JSContext"/> to compare.</param> /// <returns> /// true if <paramref name="left"/> and <paramref name="right"/> are /// unequal; otherwise, false. /// </returns> public static unsafe bool operator !=(JSContext left, JSContext right) { return left._context != right._context; } } }
26.340909
79
0.662928
[ "MIT" ]
vmas/QuickJS.NET
QuickJS.NET/Native/JSContext.cs
3,479
C#
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Newtonsoft.Json.Tests.Documentation.Samples.Serializer { public class JsonPropertyOrder { #region Types public class Account { public string EmailAddress { get; set; } // appear last [JsonProperty(Order = 1)] public bool Deleted { get; set; } [JsonProperty(Order = 2)] public DateTime DeletedDate { get; set; } public DateTime CreatedDate { get; set; } public DateTime UpdatedDate { get; set; } // appear first [JsonProperty(Order = -2)] public string FullName { get; set; } } #endregion public void Example() { #region Usage Account account = new Account { FullName = "Aaron Account", EmailAddress = "aaron@example.com", Deleted = true, DeletedDate = new DateTime(2013, 1, 25), UpdatedDate = new DateTime(2013, 1, 25), CreatedDate = new DateTime(2010, 10, 1) }; string json = JsonConvert.SerializeObject(account, Formatting.Indented); Console.WriteLine(json); // { // "FullName": "Aaron Account", // "EmailAddress": "aaron@example.com", // "CreatedDate": "2010-10-01T00:00:00", // "UpdatedDate": "2013-01-25T00:00:00", // "Deleted": true, // "DeletedDate": "2013-01-25T00:00:00" // } #endregion } } }
34.385542
84
0.610021
[ "MIT" ]
abrodersen/Newtonsoft.Json
Src/Newtonsoft.Json.Tests/Documentation/Samples/Serializer/JsonPropertyOrder.cs
2,856
C#
namespace _15.Fast_Prime_Checker { using System; public class FastPrimeChecker { public static void Main() { int ___Do___ = int.Parse(Console.ReadLine()); for (int DAVIDIM = 2; DAVIDIM <= ___Do___; DAVIDIM++) { bool TowaLIE = true; for (int delio = 2; delio <= Math.Sqrt(DAVIDIM); delio++) { if (DAVIDIM % delio == 0) { TowaLIE = false; break; } } Console.WriteLine($"{DAVIDIM} -> {TowaLIE}"); } } } }
26.269231
73
0.398243
[ "MIT" ]
spzvtbg/02-Tech-modul
Fundamental task solutions/05.Data Types and Variables - Exercises/15. Fast Prime Checker/FastPrimeChecker.cs
685
C#
using System; namespace Cuemon { /// <summary> /// Provides a mechanism for releasing both managed and unmanaged resources with focus on the former. /// Implements the <see cref="IDisposable" /> /// </summary> /// <seealso cref="IDisposable" /> public abstract class Disposable : IDisposable { /// <summary> /// Gets a value indicating whether this <see cref="Disposable"/> object is disposed. /// </summary> /// <value><c>true</c> if this <see cref="Disposable"/> object is disposed; otherwise, <c>false</c>.</value> public bool Disposed { get; private set; } /// <summary> /// Called when this object is being disposed by either <see cref="Dispose()"/> or <see cref="Dispose(bool)"/> having <c>disposing</c> set to <c>true</c> and <see cref="Disposed"/> is <c>false</c>. /// </summary> protected abstract void OnDisposeManagedResources(); /// <summary> /// Called when this object is being disposed by either <see cref="Dispose()"/> or <see cref="Dispose(bool)"/> and <see cref="Disposed"/> is <c>false</c>. /// </summary> protected virtual void OnDisposeUnmanagedResources() { } /// <summary> /// Releases all resources used by the <see cref="Disposable"/> object. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases the unmanaged resources used by the <see cref="Disposable"/> object and optionally releases the managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected void Dispose(bool disposing) { if (Disposed) { return; } if (disposing) { OnDisposeManagedResources(); } OnDisposeUnmanagedResources(); Disposed = true; } } }
38.833333
205
0.579399
[ "MIT" ]
gimlichael/Cuemon
src/Cuemon.Core/Disposable.cs
2,099
C#
using System; public class C { public string M() { #if DEBUG return "Debug"; #else return "Release"; #endif } } /* cs using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Security; using System.Security.Permissions; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue | DebuggableAttribute.DebuggingModes.DisableOptimizations)] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] public class C { public string M() { return "Debug"; } } */
27.235294
253
0.731102
[ "BSD-2-Clause" ]
bernd5/SharpLab
source/Tests/Decompilation/TestCode/Preprocessor.IfDebug.cs
926
C#
using System; namespace PasswordQueryTool.ImportModels { /// <summary> /// The possible states an import can be in. /// </summary> public enum ImportState { Unknown, Analyzing, Importing, Canceled, Finished } /// <summary> /// A single instance of an import. /// </summary> public class ImportDTO { /// <summary> /// Gets or sets the amount of total chunks in the job. /// </summary> public long ChunksAmount { get; set; } /// <summary> /// Gets or sets the amount of finished chunks in the job. /// </summary> public long ChunksFinishedAmount { get; set; } /// <summary> /// Gets or sets the id of the import. /// </summary> public Guid Id { get; set; } /// <summary> /// Gets or sets the amount of invalid lines in the job. /// </summary> public long InvalidLines { get; set; } /// <summary> /// Gets or sets the amount of lines that are finished. /// </summary> public long LinesFinished { get; set; } /// <summary> /// Gets or sets the name of the import. /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the current state of the job. /// </summary> public ImportState State { get; set; } } }
20.317647
66
0.437174
[ "MIT" ]
Konstantin-tr/PassSearch
PasswordQueryTool/PasswordQueryTool.ImportModels/ImportDTO.cs
1,729
C#
using Frapid.DataAccess; using Frapid.NPoco; namespace Frapid.Authorization.DTO { [TableName("auth.group_entity_access_policy")] [PrimaryKey("group_entity_access_policy_id", AutoIncrement = true)] public class GroupEntityAccessPolicy : IPoco { public int GroupEntityAccessPolicyId { get; set; } public string EntityName { get; set; } public int OfficeId { get; set; } public int RoleId { get; set; } public int AccessTypeId { get; set; } public bool AllowAccess { get; set; } } }
32.294118
71
0.67031
[ "MIT" ]
denza/frapid
src/Frapid.Web/Areas/Frapid.Authorization/DTO/GroupEntityAccessPolicy.cs
551
C#
using Microsoft.Extensions.ObjectPool; using Newtonsoft.Json; namespace Jasper.Serialization.Json { internal class JsonSerializerObjectPolicy : IPooledObjectPolicy<JsonSerializer> { private readonly JsonSerializerSettings _serializerSettings; public JsonSerializerObjectPolicy(JsonSerializerSettings serializerSettings) { _serializerSettings = serializerSettings; } public JsonSerializer Create() { return JsonSerializer.Create(_serializerSettings); } public bool Return(JsonSerializer serializer) { return true; } } }
25.076923
84
0.679448
[ "MIT" ]
CodingGorilla/jasper
src/Jasper/Serialization/Json/JsonSerializerObjectPolicy.cs
654
C#
namespace Strinken.Tests.FiltersTests; public class UpperFilterTest { [Fact] public void Resolve_Data_ReturnsDataToUpperCase() { var filter = new UpperFilter(); filter.Resolve("data", Array.Empty<string>()).Should().Be("DATA"); } [Fact] public void Validate_NoArguments_ReturnsTrue() { var filter = new UpperFilter(); filter.Validate(null!).Should().BeTrue(); filter.Validate(Array.Empty<string>()).Should().BeTrue(); } [Fact] public void Validate_OneOrMoreArguments_ReturnsFalse() { var filter = new UpperFilter(); filter.Validate(new string[] { "" }).Should().BeFalse(); filter.Validate(new string[] { "", "" }).Should().BeFalse(); } [Fact] public void Resolve_ReturnsResolvedString() { Parser<Data> stringSolver = new Parser<Data>().WithTag(new DataNameTag()); stringSolver.Resolve("The {DataName:Upper} is in the kitchen.", new Data { Name = "Lorem" }).Should().Be("The LOREM is in the kitchen."); } [Fact] public void Validate_ReturnsTrue() { Parser<Data> stringSolver = new Parser<Data>().WithTag(new DataNameTag()); stringSolver.Validate("The {DataName:Upper} is in the kitchen.").IsValid.Should().BeTrue(); } [Fact] public void Resolve_NullString_ReturnsResolvedString() { Parser<Data> stringSolver = new Parser<Data>().WithTag("Null", string.Empty, _ => null!); stringSolver.Resolve("The {Null:Upper} is in the kitchen.", new Data { Name = "Lorem" }).Should().Be("The is in the kitchen."); } }
31.173077
145
0.630475
[ "MIT" ]
k94ll13nn3/Strinken
tests/Strinken.Tests/FiltersTests/UpperFilterTest.cs
1,621
C#
using System.Collections; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class MainMenuScript : MonoBehaviour { private const float AnimationDampening = 0.2f; private readonly Vector3 _mainScreenEndPosition = new Vector3(0, 0, 100); private readonly Vector3 _mainScreenStartPosition = Vector3.zero; private readonly Vector3 _optionScreenEndPosition = Vector3.zero; private readonly Vector3 _optionScreenStartPosition = new Vector3(720, 0); private bool _disableInput; private bool _isOptionShown; [SerializeField] private Button _localDataButton; [SerializeField] private RectTransform _mainScreen; [SerializeField] private RectTransform _optionsScreen; [SerializeField] private Button _rnDataButton; private void Start() { _rnDataButton.onClick.AddListener(delegate { GoToMain(false); }); _localDataButton.onClick.AddListener(delegate { GoToMain(true); }); } /// <summary> /// Go to the main scene. /// </summary> /// <param name="localData">If local data is to be used or data from the React Native app</param> public void GoToMain(bool localData) { PlayerPrefs.SetInt("UseLocalData", localData ? 1 : 0); // 1 is true, 0 is false. PlayerPrefs does not have a SetBool function. SceneManager.LoadScene("Main Scene"); } /// <summary> /// Shows or hides the Options screen. /// </summary> public void GoOptionsOrBack() { if (_disableInput) return; StartCoroutine(AnimateOptions()); } /// <summary> /// Animates showing or hiding of the options screen. /// </summary> private IEnumerator AnimateOptions() { _disableInput = true; if (_isOptionShown) { // Hide Options Screen _isOptionShown = false; while (_optionsScreen.anchoredPosition.x <= 719) { _mainScreen.localPosition = Vector3.Lerp(_mainScreen.localPosition, _mainScreenStartPosition, AnimationDampening); _optionsScreen.anchoredPosition = Vector2.Lerp(_optionsScreen.anchoredPosition, _optionScreenStartPosition, AnimationDampening); yield return new WaitForEndOfFrame(); } _mainScreen.localPosition = _mainScreenStartPosition; _optionsScreen.anchoredPosition = _optionScreenStartPosition; } else { // Show Options Screen _isOptionShown = true; while (_optionsScreen.anchoredPosition.x >= 1f) { _mainScreen.localPosition = Vector3.Lerp(_mainScreen.localPosition, _mainScreenEndPosition, AnimationDampening); _optionsScreen.anchoredPosition = Vector2.Lerp(_optionsScreen.anchoredPosition, _optionScreenEndPosition, AnimationDampening); yield return new WaitForEndOfFrame(); } _mainScreen.localPosition = _mainScreenEndPosition; _optionsScreen.anchoredPosition = _optionScreenEndPosition; } _disableInput = false; } }
32.576471
118
0.758397
[ "MIT" ]
IT2901-Gruppe-16-Kantega/IT2901
Assets/Scripts/MainMenuScript.cs
2,771
C#
// <auto-generated /> using System; using Estateapp.Data.DBContext.ApplicationDBContext; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Estateapp.Data.Migrations.ApplicationDB { [DbContext(typeof(ApplicationDBContext))] partial class ApplicationDBContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.4") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Estateapp.Data.Entities.Contact", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<DateTime>("DeletedAt") .HasColumnType("datetime2"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<string>("LocalGovernmentArea") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("ModifiedAt") .HasColumnType("datetime2"); b.Property<string>("State") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("contacts"); }); modelBuilder.Entity("Estateapp.Data.Entities.Property", b => { b.Property<string>("Id") .HasColumnType("nvarchar(450)"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime2"); b.Property<DateTime>("DeletedAt") .HasColumnType("datetime2"); b.Property<bool>("IsDeleted") .HasColumnType("bit"); b.Property<DateTime>("ModifiedAt") .HasColumnType("datetime2"); b.Property<string>("Title") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("properties"); }); #pragma warning restore 612, 618 } } }
34.141026
117
0.529854
[ "MIT" ]
temmytope88/cSharpEstateApp
src/Estateapp.Data/Migrations/ApplicationDB/ApplicationDBContextModelSnapshot.cs
2,665
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("CodeActivityT")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CodeActivityT")] [assembly: AssemblyCopyright("")] [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("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
36.441176
84
0.743341
[ "MIT" ]
JeremyJeanson/WF4Templates
Sources legacy (vs 2010-2015)/CodeActivityT/Properties/AssemblyInfo.cs
1,241
C#
using UnityEditor.XR.Interaction.Toolkit.Utilities; using UnityEngine; using UnityEngine.XR.Interaction.Toolkit; namespace UnityEditor.XR.Interaction.Toolkit { /// <summary> /// Custom editor for an <see cref="XRGrabInteractable"/>. /// </summary> [CustomEditor(typeof(XRGrabInteractable), true), CanEditMultipleObjects] public class XRGrabInteractableEditor : XRBaseInteractableEditor { /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.attachTransform"/>.</summary> protected SerializedProperty m_AttachTransform; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.attachEaseInTime"/>.</summary> protected SerializedProperty m_AttachEaseInTime; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.movementType"/>.</summary> protected SerializedProperty m_MovementType; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.velocityDamping"/>.</summary> protected SerializedProperty m_VelocityDamping; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.velocityScale"/>.</summary> protected SerializedProperty m_VelocityScale; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.angularVelocityDamping"/>.</summary> protected SerializedProperty m_AngularVelocityDamping; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.angularVelocityScale"/>.</summary> protected SerializedProperty m_AngularVelocityScale; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.trackPosition"/>.</summary> protected SerializedProperty m_TrackPosition; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.smoothPosition"/>.</summary> protected SerializedProperty m_SmoothPosition; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.smoothPositionAmount"/>.</summary> protected SerializedProperty m_SmoothPositionAmount; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.tightenPosition"/>.</summary> protected SerializedProperty m_TightenPosition; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.trackRotation"/>.</summary> protected SerializedProperty m_TrackRotation; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.smoothRotation"/>.</summary> protected SerializedProperty m_SmoothRotation; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.smoothRotationAmount"/>.</summary> protected SerializedProperty m_SmoothRotationAmount; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.tightenRotation"/>.</summary> protected SerializedProperty m_TightenRotation; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.throwOnDetach"/>.</summary> protected SerializedProperty m_ThrowOnDetach; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.throwSmoothingDuration"/>.</summary> protected SerializedProperty m_ThrowSmoothingDuration; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.throwSmoothingCurve"/>.</summary> protected SerializedProperty m_ThrowSmoothingCurve; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.throwVelocityScale"/>.</summary> protected SerializedProperty m_ThrowVelocityScale; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.throwAngularVelocityScale"/>.</summary> protected SerializedProperty m_ThrowAngularVelocityScale; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.forceGravityOnDetach"/>.</summary> protected SerializedProperty m_ForceGravityOnDetach; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.retainTransformParent"/>.</summary> protected SerializedProperty m_RetainTransformParent; /// <summary><see cref="SerializedProperty"/> of the <see cref="SerializeField"/> backing <see cref="XRGrabInteractable.attachPointCompatibilityMode"/>.</summary> protected SerializedProperty m_AttachPointCompatibilityMode; /// <summary>Value to be checked before recalculate if the inspected object has a non-uniformly scaled parent.</summary> bool m_RecalculateHasNonUniformScale = true; /// <summary>Caches if the inspected object has a non-uniformly scaled parent.</summary> bool m_HasNonUniformScale; /// <summary> /// Contents of GUI elements used by this editor. /// </summary> protected static class Contents { /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.attachTransform"/>.</summary> public static readonly GUIContent attachTransform = EditorGUIUtility.TrTextContent("Attach Transform", "The attachment point to use on this Interactable (will use this object's position if none set)."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.attachEaseInTime"/>.</summary> public static readonly GUIContent attachEaseInTime = EditorGUIUtility.TrTextContent("Attach Ease In Time", "Time in seconds to ease in the attach when selected (a value of 0 indicates no easing)."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.movementType"/>.</summary> public static readonly GUIContent movementType = EditorGUIUtility.TrTextContent("Movement Type", "Specifies how this object is moved when selected, either through setting the velocity of the Rigidbody, moving the kinematic Rigidbody during Fixed Update, or by directly updating the Transform each frame."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.velocityDamping"/>.</summary> public static readonly GUIContent velocityDamping = EditorGUIUtility.TrTextContent("Velocity Damping", "Scale factor of how much to dampen the existing velocity when tracking the position of the Interactor. The smaller the value, the longer it takes for the velocity to decay."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.velocityScale"/>.</summary> public static readonly GUIContent velocityScale = EditorGUIUtility.TrTextContent("Velocity Scale", "Scale factor applied to the tracked velocity while updating the Rigidbody when tracking the position of the Interactor."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.angularVelocityDamping"/>.</summary> public static readonly GUIContent angularVelocityDamping = EditorGUIUtility.TrTextContent("Angular Velocity Damping", "Scale factor of how much to dampen the existing angular velocity when tracking the rotation of the Interactor. The smaller the value, the longer it takes for the angular velocity to decay."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.angularVelocityScale"/>.</summary> public static readonly GUIContent angularVelocityScale = EditorGUIUtility.TrTextContent("Angular Velocity Scale", "Scale factor applied to the tracked angular velocity while updating the Rigidbody when tracking the rotation of the Interactor."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.trackPosition"/>.</summary> public static readonly GUIContent trackPosition = EditorGUIUtility.TrTextContent("Track Position", "Whether this object should follow the position of the Interactor when selected."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.smoothPosition"/>.</summary> public static readonly GUIContent smoothPosition = EditorGUIUtility.TrTextContent("Smooth Position", "Apply smoothing while following the position of the Interactor when selected."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.smoothPositionAmount"/>.</summary> public static readonly GUIContent smoothPositionAmount = EditorGUIUtility.TrTextContent("Smooth Position Amount", "Scale factor for how much smoothing is applied while following the position of the Interactor when selected. The larger the value, the closer this object will remain to the position of the Interactor."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.tightenPosition"/>.</summary> public static readonly GUIContent tightenPosition = EditorGUIUtility.TrTextContent("Tighten Position", "Reduces the maximum follow position difference when using smoothing. The value ranges from 0 meaning no bias in the smoothed follow distance, to 1 meaning effectively no smoothing at all."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.trackRotation"/>.</summary> public static readonly GUIContent trackRotation = EditorGUIUtility.TrTextContent("Track Rotation", "Whether this object should follow the rotation of the Interactor when selected."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.smoothRotation"/>.</summary> public static readonly GUIContent smoothRotation = EditorGUIUtility.TrTextContent("Smooth Rotation", "Apply smoothing while following the rotation of the Interactor when selected."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.smoothRotationAmount"/>.</summary> public static readonly GUIContent smoothRotationAmount = EditorGUIUtility.TrTextContent("Smooth Rotation Amount", "Scale factor for how much smoothing is applied while following the rotation of the Interactor when selected. The larger the value, the closer this object will remain to the rotation of the Interactor."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.tightenRotation"/>.</summary> public static readonly GUIContent tightenRotation = EditorGUIUtility.TrTextContent("Tighten Rotation", "Reduces the maximum follow rotation difference when using smoothing. The value ranges from 0 meaning no bias in the smoothed follow rotation, to 1 meaning effectively no smoothing at all."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.throwOnDetach"/>.</summary> public static readonly GUIContent throwOnDetach = EditorGUIUtility.TrTextContent("Throw On Detach", "Whether this object inherits the velocity of the Interactor when released."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.throwSmoothingDuration"/>.</summary> public static readonly GUIContent throwSmoothingDuration = EditorGUIUtility.TrTextContent("Throw Smoothing Duration", "Time period to average thrown velocity over."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.throwSmoothingCurve"/>.</summary> public static readonly GUIContent throwSmoothingCurve = EditorGUIUtility.TrTextContent("Throw Smoothing Curve", "The curve to use to weight thrown velocity smoothing (most recent frames to the right)."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.throwVelocityScale"/>.</summary> public static readonly GUIContent throwVelocityScale = EditorGUIUtility.TrTextContent("Throw Velocity Scale", "Scale factor applied to this object's inherited velocity of the Interactor when released."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.throwAngularVelocityScale"/>.</summary> public static readonly GUIContent throwAngularVelocityScale = EditorGUIUtility.TrTextContent("Throw Angular Velocity Scale", "Scale factor applied to this object's inherited angular velocity of the Interactor when released."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.forceGravityOnDetach"/>.</summary> public static readonly GUIContent forceGravityOnDetach = EditorGUIUtility.TrTextContent("Force Gravity On Detach", "Force this object to have gravity when released (will still use pre-grab value if this is false)."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.retainTransformParent"/>.</summary> public static readonly GUIContent retainTransformParent = EditorGUIUtility.TrTextContent("Retain Transform Parent", "Whether to set the parent of this object back to its original parent this object was a child of after this object is dropped."); /// <summary><see cref="GUIContent"/> for <see cref="XRGrabInteractable.attachPointCompatibilityMode"/>.</summary> public static readonly GUIContent attachPointCompatibilityMode = EditorGUIUtility.TrTextContent("Attach Point Compatibility Mode", "Use Default for consistent attach points between all Movement Type values. Use Legacy for older projects that want to maintain the incorrect method which was partially based on center of mass."); /// <summary>Message for non-uniformly scaled parent.</summary> public static readonly string nonUniformScaledParentWarning = "When a child object has a non-uniformly scaled parent and is rotated relative to that parent, it may appear skewed. To avoid this, use uniform scale in all parents' Transform of this object."; /// <summary>Array of type <see cref="GUIContent"/> for the options shown in the popup for <see cref="XRGrabInteractable.attachPointCompatibilityMode"/>.</summary> public static readonly GUIContent[] attachPointCompatibilityModeOptions = { EditorGUIUtility.TrTextContent("Default (Recommended)"), EditorGUIUtility.TrTextContent("Legacy (Obsolete)") }; } /// <inheritdoc /> protected override void OnEnable() { base.OnEnable(); m_AttachTransform = serializedObject.FindProperty("m_AttachTransform"); m_AttachEaseInTime = serializedObject.FindProperty("m_AttachEaseInTime"); m_MovementType = serializedObject.FindProperty("m_MovementType"); m_VelocityDamping = serializedObject.FindProperty("m_VelocityDamping"); m_VelocityScale = serializedObject.FindProperty("m_VelocityScale"); m_AngularVelocityDamping = serializedObject.FindProperty("m_AngularVelocityDamping"); m_AngularVelocityScale = serializedObject.FindProperty("m_AngularVelocityScale"); m_TrackPosition = serializedObject.FindProperty("m_TrackPosition"); m_SmoothPosition = serializedObject.FindProperty("m_SmoothPosition"); m_SmoothPositionAmount = serializedObject.FindProperty("m_SmoothPositionAmount"); m_TightenPosition = serializedObject.FindProperty("m_TightenPosition"); m_TrackRotation = serializedObject.FindProperty("m_TrackRotation"); m_SmoothRotation = serializedObject.FindProperty("m_SmoothRotation"); m_SmoothRotationAmount = serializedObject.FindProperty("m_SmoothRotationAmount"); m_TightenRotation = serializedObject.FindProperty("m_TightenRotation"); m_ThrowOnDetach = serializedObject.FindProperty("m_ThrowOnDetach"); m_ThrowSmoothingDuration = serializedObject.FindProperty("m_ThrowSmoothingDuration"); m_ThrowSmoothingCurve = serializedObject.FindProperty("m_ThrowSmoothingCurve"); m_ThrowVelocityScale = serializedObject.FindProperty("m_ThrowVelocityScale"); m_ThrowAngularVelocityScale = serializedObject.FindProperty("m_ThrowAngularVelocityScale"); m_ForceGravityOnDetach = serializedObject.FindProperty("m_ForceGravityOnDetach"); m_RetainTransformParent = serializedObject.FindProperty("m_RetainTransformParent"); m_AttachPointCompatibilityMode = serializedObject.FindProperty("m_AttachPointCompatibilityMode"); Undo.postprocessModifications += OnPostprocessModifications; } /// <summary> /// This function is called when the object becomes disabled. /// </summary> /// <seealso cref="MonoBehaviour"/> protected virtual void OnDisable() { Undo.postprocessModifications -= OnPostprocessModifications; } /// <inheritdoc /> protected override void DrawProperties() { base.DrawProperties(); EditorGUILayout.Space(); DrawGrabConfiguration(); DrawTrackConfiguration(); DrawDetachConfiguration(); DrawAttachConfiguration(); } /// <summary> /// Draw the property fields related to grab configuration. /// </summary> protected virtual void DrawGrabConfiguration() { EditorGUILayout.PropertyField(m_MovementType, Contents.movementType); EditorGUILayout.PropertyField(m_RetainTransformParent, Contents.retainTransformParent); DrawNonUniformScaleMessage(); } /// <summary> /// Draw the property fields related to tracking configuration. /// </summary> protected virtual void DrawTrackConfiguration() { EditorGUILayout.PropertyField(m_TrackPosition, Contents.trackPosition); if (m_TrackPosition.boolValue) { using (new EditorGUI.IndentLevelScope()) { EditorGUILayout.PropertyField(m_SmoothPosition, Contents.smoothPosition); if (m_SmoothPosition.boolValue) { using (new EditorGUI.IndentLevelScope()) { EditorGUILayout.PropertyField(m_SmoothPositionAmount, Contents.smoothPositionAmount); EditorGUILayout.PropertyField(m_TightenPosition, Contents.tightenPosition); } } if (m_MovementType.intValue == (int)XRBaseInteractable.MovementType.VelocityTracking) { EditorGUILayout.PropertyField(m_VelocityDamping, Contents.velocityDamping); EditorGUILayout.PropertyField(m_VelocityScale, Contents.velocityScale); } } } EditorGUILayout.PropertyField(m_TrackRotation, Contents.trackRotation); if (m_TrackRotation.boolValue) { using (new EditorGUI.IndentLevelScope()) { EditorGUILayout.PropertyField(m_SmoothRotation, Contents.smoothRotation); if (m_SmoothRotation.boolValue) { using (new EditorGUI.IndentLevelScope()) { EditorGUILayout.PropertyField(m_SmoothRotationAmount, Contents.smoothRotationAmount); EditorGUILayout.PropertyField(m_TightenRotation, Contents.tightenRotation); } } if (m_MovementType.intValue == (int)XRBaseInteractable.MovementType.VelocityTracking) { EditorGUILayout.PropertyField(m_AngularVelocityDamping, Contents.angularVelocityDamping); EditorGUILayout.PropertyField(m_AngularVelocityScale, Contents.angularVelocityScale); } } } } /// <summary> /// Draw property fields related to detach configuration. /// </summary> protected virtual void DrawDetachConfiguration() { EditorGUILayout.PropertyField(m_ThrowOnDetach, Contents.throwOnDetach); if (m_ThrowOnDetach.boolValue) { using (new EditorGUI.IndentLevelScope()) { EditorGUILayout.PropertyField(m_ThrowSmoothingDuration, Contents.throwSmoothingDuration); EditorGUILayout.PropertyField(m_ThrowSmoothingCurve, Contents.throwSmoothingCurve); EditorGUILayout.PropertyField(m_ThrowVelocityScale, Contents.throwVelocityScale); EditorGUILayout.PropertyField(m_ThrowAngularVelocityScale, Contents.throwAngularVelocityScale); } } EditorGUILayout.PropertyField(m_ForceGravityOnDetach, Contents.forceGravityOnDetach); } /// <summary> /// Draw property fields related to attach configuration. /// </summary> protected virtual void DrawAttachConfiguration() { EditorGUILayout.PropertyField(m_AttachTransform, Contents.attachTransform); EditorGUILayout.PropertyField(m_AttachEaseInTime, Contents.attachEaseInTime); XRInteractionEditorGUI.EnumPropertyField(m_AttachPointCompatibilityMode, Contents.attachPointCompatibilityMode, Contents.attachPointCompatibilityModeOptions); } /// <summary> /// Checks if the object has a non-uniformly scaled parent and draws a message if necessary. /// </summary> protected virtual void DrawNonUniformScaleMessage() { if (m_RetainTransformParent == null || !m_RetainTransformParent.boolValue) return; if (m_RecalculateHasNonUniformScale) { var monoBehaviour = target as MonoBehaviour; if (monoBehaviour == null) return; var transform = monoBehaviour.transform; if (transform == null) return; m_HasNonUniformScale = false; for (var parent = transform.parent; parent != null; parent = parent.parent) { var localScale = parent.localScale; if (!Mathf.Approximately(localScale.x, localScale.y) || !Mathf.Approximately(localScale.x, localScale.z)) { m_HasNonUniformScale = true; break; } } m_RecalculateHasNonUniformScale = false; } if (m_HasNonUniformScale) EditorGUILayout.HelpBox(Contents.nonUniformScaledParentWarning, MessageType.Warning); } /// <summary> /// Callback registered to be triggered whenever a new set of property modifications is created. /// </summary> /// <seealso cref="Undo.postprocessModifications"/> protected virtual UndoPropertyModification[] OnPostprocessModifications(UndoPropertyModification[] modifications) { m_RecalculateHasNonUniformScale = true; return modifications; } } }
75.313665
339
0.691477
[ "MIT" ]
BigMeatBaoZi/SDM5002
Unity/vr_arm_ctrl/Library/PackageCache/com.unity.xr.interaction.toolkit@2.0.2/Editor/Interaction/Interactables/XRGrabInteractableEditor.cs
24,253
C#
using Healthy.BaseComponents.Interfaces; using MvvmHelpers; using System; using System.Collections.Generic; using System.Text; namespace Healthy.News.ViewModels { public class NewsMainViewModel : BaseViewModel, IViewModel { public NewsMainViewModel() { Title = "News"; } } }
19.117647
62
0.676923
[ "MIT" ]
peedroca/Healthy
Peedroca.Healthy/Healthy.News/ViewModels/NewsMainViewModel.cs
327
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ [assembly: global::Xamarin.Forms.Xaml.XamlResourceIdAttribute("XamarinFormsWebAPI.ClientView.xaml", "ClientView.xaml", typeof(global::XamarinFormsWebAPI.ClientView))] namespace XamarinFormsWebAPI { [global::Xamarin.Forms.Xaml.XamlFilePathAttribute("ClientView.xaml")] public partial class ClientView : global::Rg.Plugins.Popup.Pages.PopupPage { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")] private global::Xamarin.Forms.ListView listVehicle; [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")] private void InitializeComponent() { global::Xamarin.Forms.Xaml.Extensions.LoadFromXaml(this, typeof(ClientView)); listVehicle = global::Xamarin.Forms.NameScopeExtensions.FindByName<global::Xamarin.Forms.ListView>(this, "listVehicle"); } } }
47.413793
167
0.609455
[ "MIT" ]
Baadjie/XamarinFormsApp
XamarinFormsWebAPI/obj/Debug/netstandard2.0/ClientView.xaml.g.cs
1,375
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("OtpSharp.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OtpSharp.Tests")] [assembly: AssemblyCopyright("Copyright © 2012 by Devin Martin and released under the MIT license")] [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("bf2cb477-80f2-4e0f-9c81-bd6275229d79")] // 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.6.0")] [assembly: AssemblyFileVersion("1.0.6.0")]
40.166667
101
0.733057
[ "MIT" ]
arlm/otp-sharp
OtpSharp.Tests/Properties/AssemblyInfo.cs
1,449
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Text; using System.Linq; namespace SharpToolkit.AccessSynchronization { public sealed class ExceptionDeadlockResolver : ILockResolver { public int Timeout { get; private set; } public ExceptionDeadlockResolver(int timeout) { this.Timeout = timeout; } public void Resolve(ConcurrentDictionary<int, ThreadLocksTrack> taken) { var pairs = taken.SelectMany( x => taken .Where(y => x.Key != y.Key) .Select(y => (subject: x.Value, target: y.Value, subjectThread: x.Key, targetThread: y.Key))); foreach (var pair in pairs) { checkAgainst(pair.subject, pair.target, pair.subjectThread, pair.targetThread); } } private void checkAgainst(ThreadLocksTrack subject, ThreadLocksTrack target, int subjectThread, int targetThread) { var (obj, locks) = subject.Report .Where( x => x.Value .Select(y => y.AcqusitionState) .Contains(ThreadLocksTrack.AcqusitionState.Intent)) .Single(); if (target.Report.ContainsKey(obj) == false) // Target doesn't contain intended object // so no deadlock can exist. return; var (tObj, tLocks) = target.Report .Where( x => x.Value .Select(y => y.AcqusitionState) .Contains(ThreadLocksTrack.AcqusitionState.Intent)) .Single(); if (obj == tObj) // The target also intents to unlock the object. return; if (subject.Report.ContainsKey(tObj) == false) // The taget intents to unlock object that is not locked by subject. return; throw new DeadlockException( subjectThread, obj, locks.Single(x => x.AcqusitionState == ThreadLocksTrack.AcqusitionState.Intent).LockState, subject.Report[tObj].Last().LockState, targetThread, tObj, tLocks.Single(x => x.AcqusitionState == ThreadLocksTrack.AcqusitionState.Intent).LockState, target.Report[obj].Last().LockState); } } }
34.858974
122
0.510114
[ "MIT" ]
SharpToolkit/AccessSynchronization
SharpToolkit.AccessSynchronization/DeadlockResolver.cs
2,721
C#
using System.Text.Json.Serialization; namespace Horizon.Payment.Alipay.Response { /// <summary> /// AlipayAssetPointOrderQueryResponse. /// </summary> public class AlipayAssetPointOrderQueryResponse : AlipayResponse { /// <summary> /// 支付宝集分宝发放流水号 /// </summary> [JsonPropertyName("alipay_order_no")] public string AlipayOrderNo { get; set; } /// <summary> /// 发放时间,格式:yyyy-MM-dd HH:mm:ss /// </summary> [JsonPropertyName("create_time")] public string CreateTime { get; set; } /// <summary> /// 支付宝集分宝发放者用户ID /// </summary> [JsonPropertyName("dispatch_user_id")] public string DispatchUserId { get; set; } /// <summary> /// 向用户展示集分宝发放备注 /// </summary> [JsonPropertyName("memo")] public string Memo { get; set; } /// <summary> /// isv提供的发放号订单号,由数字和字母组成,最大长度为32为,需要保证每笔发放的唯一性,支付宝会对该参数做唯一性控制。如果使用同样的订单号,支付宝将返回订单号已经存在的错误 /// </summary> [JsonPropertyName("merchant_order_no")] public string MerchantOrderNo { get; set; } /// <summary> /// 集分宝发放流水状态,I表示处理中,S表示成功,F表示失败 /// </summary> [JsonPropertyName("order_status")] public string OrderStatus { get; set; } /// <summary> /// 发放集分宝的数量 /// </summary> [JsonPropertyName("point_count")] public long PointCount { get; set; } /// <summary> /// 支付宝集分宝接收者用户ID /// </summary> [JsonPropertyName("receive_user_id")] public string ReceiveUserId { get; set; } } }
27.966102
98
0.564242
[ "Apache-2.0" ]
bluexray/Horizon.Sample
Horizon.Payment.Alipay/Response/AlipayAssetPointOrderQueryResponse.cs
1,986
C#
using System; namespace Salary { internal class Program { private static void Main(string[] args) { int countTab = int.Parse(Console.ReadLine()); double salary = double.Parse(Console.ReadLine()); for (int sumWeb = 1; sumWeb <= countTab; sumWeb++) { string nameWebSite = Console.ReadLine(); if (nameWebSite == "Facebook") { salary -= 150; } else if (nameWebSite == "Instagram") { salary -= 100; } else if (nameWebSite == "Reddit") { salary -= 50; } if (salary <= 0) { Console.WriteLine("You have lost your salary."); break; } else if (sumWeb == countTab) { Console.WriteLine(salary); } } } } }
26.7
68
0.377341
[ "MIT" ]
dzhanetGerdzhikova/Programming-Basics
2.1. ForLoop-Exercise/Salary/Program.cs
1,070
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("OwnSerializerLib")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("OwnSerializerLib")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("2af76833-0e4f-496d-8adb-1ab656b051b5")] // 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.837838
84
0.749286
[ "Apache-2.0" ]
arturradiuk/PT
Task2/OwnSerializerLib/Properties/AssemblyInfo.cs
1,403
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("4OpEenRijScreensaver")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Arthur Rump")] [assembly: AssemblyProduct("4OpEenRijScreensaver")] [assembly: AssemblyCopyright("Copyright © Arthur Rump 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)] //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")]
43.035714
98
0.713278
[ "MIT" ]
arthurrump/4OpEenRijScreensaver
4OpEenRijScreensaver/Properties/AssemblyInfo.cs
2,413
C#
#if !NO_RUNTIME using System; namespace ProtoBuf.Serializers { internal sealed class Int64Serializer : IProtoSerializer { private static readonly Type expectedType = typeof(long); public Type ExpectedType => expectedType; bool IProtoSerializer.RequiresOldValue => false; bool IProtoSerializer.ReturnsValue => true; public object Read(ProtoReader source, ref ProtoReader.State state, object value) { Helpers.DebugAssert(value == null); // since replaces return source.ReadInt64(ref state); } public void Write(ProtoWriter dest, ref ProtoWriter.State state, object value) { ProtoWriter.WriteInt64((long)value, dest, ref state); } #if FEAT_COMPILER void IProtoSerializer.EmitWrite(Compiler.CompilerContext ctx, Compiler.Local valueFrom) { ctx.EmitBasicWrite("WriteInt64", valueFrom); } void IProtoSerializer.EmitRead(Compiler.CompilerContext ctx, Compiler.Local entity) { ctx.EmitBasicRead("ReadInt64", ExpectedType); } #endif } } #endif
30.25641
96
0.636441
[ "Apache-2.0" ]
James-xin/protobuf-net
src/protobuf-net/Serializers/Int64Serializer.cs
1,182
C#
namespace DemoWF13 { partial class frmClinica { /// <summary> /// Variable del diseñador requerida. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Limpiar los recursos que se estén utilizando. /// </summary> /// <param name="disposing">true si los recursos administrados se deben desechar; false en caso contrario.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Código generado por el Diseñador de Windows Forms /// <summary> /// Método necesario para admitir el Diseñador. No se puede modificar /// el contenido del método con el editor de código. /// </summary> private void InitializeComponent() { this.btnSalir = new System.Windows.Forms.Button(); this.btnNuevo = new System.Windows.Forms.Button(); this.btnGuardar = new System.Windows.Forms.Button(); this.gpbCondicion = new System.Windows.Forms.GroupBox(); this.rbtCondicionE = new System.Windows.Forms.RadioButton(); this.rbtCondicionD = new System.Windows.Forms.RadioButton(); this.rbtCondicionC = new System.Windows.Forms.RadioButton(); this.rbtCondicionB = new System.Windows.Forms.RadioButton(); this.rbtCondicionA = new System.Windows.Forms.RadioButton(); this.gpbAnalisis = new System.Windows.Forms.GroupBox(); this.nudCostoAnalisis = new System.Windows.Forms.NumericUpDown(); this.chkOrina = new System.Windows.Forms.CheckBox(); this.chkSangre = new System.Windows.Forms.CheckBox(); this.rbtTipoAB2 = new System.Windows.Forms.RadioButton(); this.rbtTipoAB1 = new System.Windows.Forms.RadioButton(); this.rbtTipoB2 = new System.Windows.Forms.RadioButton(); this.rbtTipoO2 = new System.Windows.Forms.RadioButton(); this.rbtTipoO1 = new System.Windows.Forms.RadioButton(); this.rbtTipoB1 = new System.Windows.Forms.RadioButton(); this.rbtTipoA2 = new System.Windows.Forms.RadioButton(); this.Label5 = new System.Windows.Forms.Label(); this.rbtTipoA1 = new System.Windows.Forms.RadioButton(); this.gpbEspecialidad = new System.Windows.Forms.GroupBox(); this.nudCostoConsulta = new System.Windows.Forms.NumericUpDown(); this.rbtPediatria = new System.Windows.Forms.RadioButton(); this.rbtMedicina = new System.Windows.Forms.RadioButton(); this.rbtGinecologia = new System.Windows.Forms.RadioButton(); this.rbtOftalmologia = new System.Windows.Forms.RadioButton(); this.rbtOdontologia = new System.Windows.Forms.RadioButton(); this.Label4 = new System.Windows.Forms.Label(); this.txtPaciente = new System.Windows.Forms.TextBox(); this.Label3 = new System.Windows.Forms.Label(); this.Label8 = new System.Windows.Forms.Label(); this.Label7 = new System.Windows.Forms.Label(); this.Label6 = new System.Windows.Forms.Label(); this.txtNumero = new System.Windows.Forms.TextBox(); this.Label2 = new System.Windows.Forms.Label(); this.Label1 = new System.Windows.Forms.Label(); this.nudSubTotal = new System.Windows.Forms.NumericUpDown(); this.nudDescuento = new System.Windows.Forms.NumericUpDown(); this.nudNetoPagar = new System.Windows.Forms.NumericUpDown(); this.label9 = new System.Windows.Forms.Label(); this.lblTipo = new System.Windows.Forms.Label(); this.gpbCondicion.SuspendLayout(); this.gpbAnalisis.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.nudCostoAnalisis)).BeginInit(); this.gpbEspecialidad.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.nudCostoConsulta)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.nudSubTotal)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.nudDescuento)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.nudNetoPagar)).BeginInit(); this.SuspendLayout(); // // btnSalir // this.btnSalir.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnSalir.Location = new System.Drawing.Point(323, 471); this.btnSalir.Name = "btnSalir"; this.btnSalir.Size = new System.Drawing.Size(78, 23); this.btnSalir.TabIndex = 10; this.btnSalir.Text = "&Salir"; this.btnSalir.UseVisualStyleBackColor = true; this.btnSalir.Click += new System.EventHandler(this.btnSalir_Click); // // btnNuevo // this.btnNuevo.Location = new System.Drawing.Point(239, 471); this.btnNuevo.Name = "btnNuevo"; this.btnNuevo.Size = new System.Drawing.Size(78, 23); this.btnNuevo.TabIndex = 9; this.btnNuevo.Text = "&Nuevo"; this.btnNuevo.UseVisualStyleBackColor = true; this.btnNuevo.Click += new System.EventHandler(this.btnNuevo_Click); // // btnGuardar // this.btnGuardar.Enabled = false; this.btnGuardar.Location = new System.Drawing.Point(155, 471); this.btnGuardar.Name = "btnGuardar"; this.btnGuardar.Size = new System.Drawing.Size(78, 23); this.btnGuardar.TabIndex = 8; this.btnGuardar.Text = "&Guardar"; this.btnGuardar.UseVisualStyleBackColor = true; this.btnGuardar.Click += new System.EventHandler(this.btnGuardar_Click); // // gpbCondicion // this.gpbCondicion.Controls.Add(this.rbtCondicionE); this.gpbCondicion.Controls.Add(this.rbtCondicionD); this.gpbCondicion.Controls.Add(this.rbtCondicionC); this.gpbCondicion.Controls.Add(this.rbtCondicionB); this.gpbCondicion.Controls.Add(this.rbtCondicionA); this.gpbCondicion.Enabled = false; this.gpbCondicion.Location = new System.Drawing.Point(24, 331); this.gpbCondicion.Name = "gpbCondicion"; this.gpbCondicion.Size = new System.Drawing.Size(377, 40); this.gpbCondicion.TabIndex = 3; this.gpbCondicion.TabStop = false; this.gpbCondicion.Text = "Condición Económica"; // // rbtCondicionE // this.rbtCondicionE.AutoSize = true; this.rbtCondicionE.Location = new System.Drawing.Point(239, 14); this.rbtCondicionE.Name = "rbtCondicionE"; this.rbtCondicionE.Size = new System.Drawing.Size(32, 17); this.rbtCondicionE.TabIndex = 4; this.rbtCondicionE.Text = "E"; this.rbtCondicionE.UseVisualStyleBackColor = true; // // rbtCondicionD // this.rbtCondicionD.AutoSize = true; this.rbtCondicionD.Location = new System.Drawing.Point(188, 14); this.rbtCondicionD.Name = "rbtCondicionD"; this.rbtCondicionD.Size = new System.Drawing.Size(33, 17); this.rbtCondicionD.TabIndex = 3; this.rbtCondicionD.TabStop = true; this.rbtCondicionD.Text = "D"; this.rbtCondicionD.UseVisualStyleBackColor = true; // // rbtCondicionC // this.rbtCondicionC.AutoSize = true; this.rbtCondicionC.Location = new System.Drawing.Point(131, 15); this.rbtCondicionC.Name = "rbtCondicionC"; this.rbtCondicionC.Size = new System.Drawing.Size(32, 17); this.rbtCondicionC.TabIndex = 2; this.rbtCondicionC.TabStop = true; this.rbtCondicionC.Text = "C"; this.rbtCondicionC.UseVisualStyleBackColor = true; // // rbtCondicionB // this.rbtCondicionB.AutoSize = true; this.rbtCondicionB.Location = new System.Drawing.Point(76, 14); this.rbtCondicionB.Name = "rbtCondicionB"; this.rbtCondicionB.Size = new System.Drawing.Size(32, 17); this.rbtCondicionB.TabIndex = 1; this.rbtCondicionB.TabStop = true; this.rbtCondicionB.Text = "B"; this.rbtCondicionB.UseVisualStyleBackColor = true; // // rbtCondicionA // this.rbtCondicionA.AutoSize = true; this.rbtCondicionA.Checked = true; this.rbtCondicionA.Location = new System.Drawing.Point(19, 15); this.rbtCondicionA.Name = "rbtCondicionA"; this.rbtCondicionA.Size = new System.Drawing.Size(32, 17); this.rbtCondicionA.TabIndex = 0; this.rbtCondicionA.TabStop = true; this.rbtCondicionA.Text = "A"; this.rbtCondicionA.UseVisualStyleBackColor = true; // // gpbAnalisis // this.gpbAnalisis.Controls.Add(this.nudCostoAnalisis); this.gpbAnalisis.Controls.Add(this.chkOrina); this.gpbAnalisis.Controls.Add(this.chkSangre); this.gpbAnalisis.Controls.Add(this.rbtTipoAB2); this.gpbAnalisis.Controls.Add(this.rbtTipoAB1); this.gpbAnalisis.Controls.Add(this.rbtTipoB2); this.gpbAnalisis.Controls.Add(this.rbtTipoO2); this.gpbAnalisis.Controls.Add(this.rbtTipoO1); this.gpbAnalisis.Controls.Add(this.rbtTipoB1); this.gpbAnalisis.Controls.Add(this.rbtTipoA2); this.gpbAnalisis.Controls.Add(this.Label5); this.gpbAnalisis.Controls.Add(this.rbtTipoA1); this.gpbAnalisis.Enabled = false; this.gpbAnalisis.Location = new System.Drawing.Point(24, 229); this.gpbAnalisis.Name = "gpbAnalisis"; this.gpbAnalisis.Size = new System.Drawing.Size(377, 91); this.gpbAnalisis.TabIndex = 2; this.gpbAnalisis.TabStop = false; this.gpbAnalisis.Text = "Análisis de Laboratorio"; // // nudCostoAnalisis // this.nudCostoAnalisis.DecimalPlaces = 2; this.nudCostoAnalisis.Enabled = false; this.nudCostoAnalisis.ForeColor = System.Drawing.Color.Black; this.nudCostoAnalisis.Location = new System.Drawing.Point(125, 65); this.nudCostoAnalisis.Name = "nudCostoAnalisis"; this.nudCostoAnalisis.Size = new System.Drawing.Size(103, 20); this.nudCostoAnalisis.TabIndex = 10; this.nudCostoAnalisis.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // chkOrina // this.chkOrina.AutoSize = true; this.chkOrina.Location = new System.Drawing.Point(138, 21); this.chkOrina.Name = "chkOrina"; this.chkOrina.Size = new System.Drawing.Size(104, 17); this.chkOrina.TabIndex = 1; this.chkOrina.Text = "Análisis de Orina"; this.chkOrina.UseVisualStyleBackColor = true; this.chkOrina.CheckedChanged += new System.EventHandler(this.CalcularCostoAnalisis); // // chkSangre // this.chkSangre.AutoSize = true; this.chkSangre.Location = new System.Drawing.Point(19, 22); this.chkSangre.Name = "chkSangre"; this.chkSangre.Size = new System.Drawing.Size(113, 17); this.chkSangre.TabIndex = 0; this.chkSangre.Text = "Análisis de Sangre"; this.chkSangre.UseVisualStyleBackColor = true; this.chkSangre.CheckedChanged += new System.EventHandler(this.CalcularCostoAnalisis); // // rbtTipoAB2 // this.rbtTipoAB2.AutoSize = true; this.rbtTipoAB2.Location = new System.Drawing.Point(242, 43); this.rbtTipoAB2.Name = "rbtTipoAB2"; this.rbtTipoAB2.Size = new System.Drawing.Size(42, 17); this.rbtTipoAB2.TabIndex = 7; this.rbtTipoAB2.TabStop = true; this.rbtTipoAB2.Text = "AB-"; this.rbtTipoAB2.UseVisualStyleBackColor = true; this.rbtTipoAB2.CheckedChanged += new System.EventHandler(this.DeterminarTipoSangre); // // rbtTipoAB1 // this.rbtTipoAB1.AutoSize = true; this.rbtTipoAB1.Location = new System.Drawing.Point(191, 42); this.rbtTipoAB1.Name = "rbtTipoAB1"; this.rbtTipoAB1.Size = new System.Drawing.Size(45, 17); this.rbtTipoAB1.TabIndex = 6; this.rbtTipoAB1.TabStop = true; this.rbtTipoAB1.Text = "AB+"; this.rbtTipoAB1.UseVisualStyleBackColor = true; this.rbtTipoAB1.CheckedChanged += new System.EventHandler(this.DeterminarTipoSangre); // // rbtTipoB2 // this.rbtTipoB2.AutoSize = true; this.rbtTipoB2.Location = new System.Drawing.Point(148, 42); this.rbtTipoB2.Name = "rbtTipoB2"; this.rbtTipoB2.Size = new System.Drawing.Size(35, 17); this.rbtTipoB2.TabIndex = 5; this.rbtTipoB2.TabStop = true; this.rbtTipoB2.Text = "B-"; this.rbtTipoB2.UseVisualStyleBackColor = true; this.rbtTipoB2.CheckedChanged += new System.EventHandler(this.DeterminarTipoSangre); // // rbtTipoO2 // this.rbtTipoO2.AutoSize = true; this.rbtTipoO2.Location = new System.Drawing.Point(332, 43); this.rbtTipoO2.Name = "rbtTipoO2"; this.rbtTipoO2.Size = new System.Drawing.Size(36, 17); this.rbtTipoO2.TabIndex = 9; this.rbtTipoO2.TabStop = true; this.rbtTipoO2.Text = "O-"; this.rbtTipoO2.UseVisualStyleBackColor = true; this.rbtTipoO2.CheckedChanged += new System.EventHandler(this.DeterminarTipoSangre); // // rbtTipoO1 // this.rbtTipoO1.AutoSize = true; this.rbtTipoO1.Location = new System.Drawing.Point(288, 43); this.rbtTipoO1.Name = "rbtTipoO1"; this.rbtTipoO1.Size = new System.Drawing.Size(39, 17); this.rbtTipoO1.TabIndex = 8; this.rbtTipoO1.TabStop = true; this.rbtTipoO1.Text = "O+"; this.rbtTipoO1.UseVisualStyleBackColor = true; this.rbtTipoO1.CheckedChanged += new System.EventHandler(this.DeterminarTipoSangre); // // rbtTipoB1 // this.rbtTipoB1.AutoSize = true; this.rbtTipoB1.Location = new System.Drawing.Point(107, 43); this.rbtTipoB1.Name = "rbtTipoB1"; this.rbtTipoB1.Size = new System.Drawing.Size(38, 17); this.rbtTipoB1.TabIndex = 4; this.rbtTipoB1.TabStop = true; this.rbtTipoB1.Text = "B+"; this.rbtTipoB1.UseVisualStyleBackColor = true; this.rbtTipoB1.CheckedChanged += new System.EventHandler(this.DeterminarTipoSangre); // // rbtTipoA2 // this.rbtTipoA2.AutoSize = true; this.rbtTipoA2.Location = new System.Drawing.Point(64, 43); this.rbtTipoA2.Name = "rbtTipoA2"; this.rbtTipoA2.Size = new System.Drawing.Size(35, 17); this.rbtTipoA2.TabIndex = 3; this.rbtTipoA2.TabStop = true; this.rbtTipoA2.Text = "A-"; this.rbtTipoA2.UseVisualStyleBackColor = true; this.rbtTipoA2.CheckedChanged += new System.EventHandler(this.DeterminarTipoSangre); // // Label5 // this.Label5.AutoSize = true; this.Label5.Location = new System.Drawing.Point(18, 69); this.Label5.Name = "Label5"; this.Label5.Size = new System.Drawing.Size(90, 13); this.Label5.TabIndex = 5; this.Label5.Text = "Costo Análisis S/."; // // rbtTipoA1 // this.rbtTipoA1.AutoSize = true; this.rbtTipoA1.Checked = true; this.rbtTipoA1.Location = new System.Drawing.Point(19, 43); this.rbtTipoA1.Name = "rbtTipoA1"; this.rbtTipoA1.Size = new System.Drawing.Size(38, 17); this.rbtTipoA1.TabIndex = 2; this.rbtTipoA1.TabStop = true; this.rbtTipoA1.Text = "A+"; this.rbtTipoA1.UseVisualStyleBackColor = true; this.rbtTipoA1.CheckedChanged += new System.EventHandler(this.DeterminarTipoSangre); // // gpbEspecialidad // this.gpbEspecialidad.Controls.Add(this.nudCostoConsulta); this.gpbEspecialidad.Controls.Add(this.rbtPediatria); this.gpbEspecialidad.Controls.Add(this.rbtMedicina); this.gpbEspecialidad.Controls.Add(this.rbtGinecologia); this.gpbEspecialidad.Controls.Add(this.rbtOftalmologia); this.gpbEspecialidad.Controls.Add(this.rbtOdontologia); this.gpbEspecialidad.Controls.Add(this.Label4); this.gpbEspecialidad.Enabled = false; this.gpbEspecialidad.Location = new System.Drawing.Point(24, 127); this.gpbEspecialidad.Name = "gpbEspecialidad"; this.gpbEspecialidad.Size = new System.Drawing.Size(377, 95); this.gpbEspecialidad.TabIndex = 1; this.gpbEspecialidad.TabStop = false; this.gpbEspecialidad.Text = "Especialidad"; // // nudCostoConsulta // this.nudCostoConsulta.DecimalPlaces = 2; this.nudCostoConsulta.Enabled = false; this.nudCostoConsulta.ForeColor = System.Drawing.Color.Black; this.nudCostoConsulta.Location = new System.Drawing.Point(125, 65); this.nudCostoConsulta.Name = "nudCostoConsulta"; this.nudCostoConsulta.Size = new System.Drawing.Size(103, 20); this.nudCostoConsulta.TabIndex = 6; this.nudCostoConsulta.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; this.nudCostoConsulta.Value = new decimal(new int[] { 20, 0, 0, 0}); // // rbtPediatria // this.rbtPediatria.AutoSize = true; this.rbtPediatria.Location = new System.Drawing.Point(249, 19); this.rbtPediatria.Name = "rbtPediatria"; this.rbtPediatria.Size = new System.Drawing.Size(68, 17); this.rbtPediatria.TabIndex = 2; this.rbtPediatria.TabStop = true; this.rbtPediatria.Text = "Pediatría"; this.rbtPediatria.UseVisualStyleBackColor = true; this.rbtPediatria.CheckedChanged += new System.EventHandler(this.CalcularCostoConsulta); // // rbtMedicina // this.rbtMedicina.AutoSize = true; this.rbtMedicina.Location = new System.Drawing.Point(125, 42); this.rbtMedicina.Name = "rbtMedicina"; this.rbtMedicina.Size = new System.Drawing.Size(108, 17); this.rbtMedicina.TabIndex = 4; this.rbtMedicina.TabStop = true; this.rbtMedicina.Text = "Medicina General"; this.rbtMedicina.UseVisualStyleBackColor = true; this.rbtMedicina.CheckedChanged += new System.EventHandler(this.CalcularCostoConsulta); // // rbtGinecologia // this.rbtGinecologia.AutoSize = true; this.rbtGinecologia.Location = new System.Drawing.Point(19, 42); this.rbtGinecologia.Name = "rbtGinecologia"; this.rbtGinecologia.Size = new System.Drawing.Size(83, 17); this.rbtGinecologia.TabIndex = 3; this.rbtGinecologia.TabStop = true; this.rbtGinecologia.Text = "Ginecología"; this.rbtGinecologia.UseVisualStyleBackColor = true; this.rbtGinecologia.CheckedChanged += new System.EventHandler(this.CalcularCostoConsulta); // // rbtOftalmologia // this.rbtOftalmologia.AutoSize = true; this.rbtOftalmologia.Location = new System.Drawing.Point(125, 19); this.rbtOftalmologia.Name = "rbtOftalmologia"; this.rbtOftalmologia.Size = new System.Drawing.Size(85, 17); this.rbtOftalmologia.TabIndex = 1; this.rbtOftalmologia.TabStop = true; this.rbtOftalmologia.Text = "Oftalmología"; this.rbtOftalmologia.UseVisualStyleBackColor = true; this.rbtOftalmologia.CheckedChanged += new System.EventHandler(this.CalcularCostoConsulta); // // rbtOdontologia // this.rbtOdontologia.AutoSize = true; this.rbtOdontologia.Checked = true; this.rbtOdontologia.Location = new System.Drawing.Point(19, 19); this.rbtOdontologia.Name = "rbtOdontologia"; this.rbtOdontologia.Size = new System.Drawing.Size(84, 17); this.rbtOdontologia.TabIndex = 0; this.rbtOdontologia.TabStop = true; this.rbtOdontologia.Text = "Odontología"; this.rbtOdontologia.UseVisualStyleBackColor = true; this.rbtOdontologia.CheckedChanged += new System.EventHandler(this.CalcularCostoConsulta); // // Label4 // this.Label4.AutoSize = true; this.Label4.Location = new System.Drawing.Point(18, 71); this.Label4.Name = "Label4"; this.Label4.Size = new System.Drawing.Size(96, 13); this.Label4.TabIndex = 3; this.Label4.Text = "Costo Consulta S/."; // // txtPaciente // this.txtPaciente.CharacterCasing = System.Windows.Forms.CharacterCasing.Upper; this.txtPaciente.Enabled = false; this.txtPaciente.Location = new System.Drawing.Point(93, 97); this.txtPaciente.Name = "txtPaciente"; this.txtPaciente.Size = new System.Drawing.Size(308, 20); this.txtPaciente.TabIndex = 0; // // Label3 // this.Label3.AutoSize = true; this.Label3.Location = new System.Drawing.Point(21, 100); this.Label3.Name = "Label3"; this.Label3.Size = new System.Drawing.Size(49, 13); this.Label3.TabIndex = 20; this.Label3.Text = "Paciente"; // // Label8 // this.Label8.AutoSize = true; this.Label8.Location = new System.Drawing.Point(249, 386); this.Label8.Name = "Label8"; this.Label8.Size = new System.Drawing.Size(88, 13); this.Label8.TabIndex = 16; this.Label8.Text = "Neto a Pagar S/."; this.Label8.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // Label7 // this.Label7.AutoSize = true; this.Label7.Location = new System.Drawing.Point(135, 386); this.Label7.Name = "Label7"; this.Label7.Size = new System.Drawing.Size(77, 13); this.Label7.TabIndex = 17; this.Label7.Text = "Descuento S/."; this.Label7.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // Label6 // this.Label6.AutoSize = true; this.Label6.Location = new System.Drawing.Point(22, 386); this.Label6.Name = "Label6"; this.Label6.Size = new System.Drawing.Size(71, 13); this.Label6.TabIndex = 4; this.Label6.Text = "Sub Total S/."; this.Label6.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // txtNumero // this.txtNumero.Enabled = false; this.txtNumero.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.txtNumero.Location = new System.Drawing.Point(301, 63); this.txtNumero.Name = "txtNumero"; this.txtNumero.ReadOnly = true; this.txtNumero.Size = new System.Drawing.Size(100, 23); this.txtNumero.TabIndex = 12; this.txtNumero.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // Label2 // this.Label2.AutoSize = true; this.Label2.Location = new System.Drawing.Point(209, 68); this.Label2.Name = "Label2"; this.Label2.Size = new System.Drawing.Size(86, 13); this.Label2.TabIndex = 15; this.Label2.Text = "Nro. de Consulta"; // // Label1 // this.Label1.BackColor = System.Drawing.SystemColors.ActiveCaption; this.Label1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.Label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 15.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Label1.ForeColor = System.Drawing.SystemColors.ButtonHighlight; this.Label1.Location = new System.Drawing.Point(-5, 14); this.Label1.Name = "Label1"; this.Label1.Size = new System.Drawing.Size(437, 39); this.Label1.TabIndex = 11; this.Label1.Text = "Registro de Consultas Médicas"; this.Label1.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // nudSubTotal // this.nudSubTotal.DecimalPlaces = 2; this.nudSubTotal.Enabled = false; this.nudSubTotal.ForeColor = System.Drawing.Color.Black; this.nudSubTotal.Location = new System.Drawing.Point(25, 404); this.nudSubTotal.Name = "nudSubTotal"; this.nudSubTotal.Size = new System.Drawing.Size(103, 20); this.nudSubTotal.TabIndex = 5; this.nudSubTotal.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // nudDescuento // this.nudDescuento.DecimalPlaces = 2; this.nudDescuento.Enabled = false; this.nudDescuento.ForeColor = System.Drawing.Color.Black; this.nudDescuento.Location = new System.Drawing.Point(138, 404); this.nudDescuento.Name = "nudDescuento"; this.nudDescuento.Size = new System.Drawing.Size(103, 20); this.nudDescuento.TabIndex = 6; this.nudDescuento.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // nudNetoPagar // this.nudNetoPagar.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(0)))), ((int)(((byte)(64)))), ((int)(((byte)(0))))); this.nudNetoPagar.DecimalPlaces = 2; this.nudNetoPagar.Enabled = false; this.nudNetoPagar.ForeColor = System.Drawing.Color.White; this.nudNetoPagar.Location = new System.Drawing.Point(251, 404); this.nudNetoPagar.Name = "nudNetoPagar"; this.nudNetoPagar.Size = new System.Drawing.Size(103, 20); this.nudNetoPagar.TabIndex = 7; this.nudNetoPagar.TextAlign = System.Windows.Forms.HorizontalAlignment.Right; // // label9 // this.label9.AutoSize = true; this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label9.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); this.label9.Location = new System.Drawing.Point(29, 444); this.label9.Name = "label9"; this.label9.Size = new System.Drawing.Size(76, 13); this.label9.TabIndex = 13; this.label9.Text = "Tipo Sangre"; this.label9.TextAlign = System.Drawing.ContentAlignment.MiddleRight; // // lblTipo // this.lblTipo.Font = new System.Drawing.Font("Microsoft Sans Serif", 20F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.lblTipo.ForeColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(0)))), ((int)(((byte)(0))))); this.lblTipo.Location = new System.Drawing.Point(24, 459); this.lblTipo.Name = "lblTipo"; this.lblTipo.Size = new System.Drawing.Size(86, 31); this.lblTipo.TabIndex = 13; this.lblTipo.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; // // frmClinica // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(427, 516); this.Controls.Add(this.nudNetoPagar); this.Controls.Add(this.nudDescuento); this.Controls.Add(this.nudSubTotal); this.Controls.Add(this.btnSalir); this.Controls.Add(this.btnNuevo); this.Controls.Add(this.btnGuardar); this.Controls.Add(this.gpbCondicion); this.Controls.Add(this.gpbAnalisis); this.Controls.Add(this.gpbEspecialidad); this.Controls.Add(this.txtPaciente); this.Controls.Add(this.Label3); this.Controls.Add(this.Label8); this.Controls.Add(this.Label7); this.Controls.Add(this.lblTipo); this.Controls.Add(this.label9); this.Controls.Add(this.Label6); this.Controls.Add(this.txtNumero); this.Controls.Add(this.Label2); this.Controls.Add(this.Label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "frmClinica"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Clinica \"Internacional\""; this.gpbCondicion.ResumeLayout(false); this.gpbCondicion.PerformLayout(); this.gpbAnalisis.ResumeLayout(false); this.gpbAnalisis.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.nudCostoAnalisis)).EndInit(); this.gpbEspecialidad.ResumeLayout(false); this.gpbEspecialidad.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.nudCostoConsulta)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.nudSubTotal)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.nudDescuento)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.nudNetoPagar)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion internal System.Windows.Forms.Button btnSalir; internal System.Windows.Forms.Button btnNuevo; internal System.Windows.Forms.Button btnGuardar; internal System.Windows.Forms.GroupBox gpbCondicion; internal System.Windows.Forms.RadioButton rbtCondicionE; internal System.Windows.Forms.RadioButton rbtCondicionD; internal System.Windows.Forms.RadioButton rbtCondicionC; internal System.Windows.Forms.RadioButton rbtCondicionB; internal System.Windows.Forms.RadioButton rbtCondicionA; internal System.Windows.Forms.GroupBox gpbAnalisis; private System.Windows.Forms.NumericUpDown nudCostoAnalisis; internal System.Windows.Forms.CheckBox chkOrina; internal System.Windows.Forms.CheckBox chkSangre; internal System.Windows.Forms.Label Label5; internal System.Windows.Forms.GroupBox gpbEspecialidad; private System.Windows.Forms.NumericUpDown nudCostoConsulta; internal System.Windows.Forms.RadioButton rbtPediatria; internal System.Windows.Forms.RadioButton rbtMedicina; internal System.Windows.Forms.RadioButton rbtGinecologia; internal System.Windows.Forms.RadioButton rbtOftalmologia; internal System.Windows.Forms.RadioButton rbtOdontologia; internal System.Windows.Forms.Label Label4; internal System.Windows.Forms.TextBox txtPaciente; internal System.Windows.Forms.Label Label3; internal System.Windows.Forms.Label Label8; internal System.Windows.Forms.Label Label7; internal System.Windows.Forms.Label Label6; internal System.Windows.Forms.TextBox txtNumero; internal System.Windows.Forms.Label Label2; internal System.Windows.Forms.Label Label1; private System.Windows.Forms.NumericUpDown nudSubTotal; private System.Windows.Forms.NumericUpDown nudDescuento; private System.Windows.Forms.NumericUpDown nudNetoPagar; internal System.Windows.Forms.RadioButton rbtTipoAB2; internal System.Windows.Forms.RadioButton rbtTipoAB1; internal System.Windows.Forms.RadioButton rbtTipoB2; internal System.Windows.Forms.RadioButton rbtTipoO2; internal System.Windows.Forms.RadioButton rbtTipoO1; internal System.Windows.Forms.RadioButton rbtTipoB1; internal System.Windows.Forms.RadioButton rbtTipoA2; internal System.Windows.Forms.RadioButton rbtTipoA1; internal System.Windows.Forms.Label label9; internal System.Windows.Forms.Label lblTipo; } }
51.606461
170
0.592903
[ "MIT" ]
jazuflo/SistemaClinicas
ClinicaInternacional/DemoWF13/frmClinica.Designer.cs
35,165
C#
using System.Net; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Diagnostics; using Microsoft.AspNetCore.Http; using NLog; using NLog.Fluent; namespace Quantumart.QP8.WebMvc { public class GlobalExceptionHandler { private static readonly ILogger Logger = LogManager.GetCurrentClassLogger(); public void Action(IApplicationBuilder options) { options.Run(async context => { context.Response.StatusCode = (int)HttpStatusCode.InternalServerError; context.Response.ContentType = "text/html"; var ex = context.Features.Get<IExceptionHandlerFeature>(); if (ex != null) { Logger.Error() .Exception(ex.Error) .Message("Unhandled exception occurs") .Write(); var err = $"<h1>Error: {ex.Error.Message}</h1>{ex.Error.StackTrace}"; await context.Response.WriteAsync(err).ConfigureAwait(false); } }); } } }
32.114286
89
0.563167
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
QuantumArt/QP
siteMvc/GlobalExceptionHandler.cs
1,124
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.RecoveryServices.V20210201Preview.Outputs { [OutputType] public sealed class DailyRetentionScheduleResponse { /// <summary> /// Retention duration of retention Policy. /// </summary> public readonly Outputs.RetentionDurationResponse? RetentionDuration; /// <summary> /// Retention times of retention policy. /// </summary> public readonly ImmutableArray<string> RetentionTimes; [OutputConstructor] private DailyRetentionScheduleResponse( Outputs.RetentionDurationResponse? retentionDuration, ImmutableArray<string> retentionTimes) { RetentionDuration = retentionDuration; RetentionTimes = retentionTimes; } } }
30.611111
81
0.680581
[ "Apache-2.0" ]
sebtelko/pulumi-azure-native
sdk/dotnet/RecoveryServices/V20210201Preview/Outputs/DailyRetentionScheduleResponse.cs
1,102
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; class Program { static void Main() { int n = int.Parse(Console.ReadLine()); int upperDots = (3 * n - 2) / 2; int upperSpaces = 0; //top for (int i = 1; i <= n; i++) { Console.WriteLine("{0}/{1}\\{0}", new string('.', upperDots), new string(' ', upperSpaces)); upperDots--; upperSpaces = upperSpaces + 2; } Console.WriteLine("{0}{1}{0}", new string('.', n / 2), new string('*', n * 2)); //mid for (int i = 1; i <= n * 2; i++) { Console.WriteLine("{0}|{1}|{0}", new string('.', n / 2), new string('\\', n * 2 - 2)); } //bot int botDots = n / 2; int botStars = n * 2 - 2; for (int i = 1; i <= n / 2; i++) { Console.WriteLine("{0}/{1}\\{0}", new string('.', botDots), new string('*', botStars)); botDots--; botStars = botStars + 2; } } }
26.707317
104
0.453881
[ "MIT" ]
Avarea/Programming-Basics
Exams/5Rocket/Program.cs
1,097
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public static class MathUtils { public static Vector2[] GenerateIsometricCirclePoints(float radius) { List<Vector2> points = new List<Vector2>(); float rotation = 0; int smoothness = 20; float ang = 0; float o = rotation * Mathf.Deg2Rad; float radiusX = radius * 0.816f; float radiusY = radius * 0.816f / 2; for (int i = 0; i <= smoothness; i++) { float a = ang * Mathf.Deg2Rad; float x = radiusX * Mathf.Cos(a) * Mathf.Cos(o) - radiusY * Mathf.Sin(a) * Mathf.Sin(o); float y = -radiusX * Mathf.Cos(a) * Mathf.Sin(o) - radiusY * Mathf.Sin(a) * Mathf.Cos(o); points.Add(new Vector2(x, y)); ang += 360f/smoothness; } points.RemoveAt(0); return points.ToArray(); } public static float ConvertStandardToAzimuth(float originalRotation) { float azimuthRotation; if(originalRotation >= 0 && originalRotation < 90) { azimuthRotation = 90 - originalRotation; } else if(originalRotation >= 90 && originalRotation < 180) { azimuthRotation = 270 + ( 90 - ( originalRotation - 90 ) ); } else if(originalRotation >= 180 && originalRotation < 270) { azimuthRotation = 180 + ( 90 - ( originalRotation - 180 ) ); } else { azimuthRotation = 90 + ( 270 - (originalRotation - 90) ); } return azimuthRotation; } public static void ConvertCircleToIsometricCircle(float radius, GameObject circularIndicatorObject) { circularIndicatorObject.transform.localScale = new Vector3(radius * 0.825f, radius * 0.5f * 0.825f, 1.0f); // this assumes the graphic is 512x512, and pixels per unit is 256! } }
33.22807
182
0.590813
[ "MIT" ]
XenikaIllust/Github-GameOff-2021
Assets/Scripts/Utilities/MathUtils.cs
1,894
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Akka.Util.Internal; using ConcurrentExecutorService.Messages; using ConcurrentExecutorService.Tests.TestSystem; using Xunit; namespace ConcurrentExecutorService.Tests { public class TestHelper { public static long TestOperationExecution(int numberOfBaskets, int numberOfPurchaseFromOneBasketCount,Action<List<string>,IPurchaseServiceFactory> executor, TimeSpan maxExecutionTimePerAskCall) { //Arrange var baskets = new ConcurrentDictionary<string, bool>(); var orders = new ConcurrentDictionary<string, string>(); //Act - obtain expected result for (var i = 0; i < numberOfBaskets; i++) baskets[Guid.NewGuid().ToString()] = true; var basketIds = ObtainBasketIds(baskets, numberOfPurchaseFromOneBasketCount); var purchaseService = new DelayedPurchaseServiceFactory(baskets, orders); basketIds.ForEach(basket => { var result = purchaseService.RunPurchaseServiceAsync(basket).Result; }); //var expected = baskets.Select(b => b.Key); Assert.All(baskets, b => Assert.Equal(1, orders.Count(o => o.Value == b.Key))); //undo baskets.ForEach(b => { baskets[b.Key] = true; }); orders = new ConcurrentDictionary<string, string>(); purchaseService = new DelayedPurchaseServiceFactory(baskets, orders); var watch = Stopwatch.StartNew(); executor(basketIds, purchaseService); watch.Stop(); var elapsedMs = watch.ElapsedMilliseconds; Assert.All(baskets, b => Assert.Equal(1, orders.Count(o => o.Value == b.Key))); return elapsedMs; } private static List<string> ObtainBasketIds(ConcurrentDictionary<string, bool> baskets, int numberOfPurchaseFromOneBasketCount) { var basketIds = new List<string>(); foreach (var keyValuePair in baskets) for (var i = 0; i < numberOfPurchaseFromOneBasketCount; i++) basketIds.Add(keyValuePair.Key); return basketIds; } } }
36.171875
164
0.638445
[ "MIT" ]
contactsamie/ConcurrentExecutorService
ConcurrentExecutorService.Tests/TestHelper.cs
2,317
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/MsHTML.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="SVGTextPathElement" /> struct.</summary> public static unsafe partial class SVGTextPathElementTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="SVGTextPathElement" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(SVGTextPathElement).GUID, Is.EqualTo(IID_SVGTextPathElement)); } /// <summary>Validates that the <see cref="SVGTextPathElement" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<SVGTextPathElement>(), Is.EqualTo(sizeof(SVGTextPathElement))); } /// <summary>Validates that the <see cref="SVGTextPathElement" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(SVGTextPathElement).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="SVGTextPathElement" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(SVGTextPathElement), Is.EqualTo(1)); } }
37.590909
145
0.71584
[ "MIT" ]
reflectronic/terrafx.interop.windows
tests/Interop/Windows/Windows/um/MsHTML/SVGTextPathElementTests.cs
1,656
C#
using System.Data.Common; using System.Data.Entity; using System.Data.Entity.Migrations.History; namespace SunLine.Community.Repositories { public class ExHistoryContext : HistoryContext { public ExHistoryContext(DbConnection dbConnection, string defaultSchema) : base(dbConnection, defaultSchema) { } protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<HistoryRow>().ToTable(tableName: "MigrationHistories"); } } }
28.142857
87
0.688663
[ "Apache-2.0" ]
mczachurski/community
SunLine.Community.Repositories/ExHistoryContext.cs
593
C#
//CPOL, 2010, Stan Kirk //MIT, 2015-present, EngineKit using System; using System.IO; using System.Net; namespace SharpConnect { #if DEBUG static class dbugLOG { //object that will be used to lock the listOfDataHolders static readonly object lockerForList = new object(); //If you make this true, then the IncomingDataPreparer will not write to // a List<T>, and you will not see the printout of the data at the end //of the log. public static readonly bool runLongTest = false; //If you make this true, then info about threads will print to log. public static readonly bool watchThreads = false; //If you make this true, then the above "watch-" variables will print to //both Console and log, instead of just to log. I suggest only using this if //you are having a problem with an application that is crashing. public static readonly bool consoleWatch = false; //static List<DataHolder> dbugDataHolderList; //This is for logging during testing. //You can change the path in the TestFileWriter class if you need to. //If you make this a positive value, it will simulate some delay on the //receive/send SAEA object after doing a receive operation. //That would be where you would do some work on the received data, //before responding to the client. //This is in milliseconds. So a value of 1000 = 1 second delay. public static readonly Int32 msDelayAfterGettingMessage = -1; public static bool enableDebugLog = false; //If this is true, then info about which method the program is in //will print to log. public static bool watchProgramFlow = true; //If you make this true, then connect/disconnect info will print to log. public static readonly bool watchConnectAndDisconnect = true; //If you make this true, then data will print to log. //public static readonly bool watchData = true; static dbugTestFileWriter testWriter; // To keep a record of maximum number of simultaneous connections // that occur while the server is running. This can be limited by operating // system and hardware. It will not be higher than the value that you set // for maxNumberOfConnections. public static Int32 maxSimultaneousClientsThatWereConnected = 0; //These strings are just for console interaction. public const string checkString = "C"; public const string closeString = "Z"; public const string wpf = "T"; public const string wpfNo = "F"; public static string wpfTrueString = ""; public static string wpfFalseString = ""; static object lockStart = new object(); static bool isInit = false; internal static void StartLog() { //lock (lockStart) //{ // if (!isInit) // { // //init once // BuildStringsForServerConsole(); // testWriter = new dbugTestFileWriter(); // isInit = true; // } //} } ///// <summary> ///// /Display thread info.,Use this one in method where AcceptOpUserToken is available. ///// </summary> ///// <param name="methodName"></param> ///// <param name="acceptToken"></param> //public static void dbugDealWithThreadsForTesting(SocketServer socketServer, string methodName, dbugAcceptOpUserToken acceptToken) //{ // StringBuilder sb = new StringBuilder(); // string hString = hString = ". Socket handle " + acceptToken.dbugSocketHandleNumber; // sb.Append(" In " + methodName + ", acceptToken id " + acceptToken.dbugTokenId + ". Thread id " + Thread.CurrentThread.ManagedThreadId + hString + "."); // sb.Append(socketServer.dbugDealWithNewThreads()); // dbugLOG.WriteLine(sb.ToString()); //} [System.Diagnostics.Conditional("DEBUG")] public static void dbugLog(string msg) { //if (dbugLOG.enableDebugLog && dbugLOG.watchProgramFlow) //for testing //{ // dbugLOG.WriteLine(msg); //} } internal static void WriteLine(string str) { //testWriter.WriteLine(str); } static void BuildStringsForServerConsole() { //if (dbugLOG.enableDebugLog) //{ // StringBuilder sb = new StringBuilder(); // // Make the string to write. // sb.Append("\r\n"); // sb.Append("\r\n"); // sb.Append("To take any of the following actions type the \r\ncorresponding letter below and press Enter.\r\n"); // sb.Append(closeString); // sb.Append(") to close the program\r\n"); // sb.Append(checkString); // sb.Append(") to check current status\r\n"); // string tempString = sb.ToString(); // sb.Length = 0; // // string when watchProgramFlow == true // sb.Append(wpfNo); // sb.Append(") to quit writing program flow. (ProgramFlow is being logged now.)\r\n"); // wpfTrueString = tempString + sb.ToString(); // sb.Length = 0; // // string when watchProgramFlow == false // sb.Append(wpf); // sb.Append(") to start writing program flow. (ProgramFlow is NOT being logged.)\r\n"); // wpfFalseString = tempString + sb.ToString(); //} } internal static void WriteSetupInfo(IPEndPoint localEndPoint) { //Console.WriteLine("The following options can be changed in Program.cs file."); //Console.WriteLine("server buffer size = " + testBufferSize); //Console.WriteLine("max connections = " + maxNumberOfConnections); //Console.WriteLine("backlog variable value = " + backlog); //Console.WriteLine("watchProgramFlow = " + dbugWatchProgramFlow); //Console.WriteLine("watchConnectAndDisconnect = " + watchConnectAndDisconnect); //Console.WriteLine("watchThreads = " + dbugWatchThreads); //Console.WriteLine("msDelayAfterGettingMessage = " + dbugMsDelayAfterGettingMessage); //if (dbugLOG.enableDebugLog) //{ // Console.WriteLine(); // Console.WriteLine(); // Console.WriteLine("local endpoint = " + IPAddress.Parse(((IPEndPoint)localEndPoint).Address.ToString()) + ": " + ((IPEndPoint)localEndPoint).Port.ToString()); // Console.WriteLine("server machine name = " + Environment.MachineName); // Console.WriteLine(); // Console.WriteLine("Client and server should be on separate machines for best results."); // Console.WriteLine("And your firewalls on both client and server will need to allow the connection."); // Console.WriteLine(); //} } static void WriteLogData() { //if ((watchData) && (runLongTest)) //{ // Program.testWriter.WriteLine("\r\n\r\nData from DataHolders in listOfDataHolders follows:\r\n"); // int listCount = dbugDataHolderList.Count; // for (int i = 0; i < listCount; i++) // { // //DataHolder dataHolder = dbugDataHolderList[i]; // //Program.testWriter.WriteLine(IPAddress.Parse(((IPEndPoint)dataHolder.remoteEndpoint).Address.ToString()) + ": " + // // ((IPEndPoint)dataHolder.remoteEndpoint).Port.ToString() + ", " + dataHolder.receivedTransMissionId + ", " + // // Encoding.ASCII.GetString(dataHolder.dataMessageReceived)); // } //} //testWriter.WriteLine("\r\nHighest # of simultaneous connections was " + maxSimultaneousClientsThatWereConnected); //testWriter.WriteLine("# of transmissions received was " + (mainTransMissionId - startingTid)); } } #endif #if DEBUG static class dbugConsole { static LogWriter _logWriter; static dbugConsole() { //set _logWriter = new LogWriter(null);//not write anything to disk //logWriter = new LogWriter("d:\\WImageTest\\log1.txt"); } [System.Diagnostics.Conditional("DEBUG")] public static void WriteLine(string str) { _logWriter.Write(str); _logWriter.Write("\r\n"); } [System.Diagnostics.Conditional("DEBUG")] public static void Write(string str) { _logWriter.Write(str); } class LogWriter : IDisposable { string filename; FileStream fs; StreamWriter writer; public LogWriter(string logFilename) { filename = logFilename; if (!string.IsNullOrEmpty(logFilename)) { fs = new FileStream(logFilename, FileMode.Create); writer = new StreamWriter(fs); } } public void Dispose() { if (writer != null) { writer.Flush(); writer.Dispose(); writer = null; } if (fs != null) { fs.Dispose(); fs = null; } } public void Write(string data) { if (writer != null) { writer.Write(data); writer.Flush(); } } } } #endif //-------------------------------------------------- }
39.835294
176
0.552668
[ "MIT" ]
SharpConnect/SharpConnect.WebServer
src/SharpConnect.WebServer/General/dbugLOG.cs
10,158
C#
using System; using System.IO; using System.Threading.Tasks; using Esfa.Recruit.Vacancies.Client.Application.Queues.Messages; using Esfa.Recruit.Vacancies.Client.Infrastructure.Client; using Esfa.Recruit.Vacancies.Client.Infrastructure.StorageQueue; using Esfa.Recruit.Vacancies.Jobs.Configuration; using Esfa.Recruit.Vacancies.Jobs.Jobs; using Microsoft.Azure.WebJobs; using Microsoft.Extensions.Logging; using Newtonsoft.Json; namespace Esfa.Recruit.Vacancies.Jobs.Triggers.QueueTriggers { public class TransferVacancyToLegalEntityQueueTrigger { private readonly ILogger<TransferVacancyToLegalEntityQueueTrigger> _logger; private readonly RecruitWebJobsSystemConfiguration _jobsConfig; private readonly IJobsVacancyClient _client; private readonly TransferVacancyToLegalEntityJob _runner; private string TriggerName => GetType().Name; public TransferVacancyToLegalEntityQueueTrigger(ILogger<TransferVacancyToLegalEntityQueueTrigger> logger, RecruitWebJobsSystemConfiguration jobsConfig, IJobsVacancyClient client, TransferVacancyToLegalEntityJob runner) { _logger = logger; _jobsConfig = jobsConfig; _client = client; _runner = runner; } public async Task TransferVacancyToLegalEntityAsync([QueueTrigger(QueueNames.TransferVacanciesToLegalEntityQueueName, Connection = "QueueStorage")] string message, TextWriter log) { if (_jobsConfig.DisabledJobs.Contains(TriggerName)) { _logger.LogDebug($"{TriggerName} is disabled, skipping ..."); return; } if (!string.IsNullOrEmpty(message)) { _logger.LogInformation($"Starting queueing vacancy to transfer."); try { var queueMessage = JsonConvert.DeserializeObject<TransferVacancyToLegalEntityQueueMessage>(message); await _runner.Run(queueMessage.VacancyReference, queueMessage.UserRef, queueMessage.UserEmailAddress, queueMessage.UserName, queueMessage.TransferReason); _logger.LogInformation("Finished queuing vacancy to transfer."); } catch (Exception ex) { _logger.LogError(ex, "Unable to queue vacancy to transfer."); throw; } } } } }
41.163934
187
0.665472
[ "MIT" ]
SkillsFundingAgency/das-recru
src/Jobs/Recruit.Vacancies.Jobs/Triggers/QueueTriggers/TransferVacancyToLegalEntityQueueTrigger.cs
2,511
C#
using UnityEngine; public class CameraTarget : MonoBehaviour { /// <summary> /// Step #1 /// We need a simple reference of joystick in the script /// that we need add it. /// </summary> [SerializeField] private Movement Joystick = null;//Joystick reference for assign in inspector [SerializeField] private float Speed = 5; [SerializeField] private float maxLookUp = 270f; [SerializeField] private float maxLookDown = 85f; void Update() { //Step #2 //Change Input.GetAxis (or the input that you using) to Joystick.Vertical or Joystick.Horizontal float v = Joystick.Vertical; //get the vertical value of joystick float h = Joystick.Horizontal;//get the horizontal value of joystick //in case you using keys instead of axis (due keys are bool and not float) you can do this: //bool isKeyPressed = (Joystick.Horizontal > 0) ? true : false; if ((transform.eulerAngles.x - v < maxLookDown) || (transform.eulerAngles.x - v > maxLookUp)) { Vector3 translate = (new Vector3(-v, 0.0f, 0.0f) * Time.deltaTime) * Speed; transform.Rotate(translate, Space.Self); transform.parent.Rotate((new Vector3(0.0f, h, 0.0f) * Time.deltaTime) * Speed, Space.Self); } } }
39.878788
104
0.641337
[ "MIT" ]
lolpez/jalaboy-game
Assets/UI/Scripts/CameraTarget.cs
1,318
C#
#pragma checksum "D:\PrivateSmartHome\SubServer\SubServer\App.xaml" "{406ea660-64cf-4c82-b6f0-42d48172a799}" "66483615C6522D60A20A07F0FD97D2B0" //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace FacialRecognizedDoorClient { #if !DISABLE_XAML_GENERATED_MAIN /// <summary> /// Program class /// </summary> public static class Program { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] static void Main(string[] args) { global::Windows.UI.Xaml.Application.Start((p) => new App()); } } #endif partial class App : global::Windows.UI.Xaml.Application { [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] private bool _contentLoaded; /// <summary> /// InitializeComponent() /// </summary> [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.Windows.UI.Xaml.Build.Tasks"," 14.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] public void InitializeComponent() { if (_contentLoaded) return; _contentLoaded = true; #if DEBUG && !DISABLE_XAML_GENERATED_BINDING_DEBUG_OUTPUT DebugSettings.BindingFailed += (sender, args) => { global::System.Diagnostics.Debug.WriteLine(args.Message); }; #endif #if DEBUG && !DISABLE_XAML_GENERATED_BREAK_ON_UNHANDLED_EXCEPTION UnhandledException += (sender, e) => { if (global::System.Diagnostics.Debugger.IsAttached) global::System.Diagnostics.Debugger.Break(); }; #endif } } }
35.816667
144
0.592369
[ "MIT" ]
jjg0519/PrivateSmartHome
SubServer/SubServer/obj/ARM/Debug/App.g.i.cs
2,151
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Linq; public partial class Math { //Only append content to this class as the test suite depends on line info public static int IntAdd(int a, int b) { int c = a + b; int d = c + b; int e = d + a; bool f = true; return e; } public static int UseComplex(int a, int b) { var complex = new Simple.Complex(10, "xx"); int c = a + b; int d = c + b; int e = d + a; int f = 0; e += complex.DoStuff(); return e; } delegate bool IsMathNull(Math m); public static int DelegatesTest() { Func<Math, bool> fn_func = (Math m) => m == null; Func<Math, bool> fn_func_null = null; Func<Math, bool>[] fn_func_arr = new Func<Math, bool>[] { (Math m) => m == null }; Math.IsMathNull fn_del = Math.IsMathNullDelegateTarget; var fn_del_arr = new Math.IsMathNull[] { Math.IsMathNullDelegateTarget }; var m_obj = new Math(); Math.IsMathNull fn_del_null = null; bool res = fn_func(m_obj) && fn_del(m_obj) && fn_del_arr[0](m_obj) && fn_del_null == null && fn_func_null == null && fn_func_arr[0] != null; // Unused locals Func<Math, bool> fn_func_unused = (Math m) => m == null; Func<Math, bool> fn_func_null_unused = null; Func<Math, bool>[] fn_func_arr_unused = new Func<Math, bool>[] { (Math m) => m == null }; Math.IsMathNull fn_del_unused = Math.IsMathNullDelegateTarget; Math.IsMathNull fn_del_null_unused = null; var fn_del_arr_unused = new Math.IsMathNull[] { Math.IsMathNullDelegateTarget }; OuterMethod(); Console.WriteLine("Just a test message, ignore"); return res ? 0 : 1; } public static int GenericTypesTest() { var list = new System.Collections.Generic.Dictionary<Math[], IsMathNull>(); System.Collections.Generic.Dictionary<Math[], IsMathNull> list_null = null; var list_arr = new System.Collections.Generic.Dictionary<Math[], IsMathNull>[] { new System.Collections.Generic.Dictionary<Math[], IsMathNull>() }; System.Collections.Generic.Dictionary<Math[], IsMathNull>[] list_arr_null = null; Console.WriteLine($"list_arr.Length: {list_arr.Length}, list.Count: {list.Count}"); // Unused locals var list_unused = new System.Collections.Generic.Dictionary<Math[], IsMathNull>(); System.Collections.Generic.Dictionary<Math[], IsMathNull> list_null_unused = null; var list_arr_unused = new System.Collections.Generic.Dictionary<Math[], IsMathNull>[] { new System.Collections.Generic.Dictionary<Math[], IsMathNull>() }; System.Collections.Generic.Dictionary<Math[], IsMathNull>[] list_arr_null_unused = null; OuterMethod(); Console.WriteLine("Just a test message, ignore"); return 0; } static bool IsMathNullDelegateTarget(Math m) => m == null; public static void OuterMethod() { Console.WriteLine($"OuterMethod called"); var nim = new Math.NestedInMath(); var i = 5; var text = "Hello"; var new_i = nim.InnerMethod(i); Console.WriteLine($"i: {i}"); Console.WriteLine($"-- InnerMethod returned: {new_i}, nim: {nim}, text: {text}"); int k = 19; new_i = InnerMethod2("test string", new_i, out k); Console.WriteLine($"-- InnerMethod2 returned: {new_i}, and k: {k}"); } static int InnerMethod2(string s, int i, out int k) { k = i + 10; Console.WriteLine($"s: {s}, i: {i}, k: {k}"); return i - 2; } public class NestedInMath { public int InnerMethod(int i) { SimpleStructProperty = new SimpleStruct() { dt = new DateTime(2020, 1, 2, 3, 4, 5) }; int j = i + 10; string foo_str = "foo"; Console.WriteLine($"i: {i} and j: {j}, foo_str: {foo_str} "); j += 9; Console.WriteLine($"i: {i} and j: {j}"); return j; } Math m = new Math(); public async System.Threading.Tasks.Task<bool> AsyncMethod0(string s, int i) { string local0 = "value0"; await System.Threading.Tasks.Task.Delay(1); Console.WriteLine($"* time for the second await, local0: {local0}"); await AsyncMethodNoReturn(); return true; } public async System.Threading.Tasks.Task AsyncMethodNoReturn() { var ss = new SimpleStruct() { dt = new DateTime(2020, 1, 2, 3, 4, 5) }; var ss_arr = new SimpleStruct[] { }; //ss.gs.StringField = "field in GenericStruct"; //Console.WriteLine ($"Using the struct: {ss.dt}, {ss.gs.StringField}, ss_arr: {ss_arr.Length}"); string str = "AsyncMethodNoReturn's local"; //Console.WriteLine ($"* field m: {m}"); await System.Threading.Tasks.Task.Delay(1); Console.WriteLine($"str: {str}"); } public static async System.Threading.Tasks.Task<bool> AsyncTest(string s, int i) { var li = 10 + i; var ls = s + "test"; return await new NestedInMath().AsyncMethod0(s, i); } public SimpleStruct SimpleStructProperty { get; set; } } public static void PrimitiveTypesTest() { char c0 = '€'; char c1 = 'A'; // TODO: other types! // just trying to ensure vars don't get optimized out if (c0 < 32 || c1 > 32) Console.WriteLine($"{c0}, {c1}"); } public static int DelegatesSignatureTest() { Func<Math, GenericStruct<GenericStruct<int[]>>, GenericStruct<bool[]>> fn_func = (m, gs) => new GenericStruct<bool[]>(); Func<Math, GenericStruct<GenericStruct<int[]>>, GenericStruct<bool[]>> fn_func_del = GenericStruct<int>.DelegateTargetForSignatureTest; Func<Math, GenericStruct<GenericStruct<int[]>>, GenericStruct<bool[]>> fn_func_null = null; Func<bool> fn_func_only_ret = () => { Console.WriteLine($"hello"); return true; }; var fn_func_arr = new Func<Math, GenericStruct<GenericStruct<int[]>>, GenericStruct<bool[]>>[] { (m, gs) => new GenericStruct<bool[]> () }; Math.DelegateForSignatureTest fn_del = GenericStruct<int>.DelegateTargetForSignatureTest; Math.DelegateForSignatureTest fn_del_l = (m, gs) => new GenericStruct<bool[]> { StringField = "fn_del_l#lambda" }; var fn_del_arr = new Math.DelegateForSignatureTest[] { GenericStruct<int>.DelegateTargetForSignatureTest, (m, gs) => new GenericStruct<bool[]> { StringField = "fn_del_arr#1#lambda" } }; var m_obj = new Math(); Math.DelegateForSignatureTest fn_del_null = null; var gs_gs = new GenericStruct<GenericStruct<int[]>> { List = new System.Collections.Generic.List<GenericStruct<int[]>> { new GenericStruct<int[]> { StringField = "gs#List#0#StringField" }, new GenericStruct<int[]> { StringField = "gs#List#1#StringField" } } }; Math.DelegateWithVoidReturn fn_void_del = Math.DelegateTargetWithVoidReturn; var fn_void_del_arr = new Math.DelegateWithVoidReturn[] { Math.DelegateTargetWithVoidReturn }; Math.DelegateWithVoidReturn fn_void_del_null = null; var rets = new GenericStruct<bool[]>[] { fn_func(m_obj, gs_gs), fn_func_del(m_obj, gs_gs), fn_del(m_obj, gs_gs), fn_del_l(m_obj, gs_gs), fn_del_arr[0](m_obj, gs_gs), fn_func_arr[0](m_obj, gs_gs) }; var gs = new GenericStruct<int[]>(); fn_void_del(gs); fn_void_del_arr[0](gs); fn_func_only_ret(); foreach (var ret in rets) Console.WriteLine($"ret: {ret}"); OuterMethod(); Console.WriteLine($"- {gs_gs.List[0].StringField}"); return 0; } public static int ActionTSignatureTest() { Action<GenericStruct<int[]>> fn_action = (_) => { }; Action<GenericStruct<int[]>> fn_action_del = Math.DelegateTargetWithVoidReturn; Action fn_action_bare = () => { }; Action<GenericStruct<int[]>> fn_action_null = null; var fn_action_arr = new Action<GenericStruct<int[]>>[] { (gs) => new GenericStruct<int[]>(), Math.DelegateTargetWithVoidReturn, null }; var gs = new GenericStruct<int[]>(); fn_action(gs); fn_action_del(gs); fn_action_arr[0](gs); fn_action_bare(); OuterMethod(); return 0; } public static int NestedDelegatesTest() { Func<Func<int, bool>, bool> fn_func = (_) => { return true; }; Func<Func<int, bool>, bool> fn_func_null = null; var fn_func_arr = new Func<Func<int, bool>, bool>[] { (gs) => { return true; } }; var fn_del_arr = new Func<Func<int, bool>, bool>[] { DelegateTargetForNestedFunc<Func<int, bool>> }; var m_obj = new Math(); Func<Func<int, bool>, bool> fn_del_null = null; Func<int, bool> fs = (i) => i == 0; fn_func(fs); fn_del_arr[0](fs); fn_func_arr[0](fs); OuterMethod(); return 0; } public static void DelegatesAsMethodArgsTest() { var _dst_arr = new DelegateForSignatureTest[] { GenericStruct<int>.DelegateTargetForSignatureTest, (m, gs) => new GenericStruct<bool[]>() }; Func<char[], bool> _fn_func = (cs) => cs.Length == 0; Action<GenericStruct<int>[]> _fn_action = (gss) => { }; new Math().MethodWithDelegateArgs(_dst_arr, _fn_func, _fn_action); } void MethodWithDelegateArgs(Math.DelegateForSignatureTest[] dst_arr, Func<char[], bool> fn_func, Action<GenericStruct<int>[]> fn_action) { Console.WriteLine($"Placeholder for breakpoint"); OuterMethod(); } public static async System.Threading.Tasks.Task MethodWithDelegatesAsyncTest() { await new Math().MethodWithDelegatesAsync(); } async System.Threading.Tasks.Task MethodWithDelegatesAsync() { var _dst_arr = new DelegateForSignatureTest[] { GenericStruct<int>.DelegateTargetForSignatureTest, (m, gs) => new GenericStruct<bool[]>() }; Func<char[], bool> _fn_func = (cs) => cs.Length == 0; Action<GenericStruct<int>[]> _fn_action = (gss) => { }; Console.WriteLine($"Placeholder for breakpoint"); await System.Threading.Tasks.Task.CompletedTask; } public delegate void DelegateWithVoidReturn(GenericStruct<int[]> gs); public static void DelegateTargetWithVoidReturn(GenericStruct<int[]> gs) { } public delegate GenericStruct<bool[]> DelegateForSignatureTest(Math m, GenericStruct<GenericStruct<int[]>> gs); static bool DelegateTargetForNestedFunc<T>(T arg) => true; public struct SimpleStruct { public DateTime dt; public GenericStruct<DateTime> gs; } public struct GenericStruct<T> { public System.Collections.Generic.List<T> List; public string StringField; public static GenericStruct<bool[]> DelegateTargetForSignatureTest(Math m, GenericStruct<GenericStruct<T[]>> gs) => new GenericStruct<bool[]>(); } public static void TestSimpleStrings() { string str_null = null; string str_empty = String.Empty; string str_spaces = " "; string str_esc = "\\"; var strings = new[] { str_null, str_empty, str_spaces, str_esc }; Console.WriteLine($"break here"); } } public class DebuggerTest { public static void run_all() { locals(); } public static int locals() { int l_int = 1; char l_char = 'A'; long l_long = Int64.MaxValue; ulong l_ulong = UInt64.MaxValue; locals_inner(); return 0; } static void locals_inner() { } public static void BoxingTest() { int? n_i = 5; object o_i = n_i.Value; object o_n_i = n_i; object o_s = "foobar"; object o_obj = new Math(); DebuggerTests.ValueTypesTest.GenericStruct<int>? n_gs = new DebuggerTests.ValueTypesTest.GenericStruct<int> { StringField = "n_gs#StringField" }; object o_gs = n_gs.Value; object o_n_gs = n_gs; DateTime? n_dt = new DateTime(2310, 1, 2, 3, 4, 5); object o_dt = n_dt.Value; object o_n_dt = n_dt; object o_null = null; object o_ia = new int[] {918, 58971}; Console.WriteLine ($"break here"); } public static async System.Threading.Tasks.Task BoxingTestAsync() { int? n_i = 5; object o_i = n_i.Value; object o_n_i = n_i; object o_s = "foobar"; object o_obj = new Math(); DebuggerTests.ValueTypesTest.GenericStruct<int>? n_gs = new DebuggerTests.ValueTypesTest.GenericStruct<int> { StringField = "n_gs#StringField" }; object o_gs = n_gs.Value; object o_n_gs = n_gs; DateTime? n_dt = new DateTime(2310, 1, 2, 3, 4, 5); object o_dt = n_dt.Value; object o_n_dt = n_dt; object o_null = null; object o_ia = new int[] {918, 58971}; Console.WriteLine ($"break here"); await System.Threading.Tasks.Task.CompletedTask; } public static void BoxedTypeObjectTest() { int i = 5; object o0 = i; object o1 = o0; object o2 = o1; object o3 = o2; object oo = new object(); object oo0 = oo; Console.WriteLine ($"break here"); } public static async System.Threading.Tasks.Task BoxedTypeObjectTestAsync() { int i = 5; object o0 = i; object o1 = o0; object o2 = o1; object o3 = o2; object oo = new object(); object oo0 = oo; Console.WriteLine ($"break here"); await System.Threading.Tasks.Task.CompletedTask; } public static void BoxedAsClass() { ValueType vt_dt = new DateTime(4819, 5, 6, 7, 8, 9); ValueType vt_gs = new Math.GenericStruct<string> { StringField = "vt_gs#StringField" }; Enum e = new System.IO.FileMode(); Enum ee = System.IO.FileMode.Append; Console.WriteLine ($"break here"); } public static async System.Threading.Tasks.Task BoxedAsClassAsync() { ValueType vt_dt = new DateTime(4819, 5, 6, 7, 8, 9); ValueType vt_gs = new Math.GenericStruct<string> { StringField = "vt_gs#StringField" }; Enum e = new System.IO.FileMode(); Enum ee = System.IO.FileMode.Append; Console.WriteLine ($"break here"); await System.Threading.Tasks.Task.CompletedTask; } } public class MulticastDelegateTestClass { event EventHandler<string> TestEvent; MulticastDelegate Delegate; public static void run() { var obj = new MulticastDelegateTestClass(); obj.Test(); obj.TestAsync().Wait(); } public void Test() { TestEvent += (_, s) => Console.WriteLine(s); TestEvent += (_, s) => Console.WriteLine(s + "qwe"); Delegate = TestEvent; TestEvent?.Invoke(this, Delegate?.ToString()); } public async System.Threading.Tasks.Task TestAsync() { TestEvent += (_, s) => Console.WriteLine(s); TestEvent += (_, s) => Console.WriteLine(s + "qwe"); Delegate = TestEvent; TestEvent?.Invoke(this, Delegate?.ToString()); await System.Threading.Tasks.Task.CompletedTask; } } public class EmptyClass { public static void StaticMethodWithNoLocals() { Console.WriteLine($"break here"); } public static async System.Threading.Tasks.Task StaticMethodWithNoLocalsAsync() { Console.WriteLine($"break here"); await System.Threading.Tasks.Task.CompletedTask; } public static void run() { StaticMethodWithNoLocals(); StaticMethodWithNoLocalsAsync().Wait(); } } public struct EmptyStruct { public static void StaticMethodWithNoLocals() { Console.WriteLine($"break here"); } public static async System.Threading.Tasks.Task StaticMethodWithNoLocalsAsync() { Console.WriteLine($"break here"); await System.Threading.Tasks.Task.CompletedTask; } public static void StaticMethodWithLocalEmptyStruct() { var es = new EmptyStruct(); Console.WriteLine($"break here"); } public static async System.Threading.Tasks.Task StaticMethodWithLocalEmptyStructAsync() { var es = new EmptyStruct(); Console.WriteLine($"break here"); await System.Threading.Tasks.Task.CompletedTask; } public static void run() { StaticMethodWithNoLocals(); StaticMethodWithNoLocalsAsync().Wait(); StaticMethodWithLocalEmptyStruct(); StaticMethodWithLocalEmptyStructAsync().Wait(); } } public class LoadDebuggerTest { public static void LoadLazyAssembly(string asm_base64, string pdb_base64) { byte[] asm_bytes = Convert.FromBase64String(asm_base64); byte[] pdb_bytes = null; if (pdb_base64 != null) pdb_bytes = Convert.FromBase64String(pdb_base64); var loadedAssembly = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(new System.IO.MemoryStream(asm_bytes), new System.IO.MemoryStream(pdb_bytes)); Console.WriteLine($"Loaded - {loadedAssembly}"); } } public class HiddenSequencePointTest { public static void StepOverHiddenSP() { Console.WriteLine("first line"); #line hidden Console.WriteLine("second line"); StepOverHiddenSP2(); #line default Console.WriteLine("third line"); MethodWithHiddenLinesAtTheEnd(); } public static void StepOverHiddenSP2() { Console.WriteLine("StepOverHiddenSP2"); } public static void MethodWithHiddenLinesAtTheEnd() { Console.WriteLine ($"MethodWithHiddenLinesAtTheEnd"); #line hidden Console.WriteLine ($"debugger shouldn't be able to step here"); } #line default } public class LoadDebuggerTestALC { static System.Reflection.Assembly loadedAssembly; public static void LoadLazyAssemblyInALC(string asm_base64, string pdb_base64) { var context = new System.Runtime.Loader.AssemblyLoadContext("testContext", true); byte[] asm_bytes = Convert.FromBase64String(asm_base64); byte[] pdb_bytes = null; if (pdb_base64 != null) pdb_bytes = Convert.FromBase64String(pdb_base64); loadedAssembly = context.LoadFromStream(new System.IO.MemoryStream(asm_bytes), new System.IO.MemoryStream(pdb_bytes)); Console.WriteLine($"Loaded - {loadedAssembly}"); } public static void RunMethodInALC(string type_name, string method_name) { var myType = loadedAssembly.GetType(type_name); var myMethod = myType.GetMethod(method_name); myMethod.Invoke(null, new object[] { 5, 10 }); } } public class TestHotReload { static System.Reflection.Assembly loadedAssembly; static byte[] dmeta_data1_bytes; static byte[] dil_data1_bytes; static byte[] dpdb_data1_bytes; static byte[] dmeta_data2_bytes; static byte[] dil_data2_bytes; static byte[] dpdb_data2_bytes; public static void LoadLazyHotReload(string asm_base64, string pdb_base64, string dmeta_data1, string dil_data1, string dpdb_data1, string dmeta_data2, string dil_data2, string dpdb_data2) { byte[] asm_bytes = Convert.FromBase64String(asm_base64); byte[] pdb_bytes = Convert.FromBase64String(pdb_base64); dmeta_data1_bytes = Convert.FromBase64String(dmeta_data1); dil_data1_bytes = Convert.FromBase64String(dil_data1); dpdb_data1_bytes = Convert.FromBase64String(dpdb_data1); dmeta_data2_bytes = Convert.FromBase64String(dmeta_data2); dil_data2_bytes = Convert.FromBase64String(dil_data2); dpdb_data2_bytes = Convert.FromBase64String(dpdb_data2); loadedAssembly = System.Runtime.Loader.AssemblyLoadContext.Default.LoadFromStream(new System.IO.MemoryStream(asm_bytes), new System.IO.MemoryStream(pdb_bytes)); Console.WriteLine($"Loaded - {loadedAssembly}"); } public static void RunMethod(string className, string methodName) { var ty = typeof(System.Reflection.Metadata.MetadataUpdater); var mi = ty.GetMethod("GetCapabilities", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Static, Array.Empty<Type>()); if (mi == null) return; var caps = mi.Invoke(null, null) as string; if (String.IsNullOrEmpty(caps)) return; var myType = loadedAssembly.GetType($"ApplyUpdateReferencedAssembly.{className}"); var myMethod = myType.GetMethod(methodName); myMethod.Invoke(null, null); ApplyUpdate(loadedAssembly, 1); myType = loadedAssembly.GetType($"ApplyUpdateReferencedAssembly.{className}"); myMethod = myType.GetMethod(methodName); myMethod.Invoke(null, null); ApplyUpdate(loadedAssembly, 2); myType = loadedAssembly.GetType($"ApplyUpdateReferencedAssembly.{className}"); myMethod = myType.GetMethod(methodName); myMethod.Invoke(null, null); } internal static void ApplyUpdate (System.Reflection.Assembly assm, int version) { string basename = assm.Location; if (basename == "") basename = assm.GetName().Name + ".dll"; Console.Error.WriteLine($"Apply Delta Update for {basename}, revision {version}"); if (version == 1) { System.Reflection.Metadata.MetadataUpdater.ApplyUpdate(assm, dmeta_data1_bytes, dil_data1_bytes, dpdb_data1_bytes); } else if (version == 2) { System.Reflection.Metadata.MetadataUpdater.ApplyUpdate(assm, dmeta_data2_bytes, dil_data2_bytes, dpdb_data2_bytes); } } } public class Something { public string Name { get; set; } public Something() => Name = "Same of something"; public override string ToString() => Name; } public class Foo { public string Bar => Stuffs.First(x => x.Name.StartsWith('S')).Name; public System.Collections.Generic.List<Something> Stuffs { get; } = Enumerable.Range(0, 10).Select(x => new Something()).ToList(); public string Lorem { get; set; } = "Safe"; public string Ipsum { get; set; } = "Side"; public Something What { get; } = new Something(); public int Bart() { int ret; if (Lorem.StartsWith('S')) ret = 0; else ret = 1; return ret; } public static void RunBart() { Foo foo = new Foo(); foo.Bart(); Console.WriteLine(foo.OtherBar()); foo.OtherBarAsync().Wait(10); } public bool OtherBar() { var a = 1; var b = 2; var x = "Stew"; var y = "00.123"; var c = a + b == 3 || b + a == 2; var d = TimeSpan.TryParseExact(y, @"ss\.fff", null, out var ts) && x.Contains('S'); var e = TimeSpan.TryParseExact(y, @"ss\.fff", null, out var ts1) && x.Contains('S'); var f = TimeSpan.TryParseExact(y, @"ss\.fff", null, out var ts2) && x.Contains('S'); var g = TimeSpan.TryParseExact(y, @"ss\.fff", null, out var ts3) && x.Contains('S'); return d && e == true; } public async System.Threading.Tasks.Task OtherBarAsync() { var a = 1; var b = 2; var x = "Stew"; var y = "00.123"; var c = a + b == 3 || b + a == 2; var d = TimeSpan.TryParseExact(y, @"ss\.fff", null, out var ts) && await AsyncMethod(); var e = TimeSpan.TryParseExact(y, @"ss\.fff", null, out var ts1) && await AsyncMethod(); var f = TimeSpan.TryParseExact(y, @"ss\.fff", null, out var ts2) && await AsyncMethod(); var g = await AsyncMethod() && await AsyncMethod(); Console.WriteLine(g); await System.Threading.Tasks.Task.CompletedTask; } public async System.Threading.Tasks.Task<bool> AsyncMethod() { await System.Threading.Tasks.Task.Delay(1); Console.WriteLine($"time for await"); return true; } } public class MainPage { public MainPage() { } int count = 0; private int someValue; public int SomeValue { get { return someValue; } set { someValue = value; count++; if (count == 10) { var view = 150; if (view != 50) { } System.Diagnostics.Debugger.Break(); } SomeValue = count; } } public static void CallSetValue() { var mainPage = new MainPage(); mainPage.SomeValue = 10; } } public class LoopClass { public static void LoopToBreak() { for (int i = 0; i < 10; i++) { Console.WriteLine($"should pause only on i == 3"); } Console.WriteLine("breakpoint to check"); } } public class SteppingInto { static int currentCount = 0; static MyIncrementer incrementer = new MyIncrementer(); public static void MethodToStep() { currentCount = incrementer.Increment(currentCount); } } public class MyIncrementer { private Func<DateTime> todayFunc = () => new DateTime(2061, 1, 5); // Wednesday public int Increment(int count) { var today = todayFunc(); if (today.DayOfWeek == DayOfWeek.Sunday) { return count + 2; } return count + 1; } } public class DebuggerAttribute { static int currentCount = 0; [System.Diagnostics.DebuggerHidden] public static void HiddenMethod() { currentCount++; } [System.Diagnostics.DebuggerHidden] public static void HiddenMethodDebuggerBreak() { var local_var = 12; System.Diagnostics.Debugger.Break(); currentCount++; } public static void VisibleMethod() { currentCount++; } public static void VisibleMethodDebuggerBreak() { System.Diagnostics.Debugger.Break(); currentCount++; } public static void Run() { HiddenMethod(); VisibleMethod(); } public static void RunDebuggerBreak() { HiddenMethodDebuggerBreak(); VisibleMethodDebuggerBreak(); } [System.Diagnostics.DebuggerStepThroughAttribute] public static void NotStopOnJustMyCode() { var a = 0; currentCount++; var b = 1; } [System.Diagnostics.DebuggerStepThroughAttribute] public static void NotStopOnJustMyCodeUserBp() { System.Diagnostics.Debugger.Break(); } public static void RunStepThrough() { NotStopOnJustMyCode(); NotStopOnJustMyCodeUserBp(); } } public class DebugTypeFull { public static void CallToEvaluateLocal() { var asm = System.Reflection.Assembly.LoadFrom("debugger-test-with-full-debug-type.dll"); var myType = asm.GetType("DebuggerTests.ClassToInspectWithDebugTypeFull"); var myMethod = myType.GetConstructor(new Type[] { }); var a = myMethod.Invoke(new object[]{}); System.Diagnostics.Debugger.Break(); } }
32.049774
196
0.60084
[ "MIT" ]
PeterMond/runtime
src/mono/wasm/debugger/tests/debugger-test/debugger-test.cs
28,334
C#
using System; using System.Collections.Generic; using Microsoft.Bot.Builder.Calling.ObjectModel.Contracts; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; namespace Microsoft.Bot.Builder.Calling.ObjectModel.Misc { /// <summary> /// Helper class for serializing/deserializing /// </summary> public static class Serializer { private static readonly JsonSerializerSettings defaultSerializerSettings = Serializer.GetSerializerSettings(); private static readonly JsonSerializerSettings loggingSerializerSettings = Serializer.GetSerializerSettings(Formatting.Indented); /// <summary> /// Serialize input object to string /// </summary> public static string SerializeToJson(object obj, bool forLogging = false) { return JsonConvert.SerializeObject(obj, forLogging ? loggingSerializerSettings : defaultSerializerSettings); } /// <summary> /// Serialize to JToken /// </summary> /// <param name="obj"></param> /// <returns></returns> public static JToken SerializeToJToken(Object obj) { return JToken.FromObject(obj, JsonSerializer.Create(defaultSerializerSettings)); } /// <summary> /// Deserialize input string to object /// </summary> public static T DeserializeFromJson<T>(string json) { return JsonConvert.DeserializeObject<T>(json, defaultSerializerSettings); } /// <summary> /// Deserialize from JToken /// </summary> /// <typeparam name="T"></typeparam> /// <param name="jToken"></param> /// <returns></returns> public static T DeserializeFromJToken<T>(JToken jToken) { return jToken.ToObject<T>(JsonSerializer.Create(defaultSerializerSettings)); } /// <summary> /// Returns default serializer settings. /// </summary> public static JsonSerializerSettings GetSerializerSettings(Formatting formatting = Formatting.None) { return new JsonSerializerSettings() { Formatting = formatting, ContractResolver = new CamelCasePropertyNamesContractResolver(), NullValueHandling = NullValueHandling.Ignore, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, Converters = new List<JsonConverter> { new StringEnumConverter { CamelCaseText = true }, new ActionConverter(), new OperationOutcomeConverter(), new NotificationConverter() }, }; } } }
38.337838
191
0.646458
[ "MIT" ]
Aaron-Strong/BotBuilder
CSharp/Library/Microsoft.Bot.Builder.Calling/Models/Misc/Serializer.cs
2,839
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("AWSSDK.Lightsail")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Lightsail. An extremely simplified VM creation and management service.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2019 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.3.100.35")]
44.75
157
0.749302
[ "Apache-2.0" ]
ooohtv/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/Lightsail/Properties/AssemblyInfo.cs
1,432
C#
using System; using System.ServiceModel; using Autofac; using Autofac.Integration.Wcf; using GServer.Services; using NLog; using Topshelf; using Topshelf.Autofac; using Topshelf.HostConfigurators; namespace GServer.Host.Messaging { // ReSharper disable once ClassNeverInstantiated.Global - Instantiated by Topshelf public class MessagingService { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private ServiceHost _galaxyManagerHost; private ServiceHost _archiveManagerHost; private static IContainer _container; public static void Main(string[] args) { //LoggerConfiguration.Apply(); _container = BuildContainer(); HostFactory.Run(GenerateConfiguration); } private static void GenerateConfiguration(HostConfigurator config) { config.UseAutofacContainer(_container); config.UseNLog(); config.Service<MessagingService>(instance => { instance.ConstructUsingAutofacContainer(); instance.WhenStarted(x => x.OnStart()); instance.WhenStopped(x => x.OnStop()); }); config.OnException(OnServiceException); config.SetServiceName("GMessaging"); config.SetDisplayName("Galaxy Merge Messaging Service"); config.SetDescription(@"WCF Service host for the Galaxy Merge application. This service provides client access for managing, processing, and retrieving galaxy data."); config.SetStartTimeout(TimeSpan.FromSeconds(60)); config.SetStopTimeout(TimeSpan.FromSeconds(30)); config.RunAsLocalSystem(); config.StartAutomatically(); } private void OnStart() { _galaxyManagerHost?.Close(); _galaxyManagerHost = new ServiceHost(typeof(GalaxyManager)); _galaxyManagerHost.AddDependencyInjectionBehavior(typeof(GalaxyManager), _container); Logger.Debug("Starting Galaxy Manager Service"); _galaxyManagerHost.Open(); Logger.Trace("Instantiating Archive Manager Service"); _archiveManagerHost?.Close(); _archiveManagerHost = new ServiceHost(typeof(ArchiveManager)); Logger.Trace("Configuring Archive Manager Service"); _archiveManagerHost.AddDependencyInjectionBehavior(typeof(ArchiveManager), _container); Logger.Trace("Starting Archive Manager Service"); _archiveManagerHost.Open(); Logger.Info("GMessaging Service Started"); } private void OnStop() { if (_galaxyManagerHost != null) { _galaxyManagerHost.Close(); _galaxyManagerHost = null; } if (_archiveManagerHost != null) { _archiveManagerHost.Close(); _archiveManagerHost = null; } _container.Dispose(); _container = null; } private static void OnServiceException(Exception obj) { Logger.Fatal(obj); } private static IContainer BuildContainer() { var builder = new ContainerBuilder(); return builder.Build(); } } }
33.603774
99
0.587872
[ "MIT" ]
tnunnink/GMerge
src/GServer.Host.Messaging/MessagingService.cs
3,564
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using observingobjects; using viewmodelbased.Services; namespace viewmodelbased.ViewModels { internal class MainViewModel : BaseViewModel { private List<FriendViewModel> m_friends; private IFriendService m_friendService; public MainViewModel(IFriendService friendService) { m_friendService = friendService; } public List<FriendViewModel> Friends { get => m_friends; set => SetProperty(ref m_friends, value); } public async Task Initialize() { var friends = await m_friendService.Get(); var friendsViewModels = new List<FriendViewModel>(); foreach (var friend in friends) { friendsViewModels.Add(new FriendViewModel(friend)); } Friends = friendsViewModels; } } }
25.487179
67
0.60161
[ "MIT" ]
NolwennR/xaml-code-experiences
xaml.experiences/architecture/structuring/viewmodelbased/ViewModels/MainViewModel.cs
994
C#
using GetIntoTeachingApi.Controllers; using FluentAssertions; using GetIntoTeachingApi.Models; using GetIntoTeachingApi.Services; using Microsoft.AspNetCore.Mvc; using Moq; using System; using Hangfire; using Microsoft.AspNetCore.Authorization; using Xunit; using GetIntoTeachingApi.Attributes; namespace GetIntoTeachingApiTests.Controllers { public class PrivacyPoliciesControllerTests { private readonly Mock<IStore> _mockStore; private readonly PrivacyPoliciesController _controller; public PrivacyPoliciesControllerTests() { _mockStore = new Mock<IStore>(); _controller = new PrivacyPoliciesController(_mockStore.Object); } [Fact] public void Authorize_IsPresent() { typeof(PrivacyPoliciesController).Should().BeDecoratedWith<AuthorizeAttribute>(); } [Fact] public void PrivateShortTermResponseCache_IsPresent() { typeof(PrivacyPoliciesController).Should().BeDecoratedWith<PrivateShortTermResponseCacheAttribute>(); } [Fact] public async void Get_ReturnsPrivacyPolicy() { var policy = new PrivacyPolicy() { Id = Guid.NewGuid() }; _mockStore.Setup(mock => mock.GetPrivacyPolicyAsync((Guid)policy.Id)).ReturnsAsync(policy); var response = await _controller.Get((Guid)policy.Id); var ok = response.Should().BeOfType<OkObjectResult>().Subject; ok.Value.Should().Be(policy); } [Fact] public async void Get_WithMissingEvent_ReturnsNotFound() { _mockStore.Setup(mock => mock.GetTeachingEventAsync(It.IsAny<Guid>())).ReturnsAsync(null as TeachingEvent); var response = await _controller.Get(Guid.NewGuid()); response.Should().BeOfType<NotFoundResult>(); } [Fact] public async void GetLatest_ReturnsLatestPrivacyPolicy() { var mockPolicy = MockPrivacyPolicy(); _mockStore.Setup(mock => mock.GetLatestPrivacyPolicyAsync()).ReturnsAsync(mockPolicy); var response = await _controller.GetLatest(); var ok = response.Should().BeOfType<OkObjectResult>().Subject; ok.Value.Should().Be(mockPolicy); } private static PrivacyPolicy MockPrivacyPolicy() { return new PrivacyPolicy { Id = Guid.NewGuid(), Text = "Example text", CreatedAt = DateTime.UtcNow }; } } }
33.192308
120
0.637312
[ "MIT" ]
uk-gov-mirror/DFE-Digital.get-into-teaching-api
GetIntoTeachingApiTests/Controllers/PrivacyPoliciesControllerTests.cs
2,591
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 apigatewayv2-2018-11-29.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ApiGatewayV2.Model { /// <summary> /// Container for the parameters to the GetRouteResponses operation. /// Gets the RouteResponses for a Route. /// </summary> public partial class GetRouteResponsesRequest : AmazonApiGatewayV2Request { private string _apiId; private string _maxResults; private string _nextToken; private string _routeId; /// <summary> /// Gets and sets the property ApiId. /// <para> /// The API identifier. /// </para> /// </summary> public string ApiId { get { return this._apiId; } set { this._apiId = value; } } // Check to see if ApiId property is set internal bool IsSetApiId() { return this._apiId != null; } /// <summary> /// Gets and sets the property MaxResults. /// <para> /// The maximum number of elements to be returned for this resource. /// </para> /// </summary> public string MaxResults { get { return this._maxResults; } set { this._maxResults = value; } } // Check to see if MaxResults property is set internal bool IsSetMaxResults() { return this._maxResults != null; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// The next page of elements from this collection. Not valid for the last element of /// the collection. /// </para> /// </summary> public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } /// <summary> /// Gets and sets the property RouteId. /// <para> /// The route ID. /// </para> /// </summary> public string RouteId { get { return this._routeId; } set { this._routeId = value; } } // Check to see if RouteId property is set internal bool IsSetRouteId() { return this._routeId != null; } } }
28.313043
110
0.576167
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/ApiGatewayV2/Generated/Model/GetRouteResponsesRequest.cs
3,256
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: IEntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface IDeviceAppManagementManagedAppStatusesCollectionRequest. /// </summary> public partial interface IDeviceAppManagementManagedAppStatusesCollectionRequest : IBaseRequest { /// <summary> /// Adds the specified ManagedAppStatus to the collection via POST. /// </summary> /// <param name="managedAppStatus">The ManagedAppStatus to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created ManagedAppStatus.</returns> System.Threading.Tasks.Task<ManagedAppStatus> AddAsync(ManagedAppStatus managedAppStatus, CancellationToken cancellationToken = default); /// <summary> /// Adds the specified ManagedAppStatus to the collection via POST and returns a <see cref="GraphResponse{ManagedAppStatus}"/> object of the request. /// </summary> /// <param name="managedAppStatus">The ManagedAppStatus to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{ManagedAppStatus}"/> object of the request.</returns> System.Threading.Tasks.Task<GraphResponse<ManagedAppStatus>> AddResponseAsync(ManagedAppStatus managedAppStatus, CancellationToken cancellationToken = default); /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> System.Threading.Tasks.Task<IDeviceAppManagementManagedAppStatusesCollectionPage> GetAsync(CancellationToken cancellationToken = default); /// <summary> /// Gets the collection page and returns a <see cref="GraphResponse{DeviceAppManagementManagedAppStatusesCollectionResponse}"/> object. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The <see cref="GraphResponse{DeviceAppManagementManagedAppStatusesCollectionResponse}"/> object.</returns> System.Threading.Tasks.Task<GraphResponse<DeviceAppManagementManagedAppStatusesCollectionResponse>> GetResponseAsync(CancellationToken cancellationToken = default); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IDeviceAppManagementManagedAppStatusesCollectionRequest Expand(string value); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> IDeviceAppManagementManagedAppStatusesCollectionRequest Expand(Expression<Func<ManagedAppStatus, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IDeviceAppManagementManagedAppStatusesCollectionRequest Select(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> IDeviceAppManagementManagedAppStatusesCollectionRequest Select(Expression<Func<ManagedAppStatus, object>> selectExpression); /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> IDeviceAppManagementManagedAppStatusesCollectionRequest Top(int value); /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> IDeviceAppManagementManagedAppStatusesCollectionRequest Filter(string value); /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> IDeviceAppManagementManagedAppStatusesCollectionRequest Skip(int value); /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> IDeviceAppManagementManagedAppStatusesCollectionRequest OrderBy(string value); } }
51.252252
172
0.662507
[ "MIT" ]
Aliases/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/IDeviceAppManagementManagedAppStatusesCollectionRequest.cs
5,689
C#
using System; using System.Runtime.Serialization; namespace WeatherBuddy.Models { [Serializable] internal class BadResponseException : Exception { public BadResponseException() { } public BadResponseException(string message) : base(message) { } public BadResponseException(string message, Exception innerException) : base(message, innerException) { } protected BadResponseException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
23.12
110
0.647059
[ "MIT" ]
evad37/WeatherBuddy
WeatherBuddy/WeatherBuddy/Exceptions/BadResponseException.cs
580
C#
using GalaSoft.MvvmLight.Command; using Microsoft.Phone.Shell; using System; using System.Collections.Generic; using System.Text; namespace PhoneAppBarMVVM.Helpers { public interface IApplicationBarService { IApplicationBar ApplicationBar { get;} void AddButton(string title, Uri imageUrl, Action OnClick); } }
21.375
67
0.748538
[ "MIT" ]
acaceresssit/Blog
PhoneAppBarMvvm/PhoneAppBarMvvm/Helpers/IApplicationBarService.cs
344
C#
// // This file has been generated automatically by MonoDevelop to store outlets and // actions made in the Xcode designer. If it is removed, they will be lost. // Manual changes to this file may not be handled correctly. // using Foundation; namespace SFXUGDemo.SFXUGDemoWatchAppExtension { [Register ("NotificationController")] partial class NotificationController { void ReleaseDesignerOutlets () { } } }
22.157895
81
0.75772
[ "MIT" ]
dannycabrera/SFXUGDemo
SFXUGDemo/SFXUGDemo.SFXUGDemoWatchAppExtension/NotificationController.designer.cs
423
C#
//===================================================================================================================== // Проект: LotusLocalSelfGovernment // Раздел: Модуль репозитория // Подраздел: Подсистема базы данных // Автор: MagistrBYTE aka DanielDem <dementevds@gmail.com> //--------------------------------------------------------------------------------------------------------------------- /** \file LotusLSGRepositoryDatabaseConnection.cs * Параметры подключения баз данных. */ //--------------------------------------------------------------------------------------------------------------------- // Версия: 1.0.0.0 // Последнее изменение от 27.03.2022 //===================================================================================================================== using System; using System.Collections.Generic; using System.Text; using Microsoft.EntityFrameworkCore; //===================================================================================================================== namespace Lotus { namespace LSG { //------------------------------------------------------------------------------------------------------------- //! \defgroup MunicipalityRepositoryDatabase Подсистема базы данных //! Подсистема базы данных обеспечивает хранение все информации в базе данных MySQL. //! \ingroup MunicipalityRepository /*@{*/ //------------------------------------------------------------------------------------------------------------- /// <summary> /// Статический класс для определения данных для подключения к базе данных /// </summary> //------------------------------------------------------------------------------------------------------------- public static class XDbContextConnection { #region ======================================= ДАННЫЕ ==================================================== // // Параметры удаленного сервера // /// <summary> /// Имя сервера /// </summary> public static String REMOTE_SERVER = "mysql99.1gb.ru"; /// <summary> /// Имя порта /// </summary> public static String REMOTE_PORT = "3306"; /// <summary> /// Имя базы данных /// </summary> public static String REMOTE_DATABASE = "gb_localgov1"; /// <summary> /// Имя пользователя /// </summary> public static String REMOTE_USER = "gb_localgov1"; /// <summary> /// Пароль /// </summary> public static String REMOTE_PASSWORD = "752za46az45"; // // Параметры локального сервера // /// <summary> /// Имя сервера /// </summary> public static String LOCAL_SERVER = "localhost"; /// <summary> /// Имя порта /// </summary> public static String LOCAL_PORT = "3306"; /// <summary> /// Имя базы данных /// </summary> public static String LOCAL_DATABASE = "localselfgovernment"; /// <summary> /// Имя пользователя /// </summary> public static String LOCAL_USER = "root"; /// <summary> /// Пароль /// </summary> public static String LOCAL_PASSWORD = "1111"; #endregion #region ======================================= МЕТОДЫ ==================================================== //--------------------------------------------------------------------------------------------------------- /// <summary> /// Получение строки подключения к удаленной базе данных /// </summary> /// <returns>Строка подключения к базе данных</returns> //--------------------------------------------------------------------------------------------------------- public static String GetRemoteConnectString() { String connect_string = String.Format("server={0};user={1};port={2};database={3};password={4};ConvertZeroDateTime=True", REMOTE_SERVER, REMOTE_USER, REMOTE_PORT, REMOTE_DATABASE, REMOTE_PASSWORD); return (connect_string); } //--------------------------------------------------------------------------------------------------------- /// <summary> /// Получение строки подключения к локальной базе данных /// </summary> /// <returns>Строка подключения к базе данных</returns> //--------------------------------------------------------------------------------------------------------- public static String GetLocalConnectString() { String connect_string = String.Format("server={0};user={1};port={2};database={3};password={4};ConvertZeroDateTime=True", LOCAL_SERVER, LOCAL_USER, LOCAL_PORT, LOCAL_DATABASE, LOCAL_PASSWORD); return (connect_string); } //--------------------------------------------------------------------------------------------------------- /// <summary> /// Получение строки подключения к базе данных /// </summary> /// <param name="is_remote">Статус подключения к удаленной базе данных</param> /// <returns>Строка подключения к базе данных</returns> //--------------------------------------------------------------------------------------------------------- public static String GetConnectString(Boolean is_remote) { if(is_remote) { return (GetRemoteConnectString()); } else { return (GetLocalConnectString()); } } #endregion } //------------------------------------------------------------------------------------------------------------- /*@}*/ //------------------------------------------------------------------------------------------------------------- } } //=====================================================================================================================
36.214286
120
0.40416
[ "MIT" ]
MagistrBYTE/Lotus.LSG
Lotus.LSG/Source/Repository/Database/LotusLSGRepositoryDatabaseConnection.cs
6,260
C#
/// Generated - Do Not Edit namespace BabylonJS { using System; using System.Collections.Generic; using System.Text.Json.Serialization; using System.Threading.Tasks; using EventHorizon.Blazor.Interop; using EventHorizon.Blazor.Interop.Callbacks; using Microsoft.JSInterop; public interface IAudioEngine : ICachedEntity { } [JsonConverter(typeof(CachedEntityConverter<IAudioEngineCachedEntity>))] public class IAudioEngineCachedEntity : CachedEntityObject, IAudioEngine { #region Static Accessors #endregion #region Static Properties #endregion #region Static Methods #endregion #region Accessors #endregion #region Properties public bool canUseWebAudio { get { return EventHorizonBlazorInterop.Get<bool>( this.___guid, "canUseWebAudio" ); } } private AudioContext __audioContext; public AudioContext audioContext { get { if(__audioContext == null) { __audioContext = EventHorizonBlazorInterop.GetClass<AudioContext>( this.___guid, "audioContext", (entity) => { return new AudioContext() { ___guid = entity.___guid }; } ); } return __audioContext; } } private GainNode __masterGain; public GainNode masterGain { get { if(__masterGain == null) { __masterGain = EventHorizonBlazorInterop.GetClass<GainNode>( this.___guid, "masterGain", (entity) => { return new GainNode() { ___guid = entity.___guid }; } ); } return __masterGain; } } public bool isMP3supported { get { return EventHorizonBlazorInterop.Get<bool>( this.___guid, "isMP3supported" ); } } public bool isOGGsupported { get { return EventHorizonBlazorInterop.Get<bool>( this.___guid, "isOGGsupported" ); } } public bool WarnedWebAudioUnsupported { get { return EventHorizonBlazorInterop.Get<bool>( this.___guid, "WarnedWebAudioUnsupported" ); } set { EventHorizonBlazorInterop.Set( this.___guid, "WarnedWebAudioUnsupported", value ); } } public bool useCustomUnlockedButton { get { return EventHorizonBlazorInterop.Get<bool>( this.___guid, "useCustomUnlockedButton" ); } set { EventHorizonBlazorInterop.Set( this.___guid, "useCustomUnlockedButton", value ); } } public bool unlocked { get { return EventHorizonBlazorInterop.Get<bool>( this.___guid, "unlocked" ); } } private Observable<IAudioEngineCachedEntity> __onAudioUnlockedObservable; public Observable<IAudioEngineCachedEntity> onAudioUnlockedObservable { get { if(__onAudioUnlockedObservable == null) { __onAudioUnlockedObservable = EventHorizonBlazorInterop.GetClass<Observable<IAudioEngineCachedEntity>>( this.___guid, "onAudioUnlockedObservable", (entity) => { return new Observable<IAudioEngineCachedEntity>() { ___guid = entity.___guid }; } ); } return __onAudioUnlockedObservable; } set { __onAudioUnlockedObservable = null; EventHorizonBlazorInterop.Set( this.___guid, "onAudioUnlockedObservable", value ); } } private Observable<IAudioEngineCachedEntity> __onAudioLockedObservable; public Observable<IAudioEngineCachedEntity> onAudioLockedObservable { get { if(__onAudioLockedObservable == null) { __onAudioLockedObservable = EventHorizonBlazorInterop.GetClass<Observable<IAudioEngineCachedEntity>>( this.___guid, "onAudioLockedObservable", (entity) => { return new Observable<IAudioEngineCachedEntity>() { ___guid = entity.___guid }; } ); } return __onAudioLockedObservable; } set { __onAudioLockedObservable = null; EventHorizonBlazorInterop.Set( this.___guid, "onAudioLockedObservable", value ); } } #endregion #region Constructor public IAudioEngineCachedEntity() : base() { } public IAudioEngineCachedEntity( ICachedEntity entity ) : base(entity) { } #endregion #region Methods public void @lock() { EventHorizonBlazorInterop.Func<CachedEntity>( new object[] { new string[] { this.___guid, "@lock" } } ); } public void @unlock() { EventHorizonBlazorInterop.Func<CachedEntity>( new object[] { new string[] { this.___guid, "@unlock" } } ); } public decimal getGlobalVolume() { return EventHorizonBlazorInterop.Func<decimal>( new object[] { new string[] { this.___guid, "getGlobalVolume" } } ); } public void setGlobalVolume(decimal newVolume) { EventHorizonBlazorInterop.Func<CachedEntity>( new object[] { new string[] { this.___guid, "setGlobalVolume" }, newVolume } ); } public void connectToAnalyser(Analyser analyser) { EventHorizonBlazorInterop.Func<CachedEntity>( new object[] { new string[] { this.___guid, "connectToAnalyser" }, analyser } ); } #endregion } }
26.303136
119
0.448271
[ "MIT" ]
BlazorHub/EventHorizon.Blazor.TypeScript.Interop.Generator
Sample/_generated/EventHorizon.Blazor.BabylonJS.WASM/IAudioEngine.cs
7,549
C#
namespace Fabric.Terminology.API.DependencyInjection { using Fabric.Terminology.Domain.DependencyInjection; using Fabric.Terminology.SqlServer.Persistence; using Fabric.Terminology.SqlServer.Persistence.UnitOfWork; using Nancy.TinyIoc; public class SqlRequestComposition : IContainerComposition<TinyIoCContainer> { public void Compose(TinyIoCContainer container) { container.Register<IClientTermValueUnitOfWorkManager, ClientTermValueUnitOfWorkManager>(); container.Register<SqlServer.Persistence.IClientTermValueSetRepository, SqlClientTermValueSetRepository>(); container.Register<IValueSetCodeRepository, SqlValueSetCodeRepository>(); container.Register<IValueSetCodeCountRepository, SqlValueSetCodeCountRepository>(); container.Register<IValueSetBackingItemRepository, SqlValueSetBackingItemRepository>(); container.Register<ICodeSystemRepository, SqlCodeSystemRepository>(); container.Register<ICodeSystemCodeRepository, SqlCodeSystemCodeRepository>(); } } }
47.956522
119
0.766092
[ "Apache-2.0" ]
HealthCatalyst/Fabric.Terminology
Fabric.Terminology.API/DependencyInjection/SqlRequestComposition.cs
1,105
C#
namespace Smidgenomics.Generate { using System; using System.IO; using UnityEngine; using UnityEngine.Events; [AddComponentMenu("Smidgenomics/Generate/Read File")] internal class ReadFile : MonoBehaviour { public void Read(string path) { var fullpath = path; if(!IsAbsoluteUrl(path)) { string root = Application.dataPath; #if UNITY_EDITOR root = root.Remove(root.Length - 6); #endif fullpath = Path.Combine(root, path); } if(File.Exists(fullpath)) { _onSuccess.Invoke(File.ReadAllText(fullpath)); } else { _onFail.Invoke(); } } [Serializable] private class StringEvent : UnityEvent<string> {} [SerializeField] private StringEvent _onSuccess = null; [SerializeField] private UnityEvent _onFail = null; private bool IsAbsoluteUrl(string url) { Uri result; return Uri.TryCreate(url, UriKind.Absolute, out result); } } } #if UNITY_EDITOR namespace Smidgenomics.Generate { using UnityEngine; using UnityEditor; [CanEditMultipleObjects] [CustomEditor(typeof(ReadFile))] internal class Editor_ReadFile : Editor { public override void OnInspectorGUI() { EditorGUILayout.Space(); string[] tabs = new string[]{ string.Format("Success ({0})", _successCount.arraySize), string.Format("Fail ({0})", _failCount.arraySize) }; EditorGUILayout.BeginVertical(EditorStyles.helpBox); _activeTab = GUILayout.Toolbar(_activeTab, tabs); SerializedProperty p = null; switch(_activeTab) { case 0: p = _onSuccess; break; case 1: p = _onFail; break; } EditorGUILayout.PropertyField(p, GUIContent.none); EditorGUILayout.EndVertical(); serializedObject.ApplyModifiedProperties(); } private SerializedProperty _onSuccess = null, _onFail = null; private SerializedProperty _successCount = null, _failCount = null; private static int _activeTab = 0; private void OnEnable() { _onSuccess = serializedObject.FindProperty("_onSuccess"); _onFail = serializedObject.FindProperty("_onFail"); _successCount = serializedObject.FindProperty("_onSuccess.m_PersistentCalls.m_Calls"); _failCount = serializedObject.FindProperty("_onFail.m_PersistentCalls.m_Calls"); } } } #endif
24.340659
89
0.721896
[ "MIT" ]
Smidgens/Unity-Snippet-Scripts
Assets/SnippetScripts/Scripts/Generate/ReadFile.cs
2,217
C#
using System.Drawing; using DotNet.Highcharts.Attributes; using DotNet.Highcharts.Helpers; namespace DotNet.Highcharts.Options.PlotOptions { /// <summary> /// The appearance of the point marker when selected. In order to allow a point to be selected, set the <code>series.allowPointSelect</code> option to true. /// </summary> public class PlotOptionsAreaMarkerStatesSelect { /// <summary> /// Enable or disable visible feedback for selection. /// Default: true /// </summary> public bool? Enabled { get; set; } /// <summary> /// The fill color of the point marker. When <code>null</code>, the series' or point's color is used. /// </summary> [JsonFormatter(addPropertyName: true, useCurlyBracketsForObject: false)] public BackColorOrGradient FillColor { get; set; } /// <summary> /// The color of the point marker's outline. When <code>null</code>, the series' or point's color is used. /// Default: #000000 /// </summary> public Color? LineColor { get; set; } /// <summary> /// The width of the point marker's outline. /// Default: 0 /// </summary> public Number? LineWidth { get; set; } /// <summary> /// The radius of the point marker. In hover state, it defaults to the normal state's radius + 2. /// </summary> public Number? Radius { get; set; } } }
30.651163
158
0.679818
[ "MIT" ]
CareATC/DotNet.Highcharts
DotNet.Highcharts/DotNet.Highcharts/Options/PlotOptions/PlotOptionsAreaMarkerStatesSelect.cs
1,318
C#
using System; using System.Runtime.CompilerServices; using System.Text; namespace RevolutionSnapshot.Core.Buffers { public unsafe ref struct DataBufferReader { public byte* DataPtr; public int CurrReadIndex; public int Length; public DataBufferReader(IntPtr dataPtr, int length) : this((byte*) dataPtr, length) { } public DataBufferReader(byte* dataPtr, int length) { if (dataPtr == null) throw new InvalidOperationException("dataPtr is null"); DataPtr = dataPtr; CurrReadIndex = 0; Length = length; } public DataBufferReader(DataBufferReader reader, int start, int end) { DataPtr = (byte*) ((IntPtr) reader.DataPtr + start); CurrReadIndex = 0; Length = end - start; } public DataBufferReader(DataBufferWriter writer) { DataPtr = (byte*) writer.GetSafePtr(); CurrReadIndex = 0; Length = writer.Length; } public DataBufferReader(Span<byte> data) { DataPtr = (byte*) data.GetPinnableReference(); CurrReadIndex = 0; Length = data.Length; } public int GetReadIndex(DataBufferMarker marker) { var readIndex = !marker.Valid ? CurrReadIndex : marker.Index; if (readIndex >= Length) { throw new IndexOutOfRangeException("p1"); } return readIndex; } public int GetReadIndexAndSetNew(DataBufferMarker marker, int size) { var readIndex = !marker.Valid ? CurrReadIndex : marker.Index; if (readIndex >= Length) { throw new IndexOutOfRangeException($"p1 r={readIndex} >= l={Length}"); } CurrReadIndex = readIndex + size; if (CurrReadIndex > Length) { throw new IndexOutOfRangeException("p2"); } return readIndex; } public void ReadUnsafe(byte* data, int index, int size) { Unsafe.CopyBlock(data, (void*) IntPtr.Add((IntPtr) DataPtr, index), (uint) size); } public T ReadValue<T>(DataBufferMarker marker = default(DataBufferMarker)) where T : struct { var val = default(T); var size = Unsafe.SizeOf<T>(); var readIndex = GetReadIndexAndSetNew(marker, size); // Set it for later usage CurrReadIndex = readIndex + size; // Read the value ReadUnsafe((byte*) Unsafe.AsPointer(ref val), readIndex, size); return val; } public DataBufferMarker CreateMarker(int index) { return new DataBufferMarker(index); } public ulong ReadDynInteger(DataBufferMarker marker = default(DataBufferMarker)) { var byteCount = ReadValue<byte>(); if (byteCount == 0) return 0; if (byteCount == sizeof(byte)) return ReadValue<byte>(); if (byteCount == sizeof(ushort)) return ReadValue<ushort>(); if (byteCount == sizeof(uint)) return ReadValue<uint>(); if (byteCount == sizeof(ulong)) return ReadValue<ulong>(); throw new InvalidOperationException($"Expected byte count range: [{sizeof(byte)}..{sizeof(ulong)}], received: {byteCount}"); } public void ReadDynIntegerFromMask(out ulong r1, out ulong r2) { void getval(ref DataBufferReader data, int mr, ref ulong i) { if (mr == 0) i = data.ReadValue<byte>(); if (mr == 1) i = data.ReadValue<ushort>(); if (mr == 2) i = data.ReadValue<uint>(); if (mr == 3) i = data.ReadValue<ulong>(); } var mask = ReadValue<byte>(); var val1 = (mask & 3); var val2 = (mask & 12) >> 2; r1 = default; r2 = default; getval(ref this, val1, ref r1); getval(ref this, val2, ref r2); } public void ReadDynIntegerFromMask(out ulong r1, out ulong r2, out ulong r3) { void getval(ref DataBufferReader data, int mr, ref ulong i) { if (mr == 0) i = data.ReadValue<byte>(); if (mr == 1) i = data.ReadValue<ushort>(); if (mr == 2) i = data.ReadValue<uint>(); if (mr == 3) i = data.ReadValue<ulong>(); } var mask = ReadValue<byte>(); var val1 = (mask & 3); var val2 = (mask & 12) >> 2; var val3 = (mask & 48) >> 4; r1 = default; r2 = default; r3 = default; getval(ref this, val1, ref r1); getval(ref this, val2, ref r2); getval(ref this, val3, ref r3); } public void ReadDynIntegerFromMask(out ulong r1, out ulong r2, out ulong r3, out ulong r4) { void getval(ref DataBufferReader data, int mr, ref ulong i) { if (mr == 0) i = data.ReadValue<byte>(); if (mr == 1) i = data.ReadValue<ushort>(); if (mr == 2) i = data.ReadValue<uint>(); if (mr == 3) i = data.ReadValue<ulong>(); } var mask = ReadValue<byte>(); var val1 = (mask & 3); var val2 = (mask & 12) >> 2; var val3 = (mask & 48) >> 4; var val4 = (mask & 192) >> 6; r1 = default; r2 = default; r3 = default; r4 = default; getval(ref this, val1, ref r1); getval(ref this, val2, ref r2); getval(ref this, val3, ref r3); getval(ref this, val3, ref r4); } public string ReadString(DataBufferMarker marker = default(DataBufferMarker)) { var encoding = (UTF8Encoding) Encoding.UTF8; if (!marker.Valid) marker = CreateMarker(CurrReadIndex); var strDataLength = ReadValue<int>(marker); var strDataEnd = ReadValue<int>(marker.GetOffset(sizeof(int) * 1)); var strExpectedLength = ReadValue<int>(marker.GetOffset(sizeof(int) * 2)); var strDataStart = GetReadIndex(marker.GetOffset(sizeof(int) * 3)); if (strDataLength <= 0) { if (strDataLength < 0) { throw new Exception("No string found, maybe you are reading at the wrong location or you've done a bad write?"); } return string.Empty; } var str = encoding.GetString(DataPtr + strDataStart, Math.Min(strDataEnd - strDataStart, strDataLength)); CurrReadIndex = strDataEnd; if (str.Length != strExpectedLength) { return str.Substring(0, strExpectedLength); } return str; } } }
32.813636
136
0.509766
[ "MIT" ]
guerro323/Revolution
RevolutionSnapshot.Core/Buffers/DataBufferReader.cs
7,221
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.Reflection; namespace DeadCode.WME.StringTableMgr { public partial class FormAbout : Form { public FormAbout() { InitializeComponent(); } ////////////////////////////////////////////////////////////////////////// private void OnLoad(object sender, EventArgs e) { Assembly Asm = Assembly.GetExecutingAssembly(); LblVersion.Text += " " + Asm.GetName().Version.ToString(); } ////////////////////////////////////////////////////////////////////////// private void OnLinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { System.Diagnostics.Process.Start(LblLink.Text); } } }
25.8125
77
0.579903
[ "MIT" ]
retrodump/Wintermute-Engine
src/StringTableMgr/StringTableMgr/FormAbout.cs
826
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System.Threading.Tasks; using Squidex.Infrastructure.Commands; using Squidex.Infrastructure.Orleans; namespace Squidex.Domain.Apps.Entities.Apps.DomainObject { public interface IAppGrain : IDomainObjectGrain { Task<J<IAppEntity>> GetStateAsync(); } }
34.052632
78
0.48068
[ "MIT" ]
BrightsDigi/squidex
backend/src/Squidex.Domain.Apps.Entities/Apps/DomainObject/IAppGrain.cs
649
C#
// Prexonite // // Copyright (c) 2014, Christian Klauser // 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. // The names of the contributors may be used to endorse or // promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, // WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING // IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.ObjectModel; namespace Prx.Benchmarking; public sealed class BenchmarkEntryCollection : KeyedCollection<string, BenchmarkEntry> { public BenchmarkEntryCollection() : base(StringComparer.OrdinalIgnoreCase) { } ///<summary> /// When implemented in a derived class, extracts the key from the specified element. ///</summary> ///<returns> /// The key for the specified element. ///</returns> ///<param name = "item">The element from which to extract the key.</param> protected override string GetKeyForItem(BenchmarkEntry item) { return item.Function.Id; } }
47.061224
99
0.712923
[ "BSD-3-Clause" ]
SealedSun/prx
Prx/Benchmarking/BenchmarkEntryCollection.cs
2,306
C#
// ************************************************************* // project: graphql-aspnet // -- // repo: https://github.com/graphql-aspnet // docs: https://graphql-aspnet.github.io // -- // License: MIT // ************************************************************* namespace GraphQL.Subscriptions.Tests { using System.Linq; using GraphQL.AspNet; using GraphQL.AspNet.Apollo.Messages.Converters; using GraphQL.AspNet.Configuration; using GraphQL.AspNet.Defaults; using GraphQL.AspNet.Execution; using GraphQL.AspNet.Execution.Contexts; using GraphQL.AspNet.Interfaces.Configuration; using GraphQL.AspNet.Interfaces.Middleware; using GraphQL.AspNet.Interfaces.Subscriptions; using GraphQL.AspNet.Middleware.FieldExecution; using GraphQL.AspNet.Middleware.FieldExecution.Components; using GraphQL.AspNet.Middleware.QueryExecution; using GraphQL.AspNet.Middleware.QueryExecution.Components; using GraphQL.AspNet.Schemas; using GraphQL.AspNet.Tests.Framework; using Microsoft.Extensions.DependencyInjection; using Moq; using NUnit.Framework; [TestFixture] public class SubscriptionServerExtensionTests { private ( Mock<ISchemaBuilder<GraphSchema>>, Mock<ISchemaPipelineBuilder<GraphSchema, IGraphMiddlewareComponent<GraphQueryExecutionContext>, GraphQueryExecutionContext>>, Mock<ISchemaPipelineBuilder<GraphSchema, IGraphMiddlewareComponent<GraphFieldExecutionContext>, GraphFieldExecutionContext>>) CreateSchemaBuilderMock(SchemaOptions<GraphSchema> options) { var queryPipeline = new Mock<ISchemaPipelineBuilder<GraphSchema, IGraphMiddlewareComponent<GraphQueryExecutionContext>, GraphQueryExecutionContext>>(); var fieldPipeline = new Mock<ISchemaPipelineBuilder<GraphSchema, IGraphMiddlewareComponent<GraphFieldExecutionContext>, GraphFieldExecutionContext>>(); var builder = new Mock<ISchemaBuilder<GraphSchema>>(); builder.Setup(x => x.QueryExecutionPipeline).Returns(queryPipeline.Object); builder.Setup(x => x.FieldExecutionPipeline).Returns(fieldPipeline.Object); builder.Setup(x => x.Options).Returns(options); queryPipeline.Setup(x => x.Clear()); queryPipeline.Setup(x => x.AddMiddleware<IGraphMiddlewareComponent<GraphQueryExecutionContext>>( It.IsAny<ServiceLifetime>(), It.IsAny<string>())).Returns(queryPipeline.Object); queryPipeline.Setup(x => x.Clear()); queryPipeline.Setup(x => x.AddMiddleware( It.IsAny<IGraphMiddlewareComponent<GraphQueryExecutionContext>>(), It.IsAny<string>())).Returns(queryPipeline.Object); return (builder, queryPipeline, fieldPipeline); } [Test] public void GeneralPropertyCheck() { using var restorePoint = new GraphQLProviderRestorePoint(); var serviceCollection = new ServiceCollection(); GraphQLProviders.TemplateProvider = null; var primaryOptions = new SchemaOptions<GraphSchema>(serviceCollection); var subscriptionOptions = new SubscriptionServerOptions<GraphSchema>(); (var builder, var queryPipeline, var fieldPipeline) = CreateSchemaBuilderMock(primaryOptions); var extension = new ApolloSubscriptionServerSchemaExtension<GraphSchema>(builder.Object, subscriptionOptions); extension.Configure(primaryOptions); Assert.IsTrue(primaryOptions.DeclarationOptions.AllowedOperations.Contains(GraphCollection.Subscription)); Assert.AreEqual(3, primaryOptions.ServiceCollection.Count); Assert.IsNotNull(primaryOptions.ServiceCollection.SingleOrDefault(x => x.ServiceType == typeof(SubscriptionServerOptions<GraphSchema>))); Assert.IsNotNull(primaryOptions.ServiceCollection.SingleOrDefault(x => x.ServiceType == typeof(ApolloMessageConverterFactory))); Assert.IsNotNull(primaryOptions.ServiceCollection.SingleOrDefault(x => x.ServiceType == typeof(ISubscriptionServer<GraphSchema>))); Assert.IsTrue(GraphQLProviders.TemplateProvider is SubscriptionEnabledTemplateProvider); // 9 middleware components in the subscription-swapped primary query pipeline registered by type // 1 middleware component registered by instance queryPipeline.Verify(x => x.Clear()); queryPipeline.Verify( x => x.AddMiddleware<IGraphMiddlewareComponent<GraphQueryExecutionContext>>( It.IsAny<ServiceLifetime>(), It.IsAny<string>()), Times.Exactly(9)); queryPipeline.Verify( x => x.AddMiddleware( It.IsAny<IGraphMiddlewareComponent<GraphQueryExecutionContext>>(), It.IsAny<string>()), Times.Exactly(1)); // ensur query level authorzation component was added queryPipeline.Verify( x => x.AddMiddleware<AuthorizeQueryOperationMiddleware<GraphSchema>>( It.IsAny<ServiceLifetime>(), It.IsAny<string>()), Times.Exactly(1)); // four components in the sub swaped field pipeline fieldPipeline.Verify(x => x.Clear()); fieldPipeline.Verify( x => x.AddMiddleware<IGraphMiddlewareComponent<GraphFieldExecutionContext>>(It.IsAny<ServiceLifetime>(), It.IsAny<string>()), Times.Exactly(4)); // ensure field authroization component was NOT added // to the field pipeline fieldPipeline.Verify( x => x.AddMiddleware<AuthorizeFieldMiddleware<GraphSchema>>(It.IsAny<ServiceLifetime>(), It.IsAny<string>()), Times.Exactly(0)); } } }
47.874016
163
0.650822
[ "MIT" ]
NET1211/aspnet-archive-tools
src/tests/graphql-aspnet-subscriptions-tests/SubscriptionServerExtensionTests.cs
6,082
C#
using System; using Avalonia.Controls; using Avalonia.Controls.Templates; using Avalonia.UITestFramework.Example.ViewModels; namespace Avalonia.UITestFramework.Example { public class ViewLocator : IDataTemplate { public bool SupportsRecycling => false; public IControl Build(object data) { var name = data.GetType().FullName!.Replace("ViewModel", "View"); var type = Type.GetType(name); if (type != null) { return (Control)Activator.CreateInstance(type)!; } else { return new TextBlock { Text = "Not Found: " + name }; } } public bool Match(object data) { return data is ViewModelBase; } } }
26.0625
78
0.53717
[ "MIT" ]
aboimpinto/Avalonia.UITestFramework
Avalonia.UITestFramework.Example/ViewLocator.cs
834
C#
/* Write a program that takes as input a four-digit number in format abcd (e.g. 2011) and performs the following: Calculates the sum of the digits (in our example 2 + 0 + 1 + 1 = 4). Prints on the console the number in reversed order: dcba (in our example 1102). Puts the last digit in the first position: dabc (in our example 1201). Exchanges the second and the third digits: acbd (in our example 2101). The number has always exactly 4 digits and cannot start with 0. */ using System; class FourDigitNumber { static void Main() { Input: Console.Write("Please enter your 4-digit number: "); int num; if (!int.TryParse(Console.ReadLine(), out num) || num < 1000 || num > 9999) { Console.WriteLine("Wrong input number, try again"); goto Input; } int num1 = num / 1000; int num2 = (num / 100) % 10; int num3 = (num / 10) % 10; int num4 = num % 10; Console.WriteLine("Sum of all digits is: {0}", num1 + num2 + num3 + num4); Console.WriteLine("Reversed order: {0}{1}{2}{3}", num4, num3, num2, num1); Console.WriteLine("Last digit 1st pos.: {0}{1}{2}{3}", num4, num1, num2, num3); Console.WriteLine("2nd and 3rd digit positions swapped: {0}{1}{2}{3}", num1, num3, num2, num4); } }
34.073171
111
0.582677
[ "MIT" ]
jsdelivrbot/Telerik-Academy-Homeworks
Module 1 - Essentials/01_C# Part 1/03_Operators and Expressions/06_Four-Digit Number/FourDigitNumber.cs
1,399
C#
using System; using System.Threading.Tasks; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Connector; using System.Linq; using System.Net.Http; namespace EchoBot.Dialogs { [Serializable] public class RootDialog : IDialog<object> { public Task StartAsync(IDialogContext context) { context.Wait(MessageReceivedAsync); return Task.CompletedTask; } private async Task MessageReceivedAsync(IDialogContext context, IAwaitable<object> result) { var activity = await result as Activity; // calculate something for us to return int length = (activity.Text ?? string.Empty).Length; // return our reply to the user await context.PostAsync($"You sent {activity.Text} which was {length} characters"); context.Wait(MessageReceivedAsync); } } }
27.454545
98
0.649007
[ "MIT" ]
kreuzhofer/customspeechbot
src/CustomSpeechBot/EchoBot/Dialogs/RootDialog.cs
908
C#
using DotNetty.Codecs; using DotNetty.Common.Utilities; using DotNetty.Handlers.Timeout; using DotNetty.Transport.Bootstrapping; using DotNetty.Transport.Channels; using System; using System.Collections.Generic; using System.Net; using System.Text; namespace Meou.Transport.DotNetty { internal class DefaultConnectionWatchdog : ConnectionWatchdog { private ConnectorIdleStateTrigger idleStateTrigger = new ConnectorIdleStateTrigger(); private Bootstrap boot; private readonly ProtocolEncoder encoder = new ProtocolEncoder(); private HeartBeatClientHandler handler = new HeartBeatClientHandler(); public DefaultConnectionWatchdog(Bootstrap bootstrap, ITimer timer, EndPoint endPoint, int reconnect) : base(bootstrap, timer, endPoint, reconnect) { } public override IChannelHandler[] handlers() { return new IChannelHandler[] { this, new IdleStateHandler(0, 4, 0), this.idleStateTrigger, new ProtocolDecoder(), encoder, handler }; } } }
28.195122
155
0.665225
[ "MIT" ]
lc8882972/MeouY
src/Meou.Transport.DotNetty/DefaultConnectionWatchdog.cs
1,158
C#
#pragma checksum "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\Promocoes\Index2.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "f88970b699ced9c60eacee2efb442baac3e4d40b" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Promocoes_Index2), @"mvc.1.0.view", @"/Views/Promocoes/Index2.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\_ViewImports.cshtml" using CodeAndTravel; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\_ViewImports.cshtml" using CodeAndTravel.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"f88970b699ced9c60eacee2efb442baac3e4d40b", @"/Views/Promocoes/Index2.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"4c51c95ec078b4f2f71117e1164f567082328f9d", @"/Views/_ViewImports.cshtml")] public class Views_Promocoes_Index2 : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<IEnumerable<CodeAndTravel.Models.Promocao>> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Create", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn btn-primary"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Edit", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn btn-warning"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Details", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn btn-info"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Delete", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("btn btn-danger"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("\r\n"); #nullable restore #line 3 "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\Promocoes\Index2.cshtml" ViewData["Title"] = "Promoções"; #line default #line hidden #nullable disable WriteLiteral("\r\n\r\n\r\n<h1>Promoções</h1>\r\n\r\n<p>\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "f88970b699ced9c60eacee2efb442baac3e4d40b6045", async() => { WriteLiteral("Criar Promoção"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_0.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n</p>\r\n<table class=\"table\">\r\n <thead>\r\n <tr>\r\n <th>\r\n "); #nullable restore #line 18 "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\Promocoes\Index2.cshtml" Write(Html.DisplayNameFor(model => model.Nome)); #line default #line hidden #nullable disable WriteLiteral("\r\n </th>\r\n <th>\r\n "); #nullable restore #line 21 "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\Promocoes\Index2.cshtml" Write(Html.DisplayNameFor(model => model.Destino)); #line default #line hidden #nullable disable WriteLiteral("\r\n </th>\r\n <th>\r\n "); #nullable restore #line 24 "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\Promocoes\Index2.cshtml" Write(Html.DisplayNameFor(model => model.Descricao)); #line default #line hidden #nullable disable WriteLiteral("\r\n </th>\r\n <th>\r\n "); #nullable restore #line 27 "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\Promocoes\Index2.cshtml" Write(Html.DisplayNameFor(model => model.Desconto)); #line default #line hidden #nullable disable WriteLiteral("\r\n </th>\r\n <th></th>\r\n </tr>\r\n </thead>\r\n <tbody>\r\n"); #nullable restore #line 33 "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\Promocoes\Index2.cshtml" foreach (var item in Model) { #line default #line hidden #nullable disable WriteLiteral(" <tr>\r\n <td>\r\n "); #nullable restore #line 36 "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\Promocoes\Index2.cshtml" Write(Html.DisplayFor(modelItem => item.Nome)); #line default #line hidden #nullable disable WriteLiteral("\r\n </td>\r\n <td>\r\n "); #nullable restore #line 39 "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\Promocoes\Index2.cshtml" Write(Html.DisplayFor(modelItem => item.Destino.Nome)); #line default #line hidden #nullable disable WriteLiteral("\r\n </td>\r\n <td>\r\n "); #nullable restore #line 42 "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\Promocoes\Index2.cshtml" Write(Html.DisplayFor(modelItem => item.Descricao)); #line default #line hidden #nullable disable WriteLiteral("\r\n </td>\r\n <td>\r\n "); #nullable restore #line 45 "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\Promocoes\Index2.cshtml" Write(Html.DisplayFor(modelItem => item.Desconto)); #line default #line hidden #nullable disable WriteLiteral("\r\n </td>\r\n <td>\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "f88970b699ced9c60eacee2efb442baac3e4d40b10297", async() => { WriteLiteral("Editar"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_2.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2); if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null) { throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues")); } BeginWriteTagHelperAttribute(); #nullable restore #line 48 "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\Promocoes\Index2.cshtml" WriteLiteral(item.ID); #line default #line hidden #nullable disable __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer; __tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral(" |\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "f88970b699ced9c60eacee2efb442baac3e4d40b12554", async() => { WriteLiteral("Detalhes"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_4.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null) { throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues")); } BeginWriteTagHelperAttribute(); #nullable restore #line 49 "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\Promocoes\Index2.cshtml" WriteLiteral(item.ID); #line default #line hidden #nullable disable __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer; __tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral(" |\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "f88970b699ced9c60eacee2efb442baac3e4d40b14816", async() => { WriteLiteral("Excluir"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_6.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6); if (__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues == null) { throw new InvalidOperationException(InvalidTagHelperIndexerAssignment("asp-route-id", "Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper", "RouteValues")); } BeginWriteTagHelperAttribute(); #nullable restore #line 50 "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\Promocoes\Index2.cshtml" WriteLiteral(item.ID); #line default #line hidden #nullable disable __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"] = __tagHelperStringValueBuffer; __tagHelperExecutionContext.AddTagHelperAttribute("asp-route-id", __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.RouteValues["id"], global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </td>\r\n </tr>\r\n"); #nullable restore #line 53 "C:\Users\vavah\source\repos\CodeAndTravel\CodeAndTravel\Views\Promocoes\Index2.cshtml" } #line default #line hidden #nullable disable WriteLiteral(" </tbody>\r\n</table>\r\n"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<IEnumerable<CodeAndTravel.Models.Promocao>> Html { get; private set; } } } #pragma warning restore 1591
63.678445
353
0.727485
[ "MIT" ]
Vagner-Lopes/ProjetoVagnerRecodeCerto
CodeAndTravel/CodeAndTravel/obj/Debug/net5.0/Razor/Views/Promocoes/Index2.cshtml.g.cs
18,027
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using racewrangler.Data; namespace racewrangler { public class Program { public static void Main(string[] args) { var host = CreateHostBuilder(args).Build(); CreateDbIfNotExists(host); host.Run(); } private static void CreateDbIfNotExists(IHost host) { using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; //try //{ var context = services.GetRequiredService<racewranglerContext>(); //context.Database.EnsureCreated(); dbInitializer.Initialize(context); //} //catch (Exception ex) //{ // var logger = services.GetRequiredService<ILogger<Program>>(); // logger.LogError(ex, "An error occurred creating the DB."); //} } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
29.254545
85
0.571784
[ "MIT" ]
c4tachan/racewrangler
racewrangler/Program.cs
1,609
C#
// Copyright (c) 2007-2018 Thong Nguyen (tumtumtum@gmail.com) using System; using Platform.Validation; namespace Shaolinq.Tests.TestModel { [DataAccessObject(NotPersisted = true)] public abstract class Person : DataAccessObject<Guid>, IIdentified<Guid> { [PersistedMember] [DefaultValue(Value = "Anonymous")] public abstract string Firstname { get; set; } [Index(LowercaseIndex = true), PersistedMember, SizeConstraint(MaximumLength = 64)] public abstract string Email { get; set; } [PersistedMember] public abstract string Lastname { get; set; } [PersistedMember] public abstract string Nickname { get; set; } [PersistedMember, DefaultValue(0)] public abstract double Height { get; set; } [PersistedMember] public abstract double? Weight { get; set; } [PersistedMember, DefaultValue(0)] public abstract decimal BankBalance { get; set; } [PersistedMember, DefaultValue(0)] public abstract int FavouriteNumber { get; set; } [ComputedMember("Height + (Weight ?? 0)"), DefaultValue(0)] public abstract long HeightAndWeight { get; set; } [Index(Condition = "value != null")] [ComputedMember("CalculateHeightAndWeight()")] public abstract long? HeightAndWeight2 { get; set; } [DependsOnProperty(nameof(Height))] [DependsOnProperty(nameof(Weight))] public long CalculateHeightAndWeight() { return (int)(this.Height + (this.Weight ?? 0)); } [ComputedTextMember("{Firstname} {Lastname}")] public abstract string Fullname { get; set; } [PersistedMember, DefaultValue("2016-01-01")] public abstract FixedDate? Birthdate { get; set; } [PersistedMember] public abstract FixedDate FavouriteDate { get; set; } [PersistedMember] public abstract DateTime? SpecialDate { get; set; } [PersistedMember, DefaultValue("00:00")] public abstract TimeSpan TimeSinceLastSlept { get; set; } [DependsOnProperty(nameof(Id))] protected virtual string CompactIdString => this.Id.ToString("N"); [ComputedTextMember("urn:$(PERSISTED_TYPENAME:L):{Id:N}")] public abstract string Urn { get; set; } } }
29.175676
86
0.69245
[ "MIT" ]
asizikov/Shaolinq
tests/Shaolinq.Tests/TestModel/Person.cs
2,159
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine.EventSystems; using UnityEngine.UI; namespace Cronyx.Console.UI { /// <summary> /// <see cref="ScrollRect"/> wrapper with support for various callbacks. /// </summary> internal class EventScrollRect : ScrollRect { public event Action<PointerEventData> onInitializePotentialDrag; public event Action<PointerEventData> onBeginDrag; public event Action<PointerEventData> onDrag; public event Action<PointerEventData> onEndDrag; public event Action<PointerEventData> onScroll; public override void OnInitializePotentialDrag(PointerEventData eventData) { base.OnInitializePotentialDrag(eventData); onInitializePotentialDrag?.Invoke(eventData); } public override void OnBeginDrag(PointerEventData eventData) { base.OnBeginDrag(eventData); onBeginDrag?.Invoke(eventData); } public override void OnDrag(PointerEventData eventData) { base.OnDrag(eventData); onDrag?.Invoke(eventData); } public override void OnEndDrag(PointerEventData eventData) { base.OnEndDrag(eventData); onEndDrag?.Invoke(eventData); } public override void OnScroll(PointerEventData data) { base.OnScroll(data); onScroll?.Invoke(data); } } }
24.924528
76
0.766086
[ "MIT" ]
cronyxllc/DeveloperConsole
console/Packages/com.cronyx.console/Runtime/Scripts/UI/EventScrollRect.cs
1,323
C#
using LiveSplit.Model; using System; using System.Drawing; using System.Windows.Forms; using System.Xml; namespace LiveSplit.UI.Components { public partial class CurrentComparisonSettings : UserControl { public Color TextColor { get; set; } public bool OverrideTextColor { get; set; } public Color TimeColor { get; set; } public bool OverrideTimeColor { get; set; } public Color BackgroundColor { get; set; } public Color BackgroundColor2 { get; set; } public GradientType BackgroundGradient { get; set; } public string GradientString { get { return BackgroundGradient.ToString(); } set { BackgroundGradient = (GradientType)Enum.Parse(typeof(GradientType), value); } } public Font Font1 { get; set; } public string Font1String => SettingsHelper.FormatFont(Font1); public bool OverrideFont1 { get; set; } public Font Font2 { get; set; } public string Font2String => SettingsHelper.FormatFont(Font2); public bool OverrideFont2 { get; set; } public bool Display2Rows { get; set; } public LayoutMode Mode { get; set; } public LiveSplitState CurrentState { get; set; } public CurrentComparisonSettings() { InitializeComponent(); TextColor = Color.FromArgb(255, 255, 255); OverrideTextColor = false; TimeColor = Color.FromArgb(255, 255, 255); OverrideTimeColor = false; BackgroundColor = Color.Transparent; BackgroundColor2 = Color.Transparent; BackgroundGradient = GradientType.Plain; OverrideFont1 = false; OverrideFont2 = false; Font1 = new Font("Segoe UI", 13, FontStyle.Regular, GraphicsUnit.Pixel); Font2 = new Font("Segoe UI", 13, FontStyle.Regular, GraphicsUnit.Pixel); Display2Rows = false; chkOverrideTextColor.DataBindings.Add("Checked", this, "OverrideTextColor", false, DataSourceUpdateMode.OnPropertyChanged); btnTextColor.DataBindings.Add("BackColor", this, "TextColor", false, DataSourceUpdateMode.OnPropertyChanged); chkOverrideTimeColor.DataBindings.Add("Checked", this, "OverrideTimeColor", false, DataSourceUpdateMode.OnPropertyChanged); btnTimeColor.DataBindings.Add("BackColor", this, "TimeColor", false, DataSourceUpdateMode.OnPropertyChanged); lblFont.DataBindings.Add("Text", this, "Font1String", false, DataSourceUpdateMode.OnPropertyChanged); lblFont2.DataBindings.Add("Text", this, "Font2String", false, DataSourceUpdateMode.OnPropertyChanged); cmbGradientType.SelectedIndexChanged += cmbGradientType_SelectedIndexChanged; cmbGradientType.DataBindings.Add("SelectedItem", this, "GradientString", false, DataSourceUpdateMode.OnPropertyChanged); btnColor1.DataBindings.Add("BackColor", this, "BackgroundColor", false, DataSourceUpdateMode.OnPropertyChanged); btnColor2.DataBindings.Add("BackColor", this, "BackgroundColor2", false, DataSourceUpdateMode.OnPropertyChanged); chkFont.DataBindings.Add("Checked", this, "OverrideFont1", false, DataSourceUpdateMode.OnPropertyChanged); chkFont2.DataBindings.Add("Checked", this, "OverrideFont2", false, DataSourceUpdateMode.OnPropertyChanged); chkOverrideTextColor.CheckedChanged += chkOverrideTextColor_CheckedChanged; chkOverrideTimeColor.CheckedChanged += chkOverrideTimeColor_CheckedChanged; chkFont.CheckedChanged += chkFont_CheckedChanged; chkFont2.CheckedChanged += chkFont2_CheckedChanged; } void chkFont2_CheckedChanged(object sender, EventArgs e) { label7.Enabled = lblFont2.Enabled = btnFont2.Enabled = chkFont2.Checked; } void chkFont_CheckedChanged(object sender, EventArgs e) { label5.Enabled = lblFont.Enabled = btnFont.Enabled = chkFont.Checked; } void chkOverrideTimeColor_CheckedChanged(object sender, EventArgs e) { label2.Enabled = btnTimeColor.Enabled = chkOverrideTimeColor.Checked; } void chkOverrideTextColor_CheckedChanged(object sender, EventArgs e) { label1.Enabled = btnTextColor.Enabled = chkOverrideTextColor.Checked; } void CurrentComponentSettings_Load(object sender, EventArgs e) { chkOverrideTextColor_CheckedChanged(null, null); chkOverrideTimeColor_CheckedChanged(null, null); chkFont_CheckedChanged(null, null); chkFont2_CheckedChanged(null, null); if (Mode == LayoutMode.Horizontal) { chkTwoRows.Enabled = false; chkTwoRows.DataBindings.Clear(); chkTwoRows.Checked = true; } else { chkTwoRows.Enabled = true; chkTwoRows.DataBindings.Clear(); chkTwoRows.DataBindings.Add("Checked", this, "Display2Rows", false, DataSourceUpdateMode.OnPropertyChanged); } } void cmbGradientType_SelectedIndexChanged(object sender, EventArgs e) { btnColor1.Visible = cmbGradientType.SelectedItem.ToString() != "Plain"; btnColor2.DataBindings.Clear(); btnColor2.DataBindings.Add("BackColor", this, btnColor1.Visible ? "BackgroundColor2" : "BackgroundColor", false, DataSourceUpdateMode.OnPropertyChanged); GradientString = cmbGradientType.SelectedItem.ToString(); } public void SetSettings(XmlNode node) { var element = (XmlElement)node; TextColor = SettingsHelper.ParseColor(element["TextColor"]); OverrideTextColor = SettingsHelper.ParseBool(element["OverrideTextColor"]); TimeColor = SettingsHelper.ParseColor(element["TimeColor"]); OverrideTimeColor = SettingsHelper.ParseBool(element["OverrideTimeColor"]); BackgroundColor = SettingsHelper.ParseColor(element["BackgroundColor"]); BackgroundColor2 = SettingsHelper.ParseColor(element["BackgroundColor2"]); GradientString = SettingsHelper.ParseString(element["BackgroundGradient"]); Font1 = SettingsHelper.GetFontFromElement(element["Font1"]); Font2 = SettingsHelper.GetFontFromElement(element["Font2"]); OverrideFont1 = SettingsHelper.ParseBool(element["OverrideFont1"]); OverrideFont2 = SettingsHelper.ParseBool(element["OverrideFont2"]); Display2Rows = SettingsHelper.ParseBool(element["Display2Rows"], false); } public XmlNode GetSettings(XmlDocument document) { var parent = document.CreateElement("Settings"); CreateSettingsNode(document, parent); return parent; } public int GetSettingsHashCode() => CreateSettingsNode(null, null); private int CreateSettingsNode(XmlDocument document, XmlElement parent) { return SettingsHelper.CreateSetting(document, parent, "Version", "1.4") ^ SettingsHelper.CreateSetting(document, parent, "TextColor", TextColor) ^ SettingsHelper.CreateSetting(document, parent, "OverrideTextColor", OverrideTextColor) ^ SettingsHelper.CreateSetting(document, parent, "TimeColor", TimeColor) ^ SettingsHelper.CreateSetting(document, parent, "OverrideTimeColor", OverrideTimeColor) ^ SettingsHelper.CreateSetting(document, parent, "BackgroundColor", BackgroundColor) ^ SettingsHelper.CreateSetting(document, parent, "BackgroundColor2", BackgroundColor2) ^ SettingsHelper.CreateSetting(document, parent, "BackgroundGradient", BackgroundGradient) ^ SettingsHelper.CreateSetting(document, parent, "Font1", Font1) ^ SettingsHelper.CreateSetting(document, parent, "Font2", Font2) ^ SettingsHelper.CreateSetting(document, parent, "OverrideFont1", OverrideFont1) ^ SettingsHelper.CreateSetting(document, parent, "OverrideFont2", OverrideFont2) ^ SettingsHelper.CreateSetting(document, parent, "Display2Rows", Display2Rows); } private void ColorButtonClick(object sender, EventArgs e) { SettingsHelper.ColorButtonClick((Button)sender, this); } private void btnFont1_Click(object sender, EventArgs e) { var dialog = SettingsHelper.GetFontDialog(Font1, 7, 20); dialog.FontChanged += (s, ev) => Font1 = ((CustomFontDialog.FontChangedEventArgs)ev).NewFont; dialog.ShowDialog(this); lblFont.Text = Font1String; } private void btnFont2_Click(object sender, EventArgs e) { var dialog = SettingsHelper.GetFontDialog(Font2, 7, 20); dialog.FontChanged += (s, ev) => Font2 = ((CustomFontDialog.FontChangedEventArgs)ev).NewFont; dialog.ShowDialog(this); lblFont.Text = Font2String; } } }
48.566138
165
0.663689
[ "MIT" ]
mysidia/LiveSplit-Sid
LiveSplit/Components/LiveSplit.CurrentComparison/UI/Components/CurrentComparisonSettings.cs
9,181
C#
using System; using System.Collections.Generic; using Telerik.Charting; using Windows.Foundation; namespace Telerik.UI.Xaml.Controls.Chart { internal class RangeRenderer : AreaRendererBase { internal const string TopPointGetter = "TopPointGetter"; internal const string BottomPointGetter = "BottomPointGetter"; internal RangeSeriesStrokeMode strokeMode; private static ReferenceDictionary<string, Delegate> verticalRangePlotValueExtractors; private static ReferenceDictionary<string, Delegate> horizontalRangePlotValueExtractors; public RangeRenderer() { this.strokeMode = RangeSeriesStrokeMode.LowAndHighPoints; } public static ReferenceDictionary<string, Delegate> VerticalRangePlotValueExtractors { get { if (verticalRangePlotValueExtractors == null) { verticalRangePlotValueExtractors = new ReferenceDictionary<string, Delegate>(); verticalRangePlotValueExtractors.Set(TopPointGetter, (Func<DataPoint, Point>)((currentPoint) => new Point(currentPoint.LayoutSlot.X + currentPoint.LayoutSlot.Width / 2, currentPoint.LayoutSlot.Y))); verticalRangePlotValueExtractors.Set(BottomPointGetter, (Func<DataPoint, Point>)((currentPoint) => new Point(currentPoint.LayoutSlot.X + currentPoint.LayoutSlot.Width / 2, currentPoint.LayoutSlot.Bottom))); } return verticalRangePlotValueExtractors; } } public static ReferenceDictionary<string, Delegate> HorizontalRangePlotValueExtractors { get { if (horizontalRangePlotValueExtractors == null) { horizontalRangePlotValueExtractors = new ReferenceDictionary<string, Delegate>(); horizontalRangePlotValueExtractors.Set(TopPointGetter, (Func<DataPoint, Point>)((currentPoint) => new Point(currentPoint.LayoutSlot.Right, currentPoint.LayoutSlot.Y + currentPoint.LayoutSlot.Height / 2))); horizontalRangePlotValueExtractors.Set(BottomPointGetter, (Func<DataPoint, Point>)((currentPoint) => new Point(currentPoint.LayoutSlot.X, currentPoint.LayoutSlot.Y + currentPoint.LayoutSlot.Height / 2))); } return horizontalRangePlotValueExtractors; } } protected override bool ShouldAddTopPointsToStroke { get { return (this.strokeMode & RangeSeriesStrokeMode.HighPoints) == RangeSeriesStrokeMode.HighPoints; } } protected override bool ShouldAddBottomPointsToStroke { get { return (this.strokeMode & RangeSeriesStrokeMode.LowPoints) == RangeSeriesStrokeMode.LowPoints; } } protected override IEnumerable<Windows.Foundation.Point> GetTopPoints(DataPointSegment segment) { AxisPlotDirection plotDirection = this.model.GetTypedValue<AxisPlotDirection>(AxisModel.PlotDirectionPropertyKey, AxisPlotDirection.Vertical); ReferenceDictionary<string, Delegate> valueExtractor = plotDirection == AxisPlotDirection.Vertical ? VerticalRangePlotValueExtractors : HorizontalRangePlotValueExtractors; Func<DataPoint, Point> topPointGetter = (Func<DataPoint, Point>)valueExtractor[TopPointGetter]; int pointIndex = segment.StartIndex; while (pointIndex <= segment.EndIndex) { var currentPoint = this.renderPoints[pointIndex]; yield return topPointGetter(currentPoint); pointIndex++; } } protected override IList<Point> GetBottomPoints(AreaRenderContext context) { AxisPlotDirection plotDirection = this.model.GetTypedValue<AxisPlotDirection>(AxisModel.PlotDirectionPropertyKey, AxisPlotDirection.Vertical); ReferenceDictionary<string, Delegate> valueExtractor = plotDirection == AxisPlotDirection.Vertical ? VerticalRangePlotValueExtractors : HorizontalRangePlotValueExtractors; Func<DataPoint, Point> bottomPointGetter = (Func<DataPoint, Point>)valueExtractor[BottomPointGetter]; DataPointSegment currentSegment = context.CurrentSegment; List<Point> points = new List<Point>(); int pointIndex = currentSegment.StartIndex; while (pointIndex <= currentSegment.EndIndex) { var currentPoint = this.renderPoints[pointIndex]; points.Add(bottomPointGetter(currentPoint)); pointIndex++; } return points; } } }
46.60396
226
0.676014
[ "Apache-2.0" ]
ChristianGutman/UI-For-UWP
Controls/Chart/Chart.UWP/Visualization/Common/Renderers/Cartesian/Range/RangeRenderer.cs
4,709
C#
/* Copyright (C) 2012-2014 de4dot@gmail.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System.Collections.Generic; /* All signature classes: CallingConventionSig FieldSig MethodBaseSig MethodSig PropertySig LocalSig GenericInstMethodSig */ namespace dnlib.DotNet { /// <summary> /// Base class for sigs with a calling convention /// </summary> public abstract class CallingConventionSig { /// <summary> /// The calling convention /// </summary> protected CallingConvention callingConvention; byte[] extraData; /// <summary> /// Gets/sets the extra data found after the signature /// </summary> public byte[] ExtraData { get { return extraData; } set { extraData = value; } } /// <summary> /// Returns <c>true</c> if <see cref="CallingConvention.Default"/> is set /// </summary> public bool IsDefault { get { return (callingConvention & CallingConvention.Mask) == CallingConvention.Default; } } /// <summary> /// Returns <c>true</c> if <see cref="CallingConvention.C"/> is set /// </summary> public bool IsC { get { return (callingConvention & CallingConvention.Mask) == CallingConvention.C; } } /// <summary> /// Returns <c>true</c> if <see cref="CallingConvention.StdCall"/> is set /// </summary> public bool IsStdCall { get { return (callingConvention & CallingConvention.Mask) == CallingConvention.StdCall; } } /// <summary> /// Returns <c>true</c> if <see cref="CallingConvention.ThisCall"/> is set /// </summary> public bool IsThisCall { get { return (callingConvention & CallingConvention.Mask) == CallingConvention.ThisCall; } } /// <summary> /// Returns <c>true</c> if <see cref="CallingConvention.FastCall"/> is set /// </summary> public bool IsFastCall { get { return (callingConvention & CallingConvention.Mask) == CallingConvention.FastCall; } } /// <summary> /// Returns <c>true</c> if <see cref="CallingConvention.VarArg"/> is set /// </summary> public bool IsVarArg { get { return (callingConvention & CallingConvention.Mask) == CallingConvention.VarArg; } } /// <summary> /// Returns <c>true</c> if <see cref="CallingConvention.Field"/> is set /// </summary> public bool IsField { get { return (callingConvention & CallingConvention.Mask) == CallingConvention.Field; } } /// <summary> /// Returns <c>true</c> if <see cref="CallingConvention.LocalSig"/> is set /// </summary> public bool IsLocalSig { get { return (callingConvention & CallingConvention.Mask) == CallingConvention.LocalSig; } } /// <summary> /// Returns <c>true</c> if <see cref="CallingConvention.Property"/> is set /// </summary> public bool IsProperty { get { return (callingConvention & CallingConvention.Mask) == CallingConvention.Property; } } /// <summary> /// Returns <c>true</c> if <see cref="CallingConvention.Unmanaged"/> is set /// </summary> public bool IsUnmanaged { get { return (callingConvention & CallingConvention.Mask) == CallingConvention.Unmanaged; } } /// <summary> /// Returns <c>true</c> if <see cref="CallingConvention.GenericInst"/> is set /// </summary> public bool IsGenericInst { get { return (callingConvention & CallingConvention.Mask) == CallingConvention.GenericInst; } } /// <summary> /// Returns <c>true</c> if <see cref="CallingConvention.NativeVarArg"/> is set /// </summary> public bool IsNativeVarArg { get { return (callingConvention & CallingConvention.Mask) == CallingConvention.NativeVarArg; } } /// <summary> /// Gets/sets the <see cref="CallingConvention.Generic"/> bit /// </summary> public bool Generic { get { return (callingConvention & CallingConvention.Generic) != 0; } set { if (value) callingConvention |= CallingConvention.Generic; else callingConvention &= ~CallingConvention.Generic; } } /// <summary> /// Gets/sets the <see cref="CallingConvention.HasThis"/> bit /// </summary> public bool HasThis { get { return (callingConvention & CallingConvention.HasThis) != 0; } set { if (value) callingConvention |= CallingConvention.HasThis; else callingConvention &= ~CallingConvention.HasThis; } } /// <summary> /// Gets/sets the <see cref="CallingConvention.ExplicitThis"/> bit /// </summary> public bool ExplicitThis { get { return (callingConvention & CallingConvention.ExplicitThis) != 0; } set { if (value) callingConvention |= CallingConvention.ExplicitThis; else callingConvention &= ~CallingConvention.ExplicitThis; } } /// <summary> /// Gets/sets the <see cref="CallingConvention.ReservedByCLR"/> bit /// </summary> public bool ReservedByCLR { get { return (callingConvention & CallingConvention.ReservedByCLR) != 0; } set { if (value) callingConvention |= CallingConvention.ReservedByCLR; else callingConvention &= ~CallingConvention.ReservedByCLR; } } /// <summary> /// <c>true</c> if there's an implicit <c>this</c> parameter /// </summary> public bool ImplicitThis { get { return HasThis && !ExplicitThis; } } /// <summary> /// Default constructor /// </summary> protected CallingConventionSig() { } /// <summary> /// Constructor /// </summary> /// <param name="callingConvention">The calling convention</param> protected CallingConventionSig(CallingConvention callingConvention) { this.callingConvention = callingConvention; } /// <summary> /// Gets the calling convention /// </summary> public CallingConvention GetCallingConvention() { return callingConvention; } } /// <summary> /// A field signature /// </summary> public sealed class FieldSig : CallingConventionSig { TypeSig type; /// <summary> /// Gets/sets the field type /// </summary> public TypeSig Type { get { return type; } set { type = value; } } /// <summary> /// Default constructor /// </summary> public FieldSig() { this.callingConvention = CallingConvention.Field; } /// <summary> /// Constructor /// </summary> /// <param name="type">Field type</param> public FieldSig(TypeSig type) { this.callingConvention = CallingConvention.Field; this.type = type; } /// <summary> /// Constructor /// </summary> /// <param name="type">Field type</param> /// <param name="callingConvention">The calling convention (must have Field set)</param> internal FieldSig(CallingConvention callingConvention, TypeSig type) { this.callingConvention = callingConvention; this.type = type; } /// <summary> /// Clone this /// </summary> public FieldSig Clone() { return new FieldSig(callingConvention, type); } /// <inheritdoc/> public override string ToString() { return FullNameCreator.FullName(type == null ? null : type, false); } } /// <summary> /// Method sig base class /// </summary> public abstract class MethodBaseSig : CallingConventionSig { /// <summary/> protected TypeSig retType; /// <summary/> protected IList<TypeSig> parameters; /// <summary/> protected uint genParamCount; /// <summary/> protected IList<TypeSig> paramsAfterSentinel; /// <summary> /// Gets/sets the calling convention /// </summary> public CallingConvention CallingConvention { get { return callingConvention; } set { callingConvention = value; } } /// <summary> /// Gets/sets the return type /// </summary> public TypeSig RetType { get { return retType; } set { retType = value; } } /// <summary> /// Gets the parameters. This is never <c>null</c> /// </summary> public IList<TypeSig> Params { get { return parameters; } } /// <summary> /// Gets/sets the generic param count /// </summary> public uint GenParamCount { get { return genParamCount; } set { genParamCount = value; } } /// <summary> /// Gets the parameters that are present after the sentinel. Note that this is <c>null</c> /// if there's no sentinel. It can still be empty even if it's not <c>null</c>. /// </summary> public IList<TypeSig> ParamsAfterSentinel { get { return paramsAfterSentinel; } set { paramsAfterSentinel = value; } } } /// <summary> /// A method signature /// </summary> public sealed class MethodSig : MethodBaseSig { uint origToken; /// <summary> /// Gets/sets the original token. It's set when reading calli instruction operands /// and it's a hint to the module writer if it tries to re-use the same token. /// </summary> public uint OriginalToken { get { return origToken; } set { origToken = value; } } /// <summary> /// Creates a static MethodSig /// </summary> /// <param name="retType">Return type</param> public static MethodSig CreateStatic(TypeSig retType) { return new MethodSig(CallingConvention.Default, 0, retType); } /// <summary> /// Creates a static MethodSig /// </summary> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> public static MethodSig CreateStatic(TypeSig retType, TypeSig argType1) { return new MethodSig(CallingConvention.Default, 0, retType, argType1); } /// <summary> /// Creates a static MethodSig /// </summary> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> /// <param name="argType2">Arg type #2</param> public static MethodSig CreateStatic(TypeSig retType, TypeSig argType1, TypeSig argType2) { return new MethodSig(CallingConvention.Default, 0, retType, argType1, argType2); } /// <summary> /// Creates a static MethodSig /// </summary> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> /// <param name="argType2">Arg type #2</param> /// <param name="argType3">Arg type #3</param> public static MethodSig CreateStatic(TypeSig retType, TypeSig argType1, TypeSig argType2, TypeSig argType3) { return new MethodSig(CallingConvention.Default, 0, retType, argType1, argType2, argType3); } /// <summary> /// Creates a static MethodSig /// </summary> /// <param name="retType">Return type</param> /// <param name="argTypes">Argument types</param> public static MethodSig CreateStatic(TypeSig retType, params TypeSig[] argTypes) { return new MethodSig(CallingConvention.Default, 0, retType, argTypes); } /// <summary> /// Creates an instance MethodSig /// </summary> /// <param name="retType">Return type</param> public static MethodSig CreateInstance(TypeSig retType) { return new MethodSig(CallingConvention.Default | CallingConvention.HasThis, 0, retType); } /// <summary> /// Creates an instance MethodSig /// </summary> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> public static MethodSig CreateInstance(TypeSig retType, TypeSig argType1) { return new MethodSig(CallingConvention.Default | CallingConvention.HasThis, 0, retType, argType1); } /// <summary> /// Creates an instance MethodSig /// </summary> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> /// <param name="argType2">Arg type #2</param> public static MethodSig CreateInstance(TypeSig retType, TypeSig argType1, TypeSig argType2) { return new MethodSig(CallingConvention.Default | CallingConvention.HasThis, 0, retType, argType1, argType2); } /// <summary> /// Creates an instance MethodSig /// </summary> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> /// <param name="argType2">Arg type #2</param> /// <param name="argType3">Arg type #3</param> public static MethodSig CreateInstance(TypeSig retType, TypeSig argType1, TypeSig argType2, TypeSig argType3) { return new MethodSig(CallingConvention.Default | CallingConvention.HasThis, 0, retType, argType1, argType2, argType3); } /// <summary> /// Creates an instance MethodSig /// </summary> /// <param name="retType">Return type</param> /// <param name="argTypes">Argument types</param> public static MethodSig CreateInstance(TypeSig retType, params TypeSig[] argTypes) { return new MethodSig(CallingConvention.Default | CallingConvention.HasThis, 0, retType, argTypes); } /// <summary> /// Creates a static generic MethodSig /// </summary> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> public static MethodSig CreateStaticGeneric(uint genParamCount, TypeSig retType) { return new MethodSig(CallingConvention.Default | CallingConvention.Generic, genParamCount, retType); } /// <summary> /// Creates a static generic MethodSig /// </summary> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> public static MethodSig CreateStaticGeneric(uint genParamCount, TypeSig retType, TypeSig argType1) { return new MethodSig(CallingConvention.Default | CallingConvention.Generic, genParamCount, retType, argType1); } /// <summary> /// Creates a static generic MethodSig /// </summary> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> /// <param name="argType2">Arg type #2</param> public static MethodSig CreateStaticGeneric(uint genParamCount, TypeSig retType, TypeSig argType1, TypeSig argType2) { return new MethodSig(CallingConvention.Default | CallingConvention.Generic, genParamCount, retType, argType1, argType2); } /// <summary> /// Creates a static generic MethodSig /// </summary> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> /// <param name="argType2">Arg type #2</param> /// <param name="argType3">Arg type #3</param> public static MethodSig CreateStaticGeneric(uint genParamCount, TypeSig retType, TypeSig argType1, TypeSig argType2, TypeSig argType3) { return new MethodSig(CallingConvention.Default | CallingConvention.Generic, genParamCount, retType, argType1, argType2, argType3); } /// <summary> /// Creates a static generic MethodSig /// </summary> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> /// <param name="argTypes">Argument types</param> public static MethodSig CreateStaticGeneric(uint genParamCount, TypeSig retType, params TypeSig[] argTypes) { return new MethodSig(CallingConvention.Default | CallingConvention.Generic, genParamCount, retType, argTypes); } /// <summary> /// Creates an instance generic MethodSig /// </summary> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> public static MethodSig CreateInstanceGeneric(uint genParamCount, TypeSig retType) { return new MethodSig(CallingConvention.Default | CallingConvention.HasThis | CallingConvention.Generic, genParamCount, retType); } /// <summary> /// Creates an instance generic MethodSig /// </summary> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> public static MethodSig CreateInstanceGeneric(uint genParamCount, TypeSig retType, TypeSig argType1) { return new MethodSig(CallingConvention.Default | CallingConvention.HasThis | CallingConvention.Generic, genParamCount, retType, argType1); } /// <summary> /// Creates an instance generic MethodSig /// </summary> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> /// <param name="argType2">Arg type #2</param> public static MethodSig CreateInstanceGeneric(uint genParamCount, TypeSig retType, TypeSig argType1, TypeSig argType2) { return new MethodSig(CallingConvention.Default | CallingConvention.HasThis | CallingConvention.Generic, genParamCount, retType, argType1, argType2); } /// <summary> /// Creates an instance generic MethodSig /// </summary> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> /// <param name="argType2">Arg type #2</param> /// <param name="argType3">Arg type #3</param> public static MethodSig CreateInstanceGeneric(uint genParamCount, TypeSig retType, TypeSig argType1, TypeSig argType2, TypeSig argType3) { return new MethodSig(CallingConvention.Default | CallingConvention.HasThis | CallingConvention.Generic, genParamCount, retType, argType1, argType2, argType3); } /// <summary> /// Creates an instance generic MethodSig /// </summary> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> /// <param name="argTypes">Argument types</param> public static MethodSig CreateInstanceGeneric(uint genParamCount, TypeSig retType, params TypeSig[] argTypes) { return new MethodSig(CallingConvention.Default | CallingConvention.HasThis | CallingConvention.Generic, genParamCount, retType, argTypes); } /// <summary> /// Default constructor /// </summary> public MethodSig() { this.parameters = new List<TypeSig>(); } /// <summary> /// Constructor /// </summary> /// <param name="callingConvention">Calling convention</param> public MethodSig(CallingConvention callingConvention) { this.callingConvention = callingConvention; this.parameters = new List<TypeSig>(); } /// <summary> /// Constructor /// </summary> /// <param name="callingConvention">Calling convention</param> /// <param name="genParamCount">Number of generic parameters</param> public MethodSig(CallingConvention callingConvention, uint genParamCount) { this.callingConvention = callingConvention; this.genParamCount = genParamCount; this.parameters = new List<TypeSig>(); } /// <summary> /// Constructor /// </summary> /// <param name="callingConvention">Calling convention</param> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> public MethodSig(CallingConvention callingConvention, uint genParamCount, TypeSig retType) { this.callingConvention = callingConvention; this.genParamCount = genParamCount; this.retType = retType; this.parameters = new List<TypeSig>(); } /// <summary> /// Constructor /// </summary> /// <param name="callingConvention">Calling convention</param> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> public MethodSig(CallingConvention callingConvention, uint genParamCount, TypeSig retType, TypeSig argType1) { this.callingConvention = callingConvention; this.genParamCount = genParamCount; this.retType = retType; this.parameters = new List<TypeSig> { argType1 }; } /// <summary> /// Constructor /// </summary> /// <param name="callingConvention">Calling convention</param> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> /// <param name="argType2">Arg type #2</param> public MethodSig(CallingConvention callingConvention, uint genParamCount, TypeSig retType, TypeSig argType1, TypeSig argType2) { this.callingConvention = callingConvention; this.genParamCount = genParamCount; this.retType = retType; this.parameters = new List<TypeSig> { argType1, argType2 }; } /// <summary> /// Constructor /// </summary> /// <param name="callingConvention">Calling convention</param> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> /// <param name="argType2">Arg type #2</param> /// <param name="argType3">Arg type #3</param> public MethodSig(CallingConvention callingConvention, uint genParamCount, TypeSig retType, TypeSig argType1, TypeSig argType2, TypeSig argType3) { this.callingConvention = callingConvention; this.genParamCount = genParamCount; this.retType = retType; this.parameters = new List<TypeSig> { argType1, argType2, argType3 }; } /// <summary> /// Constructor /// </summary> /// <param name="callingConvention">Calling convention</param> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> /// <param name="argTypes">Argument types</param> public MethodSig(CallingConvention callingConvention, uint genParamCount, TypeSig retType, params TypeSig[] argTypes) { this.callingConvention = callingConvention; this.genParamCount = genParamCount; this.retType = retType; this.parameters = new List<TypeSig>(argTypes); } /// <summary> /// Constructor /// </summary> /// <param name="callingConvention">Calling convention</param> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> /// <param name="argTypes">Argument types</param> public MethodSig(CallingConvention callingConvention, uint genParamCount, TypeSig retType, IList<TypeSig> argTypes) { this.callingConvention = callingConvention; this.genParamCount = genParamCount; this.retType = retType; this.parameters = new List<TypeSig>(argTypes); } /// <summary> /// Constructor /// </summary> /// <param name="callingConvention">Calling convention</param> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> /// <param name="argTypes">Argument types</param> /// <param name="paramsAfterSentinel">Parameters after sentinel</param> public MethodSig(CallingConvention callingConvention, uint genParamCount, TypeSig retType, IList<TypeSig> argTypes, IList<TypeSig> paramsAfterSentinel) { this.callingConvention = callingConvention; this.genParamCount = genParamCount; this.retType = retType; this.parameters = new List<TypeSig>(argTypes); this.paramsAfterSentinel = paramsAfterSentinel == null ? null : new List<TypeSig>(paramsAfterSentinel); } /// <summary> /// Clone this /// </summary> public MethodSig Clone() { return new MethodSig(callingConvention, genParamCount, retType, parameters, paramsAfterSentinel); } } /// <summary> /// A property signature /// </summary> public sealed class PropertySig : MethodBaseSig { /// <summary> /// Creates a static PropertySig /// </summary> /// <param name="retType">Return type</param> public static PropertySig CreateStatic(TypeSig retType) { return new PropertySig(false, retType); } /// <summary> /// Creates a static PropertySig /// </summary> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> public static PropertySig CreateStatic(TypeSig retType, TypeSig argType1) { return new PropertySig(false, retType, argType1); } /// <summary> /// Creates a static PropertySig /// </summary> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> /// <param name="argType2">Arg type #2</param> public static PropertySig CreateStatic(TypeSig retType, TypeSig argType1, TypeSig argType2) { return new PropertySig(false, retType, argType1, argType2); } /// <summary> /// Creates a static PropertySig /// </summary> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> /// <param name="argType2">Arg type #2</param> /// <param name="argType3">Arg type #3</param> public static PropertySig CreateStatic(TypeSig retType, TypeSig argType1, TypeSig argType2, TypeSig argType3) { return new PropertySig(false, retType, argType1, argType2, argType3); } /// <summary> /// Creates a static PropertySig /// </summary> /// <param name="retType">Return type</param> /// <param name="argTypes">Argument types</param> public static PropertySig CreateStatic(TypeSig retType, params TypeSig[] argTypes) { return new PropertySig(false, retType, argTypes); } /// <summary> /// Creates an instance PropertySig /// </summary> /// <param name="retType">Return type</param> public static PropertySig CreateInstance(TypeSig retType) { return new PropertySig(true, retType); } /// <summary> /// Creates an instance PropertySig /// </summary> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> public static PropertySig CreateInstance(TypeSig retType, TypeSig argType1) { return new PropertySig(true, retType, argType1); } /// <summary> /// Creates an instance PropertySig /// </summary> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> /// <param name="argType2">Arg type #2</param> public static PropertySig CreateInstance(TypeSig retType, TypeSig argType1, TypeSig argType2) { return new PropertySig(true, retType, argType1, argType2); } /// <summary> /// Creates an instance PropertySig /// </summary> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> /// <param name="argType2">Arg type #2</param> /// <param name="argType3">Arg type #3</param> public static PropertySig CreateInstance(TypeSig retType, TypeSig argType1, TypeSig argType2, TypeSig argType3) { return new PropertySig(true, retType, argType1, argType2, argType3); } /// <summary> /// Creates an instance PropertySig /// </summary> /// <param name="retType">Return type</param> /// <param name="argTypes">Argument types</param> public static PropertySig CreateInstance(TypeSig retType, params TypeSig[] argTypes) { return new PropertySig(true, retType, argTypes); } /// <summary> /// Default constructor /// </summary> public PropertySig() { this.callingConvention = CallingConvention.Property; this.parameters = new List<TypeSig>(); } /// <summary> /// Constructor /// </summary> /// <param name="callingConvention">Calling convention (must have Property set)</param> internal PropertySig(CallingConvention callingConvention) { this.callingConvention = callingConvention; this.parameters = new List<TypeSig>(); } /// <summary> /// Constructor /// </summary> /// <param name="hasThis"><c>true</c> if instance, <c>false</c> if static</param> public PropertySig(bool hasThis) { this.callingConvention = CallingConvention.Property | (hasThis ? CallingConvention.HasThis : 0); this.parameters = new List<TypeSig>(); } /// <summary> /// Constructor /// </summary> /// <param name="hasThis"><c>true</c> if instance, <c>false</c> if static</param> /// <param name="retType">Return type</param> public PropertySig(bool hasThis, TypeSig retType) { this.callingConvention = CallingConvention.Property | (hasThis ? CallingConvention.HasThis : 0); this.retType = retType; this.parameters = new List<TypeSig>(); } /// <summary> /// Constructor /// </summary> /// <param name="hasThis"><c>true</c> if instance, <c>false</c> if static</param> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> public PropertySig(bool hasThis, TypeSig retType, TypeSig argType1) { this.callingConvention = CallingConvention.Property | (hasThis ? CallingConvention.HasThis : 0); this.retType = retType; this.parameters = new List<TypeSig> { argType1 }; } /// <summary> /// Constructor /// </summary> /// <param name="hasThis"><c>true</c> if instance, <c>false</c> if static</param> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> /// <param name="argType2">Arg type #2</param> public PropertySig(bool hasThis, TypeSig retType, TypeSig argType1, TypeSig argType2) { this.callingConvention = CallingConvention.Property | (hasThis ? CallingConvention.HasThis : 0); this.retType = retType; this.parameters = new List<TypeSig> { argType1, argType2 }; } /// <summary> /// Constructor /// </summary> /// <param name="hasThis"><c>true</c> if instance, <c>false</c> if static</param> /// <param name="retType">Return type</param> /// <param name="argType1">Arg type #1</param> /// <param name="argType2">Arg type #2</param> /// <param name="argType3">Arg type #3</param> public PropertySig(bool hasThis, TypeSig retType, TypeSig argType1, TypeSig argType2, TypeSig argType3) { this.callingConvention = CallingConvention.Property | (hasThis ? CallingConvention.HasThis : 0); this.retType = retType; this.parameters = new List<TypeSig> { argType1, argType2, argType3 }; } /// <summary> /// Constructor /// </summary> /// <param name="hasThis"><c>true</c> if instance, <c>false</c> if static</param> /// <param name="retType">Return type</param> /// <param name="argTypes">Argument types</param> public PropertySig(bool hasThis, TypeSig retType, params TypeSig[] argTypes) { this.callingConvention = CallingConvention.Property | (hasThis ? CallingConvention.HasThis : 0); this.retType = retType; this.parameters = new List<TypeSig>(argTypes); } /// <summary> /// Constructor /// </summary> /// <param name="callingConvention">Calling convention</param> /// <param name="genParamCount">Number of generic parameters</param> /// <param name="retType">Return type</param> /// <param name="argTypes">Argument types</param> /// <param name="paramsAfterSentinel">Parameters after sentinel</param> internal PropertySig(CallingConvention callingConvention, uint genParamCount, TypeSig retType, IList<TypeSig> argTypes, IList<TypeSig> paramsAfterSentinel) { this.callingConvention = callingConvention; this.genParamCount = genParamCount; this.retType = retType; this.parameters = new List<TypeSig>(argTypes); this.paramsAfterSentinel = paramsAfterSentinel == null ? null : new List<TypeSig>(paramsAfterSentinel); } /// <summary> /// Clone this /// </summary> public PropertySig Clone() { return new PropertySig(callingConvention, genParamCount, retType, parameters, paramsAfterSentinel); } } /// <summary> /// A local variables signature /// </summary> public sealed class LocalSig : CallingConventionSig { readonly IList<TypeSig> locals; /// <summary> /// All local types. This is never <c>null</c>. /// </summary> public IList<TypeSig> Locals { get { return locals; } } /// <summary> /// Default constructor /// </summary> public LocalSig() { this.callingConvention = CallingConvention.LocalSig; this.locals = new List<TypeSig>(); } /// <summary> /// Constructor /// </summary> /// <param name="callingConvention">Calling convention (must have LocalSig set)</param> /// <param name="count">Number of locals</param> internal LocalSig(CallingConvention callingConvention, uint count) { this.callingConvention = callingConvention; this.locals = new List<TypeSig>((int)count); } /// <summary> /// Constructor /// </summary> /// <param name="local1">Local type #1</param> public LocalSig(TypeSig local1) { this.callingConvention = CallingConvention.LocalSig; this.locals = new List<TypeSig> { local1 }; } /// <summary> /// Constructor /// </summary> /// <param name="local1">Local type #1</param> /// <param name="local2">Local type #2</param> public LocalSig(TypeSig local1, TypeSig local2) { this.callingConvention = CallingConvention.LocalSig; this.locals = new List<TypeSig> { local1, local2 }; } /// <summary> /// Constructor /// </summary> /// <param name="local1">Local type #1</param> /// <param name="local2">Local type #2</param> /// <param name="local3">Local type #3</param> public LocalSig(TypeSig local1, TypeSig local2, TypeSig local3) { this.callingConvention = CallingConvention.LocalSig; this.locals = new List<TypeSig> { local1, local2, local3 }; } /// <summary> /// Constructor /// </summary> /// <param name="locals">All locals</param> public LocalSig(params TypeSig[] locals) { this.callingConvention = CallingConvention.LocalSig; this.locals = new List<TypeSig>(locals); } /// <summary> /// Constructor /// </summary> /// <param name="locals">All locals</param> public LocalSig(IList<TypeSig> locals) { this.callingConvention = CallingConvention.LocalSig; this.locals = new List<TypeSig>(locals); } /// <summary> /// Constructor /// </summary> /// <param name="locals">All locals (this instance now owns it)</param> /// <param name="dummy">Dummy</param> internal LocalSig(IList<TypeSig> locals, bool dummy) { this.callingConvention = CallingConvention.LocalSig; this.locals = locals; } /// <summary> /// Clone this /// </summary> public LocalSig Clone() { return new LocalSig(locals); } } /// <summary> /// An instantiated generic method signature /// </summary> public sealed class GenericInstMethodSig : CallingConventionSig { readonly IList<TypeSig> genericArgs; /// <summary> /// Gets the generic arguments (must be instantiated types, i.e., closed types) /// </summary> public IList<TypeSig> GenericArguments { get { return genericArgs; } } /// <summary> /// Default constructor /// </summary> public GenericInstMethodSig() { this.callingConvention = CallingConvention.GenericInst; this.genericArgs = new List<TypeSig>(); } /// <summary> /// Constructor /// </summary> /// <param name="callingConvention">Calling convention (must have GenericInst set)</param> /// <param name="size">Number of generic args</param> internal GenericInstMethodSig(CallingConvention callingConvention, uint size) { this.callingConvention = callingConvention; this.genericArgs = new List<TypeSig>((int)size); } /// <summary> /// Constructor /// </summary> /// <param name="arg1">Generic arg #1</param> public GenericInstMethodSig(TypeSig arg1) { this.callingConvention = CallingConvention.GenericInst; this.genericArgs = new List<TypeSig> { arg1 }; } /// <summary> /// Constructor /// </summary> /// <param name="arg1">Generic arg #1</param> /// <param name="arg2">Generic arg #2</param> public GenericInstMethodSig(TypeSig arg1, TypeSig arg2) { this.callingConvention = CallingConvention.GenericInst; this.genericArgs = new List<TypeSig> { arg1, arg2 }; } /// <summary> /// Constructor /// </summary> /// <param name="arg1">Generic arg #1</param> /// <param name="arg2">Generic arg #2</param> /// <param name="arg3">Generic arg #3</param> public GenericInstMethodSig(TypeSig arg1, TypeSig arg2, TypeSig arg3) { this.callingConvention = CallingConvention.GenericInst; this.genericArgs = new List<TypeSig> { arg1, arg2, arg3 }; } /// <summary> /// Constructor /// </summary> /// <param name="args">Generic args</param> public GenericInstMethodSig(params TypeSig[] args) { this.callingConvention = CallingConvention.GenericInst; this.genericArgs = new List<TypeSig>(args); } /// <summary> /// Constructor /// </summary> /// <param name="args">Generic args</param> public GenericInstMethodSig(IList<TypeSig> args) { this.callingConvention = CallingConvention.GenericInst; this.genericArgs = new List<TypeSig>(args); } /// <summary> /// Clone this /// </summary> public GenericInstMethodSig Clone() { return new GenericInstMethodSig(genericArgs); } } public static partial class Extensions { /// <summary> /// Gets the field type /// </summary> /// <param name="sig">this</param> /// <returns>Field type or <c>null</c> if none</returns> public static TypeSig GetFieldType(this FieldSig sig) { return sig == null ? null : sig.Type; } /// <summary> /// Gets the return type /// </summary> /// <param name="sig">this</param> /// <returns>Return type or <c>null</c> if none</returns> public static TypeSig GetRetType(this MethodBaseSig sig) { return sig == null ? null : sig.RetType; } /// <summary> /// Gets the parameters /// </summary> /// <param name="sig">this</param> /// <returns>The parameters</returns> public static IList<TypeSig> GetParams(this MethodBaseSig sig) { return sig == null ? new List<TypeSig>() : sig.Params; } /// <summary> /// Gets the parameter count /// </summary> /// <param name="sig">this</param> /// <returns>Parameter count</returns> public static int GetParamCount(this MethodBaseSig sig) { return sig == null ? 0 : sig.Params.Count; } /// <summary> /// Gets the generic parameter count /// </summary> /// <param name="sig">this</param> /// <returns>Generic parameter count</returns> public static uint GetGenParamCount(this MethodBaseSig sig) { return sig == null ? 0 : sig.GenParamCount; } /// <summary> /// Gets the parameters after the sentinel /// </summary> /// <param name="sig">this</param> /// <returns>Parameters after sentinel or <c>null</c> if none</returns> public static IList<TypeSig> GetParamsAfterSentinel(this MethodBaseSig sig) { return sig == null ? null : sig.ParamsAfterSentinel; } /// <summary> /// Gets the locals /// </summary> /// <param name="sig">this</param> /// <returns>All locals</returns> public static IList<TypeSig> GetLocals(this LocalSig sig) { return sig == null ? new List<TypeSig>() : sig.Locals; } /// <summary> /// Gets the generic arguments /// </summary> /// <param name="sig">this</param> /// <returns>All generic arguments</returns> public static IList<TypeSig> GetGenericArguments(this GenericInstMethodSig sig) { return sig == null ? new List<TypeSig>() : sig.GenericArguments; } /// <summary> /// Gets the <see cref="CallingConventionSig.IsDefault"/> property /// </summary> /// <param name="sig">this</param> /// <returns>The type's <see cref="CallingConventionSig.IsDefault"/> property or /// <c>false</c> if input is<c>null</c></returns> public static bool GetIsDefault(this CallingConventionSig sig) { return sig == null ? false : sig.IsDefault; } } }
34.279793
161
0.686996
[ "MIT" ]
liangran10000/dnlib
src/DotNet/CallingConventionSig.cs
39,698
C#
using System; using Aop.Api.Domain; using System.Collections.Generic; using Aop.Api.Response; namespace Aop.Api.Request { /// <summary> /// AOP API: alipay.boss.prod.alcagmprod.agreement.sign /// </summary> public class AlipayBossProdAlcagmprodAgreementSignRequest : IAopRequest<AlipayBossProdAlcagmprodAgreementSignResponse> { /// <summary> /// 法务c端用户协议签约 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; private Dictionary<string, string> udfParams; //add user-defined text parameters public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.boss.prod.alcagmprod.agreement.sign"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public void PutOtherTextParam(string key, string value) { if(this.udfParams == null) { this.udfParams = new Dictionary<string, string>(); } this.udfParams.Add(key, value); } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); if(udfParams != null) { parameters.AddAll(this.udfParams); } return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
26.096774
123
0.568603
[ "Apache-2.0" ]
alipay/alipay-sdk-net
AlipaySDKNet.Standard/Request/AlipayBossProdAlcagmprodAgreementSignRequest.cs
3,254
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Tida.Canvas.Shell.Contracts.ComponentModel { /// <summary> /// 编辑器的显示类型; /// </summary> public enum EditorStyle { // // Summary: // No special user interface element is used. None = 0, /// <summary> /// A button that shows a modal dialog window with the custom editor inside is displayed. /// </summary> Modal = 1, /// <summary> /// A drop down button which content is the custom editor is displayed. /// </summary> DropDown = 2, } }
24.678571
98
0.578871
[ "MIT" ]
JanusTida/Tida.CAD
Tida.Canvas.Shell.Contracts/ComponentModel/EditorStyle.cs
709
C#
/* * OpenAPI Petstore * * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Text; using System.Threading; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Web; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using ErrorEventArgs = Newtonsoft.Json.Serialization.ErrorEventArgs; using RestSharp; using RestSharp.Deserializers; using RestSharpMethod = RestSharp.Method; using Polly; namespace Org.OpenAPITools.Client { /// <summary> /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. /// </summary> internal class CustomJsonCodec : RestSharp.Serializers.ISerializer, RestSharp.Deserializers.IDeserializer { private readonly IReadableConfiguration _configuration; private static readonly string _contentType = "application/json"; private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings { // OpenAPI generated types generally hide default constructors. ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy { OverrideSpecifiedNames = false } } }; public CustomJsonCodec(IReadableConfiguration configuration) { _configuration = configuration; } public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration) { _serializerSettings = serializerSettings; _configuration = configuration; } /// <summary> /// Serialize the object into a JSON string. /// </summary> /// <param name="obj">Object to be serialized.</param> /// <returns>A JSON string.</returns> public string Serialize(object obj) { if (obj != null && obj is Org.OpenAPITools.Model.AbstractOpenAPISchema) { // the object to be serialized is an oneOf/anyOf schema return ((Org.OpenAPITools.Model.AbstractOpenAPISchema)obj).ToJson(); } else { return JsonConvert.SerializeObject(obj, _serializerSettings); } } public T Deserialize<T>(IRestResponse response) { var result = (T)Deserialize(response, typeof(T)); return result; } /// <summary> /// Deserialize the JSON string into a proper object. /// </summary> /// <param name="response">The HTTP response.</param> /// <param name="type">Object type.</param> /// <returns>Object representation of the JSON string.</returns> internal object Deserialize(IRestResponse response, Type type) { IList<Parameter> headers = response.Headers; if (type == typeof(byte[])) // return byte array { return response.RawBytes; } // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) if (type == typeof(Stream)) { var bytes = response.RawBytes; if (headers != null) { var filePath = String.IsNullOrEmpty(_configuration.TempFolderPath) ? Path.GetTempPath() : _configuration.TempFolderPath; var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); foreach (var header in headers) { var match = regex.Match(header.ToString()); if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); File.WriteAllBytes(fileName, bytes); return new FileStream(fileName, FileMode.Open); } } } var stream = new MemoryStream(bytes); return stream; } if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object { return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); } if (type == typeof(String) || type.Name.StartsWith("System.Nullable")) // return primitive type { return Convert.ChangeType(response.Content, type); } // at this point, it must be a model (json) try { return JsonConvert.DeserializeObject(response.Content, type, _serializerSettings); } catch (Exception e) { throw new ApiException(500, e.Message); } } public string RootElement { get; set; } public string Namespace { get; set; } public string DateFormat { get; set; } public string ContentType { get { return _contentType; } set { throw new InvalidOperationException("Not allowed to set content type."); } } } /// <summary> /// Provides a default implementation of an Api client (both synchronous and asynchronous implementatios), /// encapsulating general REST accessor use cases. /// </summary> public partial class ApiClient : ISynchronousClient, IAsynchronousClient { private readonly String _baseUrl; /// <summary> /// Specifies the settings on a <see cref="JsonSerializer" /> object. /// These settings can be adjusted to accomodate custom serialization rules. /// </summary> public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings { // OpenAPI generated types generally hide default constructors. ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, ContractResolver = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy { OverrideSpecifiedNames = false } } }; /// <summary> /// Allows for extending request processing for <see cref="ApiClient"/> generated code. /// </summary> /// <param name="request">The RestSharp request object</param> partial void InterceptRequest(IRestRequest request); /// <summary> /// Allows for extending response processing for <see cref="ApiClient"/> generated code. /// </summary> /// <param name="request">The RestSharp request object</param> /// <param name="response">The RestSharp response object</param> partial void InterceptResponse(IRestRequest request, IRestResponse response); /// <summary> /// Initializes a new instance of the <see cref="ApiClient" />, defaulting to the global configurations' base url. /// </summary> public ApiClient() { _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; } /// <summary> /// Initializes a new instance of the <see cref="ApiClient" /> /// </summary> /// <param name="basePath">The target service's base path in URL format.</param> /// <exception cref="ArgumentException"></exception> public ApiClient(String basePath) { if (string.IsNullOrEmpty(basePath)) throw new ArgumentException("basePath cannot be empty"); _baseUrl = basePath; } /// <summary> /// Constructs the RestSharp version of an http method /// </summary> /// <param name="method">Swagger Client Custom HttpMethod</param> /// <returns>RestSharp's HttpMethod instance.</returns> /// <exception cref="ArgumentOutOfRangeException"></exception> private RestSharpMethod Method(HttpMethod method) { RestSharpMethod other; switch (method) { case HttpMethod.Get: other = RestSharpMethod.GET; break; case HttpMethod.Post: other = RestSharpMethod.POST; break; case HttpMethod.Put: other = RestSharpMethod.PUT; break; case HttpMethod.Delete: other = RestSharpMethod.DELETE; break; case HttpMethod.Head: other = RestSharpMethod.HEAD; break; case HttpMethod.Options: other = RestSharpMethod.OPTIONS; break; case HttpMethod.Patch: other = RestSharpMethod.PATCH; break; default: throw new ArgumentOutOfRangeException("method", method, null); } return other; } /// <summary> /// Provides all logic for constructing a new RestSharp <see cref="RestRequest"/>. /// At this point, all information for querying the service is known. Here, it is simply /// mapped into the RestSharp request. /// </summary> /// <param name="method">The http verb.</param> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>[private] A new RestRequest instance.</returns> /// <exception cref="ArgumentNullException"></exception> private RestRequest NewRequest( HttpMethod method, String path, RequestOptions options, IReadableConfiguration configuration) { if (path == null) throw new ArgumentNullException("path"); if (options == null) throw new ArgumentNullException("options"); if (configuration == null) throw new ArgumentNullException("configuration"); RestRequest request = new RestRequest(Method(method)) { Resource = path, JsonSerializer = new CustomJsonCodec(SerializerSettings, configuration) }; if (options.PathParameters != null) { foreach (var pathParam in options.PathParameters) { request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment); } } if (options.QueryParameters != null) { foreach (var queryParam in options.QueryParameters) { foreach (var value in queryParam.Value) { request.AddQueryParameter(queryParam.Key, value); } } } if (configuration.DefaultHeaders != null) { foreach (var headerParam in configuration.DefaultHeaders) { request.AddHeader(headerParam.Key, headerParam.Value); } } if (options.HeaderParameters != null) { foreach (var headerParam in options.HeaderParameters) { foreach (var value in headerParam.Value) { request.AddHeader(headerParam.Key, value); } } } if (options.FormParameters != null) { foreach (var formParam in options.FormParameters) { request.AddParameter(formParam.Key, formParam.Value); } } if (options.Data != null) { if (options.HeaderParameters != null) { var contentTypes = options.HeaderParameters["Content-Type"]; if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json"))) { request.RequestFormat = DataFormat.Json; } else { // TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default. } } else { // Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly. request.RequestFormat = DataFormat.Json; } request.AddJsonBody(options.Data); } if (options.FileParameters != null) { foreach (var fileParam in options.FileParameters) { var bytes = ClientUtils.ReadAsBytes(fileParam.Value); var fileStream = fileParam.Value as FileStream; if (fileStream != null) request.Files.Add(FileParameter.Create(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name))); else request.Files.Add(FileParameter.Create(fileParam.Key, bytes, "no_file_name_provided")); } } if (options.Cookies != null && options.Cookies.Count > 0) { foreach (var cookie in options.Cookies) { request.AddCookie(cookie.Name, cookie.Value); } } return request; } private ApiResponse<T> ToApiResponse<T>(IRestResponse<T> response) { T result = response.Data; string rawContent = response.Content; var transformed = new ApiResponse<T>(response.StatusCode, new Multimap<string, string>(), result, rawContent) { ErrorText = response.ErrorMessage, Cookies = new List<Cookie>() }; if (response.Headers != null) { foreach (var responseHeader in response.Headers) { transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); } } if (response.Cookies != null) { foreach (var responseCookies in response.Cookies) { transformed.Cookies.Add( new Cookie( responseCookies.Name, responseCookies.Value, responseCookies.Path, responseCookies.Domain) ); } } return transformed; } private ApiResponse<T> Exec<T>(RestRequest req, IReadableConfiguration configuration) { RestClient client = new RestClient(_baseUrl); client.ClearHandlers(); var existingDeserializer = req.JsonSerializer as IDeserializer; if (existingDeserializer != null) { client.AddHandler("application/json", () => existingDeserializer); client.AddHandler("text/json", () => existingDeserializer); client.AddHandler("text/x-json", () => existingDeserializer); client.AddHandler("text/javascript", () => existingDeserializer); client.AddHandler("*+json", () => existingDeserializer); } else { var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); client.AddHandler("application/json", () => customDeserializer); client.AddHandler("text/json", () => customDeserializer); client.AddHandler("text/x-json", () => customDeserializer); client.AddHandler("text/javascript", () => customDeserializer); client.AddHandler("*+json", () => customDeserializer); } var xmlDeserializer = new XmlDeserializer(); client.AddHandler("application/xml", () => xmlDeserializer); client.AddHandler("text/xml", () => xmlDeserializer); client.AddHandler("*+xml", () => xmlDeserializer); client.AddHandler("*", () => xmlDeserializer); client.Timeout = configuration.Timeout; if (configuration.Proxy != null) { client.Proxy = configuration.Proxy; } if (configuration.UserAgent != null) { client.UserAgent = configuration.UserAgent; } if (configuration.ClientCertificates != null) { client.ClientCertificates = configuration.ClientCertificates; } InterceptRequest(req); IRestResponse<T> response; if (RetryConfiguration.RetryPolicy != null) { var policy = RetryConfiguration.RetryPolicy; var policyResult = policy.ExecuteAndCapture(() => client.Execute(req)); response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize<T>(policyResult.Result) : new RestResponse<T> { Request = req, ErrorException = policyResult.FinalException }; } else { response = client.Execute<T>(req); } // if the response type is oneOf/anyOf, call FromJSON to deserialize the data if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) { response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); } else if (typeof(T).Name == "Stream") // for binary response { response.Data = (T)(object)new MemoryStream(response.RawBytes); } InterceptResponse(req, response); var result = ToApiResponse(response); if (response.ErrorMessage != null) { result.ErrorText = response.ErrorMessage; } if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List<Cookie>(); foreach (var restResponseCookie in response.Cookies) { var cookie = new Cookie( restResponseCookie.Name, restResponseCookie.Value, restResponseCookie.Path, restResponseCookie.Domain ) { Comment = restResponseCookie.Comment, CommentUri = restResponseCookie.CommentUri, Discard = restResponseCookie.Discard, Expired = restResponseCookie.Expired, Expires = restResponseCookie.Expires, HttpOnly = restResponseCookie.HttpOnly, Port = restResponseCookie.Port, Secure = restResponseCookie.Secure, Version = restResponseCookie.Version }; result.Cookies.Add(cookie); } } return result; } private async Task<ApiResponse<T>> ExecAsync<T>(RestRequest req, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { RestClient client = new RestClient(_baseUrl); client.ClearHandlers(); var existingDeserializer = req.JsonSerializer as IDeserializer; if (existingDeserializer != null) { client.AddHandler("application/json", () => existingDeserializer); client.AddHandler("text/json", () => existingDeserializer); client.AddHandler("text/x-json", () => existingDeserializer); client.AddHandler("text/javascript", () => existingDeserializer); client.AddHandler("*+json", () => existingDeserializer); } else { var customDeserializer = new CustomJsonCodec(SerializerSettings, configuration); client.AddHandler("application/json", () => customDeserializer); client.AddHandler("text/json", () => customDeserializer); client.AddHandler("text/x-json", () => customDeserializer); client.AddHandler("text/javascript", () => customDeserializer); client.AddHandler("*+json", () => customDeserializer); } var xmlDeserializer = new XmlDeserializer(); client.AddHandler("application/xml", () => xmlDeserializer); client.AddHandler("text/xml", () => xmlDeserializer); client.AddHandler("*+xml", () => xmlDeserializer); client.AddHandler("*", () => xmlDeserializer); client.Timeout = configuration.Timeout; if (configuration.Proxy != null) { client.Proxy = configuration.Proxy; } if (configuration.UserAgent != null) { client.UserAgent = configuration.UserAgent; } if (configuration.ClientCertificates != null) { client.ClientCertificates = configuration.ClientCertificates; } InterceptRequest(req); IRestResponse<T> response; if (RetryConfiguration.AsyncRetryPolicy != null) { var policy = RetryConfiguration.AsyncRetryPolicy; var policyResult = await policy.ExecuteAndCaptureAsync(() => client.ExecuteAsync(req, cancellationToken)).ConfigureAwait(false); response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize<T>(policyResult.Result) : new RestResponse<T> { Request = req, ErrorException = policyResult.FinalException }; } else { response = await client.ExecuteAsync<T>(req, cancellationToken).ConfigureAwait(false); } // if the response type is oneOf/anyOf, call FromJSON to deserialize the data if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) { response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); } else if (typeof(T).Name == "Stream") // for binary response { response.Data = (T)(object)new MemoryStream(response.RawBytes); } InterceptResponse(req, response); var result = ToApiResponse(response); if (response.ErrorMessage != null) { result.ErrorText = response.ErrorMessage; } if (response.Cookies != null && response.Cookies.Count > 0) { if (result.Cookies == null) result.Cookies = new List<Cookie>(); foreach (var restResponseCookie in response.Cookies) { var cookie = new Cookie( restResponseCookie.Name, restResponseCookie.Value, restResponseCookie.Path, restResponseCookie.Domain ) { Comment = restResponseCookie.Comment, CommentUri = restResponseCookie.CommentUri, Discard = restResponseCookie.Discard, Expired = restResponseCookie.Expired, Expires = restResponseCookie.Expires, HttpOnly = restResponseCookie.HttpOnly, Port = restResponseCookie.Port, Secure = restResponseCookie.Secure, Version = restResponseCookie.Version }; result.Cookies.Add(cookie); } } return result; } #region IAsynchronousClient /// <summary> /// Make a HTTP GET request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> GetAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Get, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP POST request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> PostAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Post, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP PUT request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> PutAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Put, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP DELETE request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> DeleteAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Delete, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP HEAD request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> HeadAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Head, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP OPTION request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> OptionsAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Options, path, options, config), config, cancellationToken); } /// <summary> /// Make a HTTP PATCH request (async). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <param name="cancellationToken">Token that enables callers to cancel the request.</param> /// <returns>A Task containing ApiResponse</returns> public Task<ApiResponse<T>> PatchAsync<T>(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { var config = configuration ?? GlobalConfiguration.Instance; return ExecAsync<T>(NewRequest(HttpMethod.Patch, path, options, config), config, cancellationToken); } #endregion IAsynchronousClient #region ISynchronousClient /// <summary> /// Make a HTTP GET request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Get<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Get, path, options, config), config); } /// <summary> /// Make a HTTP POST request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Post<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Post, path, options, config), config); } /// <summary> /// Make a HTTP PUT request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Put<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Put, path, options, config), config); } /// <summary> /// Make a HTTP DELETE request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Delete<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Delete, path, options, config), config); } /// <summary> /// Make a HTTP HEAD request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Head<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Head, path, options, config), config); } /// <summary> /// Make a HTTP OPTION request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Options<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Options, path, options, config), config); } /// <summary> /// Make a HTTP PATCH request (synchronous). /// </summary> /// <param name="path">The target path (or resource).</param> /// <param name="options">The additional request options.</param> /// <param name="configuration">A per-request configuration object. It is assumed that any merge with /// GlobalConfiguration has been done before calling this method.</param> /// <returns>A Task containing ApiResponse</returns> public ApiResponse<T> Patch<T>(string path, RequestOptions options, IReadableConfiguration configuration = null) { var config = configuration ?? GlobalConfiguration.Instance; return Exec<T>(NewRequest(HttpMethod.Patch, path, options, config), config); } #endregion ISynchronousClient } }
45.506478
233
0.582969
[ "Apache-2.0" ]
AISS-2021-L1-G02/openapi-generator
samples/client/petstore/csharp-netcore/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiClient.cs
38,635
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; namespace MyKindergarten.Controls { public class IntellisenseTextBox : TextBox { // Templateparts Popup PART_IntellisensePopup; ListBox PART_IntellisenseListBox; // Using a DependencyProperty as the backing store for ContentAssistSource. This enables animation, styling, binding, etc... public static readonly DependencyProperty ContentAssistSourceProperty = DependencyProperty.Register("ContentAssistSource", typeof(IEnumerable<string>), typeof(IntellisenseTextBox), new UIPropertyMetadata(new List<string>(), OnContentAssistSourceChanged)); public IEnumerable<string> ContentAssistSource { get { return (IEnumerable<string>)GetValue(ContentAssistSourceProperty); } set { SetValue(ContentAssistSourceProperty, value); } } public IEnumerable<string> ConentAssistSource_ResultView { get { return (IEnumerable<string>)GetValue(ConentAssistSource_ResultViewProperty); } set { SetValue(ConentAssistSource_ResultViewProperty, value); } } // Using a DependencyProperty as the backing store for ConentAssistSource_ResultView. This enables animation, styling, binding, etc... public static readonly DependencyProperty ConentAssistSource_ResultViewProperty = DependencyProperty.Register("ConentAssistSource_ResultView", typeof(IEnumerable<string>), typeof(IntellisenseTextBox), new PropertyMetadata(default(IEnumerable<string>))); //public ICollectionView ContentAssistSource_CollectionView { get; private set; } private static void OnContentAssistSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is IntellisenseTextBox intellisenseTextBox) { intellisenseTextBox.SetValue(ConentAssistSource_ResultViewProperty, intellisenseTextBox.ContentAssistSource.Where(x => x.Contains(intellisenseTextBox.sbLastWords.ToString(), StringComparison.OrdinalIgnoreCase))); //intellisenseTextBox.ContentAssistSource_CollectionView = CollectionViewSource.GetDefaultView(e.NewValue ?? new List<string>()) ; //intellisenseTextBox.ContentAssistSource_CollectionView.Filter = o => { return ((string)o).Contains(intellisenseTextBox.sbLastWords.ToString(), StringComparison.OrdinalIgnoreCase); }; } } // Using a DependencyProperty as the backing store for SuffixAfterInsert. This enables animation, styling, binding, etc... public static readonly DependencyProperty SuffixAfterInsertProperty = DependencyProperty.Register("SuffixAfterInsert", typeof(string), typeof(IntellisenseTextBox), new PropertyMetadata(null)); public string SuffixAfterInsert { get { return (string)GetValue(SuffixAfterInsertProperty); } set { SetValue(SuffixAfterInsertProperty, value); } } public override void OnApplyTemplate() { base.OnApplyTemplate(); this.PART_IntellisensePopup = (Popup)GetTemplateChild(nameof(PART_IntellisensePopup)); this.PART_IntellisensePopup.Opened += PART_IntellisensePopup_Opened; this.PART_IntellisenseListBox = (ListBox)GetTemplateChild(nameof(PART_IntellisenseListBox)); this.PART_IntellisenseListBox.MouseDoubleClick += PART_IntellisenseListBox_MouseDoubleClick; this.PART_IntellisenseListBox.PreviewKeyDown += PART_IntellisenseListBox_PreviewKeyDown; } private void PART_IntellisensePopup_Opened(object sender, EventArgs e) { var pos = GetRectFromCharacterIndex(this.CaretIndex); PART_IntellisensePopup.Placement = PlacementMode.RelativePoint; PART_IntellisensePopup.PlacementTarget = this; PART_IntellisensePopup.HorizontalOffset = pos.Left; PART_IntellisensePopup.VerticalOffset = pos.Top + pos.Height; } private void PART_IntellisenseListBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e) { //if Enter\Tab\Space key is pressed, insert current selected item to richtextbox if (e.Key == Key.Enter || e.Key == Key.Tab || e.Key == Key.Space) { InsertAssistWord(); e.Handled = true; } else if (e.Key == Key.Back) { //Baskspace key is pressed, set focus to richtext box if (sbLastWords.Length >= 1) { sbLastWords.Remove(sbLastWords.Length - 1, 1); } this.Focus(); } } private void PART_IntellisenseListBox_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e) { InsertAssistWord(); } #region Content Assist private bool IsAssistKeyPressed = false; private StringBuilder sbLastWords = new System.Text.StringBuilder(); private bool InsertAssistWord() { bool isInserted = false; if (PART_IntellisenseListBox.SelectedIndex != -1) { string selectedString = (string)PART_IntellisenseListBox.SelectedItem; selectedString += SuffixAfterInsert; this.InsertText(selectedString); isInserted = true; } PART_IntellisensePopup.IsOpen = false; sbLastWords.Clear(); IsAssistKeyPressed = false; return isInserted; } public void InsertText(string text) { Focus(); var _newCaretIndex = CaretIndex - sbLastWords.Length; SetValue(TextProperty, Text.Remove(_newCaretIndex, sbLastWords.Length)); SetValue(TextProperty, Text.Insert(_newCaretIndex, text)); CaretIndex = _newCaretIndex + text.Length; sbLastWords.Clear(); PART_IntellisensePopup.IsOpen = false; Update_AssistSourceResultView(); } protected override void OnPreviewKeyDown(KeyEventArgs e) { if (!PART_IntellisensePopup.IsOpen) { base.OnPreviewKeyDown(e); return; } Update_AssistSourceResultView(); switch (e.Key) { case Key.Back: if (sbLastWords.Length > 0) { sbLastWords.Remove(sbLastWords.Length - 1, 1); Update_AssistSourceResultView(); } else { IsAssistKeyPressed = false; sbLastWords.Clear(); PART_IntellisensePopup.IsOpen = false; } break; case Key.Enter: case Key.Space: case Key.Tab: if (InsertAssistWord()) { e.Handled = true; } break; case Key.Down: if (PART_IntellisenseListBox.SelectedIndex < PART_IntellisenseListBox.Items.Count - 1) PART_IntellisenseListBox.SelectedIndex += 1; break; case Key.Up: if (PART_IntellisenseListBox.SelectedIndex > -1) PART_IntellisenseListBox.SelectedIndex -= 1; break; case Key.Escape: sbLastWords.Clear(); PART_IntellisensePopup.IsOpen = false; break; default: break; } base.OnPreviewKeyDown(e); } protected override void OnTextInput(System.Windows.Input.TextCompositionEventArgs e) { base.OnTextInput(e); if (PART_IntellisensePopup.IsOpen == false && e.Text.Length == 1) { PART_IntellisensePopup.IsOpen = true; IsAssistKeyPressed = true; Update_AssistSourceResultView(); } if (IsAssistKeyPressed) { sbLastWords.Append(e.Text); Update_AssistSourceResultView(); } } protected override void OnGotKeyboardFocus(KeyboardFocusChangedEventArgs e) { PART_IntellisensePopup.IsOpen = true; base.OnGotKeyboardFocus(e); } protected override void OnLostFocus(RoutedEventArgs e) { PART_IntellisensePopup.IsOpen = false; Update_AssistSourceResultView(); base.OnLostFocus(e); } void Update_AssistSourceResultView() { SetValue(ConentAssistSource_ResultViewProperty, ContentAssistSource.Where(x => x.Contains(sbLastWords.ToString(), StringComparison.OrdinalIgnoreCase)) .OrderBy(x => x)); } #endregion } }
37.638889
201
0.606642
[ "MIT" ]
timunie/MyKindergarten
src/MyKindergarten/MyKindergarten/Controls/IntellisenseTextBox.cs
9,487
C#
using Variables; using UnityEngine; namespace Variables.Types { [VariableMenu(menuName = "Default/Quaternion", order = 103)] public class QuaternionVariable : Variable<Quaternion> { } }
20.777778
60
0.775401
[ "MIT" ]
j-reason/ScriptableVariables
Assets/ScriptableVariables/Runtime/Variable Types/Defaults/QuaternionVariable.cs
187
C#
using System; using System.Collections.Generic; using Exceptionless.Core.Pipeline; using Exceptionless.Core.Extensions; using Exceptionless.Core.Models; namespace Exceptionless.Core.Plugins.Formatting { [Priority(99)] public sealed class DefaultFormattingPlugin : FormattingPluginBase { public DefaultFormattingPlugin(AppOptions options) : base(options) { } public override string GetStackTitle(PersistentEvent ev) { if (String.IsNullOrWhiteSpace(ev.Message) && ev.IsError()) return "Unknown Error"; return ev.Message ?? ev.Source ?? $"{ev.Type} Event".TrimStart(); } public override SummaryData GetStackSummaryData(Stack stack) { var data = new Dictionary<string, object> { { "Type", stack.Type } }; if (stack.SignatureInfo.TryGetValue("Source", out string value)) data.Add("Source", value); return new SummaryData { TemplateKey = "stack-summary", Data = data }; } public override SummaryData GetEventSummaryData(PersistentEvent ev) { var data = new Dictionary<string, object> { { "Message", GetStackTitle(ev) }, { "Source", ev.Source }, { "Type", ev.Type } }; AddUserIdentitySummaryData(data, ev.GetUserIdentity()); return new SummaryData { TemplateKey = "event-summary", Data = data }; } public override MailMessageData GetEventNotificationMailMessageData(PersistentEvent ev, bool isCritical, bool isNew, bool isRegression) { string messageOrSource = !String.IsNullOrEmpty(ev.Message) ? ev.Message : ev.Source; if (String.IsNullOrEmpty(messageOrSource)) return null; string notificationType = "Occurrence event"; if (isNew) notificationType = "New event"; else if (isRegression) notificationType = "Regression event"; if (isCritical) notificationType = String.Concat("Critical ", notificationType.ToLowerInvariant()); string subject = String.Concat(notificationType, ": ", messageOrSource).Truncate(120); var data = new Dictionary<string, object>(); if (!String.IsNullOrEmpty(ev.Message)) data.Add("Message", ev.Message.Truncate(60)); if (!String.IsNullOrEmpty(ev.Source)) data.Add("Source", ev.Source.Truncate(60)); var requestInfo = ev.GetRequestInfo(); if (requestInfo != null) data.Add("Url", requestInfo.GetFullPath(true, true, true)); return new MailMessageData { Subject = subject, Data = data }; } public override SlackMessage GetSlackEventNotification(PersistentEvent ev, Project project, bool isCritical, bool isNew, bool isRegression) { string messageOrSource = !String.IsNullOrEmpty(ev.Message) ? ev.Message : ev.Source; if (String.IsNullOrEmpty(messageOrSource)) return null; string notificationType = "Occurrence event"; if (isNew) notificationType = "New event"; else if (isRegression) notificationType = "Regression event"; if (isCritical) notificationType = String.Concat("Critical ", notificationType.ToLowerInvariant()); var attachment = new SlackMessage.SlackAttachment(ev); if (!String.IsNullOrEmpty(ev.Message)) attachment.Fields.Add(new SlackMessage.SlackAttachmentFields { Title = "Message", Value = ev.Message.Truncate(60) }); if (!String.IsNullOrEmpty(ev.Source)) attachment.Fields.Add(new SlackMessage.SlackAttachmentFields { Title = "Source", Value = ev.Source.Truncate(60) }); AddDefaultSlackFields(ev, attachment.Fields); string subject = $"[{project.Name}] A {notificationType}: *{GetSlackEventUrl(ev.Id, messageOrSource.Truncate(120))}*"; return new SlackMessage(subject) { Attachments = new List<SlackMessage.SlackAttachment> { attachment } }; } } }
43.628866
149
0.619565
[ "Apache-2.0" ]
aTiKhan/Exceptionless
src/Exceptionless.Core/Plugins/Formatting/Default/99_DefaultFormattingPlugin.cs
4,234
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using ACT.SpecialSpellTimer.Image; using ACT.SpecialSpellTimer.resources; using FFXIV.Framework.Extensions; using FFXIV.Framework.Globalization; namespace ACT.SpecialSpellTimer.Config.Views { /// <summary> /// TagView.xaml の相互作用ロジック /// </summary> public partial class IconBrowserView : Window, ILocalizable { public IconBrowserView() { this.InitializeComponent(); this.SetLocale(Settings.Default.UILocale); this.LoadConfigViewResources(); // ウィンドウのスタート位置を決める this.WindowStartupLocation = WindowStartupLocation.CenterScreen; this.MouseLeftButtonDown += (x, y) => this.DragMove(); this.PreviewKeyUp += (x, y) => { if (y.Key == Key.Escape) { this.DialogResult = false; this.Close(); } }; this.CloseButton.Click += (x, y) => { this.DialogResult = false; this.Close(); }; this.ClearButton.Click += (x, y) => { this.SelectedIcon = null; this.SelectedIconName = string.Empty; this.DialogResult = true; this.Close(); }; this.Loaded += this.IconBrowserView_Loaded; } public void SetLocale(Locales locale) => this.ReloadLocaleDictionary(locale); public IconController.IconFile SelectedIcon { get; set; } = null; public string SelectedIconName { get; set; } = string.Empty; public IconController.IconFile[] Icons => IconController.Instance.EnumerateIcon(); public IReadOnlyList<IGrouping<string, IconController.IconFile>> IconGroups => ( from x in this.Icons where !string.IsNullOrEmpty(x.DirectoryName) group x by x.DirectoryName).ToList(); private async void IconBrowserView_Loaded( object sender, RoutedEventArgs e) { var selectedGroup = default(IGrouping<string, IconController.IconFile>); await Task.Run(() => { if (!string.IsNullOrEmpty(this.SelectedIconName)) { this.SelectedIcon = this.Icons.FirstOrDefault(x => x.Name == this.SelectedIconName || x.FullPath.ContainsIgnoreCase(this.SelectedIconName)); } if (this.SelectedIcon != null) { selectedGroup = ( from x in this.IconGroups where x.Any(y => y == this.SelectedIcon) select x).FirstOrDefault(); } }); if (this.SelectedIcon == null || selectedGroup == null) { this.DirectoryListView.SelectedIndex = 0; return; } this.DirectoryListView.SelectedValue = selectedGroup?.Key; this.IconsListView.SelectedItem = this.SelectedIcon; this.DirectoryListView.ScrollIntoView(this.DirectoryListView.SelectedItem); this.IconsListView.ScrollIntoView(this.SelectedIcon); this.IconsListView.Focus(); } private void ListViewItem_PreviewMouseLeftButtonUp( object sender, MouseButtonEventArgs e) { var item = sender as ListViewItem; if (item != null && item.IsSelected) { this.SelectItem(item); } } private void ListViewItem_PreviewKeyUp( object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { var item = sender as ListViewItem; if (item != null && item.IsSelected) { this.SelectItem(item); } } } private void SelectItem( ListViewItem item) { var icon = item.DataContext as IconController.IconFile; if (icon != null) { this.SelectedIcon = icon; this.SelectedIconName = icon.Name; this.DialogResult = true; this.Close(); } } } }
30.077419
90
0.515444
[ "BSD-3-Clause" ]
MasteRyuuuu/ACT.Hojoring
source/ACT.SpecialSpellTimer/ACT.SpecialSpellTimer.Core/Config/Views/IconBrowserView.xaml.cs
4,712
C#
using System.Runtime.Serialization; namespace OneAll.Users { /// <summary>A standard OneAll contacts result data.</summary> [DataContract()] public class ContactsResult : BaseObject { #region Member Variables /// <summary>The action.</summary> private string _action; /// <summary>The results.</summary> [DataMember(Name = "results", IsRequired = false, EmitDefaultValue = false)] private BaseCollection<ContactsResultSet> _results = new BaseCollection<ContactsResultSet>(); #endregion Member Variables #region Properties #region Action /// <summary>The action.</summary> [DataMember(Name = "action", IsRequired = false, EmitDefaultValue = false)] public string Action { get { return _action; } set { _action = value; OnPropertyChanged("Action"); } } #endregion Action #region Results /// <summary>The results.</summary> public BaseCollection<ContactsResultSet> Results { get { return _results; } } #endregion Results #endregion Properties } }
25.02381
96
0.686013
[ "MIT" ]
GioCirque/OneAll
Source/Users/ContactsResult.cs
1,053
C#
//#define AluRs using ChocolArm64.State; using NUnit.Framework; namespace Ryujinx.Tests.Cpu { using Tester; using Tester.Types; [Category("AluRs"), Ignore("Tested: second half of 2018.")] public sealed class CpuTestAluRs : CpuTest { #if AluRs [SetUp] public void SetupTester() { AArch64.TakeReset(false); } [Test, Description("ADC <Xd>, <Xn>, <Xm>")] public void Adc_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(4)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(4)] ulong Xm, [Values] bool CarryIn) { uint Opcode = 0x9A000000; // ADC X0, X0, X0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31, Carry: CarryIn); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Shared.PSTATE.C = CarryIn; Base.Adc(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("ADC <Wd>, <Wn>, <Wm>")] public void Adc_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(4)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(4)] uint Wm, [Values] bool CarryIn) { uint Opcode = 0x1A000000; // ADC W0, W0, W0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31, Carry: CarryIn); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Shared.PSTATE.C = CarryIn; Base.Adc(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("ADCS <Xd>, <Xn>, <Xm>")] public void Adcs_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(4)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(4)] ulong Xm, [Values] bool CarryIn) { uint Opcode = 0xBA000000; // ADCS X0, X0, X0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Bits Op = new Bits(Opcode); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31, Carry: CarryIn); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Shared.PSTATE.C = CarryIn; Base.Adcs(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); if (Rd != 31) { Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } Assert.Multiple(() => { Assert.That(ThreadState.Negative, Is.EqualTo(Shared.PSTATE.N)); Assert.That(ThreadState.Zero, Is.EqualTo(Shared.PSTATE.Z)); Assert.That(ThreadState.Carry, Is.EqualTo(Shared.PSTATE.C)); Assert.That(ThreadState.Overflow, Is.EqualTo(Shared.PSTATE.V)); }); CompareAgainstUnicorn(); } [Test, Description("ADCS <Wd>, <Wn>, <Wm>")] public void Adcs_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(4)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(4)] uint Wm, [Values] bool CarryIn) { uint Opcode = 0x3A000000; // ADCS W0, W0, W0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Bits Op = new Bits(Opcode); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31, Carry: CarryIn); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Shared.PSTATE.C = CarryIn; Base.Adcs(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); if (Rd != 31) { Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } Assert.Multiple(() => { Assert.That(ThreadState.Negative, Is.EqualTo(Shared.PSTATE.N)); Assert.That(ThreadState.Zero, Is.EqualTo(Shared.PSTATE.Z)); Assert.That(ThreadState.Carry, Is.EqualTo(Shared.PSTATE.C)); Assert.That(ThreadState.Overflow, Is.EqualTo(Shared.PSTATE.V)); }); CompareAgainstUnicorn(); } [Test, Description("ADD <Xd>, <Xn>, <Xm>{, <shift> #<amount>}")] public void Add_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xm, [Values(0b00u, 0b01u, 0b10u)] uint shift, // <LSL, LSR, ASR> [Values(0u, 31u, 32u, 63u)] [Random(0u, 63u, 1)] uint amount) { uint Opcode = 0x8B000000; // ADD X0, X0, X0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Add_Rs(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("ADD <Wd>, <Wn>, <Wm>{, <shift> #<amount>}")] public void Add_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wm, [Values(0b00u, 0b01u, 0b10u)] uint shift, // <LSL, LSR, ASR> [Values(0u, 15u, 16u, 31u)] [Random(0u, 31u, 1)] uint amount) { uint Opcode = 0x0B000000; // ADD W0, W0, W0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Add_Rs(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); CompareAgainstUnicorn(); } } [Test, Description("ADDS <Xd>, <Xn>, <Xm>{, <shift> #<amount>}")] public void Adds_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xm, [Values(0b00u, 0b01u, 0b10u)] uint shift, // <LSL, LSR, ASR> [Values(0u, 31u, 32u, 63u)] [Random(0u, 63u, 1)] uint amount) { uint Opcode = 0xAB000000; // ADDS X0, X0, X0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); Bits Op = new Bits(Opcode); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Adds_Rs(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); if (Rd != 31) { Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } Assert.Multiple(() => { Assert.That(ThreadState.Negative, Is.EqualTo(Shared.PSTATE.N)); Assert.That(ThreadState.Zero, Is.EqualTo(Shared.PSTATE.Z)); Assert.That(ThreadState.Carry, Is.EqualTo(Shared.PSTATE.C)); Assert.That(ThreadState.Overflow, Is.EqualTo(Shared.PSTATE.V)); }); CompareAgainstUnicorn(); } [Test, Description("ADDS <Wd>, <Wn>, <Wm>{, <shift> #<amount>}")] public void Adds_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wm, [Values(0b00u, 0b01u, 0b10u)] uint shift, // <LSL, LSR, ASR> [Values(0u, 15u, 16u, 31u)] [Random(0u, 31u, 1)] uint amount) { uint Opcode = 0x2B000000; // ADDS W0, W0, W0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); Bits Op = new Bits(Opcode); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Adds_Rs(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); if (Rd != 31) { Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } Assert.Multiple(() => { Assert.That(ThreadState.Negative, Is.EqualTo(Shared.PSTATE.N)); Assert.That(ThreadState.Zero, Is.EqualTo(Shared.PSTATE.Z)); Assert.That(ThreadState.Carry, Is.EqualTo(Shared.PSTATE.C)); Assert.That(ThreadState.Overflow, Is.EqualTo(Shared.PSTATE.V)); }); CompareAgainstUnicorn(); } [Test, Description("AND <Xd>, <Xn>, <Xm>{, <shift> #<amount>}")] public void And_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xm, [Values(0b00u, 0b01u, 0b10u, 0b11u)] uint shift, // <LSL, LSR, ASR, ROR> [Values(0u, 31u, 32u, 63u)] [Random(0u, 63u, 1)] uint amount) { uint Opcode = 0x8A000000; // AND X0, X0, X0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.And_Rs(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("AND <Wd>, <Wn>, <Wm>{, <shift> #<amount>}")] public void And_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wm, [Values(0b00u, 0b01u, 0b10u, 0b11u)] uint shift, // <LSL, LSR, ASR, ROR> [Values(0u, 15u, 16u, 31u)] [Random(0u, 31u, 1)] uint amount) { uint Opcode = 0x0A000000; // AND W0, W0, W0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.And_Rs(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("ANDS <Xd>, <Xn>, <Xm>{, <shift> #<amount>}")] public void Ands_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xm, [Values(0b00u, 0b01u, 0b10u, 0b11u)] uint shift, // <LSL, LSR, ASR, ROR> [Values(0u, 31u, 32u, 63u)] [Random(0u, 63u, 1)] uint amount) { uint Opcode = 0xEA000000; // ANDS X0, X0, X0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); Bits Op = new Bits(Opcode); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Ands_Rs(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); if (Rd != 31) { Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } Assert.Multiple(() => { Assert.That(ThreadState.Negative, Is.EqualTo(Shared.PSTATE.N)); Assert.That(ThreadState.Zero, Is.EqualTo(Shared.PSTATE.Z)); Assert.That(ThreadState.Carry, Is.EqualTo(Shared.PSTATE.C)); Assert.That(ThreadState.Overflow, Is.EqualTo(Shared.PSTATE.V)); }); CompareAgainstUnicorn(); } [Test, Description("ANDS <Wd>, <Wn>, <Wm>{, <shift> #<amount>}")] public void Ands_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wm, [Values(0b00u, 0b01u, 0b10u, 0b11u)] uint shift, // <LSL, LSR, ASR, ROR> [Values(0u, 15u, 16u, 31u)] [Random(0u, 31u, 1)] uint amount) { uint Opcode = 0x6A000000; // ANDS W0, W0, W0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); Bits Op = new Bits(Opcode); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Ands_Rs(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); if (Rd != 31) { Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } Assert.Multiple(() => { Assert.That(ThreadState.Negative, Is.EqualTo(Shared.PSTATE.N)); Assert.That(ThreadState.Zero, Is.EqualTo(Shared.PSTATE.Z)); Assert.That(ThreadState.Carry, Is.EqualTo(Shared.PSTATE.C)); Assert.That(ThreadState.Overflow, Is.EqualTo(Shared.PSTATE.V)); }); CompareAgainstUnicorn(); } [Test, Description("ASRV <Xd>, <Xn>, <Xm>")] public void Asrv_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(8)] ulong Xn, [Values(0ul, 31ul, 32ul, 63ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(5)] ulong Xm) { uint Opcode = 0x9AC02800; // ASRV X0, X0, X0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Asrv(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("ASRV <Wd>, <Wn>, <Wm>")] public void Asrv_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(8)] uint Wn, [Values(0u, 15u, 16u, 31u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(5)] uint Wm) { uint Opcode = 0x1AC02800; // ASRV W0, W0, W0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Asrv(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("BIC <Xd>, <Xn>, <Xm>{, <shift> #<amount>}")] public void Bic_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xm, [Values(0b00u, 0b01u, 0b10u, 0b11u)] uint shift, // <LSL, LSR, ASR, ROR> [Values(0u, 31u, 32u, 63u)] [Random(0u, 63u, 1)] uint amount) { uint Opcode = 0x8A200000; // BIC X0, X0, X0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Bic(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("BIC <Wd>, <Wn>, <Wm>{, <shift> #<amount>}")] public void Bic_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wm, [Values(0b00u, 0b01u, 0b10u, 0b11u)] uint shift, // <LSL, LSR, ASR, ROR> [Values(0u, 15u, 16u, 31u)] [Random(0u, 31u, 1)] uint amount) { uint Opcode = 0x0A200000; // BIC W0, W0, W0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Bic(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("BICS <Xd>, <Xn>, <Xm>{, <shift> #<amount>}")] public void Bics_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xm, [Values(0b00u, 0b01u, 0b10u, 0b11u)] uint shift, // <LSL, LSR, ASR, ROR> [Values(0u, 31u, 32u, 63u)] [Random(0u, 63u, 1)] uint amount) { uint Opcode = 0xEA200000; // BICS X0, X0, X0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); Bits Op = new Bits(Opcode); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Bics(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); if (Rd != 31) { Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } Assert.Multiple(() => { Assert.That(ThreadState.Negative, Is.EqualTo(Shared.PSTATE.N)); Assert.That(ThreadState.Zero, Is.EqualTo(Shared.PSTATE.Z)); Assert.That(ThreadState.Carry, Is.EqualTo(Shared.PSTATE.C)); Assert.That(ThreadState.Overflow, Is.EqualTo(Shared.PSTATE.V)); }); CompareAgainstUnicorn(); } [Test, Description("BICS <Wd>, <Wn>, <Wm>{, <shift> #<amount>}")] public void Bics_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wm, [Values(0b00u, 0b01u, 0b10u, 0b11u)] uint shift, // <LSL, LSR, ASR, ROR> [Values(0u, 15u, 16u, 31u)] [Random(0u, 31u, 1)] uint amount) { uint Opcode = 0x6A200000; // BICS W0, W0, W0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); Bits Op = new Bits(Opcode); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Bics(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); if (Rd != 31) { Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } Assert.Multiple(() => { Assert.That(ThreadState.Negative, Is.EqualTo(Shared.PSTATE.N)); Assert.That(ThreadState.Zero, Is.EqualTo(Shared.PSTATE.Z)); Assert.That(ThreadState.Carry, Is.EqualTo(Shared.PSTATE.C)); Assert.That(ThreadState.Overflow, Is.EqualTo(Shared.PSTATE.V)); }); CompareAgainstUnicorn(); } [Test, Description("CRC32X <Wd>, <Wn>, <Xm>")] public void Crc32x([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0xFFFFFFFFu)] [Random(2)] uint Wn, [Values((ulong)0x00_00_00_00_00_00_00_00, (ulong)0x7F_FF_FF_FF_FF_FF_FF_FF, (ulong)0x80_00_00_00_00_00_00_00, (ulong)0xFF_FF_FF_FF_FF_FF_FF_FF)] [Random(64)] ulong Xm) { uint Opcode = 0x9AC04C00; // CRC32X W0, W0, X0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Xm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Crc32(Op[31], Op[20, 16], Op[11, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("CRC32W <Wd>, <Wn>, <Wm>")] public void Crc32w([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0xFFFFFFFFu)] [Random(2)] uint Wn, [Values((uint)0x00_00_00_00, (uint)0x7F_FF_FF_FF, (uint)0x80_00_00_00, (uint)0xFF_FF_FF_FF)] [Random(64)] uint Wm) { uint Opcode = 0x1AC04800; // CRC32W W0, W0, W0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Crc32(Op[31], Op[20, 16], Op[11, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("CRC32H <Wd>, <Wn>, <Wm>")] public void Crc32h([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0xFFFFFFFFu)] [Random(2)] uint Wn, [Values((ushort)0x00_00, (ushort)0x7F_FF, (ushort)0x80_00, (ushort)0xFF_FF)] [Random(64)] ushort Wm) { uint Opcode = 0x1AC04400; // CRC32H W0, W0, W0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Crc32(Op[31], Op[20, 16], Op[11, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("CRC32B <Wd>, <Wn>, <Wm>")] public void Crc32b([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0xFFFFFFFFu)] [Random(2)] uint Wn, [Values((byte)0x00, (byte)0x7F, (byte)0x80, (byte)0xFF)] [Random(64)] byte Wm) { uint Opcode = 0x1AC04000; // CRC32B W0, W0, W0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Crc32(Op[31], Op[20, 16], Op[11, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("CRC32CX <Wd>, <Wn>, <Xm>")] public void Crc32cx([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0xFFFFFFFFu)] [Random(2)] uint Wn, [Values((ulong)0x00_00_00_00_00_00_00_00, (ulong)0x7F_FF_FF_FF_FF_FF_FF_FF, (ulong)0x80_00_00_00_00_00_00_00, (ulong)0xFF_FF_FF_FF_FF_FF_FF_FF)] [Random(64)] ulong Xm) { uint Opcode = 0x9AC05C00; // CRC32CX W0, W0, X0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Xm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Crc32c(Op[31], Op[20, 16], Op[11, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("CRC32CW <Wd>, <Wn>, <Wm>")] public void Crc32cw([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0xFFFFFFFFu)] [Random(2)] uint Wn, [Values((uint)0x00_00_00_00, (uint)0x7F_FF_FF_FF, (uint)0x80_00_00_00, (uint)0xFF_FF_FF_FF)] [Random(64)] uint Wm) { uint Opcode = 0x1AC05800; // CRC32CW W0, W0, W0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Crc32c(Op[31], Op[20, 16], Op[11, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("CRC32CH <Wd>, <Wn>, <Wm>")] public void Crc32ch([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0xFFFFFFFFu)] [Random(2)] uint Wn, [Values((ushort)0x00_00, (ushort)0x7F_FF, (ushort)0x80_00, (ushort)0xFF_FF)] [Random(64)] ushort Wm) { uint Opcode = 0x1AC05400; // CRC32CH W0, W0, W0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Crc32c(Op[31], Op[20, 16], Op[11, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("CRC32CB <Wd>, <Wn>, <Wm>")] public void Crc32cb([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0xFFFFFFFFu)] [Random(2)] uint Wn, [Values((byte)0x00, (byte)0x7F, (byte)0x80, (byte)0xFF)] [Random(64)] byte Wm) { uint Opcode = 0x1AC05000; // CRC32CB W0, W0, W0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Crc32c(Op[31], Op[20, 16], Op[11, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("EON <Xd>, <Xn>, <Xm>{, <shift> #<amount>}")] public void Eon_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xm, [Values(0b00u, 0b01u, 0b10u, 0b11u)] uint shift, // <LSL, LSR, ASR, ROR> [Values(0u, 31u, 32u, 63u)] [Random(0u, 63u, 1)] uint amount) { uint Opcode = 0xCA200000; // EON X0, X0, X0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Eon(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("EON <Wd>, <Wn>, <Wm>{, <shift> #<amount>}")] public void Eon_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wm, [Values(0b00u, 0b01u, 0b10u, 0b11u)] uint shift, // <LSL, LSR, ASR, ROR> [Values(0u, 15u, 16u, 31u)] [Random(0u, 31u, 1)] uint amount) { uint Opcode = 0x4A200000; // EON W0, W0, W0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Eon(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("EOR <Xd>, <Xn>, <Xm>{, <shift> #<amount>}")] public void Eor_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xm, [Values(0b00u, 0b01u, 0b10u, 0b11u)] uint shift, // <LSL, LSR, ASR, ROR> [Values(0u, 31u, 32u, 63u)] [Random(0u, 63u, 1)] uint amount) { uint Opcode = 0xCA000000; // EOR X0, X0, X0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Eor_Rs(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("EOR <Wd>, <Wn>, <Wm>{, <shift> #<amount>}")] public void Eor_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wm, [Values(0b00u, 0b01u, 0b10u, 0b11u)] uint shift, // <LSL, LSR, ASR, ROR> [Values(0u, 15u, 16u, 31u)] [Random(0u, 31u, 1)] uint amount) { uint Opcode = 0x4A000000; // EOR W0, W0, W0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Eor_Rs(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("EXTR <Xd>, <Xn>, <Xm>, #<lsb>")] public void Extr_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(2)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(2)] ulong Xm, [Values(0u, 31u, 32u, 63u)] [Random(0u, 63u, 2)] uint lsb) { uint Opcode = 0x93C00000; // EXTR X0, X0, X0, #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((lsb & 63) << 10); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Extr(Op[31], Op[22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("EXTR <Wd>, <Wn>, <Wm>, #<lsb>")] public void Extr_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(2)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(2)] uint Wm, [Values(0u, 15u, 16u, 31u)] [Random(0u, 31u, 2)] uint lsb) { uint Opcode = 0x13800000; // EXTR W0, W0, W0, #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((lsb & 63) << 10); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Extr(Op[31], Op[22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("LSLV <Xd>, <Xn>, <Xm>")] public void Lslv_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(8)] ulong Xn, [Values(0ul, 31ul, 32ul, 63ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(5)] ulong Xm) { uint Opcode = 0x9AC02000; // LSLV X0, X0, X0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Lslv(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("LSLV <Wd>, <Wn>, <Wm>")] public void Lslv_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(8)] uint Wn, [Values(0u, 15u, 16u, 31u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(5)] uint Wm) { uint Opcode = 0x1AC02000; // LSLV W0, W0, W0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Lslv(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("LSRV <Xd>, <Xn>, <Xm>")] public void Lsrv_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(8)] ulong Xn, [Values(0ul, 31ul, 32ul, 63ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(5)] ulong Xm) { uint Opcode = 0x9AC02400; // LSRV X0, X0, X0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Lsrv(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("LSRV <Wd>, <Wn>, <Wm>")] public void Lsrv_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(8)] uint Wn, [Values(0u, 15u, 16u, 31u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(5)] uint Wm) { uint Opcode = 0x1AC02400; // LSRV W0, W0, W0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Lsrv(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("ORN <Xd>, <Xn>, <Xm>{, <shift> #<amount>}")] public void Orn_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xm, [Values(0b00u, 0b01u, 0b10u, 0b11u)] uint shift, // <LSL, LSR, ASR, ROR> [Values(0u, 31u, 32u, 63u)] [Random(0u, 63u, 1)] uint amount) { uint Opcode = 0xAA200000; // ORN X0, X0, X0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Orn(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("ORN <Wd>, <Wn>, <Wm>{, <shift> #<amount>}")] public void Orn_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wm, [Values(0b00u, 0b01u, 0b10u, 0b11u)] uint shift, // <LSL, LSR, ASR, ROR> [Values(0u, 15u, 16u, 31u)] [Random(0u, 31u, 1)] uint amount) { uint Opcode = 0x2A200000; // ORN W0, W0, W0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Orn(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("ORR <Xd>, <Xn>, <Xm>{, <shift> #<amount>}")] public void Orr_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xm, [Values(0b00u, 0b01u, 0b10u, 0b11u)] uint shift, // <LSL, LSR, ASR, ROR> [Values(0u, 31u, 32u, 63u)] [Random(0u, 63u, 1)] uint amount) { uint Opcode = 0xAA000000; // ORR X0, X0, X0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Orr_Rs(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("ORR <Wd>, <Wn>, <Wm>{, <shift> #<amount>}")] public void Orr_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wm, [Values(0b00u, 0b01u, 0b10u, 0b11u)] uint shift, // <LSL, LSR, ASR, ROR> [Values(0u, 15u, 16u, 31u)] [Random(0u, 31u, 1)] uint amount) { uint Opcode = 0x2A000000; // ORR W0, W0, W0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Orr_Rs(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("RORV <Xd>, <Xn>, <Xm>")] public void Rorv_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(8)] ulong Xn, [Values(0ul, 31ul, 32ul, 63ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(5)] ulong Xm) { uint Opcode = 0x9AC02C00; // RORV X0, X0, X0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Rorv(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("RORV <Wd>, <Wn>, <Wm>")] public void Rorv_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(8)] uint Wn, [Values(0u, 15u, 16u, 31u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(5)] uint Wm) { uint Opcode = 0x1AC02C00; // RORV W0, W0, W0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Rorv(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("SBC <Xd>, <Xn>, <Xm>")] public void Sbc_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(4)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(4)] ulong Xm, [Values] bool CarryIn) { uint Opcode = 0xDA000000; // SBC X0, X0, X0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31, Carry: CarryIn); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Shared.PSTATE.C = CarryIn; Base.Sbc(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("SBC <Wd>, <Wn>, <Wm>")] public void Sbc_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(4)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(4)] uint Wm, [Values] bool CarryIn) { uint Opcode = 0x5A000000; // SBC W0, W0, W0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31, Carry: CarryIn); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Shared.PSTATE.C = CarryIn; Base.Sbc(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("SBCS <Xd>, <Xn>, <Xm>")] public void Sbcs_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(4)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(4)] ulong Xm, [Values] bool CarryIn) { uint Opcode = 0xFA000000; // SBCS X0, X0, X0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Bits Op = new Bits(Opcode); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31, Carry: CarryIn); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Shared.PSTATE.C = CarryIn; Base.Sbcs(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); if (Rd != 31) { Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } Assert.Multiple(() => { Assert.That(ThreadState.Negative, Is.EqualTo(Shared.PSTATE.N)); Assert.That(ThreadState.Zero, Is.EqualTo(Shared.PSTATE.Z)); Assert.That(ThreadState.Carry, Is.EqualTo(Shared.PSTATE.C)); Assert.That(ThreadState.Overflow, Is.EqualTo(Shared.PSTATE.V)); }); CompareAgainstUnicorn(); } [Test, Description("SBCS <Wd>, <Wn>, <Wm>")] public void Sbcs_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(4)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(4)] uint Wm, [Values] bool CarryIn) { uint Opcode = 0x7A000000; // SBCS W0, W0, W0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Bits Op = new Bits(Opcode); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31, Carry: CarryIn); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Shared.PSTATE.C = CarryIn; Base.Sbcs(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); if (Rd != 31) { Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } Assert.Multiple(() => { Assert.That(ThreadState.Negative, Is.EqualTo(Shared.PSTATE.N)); Assert.That(ThreadState.Zero, Is.EqualTo(Shared.PSTATE.Z)); Assert.That(ThreadState.Carry, Is.EqualTo(Shared.PSTATE.C)); Assert.That(ThreadState.Overflow, Is.EqualTo(Shared.PSTATE.V)); }); CompareAgainstUnicorn(); } [Test, Description("SDIV <Xd>, <Xn>, <Xm>")] public void Sdiv_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(8)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(8)] ulong Xm) { uint Opcode = 0x9AC00C00; // SDIV X0, X0, X0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Sdiv(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("SDIV <Wd>, <Wn>, <Wm>")] public void Sdiv_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(8)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(8)] uint Wm) { uint Opcode = 0x1AC00C00; // SDIV W0, W0, W0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Sdiv(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("SUB <Xd>, <Xn>, <Xm>{, <shift> #<amount>}")] public void Sub_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xm, [Values(0b00u, 0b01u, 0b10u)] uint shift, // <LSL, LSR, ASR> [Values(0u, 31u, 32u, 63u)] [Random(0u, 63u, 1)] uint amount) { uint Opcode = 0xCB000000; // SUB X0, X0, X0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Sub_Rs(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("SUB <Wd>, <Wn>, <Wm>{, <shift> #<amount>}")] public void Sub_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wm, [Values(0b00u, 0b01u, 0b10u)] uint shift, // <LSL, LSR, ASR> [Values(0u, 15u, 16u, 31u)] [Random(0u, 31u, 1)] uint amount) { uint Opcode = 0x4B000000; // SUB W0, W0, W0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Sub_Rs(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } [Test, Description("SUBS <Xd>, <Xn>, <Xm>{, <shift> #<amount>}")] public void Subs_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(1)] ulong Xm, [Values(0b00u, 0b01u, 0b10u)] uint shift, // <LSL, LSR, ASR> [Values(0u, 31u, 32u, 63u)] [Random(0u, 63u, 1)] uint amount) { uint Opcode = 0xEB000000; // SUBS X0, X0, X0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); Bits Op = new Bits(Opcode); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Subs_Rs(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); if (Rd != 31) { Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } Assert.Multiple(() => { Assert.That(ThreadState.Negative, Is.EqualTo(Shared.PSTATE.N)); Assert.That(ThreadState.Zero, Is.EqualTo(Shared.PSTATE.Z)); Assert.That(ThreadState.Carry, Is.EqualTo(Shared.PSTATE.C)); Assert.That(ThreadState.Overflow, Is.EqualTo(Shared.PSTATE.V)); }); CompareAgainstUnicorn(); } [Test, Description("SUBS <Wd>, <Wn>, <Wm>{, <shift> #<amount>}")] public void Subs_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(1)] uint Wm, [Values(0b00u, 0b01u, 0b10u)] uint shift, // <LSL, LSR, ASR> [Values(0u, 15u, 16u, 31u)] [Random(0u, 31u, 1)] uint amount) { uint Opcode = 0x6B000000; // SUBS W0, W0, W0, LSL #0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); Opcode |= ((shift & 3) << 22) | ((amount & 63) << 10); Bits Op = new Bits(Opcode); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Subs_Rs(Op[31], Op[23, 22], Op[20, 16], Op[15, 10], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); if (Rd != 31) { Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } Assert.Multiple(() => { Assert.That(ThreadState.Negative, Is.EqualTo(Shared.PSTATE.N)); Assert.That(ThreadState.Zero, Is.EqualTo(Shared.PSTATE.Z)); Assert.That(ThreadState.Carry, Is.EqualTo(Shared.PSTATE.C)); Assert.That(ThreadState.Overflow, Is.EqualTo(Shared.PSTATE.V)); }); CompareAgainstUnicorn(); } [Test, Description("UDIV <Xd>, <Xn>, <Xm>")] public void Udiv_64bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(8)] ulong Xn, [Values(0x0000000000000000ul, 0x7FFFFFFFFFFFFFFFul, 0x8000000000000000ul, 0xFFFFFFFFFFFFFFFFul)] [Random(8)] ulong Xm) { uint Opcode = 0x9AC00800; // UDIV X0, X0, X0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); ulong _X31 = TestContext.CurrentContext.Random.NextULong(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Xn, X2: Xm, X31: _X31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Xn)); AArch64.X((int)Rm, new Bits(Xm)); Base.Udiv(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); ulong Xd = AArch64.X(64, (int)Rd).ToUInt64(); Assert.That((ulong)ThreadState.X0, Is.EqualTo(Xd)); } else { Assert.That((ulong)ThreadState.X31, Is.EqualTo(_X31)); } CompareAgainstUnicorn(); } [Test, Description("UDIV <Wd>, <Wn>, <Wm>")] public void Udiv_32bit([Values(0u, 31u)] uint Rd, [Values(1u, 31u)] uint Rn, [Values(2u, 31u)] uint Rm, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(8)] uint Wn, [Values(0x00000000u, 0x7FFFFFFFu, 0x80000000u, 0xFFFFFFFFu)] [Random(8)] uint Wm) { uint Opcode = 0x1AC00800; // UDIV W0, W0, W0 Opcode |= ((Rm & 31) << 16) | ((Rn & 31) << 5) | ((Rd & 31) << 0); uint _W31 = TestContext.CurrentContext.Random.NextUInt(); AThreadState ThreadState = SingleOpcode(Opcode, X1: Wn, X2: Wm, X31: _W31); if (Rd != 31) { Bits Op = new Bits(Opcode); AArch64.X((int)Rn, new Bits(Wn)); AArch64.X((int)Rm, new Bits(Wm)); Base.Udiv(Op[31], Op[20, 16], Op[9, 5], Op[4, 0]); uint Wd = AArch64.X(32, (int)Rd).ToUInt32(); Assert.That((uint)ThreadState.X0, Is.EqualTo(Wd)); } else { Assert.That((uint)ThreadState.X31, Is.EqualTo(_W31)); } CompareAgainstUnicorn(); } #endif } }
45.949644
105
0.454399
[ "Unlicense" ]
0x0ade/Ryujinx
Ryujinx.Tests/Cpu/CpuTestAluRs.cs
90,337
C#
using System; using System.Collections.Generic; namespace Server.DataAccess.Model { public class User : BaseModel { public Guid AccountId { get; set; } public virtual Account Account { get; set; } public string Name { get; set; } public virtual ICollection<CashAccount> CashAccounts { get; set; } public virtual ICollection<Cashflow> Cashflows { get; set; } public User() { CashAccounts = new HashSet<CashAccount>(); Cashflows = new HashSet<Cashflow>(); } } }
22.68
74
0.606702
[ "MIT" ]
EverMoneyTeam/EverMoney
Server.DataAccess/Model/User.cs
569
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using AppCondominio; using AppCondominio.Models; using AppCondominio.Repository.Interfaces; namespace AppCondominio.Controllers { public class MateriaisController : Controller { private readonly IMaterialRepo materialRepo; private readonly IFornecedorRepo fornecedorRepo; private readonly ILocadorRepo locadorRepo; public MateriaisController(IMaterialRepo materialRepo, IFornecedorRepo fornecedorRepo, ILocadorRepo locadorRepo) { this.materialRepo = materialRepo; this.fornecedorRepo = fornecedorRepo; this.locadorRepo = locadorRepo; } // GET: Materiais public async Task<IActionResult> Index() { return View(materialRepo.GetMateriais()); } // GET: Materiais/Details/5 public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var material = materialRepo.GetMaterial(id); if (material == null) { return NotFound(); } return View(material); } // GET: Materiais/Create public IActionResult Create() { ViewData["FornecedorID"] = new SelectList(fornecedorRepo.GetFornecedores(), "Id", "Nome"); ViewData["LocadorID"] = new SelectList(locadorRepo.GetLocadores(), "Id", "Nome"); return View(); } // POST: Materiais/Create // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("Nome,Descricao,ValorUnitario,Quantidade,FornecedorID,LocadorID,Id")] Material material) { if (ModelState.IsValid) { var teste = materialRepo.CreateMaterial(material); return RedirectToAction(nameof(Index)); } ViewData["FornecedorID"] = new SelectList(fornecedorRepo.GetFornecedores(), "Id", "Nome"); ViewData["LocadorID"] = new SelectList(locadorRepo.GetLocadores(), "Id", "Nome"); return View(material); } // GET: Materiais/Edit/5 public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var material = materialRepo.GetMaterial(id); if (material == null) { return NotFound(); } ViewData["FornecedorID"] = new SelectList(fornecedorRepo.GetFornecedores(), "Id", "Nome"); ViewData["LocadorID"] = new SelectList(locadorRepo.GetLocadores(), "Id", "Nome"); return View(material); } // POST: Materiais/Edit/5 // To protect from overposting attacks, please enable the specific properties you want to bind to, for // more details see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int id, [Bind("Nome,Descricao,ValorUnitario,Quantidade,FornecedorID,LocadorID,Id")] Material material) { if (id != material.Id) { return NotFound(); } if (ModelState.IsValid) { try { materialRepo.UpdateMaterial(material); } catch (DbUpdateConcurrencyException) { if (!materialRepo.MaterialExists(material.Id)) { return NotFound(); } else { throw; } } return RedirectToAction(nameof(Index)); } ViewData["FornecedorID"] = new SelectList(fornecedorRepo.GetFornecedores(), "Id", "Nome"); ViewData["LocadorID"] = new SelectList(locadorRepo.GetLocadores(), "Id", "Nome"); return View(material); } // GET: Materiais/Delete/5 public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var material = materialRepo.GetMaterial(id); if (material == null) { return NotFound(); } return View(material); } // POST: Materiais/Delete/5 [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { var material = materialRepo.GetMaterial(id); materialRepo.RemoveMaterial(material); return RedirectToAction(nameof(Index)); } } }
33.245283
148
0.551835
[ "MIT" ]
Pedro29152/app_condominio
AppCondominio/Controllers/MateriaisController.cs
5,288
C#
using System.IO; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; namespace Proverb.Api.Core { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .Build(); host.Run(); } } }
22.363636
64
0.544715
[ "MIT" ]
johnnyreilly/proverb-api-core
src/Proverb.Web/Program.cs
494
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _6._2._4_zz { class Program { static void Main(string[] args) { Console.Write("unesi broj: "); string br = Console.ReadLine(); char[] charArray = br.ToCharArray(); Array.Reverse(charArray); Console.WriteLine(charArray); Console.Read(); } } }
20.826087
48
0.5762
[ "MIT" ]
Nestjik/AlgebraCSharp2019
ConsoleApp1/6.2.4_zz/Program.cs
481
C#
using System; using System.Collections.Generic; using System.Text; using WebKit; using WebKit.Interop; namespace WebKit { internal delegate void OnNotifyEvent(IWebNotification notification); internal class WebNotificationObserver : IWebNotificationObserver { public event OnNotifyEvent OnNotify = delegate { }; #region webNotificationObserver Members public void onNotify(IWebNotification notification) { OnNotify(notification); } #endregion } }
21.12
72
0.702652
[ "Apache-2.0" ]
xuld/WebkitNet
Src/WebkitNet/WebNotificationObserver.cs
530
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("look.common")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("look.common")] [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("1f4cd870-4a49-48f7-926b-34af270637ad")] // 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.702703
84
0.743369
[ "MIT" ]
kekse/Look
look/look.common/Properties/AssemblyInfo.cs
1,398
C#
#pragma checksum "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\Modules\Pages\Page\Components\PageLink.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "1a317a6723a614d889e7bea6d676a2dfa9557bde" // <auto-generated/> #pragma warning disable 1591 #pragma warning disable 0414 #pragma warning disable 0649 #pragma warning disable 0169 namespace YourSpace.Modules.Pages.Page.Components { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #nullable restore #line 1 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using System.Net.Http; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using Microsoft.AspNetCore.Authorization; #line default #line hidden #nullable disable #nullable restore #line 3 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using Microsoft.AspNetCore.Components.Authorization; #line default #line hidden #nullable disable #nullable restore #line 4 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using Microsoft.AspNetCore.Components.Forms; #line default #line hidden #nullable disable #nullable restore #line 5 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using Microsoft.AspNetCore.Components.Routing; #line default #line hidden #nullable disable #nullable restore #line 6 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using Microsoft.AspNetCore.Components.Web; #line default #line hidden #nullable disable #nullable restore #line 7 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using Microsoft.JSInterop; #line default #line hidden #nullable disable #nullable restore #line 8 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace; #line default #line hidden #nullable disable #nullable restore #line 9 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Shared; #line default #line hidden #nullable disable #nullable restore #line 11 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.ModalWindow; #line default #line hidden #nullable disable #nullable restore #line 13 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Page; #line default #line hidden #nullable disable #nullable restore #line 14 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Page.Models; #line default #line hidden #nullable disable #nullable restore #line 15 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Page.Components; #line default #line hidden #nullable disable #nullable restore #line 16 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Page.ModifyComponents; #line default #line hidden #nullable disable #nullable restore #line 17 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Blocks.ModifyComponents; #line default #line hidden #nullable disable #nullable restore #line 18 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Blocks.Components; #line default #line hidden #nullable disable #nullable restore #line 19 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Blocks.Models; #line default #line hidden #nullable disable #nullable restore #line 20 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Blocks; #line default #line hidden #nullable disable #nullable restore #line 21 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Groups.ModifyComponents; #line default #line hidden #nullable disable #nullable restore #line 22 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Groups.ViewMode; #line default #line hidden #nullable disable #nullable restore #line 23 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Pages.Groups.Models; #line default #line hidden #nullable disable #nullable restore #line 25 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.ThingCounter; #line default #line hidden #nullable disable #nullable restore #line 26 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.ThingCounter.Components; #line default #line hidden #nullable disable #nullable restore #line 28 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.DataWorker; #line default #line hidden #nullable disable #nullable restore #line 29 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Cloner; #line default #line hidden #nullable disable #nullable restore #line 30 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Gallery; #line default #line hidden #nullable disable #nullable restore #line 31 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Gallery.Models; #line default #line hidden #nullable disable #nullable restore #line 32 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.FileUpload; #line default #line hidden #nullable disable #nullable restore #line 33 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Inputs; #line default #line hidden #nullable disable #nullable restore #line 35 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Moderation; #line default #line hidden #nullable disable #nullable restore #line 36 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Moderation.Models; #line default #line hidden #nullable disable #nullable restore #line 38 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.ComponentsView; #line default #line hidden #nullable disable #nullable restore #line 39 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Services; #line default #line hidden #nullable disable #nullable restore #line 40 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Lister; #line default #line hidden #nullable disable #nullable restore #line 41 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Image; #line default #line hidden #nullable disable #nullable restore #line 43 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.UserProfile; #line default #line hidden #nullable disable #nullable restore #line 44 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.UserProfile.Compoents; #line default #line hidden #nullable disable #nullable restore #line 46 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using Microsoft.Extensions.Localization; #line default #line hidden #nullable disable #nullable restore #line 47 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Localization; #line default #line hidden #nullable disable #nullable restore #line 48 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using YourSpace.Modules.Music; #line default #line hidden #nullable disable #nullable restore #line 50 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\_Imports.razor" using BlazorInputFile; #line default #line hidden #nullable disable public partial class PageLink : Microsoft.AspNetCore.Components.ComponentBase { #pragma warning disable 1998 protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) { } #pragma warning restore 1998 #nullable restore #line 5 "C:\Users\qzwse\Desktop\YourSpaceMDB_4.2_Optimization\YourSpace\Modules\Pages\Page\Components\PageLink.razor" [Inject] protected ISPagesUrl SUrl { get; set; } [Parameter] public string Id { get; set; } [Parameter] public bool Edit { get; set; } = false; [Parameter] public RenderFragment ChildContent { get; set; } [Parameter] public string Class { get; set; } public string Url { get; set; } protected override async Task OnInitializedAsync() { Console.WriteLine("Init PageLinkStart"); Url = Edit ? await SUrl.GetPageUrlEdit(Id) : await SUrl.GetPageUrl(Id); Console.WriteLine("Init PageLinkEnd"); } #line default #line hidden #nullable disable } } #pragma warning restore 1591
28
210
0.807563
[ "MIT" ]
Invectys/Sites
YourSpaceMDB_4.2_Optimization/YourSpace/obj/Debug/netcoreapp3.1/RazorDeclaration/Modules/Pages/Page/Components/PageLink.razor.g.cs
9,520
C#
using System.Text.RegularExpressions; using Chronic.Core.System; namespace Chronic.Core { public static class Numerizer { static readonly dynamic[,] DIRECT_NUMS = new dynamic[,] { {"eleven", "11"}, {"twelve", "12"}, {"thirteen", "13"}, {"fourteen", "14"}, {"fifteen", "15"}, {"sixteen", "16"}, {"seventeen", "17"}, {"eighteen", "18"}, {"nineteen", "19"}, {"ninteen", "19"}, // Common mis-spelling {"zero", "0"}, {"one", "1"}, {"two", "2"}, {"three", "3"}, {@"four(\W|$)", "4$1"}, // The weird regex is so that it matches four but not fourty {"five", "5"}, {@"six(\W|$)", "6$1"}, {@"seven(\W|$)", "7$1"}, {@"eight(\W|$)", "8$1"}, {@"nine(\W|$)", "9$1"}, {"ten", "10"}, {@"\ba[\b^$]", "1"} // doesn"t make sense for an "a" at the end to be a 1 }; static readonly dynamic[,] ORDINALS = new dynamic[,] { {"first", "1"}, {"third", "3"}, {"fourth", "4"}, {"fifth", "5"}, {"sixth", "6"}, {"seventh", "7"}, {"eighth", "8"}, {"ninth", "9"}, {"tenth", "10"} }; static readonly dynamic[,] TEN_PREFIXES = new dynamic[,] { {"twenty", 20}, {"thirty", 30}, {"forty", 40}, {"fourty", 40}, // Common mis-spelling {"fifty", 50}, {"sixty", 60}, {"seventy", 70}, {"eighty", 80}, {"ninety", 90} }; static readonly dynamic[,] BIG_PREFIXES = new dynamic[,] { {"hundred", 100}, {"thousand", 1000}, {"million", 1000000}, {"billion", 1000000000}, {"trillion", 1000000000000}, }; public static string Numerize(string value) { var result = value; // preprocess result = @" +|([^\d])-([^\d])".Compile().Replace(result, "$1 $2"); // will mutilate hyphenated-words but shouldn't matter for date extraction result = result.Replace("a half", "haAlf"); // take the 'a' out so it doesn't turn into a 1, save the half for the end // easy/direct replacements DIRECT_NUMS.ForEach<string, string>( (p, r) => result = Regex.Replace( result, p, "<num>" + r)); ORDINALS.ForEach<string, string>( (p, r) => result = Regex.Replace( result, p, "<num>" + r + p. LastCharacters (2))); // ten, twenty, etc. TEN_PREFIXES.ForEach<string, int>( (p, r) => result = Regex.Replace( result, "(?:" + p + @") *<num>(\d(?=[^\d]|$))*", match => "<num>" + (r + int.Parse(match.Groups[1].Value)))); TEN_PREFIXES.ForEach<string, int>( (p, r) => result = Regex.Replace(result, p, "<num>" + r.ToString())); // hundreds, thousands, millions, etc. BIG_PREFIXES.ForEach<string, long>( (p, r) => { result = Regex.Replace(result, @"(?:<num>)?(\d*) *" + p, match => "<num>" + (r * int.Parse(match.Groups[1].Value)).ToString()); result = Andition(result); }); // fractional addition // I'm not combining this with the previous block as using float addition complicates the strings // (with extraneous .0"s and such ) result = Regex.Replace(result, @"(\d +)(?: |and | -)*haAlf", match => (float.Parse(match.Groups[1].Value) + 0.5).ToString()); result = result.Replace("<num>", ""); return result; } static string Andition(string value) { var result = value; var pattern = @"<num>(\d+)( | and )<num>(\d+)(?=[^\w]|$)".Compile(); while (true) { var match = pattern.Match(result); if (match.Success == false) break; result = result.Substring(0, match.Index) + "<num>" + ((int.Parse(match.Groups[1].Value) + int.Parse(match.Groups[3].Value)).ToString()) + result.Substring(match.Index + match.Length); } return result; } } }
34.932886
147
0.377329
[ "MIT" ]
robbell/nChronic
src/Chronic.Core/Numerizer.cs
5,207
C#
using System; using System.Linq; using dueltank.core.Models.YgoPro; namespace dueltank.Domain.Helpers { public static class YgoProDeckHelpers { public static string AddLeadingZerosToCardNumber(string cardNumber) { return long.Parse(cardNumber).ToString("D8"); } public static long[] ExtractCardNumbers(string deckSection) { if (string.IsNullOrWhiteSpace(deckSection)) return new long[0]; return deckSection.Split('\n') .Where(c => !string.IsNullOrWhiteSpace(c)) .Select(c => c.Trim(Environment.NewLine.ToCharArray())) .Select(long.Parse) .ToArray(); } public static YgoProDeck MapToYgoProDeck(string deck) { var ygoProDeck = new YgoProDeck(); string[] delimiters = {"#main", "#extra", "!side"}; var deckSections = deck.Split(delimiters, StringSplitOptions.None).Skip(1).ToList(); if (deckSections.Count == 3) { var mainDeckSecion = deckSections[0].Trim(); var extraDeckSection = deckSections[1].Trim(); var sideCards = deckSections[2].Trim(); if (!string.IsNullOrWhiteSpace(mainDeckSecion)) ygoProDeck.Main.AddRange(ExtractCardNumbers(mainDeckSecion)); if (!string.IsNullOrWhiteSpace(extraDeckSection)) ygoProDeck.Extra.AddRange(ExtractCardNumbers(extraDeckSection)); if (!string.IsNullOrWhiteSpace(sideCards)) ygoProDeck.Side.AddRange(ExtractCardNumbers(sideCards)); } return ygoProDeck; } } }
32.925926
96
0.570866
[ "MIT" ]
fablecode/dueltank
src/Api/src/dueltank.Domain/Helpers/YgoProDeckHelpers.cs
1,780
C#
// <auto-generated /> using System; using Limbo_Seeing.DAL; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Limbo_Seeing.Migrations { [DbContext(typeof(Limbo_SeeingContext))] partial class Limbo_SeeingContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.13") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Limbo_Seeing.Models.Activiteiten", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<int>("Aantal") .HasColumnType("int"); b.Property<string>("Adress") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("Eind_Activiteit") .HasColumnType("datetime2"); b.Property<Guid>("Gebruiker_Id") .HasColumnType("uniqueidentifier"); b.Property<string>("Naam") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("Start_Activiteit") .HasColumnType("datetime2"); b.Property<int>("Tijdslot_grote") .HasColumnType("int"); b.HasKey("Id"); b.HasIndex("Gebruiker_Id"); b.ToTable("Activiteiten"); }); modelBuilder.Entity("Limbo_Seeing.Models.Gebruiker", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<string>("Achternaam") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("CreatedOn") .HasColumnType("datetime2"); b.Property<string>("Email") .HasColumnType("nvarchar(max)"); b.Property<DateTime>("Geboortendatum") .HasColumnType("datetime2"); b.Property<int>("Geslacht") .HasColumnType("int"); b.Property<int>("Rol") .HasColumnType("int"); b.Property<DateTime>("UpdatedOn") .HasColumnType("datetime2"); b.Property<bool>("UserActive") .HasColumnType("bit"); b.Property<string>("Voornaam") .HasColumnType("nvarchar(max)"); b.Property<string>("Wachtwoord") .HasColumnType("nvarchar(max)"); b.HasKey("Id"); b.ToTable("Gebruikers"); }); modelBuilder.Entity("Limbo_Seeing.Models.Resevering", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<Guid>("Activiteit_Id") .HasColumnType("uniqueidentifier"); b.Property<Guid>("Gebruiker_Id") .HasColumnType("uniqueidentifier"); b.Property<DateTime>("Tijdslot_Eind") .HasColumnType("datetime2"); b.Property<DateTime>("Tijdslot_Start") .HasColumnType("datetime2"); b.HasKey("Id"); b.HasIndex("Activiteit_Id"); b.HasIndex("Gebruiker_Id"); b.ToTable("Reseverings"); }); modelBuilder.Entity("Limbo_Seeing.Models.Sensors", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<int>("Battery") .HasColumnType("int"); b.Property<string>("Locatie") .HasColumnType("nvarchar(max)"); b.Property<int>("SensorType") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("Sensoren"); }); modelBuilder.Entity("Limbo_Seeing.Models.Sensors_Acties", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<int>("Aantal_bewegingen") .HasColumnType("int"); b.Property<Guid>("Sensor_Id") .HasColumnType("uniqueidentifier"); b.Property<int>("Snelheid") .HasColumnType("int"); b.Property<int>("Soort_beweging") .HasColumnType("int"); b.Property<DateTime>("Tijd") .HasColumnType("datetime2"); b.HasKey("Id"); b.HasIndex("Sensor_Id"); b.ToTable("Sensors_Acties"); }); modelBuilder.Entity("Limbo_Seeing.Models.Activiteiten", b => { b.HasOne("Limbo_Seeing.Models.Gebruiker", "Gebruiker") .WithMany("Activiteitens") .HasForeignKey("Gebruiker_Id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); modelBuilder.Entity("Limbo_Seeing.Models.Resevering", b => { b.HasOne("Limbo_Seeing.Models.Activiteiten", "Activiteit") .WithMany("Reseverings") .HasForeignKey("Activiteit_Id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); b.HasOne("Limbo_Seeing.Models.Gebruiker", "Gebruiker") .WithMany("Reseverings") .HasForeignKey("Gebruiker_Id") .OnDelete(DeleteBehavior.NoAction) .IsRequired(); }); modelBuilder.Entity("Limbo_Seeing.Models.Sensors_Acties", b => { b.HasOne("Limbo_Seeing.Models.Sensors", "Sensors") .WithMany("Sensors_Acties") .HasForeignKey("Sensor_Id") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
35.019231
117
0.463756
[ "MIT" ]
marcoduister/Limbo-Seeing-Casus
Limbo-Seeing/Migrations/Limbo_SeeingContextModelSnapshot.cs
7,286
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using XUnity.AutoTranslator.Plugin.Core.Endpoints; namespace XUnity.AutoTranslator.Plugin.Core.UI { class XuaViewModel { public XuaViewModel( List<ToggleViewModel> toggles, DropdownViewModel<TranslatorDropdownOptionViewModel, TranslationEndpointManager> dropdown, List<ButtonViewModel> commandButtons, List<LabelViewModel> labels ) { Toggles = toggles; Dropdown = dropdown; CommandButtons = commandButtons; Labels = labels; } public bool IsShown { get; set; } public List<ToggleViewModel> Toggles { get; } public DropdownViewModel<TranslatorDropdownOptionViewModel, TranslationEndpointManager> Dropdown { get; } public List<ButtonViewModel> CommandButtons { get; } public List<LabelViewModel> Labels { get; } } }
27.5
111
0.698396
[ "MIT" ]
GeBo1/XUnity.AutoTranslator
src/XUnity.AutoTranslator.Plugin.Core/UI/XuaViewModel.cs
937
C#
using Newtonsoft.Json; namespace olmelabs.battleship.api.Models.Dto { public class NewGameDto { [JsonProperty("gameId")] public string GameId { get; set; } } }
17.272727
44
0.636842
[ "MIT" ]
olmelabs/battleship-game
server-app/olmelabs.battleship.api/Models/Dto/NewGameDto.cs
192
C#
// // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // namespace Microsoft.PowerShell.PackageManagement.Cmdlets { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Management.Automation; using Microsoft.PackageManagement.Internal.Packaging; using Microsoft.PackageManagement.Internal.Utility.Async; using Microsoft.PackageManagement.Internal.Utility.Collections; using Microsoft.PackageManagement.Internal.Utility.Extensions; using Utility; using System.Security; [Cmdlet(VerbsLifecycle.Register, Constants.Nouns.PackageSourceNoun, SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=517139")] public sealed class RegisterPackageSource : CmdletWithProvider { public RegisterPackageSource() : base(new[] {OptionCategory.Provider, OptionCategory.Source}) { } [Parameter] [ValidateNotNull()] public Uri Proxy { get; set; } [Parameter] [ValidateNotNull()] public PSCredential ProxyCredential { get; set; } public override string CredentialUsername { get { return Credential != null ? Credential.UserName : null; } } public override SecureString CredentialPassword { get { return Credential != null ? Credential.Password : null; } } /// <summary> /// Returns web proxy that provider can use /// Construct the webproxy using InternalWebProxy /// </summary> public override System.Net.IWebProxy WebProxy { get { if (Proxy != null) { return new PackageManagement.Utility.InternalWebProxy(Proxy, ProxyCredential == null ? null : ProxyCredential.GetNetworkCredential()); } return null; } } protected override IEnumerable<string> ParameterSets { get { return new[] {""}; } } protected override void GenerateCmdletSpecificParameters(Dictionary<string, object> unboundArguments) { if (!IsInvocation) { var providerNames = PackageManagementService.AllProviderNames; var whatsOnCmdline = GetDynamicParameterValue<string[]>("ProviderName"); if (whatsOnCmdline != null) { providerNames = providerNames.Concat(whatsOnCmdline).Distinct(); } DynamicParameterDictionary.AddOrSet("ProviderName", new RuntimeDefinedParameter("ProviderName", typeof(string), new Collection<Attribute> { new ParameterAttribute { ValueFromPipelineByPropertyName = true, ParameterSetName = Constants.ParameterSets.SourceBySearchSet }, new AliasAttribute("Provider"), new ValidateSetAttribute(providerNames.ToArray()) })); } else { DynamicParameterDictionary.AddOrSet("ProviderName", new RuntimeDefinedParameter("ProviderName", typeof(string), new Collection<Attribute> { new ParameterAttribute { ValueFromPipelineByPropertyName = true, ParameterSetName = Constants.ParameterSets.SourceBySearchSet }, new AliasAttribute("Provider") })); } } [Parameter(Position = 0)] public string Name {get; set;} [Parameter(Position = 1)] public string Location {get; set;} [Parameter] public PSCredential Credential {get; set;} [Parameter] public SwitchParameter Trusted {get; set;} public override bool ProcessRecordAsync() { if (Stopping) { return false; } var packageProvider = SelectProviders(ProviderName).ReEnumerable(); if (ProviderName.IsNullOrEmpty()) { Error(Constants.Errors.ProviderNameNotSpecified, packageProvider.Select(p => p.ProviderName).JoinWithComma()); return false; } switch (packageProvider.Count()) { case 0: Error(Constants.Errors.UnknownProvider, ProviderName); return false; case 1: break; default: Error(Constants.Errors.MatchesMultipleProviders, packageProvider.Select(p => p.ProviderName).JoinWithComma()); return false; } var provider = packageProvider.First(); using (var sources = provider.ResolvePackageSources(this).CancelWhen(CancellationEvent.Token)) { // first, check if there is a source by this name already. var existingSources = sources.Where(each => each.IsRegistered && each.Name.Equals(Name, StringComparison.OrdinalIgnoreCase)).ToArray(); if (existingSources.Any()) { // if there is, and the user has said -Force, then let's remove it. foreach (var existingSource in existingSources) { if (Force) { if (ShouldProcess(FormatMessageString(Constants.Messages.TargetPackageSource, existingSource.Name, existingSource.Location, existingSource.ProviderName), Constants.Messages.ActionReplacePackageSource).Result) { var removedSources = provider.RemovePackageSource(existingSource.Name, this).CancelWhen(CancellationEvent.Token); foreach (var removedSource in removedSources) { Verbose(Constants.Messages.OverwritingPackageSource, removedSource.Name); } } } else { Error(Constants.Errors.PackageSourceExists, existingSource.Name); return false; } } } } string providerNameForProcessMessage = ProviderName.JoinWithComma(); if (ShouldProcess(FormatMessageString(Constants.Messages.TargetPackageSource, Name, Location, providerNameForProcessMessage), FormatMessageString(Constants.Messages.ActionRegisterPackageSource)).Result) { //Need to resolve the path created via psdrive. //e.g., New-PSDrive -Name x -PSProvider FileSystem -Root \\foobar\myfolder. Here we are resolving x:\ try { if (FilesystemExtensions.LooksLikeAFilename(Location)) { ProviderInfo providerInfo = null; var resolvedPaths = GetResolvedProviderPathFromPSPath(Location, out providerInfo); // Ensure the path is a single path from the file system provider if ((providerInfo != null) && (resolvedPaths.Count == 1) && String.Equals(providerInfo.Name, "FileSystem", StringComparison.OrdinalIgnoreCase)) { Location = resolvedPaths[0]; } } } catch (Exception) { //allow to continue handling the cases other than file system } using (var added = provider.AddPackageSource(Name, Location, Trusted, this).CancelWhen(CancellationEvent.Token)) { foreach (var addedSource in added) { WriteObject(addedSource); } } return true; } return false; } } }
41.706731
238
0.571412
[ "Apache-2.0", "MIT" ]
adbertram/PowerShell
src/Microsoft.PowerShell.PackageManagement/Cmdlets/RegisterPackageSource.cs
8,675
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; using BurnSystems.Interfaces; namespace BurnSystems.Collections { /// <summary> /// This implements the IList interface on an XContainer element. /// All addings, deletions, changes on this container will be directly done /// on the element /// </summary> /// <typeparam name="T">Type of the entity</typeparam> public class XmlList<T> : IList<T> { /// <summary> /// Stores the converter /// </summary> private readonly IXElementConverter<T> _converter; /// <summary> /// Container node being associated the list /// </summary> private readonly XContainer _container; /// <summary> /// Initializes a new instance of the XmlList class. /// </summary> /// <param name="container">Xml-Container storing the elements</param> /// <param name="converter">Converter to be used to convert items to xml and vice versa</param> public XmlList(XContainer container, IXElementConverter<T> converter) { _container = container; _converter = converter; } /// <summary> /// Gets the index of the item /// </summary> /// <param name="item">Item to be requested</param> /// <returns>Index of the item</returns> public int IndexOf(T item) { var pos = 0; foreach (var entity in _container.Elements() .Select(x => _converter.Convert(x))) { if (entity != null && entity.Equals(item)) { return pos; } pos++; } return -1; } /// <summary> /// Inserts a new item to the xmllist /// </summary> /// <param name="index">Index of the item to be added</param> /// <param name="item">Item to be added</param> public void Insert(int index, T item) { var element = _container.Elements() .ElementAtOrDefault(index - 1); if (element == null) { _container.Add(_converter.Convert(item)); } else { element.AddAfterSelf(_converter.Convert(item)); } } /// <summary> /// Removes an item at a certain position /// </summary> /// <param name="index">Index of the item</param> public void RemoveAt(int index) { var element = _container.Elements().ElementAtOrDefault(index); if (element != null) { element.Remove(); } } /// <summary> /// Gets or sets an element at a certain position /// </summary> /// <param name="index">Index of the item</param> /// <returns>Item at position</returns> public T this[int index] { get { var element = _container.Elements().ElementAt(index); return _converter.Convert(element); } set { var element = _container.Elements().ElementAtOrDefault(index); if (element != null) { element.ReplaceWith(_converter.Convert(value)); } else { _container.Add(_converter.Convert(value)); } } } /// <summary> /// Adds an item /// </summary> /// <param name="item">Item to be added</param> public void Add(T item) { _container.Add(_converter.Convert(item)); } /// <summary> /// Clears the complete list /// </summary> public void Clear() { _container.RemoveNodes(); } /// <summary> /// Checks whether the xml list contains a specific item /// </summary> /// <param name="item">Item which shall be checked</param> /// <returns>true, if item is included</returns> public bool Contains(T item) { return IndexOf(item) != -1; } /// <summary> /// Copies the complete list to an array /// </summary> /// <param name="array">Array to be added</param> /// <param name="arrayIndex"></param> public void CopyTo(T[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(); } if (arrayIndex < 0) { throw new ArgumentOutOfRangeException(); } var pos = arrayIndex; foreach (var element in this) { array[pos] = element; pos++; if (pos >= array.Length) { throw new ArgumentException(); } } } /// <summary> /// Gets the number of elements /// </summary> public int Count => _container.Elements().Count(); /// <summary> /// Gets a value indicating whether the list is read-only /// </summary> public bool IsReadOnly => false; /// <summary> /// Removes a specific item from xml list /// </summary> /// <param name="item">Item to be removed</param> /// <returns>True, if item has been removed</returns> public bool Remove(T item) { var position = IndexOf(item); if (position != -1) { RemoveAt(position); return true; } return false; } /// <summary> /// Gets an enumerator for all elements. /// Elements being null are skipped /// </summary> /// <returns>Enumerator for the list</returns> public IEnumerator<T> GetEnumerator() { foreach (var item in _container.Elements() .Select(x => _converter.Convert(x)) .Where(x => x != null)) { yield return item; } } /// <summary> /// Gets an enumerator for all elements. /// Elements being null are skipped /// </summary> /// <returns>Enumerator for the list</returns> IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } /// <summary> /// Creates an xml-List whose values matches to a specific attribute of all subnodes /// </summary> /// <param name="container">Container element containing values of all subnodes</param> /// <param name="nodeName">Name of the node containing the information</param> /// <param name="attributeName">Name of the attribute that is requested</param> /// <returns>List of information</returns> public static IList<T> GetListForAttributes(XContainer container, string nodeName, string attributeName) { var converter = new AttributeEntityConverter<T>(nodeName, attributeName); return new XmlList<T>( container, converter); } /// <summary> /// Creates an xml-List whose values matches to a specific element of all subnodes /// </summary> /// <param name="container">Container element containing values of all subnodes</param> /// <param name="nodeName">Name of the node containing the information</param> /// <returns>List of information</returns> public static IList<T> GetListForElements(XContainer container, string nodeName) { var converter = new ElementEntityConverter<T>(nodeName); return new XmlList<T>( container, converter); } /// <summary> /// Converts an attribute of all subelements to a specific type /// </summary> internal class AttributeEntityConverter<TQ> : IXElementConverter<TQ> { /// <summary> /// Name of the node /// </summary> private readonly string _nodeName; /// <summary> /// Name of the attribute /// </summary> private readonly string _attributeName; /// <summary> /// Initializes a new instance of the AttributeEntityConverter class /// </summary> /// <param name="nodeName">Name of the node</param> /// <param name="attributeName">Name of the attribute</param> public AttributeEntityConverter(string nodeName, string attributeName) { _nodeName = nodeName; _attributeName = attributeName; } /// <summary> /// Converts the element to the type /// </summary> /// <param name="element"></param> /// <returns></returns> public TQ Convert(XElement element) { if (element == null) throw new ArgumentNullException(nameof(element)); if (element.Name != _nodeName) { return default!; } var attribute = element.Attribute(_attributeName); if (attribute == null) { return default!; } return (TQ)System.Convert.ChangeType(attribute.Value, typeof(TQ)); } /// <summary> /// Converts an entity to the element /// </summary> /// <param name="entity">Entity to be converted</param> /// <returns>Entity as an XElement</returns> public XElement Convert(TQ entity) { if (entity == null) throw new ArgumentNullException(nameof(entity)); return new XElement( _nodeName, new XAttribute(_attributeName, entity.ToString())); } } /// <summary> /// Converts an element of all subelements to a specific type /// </summary> internal class ElementEntityConverter<TQ> : IXElementConverter<TQ> { /// <summary> /// Name of the node /// </summary> private readonly string _nodeName; /// <summary> /// Initializes a new instance of the AttributeEntityConverter class /// </summary> /// <param name="nodeName">Name of the node</param> public ElementEntityConverter(string nodeName) { _nodeName = nodeName; } /// <summary> /// Converts the element to the type /// </summary> /// <param name="element"></param> /// <returns></returns> public TQ Convert(XElement element) { if (element == null) throw new ArgumentNullException(nameof(element)); if (element.Name != _nodeName) { return default!; } return (TQ)System.Convert.ChangeType(element.Value, typeof(TQ)); } /// <summary> /// Converts an entity to the element /// </summary> /// <param name="entity">Entity to be converted</param> /// <returns>Entity as an XElement</returns> public XElement Convert(TQ entity) { if (entity == null) throw new ArgumentNullException(nameof(entity)); return new XElement( _nodeName, entity.ToString()); } } } }
32.328877
112
0.499545
[ "MIT" ]
mbrenn/burnsystems
src/BurnSystems/Collections/XmlList.cs
12,093
C#