content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; namespace Hydra2.Web.Models { public class Sample { public string Date { get; set; } public float? h { get; set; } public float? Q { get; set; } public float? t { get; set; } } }
19.833333
40
0.537815
[ "MIT" ]
RysavyD/Hydra2
Hydra2.Web/Models/Sample.cs
240
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using Microsoft.EntityFrameworkCore.Tools.Properties; namespace Microsoft.EntityFrameworkCore.Tools { internal class Project { private readonly string _file; private readonly string _framework; private readonly string _configuration; private readonly string _runtime; public Project(string file, string framework, string configuration, string runtime) { Debug.Assert(!string.IsNullOrEmpty(file), "file is null or empty."); _file = file; _framework = framework; _configuration = configuration; _runtime = runtime; ProjectName = Path.GetFileName(file); } public string ProjectName { get; } public string AssemblyName { get; set; } public string Language { get; set; } public string OutputPath { get; set; } public string PlatformTarget { get; set; } public string ProjectAssetsFile { get; set; } public string ProjectDir { get; set; } public string RootNamespace { get; set; } public string RuntimeFrameworkVersion { get; set; } public string TargetFileName { get; set; } public string TargetFrameworkMoniker { get; set; } public static Project FromFile( string file, string buildExtensionsDir, string framework = null, string configuration = null, string runtime = null) { Debug.Assert(!string.IsNullOrEmpty(file), "file is null or empty."); if (buildExtensionsDir == null) { buildExtensionsDir = Path.Combine(Path.GetDirectoryName(file), "obj"); } Directory.CreateDirectory(buildExtensionsDir); var efTargetsPath = Path.Combine( buildExtensionsDir, Path.GetFileName(file) + ".EntityFrameworkCore.targets"); using (var input = typeof(Resources).Assembly.GetManifestResourceStream( "Microsoft.EntityFrameworkCore.Tools.Resources.EntityFrameworkCore.targets")) using (var output = File.OpenWrite(efTargetsPath)) { // NB: Copy always in case it changes Reporter.WriteVerbose(Resources.WritingFile(efTargetsPath)); input.CopyTo(output); } IDictionary<string, string> metadata; var metadataFile = Path.GetTempFileName(); try { var propertyArg = "/property:EFProjectMetadataFile=" + metadataFile; if (framework != null) { propertyArg += ";TargetFramework=" + framework; } if (configuration != null) { propertyArg += ";Configuration=" + configuration; } if (runtime != null) { propertyArg += ";RuntimeIdentifier=" + runtime; } var args = new List<string> { "msbuild", "/target:GetEFProjectMetadata", propertyArg, "/verbosity:quiet", "/nologo" }; if (file != null) { args.Add(file); } var exitCode = Exe.Run("dotnet", args); if (exitCode != 0) { throw new CommandException(Resources.GetMetadataFailed); } metadata = File.ReadLines(metadataFile).Select(l => l.Split(new[] { ':' }, 2)) .ToDictionary(s => s[0], s => s[1].TrimStart()); } finally { File.Delete(metadataFile); } var platformTarget = metadata["PlatformTarget"]; if (platformTarget.Length == 0) { platformTarget = metadata["Platform"]; } return new Project(file, framework, configuration, runtime) { AssemblyName = metadata["AssemblyName"], Language = metadata["Language"], OutputPath = metadata["OutputPath"], PlatformTarget = platformTarget, ProjectAssetsFile = metadata["ProjectAssetsFile"], ProjectDir = metadata["ProjectDir"], RootNamespace = metadata["RootNamespace"], RuntimeFrameworkVersion = metadata["RuntimeFrameworkVersion"], TargetFileName = metadata["TargetFileName"], TargetFrameworkMoniker = metadata["TargetFrameworkMoniker"] }; } public void Build() { var args = new List<string> { "build" }; if (_file != null) { args.Add(_file); } // TODO: Only build for the first framework when unspecified if (_framework != null) { args.Add("--framework"); args.Add(_framework); } if (_configuration != null) { args.Add("--configuration"); args.Add(_configuration); } if (_runtime != null) { args.Add("--runtime"); args.Add(_runtime); } args.Add("/verbosity:quiet"); args.Add("/nologo"); var exitCode = Exe.Run("dotnet", args, interceptOutput: true); if (exitCode != 0) { throw new CommandException(Resources.BuildFailed); } } } }
33.7
111
0.519618
[ "Apache-2.0" ]
Pankraty/EntityFrameworkCore
src/dotnet-ef/Project.cs
6,066
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Maui.Controls; using Microsoft.Maui.Controls.Internals; using Microsoft.Maui.Controls.Maps; using Microsoft.Maui.Controls.Xaml; namespace Microsoft.Maui.Controls.Compatibility.ControlGallery { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class MapGallery : ContentPage { readonly Geocoder _geocoder = new Geocoder(); readonly Map Map; public MapGallery() { InitializeComponent(); Map = MakeMap(); Map.Pins.ForEach(pin => { pin.MarkerClicked += MarkerClicked; pin.InfoWindowClicked += InfoWindowClicked; }); Map.MapClicked += MapClicked; ((Grid)Content).Children.Add(Map, 0, 1); _btnToggleMoveToLastRegionOnLayoutChange.Text = Map.MoveToLastRegionOnLayoutChangeProperty.DefaultValue.ToString(); } public static Map MakeMap() { return new Map(MapSpan.FromCenterAndRadius(new Position(41.890202, 12.492049), Distance.FromMiles(0.5))) { IsShowingUser = false, Pins = { new Pin { Type = PinType.Place, Position = new Position (41.890202, 12.492049), Label = "Colosseum", Address = "Piazza del Colosseo, 00184 Rome, Province of Rome, Italy" }, new Pin { Type = PinType.Place, Position = new Position (41.898652, 12.476831), Label = "Pantheon", Address = "Piazza della Rotunda, 00186 Rome, Province of Rome, Italy" }, new Pin { Type = PinType.Place, Position = new Position (41.903209, 12.454545), Label = "Sistine Chapel", Address = "Piazza della Rotunda, 00186 Rome, Province of Rome, Italy" } } }; } void GetMapRegionClicked(object sender, EventArgs e) { if (Map.VisibleRegion == null) DisplayAlert(":(", "VisibleRegion is null, move the map to get it!", "OK"); else DisplayAlert(":)", $"Lat: {Map.VisibleRegion.Center.Latitude}, Long: {Map.VisibleRegion.Center.Longitude}, move the map to get it!", "OK"); } void MarkerClicked(object sender, PinClickedEventArgs e) { LastMarkerClickLabel.Text = $"Last Marker Clicked: {((Pin)sender).Label}"; } void InfoWindowClicked(object sender, PinClickedEventArgs e) { LastInfoWindowClickLabel.Text = $"Last Info Window Clicked: {((Pin)sender).Label}"; e.HideInfoWindow = true; } async void SearchForAddress(object sender, EventArgs e) { var searchAddress = (SearchBar)sender; var addressQuery = searchAddress.Text; searchAddress.Text = ""; searchAddress.Unfocus(); var positions = (await _geocoder.GetPositionsForAddressAsync(addressQuery)).ToList(); if (!positions.Any()) return; var position = positions.First(); Map.MoveToRegion(MapSpan.FromCenterAndRadius(position, Distance.FromMeters(4000))); Map.Pins.Add(new Pin { Label = addressQuery, Position = position, Address = addressQuery }); } void MapClicked(object sender, MapClickedEventArgs e) { LastMapClickLabel.Text = $"Last MapClick: {e.Position.Latitude}, {e.Position.Longitude}"; } async void MapTypeClicked(object sender, EventArgs e) { var result = await DisplayActionSheet("Select Map Type", null, null, "Street", "Satellite", "Hybrid"); switch (result) { case "Street": Map.MapType = MapType.Street; break; case "Satellite": Map.MapType = MapType.Satellite; break; case "Hybrid": Map.MapType = MapType.Hybrid; break; } } void ZoomInClicked(object sender, EventArgs e) { Map.MoveToRegion(Map.VisibleRegion.WithZoom(5f)); } void ZoomOutClicked(object sender, EventArgs e) { Map.MoveToRegion(Map.VisibleRegion.WithZoom(1.0 / 3)); } async void ReverseGeocodeClicked(object sender, EventArgs e) { var addresses = await _geocoder.GetAddressesForPositionAsync(new Position(41.8902, 12.4923)); foreach (var ad in addresses) Debug.WriteLine(ad); } void HomeClicked(object sender, EventArgs e) { Map.MoveToRegion(MapSpan.FromCenterAndRadius(new Position(41.890202, 12.492049), Distance.FromMiles(0.5))); } void ZoomPinClicked(object sender, EventArgs e) { var pos = new Position(41.011995, -8.642995); Map.Pins.Clear(); Map.Pins.Add(new Pin { Position = pos, Label = "Rui" }); Map.MoveToRegion(MapSpan.FromCenterAndRadius(pos, Distance.FromMiles(0.5))); } void EditPinClicked(object sender, EventArgs e) { var pin = Map.Pins.First(); pin.Label += " Edited"; pin.Address = "Edited"; var pos = new Position(pin.Position.Latitude + 1, pin.Position.Longitude + 1); pin.Position = pos; Map.MoveToRegion(MapSpan.FromCenterAndRadius(pos, Distance.FromMiles(0.5))); } void RemovePinClicked(object sender, EventArgs e) { Map.Pins.RemoveAt(0); } void ToggleMoveToLastRegionOnLayoutChange(object sender, EventArgs e) { Map.MoveToLastRegionOnLayoutChange = !Map.MoveToLastRegionOnLayoutChange; ((Button)sender).Text = Map.MoveToLastRegionOnLayoutChange.ToString(); } void ShowTrafficToggled(object sender, ToggledEventArgs e) { var control = (Switch)sender; Map.TrafficEnabled = control.IsToggled; } } }
27.416667
143
0.692819
[ "MIT" ]
Amir-Hossin-pr/maui
src/Compatibility/ControlGallery/src/Core/GalleryPages/MapGallery.xaml.cs
5,266
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _05_wordPlural { class Program { static void Main(string[] args) { string word = Console.ReadLine().ToLower(); bool endCharY = word.EndsWith("y"); bool endCharO = word.EndsWith("o"); bool endCharS = word.EndsWith("s"); bool endCharX = word.EndsWith("x"); bool endCharZ = word.EndsWith("z"); bool endCharH = word.EndsWith("h"); if (endCharY) { string result = word.Remove(word.Length-1,1); Console.WriteLine($"{result}ies"); } else if (endCharO||endCharS||endCharX||endCharZ) { Console.WriteLine($"{word}es"); } else if (endCharH) { string newWord = word.Remove(word.Length-1,1); bool endCharCH = newWord.EndsWith("c"); bool endCharSH = newWord.EndsWith("s"); if (endCharCH||endCharSH) { Console.WriteLine($"{word}es"); } } else { Console.WriteLine($"{word}s"); } } } }
22.949153
62
0.471935
[ "MIT" ]
MrPIvanov/SoftUni
02-Progr Fundamentals/06-C# Conditional Statements and Loops - Exercises/06-loopsExer/05-wordPlural/Program.cs
1,356
C#
using System.Windows; using System.Windows.Media; namespace Graphic2D.Kernel.Visuals { public interface IVisualInfo { Brush Fill { get; } Pen Stroke { get; } Point Origin { get; } double Angle { get; } } }
15
34
0.588235
[ "Apache-2.0" ]
dingweikun/DingWK.Graph2D
Graphic2D.Kernel/Visuals/IVisualInfo.cs
257
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20200601.Outputs { [OutputType] public sealed class ApplicationGatewayTrustedRootCertificateResponse { /// <summary> /// Certificate public data. /// </summary> public readonly string? Data; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> public readonly string Etag; /// <summary> /// Resource ID. /// </summary> public readonly string? Id; /// <summary> /// Secret Id of (base-64 encoded unencrypted pfx) 'Secret' or 'Certificate' object stored in KeyVault. /// </summary> public readonly string? KeyVaultSecretId; /// <summary> /// Name of the trusted root certificate that is unique within an Application Gateway. /// </summary> public readonly string? Name; /// <summary> /// The provisioning state of the trusted root certificate resource. /// </summary> public readonly string ProvisioningState; /// <summary> /// Type of the resource. /// </summary> public readonly string Type; [OutputConstructor] private ApplicationGatewayTrustedRootCertificateResponse( string? data, string etag, string? id, string? keyVaultSecretId, string? name, string provisioningState, string type) { Data = data; Etag = etag; Id = id; KeyVaultSecretId = keyVaultSecretId; Name = name; ProvisioningState = provisioningState; Type = type; } } }
29.169014
111
0.586673
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Network/V20200601/Outputs/ApplicationGatewayTrustedRootCertificateResponse.cs
2,071
C#
// Copyright (c) Simple Injector Contributors. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for license information. namespace SimpleInjector { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Reflection; using SimpleInjector.Decorators; using SimpleInjector.Internals; internal static class Requires { #if !NET40 [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] #endif [DebuggerStepThrough] internal static void IsNotNull(object? instance, string paramName) { if (instance is null) { ThrowArgumentNullException(paramName); } } [DebuggerStepThrough] internal static void IsNotNullOrEmpty(string instance, string paramName) { IsNotNull(instance, paramName); if (instance.Length == 0) { throw new ArgumentException("Value can not be empty.", paramName); } } [DebuggerStepThrough] internal static void IsReferenceType(Type type, string paramName) { if (!type.IsClass() && !type.IsInterface()) { throw new ArgumentException(StringResources.SuppliedTypeIsNotAReferenceType(type), paramName); } } [DebuggerStepThrough] internal static void IsNotOpenGenericType(Type type, string paramName) { // We check for ContainsGenericParameters to see whether there is a Generic Parameter // to find out if this type can be created. if (type.ContainsGenericParameters()) { throw new ArgumentException(StringResources.SuppliedTypeIsAnOpenGenericType(type), paramName); } } [DebuggerStepThrough] internal static void ServiceIsAssignableFromExpression( Type service, Expression expression, string paramName) { if (!service.IsAssignableFrom(expression.Type)) { ThrowSuppliedElementDoesNotInheritFromOrImplement( service, expression.Type, "expression", paramName); } } [DebuggerStepThrough] internal static void ServiceIsAssignableFromRegistration( Type service, Registration registration, string paramName) { if (!service.IsAssignableFrom(registration.ImplementationType)) { ThrowSuppliedElementDoesNotInheritFromOrImplement( service, registration.ImplementationType, "registration", paramName); } } [DebuggerStepThrough] internal static void ServiceIsAssignableFromImplementation( Type service, Type implementation, string paramName) { if (!service.IsAssignableFrom(implementation)) { ThrowSuppliedTypeDoesNotInheritFromOrImplement(service, implementation, paramName); } } [DebuggerStepThrough] internal static void IsNotAnAmbiguousType(Type type, string paramName) { if (Types.IsAmbiguousType(type)) { throw new ArgumentException(StringResources.TypeIsAmbiguous(type), paramName); } } [DebuggerStepThrough] internal static void IsGenericType(Type type, string paramName, Func<Type, string>? guidance = null) { if (!type.IsGenericType()) { string message = StringResources.SuppliedTypeIsNotAGenericType(type) + (guidance == null ? string.Empty : (" " + guidance(type))); throw new ArgumentException(message, paramName); } } [DebuggerStepThrough] internal static void IsOpenGenericType(Type type, string paramName, Func<Type, string>? guidance = null) { // We don't check for ContainsGenericParameters, because we can't handle types that don't have // a direct parameter (such as Lazy<Func<TResult>>). This is a limitation in the current // implementation of the GenericArgumentFinder. That's not an easy thing to fix :-( if (!type.ContainsGenericParameters()) { string message = StringResources.SuppliedTypeIsNotAnOpenGenericType(type) + (guidance == null ? string.Empty : (" " + guidance(type))); throw new ArgumentException(message, paramName); } } internal static void DoesNotContainNullValues<T>(IEnumerable<T?> collection, string paramName) where T : class { if (collection != null && collection.Contains(null)) { throw new ArgumentException("The collection contains null elements.", paramName); } } internal static void DoesNotContainOpenGenericTypesWhenServiceTypeIsNotGeneric( Type serviceType, IEnumerable<Type> serviceTypes, string paramName) { if (!serviceType.IsGenericType()) { Type openGenericType = serviceTypes.FirstOrDefault(t => t.ContainsGenericParameters()); if (openGenericType != null) { throw new ArgumentException( StringResources.SuppliedTypeIsAnOpenGenericTypeWhileTheServiceTypeIsNot( openGenericType), paramName); } } } internal static void ServiceTypeIsNotClosedWhenImplementationIsOpen(Type service, Type implementation) { bool implementationIsOpen = implementation.IsGenericType() && implementation.ContainsGenericParameters(); bool serviceTypeIsClosed = service.IsGenericType() && !service.ContainsGenericParameters(); if (implementationIsOpen && serviceTypeIsClosed) { throw new NotSupportedException( StringResources.SuppliedTypeCanNotBeOpenWhenDecoratorIsClosed()); } } internal static void ServiceOrItsGenericTypeDefinitionIsAssignableFromImplementation( Type service, Type implementation, string paramName) { if (service != implementation && !Types.ServiceIsAssignableFromImplementation(service, implementation)) { throw new ArgumentException( StringResources.SuppliedTypeDoesNotInheritFromOrImplement(service, implementation), paramName); } } internal static void ServiceIsAssignableFromImplementations( Type serviceType, IEnumerable<Type> typesToRegister, string paramName, bool typeCanBeServiceType = false) { var invalidType = ( from type in typesToRegister where !Types.ServiceIsAssignableFromImplementation(serviceType, type) where !typeCanBeServiceType || type != serviceType select type) .FirstOrDefault(); if (invalidType != null) { throw new ArgumentException( StringResources.SuppliedTypeDoesNotInheritFromOrImplement(serviceType, invalidType), paramName); } } internal static void ServiceIsAssignableFromImplementations( Type serviceType, IEnumerable<Registration> registrations, string paramName, bool typeCanBeServiceType = false) { var typesToRegister = registrations.Select(registration => registration.ImplementationType); ServiceIsAssignableFromImplementations( serviceType, typesToRegister, paramName, typeCanBeServiceType); } internal static void ImplementationHasSelectableConstructor( Container container, Type implementationType, string paramName) { if (!container.Options.IsConstructableType(implementationType, out string? message)) { throw new ArgumentException(message!, paramName); } } internal static void TypeFactoryReturnedTypeThatDoesNotContainUnresolvableTypeArguments( Type serviceType, Type implementationType) { try { OpenGenericTypeDoesNotContainUnresolvableTypeArguments( serviceType.IsGenericType() ? serviceType.GetGenericTypeDefinition() : serviceType, implementationType, null); } catch (ArgumentException ex) { throw new ActivationException(ex.Message); } } internal static void OpenGenericTypesDoNotContainUnresolvableTypeArguments( Type serviceType, IEnumerable<Registration> registrations, string parameterName) { OpenGenericTypesDoNotContainUnresolvableTypeArguments( serviceType, registrations.Select(registration => registration.ImplementationType), parameterName); } internal static void OpenGenericTypesDoNotContainUnresolvableTypeArguments( Type serviceType, IEnumerable<Type> implementationTypes, string parameterName) { foreach (Type implementationType in implementationTypes) { OpenGenericTypeDoesNotContainUnresolvableTypeArguments( serviceType, implementationType, parameterName); } } internal static void OpenGenericTypeDoesNotContainUnresolvableTypeArguments( Type serviceType, Type implementationType, string? parameterName) { if (serviceType.ContainsGenericParameters() && implementationType.ContainsGenericParameters()) { var builder = new GenericTypeBuilder(serviceType, implementationType); if (!builder.OpenGenericImplementationCanBeAppliedToServiceType()) { string error = StringResources.OpenGenericTypeContainsUnresolvableTypeArguments(implementationType); throw new ArgumentException(error, parameterName); } } } internal static void DecoratorIsNotAnOpenGenericTypeDefinitionWhenTheServiceTypeIsNot( Type serviceType, Type decoratorType, string parameterName) { if (!serviceType.ContainsGenericParameters() && decoratorType.ContainsGenericParameters()) { throw new ArgumentException( StringResources.DecoratorCanNotBeAGenericTypeDefinitionWhenServiceTypeIsNot( serviceType, decoratorType), parameterName); } } internal static void HasFactoryCreatedDecorator( Container container, Type serviceType, Type decoratorType) { try { IsDecorator(container, serviceType, decoratorType, null); } catch (ArgumentException ex) { throw new ActivationException(ex.Message); } } internal static void FactoryReturnsATypeThatIsAssignableFromServiceType( Type serviceType, Type implementationType) { if (!serviceType.IsAssignableFrom(implementationType)) { throw new ActivationException(StringResources.TypeFactoryReturnedIncompatibleType( serviceType, implementationType)); } } internal static void IsDecorator( Container container, Type serviceType, Type decoratorType, string? paramName) { ConstructorInfo decoratorConstructor = container.Options.SelectConstructor(decoratorType); Requires.DecoratesServiceType(serviceType, decoratorConstructor, paramName); } internal static void AreRegistrationsForThisContainer( Container container, IEnumerable<Registration> registrations, string paramName) { foreach (Registration registration in registrations) { IsRegistrationForThisContainer(container, registration, paramName); } } internal static void IsRegistrationForThisContainer( Container container, Registration registration, string paramName) { if (!object.ReferenceEquals(container, registration.Container)) { string message = StringResources.TheSuppliedRegistrationBelongsToADifferentContainer(); throw new ArgumentException(message, paramName); } } [DebuggerStepThrough] internal static void IsValidEnum<TEnum>(TEnum value, string paramName) where TEnum : struct { if (!Enum.GetValues(typeof(TEnum)).Cast<TEnum>().Contains(value)) { throw new ArgumentException( StringResources.ValueInvalidForEnumType(paramName, value, typeof(TEnum))); } } internal static void IsNotPartiallyClosed(Type openGenericServiceType, string paramName) { if (openGenericServiceType.IsPartiallyClosed()) { throw new ArgumentException( StringResources.ServiceTypeCannotBeAPartiallyClosedType(openGenericServiceType), paramName); } } internal static void IsNotPartiallyClosed( Type openGenericServiceType, string paramName, string implementationTypeParamName) { if (openGenericServiceType.IsPartiallyClosed()) { throw new ArgumentException( StringResources.ServiceTypeCannotBeAPartiallyClosedType( openGenericServiceType, paramName, implementationTypeParamName), paramName); } } private static void DecoratesServiceType( Type serviceType, ConstructorInfo decoratorConstructor, string? paramName) { bool decoratesServiceType = DecoratorHelpers.DecoratesServiceType(serviceType, decoratorConstructor); if (!decoratesServiceType) { ThrowMustDecorateServiceType(serviceType, decoratorConstructor, paramName); } } private static void ThrowMustDecorateServiceType( Type serviceType, ConstructorInfo constructor, string? paramName) { int numberOfServiceTypeDependencies = DecoratorHelpers.GetNumberOfServiceTypeDependencies(serviceType, constructor); if (numberOfServiceTypeDependencies == 0) { // We must get the real type to be decorated to prevent the exception message from being // confusing to the user. // At this point we know that the decorator type implements an service type in some way // (either open or closed), so we this call will return at least one record. serviceType = Types.GetBaseTypeCandidates(serviceType, constructor.DeclaringType).First(); ThrowMustContainTheServiceTypeAsArgument(serviceType, constructor, paramName); } else { ThrowMustContainASingleInstanceOfTheServiceTypeAsArgument(serviceType, constructor, paramName); } } private static void ThrowMustContainTheServiceTypeAsArgument( Type serviceType, ConstructorInfo decoratorConstructor, string? paramName) { string message = StringResources.TheConstructorOfTypeMustContainTheServiceTypeAsArgument( decoratorConstructor.DeclaringType, serviceType); throw new ArgumentException(message, paramName); } private static void ThrowMustContainASingleInstanceOfTheServiceTypeAsArgument( Type serviceType, ConstructorInfo decoratorConstructor, string? paramName) { string message = StringResources.TheConstructorOfTypeMustContainASingleInstanceOfTheServiceTypeAsArgument( decoratorConstructor.DeclaringType, serviceType); throw new ArgumentException(message, paramName); } private static void ThrowArgumentNullException(string paramName) { throw new ArgumentNullException(paramName); } private static void ThrowSuppliedElementDoesNotInheritFromOrImplement( Type service, Type implementation, string elementDescription, string paramName) { throw new ArgumentException( StringResources.SuppliedElementDoesNotInheritFromOrImplement( service, implementation, elementDescription), paramName); } private static void ThrowSuppliedTypeDoesNotInheritFromOrImplement( Type service, Type implementation, string paramName) { throw new ArgumentException( StringResources.SuppliedTypeDoesNotInheritFromOrImplement(service, implementation), paramName); } } }
40.955056
123
0.605542
[ "MIT" ]
Bouke/SimpleInjector
src/SimpleInjector/Requires.cs
17,783
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.IO.Pipelines; using System.Runtime; using System.Runtime.Remoting; using System.Text; using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Experiments; using Microsoft.CodeAnalysis.Extensions; using Microsoft.CodeAnalysis.Host; using Microsoft.CodeAnalysis.Serialization; using Microsoft.CodeAnalysis.TodoComments; using Microsoft.ServiceHub.Framework; using Microsoft.VisualStudio.Threading; using Nerdbank.Streams; using Roslyn.Test.Utilities; using Roslyn.Utilities; using StreamJsonRpc; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.Remote.Testing { internal sealed partial class InProcRemoteHostClient : RemoteHostClient, IRemoteHostServiceCallback { private readonly HostWorkspaceServices _workspaceServices; private readonly InProcRemoteServices _inprocServices; private readonly RemoteServiceCallbackDispatcherRegistry _callbackDispatchers; private readonly RemoteEndPoint _endPoint; private readonly TraceSource _logger; public static async Task<RemoteHostClient> CreateAsync(HostWorkspaceServices services, RemoteServiceCallbackDispatcherRegistry callbackDispatchers, TraceListener? traceListener, RemoteHostTestData testData) { var inprocServices = new InProcRemoteServices(services, traceListener, testData); var remoteHostStream = await inprocServices.RequestServiceAsync(WellKnownServiceHubService.RemoteHost).ConfigureAwait(false); var instance = new InProcRemoteHostClient(services, inprocServices, callbackDispatchers, remoteHostStream); // make sure connection is done right var uiCultureLCIDE = 0; var cultureLCID = 0; await instance._endPoint.InvokeAsync( nameof(IRemoteHostService.InitializeGlobalState), new object?[] { uiCultureLCIDE, cultureLCID }, CancellationToken.None).ConfigureAwait(false); instance.Started(); // return instance return instance; } private InProcRemoteHostClient( HostWorkspaceServices services, InProcRemoteServices inprocServices, RemoteServiceCallbackDispatcherRegistry callbackDispatchers, Stream stream) { _workspaceServices = services; _callbackDispatchers = callbackDispatchers; _logger = new TraceSource("Default"); _inprocServices = inprocServices; _endPoint = new RemoteEndPoint(stream, _logger, incomingCallTarget: this); _endPoint.Disconnected += OnDisconnected; _endPoint.StartListening(); } public static async Task<InProcRemoteHostClient> GetTestClientAsync(Workspace workspace) { var client = (InProcRemoteHostClient?)await TryGetClientAsync(workspace, CancellationToken.None).ConfigureAwait(false); Contract.ThrowIfNull(client); return client; } public RemoteWorkspace GetRemoteWorkspace() => TestData.WorkspaceManager.GetWorkspace(); /// <summary> /// Remote API. /// </summary> public Task GetAssetsAsync(int scopeId, Checksum[] checksums, string pipeName, CancellationToken cancellationToken) => RemoteEndPoint.WriteDataToNamedPipeAsync( pipeName, (scopeId, checksums), (writer, data, cancellationToken) => RemoteHostAssetSerialization.WriteDataAsync( writer, _workspaceServices.GetRequiredService<ISolutionAssetStorageProvider>().AssetStorage, _workspaceServices.GetRequiredService<ISerializerService>(), data.scopeId, data.checksums, cancellationToken), cancellationToken); /// <summary> /// Remote API. /// </summary> public Task<bool> IsExperimentEnabledAsync(string experimentName, CancellationToken cancellationToken) => _workspaceServices.GetRequiredService<IExperimentationService>().IsExperimentEnabled(experimentName) ? SpecializedTasks.True : SpecializedTasks.False; public RemoteHostTestData TestData => _inprocServices.TestData; public void RegisterService(RemoteServiceName serviceName, Func<Stream, IServiceProvider, ServiceActivationOptions, ServiceBase> serviceCreator) => _inprocServices.RegisterService(serviceName, serviceCreator); public override RemoteServiceConnection<T> CreateConnection<T>(object? callbackTarget) where T : class => new BrokeredServiceConnection<T>( callbackTarget, _callbackDispatchers, _inprocServices.ServiceBrokerClient, _workspaceServices.GetRequiredService<ISolutionAssetStorageProvider>().AssetStorage, _workspaceServices.GetRequiredService<IErrorReportingService>(), shutdownCancellationService: null, isRemoteHost64Bit: IntPtr.Size == 8, isRemoteHostServerGC: GCSettings.IsServerGC); public override async Task<RemoteServiceConnection> CreateConnectionAsync(RemoteServiceName serviceName, object? callbackTarget, CancellationToken cancellationToken) { // get stream from service hub to communicate service specific information // this is what consumer actually use to communicate information var serviceStream = await _inprocServices.RequestServiceAsync(serviceName).ConfigureAwait(false); return new JsonRpcConnection(_workspaceServices, _logger, callbackTarget, serviceStream, poolReclamation: null); } public override void Dispose() { // we are asked to disconnect. unsubscribe and dispose to disconnect _endPoint.Disconnected -= OnDisconnected; _endPoint.Dispose(); _inprocServices.Dispose(); base.Dispose(); } private void OnDisconnected(JsonRpcDisconnectedEventArgs e) => Dispose(); public sealed class ServiceProvider : IServiceProvider { public readonly TraceSource TraceSource; public readonly RemoteHostTestData TestData; public ServiceProvider(TraceSource traceSource, RemoteHostTestData testData) { TraceSource = traceSource; TestData = testData; } public object GetService(Type serviceType) { if (typeof(TraceSource) == serviceType) { return TraceSource; } if (typeof(RemoteHostTestData) == serviceType) { return TestData; } throw ExceptionUtilities.UnexpectedValue(serviceType); } } private sealed class InProcServiceBroker : IServiceBroker { private readonly InProcRemoteServices _services; public InProcServiceBroker(InProcRemoteServices services) { _services = services; } public event EventHandler<BrokeredServicesChangedEventArgs>? AvailabilityChanged { add { } remove { } } // This method is currently not needed for our IServiceBroker usage patterns. public ValueTask<IDuplexPipe?> GetPipeAsync(ServiceMoniker serviceMoniker, ServiceActivationOptions options, CancellationToken cancellationToken) => throw ExceptionUtilities.Unreachable; public ValueTask<T?> GetProxyAsync<T>(ServiceRpcDescriptor descriptor, ServiceActivationOptions options, CancellationToken cancellationToken) where T : class { var pipePair = FullDuplexStream.CreatePipePair(); var clientConnection = descriptor .WithTraceSource(_services.ServiceProvider.TraceSource) .ConstructRpcConnection(pipePair.Item2); Contract.ThrowIfFalse(options.ClientRpcTarget is null == descriptor.ClientInterface is null); if (descriptor.ClientInterface != null) { Contract.ThrowIfNull(options.ClientRpcTarget); clientConnection.AddLocalRpcTarget(options.ClientRpcTarget); } // Clear RPC target so that the server connection is forced to create a new proxy for the callback // instead of just invoking the callback object directly (this emulates the product that does // not serialize the callback object over). options.ClientRpcTarget = null; // Creates service instance and connects it to the pipe. // We don't need to store the instance anywhere. _ = _services.CreateBrokeredService(descriptor, pipePair.Item1, options); clientConnection.StartListening(); return ValueTaskFactory.FromResult((T?)clientConnection.ConstructRpcClient<T>()); } } private sealed class InProcRemoteServices : IDisposable { public readonly ServiceProvider ServiceProvider; private readonly Dictionary<ServiceMoniker, Func<object>> _inProcBrokeredServicesMap = new(); private readonly Dictionary<ServiceMoniker, BrokeredServiceBase.IFactory> _remoteBrokeredServicesMap = new(); private readonly Dictionary<RemoteServiceName, Func<Stream, IServiceProvider, ServiceActivationOptions, ServiceBase>> _factoryMap = new(); private readonly Dictionary<string, WellKnownServiceHubService> _serviceNameMap = new(); public readonly IServiceBroker ServiceBroker; public readonly ServiceBrokerClient ServiceBrokerClient; public InProcRemoteServices(HostWorkspaceServices workspaceServices, TraceListener? traceListener, RemoteHostTestData testData) { var remoteLogger = new TraceSource("InProcRemoteClient") { Switch = { Level = SourceLevels.Verbose }, }; if (traceListener != null) { remoteLogger.Listeners.Add(traceListener); } ServiceProvider = new ServiceProvider(remoteLogger, testData); ServiceBroker = new InProcServiceBroker(this); #pragma warning disable VSTHRD012 // Provide JoinableTaskFactory where allowed ServiceBrokerClient = new ServiceBrokerClient(ServiceBroker); #pragma warning restore #pragma warning disable CS0618 // Type or member is obsolete RegisterService(WellKnownServiceHubService.RemoteHost, (s, p, o) => new RemoteHostService(s, p)); #pragma warning restore RegisterInProcBrokeredService(SolutionAssetProvider.ServiceDescriptor, () => new SolutionAssetProvider(workspaceServices)); RegisterRemoteBrokeredService(new RemoteAssetSynchronizationService.Factory()); RegisterRemoteBrokeredService(new RemoteAsynchronousOperationListenerService.Factory()); RegisterRemoteBrokeredService(new RemoteSymbolSearchUpdateService.Factory()); RegisterRemoteBrokeredService(new RemoteDesignerAttributeDiscoveryService.Factory()); RegisterRemoteBrokeredService(new RemoteProjectTelemetryService.Factory()); RegisterRemoteBrokeredService(new RemoteTodoCommentsDiscoveryService.Factory()); RegisterRemoteBrokeredService(new RemoteDiagnosticAnalyzerService.Factory()); RegisterRemoteBrokeredService(new RemoteSemanticClassificationService.Factory()); RegisterRemoteBrokeredService(new RemoteSemanticClassificationCacheService.Factory()); RegisterRemoteBrokeredService(new RemoteDocumentHighlightsService.Factory()); RegisterRemoteBrokeredService(new RemoteEncapsulateFieldService.Factory()); RegisterRemoteBrokeredService(new RemoteRenamerService.Factory()); RegisterRemoteBrokeredService(new RemoteConvertTupleToStructCodeRefactoringService.Factory()); RegisterRemoteBrokeredService(new RemoteFindUsagesService.Factory()); RegisterRemoteBrokeredService(new RemoteSymbolFinderService.Factory()); RegisterRemoteBrokeredService(new RemoteNavigateToSearchService.Factory()); RegisterRemoteBrokeredService(new RemoteMissingImportDiscoveryService.Factory()); RegisterRemoteBrokeredService(new RemoteExtensionMethodImportCompletionService.Factory()); RegisterRemoteBrokeredService(new RemoteDependentTypeFinderService.Factory()); RegisterRemoteBrokeredService(new RemoteGlobalNotificationDeliveryService.Factory()); RegisterRemoteBrokeredService(new RemoteCodeLensReferencesService.Factory()); } public void Dispose() => ServiceBrokerClient.Dispose(); public RemoteHostTestData TestData => ServiceProvider.TestData; public void RegisterService(RemoteServiceName name, Func<Stream, IServiceProvider, ServiceActivationOptions, ServiceBase> serviceFactory) { _factoryMap.Add(name, serviceFactory); _serviceNameMap.Add(name.ToString(isRemoteHost64Bit: IntPtr.Size == 8, isRemoteHostServerGC: GCSettings.IsServerGC), name.WellKnownService); } public Task<Stream> RequestServiceAsync(RemoteServiceName serviceName) { var factory = _factoryMap[serviceName]; var streams = FullDuplexStream.CreatePair(); return Task.FromResult<Stream>(new WrappedStream(factory(streams.Item1, ServiceProvider, default), streams.Item2)); } public void RegisterInProcBrokeredService(ServiceDescriptor serviceDescriptor, Func<object> serviceFactory) { _inProcBrokeredServicesMap.Add(serviceDescriptor.Moniker, serviceFactory); } public void RegisterRemoteBrokeredService(BrokeredServiceBase.IFactory serviceFactory) { var moniker = ServiceDescriptors.GetServiceDescriptor(serviceFactory.ServiceType, isRemoteHost64Bit: IntPtr.Size == 8, isRemoteHostServerGC: GCSettings.IsServerGC).Moniker; _remoteBrokeredServicesMap.Add(moniker, serviceFactory); } public object CreateBrokeredService(ServiceRpcDescriptor descriptor, IDuplexPipe pipe, ServiceActivationOptions options) { if (_inProcBrokeredServicesMap.TryGetValue(descriptor.Moniker, out var inProcFactory)) { // This code is similar to service creation implemented in BrokeredServiceBase.FactoryBase. // Currently don't support callback creation as we don't have in-proc service with callbacks yet. Contract.ThrowIfFalse(descriptor.ClientInterface == null); var serviceConnection = descriptor.WithTraceSource(ServiceProvider.TraceSource).ConstructRpcConnection(pipe); var service = inProcFactory(); serviceConnection.AddLocalRpcTarget(service); serviceConnection.StartListening(); return service; } if (_remoteBrokeredServicesMap.TryGetValue(descriptor.Moniker, out var remoteFactory)) { return remoteFactory.Create(pipe, ServiceProvider, options, ServiceBroker); } throw ExceptionUtilities.UnexpectedValue(descriptor.Moniker); } private sealed class WrappedStream : Stream { private readonly IDisposable _service; private readonly Stream _stream; public WrappedStream(IDisposable service, Stream stream) { // tie service's lifetime with that of stream _service = service; _stream = stream; } public override long Position { get { return _stream.Position; } set { _stream.Position = value; } } public override int ReadTimeout { get { return _stream.ReadTimeout; } set { _stream.ReadTimeout = value; } } public override int WriteTimeout { get { return _stream.WriteTimeout; } set { _stream.WriteTimeout = value; } } public override bool CanRead => _stream.CanRead; public override bool CanSeek => _stream.CanSeek; public override bool CanWrite => _stream.CanWrite; public override long Length => _stream.Length; public override bool CanTimeout => _stream.CanTimeout; public override void Flush() => _stream.Flush(); public override Task FlushAsync(CancellationToken cancellationToken) => _stream.FlushAsync(cancellationToken); public override long Seek(long offset, SeekOrigin origin) => _stream.Seek(offset, origin); public override void SetLength(long value) => _stream.SetLength(value); public override int ReadByte() => _stream.ReadByte(); public override void WriteByte(byte value) => _stream.WriteByte(value); public override int Read(byte[] buffer, int offset, int count) => _stream.Read(buffer, offset, count); public override void Write(byte[] buffer, int offset, int count) => _stream.Write(buffer, offset, count); public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => _stream.ReadAsync(buffer, offset, count, cancellationToken); public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => _stream.WriteAsync(buffer, offset, count, cancellationToken); #if NET5_0 // nullability annotations differ public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) => _stream.BeginRead(buffer, offset, count, callback, state); public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) => _stream.BeginWrite(buffer, offset, count, callback, state); #else public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object? state) => _stream.BeginRead(buffer, offset, count, callback, state); public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object? state) => _stream.BeginWrite(buffer, offset, count, callback, state); #endif public override int EndRead(IAsyncResult asyncResult) => _stream.EndRead(asyncResult); public override void EndWrite(IAsyncResult asyncResult) => _stream.EndWrite(asyncResult); public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) => _stream.CopyToAsync(destination, bufferSize, cancellationToken); public override void Close() { _service.Dispose(); _stream.Close(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); _service.Dispose(); _stream.Dispose(); } } } } }
49.804401
223
0.663378
[ "MIT" ]
louis-z/roslyn
src/Workspaces/CoreTestUtilities/Remote/InProcRemostHostClient.cs
20,372
C#
using System; using BenchmarkDotNet.Characteristics; using BenchmarkDotNet.Jobs; namespace BenchmarkDotNet.Engines { public class EngineParameters { public IHost Host { get; set; } public Action<long> MainAction { get; set; } public Action Dummy1Action { get; set; } public Action Dummy2Action { get; set; } public Action Dummy3Action { get; set; } public Action<long> IdleAction { get; set; } public Job TargetJob { get; set; } = Job.Default; public long OperationsPerInvoke { get; set; } = 1; public Action GlobalSetupAction { get; set; } = null; public Action GlobalCleanupAction { get; set; } = null; public Action IterationSetupAction { get; set; } = null; public Action IterationCleanupAction { get; set; } = null; public IResolver Resolver { get; set; } public bool MeasureGcStats { get; set; } } }
38.75
66
0.643011
[ "MIT" ]
AlexGhiondea/BenchmarkDotNet
src/BenchmarkDotNet.Core/Engines/EngineParameters.cs
930
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using NewLife.Cube.Entity; using NewLife.Web; using XCode; using XCode.Membership; #if __CORE__ using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using NewLife.Cube.Com; using NewLife.Cube.Extensions; #else using System.Web; using System.Web.Mvc; using System.Web.Security; #endif namespace NewLife.Cube.Admin.Controllers { /// <summary>用户控制器</summary> [DisplayName("用户")] [Description("系统基于角色授权,每个角色对不同的功能模块具备添删改查以及自定义权限等多种权限设定。")] [Area("Admin")] public class UserController : EntityController<UserX> { static UserController() { MenuOrder = 100; ListFields.RemoveField("Phone"); ListFields.RemoveField("Code"); ListFields.RemoveField("StartTime"); ListFields.RemoveField("EndTime"); ListFields.RemoveField("RegisterTime"); ListFields.RemoveField("Question"); ListFields.RemoveField("Answer"); } /// <summary>搜索数据集</summary> /// <param name="p"></param> /// <returns></returns> protected override IEnumerable<UserX> Search(Pager p) { var id = p["id"].ToInt(-1); if (id > 0) { var list = new List<UserX>(); var entity = UserX.FindByID(id); if (entity != null) list.Add(entity); return list; } return UserX.Search(p["Q"], p["RoleID"].ToInt(-1), null, p["dtStart"].ToDateTime(), p["dtEnd"].ToDateTime(), p); } /// <summary>表单页视图。</summary> /// <param name="entity"></param> /// <returns></returns> protected override ActionResult FormView(UserX entity) { // 清空密码,不向浏览器输出 //entity.Password = null; entity["Password"] = null; return base.FormView(entity); } #region 登录注销 /// <summary>登录</summary> /// <returns></returns> [AllowAnonymous] public ActionResult Login() { var returnUrl = GetRequest("r"); // 如果已登录,直接跳转 if (ManageProvider.User != null) { if (Url.IsLocalUrl(returnUrl)) return Redirect(returnUrl); else return RedirectToAction("Index", "Index", new { page = returnUrl }); } // 如果禁用本地登录,且只有一个第三方登录,直接跳转,构成单点登录 if (!Setting.Current.AllowLogin) { var ms = OAuthConfig.Current.Items.Where(e => !e.AppID.IsNullOrEmpty()).ToList(); if (ms.Count == 0) throw new Exception("禁用了本地密码登录,且没有配置第三方登录"); // 只有一个,跳转 if (ms.Count == 1) { //var url = $"~/Sso/Login?name={ms[0].Name}"; //if (!returnUrl.IsNullOrEmpty()) url += "&r=" + HttpUtility.UrlEncode(returnUrl); //return Redirect(url); return RedirectToAction("Login", "Sso", new { area = "", name = ms[0].Name, r = returnUrl }); } } ViewBag.IsShowTip = UserX.Meta.Count == 1; ViewBag.ReturnUrl = returnUrl; return View(); } /// <summary>登录</summary> /// <param name="username"></param> /// <param name="password"></param> /// <param name="remember"></param> /// <returns></returns> [HttpPost] [AllowAnonymous] public ActionResult Login(String username, String password, Boolean? remember) { var returnUrl = GetRequest("r"); try { var provider = ManageProvider.Provider; if (ModelState.IsValid && provider.Login(username, password, remember ?? false) != null) { //FormsAuthentication.SetAuthCookie(username, remember ?? false); if (Url.IsLocalUrl(returnUrl)) return Redirect(returnUrl); // 不要嵌入自己 if (returnUrl.EndsWithIgnoreCase("/Admin", "/Admin/User/Login")) returnUrl = null; return RedirectToAction("Index", "Index", new { page = returnUrl }); } // 如果我们进行到这一步时某个地方出错,则重新显示表单 ModelState.AddModelError("username", "提供的用户名或密码不正确。"); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); } return View(); } /// <summary>注销</summary> /// <returns></returns> [AllowAnonymous] public ActionResult Logout() { var returnUrl = GetRequest("r"); // 如果是单点登录,则走单点登录注销 var name = GetSession<String>("Cube_Sso"); if (!name.IsNullOrEmpty()) return RedirectToAction("Logout", "Sso", new { area = "", name, r = returnUrl }); ManageProvider.Provider.Logout(); if (!returnUrl.IsNullOrEmpty()) return Redirect(returnUrl); return RedirectToAction(nameof(Login)); } #endregion /// <summary>用户资料</summary> /// <param name="id"></param> /// <returns></returns> [AllowAnonymous] public ActionResult Info(Int32? id) { if (id == null || id.Value <= 0) throw new Exception("无效用户编号!"); var user = ManageProvider.User; if (user == null) return RedirectToAction("Login"); if (id.Value != user.ID) throw new Exception("禁止修改非当前登录用户资料"); user = UserX.FindByKeyForEdit(id.Value); if (user == null) throw new Exception("无效用户编号!"); //user.Password = null; user["Password"] = null; // 用于显示的列 if (ViewBag.Fields == null) ViewBag.Fields = GetFields(true); ViewBag.Factory = UserX.Meta.Factory; // 第三方绑定 var ucs = UserConnect.FindAllByUserID(user.ID); ViewBag.Binds = ucs; return View(user); } /// <summary>用户资料</summary> /// <param name="user"></param> /// <returns></returns> [HttpPost] [AllowAnonymous] public ActionResult Info(UserX user) { var cur = ManageProvider.User; if (cur == null) return RedirectToAction("Login"); if (user.ID != cur.ID) throw new Exception("禁止修改非当前登录用户资料"); var entity = user as IEntity; if (entity.Dirtys["RoleID"]) throw new Exception("禁止修改角色!"); if (entity.Dirtys["Enable"]) throw new Exception("禁止修改禁用!"); user.Update(); return Info(user.ID); } /// <summary>注册</summary> /// <param name="email"></param> /// <param name="username"></param> /// <param name="password"></param> /// <param name="password2"></param> /// <returns></returns> [HttpPost] [AllowAnonymous] public ActionResult Register(String email, String username, String password, String password2) { var set = Setting.Current; if (!set.AllowRegister) throw new Exception("禁止注册!"); try { if (String.IsNullOrEmpty(email)) throw new ArgumentNullException("email", "邮箱地址不能为空!"); if (String.IsNullOrEmpty(username)) throw new ArgumentNullException("username", "用户名不能为空!"); if (String.IsNullOrEmpty(password)) throw new ArgumentNullException("password", "密码不能为空!"); if (String.IsNullOrEmpty(password2)) throw new ArgumentNullException("password2", "重复密码不能为空!"); if (password != password2) throw new ArgumentOutOfRangeException("password2", "两次密码必须一致!"); var user = new UserX() { Name = username, Password = password.MD5(), Mail = email, RoleID = set.DefaultRole, Enable = true }; user.Register(); // 注册成功 } catch (ArgumentException aex) { ModelState.AddModelError(aex.ParamName, aex.Message); } return View("Login"); } /// <summary>清空密码</summary> /// <param name="id"></param> /// <returns></returns> [EntityAuthorize(PermissionFlags.Update)] public ActionResult ClearPassword(Int32 id) { if (ManageProvider.User.RoleName != "管理员") throw new Exception("清除密码操作需要管理员权限,非法操作!"); // 前面表单可能已经清空密码 var user = UserX.FindByID(id); //user.Password = "nopass"; user.Password = null; user.SaveWithoutValid(); return RedirectToAction("Edit", new { id }); } /// <summary>批量启用</summary> /// <param name="keys"></param> /// <returns></returns> [EntityAuthorize(PermissionFlags.Update)] public ActionResult EnableSelect(String keys) { return EnableOrDisableSelect(); } /// <summary>批量禁用</summary> /// <param name="keys"></param> /// <returns></returns> [EntityAuthorize(PermissionFlags.Update)] public ActionResult DisableSelect(String keys) { return EnableOrDisableSelect(false); } private ActionResult EnableOrDisableSelect(Boolean isEnable = true) { var count = 0; var ids = GetRequest("keys").SplitAsInt(); if (ids.Length > 0) { Parallel.ForEach(ids, id => { var user = UserX.FindByID(id); if (user != null && user.Enable != isEnable) { user.Enable = isEnable; user.Save(); Interlocked.Increment(ref count); } }); } return JsonRefresh("共{1}[{0}]个用户".F(count, isEnable ? "启用" : "禁用")); } } }
33.676101
125
0.503035
[ "MIT" ]
NewLifeX/X_NET40
NewLife.Cube/Areas/Admin/Controllers/UserController.cs
11,491
C#
using System.Reflection; namespace N_Tier.Application.Services.Impl; public class TemplateService : ITemplateService { private readonly string _templatesPath; public TemplateService() { var projectPath = Directory.GetParent(Directory.GetCurrentDirectory()).FullName; var templateProject = Assembly.GetExecutingAssembly().GetName().Name; _templatesPath = Path.Combine(projectPath, templateProject, "Templates"); } public async Task<string> GetTemplateAsync(string templateName) { using var reader = new StreamReader(Path.Combine(_templatesPath, templateName)); return await reader.ReadToEndAsync(); } public string ReplaceInTemplate(string input, IDictionary<string, string> replaceWords) { var response = string.Empty; foreach (var temp in replaceWords) response = input.Replace(temp.Key, temp.Value); return response; } }
27.911765
91
0.704953
[ "MIT" ]
nuyonu/N-Tier
src/N-Tier.Application/Services/Impl/TemplateService.cs
951
C#
/*******************************************************} { } { HCView V1.1 作者:荆通 } { } { 本代码遵循BSD协议,你可以加入QQ群 649023932 } { 来获取更多的技术交流 2018-5-4 } { } { 文档形状对象管理单元 } { } {*******************************************************/ using HC.Win32; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Windows.Forms; using System.Xml; namespace HC.View { public enum HCShapeStyle : byte { /// <summary> 无形状 </summary> hssNone = 0, /// <summary> 直线 </summary> hssLine = 1, /// <summary> 矩形 </summary> hssRectangle = 2, /// <summary> 椭圆 </summary> hssEllipse = 3, /// <summary> 多边形 </summary> hssPolygon = 4 } public enum HCStructState : byte { /// <summary> 构建停止 </summary> hstcStop = 0, /// <summary> 构建开始 </summary> hstcStart = 1, /// <summary> 构建中 </summary> hstcStructing = 2 } public class HCShape { private byte FVersion; private HCShapeStyle FStyle; private bool FActive; private Color FColor; public static byte PointSize = 5; private HCStructState FStructState; private EventHandler FOnStructOver; protected virtual void PaintAnchor(HCCanvas aCanvas, RECT aRect) { } protected virtual void SetActive(bool value) { if (FActive != value) { FActive = value; if (!value) FStructState = HCStructState.hstcStop; } } protected virtual void SetColor(Color value) { if (FColor != value) FColor = value; } protected byte Version { get { return FVersion; } set { FVersion = value; } } protected HCStructState StructState { get { return FStructState; } set { FStructState = value; } } public Cursor Cursor; public HCShape() { FStyle = HCShapeStyle.hssNone; FStructState = HCStructState.hstcStop; FVersion = 0; FColor = Color.Black; Cursor = Cursors.Default; } public virtual void Assign(HCShape source) { FStyle = source.Style; FVersion = source.Version; FColor = source.Color; } public virtual bool MouseDown(MouseEventArgs e) { Active = true; return FActive; } public virtual bool MouseMove(MouseEventArgs e) { return FActive; } public virtual bool MouseUp(MouseEventArgs e) { return FActive; } public virtual bool KeyDown(KeyEventArgs e) { return false; } public virtual bool KeyPress(KeyEventArgs e) { return false; } public virtual bool KeyUp(KeyEventArgs e) { return false; } public virtual void PaintTo(HCCanvas aCanvas, RECT aRect, PaintInfo aPaintInfo) { } public virtual bool PointInClient(int x, int y) { return HC.PtInRect(ClientRect(), x, y); } public virtual RECT ClientRect() { return HC.Bounds(0, 0, 0, 0); } public virtual void SaveToStream(Stream aStream) { if (FStyle == HCShapeStyle.hssNone) throw new Exception("HCShape保存失败,无效的样式值!"); aStream.WriteByte((byte)FStyle); aStream.WriteByte(FVersion); HC.HCSaveColorToStream(aStream, FColor); } public virtual void LoadFromStream(Stream aStream) { FStyle = (HCShapeStyle)aStream.ReadByte(); FVersion = (byte)aStream.ReadByte(); HC.HCLoadColorFromStream(aStream, ref FColor); } public virtual void ToXml(XmlElement aNode) { aNode.SetAttribute("style", ((byte)FStyle).ToString()); aNode.SetAttribute("ver", FVersion.ToString()); aNode.SetAttribute("color", HC.HCColorToRGBString(FColor)); } public virtual void ParseXml(XmlElement aNode) { FStyle = (HCShapeStyle)byte.Parse(aNode.Attributes["style"].Value); FVersion = byte.Parse(aNode.Attributes["ver"].Value); FColor = HC.HCRGBStringToColor(aNode.Attributes["color"].Value); } public virtual void StructStart() { FStructState = HCStructState.hstcStart; } public virtual void StructOver() { FStructState = HCStructState.hstcStop; if (FOnStructOver != null) FOnStructOver(this, null); } public HCShapeStyle Style { get { return FStyle; } set { FStyle = value; } } public bool Active { get { return FActive; } set { SetActive(value); } } public Color Color { get { return FColor; } set { SetColor(value); } } public EventHandler OnStructOver { get { return FOnStructOver; } set { FOnStructOver = value; } } } public enum HCShapeLineObj : byte { sloNone = 0, sloLine = 1, sloStart = 2, sloEnd = 3 } public class HCShapeLine : HCShape { private POINT FStartPt, FEndPt, FMousePt; private HCShapeLineObj FActiveOjb; private byte FWidth; private HCPenStyle FLineStyle; private void SetWidth(byte value) { if (FWidth != value) FWidth = value; } private void SetLineStyle(HCPenStyle value) { if (FLineStyle != value) FLineStyle = value; } protected override void PaintAnchor(HCCanvas aCanvas, RECT aRect) { aCanvas.Pen.BeginUpdate(); try { aCanvas.Pen.Color = Color.Black; aCanvas.Pen.Width = 1; aCanvas.Pen.Style = HCPenStyle.psSolid; aCanvas.Brush.Color = Color.White; } finally { aCanvas.Pen.EndUpdate(); } aCanvas.Rectangle(FStartPt.X + aRect.Left - PointSize, FStartPt.Y + aRect.Top - PointSize, FStartPt.X + aRect.Left + PointSize, FStartPt.Y + aRect.Top + PointSize); aCanvas.Rectangle(FEndPt.X + aRect.Left - PointSize, FEndPt.Y + aRect.Top - PointSize, FEndPt.X + aRect.Left + PointSize, FEndPt.Y + aRect.Top + PointSize); } protected override void SetActive(bool value) { base.SetActive(value); if (!this.Active) FActiveOjb = HCShapeLineObj.sloNone; } protected virtual HCShapeLineObj GetObjAt(int x, int y) { HCShapeLineObj vResult = HCShapeLineObj.sloNone; if (HC.PtInRect(new RECT(FStartPt.X - PointSize, FStartPt.Y - PointSize, FStartPt.X + PointSize, FStartPt.Y + PointSize), new POINT(x, y))) vResult = HCShapeLineObj.sloStart; else if (HC.PtInRect(new RECT(FEndPt.X - PointSize, FEndPt.Y - PointSize, FEndPt.X + PointSize, FEndPt.Y + PointSize), new POINT(x, y))) vResult = HCShapeLineObj.sloEnd; else { POINT[] vPointArr = new POINT[4]; vPointArr[0] = new POINT(FStartPt.X - PointSize, FStartPt.Y); vPointArr[1] = new POINT(FStartPt.X + PointSize, FStartPt.Y); vPointArr[2] = new POINT(FEndPt.X + PointSize, FEndPt.Y); vPointArr[3] = new POINT(FEndPt.X - PointSize, FEndPt.Y); IntPtr vRgn = GDI.CreatePolygonRgn(vPointArr, 4, GDI.WINDING); try { if (GDI.PtInRegion(vRgn, x, y)) vResult = HCShapeLineObj.sloLine; } finally { GDI.DeleteObject(vRgn); } } return vResult; } public HCShapeLine() : base() { Style = HCShapeStyle.hssLine; FStartPt = new POINT(0, 0); FEndPt = new POINT(0, 0); FWidth = 1; FActiveOjb = HCShapeLineObj.sloNone; FLineStyle = HCPenStyle.psSolid; } public HCShapeLine(POINT aStartPt, POINT aEndPt) : this() { FStartPt = aStartPt; FEndPt = aEndPt; } public override void Assign(HCShape source) { base.Assign(source); FStartPt.X = (source as HCShapeLine).FStartPt.X; FStartPt.Y = (source as HCShapeLine).FStartPt.Y; FEndPt.X = (source as HCShapeLine).FEndPt.X; FEndPt.Y = (source as HCShapeLine).FEndPt.Y; } public override bool MouseDown(MouseEventArgs e) { if (e.Button != MouseButtons.Left) return false; bool vResult = false; if (StructState != HCStructState.hstcStop) // 正在构建 { if (StructState == HCStructState.hstcStart) // 开妈构建 { FStartPt = new POINT(e.X, e.Y); FEndPt = new POINT(e.X, e.Y); StructState = HCStructState.hstcStructing; } else // 构建进行中按下,完成构建 StructOver(); vResult = true; } else { HCShapeLineObj vLineObje = GetObjAt(e.X, e.Y); if (FActiveOjb != vLineObje) { FActiveOjb = vLineObje; Active = FActiveOjb != HCShapeLineObj.sloNone; vResult = Active; } else vResult = vLineObje != HCShapeLineObj.sloNone; if ((vResult) && (FActiveOjb == HCShapeLineObj.sloLine)) { FMousePt.X = e.X; FMousePt.Y = e.Y; } } return vResult; } public override bool MouseMove(MouseEventArgs e) { if (StructState == HCStructState.hstcStructing) { FEndPt = new POINT(e.X, e.Y); return true; } bool vResult = false; if ((e.Button == MouseButtons.Left) && (Control.ModifierKeys == Keys.None) && (FActiveOjb != HCShapeLineObj.sloNone)) { vResult = true; switch (FActiveOjb) { case HCShapeLineObj.sloLine: FStartPt.X = FStartPt.X + e.X - FMousePt.X; FStartPt.Y = FStartPt.Y + e.Y - FMousePt.Y; FEndPt.X = FEndPt.X + e.X - FMousePt.X; FEndPt.Y = FEndPt.Y + e.Y - FMousePt.Y; FMousePt.X = e.X; FMousePt.Y = e.Y; break; case HCShapeLineObj.sloStart: FStartPt.X = e.X; FStartPt.Y = e.Y; break; case HCShapeLineObj.sloEnd: FEndPt.X = e.X; FEndPt.Y = e.Y; break; } } else { HCShapeLineObj vLineOjb = GetObjAt(e.X, e.Y); if (Active && ((vLineOjb == HCShapeLineObj.sloStart) || (vLineOjb == HCShapeLineObj.sloEnd))) this.Cursor = Cursors.Cross; else if (vLineOjb != HCShapeLineObj.sloNone) this.Cursor = Cursors.SizeAll; vResult = vLineOjb != HCShapeLineObj.sloNone; } return vResult; } public override bool MouseUp(MouseEventArgs e) { return false; } public override void PaintTo(HCCanvas aCanvas, RECT aRect, PaintInfo aPaintInfo) { aCanvas.Pen.BeginUpdate(); try { aCanvas.Pen.Color = Color; aCanvas.Pen.Width = FWidth; aCanvas.Pen.Style = FLineStyle; } finally { aCanvas.Pen.EndUpdate(); } aCanvas.MoveTo(FStartPt.X + aRect.Left, FStartPt.Y + aRect.Top); aCanvas.LineTo(FEndPt.X + aRect.Left, FEndPt.Y + aRect.Top); if ((!aPaintInfo.Print) && (this.Active)) PaintAnchor(aCanvas, aRect); } public override bool PointInClient(int x, int y) { return GetObjAt(x, y) != HCShapeLineObj.sloNone; } public override RECT ClientRect() { RECT vResult = new RECT(); if (FStartPt.X < FEndPt.X) { vResult.Left = FStartPt.X; vResult.Right = FEndPt.X; } else { vResult.Left = FEndPt.X; vResult.Right = FStartPt.X; } if (FStartPt.Y < FEndPt.Y) { vResult.Top = FStartPt.Y; vResult.Bottom = FEndPt.Y; } else { vResult.Top = FEndPt.Y; vResult.Bottom = FStartPt.Y; } return vResult; } public override void SaveToStream(Stream aStream) { base.SaveToStream(aStream); aStream.WriteByte(FWidth); aStream.WriteByte((byte)FLineStyle); byte[] vBuffer = BitConverter.GetBytes(FStartPt.X); aStream.Write(vBuffer, 0, vBuffer.Length); vBuffer = BitConverter.GetBytes(FStartPt.Y); aStream.Write(vBuffer, 0, vBuffer.Length); vBuffer = BitConverter.GetBytes(FEndPt.X); aStream.Write(vBuffer, 0, vBuffer.Length); vBuffer = BitConverter.GetBytes(FEndPt.Y); aStream.Write(vBuffer, 0, vBuffer.Length); } public override void LoadFromStream(Stream aStream) { base.LoadFromStream(aStream); FWidth = (byte)aStream.ReadByte(); FLineStyle = (HCPenStyle)aStream.ReadByte(); byte[] vBuffer = BitConverter.GetBytes(FStartPt.X); aStream.Read(vBuffer, 0, vBuffer.Length); FStartPt.X = BitConverter.ToInt32(vBuffer, 0); aStream.Read(vBuffer, 0, vBuffer.Length); FStartPt.Y = BitConverter.ToInt32(vBuffer, 0); aStream.Read(vBuffer, 0, vBuffer.Length); FEndPt.X = BitConverter.ToInt32(vBuffer, 0); aStream.Read(vBuffer, 0, vBuffer.Length); FEndPt.Y = BitConverter.ToInt32(vBuffer, 0); } public override void ToXml(XmlElement aNode) { base.ToXml(aNode); aNode.SetAttribute("width", FWidth.ToString()); aNode.SetAttribute("ls", ((byte)FLineStyle).ToString()); aNode.SetAttribute("sx", FStartPt.X.ToString()); aNode.SetAttribute("sy", FStartPt.Y.ToString()); aNode.SetAttribute("ex", FEndPt.X.ToString()); aNode.SetAttribute("ey", FEndPt.Y.ToString()); } public override void ParseXml(XmlElement aNode) { base.ParseXml(aNode); FWidth = byte.Parse(aNode.Attributes["width"].Value); FLineStyle = (HCPenStyle)byte.Parse(aNode.Attributes["ls"].Value); FStartPt.X = int.Parse(aNode.Attributes["sx"].Value); FStartPt.Y = int.Parse(aNode.Attributes["sy"].Value); FEndPt.X = int.Parse(aNode.Attributes["ex"].Value); FEndPt.Y = int.Parse(aNode.Attributes["ey"].Value); } public POINT StartPt { get { return FStartPt; } set { FStartPt = value; } } public POINT EndPt { get { return FEndPt; } set { FEndPt = value; } } public byte Width { get { return FWidth; } set { SetWidth(value); } } public HCPenStyle LineStyle { get { return FLineStyle; } set { SetLineStyle(value); } } public HCShapeLineObj ActiveObj { get { return FActiveOjb; } } } public class HCShapeRectangle : HCShapeLine { private Color FBackColor; protected override HCShapeLineObj GetObjAt(int x, int y) { HCShapeLineObj vResult = HCShapeLineObj.sloNone; if (HC.PtInRect(new RECT(StartPt.X - PointSize, StartPt.Y - PointSize, StartPt.X + PointSize, StartPt.Y + PointSize), new POINT(x, y))) vResult = HCShapeLineObj.sloStart; else if (HC.PtInRect(new RECT(EndPt.X - PointSize, EndPt.Y - PointSize, EndPt.X + PointSize, EndPt.Y + PointSize), new POINT(x, y))) vResult = HCShapeLineObj.sloEnd; else { RECT vRect = ClientRect(); vRect.Inflate(PointSize, PointSize); if (HC.PtInRect(vRect, x, y)) // 在边框点宽度外 { vRect.Inflate(-PointSize - PointSize, -PointSize - PointSize); if (!HC.PtInRect(vRect, x, y)) vResult = HCShapeLineObj.sloLine; } } return vResult; } public HCShapeRectangle() : base() { Style = HCShapeStyle.hssRectangle; FBackColor = HC.HCTransparentColor; } public override void PaintTo(HCCanvas aCanvas, RECT aRect, PaintInfo aPaintInfo) { aCanvas.Pen.BeginUpdate(); try { aCanvas.Pen.Color = Color; aCanvas.Pen.Width = Width; aCanvas.Pen.Style = LineStyle; } finally { aCanvas.Pen.EndUpdate(); } if (FBackColor == HC.HCTransparentColor) aCanvas.Brush.Style = HCBrushStyle.bsClear; aCanvas.Rectangle(StartPt.X + aRect.Left, StartPt.Y + aRect.Top, EndPt.X + aRect.Left, EndPt.Y + aRect.Top); if (!aPaintInfo.Print && this.Active) PaintAnchor(aCanvas, aRect); } public Color BackColor { get { return FBackColor; } set { FBackColor = value; } } } public class HCShapeEllipse : HCShapeRectangle { protected override HCShapeLineObj GetObjAt(int x, int y) { HCShapeLineObj vResult = HCShapeLineObj.sloNone; if (HC.PtInRect(new RECT(StartPt.X - PointSize, StartPt.Y - PointSize, StartPt.X + PointSize, StartPt.Y + PointSize), new POINT(x, y))) vResult = HCShapeLineObj.sloStart; else if (HC.PtInRect(new RECT(EndPt.X - PointSize, EndPt.Y - PointSize, EndPt.X + PointSize, EndPt.Y + PointSize), new POINT(x, y))) vResult = HCShapeLineObj.sloEnd; else { RECT vRect = ClientRect(); vRect.Inflate(PointSize, PointSize); IntPtr vRgn1 = GDI.CreateEllipticRgnIndirect(ref vRect); try { if (GDI.PtInRegion(vRgn1, x, y)) // 在外围 { vRect.Inflate(-PointSize - PointSize, -PointSize - PointSize); IntPtr vRgn2 = GDI.CreateEllipticRgnIndirect(ref vRect); try { if (!GDI.PtInRegion(vRgn2, x, y)) // 不在内围 vResult = HCShapeLineObj.sloLine; } finally { GDI.DeleteObject(vRgn2); } } } finally { GDI.DeleteObject(vRgn1); } } return vResult; } public HCShapeEllipse() : base() { Style = HCShapeStyle.hssEllipse; } public override void PaintTo(HCCanvas aCanvas, RECT aRect, PaintInfo aPaintInfo) { aCanvas.Pen.BeginUpdate(); try { aCanvas.Pen.Color = Color; aCanvas.Pen.Width = Width; aCanvas.Pen.Style = LineStyle; } finally { aCanvas.Pen.EndUpdate(); } if (BackColor == HC.HCTransparentColor) aCanvas.Brush.Style = HCBrushStyle.bsClear; aCanvas.Ellipse(StartPt.X + aRect.Left, StartPt.Y + aRect.Top, EndPt.X + aRect.Left, EndPt.Y + aRect.Top); if (!aPaintInfo.Print && this.Active) PaintAnchor(aCanvas, aRect); } } public class HCPoint { public int X, Y; public HCPoint(int ax, int ay) { Init(ax, ay); } public void Init(int ax, int ay) { X = ax; Y = ay; } public void Offset(int ax, int ay) { X += ax; Y += ay; } } public class HCShapePolygon : HCShape { POINT FMousePt; List<HCPoint> FPoints; byte FWidth; HCPenStyle FLineStyle; int FActivePointIndex, FActiveLineIndex; private void OffsetPoints(int x, int y) { for (int i = 0; i < FPoints.Count; i++) FPoints[i].Offset(x, y); } private void SetWidth(byte value) { if (FWidth != value) FWidth = value; } private void SetLineStyle(HCPenStyle value) { if (FLineStyle != value) FLineStyle = value; } protected override void PaintAnchor(HCCanvas aCanvas, RECT aRect) { aCanvas.Pen.BeginUpdate(); try { aCanvas.Pen.Color = Color.Black; aCanvas.Pen.Width = 1; aCanvas.Pen.Style = HCPenStyle.psSolid; aCanvas.Brush.Color = Color.White; } finally { aCanvas.Pen.EndUpdate(); } for (int i = 0; i < FPoints.Count; i++) { aCanvas.Rectangle(FPoints[i].X + aRect.Left - PointSize, FPoints[i].Y + aRect.Top - PointSize, FPoints[i].X + aRect.Left + PointSize, FPoints[i].Y + aRect.Top + PointSize); } if (FActivePointIndex >= 0) { aCanvas.Pen.Color = Color.Red; if (StructState == HCStructState.hstcStructing) aCanvas.Pen.Style = HCPenStyle.psDot; aCanvas.Rectangle( FPoints[FActivePointIndex].X + aRect.Left - PointSize, FPoints[FActivePointIndex].Y + aRect.Top - PointSize, FPoints[FActivePointIndex].X + aRect.Left + PointSize, FPoints[FActivePointIndex].Y + aRect.Top + PointSize); } } protected override void SetActive(bool value) { base.SetActive(value); if (!this.Active) { FActivePointIndex = -1; FActiveLineIndex = -1; } } protected int GetPointAt(int x, int y) { HCPoint vPoint = null; for (int i = 0; i < FPoints.Count; i++) { vPoint = FPoints[i]; if (HC.PtInRect(new RECT(vPoint.X - PointSize, vPoint.Y - PointSize, vPoint.X + PointSize, vPoint.Y + PointSize), new POINT(x, y))) { return i; } } return -1; } protected int GetLineAt(int x, int y) { POINT[] vPointArr = new POINT[4]; IntPtr vRgn = IntPtr.Zero; for (int i = 0; i < FPoints.Count; i++) { vPointArr[0] = new POINT(FPoints[i].X - PointSize, FPoints[i].Y); vPointArr[1] = new POINT(FPoints[i].X + PointSize, FPoints[i].Y); if (i == FPoints.Count - 1) { vPointArr[2] = new POINT(FPoints[0].X + PointSize, FPoints[0].Y); vPointArr[3] = new POINT(FPoints[0].X - PointSize, FPoints[0].Y); } else { vPointArr[2] = new POINT(FPoints[i + 1].X + PointSize, FPoints[i + 1].Y); vPointArr[3] = new POINT(FPoints[i + 1].X - PointSize, FPoints[i + 1].Y); } vRgn = GDI.CreatePolygonRgn(vPointArr, 4, GDI.WINDING); try { if (GDI.PtInRegion(vRgn, x, y)) return i; } finally { GDI.DeleteObject(vRgn); } } return -1; } protected List<HCPoint> Points { get { return FPoints; } } public HCShapePolygon() : base() { Style = HCShapeStyle.hssPolygon; FWidth = 1; FLineStyle = HCPenStyle.psSolid; FPoints = new List<HCPoint>(); FActivePointIndex = -1; FActiveLineIndex = -1; } public override void Assign(HCShape source) { base.Assign(source); FPoints.Clear(); for (int i = 0; i < (source as HCShapePolygon).Points.Count; i++) { HCPoint vPoint = new HCPoint( (source as HCShapePolygon).Points[i].X, (source as HCShapePolygon).Points[i].Y); FPoints.Add(vPoint); } } public override bool MouseDown(MouseEventArgs e) { if (e.Button == MouseButtons.Right) { if (StructState == HCStructState.hstcStructing) StructOver(); return false; } if (e.Button != MouseButtons.Left) return false; bool vResult = false; if (StructState != HCStructState.hstcStop) // 没有处于构建状态 { if (StructState == HCStructState.hstcStart) // 开始构建 { HCPoint vPoint = new HCPoint(e.X, e.Y); FPoints.Add(vPoint); vPoint = new HCPoint(e.X, e.Y); FPoints.Add(vPoint); FActivePointIndex = FPoints.Count - 1; StructState = HCStructState.hstcStructing; } else if (StructState == HCStructState.hstcStructing) { HCPoint vPoint = new HCPoint(e.X, e.Y); FPoints.Add(vPoint); FActivePointIndex = FPoints.Count - 1; } else StructOver(); vResult = true; } else { int vIndex = GetPointAt(e.X, e.Y); if (FActivePointIndex != vIndex) { FActivePointIndex = vIndex; Active = FActivePointIndex >= 0; vResult = Active; } else vResult = vIndex >= 0; if (!vResult) // 是否在线段上 { vIndex = GetLineAt(e.X, e.Y); if (FActiveLineIndex != vIndex) { FActiveLineIndex = vIndex; Active = FActiveLineIndex >= 0; vResult = Active; } else vResult = vIndex >= 0; } if (vResult) { FMousePt.X = e.X; FMousePt.Y = e.Y; } } return vResult; } public override bool MouseMove(MouseEventArgs e) { if (StructState == HCStructState.hstcStructing) { FPoints[FActivePointIndex].Init(e.X, e.Y); return true; } if (e.Button == MouseButtons.Left && Control.ModifierKeys == Keys.None) { if (FActivePointIndex >= 0) { FPoints[FActivePointIndex].Init(e.X, e.Y); return true; } else if (FActiveLineIndex >= 0) // 整体移动 { OffsetPoints(e.X - FMousePt.X, e.Y - FMousePt.Y); FMousePt.X = e.X; FMousePt.Y = e.Y; return true; } } else { int vIndex = GetPointAt(e.X, e.Y); if (vIndex >= 0) { this.Cursor = Cursors.Cross; return true; } else { vIndex = GetLineAt(e.X, e.Y); if (vIndex >= 0) { this.Cursor = Cursors.SizeAll; return true; } } } return false; } public override bool MouseUp(MouseEventArgs e) { return false; } public override bool KeyDown(KeyEventArgs e) { if ((e.KeyValue == User.VK_BACK) || (e.KeyValue == User.VK_DELETE)) { if ((StructState == HCStructState.hstcStop) && (FActivePointIndex >= 0)) { if (FPoints.Count > 2) { FPoints.RemoveAt(FActivePointIndex); FActivePointIndex = -1; return true; } } } return false; } public override void PaintTo(HCCanvas aCanvas, RECT aRect, PaintInfo aPaintInfo) { aCanvas.Pen.BeginUpdate(); try { aCanvas.Pen.Color = Color; aCanvas.Pen.Width = FWidth; aCanvas.Pen.Style = FLineStyle; } finally { aCanvas.Pen.EndUpdate(); } aCanvas.MoveTo(FPoints[0].X + aRect.Left, FPoints[0].Y + aRect.Top); for (int i = 1; i < FPoints.Count; i++) aCanvas.LineTo(FPoints[i].X + aRect.Left, FPoints[i].Y + aRect.Top); if (FPoints.Count > 1) // 首尾相连 aCanvas.LineTo(FPoints[0].X + aRect.Left, FPoints[0].Y + aRect.Top); if ((!aPaintInfo.Print) && this.Active) PaintAnchor(aCanvas, aRect); } public override bool PointInClient(int x, int y) { int vIndex = GetPointAt(x, y); if (vIndex >= 0) return true; else { vIndex = GetLineAt(x, y); if (vIndex >= 0) return true; } return false; } public override void StructOver() { FActivePointIndex = -1; FActiveLineIndex = -1; if (FPoints.Count > 2) FPoints.RemoveAt(FPoints.Count - 1); base.StructOver(); } public override void SaveToStream(Stream aStream) { base.SaveToStream(aStream); aStream.WriteByte(FWidth); aStream.WriteByte((byte)FLineStyle); byte[] vBuffer = BitConverter.GetBytes(FPoints.Count); aStream.Write(vBuffer, 0, vBuffer.Length); for (int i = 0; i < FPoints.Count; i++) { vBuffer = BitConverter.GetBytes(FPoints[i].X); aStream.Write(vBuffer, 0, vBuffer.Length); vBuffer = BitConverter.GetBytes(FPoints[i].Y); aStream.Write(vBuffer, 0, vBuffer.Length); } } public override void LoadFromStream(Stream aStream) { FPoints.Clear(); base.LoadFromStream(aStream); FWidth = (byte)aStream.ReadByte(); FLineStyle = (HCPenStyle)aStream.ReadByte(); int vCount = 0; byte[] vBuffer = BitConverter.GetBytes(vCount); aStream.Read(vBuffer, 0, vBuffer.Length); vCount = BitConverter.ToInt32(vBuffer, 0); int vX = 0, vY = 0; HCPoint vPoint = null; for (int i = 0; i < vCount; i++) { aStream.Read(vBuffer, 0, vBuffer.Length); vX = BitConverter.ToInt32(vBuffer, 0); aStream.Read(vBuffer, 0, vBuffer.Length); vY = BitConverter.ToInt32(vBuffer, 0); vPoint = new HCPoint(vX, vY); FPoints.Add(vPoint); } } public override void ToXml(XmlElement aNode) { base.ToXml(aNode); aNode.SetAttribute("width", FWidth.ToString()); aNode.SetAttribute("ls", ((byte)FLineStyle).ToString()); XmlElement vNode = null; for (int i = 0; i < FPoints.Count; i++) { vNode = aNode.OwnerDocument.CreateElement("pt"); vNode.SetAttribute("x", FPoints[i].X.ToString()); vNode.SetAttribute("y", FPoints[i].Y.ToString()); aNode.AppendChild(vNode); } } public override void ParseXml(XmlElement aNode) { FPoints.Clear(); base.ParseXml(aNode); FWidth = byte.Parse(aNode.Attributes["width"].Value); FLineStyle = (HCPenStyle)byte.Parse(aNode.Attributes["ls"].Value); HCPoint vPoint = null; for (int i = 0; i < aNode.ChildNodes.Count; i++) { vPoint = new HCPoint(int.Parse(aNode.ChildNodes[i].Attributes["x"].Value), int.Parse(aNode.ChildNodes[i].Attributes["y"].Value)); FPoints.Add(vPoint); } } } public class HCShapeManager : HCList<HCShape> { private int FActiveIndex, FHotIndex; private HCShapeStyle FOperStyle; private EventHandler FOnStructOver; private int NewShape(HCShapeStyle aStyle) { HCShape vShpae = null; switch (aStyle) { case HCShapeStyle.hssNone: break; case HCShapeStyle.hssLine: vShpae = new HCShapeLine(); break; case HCShapeStyle.hssRectangle: vShpae = new HCShapeRectangle(); break; case HCShapeStyle.hssEllipse: vShpae = new HCShapeEllipse(); break; case HCShapeStyle.hssPolygon: vShpae = new HCShapePolygon(); break; } if (vShpae != null) { vShpae.OnStructOver = DoShapeStructOver; this.Add(vShpae); return this.Count - 1; } return -1; } private void DoShapeStructOver(object sender, EventArgs e) { ActiveIndex = -1; if (FOnStructOver != null) FOnStructOver(sender, e); } private void SetOperStyle(HCShapeStyle value) { if (FOperStyle != value) { ActiveIndex = -1; FOperStyle = value; } } private void SetActiveIndex(int value) { if (FActiveIndex != value) { if (FActiveIndex >= 0) this[FActiveIndex].Active = false; FActiveIndex = value; if (FActiveIndex >= 0) this[FActiveIndex].Active = true; } } public HCShapeManager() : base() { FActiveIndex = -1; FHotIndex = -1; FOperStyle = HCShapeStyle.hssNone; } public bool MouseDown(MouseEventArgs e) { bool vResult = false; if (FOperStyle != HCShapeStyle.hssNone) { if (FActiveIndex < 0) { ActiveIndex = NewShape(FOperStyle); this[FActiveIndex].StructStart(); } if (FActiveIndex >= 0) vResult = this[FActiveIndex].MouseDown(e); } else // 不在绘制 { int vIndex = -1; for (int i = 0; i < this.Count; i++) { if (this[i].PointInClient(e.X, e.Y)) { if (this[i].MouseDown(e)) { vIndex = i; vResult = true; break; } } } if (vIndex != FActiveIndex) { ActiveIndex = vIndex; vResult = true; } } return vResult; } public bool MouseMove(MouseEventArgs e) { if (FActiveIndex >= 0) { if (this[FActiveIndex].MouseMove(e)) { FHotIndex = FActiveIndex; return true; } } FHotIndex = -1; for (int i = 0; i < this.Count; i++) { if (this[i].PointInClient(e.X, e.Y)) { if (this[i].MouseMove(e)) { FHotIndex = i; return true; } } } return false; } public bool MouseUp(MouseEventArgs e) { for (int i = 0; i < this.Count; i++) { if (this[i].MouseUp(e)) return true; } return false; } public bool KeyDown(KeyEventArgs e) { if (FActiveIndex >= 0) { if (this[FActiveIndex].KeyDown(e)) return true; else if ((e.KeyValue == User.VK_BACK) || (e.KeyValue == User.VK_DELETE)) { this.RemoveAt(FActiveIndex); FActiveIndex = -1; return true; } } return false; } public void DisActive() { FOperStyle = HCShapeStyle.hssNone; if (FActiveIndex >= 0) this[FActiveIndex].Active = false; } public void PaintTo(HCCanvas aCanvas, RECT aRect, PaintInfo aPaintInfo) { for (int i = 0; i < this.Count; i++) this[i].PaintTo(aCanvas, aRect, aPaintInfo); } public void SaveToStream(Stream aStream) { byte[] vBuffer = BitConverter.GetBytes(this.Count); aStream.Write(vBuffer, 0, vBuffer.Length); for (int i = 0; i < this.Count; i++) this[i].SaveToStream(aStream); } public void LoadFromStream(Stream aStream) { this.Clear(); int vCount = 0; byte[] vBuffer = BitConverter.GetBytes(vCount); aStream.Read(vBuffer, 0, vBuffer.Length); vCount = BitConverter.ToInt32(vBuffer, 0); HCShape vShape = null; HCShapeStyle vStyle = HCShapeStyle.hssNone; for (int i = 0; i < vCount; i++) { vStyle = (HCShapeStyle)aStream.ReadByte(); switch (vStyle) { case HCShapeStyle.hssNone: throw new Exception("HCShape读取失败,无效的样式值!"); case HCShapeStyle.hssLine: vShape = new HCShapeLine(); break; case HCShapeStyle.hssRectangle: vShape = new HCShapeRectangle(); break; case HCShapeStyle.hssEllipse: vShape = new HCShapeEllipse(); break; case HCShapeStyle.hssPolygon: vShape = new HCShapePolygon(); break; } aStream.Position = aStream.Position - sizeof(byte); vShape.LoadFromStream(aStream); this.Add(vShape); } } public void ToXml(XmlElement aNode) { XmlElement vShapeNode = null; for (int i = 0; i < this.Count; i++) { vShapeNode = aNode.OwnerDocument.CreateElement("shape"); this[i].ToXml(vShapeNode); aNode.AppendChild(vShapeNode); } } public void ParseXml(XmlElement aNode) { this.Clear(); HCShape vShape = null; HCShapeStyle vStyle = HCShapeStyle.hssNone; XmlElement vShapeNode = null; for (int i = 0; i < aNode.ChildNodes.Count; i++) { vShapeNode = aNode.ChildNodes[i] as XmlElement; vStyle = (HCShapeStyle)byte.Parse(vShapeNode.Attributes["style"].Value); switch (vStyle) { case HCShapeStyle.hssNone: throw new Exception("HCShape读取失败,无效的样式值!"); case HCShapeStyle.hssLine: vShape = new HCShapeLine(); break; case HCShapeStyle.hssRectangle: vShape = new HCShapeRectangle(); break; case HCShapeStyle.hssEllipse: vShape = new HCShapeEllipse(); break; case HCShapeStyle.hssPolygon: vShape = new HCShapePolygon(); break; } vShape.ParseXml(vShapeNode); this.Add(vShape); } } public HCShapeStyle OperStyle { get { return FOperStyle; } set { SetOperStyle(value); } } public int ActiveIndex { get { return FActiveIndex; } set { SetActiveIndex(value); } } public int HotIndex { get { return FHotIndex; } } public EventHandler OnStructOver { get { return FOnStructOver; } set { FOnStructOver = value; } } } }
30.099257
129
0.456065
[ "MIT" ]
h1213159982/HDF
Example/WinForm/Editor/HCView/Source/HCShape.cs
44,903
C#
using System; using System.IO; using System.Text; using System.Collections.Generic; using GenieLamp.Core; using GenieLamp.Core.Metamodel; using GenieLamp.Core.Metamodel.Physical; using GenieLamp.Core.CodeWriters; using GenieLamp.Core.CodeWriters.Sql; namespace GenieLamp.Genies.Oracle { public class CodeGenDb { private const string VarNameFoundCount = "found"; private const string VarNameSql = "sqlstr"; private OracleGenie genie; private ICodeWriterPlSql updater; private ICodeWriterPlSql creator; private ICodeWriterPlSql cleaner; private IEnvironmentHelper environment; private bool createSchema = true; private string schemaPassword = "M@sterKey"; private string schemaDefaultTablespace = Const.EmptyValue; private string schemaTempTablespace = Const.EmptyValue; private bool schemaGrantDba = true; private bool useUniqueIndexes = false; private string outFileNameDDLCreate; private string outFileNameDDLUpdate; private string outFileNameDDLDelete; enum CommentTarget { Table, Column } #region Constructors public CodeGenDb(OracleGenie owner) { genie = owner; owner.Model.MetaObjects.SetUnprocessedAll(); environment = owner.Model.Lamp.GenieLampUtils.GetEnvironmentHelper(TargetEnvironment.OracleDb); createSchema = genie.Config.Params.ValueByName("CreateSchema", createSchema); schemaPassword = genie.Config.Params.ValueByName("Schema.Password", schemaPassword); schemaDefaultTablespace = genie.Config.Params.ValueByName("Schema.DefaultTablespace", schemaDefaultTablespace); schemaTempTablespace = genie.Config.Params.ValueByName("Schema.TempTablespace", schemaTempTablespace); schemaGrantDba = genie.Config.Params.ValueByName("Schema.GrantDba", schemaGrantDba); useUniqueIndexes = genie.Config.Params.ValueByName("UniqueIndexConstraint", useUniqueIndexes); updater = owner.Model.Lamp.CodeWritersFactory.CreateCodeWriterPlSql(); updater.DefaultOutFileEncoding = owner.Config.OutFileEncoding; creator = genie.Model.Lamp.CodeWritersFactory.CreateCodeWriterPlSql(); creator.DefaultOutFileEncoding = owner.Config.OutFileEncoding; cleaner = genie.Model.Lamp.CodeWritersFactory.CreateCodeWriterPlSql(); cleaner.DefaultOutFileEncoding = owner.Config.OutFileEncoding; outFileNameDDLCreate = Path.Combine(genie.Config.OutDir, "CRE_" + genie.Config.OutFileName); outFileNameDDLUpdate = Path.Combine(genie.Config.OutDir, "UPD_" + genie.Config.OutFileName); outFileNameDDLDelete = Path.Combine(genie.Config.OutDir, "DEL_" + genie.Config.OutFileName); } #endregion public string UpdateScriptFileName { get { return this.outFileNameDDLUpdate; } } private IModel Model { get { return genie.Model; } } public void Run() { BeginScripting(); RunCreation(); RunCleanup(); EndScripting(); } private void RunCreation() { ProcessSchemas(); ProcessSequences(); ProcessEntities(); ProcessRelations(); ProcessIndexes(); } private void RunCleanup() { foreach (IRelation r in Model.Relations) { if (r.Persistence.Persisted) { cleaner.WriteDropForeignKey(r, environment); cleaner.WriteSeparator(); } } cleaner.WriteLine(); foreach (IEntity en in Model.Entities) { if (en.Persistence.Persisted) { cleaner.WriteDropTable(en, environment); cleaner.WriteSeparator(); } } cleaner.WriteLine(); foreach (IGenerator gen in Model.Generators) { cleaner.WriteDropSequence(gen, environment); cleaner.WriteSeparator(); } } private void BeginScripting() { updater.WriteStdHeader(genie); creator.WriteStdHeader(genie); cleaner.WriteStdHeader(genie); updater.WriteLine("SET SERVEROUTPUT ON;"); updater.WriteLine("WHENEVER SQLERROR EXIT FAILURE ROLLBACK;"); updater.WriteLine("WHENEVER OSERROR EXIT FAILURE ROLLBACK;"); updater.WriteLine("DECLARE"); updater.Indent++; updater.DeclareVariable(VarNameFoundCount, "INTEGER"); updater.DeclareVariable(VarNameSql, "VARCHAR2(32000)"); updater.Indent--; updater.BeginScope(); } private void EndScripting() { updater.WriteLine("COMMIT;"); updater.Indent--; updater.WriteLine("EXCEPTION"); updater.Indent++; updater.WriteLine("WHEN OTHERS THEN"); updater.Indent++; updater.WriteLine("DBMS_OUTPUT.PUT_LINE('SQLCODE: ' || SQLCODE); "); updater.WriteLine("DBMS_OUTPUT.PUT_LINE('SQL: ' || {0});", VarNameSql); updater.WriteLine("RAISE;"); updater.Indent--; updater.EndScope(); updater.Save(outFileNameDDLUpdate); creator.Save(outFileNameDDLCreate); cleaner.Save(outFileNameDDLDelete); genie.Config.NotifyAssistants("Finished", null, creator.ToString(true)); } private void WriteExecImmediatWhenNotExists(string fromSource, string whereCondition, ICodeWriterPlSql sql) { updater.WriteLine("SELECT count(*) INTO {0} FROM {1} WHERE ROWNUM=1 AND {2};", VarNameFoundCount, fromSource, whereCondition); updater.If("{0} <> 1", VarNameFoundCount); updater.WriteSetVar(VarNameSql, sql); updater.WriteExecImmediatVariable(VarNameSql); updater.EndIf(); } private void WriteExecImmediat(ICodeWriterPlSql sql) { updater.WriteSetVar(VarNameSql, sql); updater.WriteExecImmediatVariable(VarNameSql); } private void WriteExecImmediat(string sql) { updater.WriteSetVar(VarNameSql, sql); updater.WriteExecImmediatVariable(VarNameSql); } private void WriteComment(CommentTarget target, string targetName, IDoc doc) { if (doc != null && doc.Text.Length > 0) { ICodeWriterPlSql sql = Model.Lamp.CodeWritersFactory.CreateCodeWriterPlSql(); sql.Write("COMMENT ON "); switch (target) { case CommentTarget.Table: sql.Write("TABLE "); break; default: sql.Write("COLUMN "); break; } sql.Write("{0} IS {1}", targetName, sql.ToConst(doc.Text)); genie.Config.NotifyAssistants("Doc", doc, sql.ToString(true)); WriteExecImmediat(sql); creator.WriteFrom(sql); creator.WriteSeparator(); } } private void ProcessSchemas() { List<string> schemas = new List<string>(); foreach (IEntity entity in Model.Entities) { if (!schemas.Contains(entity.Persistence.Schema)) { schemas.Add(entity.Persistence.Schema); } } if (createSchema) { foreach (string schemaName in schemas) { WriteSchema(schemaName); updater.WriteLine(); } } string sql = String.Format("ALTER SESSION SET current_schema={0}", schemas[0]); WriteExecImmediat(sql); creator.WriteLine(sql); creator.WriteSeparator(); } private void WriteSchema(string name) { updater.WriteLine("SELECT count(*) INTO {0} FROM ALL_USERS WHERE USERNAME='{1}' AND ROWNUM=1;", VarNameFoundCount, name); updater.If("{0} <> 1", VarNameFoundCount); ICodeWriterPlSql sql = Model.Lamp.CodeWritersFactory.CreateCodeWriterPlSql(); sql.WriteLine("CREATE USER {0}", name); sql.Indent++; sql.WriteLine("IDENTIFIED BY {0}", schemaPassword); sql.WriteLine("DEFAULT TABLESPACE {0}", schemaDefaultTablespace); sql.WriteLine("TEMPORARY TABLESPACE {0}", schemaTempTablespace); sql.WriteLine("ACCOUNT UNLOCK"); WriteExecImmediat(sql); creator.WriteFrom(sql); creator.WriteSeparator(); if (schemaGrantDba) { WriteExecImmediat(creator.WriteLine("GRANT DBA TO {0}", name)); creator.WriteSeparator(); } WriteExecImmediat(creator.WriteLine("GRANT SELECT ANY TABLE TO {0}", name)); creator.WriteSeparator(); WriteExecImmediat(creator.WriteLine("GRANT UPDATE ANY TABLE TO {0}", name)); creator.WriteSeparator(); WriteExecImmediat(creator.WriteLine("GRANT INSERT ANY TABLE TO {0}", name)); creator.WriteSeparator(); WriteExecImmediat(creator.WriteLine("GRANT DELETE ANY TABLE TO {0}", name)); creator.WriteSeparator(); WriteExecImmediat(creator.WriteLine("GRANT EXECUTE ANY TABLE TO {0}", name)); creator.WriteSeparator(); WriteExecImmediat(creator.WriteLine("GRANT SELECT ANY TABLE TO {0}", name)); creator.WriteSeparator(); updater.EndIf(); } #region Sequences private void ProcessSequences() { ICodeWriterPlSql sql = Model.Lamp.CodeWritersFactory.CreateCodeWriterPlSql(); foreach (IGenerator gen in Model.Generators) { if (gen.Owner is IEntity && !(gen.Owner as IEntity).Persistence.Persisted) continue; if (gen.Type == GeneratorType.Sequence) { sql.ClearAll(); sql.WriteCreateSequence(gen, environment); ISpellHint hint = genie.FindHint(gen); if (hint != null) sql.WriteText(hint.GetText(gen)); creator.WriteFrom(sql); creator.WriteSeparator(); genie.Config.NotifyAssistants("Create", gen, sql.ToString(true)); WriteExecImmediatWhenNotExists( "ALL_SEQUENCES", String.Format("SEQUENCE_OWNER='{0}' AND SEQUENCE_NAME='{1}'", gen.Persistence.Schema, gen.Persistence.Name), sql); updater.WriteLine(); } } } #endregion #region Entities private void ProcessEntities() { foreach (IEntity entity in Model.Entities) { if (entity.Persistence.Persisted) ProcessEntity(entity); updater.WriteLine(); Model.Lamp.Logger.ProgressStep(); } } private void ProcessEntity(IEntity entity) { updater.WriteLine(creator.WriteCommentLine("Table of {0}", entity.FullName)); ICodeWriterPlSql sql = Model.Lamp.CodeWritersFactory.CreateCodeWriterPlSql(); sql.WriteCreateTable(entity, environment); ISpellHint hint = genie.FindHint(entity); if (hint != null) sql.WriteText(hint.GetText(entity)); creator.WriteFrom(sql); creator.WriteSeparator(); WriteExecImmediatWhenNotExists( "ALL_TABLES", String.Format("OWNER='{0}' AND TABLE_NAME='{1}'", entity.Persistence.Schema, entity.Persistence.Name), sql); updater.WriteLine(); genie.Config.NotifyAssistants("Create", entity, sql.ToString(true)); IAttributes attributes; switch(Model.Lamp.Config.Layers.DomainConfig.MappingStrategy) { case GenieLamp.Core.Layers.MappingStrategy.TablePerSubclass: attributes = entity.GetAttributes(false); break; case GenieLamp.Core.Layers.MappingStrategy.TablePerClass: attributes = entity.GetAttributes(true); break; default: throw new GenieLamp.Core.Exceptions.GlException("Mapping strategy is not supported: '{0}'", Model.Lamp.Config.Layers.DomainConfig.MappingStrategy); } ProcessUpdateAttributes(entity, attributes); ProcessPrimaryKey(entity); ProcessUniqueIds(entity); creator.WriteLine(); updater.WriteLine(); WriteComment(CommentTarget.Table, entity.Persistence.FullName, entity.Doc); foreach (IAttribute a in attributes) { if (a.Persistence.Persisted) { WriteComment(CommentTarget.Column, String.Format("{0}.{1}", entity.Persistence.FullName, a.Persistence.Name), a.Doc); } } } private void ProcessPrimaryKey(IEntity entity) { ICodeWriterPlSql sql = Model.Lamp.CodeWritersFactory.CreateCodeWriterPlSql(); sql.WriteCreatePrimaryKey(entity.PrimaryId, environment); ISpellHint hint = genie.FindHint(entity.PrimaryId); if (hint != null) sql.WriteText(hint.GetText(entity.PrimaryId)); creator.WriteFrom(sql); creator.WriteSeparator(); WriteExecImmediatWhenNotExists( "ALL_CONSTRAINTS", String.Format("OWNER='{0}' AND TABLE_NAME='{1}' AND CONSTRAINT_TYPE='P'", entity.Persistence.Schema, entity.Persistence.Name), sql); genie.Config.NotifyAssistants("Create", entity.PrimaryId, sql.ToString(true)); updater.WriteLine(); } private void ProcessUniqueIds(IEntity entity) { ICodeWriterPlSql sql = Model.Lamp.CodeWritersFactory.CreateCodeWriterPlSql(); foreach(IUniqueId uid in entity.Constraints.UniqueIds) { sql.ClearAll(); if (!useUniqueIndexes) { sql.WriteCreateUniqueConstraint(uid, environment); creator.WriteFrom(sql); creator.WriteSeparator(); WriteExecImmediatWhenNotExists( "ALL_CONSTRAINTS", String.Format("OWNER='{0}' AND TABLE_NAME='{1}' AND CONSTRAINT_TYPE='U' AND CONSTRAINT_NAME='{2}'", entity.Persistence.Schema, entity.Persistence.Name, uid.Persistence.Name), sql); uid.Index.Processed = true; genie.Config.NotifyAssistants("Create", uid, sql.ToString(true)); updater.WriteLine(); } } } private void ProcessIndexes() { ICodeWriterPlSql sql = Model.Lamp.CodeWritersFactory.CreateCodeWriterPlSql(); foreach(IIndex index in Model.PhysicalModel.Indexes) { if (!index.Processed && index.Generate) { sql.ClearAll(); sql.WriteCreateIndex(index, environment); ISpellHint hint = genie.FindHint(index); if (hint != null) sql.WriteText(hint.GetText(index)); creator.WriteFrom(sql); creator.WriteSeparator(); StringBuilder sqlFrom = new StringBuilder(); sqlFrom.Append("SELECT I.OWNER, I.INDEX_NAME, COUNT(*) "); sqlFrom.Append("FROM ALL_INDEXES I "); sqlFrom.Append(" INNER JOIN ALL_IND_COLUMNS IC ON I.OWNER = IC.INDEX_OWNER AND I.INDEX_NAME = IC.INDEX_NAME"); sqlFrom.Append(" LEFT OUTER JOIN ALL_CONSTRAINTS AC ON I.INDEX_NAME = AC.CONSTRAINT_NAME AND I.TABLE_OWNER = AC.OWNER AND I.TABLE_NAME = AC.TABLE_NAME AND AC.CONSTRAINT_TYPE = 'P'"); sqlFrom.Append(" LEFT OUTER JOIN("); for(int i = 0; i < index.Columns.Count; i++) { sqlFrom.AppendFormat("{0}SELECT '{1}' AS COLUMN_NAME FROM DUAL", i == 0 ? "" : " UNION ", index.Columns[i].Attribute.Persistence.Name); } sqlFrom.Append(") IC2 ON IC.COLUMN_NAME = IC2.COLUMN_NAME"); sqlFrom.AppendFormat(" WHERE I.OWNER='{0}' AND I.TABLE_OWNER = '{1}' AND I.TABLE_NAME='{2}' AND AC.CONSTRAINT_NAME IS NULL", index.Schema, index.Entity.Persistence.Schema, index.Entity.Persistence.Name); sqlFrom.Append(" GROUP BY I.OWNER, I.INDEX_NAME"); sqlFrom.AppendFormat(" HAVING COUNT(*) = {0}", index.Columns.Count); sqlFrom.Append(" UNION ALL "); sqlFrom.AppendFormat("SELECT I.OWNER, I.INDEX_NAME, 1 FROM ALL_INDEXES I WHERE I.OWNER='{0}' AND I.INDEX_NAME='{1}'", index.Schema, index.Name); WriteExecImmediatWhenNotExists( String.Format("({0}) T1", sqlFrom.ToString()), "1=1", sql); genie.Config.NotifyAssistants("Create", index, sql.ToString(true)); updater.WriteLine(); } } } private void ProcessUpdateAttributes(IEntity entity, IAttributes attributes) { foreach (IAttribute a in attributes) { if (a.Persistence.Persisted) { ICodeWriterPlSql sql = Model.Lamp.CodeWritersFactory.CreateCodeWriterPlSql(); updater.WriteLine("SELECT count(*) INTO {0} FROM ALL_TAB_COLUMNS WHERE OWNER='{1}' AND TABLE_NAME='{2}' AND COLUMN_NAME='{3}' AND ROWNUM=1;", VarNameFoundCount, entity.Persistence.Schema, entity.Persistence.Name, a.Persistence.Name); updater.If("{0} <> 1", VarNameFoundCount); sql.WriteLine("ALTER TABLE {0} ADD ", entity.Persistence.FullName); sql.Indent++; sql.WriteLine("{0} {1} NULL", a.Persistence.Name, environment.ToTypeName(a, false)); WriteExecImmediat(sql); string updateColSql = sql.ToString(true); if (a.TypeDefinition.Required && a.TypeDefinition.HasDefault) { sql.ClearAll(); sql.WriteLine("UPDATE {0} SET {1}={2}", entity.Persistence.FullName, a.Persistence.Name, environment.ToDefaultValue(a)); WriteExecImmediat(sql); updateColSql = updateColSql + Environment.NewLine + sql.ToString(true); sql.ClearAll(); sql.WriteLine("ALTER TABLE {0} MODIFY ({1} NOT NULL)", entity.Persistence.FullName, a.Persistence.Name); WriteExecImmediat(sql); updateColSql = updateColSql + Environment.NewLine + sql.ToString(true); } updater.EndIf(); genie.Config.NotifyAssistants("Update", a, updateColSql); } } updater.WriteLine(); } #endregion private void ProcessRelations() { foreach (IRelation r in Model.Relations) { if (r is ISubtypeRelation) creator.WriteLine(updater.WriteCommentLine( "Subtyping reference: {0} is a {1}", r.ForeignKey.ChildTable.FullName, r.ForeignKey.ParentTable.FullName)); ICodeWriterPlSql sql = Model.Lamp.CodeWritersFactory.CreateCodeWriterPlSql(); sql.WriteCreateForeignKey(r, environment); creator.WriteFrom(sql); creator.WriteSeparator(); WriteExecImmediatWhenNotExists( "ALL_CONSTRAINTS", String.Format("OWNER='{0}' AND CONSTRAINT_NAME='{1}' AND CONSTRAINT_TYPE='R'", r.ForeignKey.ChildTable.Persistence.Schema, r.ForeignKey.Name), sql); updater.WriteLine(); genie.Config.NotifyAssistants("Create", r, sql.ToString()); } } } }
33.047706
188
0.657765
[ "MIT" ]
arbinada-com/genie-lamp
Sources/GenieLamp.Genies/GenieLamp.Genies.Oracle/CodeGenDb.cs
18,011
C#
// <copyright file="Configuration.cs" company="YAGNI"> // All rights reserved. // </copyright> using System; using System.Data.Entity.Migrations; using System.Data.SQLite.EF6.Migrations; using System.Linq; using LibrarySystem.Models.Logs; namespace LibrarySystem.Data.Logs.Migrations { /// <summary> /// Represent a <see cref="Configuration"/> class, heir of <see cref="DbMigrationsConfiguration"/>. /// </summary> internal sealed class Configuration : DbMigrationsConfiguration<LibrarySystemLogsDbContext> { /// <summary> /// Initializes a new instance of the <see cref="Configuration"/> class. /// </summary> public Configuration() { this.AutomaticMigrationsEnabled = false; this.SetSqlGenerator("System.Data.SQLite", new SQLiteMigrationSqlGenerator()); } /// <summary> /// Runs after upgrading to the latest migration to allow seed data to be updated. /// </summary> /// <param name="context">Context to be used for updating seed data.</param> protected override void Seed(LibrarySystemLogsDbContext context) { LogType logtype = context.LogTypes .Where(l => l.Name == "Updating Database") .FirstOrDefault() ?? new LogType { Name = "Updating Database" }; Log updatingLog = new Log { Message = "Running Seed method After a migration!", DateTime = DateTime.Now, // TODO: Implement DateTime provider. LogType = logtype }; context.Logs.Add(updatingLog); context.SaveChanges(); } } }
33.176471
103
0.612293
[ "MIT" ]
TeamYAGNI/LibrarySystem
LibrarySystem/LibrarySystem.Data.Logs/Migrations/Configuration.cs
1,692
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using WebApp.Models; namespace WebApp.Persistence.Repository { public interface IStationRepository: IRepository<Station,int> { } }
18.642857
65
0.773946
[ "MIT" ]
bogdanarsenic/Diplomski
WebApp/Persistence/Repository/IStationRepository.cs
263
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Test.Common; using System.Threading.Tasks; using Xunit; namespace System.Net.Http.Functional.Tests { public abstract class HttpCookieProtocolTests : HttpClientTestBase { private const string s_cookieName = "ABC"; private const string s_cookieValue = "123"; private const string s_expectedCookieHeaderValue = "ABC=123"; private const string s_customCookieHeaderValue = "CustomCookie=456"; private const string s_simpleContent = "Hello world!"; // // Send cookie tests // private static CookieContainer CreateSingleCookieContainer(Uri uri) => CreateSingleCookieContainer(uri, s_cookieName, s_cookieValue); private static CookieContainer CreateSingleCookieContainer(Uri uri, string cookieName, string cookieValue) { var container = new CookieContainer(); container.Add(uri, new Cookie(cookieName, cookieValue)); return container; } private static string GetCookieHeaderValue(string cookieName, string cookieValue) => $"{cookieName}={cookieValue}"; [Fact] public async Task GetAsync_DefaultCoookieContainer_NoCookieSent() { await LoopbackServer.CreateServerAsync(async (server, url) => { using (HttpClient client = CreateHttpClient()) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); List<string> requestLines = await serverTask; Assert.Equal(0, requestLines.Count(s => s.StartsWith("Cookie:"))); } }); } [Theory] [MemberData(nameof(CookieNamesValuesAndUseCookies))] public async Task GetAsync_SetCookieContainer_CookieSent(string cookieName, string cookieValue, bool useCookies) { await LoopbackServer.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = CreateSingleCookieContainer(url, cookieName, cookieValue); handler.UseCookies = useCookies; using (HttpClient client = new HttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); List<string> requestLines = await serverTask; if (useCookies) { Assert.Contains($"Cookie: {GetCookieHeaderValue(cookieName, cookieValue)}", requestLines); Assert.Equal(1, requestLines.Count(s => s.StartsWith("Cookie:"))); } else { Assert.Equal(0, requestLines.Count(s => s.StartsWith("Cookie:"))); } } }); } [Fact] public async Task GetAsync_SetCookieContainerMultipleCookies_CookiesSent() { var cookies = new Cookie[] { new Cookie("hello", "world"), new Cookie("foo", "bar"), new Cookie("ABC", "123") }; await LoopbackServer.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); var cookieContainer = new CookieContainer(); foreach (Cookie c in cookies) { cookieContainer.Add(url, c); } handler.CookieContainer = cookieContainer; using (HttpClient client = new HttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); List<string> requestLines = await serverTask; string expectedHeader = "Cookie: " + string.Join("; ", cookies.Select(c => $"{c.Name}={c.Value}").ToArray()); Assert.Contains(expectedHeader, requestLines); Assert.Equal(1, requestLines.Count(s => s.StartsWith("Cookie:"))); } }); } [Fact] public async Task GetAsync_AddCookieHeader_CookieHeaderSent() { if (IsNetfxHandler) { // Netfx handler does not support custom cookie header return; } await LoopbackServer.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = new HttpClient(handler)) { HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, url); requestMessage.Headers.Add("Cookie", s_customCookieHeaderValue); Task<HttpResponseMessage> getResponseTask = client.SendAsync(requestMessage); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); List<string> requestLines = await serverTask; Assert.Contains($"Cookie: {s_customCookieHeaderValue}", requestLines); Assert.Equal(1, requestLines.Count(s => s.StartsWith("Cookie:"))); } }); } [ActiveIssue(30051, TargetFrameworkMonikers.Uap)] [Fact] public async Task GetAsync_AddMultipleCookieHeaders_CookiesSent() { if (IsNetfxHandler) { // Netfx handler does not support custom cookie header return; } await LoopbackServer.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = new HttpClient(handler)) { HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, url); requestMessage.Headers.Add("Cookie", "A=1"); requestMessage.Headers.Add("Cookie", "B=2"); requestMessage.Headers.Add("Cookie", "C=3"); Task<HttpResponseMessage> getResponseTask = client.SendAsync(requestMessage); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); List<string> requestLines = await serverTask; Assert.Equal(1, requestLines.Count(s => s.StartsWith("Cookie: "))); // Multiple Cookie header values are treated as any other header values and are // concatenated using ", " as the separator. var cookieValues = requestLines.Single(s => s.StartsWith("Cookie: ")).Substring(8).Split(new string[] { ", " }, StringSplitOptions.None); Assert.Contains("A=1", cookieValues); Assert.Contains("B=2", cookieValues); Assert.Contains("C=3", cookieValues); Assert.Equal(3, cookieValues.Count()); } }); } [Fact] public async Task GetAsync_SetCookieContainerAndCookieHeader_BothCookiesSent() { if (IsNetfxHandler) { // Netfx handler does not support custom cookie header return; } if (IsCurlHandler) { // CurlHandler ignores container cookies when custom Cookie header is set. // SocketsHttpHandler behaves the expected way. Not worth fixing in CurlHandler as it is going away. return; } await LoopbackServer.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = CreateSingleCookieContainer(url); using (HttpClient client = new HttpClient(handler)) { HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, url); requestMessage.Headers.Add("Cookie", s_customCookieHeaderValue); Task<HttpResponseMessage> getResponseTask = client.SendAsync(requestMessage); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); List<string> requestLines = await serverTask; Assert.Equal(1, requestLines.Count(s => s.StartsWith("Cookie: "))); var cookies = requestLines.Single(s => s.StartsWith("Cookie: ")).Substring(8).Split(new string[] { "; " }, StringSplitOptions.None); Assert.Contains(s_expectedCookieHeaderValue, cookies); Assert.Contains(s_customCookieHeaderValue, cookies); Assert.Equal(2, cookies.Count()); } }); } [ActiveIssue(30051, TargetFrameworkMonikers.Uap)] [Fact] public async Task GetAsync_SetCookieContainerAndMultipleCookieHeaders_BothCookiesSent() { if (IsNetfxHandler) { // Netfx handler does not support custom cookie header return; } if (IsCurlHandler) { // CurlHandler ignores container cookies when custom Cookie header is set. // SocketsHttpHandler behaves the expected way. Not worth fixing in CurlHandler as it is going away. return; } await LoopbackServer.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = CreateSingleCookieContainer(url); using (HttpClient client = new HttpClient(handler)) { HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, url); requestMessage.Headers.Add("Cookie", "A=1"); requestMessage.Headers.Add("Cookie", "B=2"); Task<HttpResponseMessage> getResponseTask = client.SendAsync(requestMessage); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync(); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); List<string> requestLines = await serverTask; Assert.Equal(1, requestLines.Count(s => s.StartsWith("Cookie: "))); // Multiple Cookie header values are treated as any other header values and are // concatenated using ", " as the separator. The container cookie is concatenated to // one of these values using the "; " cookie separator. var cookieValues = requestLines.Single(s => s.StartsWith("Cookie: ")).Substring(8).Split(new string[] { ", " }, StringSplitOptions.None); Assert.Equal(2, cookieValues.Count()); // Find container cookie and remove it so we can validate the rest of the cookie header values bool sawContainerCookie = false; for (int i = 0; i < cookieValues.Length; i++) { if (cookieValues[i].Contains(';')) { Assert.False(sawContainerCookie); var cookies = cookieValues[i].Split(new string[] { "; " }, StringSplitOptions.None); Assert.Equal(2, cookies.Count()); Assert.Contains(s_expectedCookieHeaderValue, cookies); sawContainerCookie = true; cookieValues[i] = cookies.Where(c => c != s_expectedCookieHeaderValue).Single(); } } Assert.Contains("A=1", cookieValues); Assert.Contains("B=2", cookieValues); } }); } [Fact] public async Task GetAsyncWithRedirect_SetCookieContainer_CorrectCookiesSent() { const string path1 = "/foo"; const string path2 = "/bar"; await LoopbackServer.CreateClientAndServerAsync(async url => { Uri url1 = new Uri(url, path1); Uri url2 = new Uri(url, path2); Uri unusedUrl = new Uri(url, "/unused"); HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = new CookieContainer(); handler.CookieContainer.Add(url1, new Cookie("cookie1", "value1")); handler.CookieContainer.Add(url2, new Cookie("cookie2", "value2")); handler.CookieContainer.Add(unusedUrl, new Cookie("cookie3", "value3")); using (HttpClient client = new HttpClient(handler)) { client.DefaultRequestHeaders.ConnectionClose = true; // to avoid issues with connection pooling await client.GetAsync(url1); } }, async server => { List<string> request1Lines = await server.AcceptConnectionSendResponseAndCloseAsync(HttpStatusCode.Found, $"Location: {path2}\r\n"); Assert.Contains($"Cookie: cookie1=value1", request1Lines); Assert.Equal(1, request1Lines.Count(s => s.StartsWith("Cookie:"))); List<string> request2Lines = await server.AcceptConnectionSendResponseAndCloseAsync(content: s_simpleContent); Assert.Contains($"Cookie: cookie2=value2", request2Lines); Assert.Equal(1, request2Lines.Count(s => s.StartsWith("Cookie:"))); }); } // // Receive cookie tests // [Theory] [MemberData(nameof(CookieNamesValuesAndUseCookies))] public async Task GetAsync_ReceiveSetCookieHeader_CookieAdded(string cookieName, string cookieValue, bool useCookies) { await LoopbackServer.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.UseCookies = useCookies; using (HttpClient client = new HttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync( HttpStatusCode.OK, $"Set-Cookie: {GetCookieHeaderValue(cookieName, cookieValue)}\r\n", s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); if (useCookies) { Assert.Equal(1, collection.Count); Assert.Equal(cookieName, collection[0].Name); Assert.Equal(cookieValue, collection[0].Value); } else { Assert.Equal(0, collection.Count); } } }); } [Fact] public async Task GetAsync_ReceiveMultipleSetCookieHeaders_CookieAdded() { await LoopbackServer.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = new HttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync( HttpStatusCode.OK, $"Set-Cookie: A=1; Path=/\r\n" + $"Set-Cookie : B=2; Path=/\r\n" + // space before colon to verify header is trimmed and recognized $"Set-Cookie: C=3; Path=/\r\n", s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(3, collection.Count); // Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie> Cookie[] cookies = new Cookie[3]; collection.CopyTo(cookies, 0); Assert.Contains(cookies, c => c.Name == "A" && c.Value == "1"); Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2"); Assert.Contains(cookies, c => c.Name == "C" && c.Value == "3"); } }); } [Fact] public async Task GetAsync_ReceiveSetCookieHeader_CookieUpdated() { const string newCookieValue = "789"; await LoopbackServer.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = CreateSingleCookieContainer(url); using (HttpClient client = new HttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync( HttpStatusCode.OK, $"Set-Cookie: {s_cookieName}={newCookieValue}\r\n", s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(1, collection.Count); Assert.Equal(s_cookieName, collection[0].Name); Assert.Equal(newCookieValue, collection[0].Value); } }); } [ActiveIssue(30051, TargetFrameworkMonikers.Uap)] // fails to remove cookie [Fact] public async Task GetAsync_ReceiveSetCookieHeader_CookieRemoved() { await LoopbackServer.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); handler.CookieContainer = CreateSingleCookieContainer(url); using (HttpClient client = new HttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync( HttpStatusCode.OK, $"Set-Cookie: {s_cookieName}=; Expires=Sun, 06 Nov 1994 08:49:37 GMT\r\n", s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(0, collection.Count); } }); } [ActiveIssue(30051, TargetFrameworkMonikers.Uap)] // only adds one cookie [Fact] public async Task GetAsync_ReceiveInvalidSetCookieHeader_ValidCookiesAdded() { if (IsNetfxHandler) { // NetfxHandler incorrectly only processes one valid cookie return; } await LoopbackServer.CreateServerAsync(async (server, url) => { HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = new HttpClient(handler)) { Task<HttpResponseMessage> getResponseTask = client.GetAsync(url); Task<List<string>> serverTask = server.AcceptConnectionSendResponseAndCloseAsync( HttpStatusCode.OK, $"Set-Cookie: A=1; Path=/;Expires=asdfsadgads\r\n" + // invalid Expires $"Set-Cookie: B=2; Path=/\r\n" + $"Set-Cookie: C=3; Path=/\r\n", s_simpleContent); await TestHelper.WhenAllCompletedOrAnyFailed(getResponseTask, serverTask); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(2, collection.Count); // Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie> Cookie[] cookies = new Cookie[3]; collection.CopyTo(cookies, 0); Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2"); Assert.Contains(cookies, c => c.Name == "C" && c.Value == "3"); } }); } [Fact] public async Task GetAsyncWithRedirect_ReceiveSetCookie_CookieSent() { const string path1 = "/foo"; const string path2 = "/bar"; await LoopbackServer.CreateClientAndServerAsync(async url => { Uri url1 = new Uri(url, path1); HttpClientHandler handler = CreateHttpClientHandler(); using (HttpClient client = new HttpClient(handler)) { client.DefaultRequestHeaders.ConnectionClose = true; // to avoid issues with connection pooling await client.GetAsync(url1); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(2, collection.Count); // Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie> Cookie[] cookies = new Cookie[2]; collection.CopyTo(cookies, 0); Assert.Contains(cookies, c => c.Name == "A" && c.Value == "1"); Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2"); } }, async server => { List<string> request1Lines = await server.AcceptConnectionSendResponseAndCloseAsync( HttpStatusCode.Found, $"Location: {path2}\r\nSet-Cookie: A=1; Path=/\r\n"); Assert.Equal(0, request1Lines.Count(s => s.StartsWith("Cookie:"))); List<string> request2Lines = await server.AcceptConnectionSendResponseAndCloseAsync( HttpStatusCode.OK, $"Set-Cookie: B=2; Path=/\r\n", s_simpleContent); Assert.Contains($"Cookie: A=1", request2Lines); Assert.Equal(1, request2Lines.Count(s => s.StartsWith("Cookie:"))); }); } [ActiveIssue(30050, TargetFrameworkMonikers.Uap)] [Fact] public async Task GetAsyncWithBasicAuth_ReceiveSetCookie_CookieSent() { if (IsWinHttpHandler) { // Issue #26986 // WinHttpHandler does not process the cookie. return; } await LoopbackServer.CreateClientAndServerAsync(async url => { HttpClientHandler handler = CreateHttpClientHandler(); handler.Credentials = new NetworkCredential("user", "pass"); using (HttpClient client = new HttpClient(handler)) { await client.GetAsync(url); CookieCollection collection = handler.CookieContainer.GetCookies(url); Assert.Equal(2, collection.Count); // Convert to array so we can more easily process contents, since CookieCollection does not implement IEnumerable<Cookie> Cookie[] cookies = new Cookie[2]; collection.CopyTo(cookies, 0); Assert.Contains(cookies, c => c.Name == "A" && c.Value == "1"); Assert.Contains(cookies, c => c.Name == "B" && c.Value == "2"); } }, async server => { await server.AcceptConnectionAsync(async connection => { List<string> request1Lines = await connection.ReadRequestHeaderAndSendResponseAsync( HttpStatusCode.Unauthorized, $"WWW-Authenticate: Basic realm=\"WallyWorld\"\r\nSet-Cookie: A=1; Path=/\r\n"); Assert.Equal(0, request1Lines.Count(s => s.StartsWith("Cookie:"))); List<string> request2Lines = await connection.ReadRequestHeaderAndSendResponseAsync( HttpStatusCode.OK, $"Set-Cookie: B=2; Path=/\r\n", s_simpleContent); Assert.Contains($"Cookie: A=1", request2Lines); Assert.Equal(1, request2Lines.Count(s => s.StartsWith("Cookie:"))); }); }); } // // MemberData stuff // private static string GenerateCookie(string name, char repeat, int overallHeaderValueLength) { string emptyHeaderValue = $"{name}=; Path=/"; Debug.Assert(overallHeaderValueLength > emptyHeaderValue.Length); int valueCount = overallHeaderValueLength - emptyHeaderValue.Length; return new string(repeat, valueCount); } public static IEnumerable<object[]> CookieNamesValuesAndUseCookies() { foreach (bool useCookies in new[] { true, false }) { yield return new object[] { "ABC", "123", useCookies }; yield return new object[] { "Hello", "World", useCookies }; yield return new object[] { "foo", "bar", useCookies }; yield return new object[] { ".AspNetCore.Session", "RAExEmXpoCbueP_QYM", useCookies }; yield return new object[] { ".AspNetCore.Antiforgery.Xam7_OeLcN4", "CfDJ8NGNxAt7CbdClq3UJ8_6w_4661wRQZT1aDtUOIUKshbcV4P0NdS8klCL5qGSN-PNBBV7w23G6MYpQ81t0PMmzIN4O04fqhZ0u1YPv66mixtkX3iTi291DgwT3o5kozfQhe08-RAExEmXpoCbueP_QYM", useCookies }; // WinHttpHandler calls WinHttpQueryHeaders to iterate through multiple Set-Cookie header values, // using an initial buffer size of 128 chars. If the buffer is not large enough, WinHttpQueryHeaders // returns an insufficient buffer error, allowing WinHttpHandler to try again with a larger buffer. // Sometimes when WinHttpQueryHeaders fails due to insufficient buffer, it still advances the // iteration index, which would cause header values to be missed if not handled correctly. // // In particular, WinHttpQueryHeader behaves as follows for the following header value lengths: // * 0-127 chars: succeeds, index advances from 0 to 1. // * 128-255 chars: fails due to insufficient buffer, index advances from 0 to 1. // * 256+ chars: fails due to insufficient buffer, index stays at 0. // // The below overall header value lengths were chosen to exercise reading header values at these // edges, to ensure WinHttpHandler does not miss multiple Set-Cookie headers. yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 126), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 127), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 128), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 129), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 254), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 255), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 256), useCookies }; yield return new object[] { "foo", GenerateCookie(name: "foo", repeat: 'a', overallHeaderValueLength: 257), useCookies }; } } } }
46.398764
178
0.567722
[ "MIT" ]
L-Dogg/corefx
src/System.Net.Http/tests/FunctionalTests/HttpCookieProtocolTests.cs
30,022
C#
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. namespace SharpDX.Direct3D11 { public partial struct ResourceRegion { /// <summary> /// Initialize a new instance of <see cref="ResourceRegion"/> struct. /// </summary> /// <param name="left">Left coordinates (inclusive)</param> /// <param name="top">Top coordinates (inclusive)</param> /// <param name="front">Front coordinates (inclusive)</param> /// <param name="right">Right coordinates (exclusive)</param> /// <param name="bottom">Bottom coordinates (exclusive)</param> /// <param name="back">Back coordinates (exclusive)</param> /// <remarks> /// <ul> /// <li>For a Width of 1 pixels, (right - left) = 1. If left = 0, right = Width. </li> /// <li>For a Height of 1 pixels, (bottom - top) = 1. If top = 0, bottom = Height.</li> /// <li>For a Depth of 1 pixels, (back - front) = 1. If front = 0, back = Depth. </li> /// </ul> /// </remarks> public ResourceRegion(int left, int top, int front, int right, int bottom, int back) { Left = left; Top = top; Front = front; Right = right; Bottom = bottom; Back = back; } } }
47.78
95
0.641691
[ "MIT" ]
shoelzer/SharpDX
Source/SharpDX.Direct3D11/ResourceRegion.cs
2,391
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("Element")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Markit On Demand, Inc")] [assembly: AssemblyProduct("Element")] [assembly: AssemblyCopyright("Copyright © Markit On Demand, Inc 2014")] [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("97da175b-c19e-43e3-bf3b-8ee86834a42c")] // 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")] [assembly: AssemblyInformationalVersion("1.0.0")]
39.945946
84
0.746955
[ "Apache-2.0" ]
brianbaker/MOD.Web.Element
Properties/AssemblyInfo.cs
1,481
C#
// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. See LICENSE in the project root for license information. using System; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Collections.Generic; using static TorchSharp.torch; using static TorchSharp.TensorExtensionMethods; using Xunit; #nullable enable namespace TorchSharp { public class TestTensor { [Fact] public void TestScalarCreation() { using (var scalar = false.ToScalar()) { Assert.Equal(ScalarType.Bool, scalar.Type); } using (var scalar = ((byte)0).ToScalar()) { Assert.Equal(ScalarType.Int64, scalar.Type); } using (var scalar = ((short)0).ToScalar()) { Assert.Equal(ScalarType.Int64, scalar.Type); } using (var scalar = ((int)0).ToScalar()) { Assert.Equal(ScalarType.Int64, scalar.Type); } using (var scalar = ((long)0).ToScalar()) { Assert.Equal(ScalarType.Int64, scalar.Type); } using (var scalar = ((float)0).ToScalar()) { Assert.Equal(ScalarType.Float64, scalar.Type); } using (var scalar = ((double)0).ToScalar()) { Assert.Equal(ScalarType.Float64, scalar.Type); } } [Fact] public void TestToString1() { Tensor t = torch.zeros(2, 2); var str = t.ToString(); Assert.Equal("[2x2], type = Float32, device = cpu", str); } [Fact] public void TestScalarToString() { { Tensor t = (Tensor)3.14f; var str = t.ToString(true); Assert.Equal("[], type = Float32, device = cpu, value = 3.14", str); } { Tensor t = torch.tensor(3.14f); var str = t.ToString(true, "E2"); Assert.Equal("[], type = Float32, device = cpu, value = 3.14E+000", str); } { Tensor t = torch.tensor((3.14f, 6.28f), torch.complex64); var str = t.ToString(true); Assert.Equal("[], type = ComplexFloat32, device = cpu, value = 3.14+6.28i", str); } } private string _sep = OperatingSystem.IsWindows() ? "\r\n" : "\n"; [Fact] public void Test1DToString() { { Tensor t = torch.zeros(4); var str = t.ToString(true); Assert.Equal($"[4], type = Float32, device = cpu{_sep} 0 0 0 0{_sep}", str); } { Tensor t = torch.zeros(4, torch.complex64); var str = t.ToString(true); Assert.Equal($"[4], type = ComplexFloat32, device = cpu{_sep} 0 0 0 0{_sep}", str); } { Tensor t = torch.ones(4, torch.complex64); for (int i = 0; i < t.shape[0]; i++) t[i] = torch.tensor((1.0f * i, 2.43f * i * 2), torch.complex64); var str = t.ToString(true); Assert.Equal($"[4], type = ComplexFloat32, device = cpu{_sep} 0 1+4.86i 2+9.72i 3+14.58i{_sep}", str); } } [Fact] public void Test2DToString() { { Tensor t = torch.tensor(new float[] { 0.0f, 3.141f, 6.2834f, 3.14152f, 6.28e-06f, -13.141529f, 0.01f, 4713.14f }, 2, 4); var str = t.ToString(true); Assert.Equal($"[2x4], type = Float32, device = cpu{_sep}{_sep} 0 3.141 6.2834 3.1415{_sep} 6.28e-06 -13.142 0.01 4713.1{_sep}", str); } { Tensor t = torch.zeros(2, 4, torch.complex64); var str = t.ToString(true); Assert.Equal($"[2x4], type = ComplexFloat32, device = cpu{_sep}{_sep} 0 0 0 0{_sep} 0 0 0 0{_sep}", str); } { Tensor t = torch.ones(2, 4, torch.complex64); var str = t.ToString(true); Assert.Equal($"[2x4], type = ComplexFloat32, device = cpu{_sep}{_sep} 1 1 1 1{_sep} 1 1 1 1{_sep}", str); } } [Fact] public void Test3DToString() { { Tensor t = torch.tensor(new float[] { 0.0f, 3.141f, 6.2834f, 3.14152f, 6.28e-06f, -13.141529f, 0.01f, 4713.14f, 0.01f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, }, 2, 2, 4); var str = t.ToString(true, "0.0000000"); Assert.Equal($"[2x2x4], type = Float32, device = cpu{_sep}{_sep}[0,:,:] ={_sep} 0.0000000 3.1410000 6.2834000 3.1415200{_sep}" + $" 0.0000063 -13.1415300 0.0100000 4713.1400000{_sep}{_sep}[1,:,:] ={_sep} 0.0100000 0.0000000 0.0000000 0.0000000{_sep}" + $" 0.0000000 0.0000000 0.0000000 0.0000000{_sep}", str); } } [Fact] public void Test4DToString() { { Tensor t = torch.tensor(new float[] { 0.0f, 3.141f, 6.2834f, 3.14152f, 6.28e-06f, -13.141529f, 0.01f, 4713.14f, 0.01f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 3.141f, 6.2834f, 3.14152f, 6.28e-06f, -13.141529f, 0.01f, 4713.14f, 0.01f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, }, 2, 2, 2, 4); var str = t.ToString(true); Assert.Equal($"[2x2x2x4], type = Float32, device = cpu{_sep}{_sep}[0,0,:,:] ={_sep} 0 3.141 6.2834 3.1415{_sep}" + $" 6.28e-06 -13.142 0.01 4713.1{_sep}{_sep}[0,1,:,:] ={_sep} 0.01 0 0 0{_sep} 0 0 0 0{_sep}{_sep}" + $"[1,0,:,:] ={_sep} 0 3.141 6.2834 3.1415{_sep} 6.28e-06 -13.142 0.01 4713.1{_sep}{_sep}" + $"[1,1,:,:] ={_sep} 0.01 0 0 0{_sep} 0 0 0 0{_sep}", str); } } [Fact] public void Test5DToString() { { Tensor t = torch.tensor(new float[] { 0.0f, 3.141f, 6.2834f, 3.14152f, 6.28e-06f, -13.141529f, 0.01f, 4713.14f, 0.01f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 3.141f, 6.2834f, 3.14152f, 6.28e-06f, -13.141529f, 0.01f, 4713.14f, 0.01f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 3.141f, 6.2834f, 3.14152f, 6.28e-06f, -13.141529f, 0.01f, 4713.14f, 0.01f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 3.141f, 6.2834f, 3.14152f, 6.28e-06f, -13.141529f, 0.01f, 4713.14f, 0.01f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, }, new long[] { 2, 2, 2, 2, 4 }); var str = t.ToString(true); Assert.Equal($"[2x2x2x2x4], type = Float32, device = cpu{_sep}{_sep}[0,0,0,:,:] ={_sep} 0 3.141 6.2834 3.1415{_sep}" + $" 6.28e-06 -13.142 0.01 4713.1{_sep}{_sep}[0,0,1,:,:] ={_sep} 0.01 0 0 0{_sep} 0 0 0 0{_sep}{_sep}[0,1,0,:,:] ={_sep}" + $" 0 3.141 6.2834 3.1415{_sep} 6.28e-06 -13.142 0.01 4713.1{_sep}{_sep}[0,1,1,:,:] ={_sep} 0.01 0 0 0{_sep} " + $" 0 0 0 0{_sep}{_sep}[1,0,0,:,:] ={_sep} 0 3.141 6.2834 3.1415{_sep} 6.28e-06 -13.142 0.01 4713.1{_sep}{_sep}" + $"[1,0,1,:,:] ={_sep} 0.01 0 0 0{_sep} 0 0 0 0{_sep}{_sep}[1,1,0,:,:] ={_sep} 0 3.141 6.2834 3.1415{_sep}" + $" 6.28e-06 -13.142 0.01 4713.1{_sep}{_sep}[1,1,1,:,:] ={_sep} 0.01 0 0 0{_sep} 0 0 0 0{_sep}", str); } } [Fact] public void Test6DToString() { { Tensor t = torch.tensor(new float[] { 0.0f, 3.141f, 6.2834f, 3.14152f, 6.28e-06f, -13.141529f, 0.01f, 4713.14f, 0.01f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 3.141f, 6.2834f, 3.14152f, 6.28e-06f, -13.141529f, 0.01f, 4713.14f, 0.01f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 3.141f, 6.2834f, 3.14152f, 6.28e-06f, -13.141529f, 0.01f, 4713.14f, 0.01f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 3.141f, 6.2834f, 3.14152f, 6.28e-06f, -13.141529f, 0.01f, 4713.14f, 0.01f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 3.141f, 6.2834f, 3.14152f, 6.28e-06f, -13.141529f, 0.01f, 4713.14f, 0.01f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 3.141f, 6.2834f, 3.14152f, 6.28e-06f, -13.141529f, 0.01f, 4713.14f, 0.01f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 3.141f, 6.2834f, 3.14152f, 6.28e-06f, -13.141529f, 0.01f, 4713.14f, 0.01f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 3.141f, 6.2834f, 3.14152f, 6.28e-06f, -13.141529f, 0.01f, 4713.14f, 0.01f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, }, new long[] { 2, 2, 2, 2, 2, 4 }); var str = t.ToString(true); Assert.Equal($"[2x2x2x2x2x4], type = Float32, device = cpu{_sep}{_sep}[0,0,0,0,:,:] ={_sep} 0 3.141 6.2834 3.1415{_sep}" + $" 6.28e-06 -13.142 0.01 4713.1{_sep}{_sep}[0,0,0,1,:,:] ={_sep} 0.01 0 0 0{_sep} 0 0 0 0{_sep}{_sep}[0,0,1,0,:,:] ={_sep}" + $" 0 3.141 6.2834 3.1415{_sep} 6.28e-06 -13.142 0.01 4713.1{_sep}{_sep}[0,0,1,1,:,:] ={_sep} 0.01 0 0 0{_sep} 0 0 0 0{_sep}{_sep}" + $"[0,1,0,0,:,:] ={_sep} 0 3.141 6.2834 3.1415{_sep} 6.28e-06 -13.142 0.01 4713.1{_sep}{_sep}[0,1,0,1,:,:] ={_sep} 0.01 0 0 0{_sep}" + $" 0 0 0 0{_sep}{_sep}[0,1,1,0,:,:] ={_sep} 0 3.141 6.2834 3.1415{_sep} 6.28e-06 -13.142 0.01 4713.1{_sep}{_sep}" + $"[0,1,1,1,:,:] ={_sep} 0.01 0 0 0{_sep} 0 0 0 0{_sep}{_sep}[1,0,0,0,:,:] ={_sep} 0 3.141 6.2834 3.1415{_sep}" + $" 6.28e-06 -13.142 0.01 4713.1{_sep}{_sep}[1,0,0,1,:,:] ={_sep} 0.01 0 0 0{_sep} 0 0 0 0{_sep}{_sep}[1,0,1,0,:,:] ={_sep}" + $" 0 3.141 6.2834 3.1415{_sep} 6.28e-06 -13.142 0.01 4713.1{_sep}{_sep}[1,0,1,1,:,:] ={_sep} 0.01 0 0 0{_sep}" + $" 0 0 0 0{_sep}{_sep}[1,1,0,0,:,:] ={_sep} 0 3.141 6.2834 3.1415{_sep} 6.28e-06 -13.142 0.01 4713.1{_sep}{_sep}" + $"[1,1,0,1,:,:] ={_sep} 0.01 0 0 0{_sep} 0 0 0 0{_sep}{_sep}[1,1,1,0,:,:] ={_sep} 0 3.141 6.2834 3.1415{_sep}" + $" 6.28e-06 -13.142 0.01 4713.1{_sep}{_sep}[1,1,1,1,:,:] ={_sep} 0.01 0 0 0{_sep} 0 0 0 0{_sep}", str); } } [Fact] public void TestDataBool() { var x = torch.ones(5, torch.@bool); Assert.Throws<System.ArgumentException>(() => x.data<byte>()); Assert.Throws<System.ArgumentException>(() => x.data<sbyte>()); Assert.Throws<System.ArgumentException>(() => x.data<short>()); Assert.Throws<System.ArgumentException>(() => x.data<int>()); Assert.Throws<System.ArgumentException>(() => x.data<long>()); Assert.Throws<System.ArgumentException>(() => x.data<float>()); Assert.Throws<System.ArgumentException>(() => x.data<double>()); Assert.Throws<System.ArgumentException>(() => x.data<(float, float)>()); Assert.Throws<System.ArgumentException>(() => x.data<System.Numerics.Complex>()); x.data<bool>(); } [Fact] public void TestDataByte() { var x = torch.ones(5, torch.uint8); Assert.Throws<System.ArgumentException>(() => x.data<bool>()); Assert.Throws<System.ArgumentException>(() => x.data<sbyte>()); Assert.Throws<System.ArgumentException>(() => x.data<short>()); Assert.Throws<System.ArgumentException>(() => x.data<int>()); Assert.Throws<System.ArgumentException>(() => x.data<long>()); Assert.Throws<System.ArgumentException>(() => x.data<float>()); Assert.Throws<System.ArgumentException>(() => x.data<double>()); Assert.Throws<System.ArgumentException>(() => x.data<(float, float)>()); Assert.Throws<System.ArgumentException>(() => x.data<System.Numerics.Complex>()); x.data<byte>(); } [Fact] public void TestDataInt8() { var x = torch.ones(5, torch.int8); Assert.Throws<System.ArgumentException>(() => x.data<bool>()); Assert.Throws<System.ArgumentException>(() => x.data<byte>()); Assert.Throws<System.ArgumentException>(() => x.data<short>()); Assert.Throws<System.ArgumentException>(() => x.data<int>()); Assert.Throws<System.ArgumentException>(() => x.data<long>()); Assert.Throws<System.ArgumentException>(() => x.data<float>()); Assert.Throws<System.ArgumentException>(() => x.data<double>()); Assert.Throws<System.ArgumentException>(() => x.data<(float, float)>()); Assert.Throws<System.ArgumentException>(() => x.data<System.Numerics.Complex>()); x.data<sbyte>(); } [Fact] public void TestDataInt16() { var x = torch.ones(5, torch.int16); Assert.Throws<System.ArgumentException>(() => x.data<bool>()); Assert.Throws<System.ArgumentException>(() => x.data<byte>()); Assert.Throws<System.ArgumentException>(() => x.data<sbyte>()); Assert.Throws<System.ArgumentException>(() => x.data<int>()); Assert.Throws<System.ArgumentException>(() => x.data<long>()); Assert.Throws<System.ArgumentException>(() => x.data<float>()); Assert.Throws<System.ArgumentException>(() => x.data<double>()); Assert.Throws<System.ArgumentException>(() => x.data<(float, float)>()); Assert.Throws<System.ArgumentException>(() => x.data<System.Numerics.Complex>()); x.data<short>(); } [Fact] public void TestDataInt32() { var x = torch.ones(5, torch.int32); Assert.Throws<System.ArgumentException>(() => x.data<bool>()); Assert.Throws<System.ArgumentException>(() => x.data<byte>()); Assert.Throws<System.ArgumentException>(() => x.data<sbyte>()); Assert.Throws<System.ArgumentException>(() => x.data<short>()); Assert.Throws<System.ArgumentException>(() => x.data<long>()); Assert.Throws<System.ArgumentException>(() => x.data<float>()); Assert.Throws<System.ArgumentException>(() => x.data<double>()); Assert.Throws<System.ArgumentException>(() => x.data<(float, float)>()); Assert.Throws<System.ArgumentException>(() => x.data<System.Numerics.Complex>()); x.data<int>(); } [Fact] public void TestDataInt64() { var x = torch.ones(5, torch.int64); Assert.Throws<System.ArgumentException>(() => x.data<bool>()); Assert.Throws<System.ArgumentException>(() => x.data<byte>()); Assert.Throws<System.ArgumentException>(() => x.data<sbyte>()); Assert.Throws<System.ArgumentException>(() => x.data<short>()); Assert.Throws<System.ArgumentException>(() => x.data<int>()); Assert.Throws<System.ArgumentException>(() => x.data<float>()); Assert.Throws<System.ArgumentException>(() => x.data<double>()); Assert.Throws<System.ArgumentException>(() => x.data<(float, float)>()); Assert.Throws<System.ArgumentException>(() => x.data<System.Numerics.Complex>()); x.data<long>(); } [Fact] public void TestDataFloat32() { var x = torch.ones(5, torch.float32); Assert.Throws<System.ArgumentException>(() => x.data<bool>()); Assert.Throws<System.ArgumentException>(() => x.data<byte>()); Assert.Throws<System.ArgumentException>(() => x.data<sbyte>()); Assert.Throws<System.ArgumentException>(() => x.data<short>()); Assert.Throws<System.ArgumentException>(() => x.data<int>()); Assert.Throws<System.ArgumentException>(() => x.data<long>()); Assert.Throws<System.ArgumentException>(() => x.data<double>()); Assert.Throws<System.ArgumentException>(() => x.data<(float, float)>()); Assert.Throws<System.ArgumentException>(() => x.data<System.Numerics.Complex>()); x.data<float>(); } [Fact] public void TestDataFloat64() { var x = torch.ones(5, torch.float64); Assert.Throws<System.ArgumentException>(() => x.data<bool>()); Assert.Throws<System.ArgumentException>(() => x.data<byte>()); Assert.Throws<System.ArgumentException>(() => x.data<sbyte>()); Assert.Throws<System.ArgumentException>(() => x.data<short>()); Assert.Throws<System.ArgumentException>(() => x.data<int>()); Assert.Throws<System.ArgumentException>(() => x.data<long>()); Assert.Throws<System.ArgumentException>(() => x.data<float>()); Assert.Throws<System.ArgumentException>(() => x.data<(float,float)>()); Assert.Throws<System.ArgumentException>(() => x.data<System.Numerics.Complex>()); x.data<double>(); } [Fact] public void TestDataItemBool() { var x = torch.ones(1, torch.@bool); Assert.Throws<System.ArgumentException>(() => x.item<byte>()); Assert.Throws<System.ArgumentException>(() => x.item<sbyte>()); Assert.Throws<System.ArgumentException>(() => x.item<short>()); Assert.Throws<System.ArgumentException>(() => x.item<int>()); Assert.Throws<System.ArgumentException>(() => x.item<long>()); Assert.Throws<System.ArgumentException>(() => x.item<float>()); Assert.Throws<System.ArgumentException>(() => x.item<double>()); Assert.Throws<System.ArgumentException>(() => x.item<(float, float)>()); Assert.Throws<System.ArgumentException>(() => x.item<System.Numerics.Complex>()); x.item<bool>(); } [Fact] public void TestDataItemByte() { var x = torch.ones(1, torch.uint8); Assert.Throws<System.ArgumentException>(() => x.item<bool>()); Assert.Throws<System.ArgumentException>(() => x.item<sbyte>()); Assert.Throws<System.ArgumentException>(() => x.item<short>()); Assert.Throws<System.ArgumentException>(() => x.item<int>()); Assert.Throws<System.ArgumentException>(() => x.item<long>()); Assert.Throws<System.ArgumentException>(() => x.item<float>()); Assert.Throws<System.ArgumentException>(() => x.item<double>()); Assert.Throws<System.ArgumentException>(() => x.item<(float, float)>()); Assert.Throws<System.ArgumentException>(() => x.item<System.Numerics.Complex>()); x.item<byte>(); } [Fact] public void TestDataItemInt8() { var x = torch.ones(1, torch.int8); Assert.Throws<System.ArgumentException>(() => x.item<bool>()); Assert.Throws<System.ArgumentException>(() => x.item<byte>()); Assert.Throws<System.ArgumentException>(() => x.item<short>()); Assert.Throws<System.ArgumentException>(() => x.item<int>()); Assert.Throws<System.ArgumentException>(() => x.item<long>()); Assert.Throws<System.ArgumentException>(() => x.item<float>()); Assert.Throws<System.ArgumentException>(() => x.item<double>()); Assert.Throws<System.ArgumentException>(() => x.item<(float, float)>()); Assert.Throws<System.ArgumentException>(() => x.item<System.Numerics.Complex>()); x.item<sbyte>(); } [Fact] public void TestDataItemInt16() { var x = torch.ones(1, torch.int16); Assert.Throws<System.ArgumentException>(() => x.item<bool>()); Assert.Throws<System.ArgumentException>(() => x.item<byte>()); Assert.Throws<System.ArgumentException>(() => x.item<sbyte>()); Assert.Throws<System.ArgumentException>(() => x.item<int>()); Assert.Throws<System.ArgumentException>(() => x.item<long>()); Assert.Throws<System.ArgumentException>(() => x.item<float>()); Assert.Throws<System.ArgumentException>(() => x.item<double>()); Assert.Throws<System.ArgumentException>(() => x.item<(float, float)>()); Assert.Throws<System.ArgumentException>(() => x.item<System.Numerics.Complex>()); x.item<short>(); } [Fact] public void TestDataItemInt32() { var x = torch.ones(1, torch.int32); Assert.Throws<System.ArgumentException>(() => x.item<bool>()); Assert.Throws<System.ArgumentException>(() => x.item<byte>()); Assert.Throws<System.ArgumentException>(() => x.item<sbyte>()); Assert.Throws<System.ArgumentException>(() => x.item<short>()); Assert.Throws<System.ArgumentException>(() => x.item<long>()); Assert.Throws<System.ArgumentException>(() => x.item<float>()); Assert.Throws<System.ArgumentException>(() => x.item<double>()); Assert.Throws<System.ArgumentException>(() => x.item<(float, float)>()); Assert.Throws<System.ArgumentException>(() => x.item<System.Numerics.Complex>()); x.item<int>(); } [Fact] public void TestDataItemInt64() { var x = torch.ones(1, torch.int64); Assert.Throws<System.ArgumentException>(() => x.item<bool>()); Assert.Throws<System.ArgumentException>(() => x.item<byte>()); Assert.Throws<System.ArgumentException>(() => x.item<sbyte>()); Assert.Throws<System.ArgumentException>(() => x.item<short>()); Assert.Throws<System.ArgumentException>(() => x.item<int>()); Assert.Throws<System.ArgumentException>(() => x.item<float>()); Assert.Throws<System.ArgumentException>(() => x.item<double>()); Assert.Throws<System.ArgumentException>(() => x.item<(float, float)>()); Assert.Throws<System.ArgumentException>(() => x.item<System.Numerics.Complex>()); x.item<long>(); } [Fact] public void TestDataItemFloat32() { var x = torch.ones(1, torch.float32); Assert.Throws<System.ArgumentException>(() => x.item<bool>()); Assert.Throws<System.ArgumentException>(() => x.item<byte>()); Assert.Throws<System.ArgumentException>(() => x.item<sbyte>()); Assert.Throws<System.ArgumentException>(() => x.item<short>()); Assert.Throws<System.ArgumentException>(() => x.item<int>()); Assert.Throws<System.ArgumentException>(() => x.item<long>()); Assert.Throws<System.ArgumentException>(() => x.item<double>()); Assert.Throws<System.ArgumentException>(() => x.item<(float, float)>()); Assert.Throws<System.ArgumentException>(() => x.item<System.Numerics.Complex>()); x.item<float>(); } [Fact] public void TestDataItemFloat64() { var x = torch.ones(1, torch.float64); Assert.Throws<System.ArgumentException>(() => x.item<bool>()); Assert.Throws<System.ArgumentException>(() => x.item<byte>()); Assert.Throws<System.ArgumentException>(() => x.item<sbyte>()); Assert.Throws<System.ArgumentException>(() => x.item<short>()); Assert.Throws<System.ArgumentException>(() => x.item<int>()); Assert.Throws<System.ArgumentException>(() => x.item<long>()); Assert.Throws<System.ArgumentException>(() => x.item<float>()); Assert.Throws<System.ArgumentException>(() => x.item<(float, float)>()); Assert.Throws<System.ArgumentException>(() => x.item<System.Numerics.Complex>()); x.item<double>(); } [Fact] public void CreateFloat32TensorZeros() { var shape = new long[] { 2, 2 }; Tensor t = torch.zeros(shape); Assert.Equal(shape, t.shape); Assert.Equal(0.0f, t[0, 0].ToSingle()); Assert.Equal(0.0f, t[1, 1].ToSingle()); } [Fact] public void CreateFloat32TensorZeros_() { var shape = new long[] { 2, 2 }; Tensor t = torch.zeros(shape); Assert.Equal(shape, t.shape); Assert.Equal(0.0f, t[0, 0].ToSingle()); Assert.Equal(0.0f, t[1, 1].ToSingle()); } [Fact] public void CreateByteTensorZeros() { var shape = new long[] { 2, 2 }; Tensor t = torch.zeros(shape, torch.uint8); Assert.Equal(shape, t.shape); Assert.Equal((byte)0, t[0, 0].ToByte()); Assert.Equal((byte)0, t[1, 1].ToByte()); } [Fact] public void CreateByteTensorZeros_() { var shape = new long[] { 2, 2 }; Tensor t = torch.zeros(shape, torch.uint8); Assert.Equal(shape, t.shape); Assert.Equal((byte)0, t[0, 0].ToByte()); Assert.Equal((byte)0, t[1, 1].ToByte()); } [Fact] public void CreateInt32TensorZeros() { var shape = new long[] { 2, 2 }; Tensor t = torch.zeros(shape, torch.int32); Assert.Equal(shape, t.shape); Assert.Equal(0, t[0, 0].ToInt32()); Assert.Equal(0, t[1, 1].ToInt32()); } [Fact] public void CreateInt32TensorZeros_() { var shape = new long[] { 2, 2 }; Tensor t = torch.zeros(shape, torch.int32); Assert.Equal(shape, t.shape); Assert.Equal(0, t[0, 0].ToInt32()); Assert.Equal(0, t[1, 1].ToInt32()); } [Fact] public void CreateInt64TensorZeros() { var shape = new long[] { 2, 2 }; Tensor t = torch.zeros(shape, torch.int64); Assert.Equal(shape, t.shape); Assert.Equal(0L, t[0, 0].ToInt64()); Assert.Equal(0L, t[1, 1].ToInt64()); } [Fact] public void CreateBoolTensorZeros() { var shape = new long[] { 2, 2 }; Tensor t = torch.zeros(shape, torch.@bool); Assert.Equal(shape, t.shape); Assert.Equal((object)false, t[0, 0].ToBoolean()); Assert.Equal((object)false, t[1, 1].ToBoolean()); } [Fact] public void CreateFloat16TensorZeros() { foreach (var device in new Device[] { torch.CUDA }) { if (device.type != DeviceType.CUDA || torch.cuda.is_available()) { var shape = new long[] { 2, 2 }; Tensor t = torch.zeros(shape, device: device, dtype: torch.float16); Assert.Equal(shape, t.shape); Assert.Equal(0.0f, t[0, 0].ToSingle()); Assert.Equal(0.0f, t[1, 1].ToSingle()); } } } [Fact] public void CreateBFloat16TensorZeros() { foreach (var device in new Device[] { torch.CUDA }) { if (device.type != DeviceType.CUDA || torch.cuda.is_available()) { var shape = new long[] { 2, 2 }; Tensor t = torch.zeros(shape, device: device, dtype: torch.bfloat16); Assert.Equal(shape, t.shape); Assert.Equal(0.0f, t[0, 0].ToSingle()); Assert.Equal(0.0f, t[1, 1].ToSingle()); } } } [Fact] public void CreateFloat32TensorEmpty() { var shape = new long[] { 2, 2 }; Tensor t = torch.empty(shape); Assert.Equal(shape, t.shape); } [Fact] public void CreateFloat32TensorFull() { var shape = new long[] { 2, 2 }; Tensor t = torch.full(2, 2, 3.14f); Assert.Equal(shape, t.shape); Assert.Equal(3.14f, t[0, 0].ToSingle()); Assert.Equal(3.14f, t[1, 1].ToSingle()); } [Fact] public void CreateByteTensorEmpty() { var shape = new long[] { 2, 2 }; Tensor t = torch.empty(shape, torch.uint8); Assert.Equal(shape, t.shape); } [Fact] public void CreateInt32TensorEmpty() { var shape = new long[] { 2, 2 }; Tensor t = torch.empty(shape, torch.int32); Assert.Equal(shape, t.shape); } [Fact] public void CreateInt32TensorFull() { var shape = new long[] { 2, 2 }; Tensor t = torch.full(2, 2, 17, torch.int32); Assert.Equal(shape, t.shape); Assert.Equal(17, t[0, 0].ToInt32()); Assert.Equal(17, t[1, 1].ToInt32()); } [Fact] public void CreateInt64TensorEmpty() { var shape = new long[] { 2, 2 }; Tensor t = torch.empty(shape, torch.int64); Assert.Equal(shape, t.shape); } [Fact] public void CreateBoolTensorEmpty() { var shape = new long[] { 2, 2 }; Tensor t = torch.empty(shape, @bool); Assert.Equal(shape, t.shape); } [Fact] public void CreateTensorEmptyStrided() { var shape = new long[] { 2, 3 }; var strides = new long[] { 1, 2 }; Tensor t = torch.empty_strided(shape, strides); Assert.Equal(shape, t.shape); Assert.Equal(1, t.stride(0)); Assert.Equal(2, t.stride(1)); t = torch.empty_strided(shape, strides); Assert.Equal(shape, t.shape); Assert.Equal(1, t.stride(0)); Assert.Equal(2, t.stride(1)); } [Fact] public void CreateTensorEmptyAsStrided() { var shape = new long[] { 2, 3 }; var strides = new long[] { 1, 2 }; Tensor t = torch.empty(shape).as_strided(shape, strides); Assert.Equal(shape, t.shape); Assert.Equal(1, t.stride(0)); Assert.Equal(2, t.stride(1)); t = torch.empty(shape).as_strided(shape, strides); Assert.Equal(shape, t.shape); Assert.Equal(1, t.stride(0)); Assert.Equal(2, t.stride(1)); } [Fact] public void CreateFloat16TensorEmpty() { foreach (var device in new Device[] { torch.CUDA }) { if (device.type != DeviceType.CUDA || torch.cuda.is_available()) { var shape = new long[] { 2, 2 }; Tensor t = torch.empty(shape, float16, device: device); Assert.Equal(shape, t.shape); } } } [Fact] public void CreateBFloat16TensorEmpty() { foreach (var device in new Device[] { torch.CUDA }) { if (device.type != DeviceType.CUDA || torch.cuda.is_available()) { var shape = new long[] { 2, 2 }; Tensor t = torch.empty(shape, bfloat16, device: device); Assert.Equal(shape, t.shape); } } } [Fact] public void CreateFloat32Linspace() { Tensor t = torch.linspace(0.0f, 10.0f, 101); Assert.Equal(101, t.shape[0]); Assert.Equal(0.0f, t[0].ToSingle()); Assert.Equal(0.1f, t[1].ToSingle()); } [Fact] public void CreateFloat32Logspace() { Tensor t = torch.logspace(0.0f, 10.0f, 101); Assert.Equal(101, t.shape[0]); Assert.Equal(1.0f, t[0].ToSingle()); Assert.Equal(10.0f, t[10].ToSingle()); } [Fact] public void CreateFloat32TensorOnes() { var shape = new long[] { 2, 2 }; Tensor t = torch.ones(shape); Assert.Equal(shape, t.shape); Assert.Equal(1.0f, t[0, 0].ToSingle()); Assert.Equal(1.0f, t[1, 1].ToSingle()); } [Fact] public void CreateByteTensorOnes() { var shape = new long[] { 2, 2 }; Tensor t = torch.ones(shape, uint8); Assert.Equal(shape, t.shape); Assert.Equal((byte)1, t[0, 0].ToByte()); Assert.Equal((byte)1, t[1, 1].ToByte()); } [Fact] public void CreateInt32TensorOnes() { var shape = new long[] { 2, 2 }; Tensor t = torch.ones(shape, int32); Assert.Equal(shape, t.shape); Assert.Equal(1, t[0, 0].ToInt32()); Assert.Equal(1, t[1, 1].ToInt32()); } [Fact] public void CreateInt64TensorOnes() { var shape = new long[] { 2, 2 }; Tensor t = torch.ones(shape, int64); Assert.Equal(shape, t.shape); Assert.Equal(1L, t[0, 0].ToInt64()); Assert.Equal(1L, t[1, 1].ToInt64()); } [Fact] public void CreateBoolTensorOnes() { var shape = new long[] { 2, 2 }; Tensor t = torch.ones(shape, @bool); Assert.Equal(shape, t.shape); Assert.Equal((object)true, t[0, 0].ToBoolean()); Assert.Equal((object)true, t[1, 1].ToBoolean()); } [Fact] public void CreateFloat16TensorOnes() { foreach (var device in new Device[] { torch.CUDA }) { if (device.type != DeviceType.CUDA || torch.cuda.is_available()) { var shape = new long[] { 2, 2 }; Tensor t = torch.ones(shape, float16, device: device); Assert.Equal(shape, t.shape); Assert.Equal(1.0f, t[0, 0].ToSingle()); Assert.Equal(1.0f, t[1, 1].ToSingle()); } } } [Fact] public void CreateBFloat16TensorOnes() { foreach (var device in new Device[] { torch.CUDA }) { if (device.type != DeviceType.CUDA || torch.cuda.is_available()) { var shape = new long[] { 2, 2 }; Tensor t = torch.ones(shape, bfloat16, device: device); Assert.Equal(shape, t.shape); Assert.Equal(1.0f, t[0, 0].ToSingle()); Assert.Equal(1.0f, t[1, 1].ToSingle()); } } } [Fact] public void CreateComplexFloat32TensorZeros() { var shape = new long[] { 2, 2 }; Tensor t = torch.zeros(shape, torch.complex64); Assert.Equal(shape, t.shape); var v3 = t.data<(float Real, float Imaginary)>().ToArray(); for (var i = 0; i < v3.Length; i++) { Assert.Equal(0.0f, v3[i].Real); Assert.Equal(0.0f, v3[i].Imaginary); } } [Fact] public void CreateComplexFloat32TensorOnes() { var shape = new long[] { 2, 2 }; Tensor t = torch.ones(shape, torch.complex64); Assert.Equal(shape, t.shape); var v3 = t.data<(float Real, float Imaginary)>().ToArray(); for (var i = 0; i < v3.Length; i++) { Assert.Equal(1.0f, v3[i].Real); Assert.Equal(0.0f, v3[i].Imaginary); } } [Fact] public void CreateComplex32() { var shape = new long[] { 2, 2 }; Tensor r = torch.randn(shape); Tensor i = torch.randn(shape); Tensor x = torch.complex(r, i); Assert.Equal(shape, x.shape); Assert.Equal(ScalarType.ComplexFloat32, x.dtype); Assert.True(r.allclose(x.real)); Assert.True(i.allclose(x.imag)); } [Fact] public void CreateComplex64() { var shape = new long[] { 2, 2 }; Tensor r = torch.randn(shape, torch.float64); Tensor i = torch.randn(shape, torch.float64); Tensor x = torch.complex(r, i); Assert.Equal(shape, x.shape); Assert.Equal(ScalarType.ComplexFloat64, x.dtype); Assert.True(r.allclose(x.real)); Assert.True(i.allclose(x.imag)); } [Fact] public void CreatePolar32() { var shape = new long[] { 2, 2 }; Tensor r = torch.randn(shape); Tensor i = torch.randn(shape); Tensor x = torch.complex(r, i); Tensor p = torch.polar(x.abs(), x.angle()); Assert.Equal(x.shape, p.shape); Assert.Equal(ScalarType.ComplexFloat32, p.dtype); Assert.True(r.allclose(p.real, rtol: 1e-04, atol: 1e-07)); Assert.True(i.allclose(p.imag, rtol: 1e-04, atol: 1e-07)); } [Fact] public void CreatePolar64() { var shape = new long[] { 2, 2 }; Tensor r = torch.randn(shape, torch.float64); Tensor i = torch.randn(shape, torch.float64); Tensor x = torch.complex(r, i); Tensor p = torch.polar(x.abs(), x.angle()); Assert.Equal(x.shape, p.shape); Assert.Equal(ScalarType.ComplexFloat64, p.dtype); Assert.True(r.allclose(p.real, rtol: 1e-04, atol: 1e-07)); Assert.True(i.allclose(p.imag, rtol: 1e-04, atol: 1e-07)); } [Fact] public void CreateComplexFloat32TensorRand() { var shape = new long[] { 2, 2 }; Tensor t = torch.rand(shape, torch.complex64); Assert.Equal(shape, t.shape); var v3 = t.data<(float Real, float Imaginary)>().ToArray(); Assert.All(v3, t => Assert.True(t.Real >= 0.0f && t.Real < 1.0f && t.Imaginary >= 0.0f && t.Imaginary < 1.0f)); } [Fact] public void CreateComplexFloat32TensorRandn() { var shape = new long[] { 2, 2 }; Tensor t = torch.randn(shape, torch.complex64); Assert.Equal(shape, t.shape); var v3 = t.data<(float Real, float Imaginary)>().ToArray(); } [Fact] public void CreateComplexFloat64TensorZeros() { var shape = new long[] { 2, 2 }; Tensor t = torch.zeros(shape, complex128); Assert.Equal(shape, t.shape); var v3 = t.data<System.Numerics.Complex>().ToArray(); for (var i = 0; i < v3.Length; i++) { Assert.Equal(0.0, v3[i].Real); Assert.Equal(0.0, v3[i].Imaginary); } } [Fact] public void CreateComplexFloat64TensorOnes() { var shape = new long[] { 2, 2 }; Tensor t = torch.ones(shape, complex128); Assert.Equal(shape, t.shape); var v3 = t.data<System.Numerics.Complex>().ToArray(); for (var i = 0; i < v3.Length; i++) { Assert.Equal(1.0, v3[i].Real); Assert.Equal(0.0, v3[i].Imaginary); } } [Fact] public void CreateFloat32TensorCheckMemory() { Tensor? ones = null; for (int i = 0; i < 10; i++) { using (var tmp = torch.ones(new long[] { 100, 100, 100 })) { ones = tmp; Assert.NotNull(ones); } } } [Fact] public void CreateFloat32TensorOnesCheckData() { var ones = torch.ones(new long[] { 2, 2 }); var data = ones.data<float>(); for (int i = 0; i < 4; i++) { Assert.Equal(1.0, data[i]); } } [Fact] public void CreateFloat32TensorZerosCheckData() { var zeros = torch.zeros(new long[] { 2, 2 }); var data = zeros.data<float>(); for (int i = 0; i < 4; i++) { Assert.Equal(0, data[i]); } } [Fact] public void CreateInt32TensorOnesCheckData() { var ones = torch.ones(new long[] { 2, 2 }, int32); var data = ones.data<int>(); for (int i = 0; i < 4; i++) { Assert.Equal(1, data[i]); } } [Fact] public void CreateInt32TensorEyeCheckData1() { var ones = torch.eye(4, 4, int32); Assert.Equal(ones.shape[0], ones.shape[1]); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (i == j) Assert.Equal(1, ones[i, j].ToInt32()); else Assert.Equal(0, ones[i, j].ToInt32()); } } } [Fact] public void CreateInt32TensorEyeCheckData2() { var ones = torch.eye(4, dtype: torch.int32); Assert.Equal(ones.shape[0], ones.shape[1]); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (i == j) Assert.Equal(1, ones[i, j].ToInt32()); else Assert.Equal(0, ones[i, j].ToInt32()); } } } [Fact] public void CreateComplexFloat32TensorEyeCheckData() { var ones = torch.eye(4, 4, torch.complex64); Assert.Equal(ones.shape[0], ones.shape[1]); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (i == j) { var scalar = ones[i, j].ToComplex32(); Assert.Equal(1.0f, scalar.Real); Assert.Equal(0.0f, scalar.Imaginary); } else { var scalar = ones[i, j].ToComplex32(); Assert.Equal(0.0f, scalar.Real); Assert.Equal(0.0f, scalar.Imaginary); } } } } [Fact] public void CreateComplexFloat64TensorEyeCheckData() { var ones = torch.eye(4, 4, torch.complex128); Assert.Equal(ones.shape[0], ones.shape[1]); for (int i = 0; i < 4; i++) { for (int j = 0; j < 4; j++) { if (i == j) { var scalar = ones[i, j].ToComplex64(); Assert.Equal(1.0, scalar.Real); Assert.Equal(0.0, scalar.Imaginary); } else { var scalar = ones[i, j].ToComplex64(); Assert.Equal(0.0, scalar.Real); Assert.Equal(0.0, scalar.Imaginary); } } } } [Fact] public void CreateFloat32TensorCheckDevice() { var ones = torch.ones(new long[] { 2, 2 }); var device = ones.device; Assert.Equal("cpu", ones.device.ToString()); } [Fact] public void CreateFloat32TensorFromData() { var data = new float[1000]; data[100] = 1; using (var tensor = torch.tensor(data, new long[] { 100, 10 })) { Assert.Equal(1, tensor.data<float>()[100]); } } [Fact] public void CreateFloat32TensorFromDataCheckDispose() { var data = new float[1000]; data[100] = 1; using (var tensor = torch.tensor(data, new long[] { 100, 10 })) { Assert.Equal(1, tensor.data<float>()[100]); } Assert.Equal(1, data[100]); } [Fact] public void CreateFloat32TensorFromData2() { var data = new float[1000]; using (var tensor = data.ToTensor(new long[] { 10, 100 })) { Assert.Equal(default(float), tensor.data<float>()[100]); } } [Fact] public void CreateFloat32TensorFromDataCheckStrides() { var data = new double[] { 0.2663158, 0.1144736, 0.1147367, 0.1249998, 0.1957895, 0.1231576, 0.1944732, 0.111842, 0.1065789, 0.667881, 0.5682123, 0.5824502, 0.4824504, 0.4844371, 0.6463582, 0.5334439, 0.5079474, 0.2281452 }; var dataTensor = data.ToTensor(new long[] { 2, 9 }); for (int r = 0; r < 2; r++) { for (int i = 0; i < 9; i++) { var fromData = data[(r * 9) + i]; var fromTensor = dataTensor[r, i].ToDouble(); Assert.True(Math.Abs(fromData - fromTensor) < 0.0001); } } var firstPart = dataTensor[0]; for (int i = 0; i < 9; i++) { var fromData = data[i]; var fromChunk = firstPart[i].ToDouble(); Assert.True(Math.Abs(fromData - fromChunk) < 0.0001); } } [Fact] public void CreateFloat16TensorFromDataCheckStrides() { var data = new float[] { 0.2663158f, 0.1144736f, 0.1147367f, 0.1249998f, 0.1957895f, 0.1231576f, 0.1944732f, 0.111842f, 0.1065789f, 0.667881f, 0.5682123f, 0.5824502f, 0.4824504f, 0.4844371f, 0.6463582f, 0.5334439f, 0.5079474f, 0.2281452f }; var dataTensor = torch.tensor(data, new long[] { 2, 9 }, float16); for (int r = 0; r < 2; r++) { for (int i = 0; i < 9; i++) { var fromData = data[(r * 9) + i]; var fromTensor = dataTensor[r, i].ToSingle(); Assert.True(Math.Abs(fromData - fromTensor) < 0.01); } } var firstPart = dataTensor[0]; for (int i = 0; i < 9; i++) { var fromData = data[i]; var fromChunk = firstPart[i].ToSingle(); Assert.True(Math.Abs(fromData - fromChunk) < 0.01); } } [Fact] public void CreateBFloat16TensorFromDataCheckStrides() { var data = new float[] { 0.2663158f, 0.1144736f, 0.1147367f, 0.1249998f, 0.1957895f, 0.1231576f, 0.1944732f, 0.111842f, 0.1065789f, 0.667881f, 0.5682123f, 0.5824502f, 0.4824504f, 0.4844371f, 0.6463582f, 0.5334439f, 0.5079474f, 0.2281452f }; var dataTensor = torch.tensor(data, new long[] { 2, 9 }, bfloat16); for (int r = 0; r < 2; r++) { for (int i = 0; i < 9; i++) { var fromData = data[(r * 9) + i]; var fromTensor = dataTensor[r, i].ToSingle(); Assert.True(Math.Abs(fromData - fromTensor) < 0.1); } } var firstPart = dataTensor[0]; for (int i = 0; i < 9; i++) { var fromData = data[i]; var fromChunk = firstPart[i].ToSingle(); Assert.True(Math.Abs(fromData - fromChunk) < 0.1); } } [Fact] public void CreateFloat32BartlettWindow() { Tensor t = torch.bartlett_window(100); Assert.Equal(100, t.shape[0]); } [Fact] public void CreateFloat32BlackmanWindow() { Tensor t = torch.blackman_window(100); Assert.Equal(100, t.shape[0]); } [Fact] public void CreateFloat32HammingWindow() { Tensor t = torch.hamming_window(100); Assert.Equal(100, t.shape[0]); } [Fact] public void CreateFloat32HannWindow() { Tensor t = torch.hann_window(100); Assert.Equal(100, t.shape[0]); } [Fact] public void CreateFloat32KaiserWindow() { Tensor t = torch.kaiser_window(100); Assert.Equal(100, t.shape[0]); } [Fact] public void CreateFloat32TensorFromScalar() { float scalar = 333.0f; using (var tensor = torch.tensor(scalar)) { Assert.Equal(333.0f, tensor.ToSingle()); } } [Fact] public void CreateFloat16TensorFromScalar() { float scalar = 333.0f; using (var tensor = torch.tensor(scalar, float16)) { Assert.Equal(333.0f, tensor.ToSingle()); } } [Fact] public void CreateBFloat16TensorFromScalar() { float scalar = 333.0f; using (var tensor = torch.tensor(scalar, bfloat16)) { Assert.Equal(332.0f, tensor.ToSingle()); // NOTE: bfloat16 loses precision, this really is 332.0f } } [Fact] public void CreateFloat32TensorFromScalar2() { float scalar = 333.0f; using (var tensor = scalar.ToTensor()) { Assert.Equal(333, tensor.ToSingle()); } } [Fact] public void CreateFloat32TensorOnesLike() { var shape = new long[] { 10, 20, 30 }; Tensor t1 = torch.empty(shape); Tensor t2 = t1.ones_like(); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.Float32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.Float32, t2.dtype); Assert.All(t2.data<float>().ToArray(), t => Assert.True(t == 1.0f)); } [Fact] public void CreateFloat32TensorOnesLikeWithType() { var shape = new long[] { 10, 20, 30 }; Tensor t1 = torch.empty(shape); Tensor t2 = t1.ones_like(dtype: ScalarType.Float64); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.Float32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.Float64, t2.dtype); Assert.All(t2.data<double>().ToArray(), t => Assert.True(t == 1.0)); } [Fact] public void CreateFloat32TensorZerosLike() { var shape = new long[] { 10, 20, 30 }; Tensor t1 = torch.empty(shape); Tensor t2 = t1.zeros_like(); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.Float32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.Float32, t2.dtype); Assert.All(t2.data<float>().ToArray(), t => Assert.True(t == 0.0f)); } [Fact] public void CreateFloat32TensorZerosLikeWithType() { var shape = new long[] { 10, 20, 30 }; Tensor t1 = torch.empty(shape); Tensor t2 = t1.zeros_like(dtype: ScalarType.Float64); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.Float32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.Float64, t2.dtype); Assert.All(t2.data<double>().ToArray(), t => Assert.True(t == 0.0)); } [Fact] public void CreateFloat32TensorEmptyLike() { var shape = new long[] { 10, 20, 30 }; Tensor t1 = torch.empty(shape); Tensor t2 = t1.empty_like(); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.Float32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.Float32, t2.dtype); } [Fact] public void CreateFloat32TensorEmptyLikeWithType() { var shape = new long[] { 10, 20, 30 }; Tensor t1 = torch.empty(shape); Tensor t2 = t1.empty_like(dtype: ScalarType.Float64); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.Float32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.Float64, t2.dtype); } [Fact] public void CreateFloat32TensorFullLike() { var shape = new long[] { 10, 20, 30 }; Scalar value = 3.14f; Tensor t1 = torch.empty(shape); Tensor t2 = t1.full_like(value); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.Float32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.Float32, t2.dtype); Assert.All(t2.data<float>().ToArray(), t => Assert.True(t == 3.14f)); } [Fact] public void CreateFloat32TensorFullLikeWithType() { var shape = new long[] { 10, 20, 30 }; Scalar value = 3.14; Tensor t1 = torch.empty(shape); Tensor t2 = t1.full_like(value, dtype: ScalarType.Float64); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.Float32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.Float64, t2.dtype); Assert.All(t2.data<double>().ToArray(), t => Assert.True(t == 3.14)); } [Fact] public void CreateFloat32TensorRandLike() { var shape = new long[] { 10, 20, 30 }; Tensor t1 = torch.empty(shape); Tensor t2 = t1.rand_like(); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.Float32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.Float32, t2.dtype); Assert.All(t2.data<float>().ToArray(), t => Assert.True(t >= 0.0f && t < 1.0f)); } [Fact] public void CreateFloat32TensorRandLikeWithType() { var shape = new long[] { 10, 20, 30 }; Tensor t1 = torch.empty(shape); Tensor t2 = t1.rand_like(dtype: ScalarType.Float64); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.Float32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.Float64, t2.dtype); Assert.All(t2.data<double>().ToArray(), t => Assert.True(t >= 0.0 && t < 1.0)); } [Fact] public void CreateComplexFloat32TensorRandLike() { var shape = new long[] { 10, 20, 30 }; Tensor t1 = torch.empty(shape, complex64); Tensor t2 = t1.rand_like(); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.ComplexFloat32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.ComplexFloat32, t2.dtype); } [Fact] public void CreateComplexFloat32TensorRandLikeWithType() { var shape = new long[] { 10, 20, 30 }; Tensor t1 = torch.empty(shape); Tensor t2 = t1.rand_like(dtype: ScalarType.ComplexFloat32); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.Float32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.ComplexFloat32, t2.dtype); } [Fact] public void CreateFloat32TensorRandnLike() { var shape = new long[] { 10, 20, 30 }; Tensor t1 = torch.empty(shape); Tensor t2 = t1.randn_like(); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.Float32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.Float32, t2.dtype); } [Fact] public void CreateFloat32TensorRandnLikeWithType() { var shape = new long[] { 10, 20, 30 }; Tensor t1 = torch.empty(shape); Tensor t2 = t1.randn_like(dtype: ScalarType.Float64); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.Float32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.Float64, t2.dtype); } [Fact] public void CreateComplexFloat32TensorRandnLike() { var shape = new long[] { 10, 20, 30 }; Tensor t1 = torch.empty(shape, complex64); Tensor t2 = t1.randn_like(); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.ComplexFloat32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.ComplexFloat32, t2.dtype); } [Fact] public void CreateComplexFloat32TensorRandnLikeWithType() { var shape = new long[] { 10, 20, 30 }; Tensor t1 = torch.empty(shape); Tensor t2 = t1.randn_like(dtype: ScalarType.ComplexFloat32); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.Float32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.ComplexFloat32, t2.dtype); } [Fact] public void CreateFloat32TensorRandintLike() { var shape = new long[] { 10, 20, 30 }; Tensor t1 = torch.empty(shape); Tensor t2 = t1.randint_like(5, 15); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.Float32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.Float32, t2.dtype); Assert.All(t2.data<float>().ToArray(), t => Assert.True(t >= 5.0f && t < 15.0f)); } [Fact] public void CreateFloat32TensorRandintLikeWithType() { var shape = new long[] { 10, 20, 30 }; Tensor t1 = torch.empty(shape); Tensor t2 = t1.randint_like(5, 15, dtype: ScalarType.Float64); Assert.Equal(shape, t1.shape); Assert.Equal(ScalarType.Float32, t1.dtype); Assert.Equal(t1.shape, t2.shape); Assert.Equal(ScalarType.Float64, t2.dtype); Assert.All(t2.data<double>().ToArray(), t => Assert.True(t >= 5.0 && t < 15.0)); } [Fact] public void Float32Mean() { using (var tensor = torch.arange(1, 100, float32)) { var mean = tensor.mean().item<float>(); Assert.Equal(50.0f, mean); } } [Fact] public void Int32Mode() { using (var tensor = torch.tensor(new int[] { 1, 5, 4, 5, 3, 3, 5, 5 })) { var mode = tensor.mode(); Assert.Equal(new int[] { 5 }, mode.values.data<int>().ToArray()); Assert.Equal(new long[] { 7 }, mode.indices.data<long>().ToArray()); } } [Fact] public void GetSetItem2() { var shape = new long[] { 2, 3 }; Tensor t = torch.ones(shape); Assert.Equal(shape, t.shape); Assert.Equal(1.0f, t[0, 0].ToSingle()); Assert.Equal(1.0f, t[1, 2].ToSingle()); t[1, 2] = torch.tensor(2.0f); Assert.Equal(2.0f, t[1, 2].ToSingle()); } [Fact] public void GetSetItemComplexFloat2() { var shape = new long[] { 2, 3 }; Tensor t = torch.ones(shape, complex64); Assert.Equal(shape, t.shape); Assert.Equal(1.0f, t[0, 0].ToComplex32().Real); Assert.Equal(1.0f, t[1, 1].ToComplex32().Real); Assert.Equal(1.0f, t[1, 2].ToComplex32().Real); t[1, 1] = torch.tensor(0.5f, 1.0f, complex64); Assert.Equal(0.5f, t[1, 1].ToComplex32().Real); Assert.Equal(1.0f, t[1, 1].ToComplex32().Imaginary); t[1, 2] = torch.tensor((2.0f, 3.0f), complex64); Assert.Equal(2.0f, t[1, 2].ToComplex32().Real); Assert.Equal(3.0f, t[1, 2].ToComplex32().Imaginary); } [Fact] public void GetSetItemComplexDouble2() { var shape = new long[] { 2, 3 }; Tensor t = torch.ones(shape, complex128); Assert.Equal(shape, t.shape); Assert.Equal(1.0f, t[0, 0].ToComplex64().Real); Assert.Equal(1.0f, t[1, 1].ToComplex64().Real); Assert.Equal(1.0f, t[1, 2].ToComplex64().Real); t[0, 1] = torch.tensor((0.5, 1.0), complex128); Assert.Equal(0.5f, t[0, 1].ToComplex64().Real); Assert.Equal(1.0f, t[0, 1].ToComplex64().Imaginary); t[1, 1] = torch.tensor(0.5, 1.0, complex128); Assert.Equal(0.5f, t[1, 1].ToComplex64().Real); Assert.Equal(1.0f, t[1, 1].ToComplex64().Imaginary); t[1, 2] = torch.tensor(new System.Numerics.Complex(2.0, 3.0f), complex128); Assert.Equal(2.0f, t[1, 2].ToComplex64().Real); Assert.Equal(3.0f, t[1, 2].ToComplex64().Imaginary); } [Fact] public void GetSetItem3() { var shape = new long[] { 2, 3, 4 }; Tensor t = torch.ones(shape); Assert.Equal(shape, t.shape); Assert.Equal(1.0f, t[0, 0, 0].ToSingle()); Assert.Equal(1.0f, t[1, 2, 3].ToSingle()); t[1, 2, 3] = torch.tensor(2.0f); Assert.Equal(2.0f, t[1, 2, 3].ToSingle()); } [Fact] public void GetSetItem4() { var shape = new long[] { 2, 3, 4, 5 }; Tensor t = torch.ones(shape); Assert.Equal(shape, t.shape); Assert.Equal(1.0f, t[0, 0, 0, 0].ToSingle()); Assert.Equal(1.0f, t[1, 2, 3, 4].ToSingle()); t[1, 2, 3, 4] = torch.tensor(2.0f); Assert.Equal(2.0f, t[1, 2, 3, 4].ToSingle()); } [Fact] public void GetSetItem5() { var shape = new long[] { 2, 3, 4, 5, 6 }; Tensor t = torch.ones(shape); Assert.Equal(shape, t.shape); Assert.Equal(1.0f, t[0, 0, 0, 0, 0].ToSingle()); Assert.Equal(1.0f, t[1, 2, 3, 4, 5].ToSingle()); t[1, 2, 3, 4, 5] = torch.tensor(2.0f); Assert.Equal(2.0f, t[1, 2, 3, 4, 5].ToSingle()); } [Fact] public void GetSetItem6() { var shape = new long[] { 2, 3, 4, 5, 6, 7 }; Tensor t = torch.ones(shape); Assert.Equal(shape, t.shape); Assert.Equal(1.0f, t[0, 0, 0, 0, 0, 0].ToSingle()); Assert.Equal(1.0f, t[1, 2, 3, 4, 5, 6].ToSingle()); t[1, 2, 3, 4, 5, 6] = torch.tensor(2.0f); Assert.Equal(2.0f, t[1, 2, 3, 4, 5, 6].ToSingle()); } [Fact] public void TestScalarToTensor() { Assert.Throws<ArgumentException>(() => 1.ToTensor(requiresGrad: true)); } [Fact] public void TestScalarToTensor2() { using (var tensor = 1.ToTensor()) { Assert.Equal(ScalarType.Int32, tensor.dtype); Assert.Equal(1, tensor.ToInt32()); } using (var tensor = ((byte)1).ToTensor()) { Assert.Equal(ScalarType.Byte, tensor.dtype); Assert.Equal(1, tensor.ToByte()); } using (var tensor = ((sbyte)-1).ToTensor()) { Assert.Equal(ScalarType.Int8, tensor.dtype); Assert.Equal(-1, tensor.ToSByte()); } using (var tensor = ((short)-1).ToTensor()) { Assert.Equal(ScalarType.Int16, tensor.dtype); Assert.Equal(-1, tensor.ToInt16()); } using (var tensor = ((long)-1).ToTensor()) { Assert.Equal(ScalarType.Int64, tensor.dtype); Assert.Equal(-1L, tensor.ToInt64()); } using (var tensor = ((float)-1).ToTensor()) { Assert.Equal(ScalarType.Float32, tensor.dtype); Assert.Equal(-1.0f, tensor.ToSingle()); } using (var tensor = ((double)-1).ToTensor()) { Assert.Equal(ScalarType.Float64, tensor.dtype); Assert.Equal(-1.0, tensor.ToDouble()); } } [Fact] public void TestScalarToTensor3() { using (var tensor = 1.ToTensor()) { Assert.Equal(ScalarType.Int32, tensor.dtype); Assert.Equal(1, (int)tensor); } using (var tensor = ((byte)1).ToTensor()) { Assert.Equal(ScalarType.Byte, tensor.dtype); Assert.Equal(1, (byte)tensor); } using (var tensor = ((sbyte)-1).ToTensor()) { Assert.Equal(ScalarType.Int8, tensor.dtype); Assert.Equal(-1, (sbyte)tensor); } using (var tensor = ((short)-1).ToTensor()) { Assert.Equal(ScalarType.Int16, tensor.dtype); Assert.Equal(-1, (short)tensor); } using (var tensor = ((long)-1).ToTensor()) { Assert.Equal(ScalarType.Int64, tensor.dtype); Assert.Equal(-1L, (long)tensor); } using (var tensor = ((float)-1).ToTensor()) { Assert.Equal(ScalarType.Float32, tensor.dtype); Assert.Equal(-1.0f, (float)tensor); } using (var tensor = ((double)-1).ToTensor()) { Assert.Equal(ScalarType.Float64, tensor.dtype); Assert.Equal(-1.0, (double)tensor); } } [Fact] public void TestCalculateGain() { Assert.Equal(1, torch.nn.init.calculate_gain(torch.nn.init.NonlinearityType.Linear)); Assert.Equal(1, torch.nn.init.calculate_gain(torch.nn.init.NonlinearityType.Conv1D)); Assert.Equal(1, torch.nn.init.calculate_gain(torch.nn.init.NonlinearityType.Conv2D)); Assert.Equal(1, torch.nn.init.calculate_gain(torch.nn.init.NonlinearityType.Conv3D)); Assert.Equal(1, torch.nn.init.calculate_gain(torch.nn.init.NonlinearityType.Sigmoid)); Assert.Equal(5.0 / 3.0, torch.nn.init.calculate_gain(torch.nn.init.NonlinearityType.Tanh)); Assert.Equal(Math.Sqrt(2.0), torch.nn.init.calculate_gain(torch.nn.init.NonlinearityType.ReLU)); } [Fact] public void InfinityTest() { using (Tensor tensor = torch.empty(new long[] { 2, 2 })) { tensor.fill_(Single.PositiveInfinity); Assert.True(tensor.isposinf().data<bool>().ToArray().All(b => b)); Assert.True(tensor.isinf().data<bool>().ToArray().All(b => b)); Assert.False(tensor.isneginf().data<bool>().ToArray().All(b => b)); Assert.False(tensor.isfinite().data<bool>().ToArray().All(b => b)); tensor.fill_(Single.NegativeInfinity); Assert.True(tensor.isneginf().data<bool>().ToArray().All(b => b)); Assert.True(tensor.isinf().data<bool>().ToArray().All(b => b)); Assert.False(tensor.isposinf().data<bool>().ToArray().All(b => b)); Assert.False(tensor.isfinite().data<bool>().ToArray().All(b => b)); } } [Fact] public void TorchBernoulli() { using (var tensor = torch.bernoulli(torch.rand(5))) { Assert.Equal(5, tensor.shape[0]); } } [Fact] public void TorchMultinomial() { using (var tensor = torch.multinomial(torch.rand(5), 17, true)) { Assert.Equal(17, tensor.shape[0]); } } [Fact] public void TorchPoisson() { using (var tensor = torch.poisson(torch.rand(5))) { Assert.Equal(5, tensor.shape[0]); } } [Fact] public void InitZeros() { using (Tensor tensor = torch.zeros(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = torch.nn.init.zeros_(tensor)) { } } } [Fact] public void InitOnes() { using (Tensor tensor = torch.zeros(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = torch.nn.init.ones_(tensor)) { } } } [Fact] public void InitDirac() { using (Tensor tensor = torch.zeros(new long[] { 2, 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = torch.nn.init.dirac_(tensor)) { } } } [Fact] public void InitEye() { using (Tensor tensor = torch.zeros(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = torch.nn.init.eye_(tensor)) { } } } [Fact] public void InitConstant() { using (Tensor tensor = torch.zeros(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = torch.nn.init.constant_(tensor, Math.PI)) { } } } [Fact] public void InitUniform() { using (Tensor tensor = torch.zeros(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = torch.nn.init.uniform_(tensor)) { } } } [Fact] public void InitNormal() { using (Tensor tensor = torch.zeros(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = torch.nn.init.normal_(tensor)) { } } } [Fact] public void InitOrthogonal() { using (Tensor tensor = torch.zeros(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = torch.nn.init.orthogonal_(tensor)) { } } } [Fact] public void InitSparse() { using (Tensor tensor = torch.zeros(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = torch.nn.init.sparse_(tensor, 0.25)) { } } } [Fact] public void InitKaimingUniform() { using (Tensor tensor = torch.zeros(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = torch.nn.init.kaiming_uniform_(tensor)) { } } } [Fact] public void InitKaimingNormal() { using (Tensor tensor = torch.zeros(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = torch.nn.init.kaiming_normal_(tensor)) { } } } [Fact] public void InitXavierUniform() { using (Tensor tensor = torch.zeros(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = torch.nn.init.xavier_uniform_(tensor)) { } } } [Fact] public void InitXavierNormal() { using (Tensor tensor = torch.zeros(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = torch.nn.init.xavier_normal_(tensor)) { } } } [Fact] public void InplaceBernoulli() { using (Tensor tensor = torch.empty(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = tensor.bernoulli_()) { } using (var gen = new torch.Generator(4711L)) using (var res = tensor.bernoulli_(generator: gen)) { } } } [Fact] public void InplaceCauchy() { using (Tensor tensor = torch.empty(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = tensor.cauchy_()) { } using (var gen = new torch.Generator(4711L)) using (var res = tensor.cauchy_(generator: gen)) { } } } [Fact] public void InplaceExponential() { using (Tensor tensor = torch.empty(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = tensor.exponential_()) { } using (var gen = new torch.Generator(4711L)) using (var res = tensor.exponential_(generator: gen)) { } } } [Fact] public void InplaceGeometric() { using (Tensor tensor = torch.empty(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = tensor.geometric_(0.25)) { } using (var gen = new torch.Generator(4711L)) using (var res = tensor.geometric_(0.25, generator: gen)) { } } } [Fact] public void InplaceLogNormal() { using (Tensor tensor = torch.empty(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = tensor.log_normal_()) { } using (var gen = new torch.Generator(4711L)) using (var res = tensor.log_normal_(generator: gen)) { } } } [Fact] public void InplaceNormal() { using (Tensor tensor = torch.empty(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = tensor.normal_()) { } using (var gen = new torch.Generator(4711L)) using (var res = tensor.normal_(generator: gen)) { } } } [Fact] public void InplaceRandom() { using (Tensor tensor = torch.empty(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = tensor.random_(0.0, 1.0)) { } using (var gen = new torch.Generator(4711L)) using (var res = tensor.random_(0, 1, generator: gen)) { } } } [Fact] public void InplaceUniform() { using (Tensor tensor = torch.empty(new long[] { 2, 2 })) { // Really just testing that the native interop works and that the fact // that there are two handles to the tensor is okay. using (var res = tensor.uniform_(0.0, 1.0)) { } using (var gen = new torch.Generator(4711L)) using (var res = tensor.uniform_(0, 1, generator: gen)) { } } } [Fact] public void TestSparse() { using (var i = torch.tensor(new long[] { 0, 1, 1, 2, 0, 2 }, new long[] { 2, 3 })) using (Tensor v = new float[] { 3, 4, 5 }) { var sparse = torch.sparse(i, v, new long[] { 2, 3 }); Assert.True(sparse.is_sparse); Assert.False(i.is_sparse); Assert.False(v.is_sparse); Assert.Equal(sparse.SparseIndices.data<long>().ToArray(), new long[] { 0, 1, 1, 2, 0, 2 }); Assert.Equal(sparse.SparseValues.data<float>().ToArray(), new float[] { 3, 4, 5 }); } } [Fact] public void TestIndexSingle() { using (var i = torch.tensor(new long[] { 0, 1, 2, 6, 5, 4 }, new long[] { 2, 3 })) { Assert.Equal(0, i.index(new TensorIndex[] { TensorIndex.Single(0), TensorIndex.Single(0) }).ToInt32()); Assert.Equal(1, i.index(new TensorIndex[] { TensorIndex.Single(0), TensorIndex.Single(1) }).ToInt32()); Assert.Equal(2, i.index(new TensorIndex[] { TensorIndex.Single(0), TensorIndex.Single(2) }).ToInt32()); Assert.Equal(6, i.index(new TensorIndex[] { TensorIndex.Single(1), TensorIndex.Single(0) }).ToInt32()); Assert.Equal(5, i.index(new TensorIndex[] { TensorIndex.Single(1), TensorIndex.Single(1) }).ToInt32()); Assert.Equal(4, i.index(new TensorIndex[] { TensorIndex.Single(1), TensorIndex.Single(2) }).ToInt32()); } } [Fact] public void TestIndexEllipsis() { using (var i = torch.tensor(new long[] { 0, 1, 2, 6, 5, 4 }, new long[] { 2, 3 })) { var t1 = i.index(new TensorIndex[] { TensorIndex.Ellipsis, TensorIndex.Single(0) }); Assert.Equal(0, t1[0].ToInt32()); Assert.Equal(6, t1[1].ToInt32()); } } [Fact] public void TestIndexNull() { using (var i = torch.tensor(new long[] { 0, 1, 2, 6, 5, 4 }, new long[] { 2, 3 })) { var t1 = i.index(new TensorIndex[] { TensorIndex.None, TensorIndex.Single(0) }); Assert.Equal(0, t1[0, 0].ToInt32()); Assert.Equal(1, t1[0, 1].ToInt32()); Assert.Equal(2, t1[0, 2].ToInt32()); } } [Fact] public void TestIndexNone() { using (var i = torch.tensor(new long[] { 0, 1, 2, 6, 5, 4 }, new long[] { 2, 3 })) { var t1 = i.index(new TensorIndex[] { TensorIndex.None, TensorIndex.Single(0) }); Assert.Equal(0, t1[0, 0].ToInt32()); Assert.Equal(1, t1[0, 1].ToInt32()); Assert.Equal(2, t1[0, 2].ToInt32()); } } [Fact] public void TestIndexSlice1() { using (var i = torch.tensor(new long[] { 0, 1, 2, 6, 5, 4 }, new long[] { 2, 3 })) { var t1 = i.index(new TensorIndex[] { TensorIndex.Slice(0, 2), TensorIndex.Single(0) }); Assert.Equal(0, t1[0].ToInt32()); Assert.Equal(6, t1[1].ToInt32()); // one slice var t2 = i.index(new TensorIndex[] { TensorIndex.Slice(1, 2), TensorIndex.Single(0) }); Assert.Equal(6, t2[0].ToInt32()); // two slice var t3 = i.index(new TensorIndex[] { TensorIndex.Slice(1, 2), TensorIndex.Slice(1, 3) }); Assert.Equal(5, t3[0, 0].ToInt32()); Assert.Equal(4, t3[0, 1].ToInt32()); // slice with step var t4 = i.index(new TensorIndex[] { TensorIndex.Slice(1, 2), TensorIndex.Slice(0, 3, step: 2) }); Assert.Equal(6, t4[0, 0].ToInt32()); Assert.Equal(4, t4[0, 1].ToInt32()); // end absent var t5 = i.index(new TensorIndex[] { TensorIndex.Slice(start: 1), TensorIndex.Slice(start: 1) }); Assert.Equal(5, t5[0, 0].ToInt32()); Assert.Equal(4, t5[0, 1].ToInt32()); // start absent var t6 = i.index(new TensorIndex[] { TensorIndex.Slice(start: 1), TensorIndex.Slice(stop: 2) }); Assert.Equal(6, t6[0, 0].ToInt32()); Assert.Equal(5, t6[0, 1].ToInt32()); // start and end absent var t7 = i.index(new TensorIndex[] { TensorIndex.Slice(start: 1), TensorIndex.Slice(step: 2) }); Assert.Equal(6, t7[0, 0].ToInt32()); Assert.Equal(4, t7[0, 1].ToInt32()); } } [Fact] public void TestIndexSlice2() { using (var i = torch.tensor(new long[] { 0, 1, 2, 6, 5, 4 }, new long[] { 2, 3 })) { var t1 = i[ 0..2, 0]; Assert.Equal(0, t1[0].ToInt32()); Assert.Equal(6, t1[1].ToInt32()); // one slice var t2 = i[ 1..2, 0 ]; Assert.Equal(6, t2[0].ToInt32()); // two slice var t3 = i[ 1..2, 1..3]; Assert.Equal(5, t3[0, 0].ToInt32()); Assert.Equal(4, t3[0, 1].ToInt32()); // both absent var t4 = i[.., ..]; Assert.Equal(0, t4[0, 0].ToInt32()); Assert.Equal(1, t4[0, 1].ToInt32()); // end absent var t5 = i[1.., 1..]; Assert.Equal(5, t5[0, 0].ToInt32()); Assert.Equal(4, t5[0, 1].ToInt32()); // start absent var t6 = i[1.., ..2]; Assert.Equal(6, t6[0, 0].ToInt32()); Assert.Equal(5, t6[0, 1].ToInt32()); } } [Fact] public void CopyCpuToCuda() { Tensor cpu = torch.ones(new long[] { 2, 2 }); Assert.Equal("cpu", cpu.device.ToString()); if (torch.cuda.is_available()) { var cuda = cpu.cuda(); Assert.Equal("cuda:0", cuda.device.ToString()); // Copy back to CPU to inspect the elements var cpu2 = cuda.cpu(); Assert.Equal("cpu", cpu2.device.ToString()); var data = cpu.data<float>(); for (int i = 0; i < 4; i++) { Assert.Equal(1, data[i]); } } else { Assert.Throws<InvalidOperationException>(() => cpu.cuda()); } } [Fact] public void CopyCudaToCpu() { if (torch.cuda.is_available()) { var cuda = torch.ones(new long[] { 2, 2 }, device: torch.CUDA); Assert.Equal("cuda:0", cuda.device.ToString()); var cpu = cuda.cpu(); Assert.Equal("cpu", cpu.device.ToString()); var data = cpu.data<float>(); for (int i = 0; i < 4; i++) { Assert.Equal(1, data[i]); } } else { Assert.Throws<InvalidOperationException>((Action)(() => { torch.ones(new long[] { 2, 2 }, device: torch.CUDA); })); } } [Fact] public void TestSquareEuclideanDistance() { Tensor input = new float[] { 0.1f, 0.1f, 0.1f, 0.1f, 0.2f, 0.1f, 0.2f, 0.1f, 0.1f }; var zeros = torch.zeros(new long[] { 1, 9 }); var ones = torch.ones(new long[] { 1, 9 }); var centroids = torch.cat(new Tensor[] { zeros, ones }, 0); var distanceFromZero = input.reshape(new long[] { -1, 1, 9 }).sub(zeros).pow(2.ToScalar()).sum(new long[] { 2 }); var distanceFromOne = input.reshape(new long[] { -1, 1, 9 }).sub(ones).pow(2.ToScalar()).sum(new long[] { 2 }); var distanceFromCentroids = input.reshape(new long[] { -1, 1, 9 }).sub(centroids).pow(2.ToScalar()).sum(new long[] { 2 }); Assert.True(true); } [Fact] public void TestCat() { var zeros = torch.zeros(new long[] { 1, 9 }); var ones = torch.ones(new long[] { 1, 9 }); var centroids = torch.cat(new Tensor[] { zeros, ones }, 0); var shape = centroids.shape; Assert.Equal(new long[] { 2, 9 }, shape); } [Fact] public void TestCatCuda() { if (torch.cuda.is_available()) { var zeros = torch.zeros(new long[] { 1, 9 }).cuda(); var ones = torch.ones(new long[] { 1, 9 }).cuda(); var centroids = torch.cat(new Tensor[] { zeros, ones }, 0); var shape = centroids.shape; Assert.Equal(new long[] { 2, 9 }, shape); Assert.Equal(DeviceType.CUDA, centroids.device_type); } } [Fact] public void TestCopy() { var first = torch.rand(new long[] { 1, 9 }); var second = torch.zeros(new long[] { 1, 9 }); second.copy_(first); Assert.Equal(first, second); } [Fact] public void TestCopyCuda() { if (torch.cuda.is_available()) { var first = torch.rand(new long[] { 1, 9 }).cuda(); var second = torch.zeros(new long[] { 1, 9 }).cuda(); second.copy_(first); Assert.Equal(first, second); } } void TestStackGen(Device device) { { var t1 = torch.zeros(new long[] { }, device: device); var t2 = torch.ones(new long[] { }, device: device); var t3 = torch.ones(new long[] { }, device: device); var res = torch.stack(new Tensor[] { t1, t2, t3 }, 0); var shape = res.shape; Assert.Equal(new long[] { 3 }, shape); Assert.Equal(device.type, res.device_type); } { var t1 = torch.zeros(new long[] { }, device: device); var t2 = torch.ones(new long[] { }, device: device); var t3 = torch.ones(new long[] { }, device: device); var res = torch.hstack(new Tensor[] { t1, t2, t3 }); var shape = res.shape; Assert.Equal(new long[] { 3 }, shape); Assert.Equal(device.type, res.device_type); } { var t1 = torch.zeros(new long[] { 2, 9 }, device: device); var t2 = torch.ones(new long[] { 2, 9 }, device: device); var res = torch.stack(new Tensor[] { t1, t2 }, 0); var shape = res.shape; Assert.Equal(new long[] { 2, 2, 9 }, shape); Assert.Equal(device.type, res.device_type); } { var t1 = torch.zeros(new long[] { 2, 9 }, device: device); var t2 = torch.ones(new long[] { 2, 9 }, device: device); var res = torch.hstack(new Tensor[] { t1, t2 }); var shape = res.shape; Assert.Equal(new long[] { 2, 18 }, shape); Assert.Equal(device.type, res.device_type); } { var t1 = torch.zeros(new long[] { 2, 9 }, device: device); var t2 = torch.ones(new long[] { 2, 9 }, device: device); var res = torch.vstack(new Tensor[] { t1, t2 }); var shape = res.shape; Assert.Equal(new long[] { 4, 9 }, shape); Assert.Equal(device.type, res.device_type); } { var t1 = torch.zeros(new long[] { 2, 9 }, device: device); var t2 = torch.ones(new long[] { 2, 9 }, device: device); var res = torch.dstack(new Tensor[] { t1, t2 }); var shape = res.shape; Assert.Equal(new long[] { 2, 9, 2 }, shape); Assert.Equal(device.type, res.device_type); } } [Fact] public void TestMoveAndCast() { var input = torch.rand(new long[] { 128 }, float64, torch.CPU); if (torch.cuda.is_available()) { var moved = input.to(ScalarType.Float32, torch.CUDA); Assert.Equal(ScalarType.Float32, moved.dtype); Assert.Equal(DeviceType.CUDA, moved.device_type); } else { var moved = input.to(ScalarType.Float32); Assert.Equal(ScalarType.Float32, moved.dtype); Assert.Equal(DeviceType.CPU, moved.device_type); } } [Fact] public void TestMaskedScatter() { var input = torch.zeros(new long[] { 4, 4 }); var mask = torch.zeros(new long[] { 4, 4 }, torch.@bool); var tTrue = torch.tensor(true); mask[0, 1] = tTrue; mask[2, 3] = tTrue; var res = input.masked_scatter(mask, torch.tensor(new float[] { 3.14f, 2 * 3.14f })); Assert.Equal(3.14f, res[0, 1].item<float>()); Assert.Equal(2 * 3.14f, res[2, 3].item<float>()); input.masked_scatter_(mask, torch.tensor(new float[] { 3.14f, 2 * 3.14f })); Assert.Equal(3.14f, input[0, 1].item<float>()); Assert.Equal(2 * 3.14f, input[2, 3].item<float>()); } [Fact] public void TestMaskedSelect() { var input = torch.zeros(new long[] { 4, 4 }); var mask = torch.eye(4, 4, torch.@bool); var res = input.masked_select(mask); Assert.Equal(4, res.numel()); } [Fact] public void TestStackCpu() { TestStackGen(torch.CPU); } [Fact] public void TestStackCuda() { if (torch.cuda.is_available()) { TestStackGen(torch.CUDA); } } [Fact] public void TestBlockDiag() { // Example from PyTorch documentation var A = torch.tensor(new long[] { 0, 1, 1, 0 }, 2, 2, int64); var B = torch.tensor(new long[] { 3, 4, 5, 6, 7, 8 }, 2, 3, int64); var C = torch.tensor(7, int64); var D = torch.tensor(new long[] { 1, 2, 3 }, int64); var E = torch.tensor(new long[] { 4, 5, 6 }, 3, 1, int64); var expected = torch.tensor(new long[] { 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 5, 0, 0, 0, 0, 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6 }, 9, 10); var res = Tensor.block_diag(A, B, C, D, E); Assert.Equal(expected, res); } [Fact] public void TestDiag1D() { var input = torch.ones(new long[] { 3 }, int64); var expected = new long[] { 1, 0, 0, 0, 1, 0, 0, 0, 1 }; var res = input.diag(); Assert.Equal(2, res.Dimensions); Assert.Equal(expected, res.data<long>().ToArray()); } [Fact] public void TestDiag2D() { var input = torch.zeros(new long[] { 5, 5 }, int64); for (int i = 0; i < 5; i++) { input[i, i] = torch.tensor(1, int64); } var expected = new long[] { 1, 1, 1, 1, 1 }; var res = input.diag(); Assert.Equal(1, res.Dimensions); Assert.Equal(expected, res.data<long>().ToArray()); } [Fact] public void TestDiagFlat1D() { var input = torch.ones(new long[] { 3 }, int64); var expected = new long[] { 1, 0, 0, 0, 1, 0, 0, 0, 1 }; var res = input.diagflat(); Assert.Equal(2, res.Dimensions); Assert.Equal(expected, res.data<long>().ToArray()); } [Fact] public void TestDiagFlat2D() { var input = torch.ones(new long[] { 2, 2 }, int64); var expected = new long[] { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; var res = input.diagflat(); Assert.Equal(2, res.Dimensions); Assert.Equal(expected, res.data<long>().ToArray()); } [Fact] public void TestDimensions() { { var res = torch.rand(new long[] { 5 }); Assert.Equal(1, res.Dimensions); Assert.Equal(1, res.dim()); } { var res = torch.rand(new long[] { 5, 5 }); Assert.Equal(2, res.Dimensions); Assert.Equal(2, res.dim()); } { var res = torch.rand(new long[] { 5, 5, 5 }); Assert.Equal(3, res.Dimensions); Assert.Equal(3, res.dim()); } { var res = torch.rand(new long[] { 5, 5, 5, 5 }); Assert.Equal(4, res.Dimensions); Assert.Equal(4, res.dim()); } } [Fact] public void TestNumberofElements() { { var res = torch.rand(new long[] { 5 }); Assert.Equal(5, res.NumberOfElements); Assert.Equal(5, res.numel()); } { var res = torch.rand(new long[] { 5, 5 }); Assert.Equal(25, res.NumberOfElements); Assert.Equal(25, res.numel()); } { var res = torch.rand(new long[] { 5, 5, 5 }); Assert.Equal(125, res.NumberOfElements); Assert.Equal(125, res.numel()); } { var res = torch.rand(new long[] { 5, 5, 5, 5 }); Assert.Equal(625, res.NumberOfElements); Assert.Equal(625, res.numel()); } } [Fact] public void TestElementSize() { { var res = torch.randint(100, new long[] { 5 }, int8); Assert.Equal(1, res.ElementSize); Assert.Equal(1, res.element_size()); } { var res = torch.randint(250, new long[] { 5 }, int16); Assert.Equal(2, res.ElementSize); Assert.Equal(2, res.element_size()); } { var res = torch.randint(250, new long[] { 5 }, int32); Assert.Equal(4, res.ElementSize); Assert.Equal(4, res.element_size()); } { var res = torch.randint(250, new long[] { 5 }, int64); Assert.Equal(8, res.ElementSize); Assert.Equal(8, res.element_size()); } { var res = torch.rand(new long[] { 5 }); Assert.Equal(4, res.ElementSize); Assert.Equal(4, res.element_size()); } { var res = torch.rand(new long[] { 5 }, float64); Assert.Equal(8, res.ElementSize); Assert.Equal(8, res.element_size()); } } [Fact] public void TestAtleast1d() { { var input = torch.tensor(1.0f); var res = input.atleast_1d(); Assert.Equal(1, res.Dimensions); Assert.Equal(1, res.dim()); Assert.Equal(1, res.NumberOfElements); Assert.Equal(1, res.numel()); } { var input = torch.rand(new long[] { 5 }); var res = input.atleast_1d(); Assert.Equal(1, res.Dimensions); Assert.Equal(1, res.dim()); Assert.Equal(5, res.NumberOfElements); Assert.Equal(5, res.numel()); } { var input = torch.rand(new long[] { 5, 5 }); var res = input.atleast_1d(); Assert.Equal(2, res.Dimensions); Assert.Equal(2, res.dim()); Assert.Equal(25, res.NumberOfElements); Assert.Equal(25, res.numel()); } { var input = torch.rand(new long[] { 5, 5, 5 }); var res = input.atleast_1d(); Assert.Equal(3, res.Dimensions); Assert.Equal(3, res.dim()); Assert.Equal(125, res.NumberOfElements); Assert.Equal(125, res.numel()); } { var input = torch.rand(new long[] { 5, 5, 5, 5 }); var res = input.atleast_1d(); Assert.Equal(4, res.Dimensions); Assert.Equal(4, res.dim()); Assert.Equal(625, res.NumberOfElements); Assert.Equal(625, res.numel()); } } [Fact] public void TestAtleast2d() { { var input = torch.tensor(1.0f); var res = input.atleast_2d(); Assert.Equal(2, res.Dimensions); } { var input = torch.rand(new long[] { 5 }); var res = input.atleast_2d(); Assert.Equal(2, res.Dimensions); } { var input = torch.rand(new long[] { 5, 5 }); var res = input.atleast_2d(); Assert.Equal(2, res.Dimensions); } { var input = torch.rand(new long[] { 5, 5, 5 }); var res = input.atleast_2d(); Assert.Equal(3, res.Dimensions); } { var input = torch.rand(new long[] { 5, 5, 5, 5 }); var res = input.atleast_2d(); Assert.Equal(4, res.Dimensions); } } [Fact] public void TestAtleast3d() { { var input = torch.tensor(1.0f); var res = input.atleast_3d(); Assert.Equal(3, res.Dimensions); } { var input = torch.rand(new long[] { 5 }); var res = input.atleast_3d(); Assert.Equal(3, res.Dimensions); } { var input = torch.rand(new long[] { 5, 5 }); var res = input.atleast_3d(); Assert.Equal(3, res.Dimensions); } { var input = torch.rand(new long[] { 5, 5, 5 }); var res = input.atleast_3d(); Assert.Equal(3, res.Dimensions); } { var input = torch.rand(new long[] { 5, 5, 5, 5 }); var res = input.atleast_3d(); Assert.Equal(4, res.Dimensions); } } [Fact] public void TestSetGrad() { var x = torch.rand(new long[] { 10, 10 }); Assert.False(x.requires_grad); x.requires_grad = true; Assert.True(x.requires_grad); x.requires_grad = false; Assert.False(x.requires_grad); } [Fact] public void TestAutoGradMode() { // TODO: (Skip = "Not working on MacOS (note: may now be working, we need to recheck)") if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var x = torch.randn(new long[] { 2, 3 }, requiresGrad: true); using (torch.no_grad()) { Assert.False(torch.is_grad_enabled()); var sum = x.sum(); Assert.Throws<ExternalException>(() => sum.backward()); //var grad = x.Grad(); //Assert.True(grad.Handle == IntPtr.Zero); } using (torch.enable_grad()) { Assert.True(torch.is_grad_enabled()); var sum = x.sum(); sum.backward(); var grad = x.grad(); Assert.False(grad is null || grad.Handle == IntPtr.Zero); var data = grad is not null ? grad.data<float>().ToArray() : new float[] { }; for (int i = 0; i < 2 * 3; i++) { Assert.Equal(1.0, data[i]); } } x = torch.randn(new long[] { 2, 3 }, requiresGrad: true); using (torch.set_grad_enabled(false)) { Assert.False(torch.is_grad_enabled()); var sum = x.sum(); Assert.Throws<ExternalException>(() => sum.backward()); //var grad = x.Grad(); //Assert.True(grad.Handle == IntPtr.Zero); } using (torch.set_grad_enabled(true)) { Assert.True(torch.is_grad_enabled()); var sum = x.sum(); sum.backward(); var grad = x.grad(); Assert.False(grad is not null && grad.Handle == IntPtr.Zero); var data = grad is not null ? grad.data<float>().ToArray() : new float[] { }; for (int i = 0; i < 2 * 3; i++) { Assert.Equal(1.0, data[i]); } } } } [Fact] public void TestSubInPlace() { var x = torch.ones(new long[] { 100, 100 }, int32); var y = torch.ones(new long[] { 100, 100 }, int32); x.sub_(y); var xdata = x.data<int>(); for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { Assert.Equal(0, xdata[i + j]); } } } [Fact] public void TestMemoryDisposalZeros() { for (int i = 0; i < 1024; i++) { var x = torch.zeros(new long[] { 1024, 1024 }, float64); x.Dispose(); //System.GC.Collect(); } } [Fact] public void TestMemoryDisposalOnes() { for (int i = 0; i < 1024; i++) { var x = torch.ones(new long[] { 1024, 1024 }, float64); x.Dispose(); } } [Fact] public void TestMemoryDisposalScalarTensors() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 1000 * 100; j++) { var x = torch.tensor(i * j * 3.1415); x.Dispose(); } //System.GC.Collect(); } } [Fact] public void TestMemoryDisposalScalars() { for (int i = 0; i < 5; i++) { for (int j = 0; j < 1000 * 100; j++) { var x = (i * j * 3.1415).ToScalar(); x.Dispose(); } //System.GC.Collect(); } } [Fact] public void TestSaveLoadTensorDouble() { var file = ".saveload.double.ts"; if (File.Exists(file)) File.Delete(file); var tensor = torch.ones(new long[] { 5, 6 }, float64); tensor.save(file); var tensorLoaded = Tensor.load(file); File.Delete(file); Assert.NotNull(tensorLoaded); Assert.Equal(tensorLoaded.dtype, tensor.dtype); Assert.Equal(tensorLoaded, tensor); } [Fact] public void TestSaveLoadTensorFloat() { var file = ".saveload.float.ts"; if (File.Exists(file)) File.Delete(file); var tensor = torch.ones(new long[] { 5, 6 }); tensor.save(file); var tensorLoaded = Tensor.load(file); File.Delete(file); Assert.NotNull(tensorLoaded); Assert.Equal(tensorLoaded.dtype, tensor.dtype); Assert.Equal(tensorLoaded, tensor); } [Fact] public void TestArithmeticOperatorsFloat16() { // Float16 arange_cuda not available on cuda in LibTorch 1.8.0 // Float16 arange_cpu not available on cuda in LibTorch 1.8.0 foreach (var device in new Device[] { torch.CPU, torch.CUDA }) { if (device.type != DeviceType.CUDA || torch.cuda.is_available()) { var c1 = torch.ones(new long[] { 10, 10 }, float16, device: device); var c2 = torch.ones(new long[] { 10, 10 }, float16, device: device); var c3 = torch.ones(new long[] { 10, 10 }, float16, device: device); Func<Tensor, long, long, float> getFunc = (tt, i, j) => tt[i, j].ToSingle(); // scalar-tensor operators TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a + 0.5f, a => a + 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => 0.5f + a, a => 0.5f + a); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a - 0.5f, a => a - 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a * 0.5f, a => a * 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => 0.5f * a, a => 0.5f * a); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a / 0.5f, a => a / 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.add(0.5f), a => a + 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.sub(0.5f), a => a - 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.mul(0.5f), a => a * 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.div(0.5f), a => a / 0.5f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.add_(0.5f), a => a + 0.5f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.sub_(0.5f), a => a - 0.5f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.mul_(0.5f), a => a * 0.5f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.div_(0.5f), a => a / 0.5f); // tensor-tensor operators TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a + b, (a, b) => a + b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a - b, (a, b) => a - b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a * b, (a, b) => a * b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a / b, (a, b) => a / b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.add(b), (a, b) => a + b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.sub(b), (a, b) => a - b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.mul(b), (a, b) => a * b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.div(b), (a, b) => a / b); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.add_(b), (a, b) => a + b); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.sub_(b), (a, b) => a - b); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.mul_(b), (a, b) => a * b); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.div_(b), (a, b) => a / b); } } } [Fact] public void TestArithmeticOperatorsBFloat16() { // BFloat16 arange_cuda not available on cuda in LibTorch 1.8.0 // BFloat16 arange_cpu not available on cuda in LibTorch 1.8.0 foreach (var device in new Device[] { torch.CPU, torch.CUDA }) { if (device.type != DeviceType.CUDA || torch.cuda.is_available()) { var c1 = torch.ones(new long[] { 10, 10 }, bfloat16, device: device); var c2 = torch.ones(new long[] { 10, 10 }, bfloat16, device: device); var c3 = torch.ones(new long[] { 10, 10 }, bfloat16, device: device); Func<Tensor, long, long, float> getFunc = (tt, i, j) => tt[i, j].ToSingle(); // scalar-tensor operators TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a + 0.5f, a => a + 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => 0.5f + a, a => 0.5f + a); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a - 0.5f, a => a - 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a * 0.5f, a => a * 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => 0.5f * a, a => 0.5f * a); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a / 0.5f, a => a / 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.add(0.5f), a => a + 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.sub(0.5f), a => a - 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.mul(0.5f), a => a * 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.div(0.5f), a => a / 0.5f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.add_(0.5f), a => a + 0.5f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.sub_(0.5f), a => a - 0.5f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.mul_(0.5f), a => a * 0.5f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.div_(0.5f), a => a / 0.5f); // tensor-tensor operators TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a + b, (a, b) => a + b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a - b, (a, b) => a - b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a * b, (a, b) => a * b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a / b, (a, b) => a / b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.add(b), (a, b) => a + b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.sub(b), (a, b) => a - b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.mul(b), (a, b) => a * b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.div(b), (a, b) => a / b); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.add_(b), (a, b) => a + b); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.sub_(b), (a, b) => a - b); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.mul_(b), (a, b) => a * b); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.div_(b), (a, b) => a / b); } } } [Fact] public void TestArithmeticOperatorsFloat32() { foreach (var device in new Device[] { torch.CPU, torch.CUDA }) { if (device.type != DeviceType.CUDA || torch.cuda.is_available()) { var c1 = torch.arange(0, 10, float32, device: device).expand(new long[] { 10, 10 }); var c2 = torch.arange(10, 0, -1, float32, device: device).expand(new long[] { 10, 10 }); var c3 = torch.ones(new long[] { 10, 10 }, float32, device: device); Func<Tensor, long, long, float> getFunc = (tt, i, j) => tt[i, j].ToSingle(); // scalar-tensor operators TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a + 0.5f, a => a + 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => 0.5f + a, a => 0.5f + a); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a - 0.5f, a => a - 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a * 0.5f, a => a * 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => 0.5f * a, a => 0.5f * a); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a / 0.5f, a => a / 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.add(0.5f), a => a + 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.sub(0.5f), a => a - 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.mul(0.5f), a => a * 0.5f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a.div(0.5f), a => a / 0.5f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.add_(0.5f), a => a + 0.5f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.sub_(0.5f), a => a - 0.5f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.mul_(0.5f), a => a * 0.5f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.div_(0.5f), a => a / 0.5f); // tensor-tensor operators TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a + b, (a, b) => a + b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a - b, (a, b) => a - b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a * b, (a, b) => a * b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a / b, (a, b) => a / b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.add(b), (a, b) => a + b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.sub(b), (a, b) => a - b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.mul(b), (a, b) => a * b); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a.div(b), (a, b) => a / b); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.add_(b), (a, b) => a + b); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.sub_(b), (a, b) => a - b); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.mul_(b), (a, b) => a * b); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.div_(b), (a, b) => a / b); } } } [Fact] public void TestArithmeticOperatorsFloat64() { foreach (var device in new Device[] { torch.CPU, torch.CUDA }) { if (device.type != DeviceType.CUDA || torch.cuda.is_available()) { var c1 = torch.arange(0, 10, float64, device: device).expand(new long[] { 10, 10 }); var c2 = torch.arange(10, 0, -1, float64, device: device).expand(new long[] { 10, 10 }); var c3 = torch.ones(new long[] { 10, 10 }, float64, device: device); Func<Tensor, long, long, double> getFunc = (tt, i, j) => tt[i, j].ToDouble(); // scalar-tensor operators TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => a + 0.5, a => a + 0.5); TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => 0.5 + a, a => 0.5 + a); TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => a - 0.5, a => a - 0.5); TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => a * 0.5, a => a * 0.5); TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => 0.5 * a, a => 0.5 * a); TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => a / 0.5, a => a / 0.5); TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => a.add(0.5), a => a + 0.5); TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => a.sub(0.5), a => a - 0.5); TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => a.mul(0.5), a => a * 0.5); TestOneTensor<double, double>(c1, c2, getFunc, getFunc, a => a.div(0.5), a => a / 0.5); TestOneTensorInPlace<double>(c1, c2, getFunc, a => a.add_(0.5), a => a + 0.5); TestOneTensorInPlace<double>(c1, c2, getFunc, a => a.sub_(0.5), a => a - 0.5); TestOneTensorInPlace<double>(c1, c2, getFunc, a => a.mul_(0.5), a => a * 0.5); TestOneTensorInPlace<double>(c1, c2, getFunc, a => a.div_(0.5), a => a / 0.5); // tensor-tensor operators TestTwoTensor<double, double>(c1, c2, c3, getFunc, getFunc, (a, b) => a + b, (a, b) => a + b); TestTwoTensor<double, double>(c1, c2, c3, getFunc, getFunc, (a, b) => a - b, (a, b) => a - b); TestTwoTensor<double, double>(c1, c2, c3, getFunc, getFunc, (a, b) => a * b, (a, b) => a * b); TestTwoTensor<double, double>(c1, c2, c3, getFunc, getFunc, (a, b) => a / b, (a, b) => a / b); TestTwoTensor<double, double>(c1, c2, c3, getFunc, getFunc, (a, b) => a.add(b), (a, b) => a + b); TestTwoTensor<double, double>(c1, c2, c3, getFunc, getFunc, (a, b) => a.sub(b), (a, b) => a - b); TestTwoTensor<double, double>(c1, c2, c3, getFunc, getFunc, (a, b) => a.mul(b), (a, b) => a * b); TestTwoTensor<double, double>(c1, c2, c3, getFunc, getFunc, (a, b) => a.div(b), (a, b) => a / b); TestTwoTensorInPlace<double>(c1, c2, c3, getFunc, (a, b) => a.add_(b), (a, b) => a + b); TestTwoTensorInPlace<double>(c1, c2, c3, getFunc, (a, b) => a.sub_(b), (a, b) => a - b); TestTwoTensorInPlace<double>(c1, c2, c3, getFunc, (a, b) => a.mul_(b), (a, b) => a * b); TestTwoTensorInPlace<double>(c1, c2, c3, getFunc, (a, b) => a.div_(b), (a, b) => a / b); } } } [Fact] public void TestArithmeticOperatorsComplexFloat64() { foreach (var device in new Device[] { torch.CPU, torch.CUDA }) { if (device.type != DeviceType.CUDA || torch.cuda.is_available()) { var c1 = torch.arange(0, 10, complex128, device: device).expand(new long[] { 10, 10 }); var c2 = torch.arange(10, 0, -1, complex128, device: device).expand(new long[] { 10, 10 }); var c3 = torch.ones(new long[] { 10, 10 }, complex128, device: device); Func<Tensor, long, long, System.Numerics.Complex> getFunc = (tt, i, j) => tt[i, j].ToComplexFloat64(); // scalar-tensor operators TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => a + 0.5, a => a + 0.5); TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => 0.5 + a, a => 0.5 + a); TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => a - 0.5, a => a - 0.5); TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => a * 0.5, a => a * 0.5); TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => 0.5 * a, a => 0.5 * a); TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => a / 0.5, a => a / 0.5); TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => a.add(0.5), a => a + 0.5); TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => a.sub(0.5), a => a - 0.5); TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => a.mul(0.5), a => a * 0.5); TestOneTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, getFunc, getFunc, a => a.div(0.5), a => a / 0.5); TestOneTensorInPlace<System.Numerics.Complex>(c1, c2, getFunc, a => a.add_(0.5), a => a + 0.5); TestOneTensorInPlace<System.Numerics.Complex>(c1, c2, getFunc, a => a.sub_(0.5), a => a - 0.5); TestOneTensorInPlace<System.Numerics.Complex>(c1, c2, getFunc, a => a.mul_(0.5), a => a * 0.5); TestOneTensorInPlace<System.Numerics.Complex>(c1, c2, getFunc, a => a.div_(0.5), a => a / 0.5); // tensor-tensor operators TestTwoTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, c3, getFunc, getFunc, (a, b) => a + b, (a, b) => a + b); TestTwoTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, c3, getFunc, getFunc, (a, b) => a - b, (a, b) => a - b); TestTwoTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, c3, getFunc, getFunc, (a, b) => a * b, (a, b) => a * b); TestTwoTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, c3, getFunc, getFunc, (a, b) => a / b, (a, b) => a / b); TestTwoTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, c3, getFunc, getFunc, (a, b) => a.add(b), (a, b) => a + b); TestTwoTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, c3, getFunc, getFunc, (a, b) => a.sub(b), (a, b) => a - b); TestTwoTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, c3, getFunc, getFunc, (a, b) => a.mul(b), (a, b) => a * b); TestTwoTensor<System.Numerics.Complex, System.Numerics.Complex>(c1, c2, c3, getFunc, getFunc, (a, b) => a.div(b), (a, b) => a / b); TestTwoTensorInPlace<System.Numerics.Complex>(c1, c2, c3, getFunc, (a, b) => a.add_(b), (a, b) => a + b); TestTwoTensorInPlace<System.Numerics.Complex>(c1, c2, c3, getFunc, (a, b) => a.sub_(b), (a, b) => a - b); TestTwoTensorInPlace<System.Numerics.Complex>(c1, c2, c3, getFunc, (a, b) => a.mul_(b), (a, b) => a * b); TestTwoTensorInPlace<System.Numerics.Complex>(c1, c2, c3, getFunc, (a, b) => a.div_(b), (a, b) => a / b); } } } [Fact] public void TestComparisonOperatorsFloat32() { foreach (var device in new Device[] { torch.CPU, torch.CUDA }) { if (device.type != DeviceType.CUDA || torch.cuda.is_available()) { var c1 = torch.arange(0, 10, float32, device: device).expand(new long[] { 10, 10 }); var c2 = torch.arange(10, 0, -1, float32, device: device).expand(new long[] { 10, 10 }); var c3 = torch.ones(new long[] { 10, 10 }, float32, device: device); Func<Tensor, long, long, float> getFunc = (tt, i, j) => tt[i, j].ToSingle(); Func<Tensor, long, long, bool> getFuncBool = (tt, i, j) => tt[i, j].ToBoolean(); // scalar-tensor operators TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => a == 5.0f, a => a == 5.0f); TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => a != 5.0f, a => a != 5.0f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.eq_(5.0f), a => a == 5.0f ? 1.0f : 0.0f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.ne_(5.0f), a => a != 5.0f ? 1.0f : 0.0f); TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => a < 5.0f, a => a < 5.0f); TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => 5.0f < a, a => 5.0f < a); TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => a <= 5.0f, a => a <= 5.0f); TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => 5.0f <= a, a => 5.0f <= a); TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => a > 5.0f, a => a > 5.0f); TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => 5.0f > a, a => 5.0f > a); TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => a >= 5.0f, a => a >= 5.0f); TestOneTensor<float, bool>(c1, c2, getFunc, getFuncBool, a => 5.0f >= a, a => 5.0f >= a); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.lt_(5.0f), a => a < 5.0f ? 1.0f : 0.0f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.le_(5.0f), a => a <= 5.0f ? 1.0f : 0.0f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.gt_(5.0f), a => a > 5.0f ? 1.0f : 0.0f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.ge_(5.0f), a => a >= 5.0f ? 1.0f : 0.0f); TestOneTensor<float, float>(c1, c2, getFunc, getFunc, a => a % 5.0f, a => a % 5.0f); TestOneTensorInPlace<float>(c1, c2, getFunc, a => a.remainder_(5.0f), a => a % 5.0f); // tensor-tensor operators TestTwoTensor<float, bool>(c1, c2, c3, getFunc, getFuncBool, (a, b) => a == b, (a, b) => a == b); TestTwoTensor<float, bool>(c1, c2, c3, getFunc, getFuncBool, (a, b) => a != b, (a, b) => a != b); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.eq_(b), (a, b) => a == b ? 1.0f : 0.0f); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.ne_(b), (a, b) => a != b ? 1.0f : 0.0f); TestTwoTensor<float, bool>(c1, c2, c3, getFunc, getFuncBool, (a, b) => a < b, (a, b) => a < b); TestTwoTensor<float, bool>(c1, c2, c3, getFunc, getFuncBool, (a, b) => a <= b, (a, b) => a <= b); TestTwoTensor<float, bool>(c1, c2, c3, getFunc, getFuncBool, (a, b) => a > b, (a, b) => a > b); TestTwoTensor<float, bool>(c1, c2, c3, getFunc, getFuncBool, (a, b) => a >= b, (a, b) => a >= b); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.lt_(b), (a, b) => a < b ? 1.0f : 0.0f); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.le_(b), (a, b) => a <= b ? 1.0f : 0.0f); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.gt_(b), (a, b) => a > b ? 1.0f : 0.0f); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.ge_(b), (a, b) => a >= b ? 1.0f : 0.0f); TestTwoTensor<float, float>(c1, c2, c3, getFunc, getFunc, (a, b) => a % b, (a, b) => a % b); TestTwoTensorInPlace<float>(c1, c2, c3, getFunc, (a, b) => a.remainder_(b), (a, b) => a % b); } } } private void TestOneTensor<Tin, Tout>( Tensor c1, Tensor c2, Func<Tensor, long, long, Tin> getFuncIn, Func<Tensor, long, long, Tout> getFuncOut, Func<Tensor, Tensor> tensorFunc, Func<Tin, Tout> scalarFunc) { var x = c1 * c2; var y = tensorFunc(x); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { var xv = getFuncIn(x, i, j); var yv = getFuncOut(y, i, j); Assert.Equal<Tout>(yv, scalarFunc(xv)); } } } private void TestOneTensorInPlace<Tin>( Tensor c1, Tensor c2, Func<Tensor, long, long, Tin> getFuncIn, Func<Tensor, Tensor> tensorFunc, Func<Tin, Tin> scalarFunc) { var x = c1 * c2; var xClone = x.clone(); var y = tensorFunc(x); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { var xClonev = getFuncIn(xClone, i, j); var xv = getFuncIn(x, i, j); var yv = getFuncIn(y, i, j); Assert.Equal(yv, scalarFunc(xClonev)); Assert.Equal(yv, xv); } } } private void TestTwoTensor<Tin, Tout>( Tensor c1, Tensor c2, Tensor c3, Func<Tensor, long, long, Tin> getFuncIn, Func<Tensor, long, long, Tout> getFuncOut, Func<Tensor, Tensor, Tensor> tensorFunc, Func<Tin, Tin, Tout> scalarFunc) { var x = c1 * c3; var y = c2 * c3; var z = tensorFunc(x, y); for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { var xv = getFuncIn(x, i, j); var yv = getFuncIn(y, i, j); var zv = getFuncOut(z, i, j); Assert.Equal(zv, scalarFunc(xv, yv)); } } } private void TestTwoTensorInPlace<Tin>( Tensor c1, Tensor c2, Tensor c3, Func<Tensor, long, long, Tin> getFuncIn, Func<Tensor, Tensor, Tensor> tensorFunc, Func<Tin, Tin, Tin> scalarFunc) where Tin : unmanaged { var x = c1 * c3; var xClone = x.clone(); var y = c2 * c3; var z = tensorFunc(x, y); if (x.device_type == DeviceType.CPU) { var xData = x.data<Tin>(); var yData = y.data<Tin>(); var zData = z.data<Tin>(); Assert.True(xData == zData); } for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { var xClonev = getFuncIn(xClone, i, j); var xv = getFuncIn(x, i, j); var yv = getFuncIn(y, i, j); var zv = getFuncIn(z, i, j); Assert.Equal(zv, scalarFunc(xClonev, yv)); Assert.Equal(zv, xv); } } } [Fact] public void TestMul() { var x = torch.ones(new long[] { 100, 100 }); var y = x.mul(0.5f.ToScalar()); var ydata = y.data<float>(); var xdata = x.data<float>(); for (int i = 0; i < 100; i++) { for (int j = 0; j < 100; j++) { Assert.Equal(ydata[i + j], xdata[i + j] * 0.5f); } } } void TestMmGen(Device device) { { var x1 = torch.ones(new long[] { 1, 2 }, device: device); var x2 = torch.ones(new long[] { 2, 1 }, device: device); var y = x1.mm(x2).to(DeviceType.CPU); var ydata = y.data<float>(); Assert.Equal(2.0f, ydata[0]); } //System.Runtime.InteropServices.ExternalException : addmm for CUDA tensors only supports floating - point types.Try converting the tensors with.float() at C:\w\b\windows\pytorch\aten\src\THC / generic / THCTensorMathBlas.cu:453 if (device.type == DeviceType.CPU) { var x1 = torch.ones(new long[] { 1, 2 }, int64, device: device); var x2 = torch.ones(new long[] { 2, 1 }, int64, device: device); var y = x1.mm(x2).to(DeviceType.CPU); var ydata = y.data<long>(); Assert.Equal(2L, ydata[0]); } } [Fact] public void TestMmCpu() { TestMmGen(torch.CPU); } [Fact] public void TestMmCuda() { if (torch.cuda.is_available()) { TestMmGen(torch.CUDA); } } void TestMVGen(Device device) { { var mat1 = torch.ones(new long[] { 4, 3 }, device: device); var vec1 = torch.ones(new long[] { 3 }, device: device); var y = mat1.mv(vec1).to(DeviceType.CPU); Assert.Equal(4, y.shape[0]); } } void TestAddMVGen(Device device) { { var x1 = torch.ones(new long[] { 4 }, device: device); var mat1 = torch.ones(new long[] { 4, 3 }, device: device); var vec1 = torch.ones(new long[] { 3 }, device: device); var y = x1.addmv(mat1, vec1).to(DeviceType.CPU); Assert.Equal(4, y.shape[0]); } } [Fact] public void TestMVCpu() { TestMVGen(torch.CPU); } [Fact] public void TestMVCuda() { if (torch.cuda.is_available()) { TestMVGen(torch.CUDA); } } [Fact] public void TestAddMVCpu() { TestAddMVGen(torch.CPU); } [Fact] public void TestAddMVCuda() { if (torch.cuda.is_available()) { TestAddMVGen(torch.CUDA); } } void TestAddRGen(Device device) { { var x1 = torch.ones(new long[] { 4, 3 }, device: device); var vec1 = torch.ones(new long[] { 4 }, device: device); var vec2 = torch.ones(new long[] { 3 }, device: device); var y = x1.addr(vec1, vec2).to(DeviceType.CPU); Assert.Equal(new long[] { 4, 3 }, y.shape); } } [Fact] public void TestPositive() { var a = torch.randn(25, 25); var b = a.positive(); Assert.Equal(a.data<float>().ToArray(), b.data<float>().ToArray()); var c = torch.ones(25, 25, @bool); Assert.Throws<ArgumentException>(() => c.positive()); } [Fact] public void TestFrexp() { var x = torch.arange(9, float32); var r = x.frexp(); Assert.Equal(new float[] { 0.0000f, 0.5000f, 0.5000f, 0.7500f, 0.5000f, 0.6250f, 0.7500f, 0.8750f, 0.5000f }, r.Mantissa.data<float>().ToArray()); Assert.Equal(new int[] { 0, 1, 2, 2, 3, 3, 3, 3, 4 }, r.Exponent.data<int>().ToArray()); } [Fact] public void TestAddRCpu() { TestAddRGen(torch.CPU); } [Fact] public void TestAddRCuda() { if (torch.cuda.is_available()) { TestAddRGen(torch.CUDA); } } [Fact] public void Deg2RadTest() { var data = new float[] { 1.0f, 2.0f, 3.0f }; var expected = data.Select(angl => (angl * MathF.PI) / 180.0f).ToArray(); var res = torch.tensor(data).deg2rad(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void ClampTest1() { var data = torch.rand(3, 3, 3) * 10; var cl = data.clamp(1, 5); Assert.All(cl.data<float>().ToArray(), d => Assert.True(d >= 1.0f && d <= 5.0f)); } [Fact] public void ClampTest2() { var data = torch.rand(3, 3, 3) * 10; var cl = data.clamp(torch.ones(3,3,3), torch.ones(3,3,3) * 5); Assert.All(cl.data<float>().ToArray(), d => Assert.True(d >= 1.0f && d <= 5.0f)); } [Fact] public void ClampTest3() { var data = torch.rand(3, 3, 3) * 10; var cl = torch.clamp(data, 1, 5); Assert.All(cl.data<float>().ToArray(), d => Assert.True(d >= 1.0f && d <= 5.0f)); } [Fact] public void ClampTest4() { var data = torch.rand(3, 3, 3) * 10; var cl = torch.clamp(data, torch.ones(3, 3, 3), torch.ones(3, 3, 3) * 5); Assert.All(cl.data<float>().ToArray(), d => Assert.True(d >= 1.0f && d <= 5.0f)); } [Fact] public void Rad2DegTest() { var data = new float[] { 1.0f, 2.0f, 3.0f }; var expected = data.Select(angl => (angl * 180.0f) / MathF.PI).ToArray(); var res = torch.tensor(data).rad2deg(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void AbsTest() { var data = torch.arange(-10.0f, 10.0f, 1.0f); var expected = data.data<float>().ToArray().Select(MathF.Abs).ToArray(); var res = data.abs(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void AbsTestC32() { var data = torch.rand(new long[] { 25 }, complex64); var expected = data.data<(float R, float I)>().ToArray().Select(c => MathF.Sqrt(c.R * c.R + c.I * c.I)).ToArray(); var res = data.abs(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void AbsTestC64() { var data = torch.rand(new long[] { 25 }, complex128); var expected = data.data<System.Numerics.Complex>().ToArray().Select(c => Math.Sqrt(c.Real * c.Real + c.Imaginary * c.Imaginary)).ToArray<double>(); var res = data.abs(); Assert.True(res.allclose(torch.tensor(expected, float64))); } [Fact] public void AngleTestC32() { var data = torch.randn(new long[] { 25 }, complex64); var expected = data.data<(float R, float I)>().ToArray().Select(c => { var x = c.R; var y = c.I; return (x > 0 || y != 0) ? 2 * MathF.Atan(y / (MathF.Sqrt(x * x + y * y) + x)) : (x < 0 && y == 0) ? MathF.PI : 0; }).ToArray(); var res = data.angle(); Assert.True(res.allclose(torch.tensor(expected), rtol: 1e-03, atol: 1e-05)); } [Fact] public void AngleTestC64() { var data = torch.randn(new long[] { 25 }, complex128); var expected = data.data<System.Numerics.Complex>().ToArray().Select(c => { var x = c.Real; var y = c.Imaginary; return (x > 0 || y != 0) ? 2 * Math.Atan(y / (Math.Sqrt(x * x + y * y) + x)) : (x < 0 && y == 0) ? Math.PI : 0; }).ToArray<double>(); var res = data.angle(); Assert.True(res.allclose(torch.tensor(expected, float64), rtol: 1e-03, atol: 1e-05)); } [Fact] public void SqrtTest() { var data = new float[] { 1.0f, 2.0f, 3.0f }; var expected = data.Select(MathF.Sqrt).ToArray(); var res = torch.tensor(data).sqrt(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void SinTest() { var data = new float[] { 1.0f, 2.0f, 3.0f }; var expected = data.Select(MathF.Sin).ToArray(); var res = torch.tensor(data).sin(); Assert.True(res.allclose(torch.tensor(expected))); res = torch.sin(torch.tensor(data)); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void CosTest() { var data = new float[] { 1.0f, 2.0f, 3.0f }; var expected = data.Select(MathF.Cos).ToArray(); var res = torch.tensor(data).cos(); Assert.True(res.allclose(torch.tensor(expected))); res = torch.cos(torch.tensor(data)); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void I0Test() { var data = torch.arange(0, 5, 1, float32); var expected = new float[] { 0.99999994f, 1.266066f, 2.27958512f, 4.88079262f, 11.3019209f }; var res = data.i0(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void HypotTest() { var a = new float[] { 1.0f, 2.0f, 3.0f }; var b = new float[] { 1.0f, 2.0f, 3.0f }; var expected = a.Select(x => MathF.Sqrt(2.0f) * x).ToArray(); var res = torch.tensor(a).hypot(torch.tensor(b)); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void VdotTest() { var a = new float[] { 1.0f, 2.0f, 3.0f }; var b = new float[] { 1.0f, 2.0f, 3.0f }; var expected = torch.tensor(a.Zip(b).Select(x => x.First * x.Second).Sum()); var res = torch.tensor(a).vdot(torch.tensor(b)); Assert.True(res.allclose(expected)); } [Fact] public void WhereTest() { var bits = 3; var mask = -(1 << (8 - bits)); var condition = torch.rand(25) > 0.5; var ones = torch.ones(25, int32); var zeros = torch.zeros(25, int32); var cond1 = ones.where(condition, zeros); var cond2 = condition.to_type(ScalarType.Int32); Assert.Equal(cond1, cond2); } [Fact] public void HeavisideTest() { var input = new float[] { -1.0f, 0.0f, 3.0f }; var values = new float[] { 1.0f, 2.0f, 1.0f }; var expected = new float[] { 0.0f, 2.0f, 1.0f }; var res = torch.tensor(input).heaviside(torch.tensor(values)); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void MaximumTest() { var a = torch.tensor(new float[] { 1.0f, 2.0f, 3.0f }); var b = a.neg(); var expected = a; var res = a.maximum(b); Assert.Equal(expected, res); } [Fact] public void MinimumTest() { var a = torch.tensor(new float[] { 1.0f, 2.0f, 3.0f }); var b = a.neg(); var expected = b; var res = a.minimum(b); Assert.Equal(expected, res); } [Fact] public void ArgMaxTest() { var a = torch.randn(new long[] { 15, 5 }); var b = a.argmax(); Assert.Equal(1, b.NumberOfElements); var c = a.argmax(0, keepDim: true); Assert.Equal(new long[] { 1, 5 }, c.shape); var d = a.argmax(0, keepDim: false); Assert.Equal(new long[] { 5 }, d.shape); } [Fact] public void ArgMinTest() { var a = torch.randn(new long[] { 15, 5 }); var b = a.argmin(); Assert.Equal(1, b.NumberOfElements); var c = a.argmin(0, keepDim: true); Assert.Equal(new long[] { 1, 5 }, c.shape); var d = a.argmin(0, keepDim: false); Assert.Equal(new long[] { 5 }, d.shape); } [Fact] public void AMaxTest() { var a = torch.randn(new long[] { 15, 5, 4, 3 }); var b = a.amax(new long[] { 0, 1 }); Assert.Equal(new long[] { 4, 3 }, b.shape); var c = a.amax(new long[] { 0, 1 }, keepDim: true); Assert.Equal(new long[] { 1, 1, 4, 3 }, c.shape); } [Fact] public void AMinTest() { var a = torch.randn(new long[] { 15, 5, 4, 3 }); var b = a.amax(new long[] { 0, 1 }); Assert.Equal(new long[] { 4, 3 }, b.shape); var c = a.amax(new long[] { 0, 1 }, keepDim: true); Assert.Equal(new long[] { 1, 1, 4, 3 }, c.shape); } [Fact] public void TanTest() { var data = new float[] { 1.0f, 2.0f, 3.0f }; var expected = data.Select(MathF.Tan).ToArray(); var res = torch.tensor(data).tan(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void SinhTest() { var data = new float[] { 1.0f, 2.0f, 3.0f }; var expected = data.Select(MathF.Sinh).ToArray(); var res = torch.tensor(data).sinh(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void CoshTest() { var data = new float[] { 1.0f, 2.0f, 3.0f }; var expected = data.Select(MathF.Cosh).ToArray(); var res = torch.tensor(data).cosh(); var tmp = res.data<Single>(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void TanhTest() { var data = new float[] { 1.0f, 2.0f, 3.0f }; var expected = data.Select(MathF.Tanh).ToArray(); var res = torch.tensor(data).tanh(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void ArcSinhTest() { var data = new float[] { -0.1f, 0.0f, 0.1f }; var expected = data.Select(MathF.Asinh).ToArray(); var res = torch.tensor(data).asinh(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void ArcCoshTest() { var data = new float[] { 1.0f, 2.0f, 3.0f }; var expected = data.Select(MathF.Acosh).ToArray(); var res = torch.tensor(data).acosh(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void ArcTanhTest() { var data = new float[] { -0.1f, 0.0f, 0.1f }; var expected = data.Select(MathF.Atanh).ToArray(); var res = torch.tensor(data).atanh(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void AsinTest() { var data = new float[] { 1.0f, 0.2f, -0.1f }; var expected = data.Select(MathF.Asin).ToArray(); { var res = torch.tensor(data).asin(); Assert.True(res.allclose(torch.tensor(expected))); } { var res = torch.tensor(data).arcsin(); Assert.True(res.allclose(torch.tensor(expected))); } } [Fact] public void AcosTest() { var data = new float[] { 1.0f, 0.2f, -0.1f }; var expected = data.Select(MathF.Acos).ToArray(); { var res = torch.tensor(data).acos(); Assert.True(res.allclose(torch.tensor(expected))); } { var res = torch.tensor(data).arccos(); Assert.True(res.allclose(torch.tensor(expected))); } } [Fact] public void AtanTest() { var data = new float[] { 1.0f, 0.2f, -0.1f }; var expected = data.Select(MathF.Atan).ToArray(); { var res = torch.tensor(data).atan(); Assert.True(res.allclose(torch.tensor(expected))); } { var res = torch.tensor(data).arctan(); Assert.True(res.allclose(torch.tensor(expected))); } } [Fact] public void LogTest() { var data = new float[] { 1.0f, 2.0f, 3.0f }; var expected = data.Select(x => MathF.Log(x)).ToArray(); var res = torch.tensor(data).log(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void Log10Test() { var data = new float[] { 1.0f, 2.0f, 3.0f }; var expected = data.Select(MathF.Log10).ToArray(); var res = torch.tensor(data).log10(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void Log2Test() { var data = new float[] { 1.0f, 2.0f, 32.0f }; var expected = data.Select(MathF.Log2).ToArray(); var res = torch.tensor(data).log2(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void LogitTest() { // From the PyTorch reference docs. var data = new float[] { 0.2796f, 0.9331f, 0.6486f, 0.1523f, 0.6516f }; var expected = new float[] { -0.946446538f, 2.635313f, 0.6128909f, -1.71667457f, 0.6260796f }; var res = torch.tensor(data).logit(eps: 1f - 6); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void LogCumSumExpTest() { var data = new float[] { 1.0f, 2.0f, 3.0f, 10.0f, 20.0f, 30.0f }; var expected = new float[data.Length]; for (int i = 0; i < data.Length; i++) { for (int j = 0; j <= i; j++) { expected[i] += MathF.Exp(data[j]); } expected[i] = MathF.Log(expected[i]); } var res = torch.tensor(data).logcumsumexp(dim: 0); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void LogAddExpTest() { var x = new float[] { 1.0f, 2.0f, 3.0f }; var y = new float[] { 4.0f, 5.0f, 6.0f }; var expected = new float[x.Length]; for (int i = 0; i < x.Length; i++) { expected[i] = MathF.Log(MathF.Exp(x[i]) + MathF.Exp(y[i])); } var res = torch.tensor(x).logaddexp(torch.tensor(y)); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void LogAddExp2Test() { var x = new float[] { 1.0f, 2.0f, 3.0f }; var y = new float[] { 4.0f, 5.0f, 6.0f }; var expected = new float[x.Length]; for (int i = 0; i < x.Length; i++) { expected[i] = MathF.Log(MathF.Pow(2.0f, x[i]) + MathF.Pow(2.0f, y[i]), 2.0f); } var res = torch.tensor(x).logaddexp2(torch.tensor(y)); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void ReciprocalTest() { var x = torch.ones(new long[] { 10, 10 }); x.fill_(4.0f); var y = x.reciprocal(); Assert.All(x.data<float>().ToArray(), a => Assert.Equal(4.0f, a)); Assert.All(y.data<float>().ToArray(), a => Assert.Equal(0.25f, a)); x.reciprocal_(); Assert.All(x.data<float>().ToArray(), a => Assert.Equal(0.25f, a)); } [Fact] public void OuterTest() { var x = torch.arange(1, 5, 1, float32); var y = torch.arange(1, 4, 1, float32); var expected = new float[] { 1, 2, 3, 2, 4, 6, 3, 6, 9, 4, 8, 12 }; var res = x.outer(y); Assert.Equal(torch.tensor(expected, 4, 3), res); } [Fact] public void Exp2Test() { var x = new float[] { 1.0f, 2.0f, 3.0f }; var expected = new float[] { 2.0f, 4.0f, 8.0f }; var res = torch.tensor(x).exp2(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void FloorTest() { var data = new float[] { 1.1f, 2.0f, 3.1f }; var expected = data.Select(MathF.Floor).ToArray(); var input = torch.tensor(data); var res = input.floor(); Assert.True(res.allclose(torch.tensor(expected))); input.floor_(); Assert.True(input.allclose(torch.tensor(expected))); } [Fact] public void TruncTest() { var input = torch.randn(new long[] { 25 }); var expected = input.data<float>().ToArray().Select(MathF.Truncate).ToArray(); var res = input.trunc(); Assert.True(res.allclose(torch.tensor(expected))); input.trunc_(); Assert.True(input.allclose(torch.tensor(expected))); } [Fact] public void CeilTest() { var data = new float[] { 1.1f, 2.0f, 3.1f }; var expected = data.Select(MathF.Ceiling).ToArray(); var input = torch.tensor(data); var res = input.ceil(); Assert.True(res.allclose(torch.tensor(expected))); input.ceil_(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void RoundTest() { var data = new float[] { 1.1f, 2.0f, 3.1f }; var expected = data.Select(x => MathF.Round(x)).ToArray(); var input = torch.tensor(data); var res = input.round(); Assert.True(res.allclose(torch.tensor(expected))); input.round_(); Assert.True(res.allclose(torch.tensor(expected))); } [Fact] public void BucketizeTest() { var boundaries = torch.tensor(new int[] { 1, 3, 5, 7, 9 }); var tensor = torch.tensor(new int[] { 3, 6, 9, 3, 6, 9 }, 2, 3); { var res = tensor.bucketize(boundaries, true, false); var expected = torch.tensor(new int[] { 1, 3, 4, 1, 3, 4 }, 2, 3); Assert.True(res.allclose(expected)); } { var res = tensor.bucketize(boundaries, true, true); var expected = torch.tensor(new int[] { 2, 3, 5, 2, 3, 5 }, 2, 3); Assert.True(res.allclose(expected)); } } [Fact] public void VanderTest() { var x = torch.tensor(new int[] { 1, 2, 3, 5 }); { var res = x.vander(); var expected = torch.tensor(new long[] { 1, 1, 1, 1, 8, 4, 2, 1, 27, 9, 3, 1, 125, 25, 5, 1 }, 4, 4); Assert.Equal(expected, res); } { var res = x.vander(3); var expected = torch.tensor(new long[] { 1, 1, 1, 4, 2, 1, 9, 3, 1, 25, 5, 1 }, 4, 3); Assert.Equal(expected, res); } { var res = x.vander(3, true); var expected = torch.tensor(new long[] { 1, 1, 1, 1, 2, 4, 1, 3, 9, 1, 5, 25 }, 4, 3); Assert.Equal(expected, res); } } [Fact] public void ExpandTest() { Tensor ones = torch.ones(new long[] { 2 }); Tensor onesExpanded = ones.expand(new long[] { 3, 2 }); Assert.Equal(onesExpanded.shape, new long[] { 3, 2 }); for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { Assert.Equal(1.0, onesExpanded[i, j].ToSingle()); } } } [Fact] public void MovedimTest() { Tensor input = torch.randn(new long[] { 3, 2, 1 }); { var res = input.movedim(new long[] { 1 }, new long[] { 0 }); Assert.Equal(new long[] { 2, 3, 1 }, res.shape); } { var res = input.movedim(new long[] { 1, 2 }, new long[] { 0, 1 }); Assert.Equal(new long[] { 2, 1, 3 }, res.shape); } } [Fact] public void CountNZTest() { Tensor input = torch.tensor(new float[] { 0, 1, 1, 0, 0, 0, 0, 0, 1 }, 3, 3); { var res = input.count_nonzero(); Assert.Equal(torch.tensor(3, int64), res); } { var res = input.count_nonzero(new long[] { 0 }); Assert.Equal(torch.tensor(new long[] { 0, 1, 2 }), res); } } [Fact] public void SortTest1() { var input = torch.tensor(new double[] { -0.1321, 0.4370, -1.2631, -1.1289, -2.0527, -1.1250, 0.2275, 0.3077, -0.0881, -0.1259, -0.5495, 1.0284 }, 3, 4); var expectedValues = torch.tensor(new double[] { -1.2631, -1.1289, -0.1321, 0.4370, -2.0527, -1.1250, 0.2275, 0.3077, -0.5495, -0.1259, -0.0881, 1.0284 }, 3, 4); var expectedIndices = torch.tensor(new long[] { 2, 3, 0, 1, 0, 1, 2, 3, 2, 1, 0, 3 }, 3, 4); var res = input.sort(); Assert.True(res.Values.allclose(expectedValues)); Assert.Equal(expectedIndices, res.Indices); } [Fact] public void SortTest2() { var input = torch.tensor(new double[] { -0.1321, 0.4370, -1.2631, -1.1289, -2.0527, -1.1250, 0.2275, 0.3077, -0.0881, -0.1259, -0.5495, 1.0284 }, 3, 4); var expectedValues = torch.tensor(new double[] { -2.0527, -1.1250, -1.2631, -1.1289, -0.1321, -0.1259, -0.5495, 0.3077, -0.0881, 0.4370, 0.2275, 1.0284 }, 3, 4); var expectedIndices = torch.tensor(new long[] { 1, 1, 0, 0, 0, 2, 2, 1, 2, 0, 1, 2 }, 3, 4); var res = input.sort(dim: 0); Assert.True(res.Values.allclose(expectedValues)); Assert.Equal(expectedIndices, res.Indices); } [Fact] public void SortTest3() { var input = torch.tensor(new double[] { -0.1321, 0.4370, -1.2631, -1.1289, -2.0527, -1.1250, 0.2275, 0.3077, -0.0881, -0.1259, -0.5495, 1.0284, }, 3, 4); var expectedValues = torch.tensor(new double[] { 0.4370, -0.1321, -1.1289, -1.2631, 0.3077, 0.2275, -1.1250, -2.0527, 1.0284, -0.0881, -0.1259, -0.5495, }, 3, 4); var expectedIndices = torch.tensor(new long[] { 1, 0, 3, 2, 3, 2, 1, 0, 3, 0, 1, 2, }, 3, 4); var res = input.sort(descending: true); Assert.True(res.Values.allclose(expectedValues)); Assert.Equal(expectedIndices, res.Indices); } [Fact] public void SortTest4() { var input = torch.tensor(new double[] { -0.1321, 0.4370, -1.2631, -1.1289, -2.0527, -1.1250, 0.2275, 0.3077, -0.0881, -0.1259, -0.5495, 1.0284 }, 3, 4); var expectedValues = torch.tensor(new double[] { -0.0881, 0.4370, 0.2275, 1.0284, -0.1321, -0.1259, -0.5495, 0.3077, -2.0527, -1.1250, -1.2631, -1.1289, }, 3, 4); var expectedIndices = torch.tensor(new long[] { 2, 0, 1, 2, 0, 2, 2, 1, 1, 1, 0, 0, }, 3, 4); var res = input.sort(dim: 0, descending: true); Assert.True(res.Values.allclose(expectedValues)); Assert.Equal(expectedIndices, res.Indices); } [Fact] public void MSortTest() { var input = torch.tensor(new double[] { -0.1321, 0.4370, -1.2631, -1.1289, -2.0527, -1.1250, 0.2275, 0.3077, -0.0881, -0.1259, -0.5495, 1.0284 }, 3, 4); var expected = torch.tensor(new double[] { -2.0527, -1.1250, -1.2631, -1.1289, -0.1321, -0.1259, -0.5495, 0.3077, -0.0881, 0.4370, 0.2275, 1.0284 }, 3, 4); var res = input.msort(); Assert.True(res.allclose(expected)); } [Fact] public void RepeatTest() { var input = torch.tensor(new int[] { 1, 2, 3 }); var expected = torch.tensor(new int[] { 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, 3 }).reshape(4, 6); var res = input.repeat(new long[] { 4, 2 }); Assert.Equal(res, expected); } [Fact] public void FlipLRTest() { var input = torch.tensor(new int[] { 1, 2, 3, 1, 2, 3, 1, 2, 3, }).reshape(3, 3); var expected = torch.tensor(new int[] { 3, 2, 1, 3, 2, 1, 3, 2, 1, }).reshape(3, 3); var res = input.fliplr(); Assert.Equal(res, expected); } [Fact] public void FlipUDTest() { var input = torch.tensor(new int[] { 1, 1, 1, 2, 2, 2, 3, 3, 3, }).reshape(3, 3); var expected = torch.tensor(new int[] { 3, 3, 3, 2, 2, 2, 1, 1, 1, }).reshape(3, 3); var res = input.flipud(); Assert.Equal(res, expected); } [Fact] public void TopKTest() { var data = new float[] { 1.1f, 2.0f, 3.1f }; var res1 = torch.tensor(data).topk(1); var res1_0 = res1.values[0].ToSingle(); var index1_0 = res1.indexes[0].ToInt64(); Assert.Equal(3.1f, res1_0); Assert.Equal(2L, index1_0); var res2 = torch.tensor(data).topk(2, sorted: true); var res2_0 = res2.values[0].ToSingle(); var index2_0 = res2.indexes[0].ToInt64(); var res2_1 = res2.values[1].ToSingle(); var index2_1 = res2.indexes[1].ToInt64(); Assert.Equal(3.1f, res2_0); Assert.Equal(2L, index2_0); Assert.Equal(2.0f, res2_1); Assert.Equal(1L, index2_1); } [Fact] public void SumTest() { var data = new float[] { 1.0f, 2.0f, 3.0f }; var res1 = torch.tensor(data).sum(); var res1_0 = res1.ToSingle(); Assert.Equal(6.0f, res1_0); var res2 = torch.tensor(data).sum(type: ScalarType.Float64); var res2_0 = res2.ToDouble(); Assert.Equal(6.0, res2_0); // summing integers gives long unless type is explicitly specified var dataInt32 = new int[] { 1, 2, 3 }; var res3 = torch.tensor(dataInt32).sum(); Assert.Equal(ScalarType.Int64, res3.dtype); var res3_0 = res3.ToInt64(); Assert.Equal(6L, res3_0); // summing integers gives long unless type is explicitly specified var res4 = torch.tensor(dataInt32).sum(type: ScalarType.Int32); Assert.Equal(ScalarType.Int32, res4.dtype); var res4_0 = res4.ToInt32(); Assert.Equal(6L, res4_0); } [Fact] public void UnbindTest() { var data = new float[] { 1.1f, 2.0f, 3.1f }; var res = torch.tensor(data).unbind(); Assert.Equal(3, res.Length); Assert.Equal(new long[] { }, res[0].shape); Assert.Equal(new long[] { }, res[1].shape); Assert.Equal(new long[] { }, res[2].shape); Assert.Equal(1.1f, res[0].ToSingle()); Assert.Equal(2.0f, res[1].ToSingle()); Assert.Equal(3.1f, res[2].ToSingle()); } [Fact] public void SplitWithSizeTest() { var data = new float[] { 1.1f, 2.0f, 3.1f, 4.2f, 5.3f }; var res = torch.tensor(data).split(2); Assert.Equal(3, res.Length); Assert.Equal(new long[] { 2 }, res[0].shape); Assert.Equal(new long[] { 2 }, res[1].shape); Assert.Equal(new long[] { 1 }, res[2].shape); Assert.Equal(1.1f, res[0][0].ToSingle()); Assert.Equal(2.0f, res[0][1].ToSingle()); Assert.Equal(3.1f, res[1][0].ToSingle()); Assert.Equal(4.2f, res[1][1].ToSingle()); Assert.Equal(5.3f, res[2][0].ToSingle()); } [Fact] public void SplitWithSizesTest() { var data = new float[] { 1.1f, 2.0f, 3.1f }; var res = torch.tensor(data).split(new long[] { 2, 1 }); Assert.Equal(2, res.Length); Assert.Equal(new long[] { 2 }, res[0].shape); Assert.Equal(new long[] { 1 }, res[1].shape); Assert.Equal(1.1f, res[0][0].ToSingle()); Assert.Equal(2.0f, res[0][1].ToSingle()); Assert.Equal(3.1f, res[1][0].ToSingle()); } [Fact] public void TensorSplitWithSizeTest() { var data = new float[] { 1.1f, 2.0f, 3.1f, 4.2f, 5.3f }; var res = torch.tensor(data).tensor_split(2); Assert.Equal(2, res.Length); Assert.Equal(new long[] { 3 }, res[0].shape); Assert.Equal(new long[] { 2 }, res[1].shape); Assert.Equal(1.1f, res[0][0].ToSingle()); Assert.Equal(2.0f, res[0][1].ToSingle()); Assert.Equal(3.1f, res[0][2].ToSingle()); Assert.Equal(4.2f, res[1][0].ToSingle()); Assert.Equal(5.3f, res[1][1].ToSingle()); } [Fact] public void TensorSplitWithSizesTest() { var data = new float[] { 1.1f, 2.0f, 3.1f, 4.2f, 5.3f }; var res = torch.tensor(data).tensor_split(new long[] { 1, 4 }); Assert.Equal(3, res.Length); Assert.Equal(new long[] { 1 }, res[0].shape); Assert.Equal(new long[] { 3 }, res[1].shape); Assert.Equal(new long[] { 1 }, res[2].shape); Assert.Equal(1.1f, res[0][0].ToSingle()); Assert.Equal(2.0f, res[1][0].ToSingle()); Assert.Equal(3.1f, res[1][1].ToSingle()); Assert.Equal(4.2f, res[1][2].ToSingle()); Assert.Equal(5.3f, res[2][0].ToSingle()); } [Fact] public void VSplitWithSizeTest() { var a = torch.arange(64, int32).reshape(4, 4, 4); var b = a.vsplit(2); Assert.Equal(new long[] { 2, 4, 4 }, b[0].shape); Assert.Equal(new long[] { 2, 4, 4 }, b[1].shape); Assert.Throws<ArgumentException>(() => a.vsplit(3)); } [Fact] public void VSplitWithSizesTest() { var a = torch.arange(80, int32).reshape(5, 4, 4); var b = a.vsplit(new long[] { 2, 3 }); Assert.Equal(new long[] { 2, 4, 4 }, b[0].shape); Assert.Equal(new long[] { 1, 4, 4 }, b[1].shape); Assert.Equal(new long[] { 2, 4, 4 }, b[2].shape); } [Fact] public void HSplitWithSizeTest() { var a = torch.arange(64, int32).reshape(4, 4, 4); var b = a.hsplit(2); Assert.Equal(new long[] { 4, 2, 4 }, b[0].shape); Assert.Equal(new long[] { 4, 2, 4 }, b[1].shape); Assert.Throws<ArgumentException>(() => a.hsplit(3)); } [Fact] public void HSplitWithSizesTest() { var a = torch.arange(80, int32).reshape(4, 5, 4); var b = a.hsplit(new long[] { 2, 3 }); Assert.Equal(new long[] { 4, 2, 4 }, b[0].shape); Assert.Equal(new long[] { 4, 1, 4 }, b[1].shape); Assert.Equal(new long[] { 4, 2, 4 }, b[2].shape); } [Fact] public void DSplitWithSizeTest() { var a = torch.arange(64, int32).reshape(4, 4, 4); var b = a.dsplit(2); Assert.Equal(new long[] { 4, 4, 2 }, b[0].shape); Assert.Equal(new long[] { 4, 4, 2 }, b[1].shape); Assert.Throws<ArgumentException>(() => a.hsplit(3)); } [Fact] public void DSplitWithSizesTest() { var a = torch.arange(80, int32).reshape(4, 4, 5); var b = a.dsplit(new long[] { 2, 3 }); Assert.Equal(new long[] { 4, 4, 2 }, b[0].shape); Assert.Equal(new long[] { 4, 4, 1 }, b[1].shape); Assert.Equal(new long[] { 4, 4, 2 }, b[2].shape); } [Fact] public void TensorSplitWithTensorSizesTest() { var data = new float[] { 1.1f, 2.0f, 3.1f, 4.2f, 5.3f }; var res = torch.tensor(data).tensor_split(torch.tensor(new long[] { 1, 4 })); Assert.Equal(3, res.Length); Assert.Equal(new long[] { 1 }, res[0].shape); Assert.Equal(new long[] { 3 }, res[1].shape); Assert.Equal(new long[] { 1 }, res[2].shape); Assert.Equal(1.1f, res[0][0].ToSingle()); Assert.Equal(2.0f, res[1][0].ToSingle()); Assert.Equal(3.1f, res[1][1].ToSingle()); Assert.Equal(4.2f, res[1][2].ToSingle()); Assert.Equal(5.3f, res[2][0].ToSingle()); } [Fact] public void TensorChunkTest() { var data = new float[] { 1.1f, 2.0f, 3.1f, 4.2f, 5.3f }; var res = torch.tensor(data).chunk(2); Assert.Equal(2, res.Length); Assert.Equal(new long[] { 3 }, res[0].shape); Assert.Equal(new long[] { 2 }, res[1].shape); Assert.Equal(1.1f, res[0][0].ToSingle()); Assert.Equal(2.0f, res[0][1].ToSingle()); Assert.Equal(3.1f, res[0][2].ToSingle()); Assert.Equal(4.2f, res[1][0].ToSingle()); Assert.Equal(5.3f, res[1][1].ToSingle()); } [Fact] public void TensorNonZeroTest() { var data = new double[] { 0.6, 0.0, 0.0, 0.0, 0.0, 0.4, 0.0, 0.0, 0.0, 0.0, 1.2, 0.5 }; using (var t = torch.tensor(data, 3, 4)) { { var res = t.nonzero(); Assert.Equal(new long[] { 4, 2 }, res.shape); } { var res = t.nonzero_as_list(); Assert.Equal(2, res.Count); Assert.Equal(4, res[0].shape[0]); } } } [Fact] public void TakeAlongTest() { var t = torch.tensor(new int[] { 10, 30, 20, 60, 40, 50 }).reshape(2, 3); var max_idx = t.argmax(); var sort_idx = t.argsort(dimension: 1); var x = t.take_along_dim(max_idx); var y = t.take_along_dim(sort_idx, dimension: 1); Assert.Equal(60, x.item<int>()); Assert.Equal(new int[] { 10, 20, 30, 40, 50, 60 }, y.data<int>().ToArray()); } [Fact] public void RandomTest() { var res = torch.rand(new long[] { 2 }); Assert.Equal(new long[] { 2 }, res.shape); var res1 = torch.randint(10, new long[] { 200 }, int16); Assert.Equal(new long[] { 200 }, res1.shape); var res2 = torch.randint(10, new long[] { 200 }, int32); Assert.Equal(new long[] { 200 }, res2.shape); var res3 = torch.randint(10, new long[] { 200 }, int64); Assert.Equal(new long[] { 200 }, res3.shape); var res4 = torch.randint(10, new long[] { 200 }, uint8); Assert.Equal(new long[] { 200 }, res4.shape); var res5 = torch.randint(10, new long[] { 200 }, int8); Assert.Equal(new long[] { 200 }, res5.shape); var res6 = torch.randint(10, new long[] { 200 }, float16); Assert.Equal(new long[] { 200 }, res6.shape); var res7 = torch.randint(10, new long[] { 200 }, bfloat16); Assert.Equal(new long[] { 200 }, res7.shape); var res8 = torch.randint(10, new long[] { 200 }); Assert.Equal(new long[] { 200 }, res8.shape); var res9 = torch.randint(10, 200, float64); Assert.Equal(new long[] { 200 }, res9.shape); //var res7 = torch.randint(100, new long[] { 20, 10 }, complex32); //Assert.Equal(new long[] { 200 }, res7.Shape); var res10 = torch.randint(100, ( 20, 10 ), complex64); Assert.Equal(new long[] { 20, 10 }, res10.shape); var res11 = torch.randint(10, ( 20, 10 ), complex128); Assert.Equal(new long[] { 20, 10 }, res11.shape); } [Fact] public void SqueezeTest() { var data = new float[] { 1.1f, 2.0f, 3.1f }; using (var res = torch.tensor(data).expand(new long[] { 1, 1, 3 }).squeeze(0).squeeze(0)) { Assert.Equal(new long[] { 3 }, res.shape); Assert.Equal(1.1f, res[0].ToSingle()); Assert.Equal(2.0f, res[1].ToSingle()); Assert.Equal(3.1f, res[2].ToSingle()); } // Test negative dims, too. using (var res = torch.tensor(data).expand(new long[] { 1, 1, 3 }).squeeze(-3).squeeze(0)) { Assert.Equal(new long[] { 3 }, res.shape); Assert.Equal(1.1f, res[0].ToSingle()); Assert.Equal(2.0f, res[1].ToSingle()); Assert.Equal(3.1f, res[2].ToSingle()); } // And all dims. using (var res = torch.tensor(data).expand(new long[] { 1, 1, 3 }).squeeze()) { Assert.Equal(new long[] { 3 }, res.shape); Assert.Equal(1.1f, res[0].ToSingle()); Assert.Equal(2.0f, res[1].ToSingle()); Assert.Equal(3.1f, res[2].ToSingle()); } } [Fact] public void NarrowTest() { var data = new float[] { 1.1f, 2.0f, 3.1f }; var res = torch.tensor(data).narrow(0, 1, 2); Assert.Equal(new long[] { 2 }, res.shape); Assert.Equal(2.0f, res[0].ToSingle()); Assert.Equal(3.1f, res[1].ToSingle()); } [Fact] public void SliceTest() { var data = new float[] { 1.1f, 2.0f, 3.1f, 4.0f }; var res = torch.tensor(data).slice(0, 1, 1, 1); Assert.Equal(new long[] { 0 }, res.shape); var res2 = torch.tensor(data).slice(0, 1, 2, 1); Assert.Equal(new long[] { 1 }, res2.shape); Assert.Equal(2.0f, res2[0].ToSingle()); var res3 = torch.tensor(data).slice(0, 1, 4, 2); Assert.Equal(new long[] { 2 }, res3.shape); Assert.Equal(2.0f, res3[0].ToSingle()); Assert.Equal(4.0f, res3[1].ToSingle()); } [Fact] public void Conv1DTest() { var t1 = new float[3, 4, 5] {{{0.3460f, 0.4414f, 0.2384f, 0.7905f, 0.2267f}, {0.5161f, 0.9032f, 0.6741f, 0.6492f, 0.8576f}, {0.3373f, 0.0863f, 0.8137f, 0.2649f, 0.7125f}, {0.7144f, 0.1020f, 0.0437f, 0.5316f, 0.7366f}}, {{0.9871f, 0.7569f, 0.4329f, 0.1443f, 0.1515f}, {0.5950f, 0.7549f, 0.8619f, 0.0196f, 0.8741f}, {0.4595f, 0.7844f, 0.3580f, 0.6469f, 0.7782f}, {0.0130f, 0.8869f, 0.8532f, 0.2119f, 0.8120f}}, {{0.5163f, 0.5590f, 0.5155f, 0.1905f, 0.4255f}, {0.0823f, 0.7887f, 0.8918f, 0.9243f, 0.1068f}, {0.0337f, 0.2771f, 0.9744f, 0.0459f, 0.4082f}, {0.9154f, 0.2569f, 0.9235f, 0.9234f, 0.3148f}}}; var t2 = new float[2, 4, 3] {{{0.4941f, 0.8710f, 0.0606f}, {0.2831f, 0.7930f, 0.5602f}, {0.0024f, 0.1236f, 0.4394f}, {0.9086f, 0.1277f, 0.2450f}}, {{0.5196f, 0.1349f, 0.0282f}, {0.1749f, 0.6234f, 0.5502f}, {0.7678f, 0.0733f, 0.3396f}, {0.6023f, 0.6546f, 0.3439f}}}; var t1raw = new float[3 * 4 * 5]; var t2raw = new float[2 * 4 * 3]; { for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) for (int k = 0; k < 5; k++) { t1raw[i * 4 * 5 + j * 5 + k] = t1[i, j, k]; } } { for (int i = 0; i < 2; i++) for (int j = 0; j < 4; j++) for (int k = 0; k < 3; k++) { t2raw[i * 4 * 3 + j * 3 + k] = t2[i, j, k]; } } var t1t = torch.tensor(t1raw, new long[] { 3, 4, 5 }); var t2t = torch.tensor(t2raw, new long[] { 2, 4, 3 }); if (torch.cuda.is_available()) { t1t = t1t.cuda(); t2t = t2t.cuda(); } var t3t = torch.nn.functional.conv1d(t1t, t2t, stride: 1, padding: 0, dilation: 1); if (torch.cuda.is_available()) { t3t = t3t.cpu(); } // Check the answer var t3Correct = new float[3, 2, 3] {{{2.8516f, 2.0732f, 2.6420f}, {2.3239f, 1.7078f, 2.7450f}}, {{3.0127f, 2.9651f, 2.5219f}, {3.0899f, 3.1496f, 2.4110f}}, {{3.4749f, 2.9038f, 2.7131f}, {2.7692f, 2.9444f, 3.2554f}}}; { for (int i = 0; i < 3; i++) for (int j = 0; j < 2; j++) for (int k = 0; k < 3; k++) { var itemCorrect = t3Correct[i, j, k]; var item = t3t[i, j, k].ToDouble(); Assert.True(Math.Abs(itemCorrect - item) < 0.01f); } } } [Fact] public void Conv1DTest2() { var t1 = new float[2, 3, 4] {{{0.1264f, 5.3183f, 6.6905f, -10.6416f}, { 13.8060f, 4.5253f, 2.8568f, -3.2037f}, { -0.5796f, -2.7937f, -3.3662f, -1.3017f}}, {{ -2.8910f, 3.9349f, -4.3892f, -2.6051f}, { 4.2547f, 2.6049f, -9.8226f, -5.4543f}, { -0.9674f, 1.0070f, -4.6518f, 7.1702f}}}; var t2 = new float[2, 3, 2] {{{4.0332e+00f, 6.3036e+00f}, { 8.4410e+00f, -5.7543e+00f}, {-5.6937e-03f, -6.7241e+00f}}, {{-2.2619e+00f, 1.2082e+00f}, {-1.2203e-01f, -4.9373e+00f}, {-4.1881e+00f, -3.4198e+00f}}}; var t1raw = new float[2 * 3 * 4]; var t2raw = new float[2 * 3 * 2]; { for (int i = 0; i < 2; i++) for (int j = 0; j < 3; j++) for (int k = 0; k < 4; k++) { t1raw[i * 3 * 4 + j * 4 + k] = t1[i, j, k]; } } { for (int i = 0; i < 2; i++) for (int j = 0; j < 3; j++) for (int k = 0; k < 2; k++) { t2raw[i * 3 * 2 + j * 2 + k] = t2[i, j, k]; } } var t1t = torch.tensor(t1raw, new long[] { 2, 3, 4 }); var t2t = torch.tensor(t2raw, new long[] { 2, 3, 2 }); if (torch.cuda.is_available()) { t1t = t1t.cuda(); t2t = t2t.cuda(); } var t3t = torch.nn.functional.conv1d(t1t, t2t, stride: 1, padding: 0, dilation: 1); if (torch.cuda.is_available()) { t3t = t3t.cpu(); } // Check the answer var t3Correct = new float[2, 2, 3] {{{143.3192f, 108.0332f, 11.2241f}, { -5.9062f, 4.6091f, 6.0273f}}, {{ 27.3032f, 97.9855f, -133.8372f}, { -1.4792f, 45.6659f, 29.8705f}}}; { for (int i = 0; i < 2; i++) for (int j = 0; j < 2; j++) for (int k = 0; k < 3; k++) { var itemCorrect = t3Correct[i, j, k]; var item = t3t[i, j, k].ToDouble(); Assert.True(Math.Abs(itemCorrect - item) < 0.01f); } } } [Fact] public void Conv1DTestPadding2Dilation3() { var t1 = new float[3, 4, 5] {{{0.3460f, 0.4414f, 0.2384f, 0.7905f, 0.2267f}, {0.5161f, 0.9032f, 0.6741f, 0.6492f, 0.8576f}, {0.3373f, 0.0863f, 0.8137f, 0.2649f, 0.7125f}, {0.7144f, 0.1020f, 0.0437f, 0.5316f, 0.7366f}}, {{0.9871f, 0.7569f, 0.4329f, 0.1443f, 0.1515f}, {0.5950f, 0.7549f, 0.8619f, 0.0196f, 0.8741f}, {0.4595f, 0.7844f, 0.3580f, 0.6469f, 0.7782f}, {0.0130f, 0.8869f, 0.8532f, 0.2119f, 0.8120f}}, {{0.5163f, 0.5590f, 0.5155f, 0.1905f, 0.4255f}, {0.0823f, 0.7887f, 0.8918f, 0.9243f, 0.1068f}, {0.0337f, 0.2771f, 0.9744f, 0.0459f, 0.4082f}, {0.9154f, 0.2569f, 0.9235f, 0.9234f, 0.3148f}}}; var t2 = new float[2, 4, 3] {{{0.4941f, 0.8710f, 0.0606f}, {0.2831f, 0.7930f, 0.5602f}, {0.0024f, 0.1236f, 0.4394f}, {0.9086f, 0.1277f, 0.2450f}}, {{0.5196f, 0.1349f, 0.0282f}, {0.1749f, 0.6234f, 0.5502f}, {0.7678f, 0.0733f, 0.3396f}, {0.6023f, 0.6546f, 0.3439f}}}; var t1raw = new float[3 * 4 * 5]; var t2raw = new float[2 * 4 * 3]; { for (int i = 0; i < 3; i++) for (int j = 0; j < 4; j++) for (int k = 0; k < 5; k++) { t1raw[i * 4 * 5 + j * 5 + k] = t1[i, j, k]; } } { for (int i = 0; i < 2; i++) for (int j = 0; j < 4; j++) for (int k = 0; k < 3; k++) { t2raw[i * 4 * 3 + j * 3 + k] = t2[i, j, k]; } } var t1t = torch.tensor(t1raw, new long[] { 3, 4, 5 }); //.cuda(); var t2t = torch.tensor(t2raw, new long[] { 2, 4, 3 }); //.cuda(); if (torch.cuda.is_available()) { t1t = t1t.cuda(); t2t = t2t.cuda(); } var t3p2d3 = torch.nn.functional.conv1d(t1t, t2t, padding: 2, dilation: 3); if (torch.cuda.is_available()) { t3p2d3 = t3p2d3.cpu(); } // Check the answer var t3p2d3Correct = new float[3, 2, 3] {{{ 2.1121f, 0.8484f, 2.2709f}, {1.6692f, 0.5406f, 1.8381f}}, {{2.5078f, 1.2137f, 0.9173f}, {2.2395f, 1.1805f, 1.1954f}}, {{1.5215f, 1.3946f, 2.1327f}, {1.0732f, 1.3014f, 2.0696f}}}; { var data = t3p2d3.data<float>(); for (int i = 0; i < 3; i++) for (int j = 0; j < 2; j++) for (int k = 0; k < 3; k++) { var itemCorrect = t3p2d3Correct[i, j, k]; var item = t3p2d3[i, j, k].ToDouble(); Assert.True(Math.Abs(itemCorrect - item) < 0.01f); } } } [Fact] public void CholeskyTest() { var a = torch.randn(new long[] { 3, 2, 2 }, float64); a = a.matmul(a.swapdims(-2, -1)); // Worked this in to get it tested. Alias for 'transpose' var l = linalg.cholesky(a); Assert.True(a.allclose(l.matmul(l.swapaxes(-2, -1)))); // Worked this in to get it tested. Alias for 'transpose' } [Fact] public void CholeskyExTest() { var a = torch.randn(new long[] { 3, 2, 2 }, float64); a = a.matmul(a.swapdims(-2, -1)); // Worked this in to get it tested. Alias for 'transpose' var (l,info) = linalg.cholesky_ex(a); Assert.True(a.allclose(l.matmul(l.swapaxes(-2, -1)))); } [Fact] public void InvTest() { var a = torch.randn(new long[] { 3, 2, 2 }, float64); var l = linalg.inv(a); Assert.Equal(a.shape, l.shape); } [Fact] public void InvExTest() { var a = torch.randn(new long[] { 3, 2, 2 }, float64); var (l, info) = linalg.inv_ex(a); Assert.Equal(a.shape, l.shape); } [Fact] public void CondTestF64() { { var a = torch.randn(new long[] { 3, 3, 3 }, float64); // The following mostly checks that the runtime interop doesn't blow up. var l = linalg.cond(a); l = linalg.cond(a, "fro"); l = linalg.cond(a, "nuc"); l = linalg.cond(a, 1); l = linalg.cond(a, -1); l = linalg.cond(a, 2); l = linalg.cond(a, -2); l = linalg.cond(a, Double.PositiveInfinity); l = linalg.cond(a, Double.NegativeInfinity); } } [Fact] public void CondTestCF64() { { var a = torch.randn(new long[] { 3, 3, 3 }, complex128); // The following mostly checks that the runtime interop doesn't blow up. var l = linalg.cond(a); l = linalg.cond(a, "fro"); l = linalg.cond(a, "nuc"); l = linalg.cond(a, 1); l = linalg.cond(a, -1); l = linalg.cond(a, 2); l = linalg.cond(a, -2); l = linalg.cond(a, Double.PositiveInfinity); l = linalg.cond(a, Double.NegativeInfinity); } } [Fact] public void QRTest() { var a = torch.randn(new long[] { 4, 25, 25 }); var l = linalg.qr(a); Assert.Equal(a.shape, l.Q.shape); Assert.Equal(a.shape, l.R.shape); } [Fact] public void SVDTest() { var a = torch.randn(new long[] { 4, 25, 15 }); var l = linalg.svd(a); Assert.Equal(new long[] { 4, 25, 25 }, l.U.shape); Assert.Equal(new long[] { 4, 15 }, l.S.shape); Assert.Equal(new long[] { 4, 15, 15 }, l.Vh.shape); l = linalg.svd(a, fullMatrices: false); Assert.Equal(a.shape, l.U.shape); Assert.Equal(new long[] { 4, 15 }, l.S.shape); Assert.Equal(new long[] { 4, 15, 15 }, l.Vh.shape); } [Fact] public void SVDValsTest() { var a = torch.tensor(new double[] { -1.3490, -0.1723, 0.7730, -1.6118, -0.3385, -0.6490, 0.0908, 2.0704, 0.5647, -0.6451, 0.1911, 0.7353, 0.5247, 0.5160, 0.5110}, 5, 3); var l = linalg.svdvals(a); Assert.True(l.allclose(torch.tensor(new double[] { 2.5138929972840613, 2.1086555338402455, 1.1064930672223237 }), rtol: 1e-04, atol: 1e-07)); } [Fact] public void LSTSQTest() { var a = torch.randn(new long[] { 4, 25, 15 }); var b = torch.randn(new long[] { 4, 25, 10 }); var l = linalg.lstsq(a, b); Assert.Equal(new long[] { 4, 15, 10 }, l.Solution.shape); Assert.Equal(0, l.Residuals.shape[0]); Assert.Equal(new long[] { 4 }, l.Rank.shape); Assert.Equal(new long[] { 4, 15, 10 }, l.Solution.shape); Assert.Equal(0, l.SingularValues.shape[0]); } [Fact] public void MatrixPowerTest() { var a = torch.randn(new long[] { 25, 25 }); var b = a.matrix_power(3); Assert.Equal(new long[] { 25, 25 }, b.shape); } [Fact] public void MatrixExpTest1() { var a = torch.randn(new long[] { 25, 25 }); var b = a.matrix_exp(); Assert.Equal(new long[] { 25, 25 }, b.shape); var c = torch.matric_exp(a); Assert.Equal(new long[] { 25, 25 }, c.shape); } [Fact] public void MatrixExpTest2() { var a = torch.randn(new long[] { 16, 25, 25 }); var b = a.matrix_exp(); Assert.Equal(new long[] { 16, 25, 25 }, b.shape); var c = torch.matric_exp(a); Assert.Equal(new long[] { 16, 25, 25 }, c.shape); } [Fact] public void MultiDotTest() { var a = torch.randn(new long[] { 25, 25 }); var b = torch.randn(new long[] { 25, 25 }); var c = torch.randn(new long[] { 25, 25 }); var d = torch.linalg.multi_dot(new Tensor[] { a, b, c }); Assert.Equal(new long[] { 25, 25 }, d.shape); } [Fact] public void DeterminantTest() { { var a = torch.tensor( new float[] { 0.9478f, 0.9158f, -1.1295f, 0.9701f, 0.7346f, -1.8044f, -0.2337f, 0.0557f, 0.6929f }, 3, 3); var l = linalg.det(a); Assert.True(l.allclose(torch.tensor(0.09335048f))); } { var a = torch.tensor( new float[] { 0.9254f, -0.6213f, -0.5787f, 1.6843f, 0.3242f, -0.9665f, 0.4539f, -0.0887f, 1.1336f, -0.4025f, -0.7089f, 0.9032f }, 3, 2, 2); var l = linalg.det(a); Assert.True(l.allclose(torch.tensor(new float[] { 1.19910491f, 0.4099378f, 0.7385352f }))); } } [Fact] public void MatrixNormTest() { { var a = torch.arange(9, float32).view(3, 3); var b = linalg.matrix_norm(a); var c = linalg.matrix_norm(a, ord: -1); Assert.Equal(14.282857f, b.item<float>()); Assert.Equal(9.0f, c.item<float>()); } } [Fact] public void VectorNormTest() { { var a = torch.tensor( new float[] { -4.0f, -3.0f, -2.0f, -1.0f, 0, 1.0f, 2.0f, 3.0f, 4.0f }); var b = linalg.vector_norm(a, ord: 3.5); var c = linalg.vector_norm(a.view(3, 3), ord: 3.5); Assert.Equal(5.4344883f, b.item<float>()); Assert.Equal(5.4344883f, c.item<float>()); } } [Fact] public void EighvalsTest32() { { var a = torch.tensor( new float[] { 2.8050f, -0.3850f, -0.3850f, 3.2376f, -1.0307f, -2.7457f, -2.7457f, -1.7517f, 1.7166f }, 3, 3); var expected = torch.tensor( new (float, float)[] { (3.44288778f, 0.0f), (2.17609453f, 0.0f), (-2.128083f, 0.0f) }); var l = linalg.eigvals(a); Assert.True(l.allclose(expected)); } } [Fact] public void EighvalsTest64() { // TODO: (Skip = "Not working on MacOS (note: may now be working, we need to recheck)") if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var a = torch.tensor( new double[] { 2.8050f, -0.3850f, -0.3850f, 3.2376f, -1.0307f, -2.7457f, -2.7457f, -1.7517f, 1.7166f }, 3, 3); var expected = torch.tensor( new System.Numerics.Complex[] { new System.Numerics.Complex(3.44288778f, 0.0f), new System.Numerics.Complex(2.17609453f, 0.0f), new System.Numerics.Complex(-2.128083f, 0.0f) }); var l = linalg.eigvals(a); Assert.True(l.allclose(expected)); } } [Fact] public void EighvalshTest32() { // TODO: (Skip = "Not working on MacOS (note: may now be working, we need to recheck)") if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { var a = torch.tensor( new float[] { 2.8050f, -0.3850f, -0.3850f, 3.2376f, -1.0307f, -2.7457f, -2.7457f, -1.7517f, 1.7166f, 2.2207f, 2.2207f, -2.0898f }, 3, 2, 2); var expected = torch.tensor( new float[] { 2.5797f, 3.46290016f, -4.16046524f, 1.37806475f, -3.11126733f, 2.73806715f }, 3, 2); var l = linalg.eigvalsh(a); Assert.True(l.allclose(expected)); } } [Fact] public void EighvalshTest64() { { var a = torch.tensor( new double[] { 2.8050, -0.3850, -0.3850, 3.2376, -1.0307, -2.7457, -2.7457, -1.7517, 1.7166, 2.2207, 2.2207, -2.0898 }, 3, 2, 2); var expected = torch.tensor( new double[] { 2.5797, 3.46290016, -4.16046524, 1.37806475, -3.11126733, 2.73806715 }, 3, 2); var l = linalg.eigvalsh(a); Assert.True(l.allclose(expected)); } } [Fact] public void LinalgNormTest() { { var a = torch.tensor( new float[] { -4.0f, -3.0f, -2.0f, -1.0f, 0.0f, 1.0f, 2.0f, 3.0f, 4.0f }); var b = a.reshape(3, 3); Assert.True(linalg.norm(a).allclose(torch.tensor(7.7460f))); Assert.True(linalg.norm(b).allclose(torch.tensor(7.7460f))); Assert.True(linalg.norm(b, "fro").allclose(torch.tensor(7.7460f))); Assert.True(linalg.norm(a, float.PositiveInfinity).allclose(torch.tensor(4.0f))); Assert.True(linalg.norm(b, float.PositiveInfinity).allclose(torch.tensor(9.0f))); Assert.True(linalg.norm(a, float.NegativeInfinity).allclose(torch.tensor(0.0f))); Assert.True(linalg.norm(b, float.NegativeInfinity).allclose(torch.tensor(2.0f))); Assert.True(linalg.norm(a, 1).allclose(torch.tensor(20.0f))); Assert.True(linalg.norm(b, 1).allclose(torch.tensor(7.0f))); Assert.True(linalg.norm(a, -1).allclose(torch.tensor(0.0f))); Assert.True(linalg.norm(b, -1).allclose(torch.tensor(6.0f))); Assert.True(linalg.norm(a, 2).allclose(torch.tensor(7.7460f))); Assert.True(linalg.norm(b, 2).allclose(torch.tensor(7.3485f))); Assert.True(linalg.norm(a, 3).allclose(torch.tensor(5.8480f))); Assert.True(linalg.norm(a, -2).allclose(torch.tensor(0.0f))); Assert.True(linalg.norm(a, -3).allclose(torch.tensor(0.0f))); } } [Fact] public void TestSpecialEntropy() { var a = torch.tensor(new float[] { -0.5f, 1.0f, 0.5f }); var expected = torch.tensor( new float[] { Single.NegativeInfinity, 0.0f, 0.3465736f }); var b = torch.special.entr(a); Assert.True(b.allclose(expected)); } [Fact] public void TestSpecialErrorFunction() { var a = torch.tensor(new float[] { 0.0f, -1.0f, 10.0f }); var expected = torch.tensor( new float[] { 0.0f, -0.8427f, 1.0f }); var b = torch.special.erf(a); Assert.True(b.allclose(expected)); } [Fact] public void TestSpecialComplementaryErrorFunction() { var a = torch.tensor(new float[] { 0.0f, -1.0f, 10.0f }); var expected = torch.tensor( new float[] { 1.0f, 1.8427f, 0.0f }); var b = torch.special.erfc(a); Assert.True(b.allclose(expected)); } [Fact] public void TestSpecialInverseErrorFunction() { var a = torch.tensor(new float[] { 0.0f, 0.5f, -1.0f }); var expected = torch.tensor( new float[] { 0.0f, 0.476936281f, Single.NegativeInfinity }); var b = torch.special.erfinv(a); Assert.True(b.allclose(expected)); } [Fact] public void TestSpecialExpit() { var a = torch.randn(new long[] { 10 }); var expected = torch.tensor(a.data<float>().ToArray().Select(x => 1.0f / (1.0f + MathF.Exp(-x))).ToArray()); var b = torch.special.expit(a); Assert.True(b.allclose(expected, rtol: 1e-04, atol: 1e-07)); } [Fact] public void TestSpecialExpm1() { var a = torch.randn(new long[] { 10 }); var expected = torch.tensor(a.data<float>().ToArray().Select(x => MathF.Exp(x) - 1.0f).ToArray()); var b = torch.special.expm1(a); Assert.True(b.allclose(expected, rtol: 1e-04, atol: 1e-07)); } [Fact] public void TestSpecialExp2() { var a = torch.randn(new long[] { 10 }); var expected = torch.tensor(a.data<float>().ToArray().Select(x => MathF.Pow(2.0f, x)).ToArray()); var b = torch.special.exp2(a); Assert.True(b.allclose(expected, rtol: 1e-04, atol: 1e-07)); } [Fact] public void TestSpecialGammaLN() { var a = torch.arange(0.5f, 2f, 0.5f); var expected = torch.tensor(new float[] { 0.5723649f, 0.0f, -0.120782226f }); var b = torch.special.gammaln(a); Assert.True(b.allclose(expected)); } [Fact] public void TestSpeciali0e() { var a = torch.arange(0.0f, 5.0f, 1.0f); var expected = torch.tensor(new float[] { 1.0f, 0.465759635f, 0.3085083f, 0.243000358f, 0.20700191f }); var b = torch.special.i0e(a); Assert.True(b.allclose(expected)); } [Fact] public void NanToNumTest() { { var a = torch.tensor(new float[] { Single.NaN, Single.PositiveInfinity, Single.NegativeInfinity, MathF.PI }); { var expected = torch.tensor(new float[] { 0.0f, Single.MaxValue, Single.MinValue, MathF.PI }); Assert.True(a.nan_to_num().allclose(expected)); } { var expected = torch.tensor(new float[] { 2.0f, Single.MaxValue, Single.MinValue, MathF.PI }); Assert.True(a.nan_to_num(nan: 2.0f).allclose(expected)); } { var expected = torch.tensor(new float[] { 2.0f, 3.0f, Single.MinValue, MathF.PI }); Assert.True(a.nan_to_num(nan: 2.0f, posinf: 3.0f).allclose(expected)); } { var expected = torch.tensor(new float[] { 2.0f, 3.0f, -13.0f, MathF.PI }); Assert.True(a.nan_to_num(nan: 2.0f, posinf: 3.0f, neginf: -13.0f).allclose(expected)); } } } [Fact] public void TensorDiffTest() { var a = torch.tensor(new float[] { 1, 3, 2 }); Assert.True(a.diff().allclose(torch.tensor(new float[] { 2, -1 }))); var b = torch.tensor(new float[] { 4, 5 }); Assert.True(a.diff(append: b).allclose(torch.tensor(new float[] { 2, -1, 2, 1 }))); var c = torch.tensor(new float[] { 1, 2, 3, 3, 4, 5 }, 2, 3); Assert.True(c.diff(dim: 0).allclose(torch.tensor(new float[] { 2, 2, 2 }, 1, 3))); Assert.True(c.diff(dim: 1).allclose(torch.tensor(new float[] { 1, 1, 1, 1 }, 2, 2))); } [Fact] public void RavelTest() { var expected = torch.tensor(new int[] { 1, 2, 3, 4, 5, 6, 7, 8 }); var a = expected.view(2, 2, 2); Assert.Equal(new long[] { 2, 2, 2 }, a.shape); Assert.Equal(expected, a.ravel()); } [Fact] public void StrideTest_1() { var x = torch.zeros(new long[] { 2, 2, 2 }, int32); Assert.Equal(4, x.stride(0)); Assert.Equal(2, x.stride(1)); Assert.Equal(1, x.stride(2)); Assert.Equal(new long[] { 4, 2, 1 }, x.stride()); } [Fact] public void StrideTest_2() { var x = torch.zeros(new long[] { 2, 2, 2 }, int32); Assert.Equal(new long[] { 4, 2, 1 }, x.stride()); } [Fact] public void Complex32PartsTest() { var x = torch.zeros(new long[] { 20 }, complex64); var r1 = x.real; var i1 = x.imag; Assert.Equal(x.shape, r1.shape); Assert.Equal(x.shape, i1.shape); Assert.Equal(ScalarType.Float32, r1.dtype); Assert.Equal(ScalarType.Float32, i1.dtype); var vasr = x.view_as_real(); Assert.Equal(new long[] { 20, 2 }, vasr.shape); Assert.Equal(ScalarType.Float32, vasr.dtype); var r2 = vasr[TensorIndex.Ellipsis, TensorIndex.Single(0)]; var i2 = vasr[TensorIndex.Ellipsis, TensorIndex.Single(1)]; Assert.Equal(x.shape, r2.shape); Assert.Equal(x.shape, i2.shape); Assert.Equal(ScalarType.Float32, r2.dtype); Assert.Equal(ScalarType.Float32, i2.dtype); Assert.Equal(r1, r2); Assert.Equal(i1, i2); } [Fact] public void Complex64PartsTest() { var x = torch.zeros(new long[] { 20 }, complex128); var r1 = x.real; var i1 = x.imag; Assert.Equal(x.shape, r1.shape); Assert.Equal(x.shape, i1.shape); Assert.Equal(ScalarType.Float64, r1.dtype); Assert.Equal(ScalarType.Float64, i1.dtype); var vasr = x.view_as_real(); Assert.Equal(new long[] { 20, 2 }, vasr.shape); Assert.Equal(ScalarType.Float64, vasr.dtype); var r2 = vasr[TensorIndex.Ellipsis, TensorIndex.Single(0)]; var i2 = vasr[TensorIndex.Ellipsis, TensorIndex.Single(1)]; Assert.Equal(x.shape, r2.shape); Assert.Equal(x.shape, i2.shape); Assert.Equal(ScalarType.Float64, r2.dtype); Assert.Equal(ScalarType.Float64, i2.dtype); Assert.Equal(r1, r2); Assert.Equal(i1, i2); } [Fact] public void Complex32TensorView() { var x = torch.zeros(new long[] { 20, 20, 20 }, complex64); var y = torch.zeros(new long[] { 20, 20, 20, 2 }); var vasr = x.view_as_real(); Assert.Equal(new long[] { 20, 20, 20, 2 }, vasr.shape); Assert.Equal(ScalarType.Float32, vasr.dtype); var vasc = y.view_as_complex(); Assert.Equal(ScalarType.ComplexFloat32, vasc.dtype); Assert.Equal(x.shape, vasc.shape); } [Fact] public void Complex64TensorView() { var x = torch.zeros(new long[] { 20, 20, 20 }, complex128); var y = torch.zeros(new long[] { 20, 20, 20, 2 }, float64); var vasr = x.view_as_real(); Assert.Equal(new long[] { 20, 20, 20, 2 }, vasr.shape); Assert.Equal(ScalarType.Float64, vasr.dtype); var vasc = y.view_as_complex(); Assert.Equal(ScalarType.ComplexFloat64, vasc.dtype); Assert.Equal(x.shape, vasc.shape); } [Fact] public void Float32FFT() { var input = torch.arange(4); var output = fft.fft_(input); Assert.Equal(input.shape, output.shape); Assert.Equal(ScalarType.ComplexFloat32, output.dtype); var inverted = fft.ifft(output); Assert.Equal(ScalarType.ComplexFloat32, inverted.dtype); } [Fact] public void Float64FFT() { var input = torch.arange(4, float64); var output = fft.fft_(input); Assert.Equal(input.shape, output.shape); Assert.Equal(ScalarType.ComplexFloat64, output.dtype); var inverted = fft.ifft(output); Assert.Equal(ScalarType.ComplexFloat64, inverted.dtype); } [Fact] public void Float32HFFT() { var input = torch.arange(4); var output = fft.hfft(input); Assert.Equal(6, output.shape[0]); Assert.Equal(ScalarType.Float32, output.dtype); var inverted = fft.ifft(output); Assert.Equal(ScalarType.ComplexFloat32, inverted.dtype); } [Fact] public void Float64HFFT() { var input = torch.arange(4, float64); var output = fft.hfft(input); Assert.Equal(6, output.shape[0]); Assert.Equal(ScalarType.Float64, output.dtype); var inverted = fft.ifft(output); Assert.Equal(ScalarType.ComplexFloat64, inverted.dtype); } [Fact] public void Float32RFFT() { var input = torch.arange(4); var output = fft.rfft(input); Assert.Equal(3, output.shape[0]); Assert.Equal(ScalarType.ComplexFloat32, output.dtype); var inverted = fft.irfft(output); Assert.Equal(ScalarType.Float32, inverted.dtype); } [Fact] public void Float64RFFT() { var input = torch.arange(4, float64); var output = fft.rfft(input); Assert.Equal(3, output.shape[0]); Assert.Equal(ScalarType.ComplexFloat64, output.dtype); var inverted = fft.irfft(output); Assert.Equal(ScalarType.Float64, inverted.dtype); } [Fact] public void ComplexFloat32FFT() { var input = torch.arange(4, complex64); var output = fft.fft_(input); Assert.Equal(input.shape, output.shape); Assert.Equal(ScalarType.ComplexFloat32, output.dtype); var inverted = fft.ifft(output); Assert.Equal(ScalarType.ComplexFloat32, inverted.dtype); } [Fact] public void ComplexFloat64FFT() { var input = torch.arange(4, complex128); var output = fft.fft_(input); Assert.Equal(input.shape, output.shape); Assert.Equal(ScalarType.ComplexFloat64, output.dtype); var inverted = fft.ifft(output); Assert.Equal(ScalarType.ComplexFloat64, inverted.dtype); } [Fact] public void ComplexFloat32HFFT() { var input = torch.arange(4, complex64); var output = fft.hfft(input); Assert.Equal(6, output.shape[0]); Assert.Equal(ScalarType.Float32, output.dtype); var inverted = fft.ihfft(output); Assert.Equal(ScalarType.ComplexFloat32, inverted.dtype); } [Fact] public void ComplexFloat64HFFT() { var input = torch.arange(4, complex128); var output = fft.hfft(input); Assert.Equal(6, output.shape[0]); Assert.Equal(ScalarType.Float64, output.dtype); var inverted = fft.ihfft(output); Assert.Equal(ScalarType.ComplexFloat64, inverted.dtype); } [Fact] public void Float32FFT2() { var input = torch.rand(new long[] { 5, 5 }); var output = fft.fft2(input); Assert.Equal(input.shape, output.shape); Assert.Equal(ScalarType.ComplexFloat32, output.dtype); var inverted = fft.ifft2(output); Assert.Equal(ScalarType.ComplexFloat32, inverted.dtype); } [Fact] public void Float64FFT2() { var input = torch.rand(new long[] { 5, 5 }, float64); var output = fft.fft2(input); Assert.Equal(input.shape, output.shape); Assert.Equal(ScalarType.ComplexFloat64, output.dtype); var inverted = fft.ifft2(output); Assert.Equal(ScalarType.ComplexFloat64, inverted.dtype); } [Fact] public void Float32RFFT2() { var input = torch.rand(new long[] { 5, 5 }); var output = fft.rfft2(input); Assert.Equal(new long[] { 5, 3 }, output.shape); Assert.Equal(ScalarType.ComplexFloat32, output.dtype); var inverted = fft.irfft2(output); Assert.Equal(ScalarType.Float32, inverted.dtype); } [Fact] public void Float64RFFT2() { var input = torch.rand(new long[] { 5, 5 }, float64); var output = fft.rfft2(input); Assert.Equal(new long[] { 5, 3 }, output.shape); Assert.Equal(ScalarType.ComplexFloat64, output.dtype); var inverted = fft.irfft2(output); Assert.Equal(ScalarType.Float64, inverted.dtype); } [Fact] public void ComplexFloat32FFT2() { var input = torch.rand(new long[] { 5, 5 }, complex64); var output = fft.fft2(input); Assert.Equal(input.shape, output.shape); Assert.Equal(ScalarType.ComplexFloat32, output.dtype); var inverted = fft.ifft2(output); Assert.Equal(ScalarType.ComplexFloat32, inverted.dtype); } [Fact] public void ComplexFloat64FFT2() { var input = torch.rand(new long[] { 5, 5 }, complex128); var output = fft.fft2(input); Assert.Equal(input.shape, output.shape); Assert.Equal(ScalarType.ComplexFloat64, output.dtype); var inverted = fft.ifft2(output); Assert.Equal(ScalarType.ComplexFloat64, inverted.dtype); } [Fact] public void Float32FFTN() { var input = torch.rand(new long[] { 5, 5, 5, 5 }); var output = fft.fftn(input); Assert.Equal(input.shape, output.shape); Assert.Equal(ScalarType.ComplexFloat32, output.dtype); var inverted = fft.ifftn(output); Assert.Equal(ScalarType.ComplexFloat32, inverted.dtype); } [Fact] public void Float64FFTN() { var input = torch.rand(new long[] { 5, 5, 5, 5 }, float64); var output = fft.fftn(input); Assert.Equal(input.shape, output.shape); Assert.Equal(ScalarType.ComplexFloat64, output.dtype); var inverted = fft.ifftn(output); Assert.Equal(ScalarType.ComplexFloat64, inverted.dtype); } [Fact] public void Float32RFFTN() { var input = torch.rand(new long[] { 5, 5, 5, 5 }); var output = fft.rfftn(input); Assert.Equal(new long[] { 5, 5, 5, 3 }, output.shape); Assert.Equal(ScalarType.ComplexFloat32, output.dtype); var inverted = fft.irfftn(output); Assert.Equal(ScalarType.Float32, inverted.dtype); } [Fact] public void Float64RFFTN() { var input = torch.rand(new long[] { 5, 5, 5, 5 }, float64); var output = fft.rfftn(input); Assert.Equal(new long[] { 5, 5, 5, 3 }, output.shape); Assert.Equal(ScalarType.ComplexFloat64, output.dtype); var inverted = fft.irfftn(output); Assert.Equal(ScalarType.Float64, inverted.dtype); } [Fact] public void ComplexFloat32FFTN() { var input = torch.rand(new long[] { 5, 5, 5, 5 }, complex64); var output = fft.fftn(input); Assert.Equal(input.shape, output.shape); Assert.Equal(ScalarType.ComplexFloat32, output.dtype); var inverted = fft.ifftn(output); Assert.Equal(ScalarType.ComplexFloat32, inverted.dtype); } [Fact] public void ComplexFloat64FFTN() { var input = torch.rand(new long[] { 5, 5, 5, 5 }, complex128); var output = fft.fftn(input); Assert.Equal(input.shape, output.shape); Assert.Equal(ScalarType.ComplexFloat64, output.dtype); var inverted = fft.ifftn(output); Assert.Equal(ScalarType.ComplexFloat64, inverted.dtype); } [Fact] public void Float32FFTFrequency() { var x = torch.fft.fftfreq(5); Assert.Equal(ScalarType.Float32, x.dtype); Assert.Equal(1, x.dim()); Assert.Equal(5, x.shape[0]); } [Fact] public void Float64FFTFrequency() { var x = torch.fft.fftfreq(5, dtype: float64); Assert.Equal(ScalarType.Float64, x.dtype); Assert.Equal(1, x.dim()); Assert.Equal(5, x.shape[0]); } [Fact] public void Float32FFTShift() { var x = torch.fft.fftfreq(4, dtype: float32); var shifted = fft.fftshift(x); Assert.Equal(ScalarType.Float32, shifted.dtype); Assert.Equal(1, shifted.dim()); Assert.Equal(4, shifted.shape[0]); var y = fft.ifftshift(x); Assert.Equal(ScalarType.Float32, y.dtype); Assert.Equal(1, y.dim()); Assert.Equal(4, y.shape[0]); } [Fact] public void Float64FFTShift() { var x = torch.fft.fftfreq(4, dtype: float64); var shifted = fft.fftshift(x); Assert.Equal(ScalarType.Float64, shifted.dtype); Assert.Equal(1, shifted.dim()); Assert.Equal(4, shifted.shape[0]); var y = fft.ifftshift(x); Assert.Equal(ScalarType.Float64, y.dtype); Assert.Equal(1, y.dim()); Assert.Equal(4, y.shape[0]); } [Fact] public void CropTensor() { { var input = torch.rand(25, 25); var cropped = input.crop(5, 5, 15, 13); Assert.Equal(new long[] { 15, 13 }, cropped.shape); for (int i = 0; i < 13; i++) { // Test the diagonal only. Assert.Equal(input[5 + i, 5 + i], cropped[i, i]); } } { var input = torch.rand(3, 25, 25); var cropped = input.crop(5, 5, 15, 13); Assert.Equal(new long[] { 3, 15, 13 }, cropped.shape); for (int c = 0; c < 3; c++) for (int i = 0; i < 13; i++) { // Test the diagonal only. Assert.Equal(input[c, 5 + i, 5 + i], cropped[c, i, i]); } } { var input = torch.rand(16, 3, 25, 25); var cropped = input.crop(5, 5, 15, 13); Assert.Equal(new long[] { 16, 3, 15, 13 }, cropped.shape); for (int n = 0; n < 16; n++) for (int c = 0; c < 3; c++) for (int i = 0; i < 13; i++) { // Test the diagonal only. Assert.Equal(input[n, c, 5 + i, 5 + i], cropped[n, c, i, i]); } } } [Fact] public void CroppedTensorWithPadding() { { var input = torch.rand(25, 25); var cropped = input.crop(-1, -1, 15, 13); Assert.Equal(new long[] { 15, 13 }, cropped.shape); for (int i = 0; i < 12; i++) { // Test the diagonal only, and skip the padded corner. Assert.Equal(input[i, i], cropped[i + 1, i + 1]); } } { var input = torch.rand(25, 25); var cropped = input.crop(11, 13, 15, 13); Assert.Equal(new long[] { 15, 13 }, cropped.shape); for (int i = 0; i < 12; i++) { // Test the diagonal only, and skip the padded corner. Assert.Equal(input[11 + i, 13 + i], cropped[i, i]); } } } [Fact] public void RandomResizeCropTensor() { { var input = torch.rand(4, 3, 100, 100); var cropped = torchvision.transforms.RandomResizedCrop(100, 0.1, 0.5).forward(input); Assert.Equal(new long[] { 4, 3, 100, 100 }, cropped.shape); } } [Fact] public void CenterCropTensor() { { var input = torch.rand(25, 25); var cropped = torchvision.transforms.CenterCrop(15, 13).forward(input); Assert.Equal(new long[] { 15, 13 }, cropped.shape); for (int i = 0; i < 13; i++) { // Test the diagonal only. Assert.Equal(input[5 + i, 6 + i], cropped[i, i]); } } { var input = torch.rand(3, 25, 25); var cropped = torchvision.transforms.CenterCrop(15, 13).forward(input); Assert.Equal(new long[] { 3, 15, 13 }, cropped.shape); for (int c = 0; c < 3; c++) for (int i = 0; i < 13; i++) { // Test the diagonal only. Assert.Equal(input[c, 5 + i, 6 + i], cropped[c, i, i]); } } { var input = torch.rand(16, 3, 25, 25); var cropped = torchvision.transforms.CenterCrop(15, 13).forward(input); Assert.Equal(new long[] { 16, 3, 15, 13 }, cropped.shape); for (int n = 0; n < 16; n++) for (int c = 0; c < 3; c++) for (int i = 0; i < 13; i++) { // Test the diagonal only. Assert.Equal(input[n, c, 5 + i, 6 + i], cropped[n, c, i, i]); } } } [Fact] public void ResizeTensorDown() { { var input = torch.rand(16, 3, 25, 25); var resized = torchvision.transforms.Resize(15).forward(input); Assert.Equal(new long[] { 16, 3, 15, 15 }, resized.shape); } { var input = torch.randint(255, new long[] { 16, 3, 25, 25 }, int32); var resized = torchvision.transforms.Resize(15).forward(input); Assert.Equal(new long[] { 16, 3, 15, 15 }, resized.shape); } } [Fact] public void ResizeTensorUp() { { var input = torch.rand(16, 3, 25, 25); var resized = torchvision.transforms.Resize(50).forward(input); Assert.Equal(new long[] { 16, 3, 50, 50 }, resized.shape); } { var input = torch.randint(255, new long[] { 16, 3, 25, 25 }, int32); var resized = torchvision.transforms.Resize(50).forward(input); Assert.Equal(new long[] { 16, 3, 50, 50 }, resized.shape); } } [Fact] public void GrayscaleTensor() { { var input = torch.rand(16, 3, 25, 25); var gray = torchvision.transforms.Grayscale().forward(input); Assert.Equal(new long[] { 16, 1, 25, 25 }, gray.shape); } { var input = torch.rand(16, 3, 25, 25); var gray = torchvision.transforms.Grayscale(3).forward(input); Assert.Equal(new long[] { 16, 3, 25, 25 }, gray.shape); for (int n = 0; n < 16; n++) for (int i = 0; i < 15; i++) { // Test the diagonal only. Assert.Equal(gray[n, 0, i, i], gray[n, 1, i, i]); Assert.Equal(gray[n, 0, i, i], gray[n, 2, i, i]); } } } [Fact] public void InvertTensor() { { using (var input = torch.rand(25)) { var iData = input.data<float>(); var poster = torchvision.transforms.Invert().forward(input); var pData = poster.data<float>(); Assert.Equal(new long[] { 25 }, poster.shape); for (int i = 0; i < poster.shape[0]; i++) { Assert.Equal(1.0f - iData[i], pData[i]); } } } } [Fact] public void PosterizeTensor() { { using (var input = torch.randint(255, new long[] { 16, 3, 25, 25 }, torch.uint8)) { var poster = torchvision.transforms.Posterize(4).forward(input); Assert.Equal(new long[] { 16, 3, 25, 25 }, poster.shape); } } { using (var input = torch.randint(255, new long[] { 25 }, torch.uint8)) { var poster = torchvision.transforms.Posterize(4).forward(input); Assert.Equal(new long[] { 25 }, poster.shape); Assert.All(poster.data<byte>().ToArray(), b => Assert.Equal(0, b & 0xf)); } } } [Fact] public void AdjustSharpnessTensor() { { using (var input = torch.randint(255, new long[] { 16, 3, 25, 25 }, torch.uint8)) { var poster = torchvision.transforms.AdjustSharpness(1.5).forward(input); Assert.Equal(new long[] { 16, 3, 25, 25 }, poster.shape); } } { using (var input = torch.randint(255, new long[] { 16, 3, 25, 25 }, torch.uint8)) { var poster = torchvision.transforms.AdjustSharpness(0.5).forward(input); Assert.Equal(new long[] { 16, 3, 25, 25 }, poster.shape); } } } [Fact] public void AdjustHueTensor() { { using (var input = torch.stack(new Tensor[] { torch.zeros(1, 2, 2), torch.ones(1, 2, 2), torch.zeros(1, 2, 2) }, dimension: -3)) { var poster = torchvision.transforms.AdjustHue(0).forward(input); var istr = input.ToString(true); var pstr = poster.ToString(true); Assert.Equal(new long[] { 1, 3, 2, 2 }, poster.shape); Assert.True(poster.allclose(input)); } } } [Fact] public void RotateTensor() { { using (var input = torch.rand(16, 3, 25, 50)) { var poster = torchvision.transforms.Rotate(90).forward(input); Assert.Equal(new long[] { 16, 3, 25, 50 }, poster.shape); } } } [Fact] public void AutocontrastTensor() { { using (var input = torch.randint(255, new long[] { 16, 3, 25, 25 }, torch.uint8)) { var poster = torchvision.transforms.AutoContrast().forward(input); Assert.Equal(new long[] { 16, 3, 25, 25 }, poster.shape); } } { using (var input = torch.randint(255, new long[] { 16, 3, 25, 25 }, torch.uint8)) { var poster = torchvision.transforms.AutoContrast().forward(input); Assert.Equal(new long[] { 16, 3, 25, 25 }, poster.shape); } } } [Fact] public void PerspectiveTest() { { using (var input = torch.ones(1, 3, 8, 8)) { var startpoints = new List<IList<int>>(); startpoints.Add(new int[] { 0, 0 }); startpoints.Add(new int[] { 7, 0 }); startpoints.Add(new int[] { 7, 7 }); startpoints.Add(new int[] { 0, 7 }); var endpoints = new List<IList<int>>(); endpoints.Add(new int[] { 1, 1 }); endpoints.Add(new int[] { 5, 2 }); endpoints.Add(new int[] { 5, 6 }); endpoints.Add(new int[] { 3, 7 }); var poster = torchvision.transforms.functional.perspective(input, startpoints, endpoints); var pStr = poster.ToString(true); Assert.Equal(new long[] { 1, 3, 8, 8 }, poster.shape); } } } [Fact] public void GaussianBlurTest() { { using (var input = torch.randint(255, new long[] { 16, 3, 25, 25 }, torch.uint8)) { var poster = torchvision.transforms.GaussianBlur(4).forward(input); Assert.Equal(new long[] { 16, 3, 25, 25 }, poster.shape); } } { using (var input = torch.rand(16, 3, 25, 25)) { // Test even-number kernel size. var poster = torchvision.transforms.GaussianBlur(4).forward(input); Assert.Equal(new long[] { 16, 3, 25, 25 }, poster.shape); } } { using (var input = torch.rand(16, 3, 25, 25)) { // Test odd-number kernel size. var poster = torchvision.transforms.GaussianBlur(5).forward(input); Assert.Equal(new long[] { 16, 3, 25, 25 }, poster.shape); } } { using (var input = torch.rand(16, 3, 25, 25)) { var random = torchvision.transforms.Randomize(torchvision.transforms.GaussianBlur(4), 0.5); var poster = random.forward(input); Assert.Equal(new long[] { 16, 3, 25, 25 }, poster.shape); } } } [Fact] public void SolarizeTensor() { { using (var input = torch.rand(25)) { var poster = torchvision.transforms.Solarize(0.55).forward(input); Assert.Equal(new long[] { 25 }, poster.shape); Assert.All(poster.data<float>().ToArray(), f => Assert.True(f < 0.55f)); } } } [Fact] public void HorizontalFlipTest() { var input = torch.tensor(new int[] { 1, 2, 3, 1, 2, 3, 1, 2, 3, }).reshape(3, 3); var expected = torch.tensor(new int[] { 3, 2, 1, 3, 2, 1, 3, 2, 1, }).reshape(3, 3); var res = torchvision.transforms.HorizontalFlip().forward(input); Assert.Equal(res, expected); } [Fact] public void VerticalFlipTest() { var input = torch.tensor(new int[] { 1, 1, 1, 2, 2, 2, 3, 3, 3, }).reshape(3, 3); var expected = torch.tensor(new int[] { 3, 3, 3, 2, 2, 2, 1, 1, 1, }).reshape(3, 3); var res = torchvision.transforms.VerticalFlip().forward(input); Assert.Equal(res, expected); } } }
39.271172
252
0.472136
[ "MIT" ]
xamarin/TorchSharp
test/TorchSharpTest/TestTorchTensor.cs
231,857
C#
using System.Threading.Tasks; using Roc.CMS.Sessions.Dto; namespace Roc.CMS.Sessions { public class ProxySessionAppService : ProxyAppServiceBase, ISessionAppService { public async Task<GetCurrentLoginInformationsOutput> GetCurrentLoginInformations() { return await ApiClient.GetAsync<GetCurrentLoginInformationsOutput>(GetEndpoint(nameof(GetCurrentLoginInformations))); } public async Task<UpdateUserSignInTokenOutput> UpdateUserSignInToken() { return await ApiClient.PutAsync<UpdateUserSignInTokenOutput>(GetEndpoint(nameof(UpdateUserSignInToken))); } } }
33.894737
129
0.73913
[ "MIT" ]
RocChing/Roc.CMS
src/Roc.CMS.Application.Client/Sessions/ProxySessionAppService.cs
646
C#
using NBitcoin; using NBitcoin.Crypto; using NBitcoin.DataEncoders; using NBitcoin.Protocol; using NBitcoin.RPC; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Threading.Tasks; namespace NBitcoin.Altcoins { public class GoByte : NetworkSetBase { public static GoByte Instance { get; } = new GoByte(); public override string CryptoCode => "GBX"; private GoByte() { } public class GoByteConsensusFactory : ConsensusFactory { private GoByteConsensusFactory() { } public static GoByteConsensusFactory Instance { get; } = new GoByteConsensusFactory(); public override BlockHeader CreateBlockHeader() { return new GoByteBlockHeader(); } public override Block CreateBlock() { return new GoByteBlock(new GoByteBlockHeader()); } } #pragma warning disable CS0618 // Type or member is obsolete public class GoByteBlockHeader : BlockHeader { static byte[] CalculateHash(byte[] data, int offset, int count) { // TODO: change the hash algorithm return new HashX11.X11().ComputeBytes(data.Skip(offset).Take(count).ToArray()); } protected override HashStreamBase CreateHashStream() { return BufferedHashStream.CreateFrom(CalculateHash, 80); } } public class GoByteBlock : Block { #pragma warning disable CS0612 // Type or member is obsolete public GoByteBlock(GoByteBlockHeader h) : base(h) #pragma warning restore CS0612 // Type or member is obsolete { } public override ConsensusFactory GetConsensusFactory() { return GoByteConsensusFactory.Instance; } } #pragma warning restore CS0618 // Type or member is obsolete protected override void PostInit() { RegisterDefaultCookiePath("GoByteCore"); } static uint256 GetPoWHash(BlockHeader header) { var headerBytes = header.ToBytes(); var h = NBitcoin.Crypto.SCrypt.ComputeDerivedKey(headerBytes, headerBytes, 1024, 1, 1, null, 32); return new uint256(h); } protected override NetworkBuilder CreateMainnet() { var builder = new NetworkBuilder(); builder.SetConsensus(new Consensus() { SubsidyHalvingInterval = 210240, // one year MajorityEnforceBlockUpgrade = 750, MajorityRejectBlockOutdated = 950, MajorityWindow = 1000, BIP34Hash = new uint256("0x00000c8a1ff01bae3f3875c81cb14115429af5744643b34b4ad1cbb7d2d59ca2"), PowLimit = new Target(new uint256("00000fffff000000000000000000000000000000000000000000000000000000")), MinimumChainWork = new uint256("00000fffff000000000000000000000000000000000000000000000000000000"), PowTargetTimespan = TimeSpan.FromSeconds(60 * 60), PowTargetSpacing = TimeSpan.FromSeconds(2.5 * 60), PowAllowMinDifficultyBlocks = false, CoinbaseMaturity = 100, PowNoRetargeting = false, RuleChangeActivationThreshold = 1916, // 95% of 2016 MinerConfirmationWindow = 2016, ConsensusFactory = GoByteConsensusFactory.Instance, SupportSegwit = false }) // done .SetBase58Bytes(Base58Type.PUBKEY_ADDRESS, new byte[] { 38 }) .SetBase58Bytes(Base58Type.SCRIPT_ADDRESS, new byte[] { 10 }) .SetBase58Bytes(Base58Type.SECRET_KEY, new byte[] { 198 }) .SetBase58Bytes(Base58Type.EXT_PUBLIC_KEY, new byte[] { 0x04, 0x88, 0xB2, 0x1E }) .SetBase58Bytes(Base58Type.EXT_SECRET_KEY, new byte[] { 0x04, 0x88, 0xAD, 0xE4 }) .SetBech32(Bech32Type.WITNESS_PUBKEY_ADDRESS, Encoders.Bech32("gobyte")) .SetBech32(Bech32Type.WITNESS_SCRIPT_ADDRESS, Encoders.Bech32("gobyte")) .SetMagic(0xD4C3B21A) .SetPort(12455) .SetRPCPort(12454) .SetMaxP2PVersion(70209) .SetName("gobyte-main") .AddAlias("gobyte-mainnet") .AddDNSSeeds(new[] { new DNSSeedData("seed1.gobyte.network", "seed1.gobyte.network"), new DNSSeedData("seed2.gobyte.network", "seed2.gobyte.network"), new DNSSeedData("seed3.gobyte.network", "seed3.gobyte.network"), new DNSSeedData("seed4.gobyte.network", "seed4.gobyte.network"), new DNSSeedData("seed5.gobyte.network", "seed5.gobyte.network"), new DNSSeedData("seed6.gobyte.network", "seed6.gobyte.network"), new DNSSeedData("seed7.gobyte.network", "seed7.gobyte.network"), new DNSSeedData("seed8.gobyte.network", "seed8.gobyte.network"), new DNSSeedData("seed9.gobyte.network", "seed9.gobyte.network"), new DNSSeedData("seed10.gobyte.network", "seed10.gobyte.network") }) // done .AddSeeds(new NetworkAddress[0]) .SetGenesis("010000000000000000000000000000000000000000000000000000000000000000000000219f39f283f43185a0ef69cba1702151ab0cf02454a57e1039dabcc19d719adc00b60d5af0ff0f1e6fe618000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4204ffff001d01043a5468652053746172204d616c61797369612031377468204e6f76656d626572203230313720476f427974652047656e65736973205265626f726effffffff0100f2052a010000004341043e5a5fbfbb2caa5f4b7c8fd24d890d6c244de254d579b5ba629f64c1b48275f59e0e1c834a60f6ffb4aaa022aaa4866434ca729a12465f80618fb2070045cb16ac00000000"); return builder; } protected override NetworkBuilder CreateTestnet() { var builder = new NetworkBuilder(); builder.SetConsensus(new Consensus() { SubsidyHalvingInterval = 210240, MajorityEnforceBlockUpgrade = 51, MajorityRejectBlockOutdated = 75, MajorityWindow = 100, BIP34Hash = new uint256("0x0000064a72bc327f2c93169784623348d8ad8975873563a2c3e0e1deb6bcc9f7"), PowLimit = new Target(new uint256("0x00000fffff000000000000000000000000000000000000000000000000000000")), MinimumChainWork = new uint256("0x000000000000000000000000000000000000000000000000000006a96dd9119d"), PowTargetTimespan = TimeSpan.FromSeconds(60 * 60), PowTargetSpacing = TimeSpan.FromSeconds(2.5 * 60), PowAllowMinDifficultyBlocks = true, CoinbaseMaturity = 100, PowNoRetargeting = false, RuleChangeActivationThreshold = 1512, MinerConfirmationWindow = 2016, ConsensusFactory = GoByteConsensusFactory.Instance, SupportSegwit = false }) .SetBase58Bytes(Base58Type.PUBKEY_ADDRESS, new byte[] { 112 }) .SetBase58Bytes(Base58Type.SCRIPT_ADDRESS, new byte[] { 20 }) .SetBase58Bytes(Base58Type.SECRET_KEY, new byte[] { 239 }) .SetBase58Bytes(Base58Type.EXT_PUBLIC_KEY, new byte[] { 0x04, 0x35, 0x87, 0xCF }) .SetBase58Bytes(Base58Type.EXT_SECRET_KEY, new byte[] { 0x04, 0x35, 0x83, 0x94 }) .SetBech32(Bech32Type.WITNESS_PUBKEY_ADDRESS, Encoders.Bech32("tgobyte")) .SetBech32(Bech32Type.WITNESS_SCRIPT_ADDRESS, Encoders.Bech32("tgobyte")) .SetMagic(0xFFCAE2CE) .SetPort(13455) .SetRPCPort(13454) .SetMaxP2PVersion(70209) .SetName("gobyte-test") .AddAlias("gobyte-testnet") .AddDNSSeeds(new[] { new DNSSeedData("gobyte.network", "testnet-dns.gobyte.network"), new DNSSeedData("gobyte.network", "testnet2-dns.gobyte.network") }) .AddSeeds(new NetworkAddress[0]) .SetGenesis("010000000000000000000000000000000000000000000000000000000000000000000000219f39f283f43185a0ef69cba1702151ab0cf02454a57e1039dabcc19d719adc20de0b5af0ff0f1ebbc02d000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4204ffff001d01043a5468652053746172204d616c61797369612031377468204e6f76656d626572203230313720476f427974652047656e65736973205265626f726effffffff0100f2052a010000004341043e5a5fbfbb2caa5f4b7c8fd24d890d6c244de254d579b5ba629f64c1b48275f59e0e1c834a60f6ffb4aaa022aaa4866434ca729a12465f80618fb2070045cb16ac00000000"); return builder; } protected override NetworkBuilder CreateRegtest() { var builder = new NetworkBuilder(); builder.SetConsensus(new Consensus() { SubsidyHalvingInterval = 150, MajorityEnforceBlockUpgrade = 750, MajorityRejectBlockOutdated = 950, MajorityWindow = 1000, BIP34Hash = new uint256(), PowLimit = new Target(new uint256("7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), MinimumChainWork = new uint256("0x000000000000000000000000000000000000000000000000000924e924a21715"), PowTargetTimespan = TimeSpan.FromSeconds(24 * 60 * 60), PowTargetSpacing = TimeSpan.FromSeconds(2.5 * 60), PowAllowMinDifficultyBlocks = true, CoinbaseMaturity = 100, PowNoRetargeting = true, RuleChangeActivationThreshold = 108, MinerConfirmationWindow = 144, ConsensusFactory = GoByteConsensusFactory.Instance, SupportSegwit = false }) .SetBase58Bytes(Base58Type.PUBKEY_ADDRESS, new byte[] { 112 }) .SetBase58Bytes(Base58Type.SCRIPT_ADDRESS, new byte[] { 20 }) .SetBase58Bytes(Base58Type.SECRET_KEY, new byte[] { 240 }) .SetBase58Bytes(Base58Type.EXT_PUBLIC_KEY, new byte[] { 0x04, 0x35, 0x87, 0xCF }) .SetBase58Bytes(Base58Type.EXT_SECRET_KEY, new byte[] { 0x04, 0x35, 0x83, 0x94 }) .SetBech32(Bech32Type.WITNESS_PUBKEY_ADDRESS, Encoders.Bech32("tgobyte")) .SetBech32(Bech32Type.WITNESS_SCRIPT_ADDRESS, Encoders.Bech32("tgobyte")) .SetMagic(0x7BD5B3A1) .SetPort(13565) .SetRPCPort(13564) .SetMaxP2PVersion(70209) .SetName("gobyte-reg") .AddAlias("gobyte-regtest") .AddDNSSeeds(new DNSSeedData[0]) .AddSeeds(new NetworkAddress[0]) .SetGenesis("010000000000000000000000000000000000000000000000000000000000000000000000219f39f283f43185a0ef69cba1702151ab0cf02454a57e1039dabcc19d719adcbcdd0b5af0ff0f1e63c00d000101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff4204ffff001d01043a5468652053746172204d616c61797369612031377468204e6f76656d626572203230313720476f427974652047656e65736973205265626f726effffffff0100f2052a010000004341043e5a5fbfbb2caa5f4b7c8fd24d890d6c244de254d579b5ba629f64c1b48275f59e0e1c834a60f6ffb4aaa022aaa4866434ca729a12465f80618fb2070045cb16ac00000000"); return builder; } } }
46.457143
569
0.776548
[ "MIT" ]
BitcoinRhodium/NBitcoin
NBitcoin.Altcoins/Gobyte.cs
9,758
C#
using UnityEngine; /// <summary> /// System to place towers. Sets up the TowerPlacer. /// </summary> public class TowerPlacementSystem : MonoBehaviour { /// <summary> /// Prefab to use as the TowerPlacer. /// </summary> public GameObject PlacerPrefab; private GameObject instance; private bool isActive = false; private bool isChecking = false; void Start() { EventRegistry.RegisterAction<GameObject, Vector3, bool>("togglePlacer", TogglePlacer); } void Update() { if (isChecking) { if (isActive && instance.GetComponent<TowerPlacer>().CheckTransaction()) { isChecking = false; DestroyPlacer(); } } else { if (isActive && Input.GetButtonDown("Fire1")) { if (instance.GetComponent<TowerPlacer>().PlaceTower()) { isChecking = true; } } } } /// <summary> /// Callback for the <c>togglePlacer </c> event. Toggles the TowerPlacer. /// </summary> /// <param name="targetTower">The tower to create with this placer.</param> /// <param name="location">The position to create the placer at.</param> /// <param name="isMove">Whether we are moving or creating a new tower.</param> public void TogglePlacer(GameObject targetTower, Vector3 location, bool isMove) { if (isActive) { DestroyPlacer(); } else { CreatePlacer(targetTower, location, isMove); } } private void CreatePlacer(GameObject targetTower, Vector3 location, bool isMove) { location.y = 0; // so that the indicator spawns on the ground instance = Instantiate(PlacerPrefab, location, Quaternion.identity); instance.GetComponent<TowerPlacer>().SetTower(targetTower, isMove); isActive = true; isChecking = false; } private void DestroyPlacer() { Destroy(instance); isActive = false; } }
27.428571
94
0.572443
[ "MIT" ]
fahad-30/tower-defense
Assets/Scripts/Towers/TowerPlacementSystem.cs
2,112
C#
using GalaSoft.MvvmLight.Command; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Windows.ApplicationModel.DataTransfer; namespace EasyDictionary.Domain { /// Represents a single translation. /// Eg.: House (en_US) -> Haus (de_DE) public class Translation { public String Source { get; set; } public String Destination { get; set; } } }
23.85
47
0.712788
[ "MIT" ]
marcobusemann/easydictionary
EasyDictionary/Domain/Translation.cs
479
C#
#region Copyright // // Copyright 2015 Underscore Research LLC. // ALL RIGHTS RESERVED. // // UNDERSCORE RESEARCH LLC. MAKES NO REPRESENTATIONS OR // WARRANTIES ABOUT THE SUITABILITY OF THE SOFTWARE, EITHER // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A // PARTICULAR PURPOSE, OR NON-INFRINGEMENT. DELL SHALL // NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE // AS A RESULT OF USING, MODIFYING OR DISTRIBUTING // THIS SOFTWARE OR ITS DERIVATIVES. // // Authored by Henrik Johnson // #endregion using System; using System.Collections.Generic; namespace Underscore.SoapParser.Test { /// <summary> /// Byte array comparer. /// </summary> public class ByteArrayComparer : IComparer<byte[]> { private static readonly ByteArrayComparer comparer = new ByteArrayComparer(); /// <summary> /// Preallocated instance /// </summary> public static ByteArrayComparer Comparer { get { return comparer; } } #region Implementation of IComparer<in byte[]> /// <summary> /// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other. /// </summary> /// <returns> /// A signed integer that indicates the relative values of <paramref name="x"/> and <paramref name="y"/>, as shown in the following table.Value Meaning Less than zero<paramref name="x"/> is less than <paramref name="y"/>.Zero<paramref name="x"/> equals <paramref name="y"/>.Greater than zero<paramref name="x"/> is greater than <paramref name="y"/>. /// </returns> /// <param name="x">The first object to compare.</param><param name="y">The second object to compare.</param> public int Compare(byte[] x, byte[] y) { int min = Math.Min(x.Length, y.Length); for (int i = 0; i < min; i++) if (x[i] != y[i]) return (int)x[i] - (int)y[i]; return x.Length - y.Length; } #endregion } }
32.590164
353
0.67002
[ "MIT" ]
UnderscoreResearch/SoapParser
SoapParser.Test/ByteArrayComparer.cs
1,990
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.Diagnostics; namespace System.Collections.Specialized { /// <summary> /// Arguments for the CollectionChanged event. /// A collection that supports INotifyCollectionChangedThis raises this event /// whenever an item is added or removed, or when the contents of the collection /// changes dramatically. /// </summary> public class NotifyCollectionChangedEventArgs : EventArgs { private readonly NotifyCollectionChangedAction _action; private readonly IList? _newItems; private readonly IList? _oldItems; private readonly int _newStartingIndex = -1; private readonly int _oldStartingIndex = -1; /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a reset change. /// </summary> /// <param name="action">The action that caused the event (must be Reset).</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action) { if (action != NotifyCollectionChangedAction.Reset) { throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Reset), nameof(action)); } _action = action; } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item change. /// </summary> /// <param name="action">The action that caused the event; can only be Reset, Add or Remove action.</param> /// <param name="changedItem">The item affected by the change.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object? changedItem) : this(action, changedItem, -1) { } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item change. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItem">The item affected by the change.</param> /// <param name="index">The index where the change occurred.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object? changedItem, int index) { switch (action) { case NotifyCollectionChangedAction.Reset: if (changedItem != null) { throw new ArgumentException(SR.ResetActionRequiresNullItem, nameof(action)); } if (index != -1) { throw new ArgumentException(SR.ResetActionRequiresIndexMinus1, nameof(action)); } break; case NotifyCollectionChangedAction.Add: _newItems = new SingleItemReadOnlyList(changedItem); _newStartingIndex = index; break; case NotifyCollectionChangedAction.Remove: _oldItems = new SingleItemReadOnlyList(changedItem); _oldStartingIndex = index; break; default: throw new ArgumentException(SR.MustBeResetAddOrRemoveActionForCtor, nameof(action)); } _action = action; } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item change. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList? changedItems) : this(action, changedItems, -1) { } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item change (or a reset). /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> /// <param name="startingIndex">The index where the change occurred.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList? changedItems, int startingIndex) { switch (action) { case NotifyCollectionChangedAction.Reset: if (changedItems != null) { throw new ArgumentException(SR.ResetActionRequiresNullItem, nameof(action)); } if (startingIndex != -1) { throw new ArgumentException(SR.ResetActionRequiresIndexMinus1, nameof(action)); } break; case NotifyCollectionChangedAction.Add: case NotifyCollectionChangedAction.Remove: ArgumentNullException.ThrowIfNull(changedItems); if (startingIndex < -1) { throw new ArgumentException(SR.IndexCannotBeNegative, nameof(startingIndex)); } if (action == NotifyCollectionChangedAction.Add) { _newItems = new ReadOnlyList(changedItems); _newStartingIndex = startingIndex; } else { _oldItems = new ReadOnlyList(changedItems); _oldStartingIndex = startingIndex; } break; default: throw new ArgumentException(SR.MustBeResetAddOrRemoveActionForCtor, nameof(action)); } _action = action; } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItem">The new item replacing the original item.</param> /// <param name="oldItem">The original item that is replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object? newItem, object? oldItem) : this(action, newItem, oldItem, -1) { } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItem">The new item replacing the original item.</param> /// <param name="oldItem">The original item that is replaced.</param> /// <param name="index">The index of the item being replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object? newItem, object? oldItem, int index) { if (action != NotifyCollectionChangedAction.Replace) { throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), nameof(action)); } _action = action; _newItems = new SingleItemReadOnlyList(newItem); _oldItems = new SingleItemReadOnlyList(oldItem); _newStartingIndex = _oldStartingIndex = index; } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItems">The new items replacing the original items.</param> /// <param name="oldItems">The original items that are replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems) : this(action, newItems, oldItems, -1) { } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Replace event. /// </summary> /// <param name="action">Can only be a Replace action.</param> /// <param name="newItems">The new items replacing the original items.</param> /// <param name="oldItems">The original items that are replaced.</param> /// <param name="startingIndex">The starting index of the items being replaced.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList newItems, IList oldItems, int startingIndex) { if (action != NotifyCollectionChangedAction.Replace) { throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Replace), nameof(action)); } ArgumentNullException.ThrowIfNull(newItems); ArgumentNullException.ThrowIfNull(oldItems); _action = action; _newItems = new ReadOnlyList(newItems); _oldItems = new ReadOnlyList(oldItems); _newStartingIndex = _oldStartingIndex = startingIndex; } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a one-item Move event. /// </summary> /// <param name="action">Can only be a Move action.</param> /// <param name="changedItem">The item affected by the change.</param> /// <param name="index">The new index for the changed item.</param> /// <param name="oldIndex">The old index for the changed item.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, object? changedItem, int index, int oldIndex) { if (action != NotifyCollectionChangedAction.Move) { throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Move), nameof(action)); } if (index < 0) { throw new ArgumentException(SR.IndexCannotBeNegative, nameof(index)); } _action = action; _newItems = _oldItems = new SingleItemReadOnlyList(changedItem); _newStartingIndex = index; _oldStartingIndex = oldIndex; } /// <summary> /// Construct a NotifyCollectionChangedEventArgs that describes a multi-item Move event. /// </summary> /// <param name="action">The action that caused the event.</param> /// <param name="changedItems">The items affected by the change.</param> /// <param name="index">The new index for the changed items.</param> /// <param name="oldIndex">The old index for the changed items.</param> public NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction action, IList? changedItems, int index, int oldIndex) { if (action != NotifyCollectionChangedAction.Move) { throw new ArgumentException(SR.Format(SR.WrongActionForCtor, NotifyCollectionChangedAction.Move), nameof(action)); } if (index < 0) { throw new ArgumentException(SR.IndexCannotBeNegative, nameof(index)); } _action = action; _newItems = _oldItems = changedItems is not null ? new ReadOnlyList(changedItems) : null; _newStartingIndex = index; _oldStartingIndex = oldIndex; } /// <summary> /// The action that caused the event. /// </summary> public NotifyCollectionChangedAction Action => _action; /// <summary> /// The items affected by the change. /// </summary> public IList? NewItems => _newItems; /// <summary> /// The old items affected by the change (for Replace events). /// </summary> public IList? OldItems => _oldItems; /// <summary> /// The index where the change occurred. /// </summary> public int NewStartingIndex => _newStartingIndex; /// <summary> /// The old index where the change occurred (for Move events). /// </summary> public int OldStartingIndex => _oldStartingIndex; } /// <summary> /// The delegate to use for handlers that receive the CollectionChanged event. /// </summary> public delegate void NotifyCollectionChangedEventHandler(object? sender, NotifyCollectionChangedEventArgs e); internal sealed class ReadOnlyList : IList { private readonly IList _list; internal ReadOnlyList(IList list) { Debug.Assert(list != null); _list = list; } public int Count => _list.Count; public bool IsReadOnly => true; public bool IsFixedSize => true; public bool IsSynchronized => _list.IsSynchronized; public object? this[int index] { get => _list[index]; set => throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public object SyncRoot => _list.SyncRoot; public int Add(object? value) => throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); public void Clear() => throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); public bool Contains(object? value) => _list.Contains(value); public void CopyTo(Array array, int index) => _list.CopyTo(array, index); public IEnumerator GetEnumerator() => _list.GetEnumerator(); public int IndexOf(object? value) => _list.IndexOf(value); public void Insert(int index, object? value) => throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); public void Remove(object? value) => throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); public void RemoveAt(int index) => throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } internal sealed class SingleItemReadOnlyList : IList { private readonly object? _item; public SingleItemReadOnlyList(object? item) => _item = item; public object? this[int index] { get { if (index != 0) { throw new ArgumentOutOfRangeException(nameof(index)); } return _item; } set => throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } public bool IsFixedSize => true; public bool IsReadOnly => true; public int Count => 1; public bool IsSynchronized => false; public object SyncRoot => this; public IEnumerator GetEnumerator() { yield return _item; } public bool Contains(object? value) => _item is null ? value is null : _item.Equals(value); public int IndexOf(object? value) => Contains(value) ? 0 : -1; public void CopyTo(Array array, int index) { CollectionHelpers.ValidateCopyToArguments(1, array, index); array.SetValue(_item, index); } public int Add(object? value) => throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); public void Clear() => throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); public void Insert(int index, object? value) => throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); public void Remove(object? value) => throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); public void RemoveAt(int index) => throw new NotSupportedException(SR.NotSupported_ReadOnlyCollection); } }
41.939791
136
0.612321
[ "MIT" ]
AUTOMATE-2001/runtime
src/libraries/System.ObjectModel/src/System/Collections/Specialized/NotifyCollectionChangedEventArgs.cs
16,021
C#
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\ddrawi.h(1404,9) using System; using System.Runtime.InteropServices; using LPDDCOLORCONTROL = DirectN._DDCOLORCONTROL; namespace DirectN { [StructLayout(LayoutKind.Sequential)] public partial struct _DDRAWI_DDRAWSURFACE_GBL_MORE { public uint dwSize; public _DDRAWI_DDRAWSURFACE_GBL_MORE__union_0 __union_1; public IntPtr pPageTable; public uint cPages; public IntPtr dwSavedDCContext; public ulong fpAliasedVidMem; public IntPtr dwDriverReserved; public IntPtr dwHELReserved; public uint cPageUnlocks; public IntPtr hKernelSurface; public uint dwKernelRefCnt; public IntPtr lpColorInfo; public ulong fpNTAlias; public uint dwContentsStamp; public IntPtr lpvUnswappedDriverReserved; public IntPtr lpDDRAWReserved2; public uint dwDDRAWReserved1; public uint dwDDRAWReserved2; public ulong fpAliasOfVidMem; } }
32.65625
83
0.708134
[ "MIT" ]
bbday/DirectN
DirectN/DirectN/Generated/_DDRAWI_DDRAWSURFACE_GBL_MORE.cs
1,047
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> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("RestWithASPNETUdemy_Calculator")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("RestWithASPNETUdemy_Calculator")] [assembly: System.Reflection.AssemblyTitleAttribute("RestWithASPNETUdemy_Calculator")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
43.333333
88
0.667308
[ "MIT" ]
Luisssp/ResAPi-Calculator
RestWithASPNETUdemy_Calculator/obj/Debug/net5.0/RestWithASPNETUdemy_Calculator.AssemblyInfo.cs
1,040
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; namespace ToDoListVS3 { public class Program { public static void Main(string[] args) { var host = new WebHostBuilder() .UseKestrel() .UseContentRoot(Directory.GetCurrentDirectory()) .UseIISIntegration() .UseStartup<Startup>() .UseApplicationInsights() .Build(); host.Run(); } } }
22.692308
64
0.569492
[ "Unlicense" ]
Sara-Hamilton/ToDoListVS3
ToDoListVS3/Program.cs
592
C#
/* ======================================================================== * Copyright (c) 2005-2016 The OPC Foundation, Inc. All rights reserved. * * OPC Foundation MIT License 1.00 * * 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. * * The complete license agreement can be found here: * http://opcfoundation.org/License/MIT/1.00/ * ======================================================================*/ using System; using System.Collections.Generic; using System.Text; using System.Xml; using System.Runtime.Serialization; using Prefix0; namespace Prefix2 { #region DataType Identifiers /// <summary> /// A class that declares constants for all DataTypes in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class DataTypes { /// <summary> /// The identifier for the JobOrderCommandEnum DataType. /// </summary> public const uint JobOrderCommandEnum = 1; /// <summary> /// The identifier for the JobOrderStateEnum DataType. /// </summary> public const uint JobOrderStateEnum = 4; /// <summary> /// The identifier for the OPENSCSReturnEnum DataType. /// </summary> public const uint OPENSCSReturnEnum = 7; /// <summary> /// The identifier for the OPENSCSSerialNumberStateEnum DataType. /// </summary> public const uint OPENSCSSerialNumberStateEnum = 10; /// <summary> /// The identifier for the OPENSCSAggregationDataType DataType. /// </summary> public const uint OPENSCSAggregationDataType = 13; /// <summary> /// The identifier for the OPENSCSCollectionDataType DataType. /// </summary> public const uint OPENSCSCollectionDataType = 14; /// <summary> /// The identifier for the OPENSCSLabelCollectionDataType DataType. /// </summary> public const uint OPENSCSLabelCollectionDataType = 15; /// <summary> /// The identifier for the OPENSCSSNCollectionDataType DataType. /// </summary> public const uint OPENSCSSNCollectionDataType = 16; /// <summary> /// The identifier for the OPENSCSEventStreamArgumentDataType DataType. /// </summary> public const uint OPENSCSEventStreamArgumentDataType = 17; /// <summary> /// The identifier for the OPENSCSKeyValueDataType DataType. /// </summary> public const uint OPENSCSKeyValueDataType = 18; /// <summary> /// The identifier for the OPENSCSLabelDataType DataType. /// </summary> public const uint OPENSCSLabelDataType = 19; /// <summary> /// The identifier for the OPENSCSLabelPropertyDataType DataType. /// </summary> public const uint OPENSCSLabelPropertyDataType = 20; /// <summary> /// The identifier for the OPENSCSSIDClassPropertyDataType DataType. /// </summary> public const uint OPENSCSSIDClassPropertyDataType = 21; } #endregion #region Method Identifiers /// <summary> /// A class that declares constants for all Methods in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class Methods { /// <summary> /// The identifier for the OPENSCSAggregationManagerObjectType_AggregationPackingEvent Method. /// </summary> public const uint OPENSCSAggregationManagerObjectType_AggregationPackingEvent = 23; /// <summary> /// The identifier for the OPENSCSAggregationManagerObjectType_AggregationUnpackingEvent Method. /// </summary> public const uint OPENSCSAggregationManagerObjectType_AggregationUnpackingEvent = 26; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForRead Method. /// </summary> public const uint OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForRead = 33; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForWrite Method. /// </summary> public const uint OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForWrite = 36; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_CloseAndCommit Method. /// </summary> public const uint OPENSCSEventManagerObjectType_EPCISStream_CloseAndCommit = 39; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsEncodingEvent Method. /// </summary> public const uint OPENSCSEventManagerObjectType_LabelsEncodingEvent = 42; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsInspectingEvent Method. /// </summary> public const uint OPENSCSEventManagerObjectType_LabelsInspectingEvent = 45; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsSamplingEvent Method. /// </summary> public const uint OPENSCSEventManagerObjectType_LabelsSamplingEvent = 48; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsScrappingEvent Method. /// </summary> public const uint OPENSCSEventManagerObjectType_LabelsScrappingEvent = 51; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDCommissioningEvent Method. /// </summary> public const uint OPENSCSEventManagerObjectType_SIDCommissioningEvent = 57; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDDecommissioningEvent Method. /// </summary> public const uint OPENSCSEventManagerObjectType_SIDDecommissioningEvent = 60; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDDestroyingEvent Method. /// </summary> public const uint OPENSCSEventManagerObjectType_SIDDestroyingEvent = 63; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDInspectingEvent Method. /// </summary> public const uint OPENSCSEventManagerObjectType_SIDInspectingEvent = 66; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDShippingEvent Method. /// </summary> public const uint OPENSCSEventManagerObjectType_SIDShippingEvent = 69; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SNInvalidatingEvent Method. /// </summary> public const uint OPENSCSEventManagerObjectType_SNInvalidatingEvent = 72; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestAllocated Method. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNRequestAllocated = 81; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestUnallocated Method. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNRequestUnallocated = 84; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestUnassigned Method. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNRequestUnassigned = 87; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNReturnAllocated Method. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNReturnAllocated = 90; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNReturnUnallocated Method. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNReturnUnallocated = 93; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoAllocated Method. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNtoAllocated = 96; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoEncoded Method. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNtoEncoded = 99; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoUnallocated Method. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNtoUnallocated = 102; } #endregion #region Object Identifiers /// <summary> /// A class that declares constants for all Objects in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class Objects { /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream Object. /// </summary> public const uint OPENSCSEventManagerObjectType_EPCISStream = 31; /// <summary> /// The identifier for the OPENSCSAggregationDataType_Encoding_DefaultXml Object. /// </summary> public const uint OPENSCSAggregationDataType_Encoding_DefaultXml = 113; /// <summary> /// The identifier for the OPENSCSCollectionDataType_Encoding_DefaultXml Object. /// </summary> public const uint OPENSCSCollectionDataType_Encoding_DefaultXml = 114; /// <summary> /// The identifier for the OPENSCSLabelCollectionDataType_Encoding_DefaultXml Object. /// </summary> public const uint OPENSCSLabelCollectionDataType_Encoding_DefaultXml = 115; /// <summary> /// The identifier for the OPENSCSSNCollectionDataType_Encoding_DefaultXml Object. /// </summary> public const uint OPENSCSSNCollectionDataType_Encoding_DefaultXml = 116; /// <summary> /// The identifier for the OPENSCSEventStreamArgumentDataType_Encoding_DefaultXml Object. /// </summary> public const uint OPENSCSEventStreamArgumentDataType_Encoding_DefaultXml = 117; /// <summary> /// The identifier for the OPENSCSKeyValueDataType_Encoding_DefaultXml Object. /// </summary> public const uint OPENSCSKeyValueDataType_Encoding_DefaultXml = 118; /// <summary> /// The identifier for the OPENSCSLabelDataType_Encoding_DefaultXml Object. /// </summary> public const uint OPENSCSLabelDataType_Encoding_DefaultXml = 119; /// <summary> /// The identifier for the OPENSCSLabelPropertyDataType_Encoding_DefaultXml Object. /// </summary> public const uint OPENSCSLabelPropertyDataType_Encoding_DefaultXml = 120; /// <summary> /// The identifier for the OPENSCSSIDClassPropertyDataType_Encoding_DefaultXml Object. /// </summary> public const uint OPENSCSSIDClassPropertyDataType_Encoding_DefaultXml = 121; /// <summary> /// The identifier for the OPENSCSAggregationDataType_Encoding_DefaultBinary Object. /// </summary> public const uint OPENSCSAggregationDataType_Encoding_DefaultBinary = 152; /// <summary> /// The identifier for the OPENSCSCollectionDataType_Encoding_DefaultBinary Object. /// </summary> public const uint OPENSCSCollectionDataType_Encoding_DefaultBinary = 153; /// <summary> /// The identifier for the OPENSCSLabelCollectionDataType_Encoding_DefaultBinary Object. /// </summary> public const uint OPENSCSLabelCollectionDataType_Encoding_DefaultBinary = 154; /// <summary> /// The identifier for the OPENSCSSNCollectionDataType_Encoding_DefaultBinary Object. /// </summary> public const uint OPENSCSSNCollectionDataType_Encoding_DefaultBinary = 155; /// <summary> /// The identifier for the OPENSCSEventStreamArgumentDataType_Encoding_DefaultBinary Object. /// </summary> public const uint OPENSCSEventStreamArgumentDataType_Encoding_DefaultBinary = 156; /// <summary> /// The identifier for the OPENSCSKeyValueDataType_Encoding_DefaultBinary Object. /// </summary> public const uint OPENSCSKeyValueDataType_Encoding_DefaultBinary = 157; /// <summary> /// The identifier for the OPENSCSLabelDataType_Encoding_DefaultBinary Object. /// </summary> public const uint OPENSCSLabelDataType_Encoding_DefaultBinary = 158; /// <summary> /// The identifier for the OPENSCSLabelPropertyDataType_Encoding_DefaultBinary Object. /// </summary> public const uint OPENSCSLabelPropertyDataType_Encoding_DefaultBinary = 159; /// <summary> /// The identifier for the OPENSCSSIDClassPropertyDataType_Encoding_DefaultBinary Object. /// </summary> public const uint OPENSCSSIDClassPropertyDataType_Encoding_DefaultBinary = 160; } #endregion #region ObjectType Identifiers /// <summary> /// A class that declares constants for all ObjectTypes in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class ObjectTypes { /// <summary> /// The identifier for the OPENSCSAggregationManagerObjectType ObjectType. /// </summary> public const uint OPENSCSAggregationManagerObjectType = 22; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType ObjectType. /// </summary> public const uint OPENSCSEventManagerObjectType = 30; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType ObjectType. /// </summary> public const uint OPENSCSPoolManagerObjectType = 75; /// <summary> /// The identifier for the OPENSCSSIDClassObjectType ObjectType. /// </summary> public const uint OPENSCSSIDClassObjectType = 105; } #endregion #region Variable Identifiers /// <summary> /// A class that declares constants for all Variables in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class Variables { /// <summary> /// The identifier for the JobOrderCommandEnum_EnumValues Variable. /// </summary> public const uint JobOrderCommandEnum_EnumValues = 2; /// <summary> /// The identifier for the JobOrderCommandEnum_EnumStrings Variable. /// </summary> public const uint JobOrderCommandEnum_EnumStrings = 3; /// <summary> /// The identifier for the JobOrderStateEnum_EnumValues Variable. /// </summary> public const uint JobOrderStateEnum_EnumValues = 5; /// <summary> /// The identifier for the JobOrderStateEnum_EnumStrings Variable. /// </summary> public const uint JobOrderStateEnum_EnumStrings = 6; /// <summary> /// The identifier for the OPENSCSReturnEnum_EnumValues Variable. /// </summary> public const uint OPENSCSReturnEnum_EnumValues = 8; /// <summary> /// The identifier for the OPENSCSReturnEnum_EnumStrings Variable. /// </summary> public const uint OPENSCSReturnEnum_EnumStrings = 9; /// <summary> /// The identifier for the OPENSCSSerialNumberStateEnum_EnumValues Variable. /// </summary> public const uint OPENSCSSerialNumberStateEnum_EnumValues = 11; /// <summary> /// The identifier for the OPENSCSSerialNumberStateEnum_EnumStrings Variable. /// </summary> public const uint OPENSCSSerialNumberStateEnum_EnumStrings = 12; /// <summary> /// The identifier for the OPENSCSAggregationManagerObjectType_AggregationPackingEvent_InputArguments Variable. /// </summary> public const uint OPENSCSAggregationManagerObjectType_AggregationPackingEvent_InputArguments = 24; /// <summary> /// The identifier for the OPENSCSAggregationManagerObjectType_AggregationPackingEvent_OutputArguments Variable. /// </summary> public const uint OPENSCSAggregationManagerObjectType_AggregationPackingEvent_OutputArguments = 25; /// <summary> /// The identifier for the OPENSCSAggregationManagerObjectType_AggregationUnpackingEvent_InputArguments Variable. /// </summary> public const uint OPENSCSAggregationManagerObjectType_AggregationUnpackingEvent_InputArguments = 27; /// <summary> /// The identifier for the OPENSCSAggregationManagerObjectType_AggregationUnpackingEvent_OutputArguments Variable. /// </summary> public const uint OPENSCSAggregationManagerObjectType_AggregationUnpackingEvent_OutputArguments = 28; /// <summary> /// The identifier for the OPENSCSAggregationManagerObjectType_MaxAggregationEvents Variable. /// </summary> public const uint OPENSCSAggregationManagerObjectType_MaxAggregationEvents = 29; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_ClientProcessingTimeout Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_EPCISStream_ClientProcessingTimeout = 32; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForRead_InputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForRead_InputArguments = 34; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForRead_OutputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForRead_OutputArguments = 35; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForWrite_InputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForWrite_InputArguments = 37; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForWrite_OutputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForWrite_OutputArguments = 38; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_CloseAndCommit_InputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_EPCISStream_CloseAndCommit_InputArguments = 40; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_CloseAndCommit_OutputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_EPCISStream_CloseAndCommit_OutputArguments = 41; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsEncodingEvent_InputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_LabelsEncodingEvent_InputArguments = 43; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsEncodingEvent_OutputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_LabelsEncodingEvent_OutputArguments = 44; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsInspectingEvent_InputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_LabelsInspectingEvent_InputArguments = 46; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsInspectingEvent_OutputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_LabelsInspectingEvent_OutputArguments = 47; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsSamplingEvent_InputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_LabelsSamplingEvent_InputArguments = 49; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsSamplingEvent_OutputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_LabelsSamplingEvent_OutputArguments = 50; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsScrappingEvent_InputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_LabelsScrappingEvent_InputArguments = 52; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsScrappingEvent_OutputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_LabelsScrappingEvent_OutputArguments = 53; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_MaxEPCISaggregationEvents Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_MaxEPCISaggregationEvents = 54; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_MaxEPCISObjectEventSIDs Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_MaxEPCISObjectEventSIDs = 55; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_MaxEvents Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_MaxEvents = 56; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDCommissioningEvent_InputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_SIDCommissioningEvent_InputArguments = 58; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDCommissioningEvent_OutputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_SIDCommissioningEvent_OutputArguments = 59; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDDecommissioningEvent_InputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_SIDDecommissioningEvent_InputArguments = 61; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDDecommissioningEvent_OutputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_SIDDecommissioningEvent_OutputArguments = 62; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDDestroyingEvent_InputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_SIDDestroyingEvent_InputArguments = 64; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDDestroyingEvent_OutputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_SIDDestroyingEvent_OutputArguments = 65; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDInspectingEvent_InputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_SIDInspectingEvent_InputArguments = 67; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDInspectingEvent_OutputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_SIDInspectingEvent_OutputArguments = 68; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDShippingEvent_InputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_SIDShippingEvent_InputArguments = 70; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDShippingEvent_OutputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_SIDShippingEvent_OutputArguments = 71; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SNInvalidatingEvent_InputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_SNInvalidatingEvent_InputArguments = 73; /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SNInvalidatingEvent_OutputArguments Variable. /// </summary> public const uint OPENSCSEventManagerObjectType_SNInvalidatingEvent_OutputArguments = 74; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_MaxSNPushable Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_MaxSNPushable = 76; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_MaxSNRequestable Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_MaxSNRequestable = 77; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_MaxSNReturnable Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_MaxSNReturnable = 78; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_PoolSelectionCriteria Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_PoolSelectionCriteria = 79; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNFormat Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNFormat = 80; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestAllocated_InputArguments Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNRequestAllocated_InputArguments = 82; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestAllocated_OutputArguments Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNRequestAllocated_OutputArguments = 83; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestUnallocated_InputArguments Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNRequestUnallocated_InputArguments = 85; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestUnallocated_OutputArguments Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNRequestUnallocated_OutputArguments = 86; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestUnassigned_InputArguments Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNRequestUnassigned_InputArguments = 88; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestUnassigned_OutputArguments Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNRequestUnassigned_OutputArguments = 89; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNReturnAllocated_InputArguments Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNReturnAllocated_InputArguments = 91; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNReturnAllocated_OutputArguments Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNReturnAllocated_OutputArguments = 92; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNReturnUnallocated_InputArguments Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNReturnUnallocated_InputArguments = 94; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNReturnUnallocated_OutputArguments Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNReturnUnallocated_OutputArguments = 95; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoAllocated_InputArguments Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNtoAllocated_InputArguments = 97; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoAllocated_OutputArguments Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNtoAllocated_OutputArguments = 98; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoEncoded_InputArguments Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNtoEncoded_InputArguments = 100; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoEncoded_OutputArguments Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNtoEncoded_OutputArguments = 101; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoUnallocated_InputArguments Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNtoUnallocated_InputArguments = 103; /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoUnallocated_OutputArguments Variable. /// </summary> public const uint OPENSCSPoolManagerObjectType_SNtoUnallocated_OutputArguments = 104; /// <summary> /// The identifier for the OPENSCSSIDClassObjectType_AllowedCharacterSet Variable. /// </summary> public const uint OPENSCSSIDClassObjectType_AllowedCharacterSet = 106; /// <summary> /// The identifier for the OPENSCSSIDClassObjectType_IntendedUse Variable. /// </summary> public const uint OPENSCSSIDClassObjectType_IntendedUse = 107; /// <summary> /// The identifier for the OPENSCSSIDClassObjectType_SIDClassDescription Variable. /// </summary> public const uint OPENSCSSIDClassObjectType_SIDClassDescription = 108; /// <summary> /// The identifier for the OPENSCSSIDClassObjectType_SIDClassID Variable. /// </summary> public const uint OPENSCSSIDClassObjectType_SIDClassID = 109; /// <summary> /// The identifier for the OPENSCSSIDClassObjectType_SIDClassOwner Variable. /// </summary> public const uint OPENSCSSIDClassObjectType_SIDClassOwner = 110; /// <summary> /// The identifier for the OPENSCSSIDClassObjectType_SIDClassProperty Variable. /// </summary> public const uint OPENSCSSIDClassObjectType_SIDClassProperty = 111; /// <summary> /// The identifier for the OPENSCSSIDClassObjectType_SyntaxSpecification Variable. /// </summary> public const uint OPENSCSSIDClassObjectType_SyntaxSpecification = 112; /// <summary> /// The identifier for the Name2_XmlSchema Variable. /// </summary> public const uint Name2_XmlSchema = 122; /// <summary> /// The identifier for the Name2_XmlSchema_NamespaceUri Variable. /// </summary> public const uint Name2_XmlSchema_NamespaceUri = 124; /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSAggregationDataType Variable. /// </summary> public const uint Name2_XmlSchema_OPENSCSAggregationDataType = 125; /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSCollectionDataType Variable. /// </summary> public const uint Name2_XmlSchema_OPENSCSCollectionDataType = 128; /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSLabelCollectionDataType Variable. /// </summary> public const uint Name2_XmlSchema_OPENSCSLabelCollectionDataType = 131; /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSSNCollectionDataType Variable. /// </summary> public const uint Name2_XmlSchema_OPENSCSSNCollectionDataType = 134; /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSEventStreamArgumentDataType Variable. /// </summary> public const uint Name2_XmlSchema_OPENSCSEventStreamArgumentDataType = 137; /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSKeyValueDataType Variable. /// </summary> public const uint Name2_XmlSchema_OPENSCSKeyValueDataType = 140; /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSLabelDataType Variable. /// </summary> public const uint Name2_XmlSchema_OPENSCSLabelDataType = 143; /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSLabelPropertyDataType Variable. /// </summary> public const uint Name2_XmlSchema_OPENSCSLabelPropertyDataType = 146; /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSSIDClassPropertyDataType Variable. /// </summary> public const uint Name2_XmlSchema_OPENSCSSIDClassPropertyDataType = 149; /// <summary> /// The identifier for the Name2_BinarySchema Variable. /// </summary> public const uint Name2_BinarySchema = 161; /// <summary> /// The identifier for the Name2_BinarySchema_NamespaceUri Variable. /// </summary> public const uint Name2_BinarySchema_NamespaceUri = 163; /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSAggregationDataType Variable. /// </summary> public const uint Name2_BinarySchema_OPENSCSAggregationDataType = 164; /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSCollectionDataType Variable. /// </summary> public const uint Name2_BinarySchema_OPENSCSCollectionDataType = 167; /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSLabelCollectionDataType Variable. /// </summary> public const uint Name2_BinarySchema_OPENSCSLabelCollectionDataType = 170; /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSSNCollectionDataType Variable. /// </summary> public const uint Name2_BinarySchema_OPENSCSSNCollectionDataType = 173; /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSEventStreamArgumentDataType Variable. /// </summary> public const uint Name2_BinarySchema_OPENSCSEventStreamArgumentDataType = 176; /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSKeyValueDataType Variable. /// </summary> public const uint Name2_BinarySchema_OPENSCSKeyValueDataType = 179; /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSLabelDataType Variable. /// </summary> public const uint Name2_BinarySchema_OPENSCSLabelDataType = 182; /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSLabelPropertyDataType Variable. /// </summary> public const uint Name2_BinarySchema_OPENSCSLabelPropertyDataType = 185; /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSSIDClassPropertyDataType Variable. /// </summary> public const uint Name2_BinarySchema_OPENSCSSIDClassPropertyDataType = 188; } #endregion #region DataType Node Identifiers /// <summary> /// A class that declares constants for all DataTypes in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class DataTypeIds { /// <summary> /// The identifier for the JobOrderCommandEnum DataType. /// </summary> public static readonly ExpandedNodeId JobOrderCommandEnum = new ExpandedNodeId(Prefix2.DataTypes.JobOrderCommandEnum, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the JobOrderStateEnum DataType. /// </summary> public static readonly ExpandedNodeId JobOrderStateEnum = new ExpandedNodeId(Prefix2.DataTypes.JobOrderStateEnum, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSReturnEnum DataType. /// </summary> public static readonly ExpandedNodeId OPENSCSReturnEnum = new ExpandedNodeId(Prefix2.DataTypes.OPENSCSReturnEnum, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSerialNumberStateEnum DataType. /// </summary> public static readonly ExpandedNodeId OPENSCSSerialNumberStateEnum = new ExpandedNodeId(Prefix2.DataTypes.OPENSCSSerialNumberStateEnum, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSAggregationDataType DataType. /// </summary> public static readonly ExpandedNodeId OPENSCSAggregationDataType = new ExpandedNodeId(Prefix2.DataTypes.OPENSCSAggregationDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSCollectionDataType DataType. /// </summary> public static readonly ExpandedNodeId OPENSCSCollectionDataType = new ExpandedNodeId(Prefix2.DataTypes.OPENSCSCollectionDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSLabelCollectionDataType DataType. /// </summary> public static readonly ExpandedNodeId OPENSCSLabelCollectionDataType = new ExpandedNodeId(Prefix2.DataTypes.OPENSCSLabelCollectionDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSNCollectionDataType DataType. /// </summary> public static readonly ExpandedNodeId OPENSCSSNCollectionDataType = new ExpandedNodeId(Prefix2.DataTypes.OPENSCSSNCollectionDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventStreamArgumentDataType DataType. /// </summary> public static readonly ExpandedNodeId OPENSCSEventStreamArgumentDataType = new ExpandedNodeId(Prefix2.DataTypes.OPENSCSEventStreamArgumentDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSKeyValueDataType DataType. /// </summary> public static readonly ExpandedNodeId OPENSCSKeyValueDataType = new ExpandedNodeId(Prefix2.DataTypes.OPENSCSKeyValueDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSLabelDataType DataType. /// </summary> public static readonly ExpandedNodeId OPENSCSLabelDataType = new ExpandedNodeId(Prefix2.DataTypes.OPENSCSLabelDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSLabelPropertyDataType DataType. /// </summary> public static readonly ExpandedNodeId OPENSCSLabelPropertyDataType = new ExpandedNodeId(Prefix2.DataTypes.OPENSCSLabelPropertyDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSIDClassPropertyDataType DataType. /// </summary> public static readonly ExpandedNodeId OPENSCSSIDClassPropertyDataType = new ExpandedNodeId(Prefix2.DataTypes.OPENSCSSIDClassPropertyDataType, Prefix2.Namespaces.Name2); } #endregion #region Method Node Identifiers /// <summary> /// A class that declares constants for all Methods in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class MethodIds { /// <summary> /// The identifier for the OPENSCSAggregationManagerObjectType_AggregationPackingEvent Method. /// </summary> public static readonly ExpandedNodeId OPENSCSAggregationManagerObjectType_AggregationPackingEvent = new ExpandedNodeId(Prefix2.Methods.OPENSCSAggregationManagerObjectType_AggregationPackingEvent, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSAggregationManagerObjectType_AggregationUnpackingEvent Method. /// </summary> public static readonly ExpandedNodeId OPENSCSAggregationManagerObjectType_AggregationUnpackingEvent = new ExpandedNodeId(Prefix2.Methods.OPENSCSAggregationManagerObjectType_AggregationUnpackingEvent, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForRead Method. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForRead = new ExpandedNodeId(Prefix2.Methods.OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForRead, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForWrite Method. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForWrite = new ExpandedNodeId(Prefix2.Methods.OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForWrite, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_CloseAndCommit Method. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_EPCISStream_CloseAndCommit = new ExpandedNodeId(Prefix2.Methods.OPENSCSEventManagerObjectType_EPCISStream_CloseAndCommit, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsEncodingEvent Method. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_LabelsEncodingEvent = new ExpandedNodeId(Prefix2.Methods.OPENSCSEventManagerObjectType_LabelsEncodingEvent, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsInspectingEvent Method. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_LabelsInspectingEvent = new ExpandedNodeId(Prefix2.Methods.OPENSCSEventManagerObjectType_LabelsInspectingEvent, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsSamplingEvent Method. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_LabelsSamplingEvent = new ExpandedNodeId(Prefix2.Methods.OPENSCSEventManagerObjectType_LabelsSamplingEvent, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsScrappingEvent Method. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_LabelsScrappingEvent = new ExpandedNodeId(Prefix2.Methods.OPENSCSEventManagerObjectType_LabelsScrappingEvent, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDCommissioningEvent Method. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SIDCommissioningEvent = new ExpandedNodeId(Prefix2.Methods.OPENSCSEventManagerObjectType_SIDCommissioningEvent, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDDecommissioningEvent Method. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SIDDecommissioningEvent = new ExpandedNodeId(Prefix2.Methods.OPENSCSEventManagerObjectType_SIDDecommissioningEvent, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDDestroyingEvent Method. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SIDDestroyingEvent = new ExpandedNodeId(Prefix2.Methods.OPENSCSEventManagerObjectType_SIDDestroyingEvent, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDInspectingEvent Method. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SIDInspectingEvent = new ExpandedNodeId(Prefix2.Methods.OPENSCSEventManagerObjectType_SIDInspectingEvent, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDShippingEvent Method. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SIDShippingEvent = new ExpandedNodeId(Prefix2.Methods.OPENSCSEventManagerObjectType_SIDShippingEvent, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SNInvalidatingEvent Method. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SNInvalidatingEvent = new ExpandedNodeId(Prefix2.Methods.OPENSCSEventManagerObjectType_SNInvalidatingEvent, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestAllocated Method. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNRequestAllocated = new ExpandedNodeId(Prefix2.Methods.OPENSCSPoolManagerObjectType_SNRequestAllocated, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestUnallocated Method. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNRequestUnallocated = new ExpandedNodeId(Prefix2.Methods.OPENSCSPoolManagerObjectType_SNRequestUnallocated, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestUnassigned Method. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNRequestUnassigned = new ExpandedNodeId(Prefix2.Methods.OPENSCSPoolManagerObjectType_SNRequestUnassigned, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNReturnAllocated Method. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNReturnAllocated = new ExpandedNodeId(Prefix2.Methods.OPENSCSPoolManagerObjectType_SNReturnAllocated, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNReturnUnallocated Method. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNReturnUnallocated = new ExpandedNodeId(Prefix2.Methods.OPENSCSPoolManagerObjectType_SNReturnUnallocated, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoAllocated Method. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNtoAllocated = new ExpandedNodeId(Prefix2.Methods.OPENSCSPoolManagerObjectType_SNtoAllocated, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoEncoded Method. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNtoEncoded = new ExpandedNodeId(Prefix2.Methods.OPENSCSPoolManagerObjectType_SNtoEncoded, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoUnallocated Method. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNtoUnallocated = new ExpandedNodeId(Prefix2.Methods.OPENSCSPoolManagerObjectType_SNtoUnallocated, Prefix2.Namespaces.Name2); } #endregion #region Object Node Identifiers /// <summary> /// A class that declares constants for all Objects in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class ObjectIds { /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream Object. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_EPCISStream = new ExpandedNodeId(Prefix2.Objects.OPENSCSEventManagerObjectType_EPCISStream, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSAggregationDataType_Encoding_DefaultXml Object. /// </summary> public static readonly ExpandedNodeId OPENSCSAggregationDataType_Encoding_DefaultXml = new ExpandedNodeId(Prefix2.Objects.OPENSCSAggregationDataType_Encoding_DefaultXml, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSCollectionDataType_Encoding_DefaultXml Object. /// </summary> public static readonly ExpandedNodeId OPENSCSCollectionDataType_Encoding_DefaultXml = new ExpandedNodeId(Prefix2.Objects.OPENSCSCollectionDataType_Encoding_DefaultXml, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSLabelCollectionDataType_Encoding_DefaultXml Object. /// </summary> public static readonly ExpandedNodeId OPENSCSLabelCollectionDataType_Encoding_DefaultXml = new ExpandedNodeId(Prefix2.Objects.OPENSCSLabelCollectionDataType_Encoding_DefaultXml, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSNCollectionDataType_Encoding_DefaultXml Object. /// </summary> public static readonly ExpandedNodeId OPENSCSSNCollectionDataType_Encoding_DefaultXml = new ExpandedNodeId(Prefix2.Objects.OPENSCSSNCollectionDataType_Encoding_DefaultXml, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventStreamArgumentDataType_Encoding_DefaultXml Object. /// </summary> public static readonly ExpandedNodeId OPENSCSEventStreamArgumentDataType_Encoding_DefaultXml = new ExpandedNodeId(Prefix2.Objects.OPENSCSEventStreamArgumentDataType_Encoding_DefaultXml, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSKeyValueDataType_Encoding_DefaultXml Object. /// </summary> public static readonly ExpandedNodeId OPENSCSKeyValueDataType_Encoding_DefaultXml = new ExpandedNodeId(Prefix2.Objects.OPENSCSKeyValueDataType_Encoding_DefaultXml, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSLabelDataType_Encoding_DefaultXml Object. /// </summary> public static readonly ExpandedNodeId OPENSCSLabelDataType_Encoding_DefaultXml = new ExpandedNodeId(Prefix2.Objects.OPENSCSLabelDataType_Encoding_DefaultXml, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSLabelPropertyDataType_Encoding_DefaultXml Object. /// </summary> public static readonly ExpandedNodeId OPENSCSLabelPropertyDataType_Encoding_DefaultXml = new ExpandedNodeId(Prefix2.Objects.OPENSCSLabelPropertyDataType_Encoding_DefaultXml, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSIDClassPropertyDataType_Encoding_DefaultXml Object. /// </summary> public static readonly ExpandedNodeId OPENSCSSIDClassPropertyDataType_Encoding_DefaultXml = new ExpandedNodeId(Prefix2.Objects.OPENSCSSIDClassPropertyDataType_Encoding_DefaultXml, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSAggregationDataType_Encoding_DefaultBinary Object. /// </summary> public static readonly ExpandedNodeId OPENSCSAggregationDataType_Encoding_DefaultBinary = new ExpandedNodeId(Prefix2.Objects.OPENSCSAggregationDataType_Encoding_DefaultBinary, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSCollectionDataType_Encoding_DefaultBinary Object. /// </summary> public static readonly ExpandedNodeId OPENSCSCollectionDataType_Encoding_DefaultBinary = new ExpandedNodeId(Prefix2.Objects.OPENSCSCollectionDataType_Encoding_DefaultBinary, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSLabelCollectionDataType_Encoding_DefaultBinary Object. /// </summary> public static readonly ExpandedNodeId OPENSCSLabelCollectionDataType_Encoding_DefaultBinary = new ExpandedNodeId(Prefix2.Objects.OPENSCSLabelCollectionDataType_Encoding_DefaultBinary, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSNCollectionDataType_Encoding_DefaultBinary Object. /// </summary> public static readonly ExpandedNodeId OPENSCSSNCollectionDataType_Encoding_DefaultBinary = new ExpandedNodeId(Prefix2.Objects.OPENSCSSNCollectionDataType_Encoding_DefaultBinary, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventStreamArgumentDataType_Encoding_DefaultBinary Object. /// </summary> public static readonly ExpandedNodeId OPENSCSEventStreamArgumentDataType_Encoding_DefaultBinary = new ExpandedNodeId(Prefix2.Objects.OPENSCSEventStreamArgumentDataType_Encoding_DefaultBinary, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSKeyValueDataType_Encoding_DefaultBinary Object. /// </summary> public static readonly ExpandedNodeId OPENSCSKeyValueDataType_Encoding_DefaultBinary = new ExpandedNodeId(Prefix2.Objects.OPENSCSKeyValueDataType_Encoding_DefaultBinary, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSLabelDataType_Encoding_DefaultBinary Object. /// </summary> public static readonly ExpandedNodeId OPENSCSLabelDataType_Encoding_DefaultBinary = new ExpandedNodeId(Prefix2.Objects.OPENSCSLabelDataType_Encoding_DefaultBinary, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSLabelPropertyDataType_Encoding_DefaultBinary Object. /// </summary> public static readonly ExpandedNodeId OPENSCSLabelPropertyDataType_Encoding_DefaultBinary = new ExpandedNodeId(Prefix2.Objects.OPENSCSLabelPropertyDataType_Encoding_DefaultBinary, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSIDClassPropertyDataType_Encoding_DefaultBinary Object. /// </summary> public static readonly ExpandedNodeId OPENSCSSIDClassPropertyDataType_Encoding_DefaultBinary = new ExpandedNodeId(Prefix2.Objects.OPENSCSSIDClassPropertyDataType_Encoding_DefaultBinary, Prefix2.Namespaces.Name2); } #endregion #region ObjectType Node Identifiers /// <summary> /// A class that declares constants for all ObjectTypes in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class ObjectTypeIds { /// <summary> /// The identifier for the OPENSCSAggregationManagerObjectType ObjectType. /// </summary> public static readonly ExpandedNodeId OPENSCSAggregationManagerObjectType = new ExpandedNodeId(Prefix2.ObjectTypes.OPENSCSAggregationManagerObjectType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType ObjectType. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType = new ExpandedNodeId(Prefix2.ObjectTypes.OPENSCSEventManagerObjectType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType ObjectType. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType = new ExpandedNodeId(Prefix2.ObjectTypes.OPENSCSPoolManagerObjectType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSIDClassObjectType ObjectType. /// </summary> public static readonly ExpandedNodeId OPENSCSSIDClassObjectType = new ExpandedNodeId(Prefix2.ObjectTypes.OPENSCSSIDClassObjectType, Prefix2.Namespaces.Name2); } #endregion #region Variable Node Identifiers /// <summary> /// A class that declares constants for all Variables in the Model Design. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public static partial class VariableIds { /// <summary> /// The identifier for the JobOrderCommandEnum_EnumValues Variable. /// </summary> public static readonly ExpandedNodeId JobOrderCommandEnum_EnumValues = new ExpandedNodeId(Prefix2.Variables.JobOrderCommandEnum_EnumValues, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the JobOrderCommandEnum_EnumStrings Variable. /// </summary> public static readonly ExpandedNodeId JobOrderCommandEnum_EnumStrings = new ExpandedNodeId(Prefix2.Variables.JobOrderCommandEnum_EnumStrings, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the JobOrderStateEnum_EnumValues Variable. /// </summary> public static readonly ExpandedNodeId JobOrderStateEnum_EnumValues = new ExpandedNodeId(Prefix2.Variables.JobOrderStateEnum_EnumValues, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the JobOrderStateEnum_EnumStrings Variable. /// </summary> public static readonly ExpandedNodeId JobOrderStateEnum_EnumStrings = new ExpandedNodeId(Prefix2.Variables.JobOrderStateEnum_EnumStrings, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSReturnEnum_EnumValues Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSReturnEnum_EnumValues = new ExpandedNodeId(Prefix2.Variables.OPENSCSReturnEnum_EnumValues, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSReturnEnum_EnumStrings Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSReturnEnum_EnumStrings = new ExpandedNodeId(Prefix2.Variables.OPENSCSReturnEnum_EnumStrings, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSerialNumberStateEnum_EnumValues Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSSerialNumberStateEnum_EnumValues = new ExpandedNodeId(Prefix2.Variables.OPENSCSSerialNumberStateEnum_EnumValues, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSerialNumberStateEnum_EnumStrings Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSSerialNumberStateEnum_EnumStrings = new ExpandedNodeId(Prefix2.Variables.OPENSCSSerialNumberStateEnum_EnumStrings, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSAggregationManagerObjectType_AggregationPackingEvent_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSAggregationManagerObjectType_AggregationPackingEvent_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSAggregationManagerObjectType_AggregationPackingEvent_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSAggregationManagerObjectType_AggregationPackingEvent_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSAggregationManagerObjectType_AggregationPackingEvent_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSAggregationManagerObjectType_AggregationPackingEvent_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSAggregationManagerObjectType_AggregationUnpackingEvent_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSAggregationManagerObjectType_AggregationUnpackingEvent_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSAggregationManagerObjectType_AggregationUnpackingEvent_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSAggregationManagerObjectType_AggregationUnpackingEvent_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSAggregationManagerObjectType_AggregationUnpackingEvent_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSAggregationManagerObjectType_AggregationUnpackingEvent_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSAggregationManagerObjectType_MaxAggregationEvents Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSAggregationManagerObjectType_MaxAggregationEvents = new ExpandedNodeId(Prefix2.Variables.OPENSCSAggregationManagerObjectType_MaxAggregationEvents, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_ClientProcessingTimeout Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_EPCISStream_ClientProcessingTimeout = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_EPCISStream_ClientProcessingTimeout, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForRead_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForRead_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForRead_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForRead_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForRead_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForRead_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForWrite_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForWrite_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForWrite_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForWrite_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForWrite_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_EPCISStream_GenerateFileForWrite_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_CloseAndCommit_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_EPCISStream_CloseAndCommit_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_EPCISStream_CloseAndCommit_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_EPCISStream_CloseAndCommit_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_EPCISStream_CloseAndCommit_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_EPCISStream_CloseAndCommit_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsEncodingEvent_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_LabelsEncodingEvent_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_LabelsEncodingEvent_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsEncodingEvent_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_LabelsEncodingEvent_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_LabelsEncodingEvent_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsInspectingEvent_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_LabelsInspectingEvent_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_LabelsInspectingEvent_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsInspectingEvent_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_LabelsInspectingEvent_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_LabelsInspectingEvent_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsSamplingEvent_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_LabelsSamplingEvent_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_LabelsSamplingEvent_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsSamplingEvent_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_LabelsSamplingEvent_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_LabelsSamplingEvent_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsScrappingEvent_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_LabelsScrappingEvent_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_LabelsScrappingEvent_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_LabelsScrappingEvent_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_LabelsScrappingEvent_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_LabelsScrappingEvent_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_MaxEPCISaggregationEvents Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_MaxEPCISaggregationEvents = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_MaxEPCISaggregationEvents, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_MaxEPCISObjectEventSIDs Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_MaxEPCISObjectEventSIDs = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_MaxEPCISObjectEventSIDs, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_MaxEvents Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_MaxEvents = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_MaxEvents, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDCommissioningEvent_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SIDCommissioningEvent_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_SIDCommissioningEvent_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDCommissioningEvent_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SIDCommissioningEvent_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_SIDCommissioningEvent_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDDecommissioningEvent_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SIDDecommissioningEvent_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_SIDDecommissioningEvent_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDDecommissioningEvent_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SIDDecommissioningEvent_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_SIDDecommissioningEvent_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDDestroyingEvent_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SIDDestroyingEvent_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_SIDDestroyingEvent_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDDestroyingEvent_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SIDDestroyingEvent_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_SIDDestroyingEvent_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDInspectingEvent_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SIDInspectingEvent_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_SIDInspectingEvent_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDInspectingEvent_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SIDInspectingEvent_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_SIDInspectingEvent_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDShippingEvent_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SIDShippingEvent_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_SIDShippingEvent_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SIDShippingEvent_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SIDShippingEvent_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_SIDShippingEvent_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SNInvalidatingEvent_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SNInvalidatingEvent_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_SNInvalidatingEvent_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSEventManagerObjectType_SNInvalidatingEvent_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSEventManagerObjectType_SNInvalidatingEvent_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSEventManagerObjectType_SNInvalidatingEvent_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_MaxSNPushable Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_MaxSNPushable = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_MaxSNPushable, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_MaxSNRequestable Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_MaxSNRequestable = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_MaxSNRequestable, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_MaxSNReturnable Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_MaxSNReturnable = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_MaxSNReturnable, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_PoolSelectionCriteria Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_PoolSelectionCriteria = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_PoolSelectionCriteria, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNFormat Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNFormat = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNFormat, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestAllocated_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNRequestAllocated_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNRequestAllocated_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestAllocated_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNRequestAllocated_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNRequestAllocated_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestUnallocated_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNRequestUnallocated_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNRequestUnallocated_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestUnallocated_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNRequestUnallocated_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNRequestUnallocated_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestUnassigned_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNRequestUnassigned_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNRequestUnassigned_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNRequestUnassigned_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNRequestUnassigned_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNRequestUnassigned_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNReturnAllocated_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNReturnAllocated_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNReturnAllocated_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNReturnAllocated_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNReturnAllocated_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNReturnAllocated_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNReturnUnallocated_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNReturnUnallocated_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNReturnUnallocated_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNReturnUnallocated_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNReturnUnallocated_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNReturnUnallocated_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoAllocated_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNtoAllocated_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNtoAllocated_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoAllocated_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNtoAllocated_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNtoAllocated_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoEncoded_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNtoEncoded_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNtoEncoded_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoEncoded_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNtoEncoded_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNtoEncoded_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoUnallocated_InputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNtoUnallocated_InputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNtoUnallocated_InputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSPoolManagerObjectType_SNtoUnallocated_OutputArguments Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSPoolManagerObjectType_SNtoUnallocated_OutputArguments = new ExpandedNodeId(Prefix2.Variables.OPENSCSPoolManagerObjectType_SNtoUnallocated_OutputArguments, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSIDClassObjectType_AllowedCharacterSet Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSSIDClassObjectType_AllowedCharacterSet = new ExpandedNodeId(Prefix2.Variables.OPENSCSSIDClassObjectType_AllowedCharacterSet, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSIDClassObjectType_IntendedUse Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSSIDClassObjectType_IntendedUse = new ExpandedNodeId(Prefix2.Variables.OPENSCSSIDClassObjectType_IntendedUse, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSIDClassObjectType_SIDClassDescription Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSSIDClassObjectType_SIDClassDescription = new ExpandedNodeId(Prefix2.Variables.OPENSCSSIDClassObjectType_SIDClassDescription, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSIDClassObjectType_SIDClassID Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSSIDClassObjectType_SIDClassID = new ExpandedNodeId(Prefix2.Variables.OPENSCSSIDClassObjectType_SIDClassID, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSIDClassObjectType_SIDClassOwner Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSSIDClassObjectType_SIDClassOwner = new ExpandedNodeId(Prefix2.Variables.OPENSCSSIDClassObjectType_SIDClassOwner, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSIDClassObjectType_SIDClassProperty Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSSIDClassObjectType_SIDClassProperty = new ExpandedNodeId(Prefix2.Variables.OPENSCSSIDClassObjectType_SIDClassProperty, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the OPENSCSSIDClassObjectType_SyntaxSpecification Variable. /// </summary> public static readonly ExpandedNodeId OPENSCSSIDClassObjectType_SyntaxSpecification = new ExpandedNodeId(Prefix2.Variables.OPENSCSSIDClassObjectType_SyntaxSpecification, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_XmlSchema Variable. /// </summary> public static readonly ExpandedNodeId Name2_XmlSchema = new ExpandedNodeId(Prefix2.Variables.Name2_XmlSchema, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_XmlSchema_NamespaceUri Variable. /// </summary> public static readonly ExpandedNodeId Name2_XmlSchema_NamespaceUri = new ExpandedNodeId(Prefix2.Variables.Name2_XmlSchema_NamespaceUri, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSAggregationDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_XmlSchema_OPENSCSAggregationDataType = new ExpandedNodeId(Prefix2.Variables.Name2_XmlSchema_OPENSCSAggregationDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSCollectionDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_XmlSchema_OPENSCSCollectionDataType = new ExpandedNodeId(Prefix2.Variables.Name2_XmlSchema_OPENSCSCollectionDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSLabelCollectionDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_XmlSchema_OPENSCSLabelCollectionDataType = new ExpandedNodeId(Prefix2.Variables.Name2_XmlSchema_OPENSCSLabelCollectionDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSSNCollectionDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_XmlSchema_OPENSCSSNCollectionDataType = new ExpandedNodeId(Prefix2.Variables.Name2_XmlSchema_OPENSCSSNCollectionDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSEventStreamArgumentDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_XmlSchema_OPENSCSEventStreamArgumentDataType = new ExpandedNodeId(Prefix2.Variables.Name2_XmlSchema_OPENSCSEventStreamArgumentDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSKeyValueDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_XmlSchema_OPENSCSKeyValueDataType = new ExpandedNodeId(Prefix2.Variables.Name2_XmlSchema_OPENSCSKeyValueDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSLabelDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_XmlSchema_OPENSCSLabelDataType = new ExpandedNodeId(Prefix2.Variables.Name2_XmlSchema_OPENSCSLabelDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSLabelPropertyDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_XmlSchema_OPENSCSLabelPropertyDataType = new ExpandedNodeId(Prefix2.Variables.Name2_XmlSchema_OPENSCSLabelPropertyDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_XmlSchema_OPENSCSSIDClassPropertyDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_XmlSchema_OPENSCSSIDClassPropertyDataType = new ExpandedNodeId(Prefix2.Variables.Name2_XmlSchema_OPENSCSSIDClassPropertyDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_BinarySchema Variable. /// </summary> public static readonly ExpandedNodeId Name2_BinarySchema = new ExpandedNodeId(Prefix2.Variables.Name2_BinarySchema, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_BinarySchema_NamespaceUri Variable. /// </summary> public static readonly ExpandedNodeId Name2_BinarySchema_NamespaceUri = new ExpandedNodeId(Prefix2.Variables.Name2_BinarySchema_NamespaceUri, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSAggregationDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_BinarySchema_OPENSCSAggregationDataType = new ExpandedNodeId(Prefix2.Variables.Name2_BinarySchema_OPENSCSAggregationDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSCollectionDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_BinarySchema_OPENSCSCollectionDataType = new ExpandedNodeId(Prefix2.Variables.Name2_BinarySchema_OPENSCSCollectionDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSLabelCollectionDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_BinarySchema_OPENSCSLabelCollectionDataType = new ExpandedNodeId(Prefix2.Variables.Name2_BinarySchema_OPENSCSLabelCollectionDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSSNCollectionDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_BinarySchema_OPENSCSSNCollectionDataType = new ExpandedNodeId(Prefix2.Variables.Name2_BinarySchema_OPENSCSSNCollectionDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSEventStreamArgumentDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_BinarySchema_OPENSCSEventStreamArgumentDataType = new ExpandedNodeId(Prefix2.Variables.Name2_BinarySchema_OPENSCSEventStreamArgumentDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSKeyValueDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_BinarySchema_OPENSCSKeyValueDataType = new ExpandedNodeId(Prefix2.Variables.Name2_BinarySchema_OPENSCSKeyValueDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSLabelDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_BinarySchema_OPENSCSLabelDataType = new ExpandedNodeId(Prefix2.Variables.Name2_BinarySchema_OPENSCSLabelDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSLabelPropertyDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_BinarySchema_OPENSCSLabelPropertyDataType = new ExpandedNodeId(Prefix2.Variables.Name2_BinarySchema_OPENSCSLabelPropertyDataType, Prefix2.Namespaces.Name2); /// <summary> /// The identifier for the Name2_BinarySchema_OPENSCSSIDClassPropertyDataType Variable. /// </summary> public static readonly ExpandedNodeId Name2_BinarySchema_OPENSCSSIDClassPropertyDataType = new ExpandedNodeId(Prefix2.Variables.Name2_BinarySchema_OPENSCSSIDClassPropertyDataType, Prefix2.Namespaces.Name2); } #endregion #region BrowseName Declarations /// <summary> /// Declares all of the BrowseNames used in the Model Design. /// </summary> public static partial class BrowseNames { /// <summary> /// The BrowseName for the AggregationPackingEvent component. /// </summary> public const string AggregationPackingEvent = "AggregationPackingEvent"; /// <summary> /// The BrowseName for the AggregationUnpackingEvent component. /// </summary> public const string AggregationUnpackingEvent = "AggregationUnpackingEvent"; /// <summary> /// The BrowseName for the AllowedCharacterSet component. /// </summary> public const string AllowedCharacterSet = "AllowedCharacterSet"; /// <summary> /// The BrowseName for the EPCISStream component. /// </summary> public const string EPCISStream = "EPCISStream"; /// <summary> /// The BrowseName for the IntendedUse component. /// </summary> public const string IntendedUse = "IntendedUse"; /// <summary> /// The BrowseName for the JobOrderCommandEnum component. /// </summary> public const string JobOrderCommandEnum = "JobOrderCommandEnum"; /// <summary> /// The BrowseName for the JobOrderStateEnum component. /// </summary> public const string JobOrderStateEnum = "JobOrderStateEnum"; /// <summary> /// The BrowseName for the LabelsEncodingEvent component. /// </summary> public const string LabelsEncodingEvent = "LabelsEncodingEvent"; /// <summary> /// The BrowseName for the LabelsInspectingEvent component. /// </summary> public const string LabelsInspectingEvent = "LabelsInspectingEvent"; /// <summary> /// The BrowseName for the LabelsSamplingEvent component. /// </summary> public const string LabelsSamplingEvent = "LabelsSamplingEvent"; /// <summary> /// The BrowseName for the LabelsScrappingEvent component. /// </summary> public const string LabelsScrappingEvent = "LabelsScrappingEvent"; /// <summary> /// The BrowseName for the MaxAggregationEvents component. /// </summary> public const string MaxAggregationEvents = "MaxAggregationEvents"; /// <summary> /// The BrowseName for the MaxEPCISaggregationEvents component. /// </summary> public const string MaxEPCISaggregationEvents = "MaxEPCISaggregationEvents"; /// <summary> /// The BrowseName for the MaxEPCISObjectEventSIDs component. /// </summary> public const string MaxEPCISObjectEventSIDs = "MaxEPCISObjectEventSIDs"; /// <summary> /// The BrowseName for the MaxEvents component. /// </summary> public const string MaxEvents = "MaxEvents"; /// <summary> /// The BrowseName for the MaxSNPushable component. /// </summary> public const string MaxSNPushable = "MaxSNPushable"; /// <summary> /// The BrowseName for the MaxSNRequestable component. /// </summary> public const string MaxSNRequestable = "MaxSNRequestable"; /// <summary> /// The BrowseName for the MaxSNReturnable component. /// </summary> public const string MaxSNReturnable = "MaxSNReturnable"; /// <summary> /// The BrowseName for the Name2_BinarySchema component. /// </summary> public const string Name2_BinarySchema = "Prefix2"; /// <summary> /// The BrowseName for the Name2_XmlSchema component. /// </summary> public const string Name2_XmlSchema = "Prefix2"; /// <summary> /// The BrowseName for the OPENSCSAggregationDataType component. /// </summary> public const string OPENSCSAggregationDataType = "OPENSCSAggregationDataType"; /// <summary> /// The BrowseName for the OPENSCSAggregationManagerObjectType component. /// </summary> public const string OPENSCSAggregationManagerObjectType = "OPENSCSAggregationManagerObjectType"; /// <summary> /// The BrowseName for the OPENSCSCollectionDataType component. /// </summary> public const string OPENSCSCollectionDataType = "OPENSCSCollectionDataType"; /// <summary> /// The BrowseName for the OPENSCSEventManagerObjectType component. /// </summary> public const string OPENSCSEventManagerObjectType = "OPENSCSEventManagerObjectType"; /// <summary> /// The BrowseName for the OPENSCSEventStreamArgumentDataType component. /// </summary> public const string OPENSCSEventStreamArgumentDataType = "OPENSCSEventStreamArgumentDataType"; /// <summary> /// The BrowseName for the OPENSCSKeyValueDataType component. /// </summary> public const string OPENSCSKeyValueDataType = "OPENSCSKeyValueDataType"; /// <summary> /// The BrowseName for the OPENSCSLabelCollectionDataType component. /// </summary> public const string OPENSCSLabelCollectionDataType = "OPENSCSLabelCollectionDataType"; /// <summary> /// The BrowseName for the OPENSCSLabelDataType component. /// </summary> public const string OPENSCSLabelDataType = "OPENSCSLabelDataType"; /// <summary> /// The BrowseName for the OPENSCSLabelPropertyDataType component. /// </summary> public const string OPENSCSLabelPropertyDataType = "OPENSCSLabelPropertyDataType"; /// <summary> /// The BrowseName for the OPENSCSPoolManagerObjectType component. /// </summary> public const string OPENSCSPoolManagerObjectType = "OPENSCSPoolManagerObjectType"; /// <summary> /// The BrowseName for the OPENSCSReturnEnum component. /// </summary> public const string OPENSCSReturnEnum = "OPENSCSReturnEnum"; /// <summary> /// The BrowseName for the OPENSCSSerialNumberStateEnum component. /// </summary> public const string OPENSCSSerialNumberStateEnum = "OPENSCSSerialNumberStateEnum"; /// <summary> /// The BrowseName for the OPENSCSSIDClassObjectType component. /// </summary> public const string OPENSCSSIDClassObjectType = "OPENSCSSIDClassObjectType"; /// <summary> /// The BrowseName for the OPENSCSSIDClassPropertyDataType component. /// </summary> public const string OPENSCSSIDClassPropertyDataType = "OPENSCSSIDClassPropertyDataType"; /// <summary> /// The BrowseName for the OPENSCSSNCollectionDataType component. /// </summary> public const string OPENSCSSNCollectionDataType = "OPENSCSSNCollectionDataType"; /// <summary> /// The BrowseName for the PoolSelectionCriteria component. /// </summary> public const string PoolSelectionCriteria = "PoolSelectionCriteria"; /// <summary> /// The BrowseName for the SIDClassDescription component. /// </summary> public const string SIDClassDescription = "SIDClassDescription"; /// <summary> /// The BrowseName for the SIDClassID component. /// </summary> public const string SIDClassID = "SIDClassID"; /// <summary> /// The BrowseName for the SIDClassOwner component. /// </summary> public const string SIDClassOwner = "SIDClassOwner"; /// <summary> /// The BrowseName for the SIDClassProperty component. /// </summary> public const string SIDClassProperty = "SIDClassProperty"; /// <summary> /// The BrowseName for the SIDCommissioningEvent component. /// </summary> public const string SIDCommissioningEvent = "SIDCommissioningEvent"; /// <summary> /// The BrowseName for the SIDDecommissioningEvent component. /// </summary> public const string SIDDecommissioningEvent = "SIDDecommissioningEvent"; /// <summary> /// The BrowseName for the SIDDestroyingEvent component. /// </summary> public const string SIDDestroyingEvent = "SIDDestroyingEvent"; /// <summary> /// The BrowseName for the SIDInspectingEvent component. /// </summary> public const string SIDInspectingEvent = "SIDInspectingEvent"; /// <summary> /// The BrowseName for the SIDShippingEvent component. /// </summary> public const string SIDShippingEvent = "SIDShippingEvent"; /// <summary> /// The BrowseName for the SNFormat component. /// </summary> public const string SNFormat = "SNFormat"; /// <summary> /// The BrowseName for the SNInvalidatingEvent component. /// </summary> public const string SNInvalidatingEvent = "SNInvalidatingEvent"; /// <summary> /// The BrowseName for the SNRequestAllocated component. /// </summary> public const string SNRequestAllocated = "SNRequestAllocated"; /// <summary> /// The BrowseName for the SNRequestUnallocated component. /// </summary> public const string SNRequestUnallocated = "SNRequestUnallocated"; /// <summary> /// The BrowseName for the SNRequestUnassigned component. /// </summary> public const string SNRequestUnassigned = "SNRequestUnassigned"; /// <summary> /// The BrowseName for the SNReturnAllocated component. /// </summary> public const string SNReturnAllocated = "SNReturnAllocated"; /// <summary> /// The BrowseName for the SNReturnUnallocated component. /// </summary> public const string SNReturnUnallocated = "SNReturnUnallocated"; /// <summary> /// The BrowseName for the SNtoAllocated component. /// </summary> public const string SNtoAllocated = "SNtoAllocated"; /// <summary> /// The BrowseName for the SNtoEncoded component. /// </summary> public const string SNtoEncoded = "SNtoEncoded"; /// <summary> /// The BrowseName for the SNtoUnallocated component. /// </summary> public const string SNtoUnallocated = "SNtoUnallocated"; /// <summary> /// The BrowseName for the SyntaxSpecification component. /// </summary> public const string SyntaxSpecification = "SyntaxSpecification"; } #endregion #region Namespace Declarations /// <summary> /// Defines constants for all namespaces referenced by the model design. /// </summary> public static partial class Namespaces { /// <summary> /// The URI for the Name0Xsd namespace (.NET code namespace is 'Prefix0'). /// </summary> public const string Name0Xsd = "http://opcfoundation.org/UA/"; /// <summary> /// The URI for the Name0Xsd namespace (.NET code namespace is 'Prefix0'). /// </summary> public const string Name0Xsd = "http://opcfoundation.org/UA/"; /// <summary> /// The URI for the Name2Xsd namespace (.NET code namespace is 'Prefix2'). /// </summary> public const string Name2Xsd = "http://opcfoundation.org/UA/OPENSCS-SER/"; /// <summary> /// The URI for the Name2Xsd namespace (.NET code namespace is 'Prefix2'). /// </summary> public const string Name2Xsd = "http://opcfoundation.org/UA/OPENSCS-SER/"; } #endregion #region JobOrderCommandEnum Enumeration #if (!OPCUA_EXCLUDE_JobOrderCommandEnum) /// <summary> /// Describes the possible job order commands. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [DataContract(Namespace = Prefix2.Namespaces.Name2Xsd)] public enum JobOrderCommandEnum { /// <summary> /// Undefined value, should never be seen. /// </summary> [EnumMember(Value = "Undefined_0")] Undefined_0 = 0, /// <summary> /// Command to store the job order in local storage, but not to start the order. /// </summary> [EnumMember(Value = "Store_1")] Store_1 = 1, /// <summary> /// Command to store the job order and start it as soon as the Job Order receiver is ready to start. /// </summary> [EnumMember(Value = "StoreAndStart_2")] StoreAndStart_2 = 2, /// <summary> /// Command to start a stored job order as soon as the receiver is ready to start. Only the Job Orders ID is used to identify the stored job order, all other information is not used. No changes are made to the stored order. If multiple Job Orders have been commanded to Start, then the priority and timing values in the Job Orders shall be used to determine the order of execution of the orders. /// </summary> [EnumMember(Value = "Start_3")] Start_3 = 3, /// <summary> /// Command to update a stored Job Order that has not yet been started, with the new order information. All previously stored information is replaced. /// </summary> [EnumMember(Value = "Update_4")] Update_4 = 4, /// <summary> /// Command to stop a started job order, report on any work done on the order, and remove the stored information. Only the Job Orders ID is used to identify the job order, all other information is not used. /// </summary> [EnumMember(Value = "Stop_5")] Stop_5 = 5, /// <summary> /// Cancel an un-started job order and remove the stored information. Only the Job Orders ID is used to identify the job order, all other information is not used. /// </summary> [EnumMember(Value = "Cancel_6")] Cancel_6 = 6, /// <summary> /// Command to allow the Information Receiver to clear any maintained information on the Job Order (usually sent after a receipt of a Job Response with a status of Finished.) Only the Job Orders ID is used to identify the job order, all other information is not used. /// </summary> [EnumMember(Value = "Clear_7")] Clear_7 = 7, } #region JobOrderCommandEnumCollection Class /// <summary> /// A collection of JobOrderCommandEnum objects. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfJobOrderCommandEnum", Namespace = Prefix2.Namespaces.Name2Xsd, ItemName = "JobOrderCommandEnum")] #if !NET_STANDARD public partial class JobOrderCommandEnumCollection : List<JobOrderCommandEnum>, ICloneable #else public partial class JobOrderCommandEnumCollection : List<JobOrderCommandEnum> #endif { #region Constructors /// <summary> /// Initializes the collection with default values. /// </summary> public JobOrderCommandEnumCollection() {} /// <summary> /// Initializes the collection with an initial capacity. /// </summary> public JobOrderCommandEnumCollection(int capacity) : base(capacity) {} /// <summary> /// Initializes the collection with another collection. /// </summary> public JobOrderCommandEnumCollection(IEnumerable<JobOrderCommandEnum> collection) : base(collection) {} #endregion #region Static Operators /// <summary> /// Converts an array to a collection. /// </summary> public static implicit operator JobOrderCommandEnumCollection(JobOrderCommandEnum[] values) { if (values != null) { return new JobOrderCommandEnumCollection(values); } return new JobOrderCommandEnumCollection(); } /// <summary> /// Converts a collection to an array. /// </summary> public static explicit operator JobOrderCommandEnum[](JobOrderCommandEnumCollection values) { if (values != null) { return values.ToArray(); } return null; } #endregion #if !NET_STANDARD #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> public object Clone() { return (JobOrderCommandEnumCollection)this.MemberwiseClone(); } #endregion #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { JobOrderCommandEnumCollection clone = new JobOrderCommandEnumCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((JobOrderCommandEnum)Utils.Clone(this[ii])); } return clone; } } #endregion #endif #endregion #region JobOrderStateEnum Enumeration #if (!OPCUA_EXCLUDE_JobOrderStateEnum) /// <summary> /// Describes the possible serial number statesjob order states. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [DataContract(Namespace = Prefix2.Namespaces.Name2Xsd)] public enum JobOrderStateEnum { /// <summary> /// defined value, should never be seen. /// </summary> [EnumMember(Value = "Undefined_0")] Undefined_0 = 0, /// <summary> /// The necessary pre-conditions have not been met and the order is not ready to run. /// </summary> [EnumMember(Value = "Waiting_1")] Waiting_1 = 1, /// <summary> /// The necessary pre-conditions have been met and the order is ready to run, awaiting a Start command. /// </summary> [EnumMember(Value = "Ready_2")] Ready_2 = 2, /// <summary> /// In situations where only one job may be in active memory and is able to be run, then the job is loaded in active memory, the necessary pre-conditions have been met, and the order is ready to run, awaiting a Start command. /// </summary> [EnumMember(Value = "Loaded_3")] Loaded_3 = 3, /// <summary> /// The order is executing. /// </summary> [EnumMember(Value = "Running_4")] Running_4 = 4, /// <summary> /// The order has been completed and are no longer in execution. /// </summary> [EnumMember(Value = "Completed_5")] Completed_5 = 5, /// <summary> /// The order was aborted. /// </summary> [EnumMember(Value = "Aborted_6")] Aborted_6 = 6, /// <summary> /// The order has been temporarily stopped due to a constraint of some form. /// </summary> [EnumMember(Value = "Held_7")] Held_7 = 7, /// <summary> /// The order has been temporarily stopped due to a deliberate decision within the execution system. /// </summary> [EnumMember(Value = "Suspended_8")] Suspended_8 = 8, /// <summary> /// The order has been completed and fully reconciled. No further changes, or restatement of actuals is expected. /// </summary> [EnumMember(Value = "Closed_9")] Closed_9 = 9, } #region JobOrderStateEnumCollection Class /// <summary> /// A collection of JobOrderStateEnum objects. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfJobOrderStateEnum", Namespace = Prefix2.Namespaces.Name2Xsd, ItemName = "JobOrderStateEnum")] #if !NET_STANDARD public partial class JobOrderStateEnumCollection : List<JobOrderStateEnum>, ICloneable #else public partial class JobOrderStateEnumCollection : List<JobOrderStateEnum> #endif { #region Constructors /// <summary> /// Initializes the collection with default values. /// </summary> public JobOrderStateEnumCollection() {} /// <summary> /// Initializes the collection with an initial capacity. /// </summary> public JobOrderStateEnumCollection(int capacity) : base(capacity) {} /// <summary> /// Initializes the collection with another collection. /// </summary> public JobOrderStateEnumCollection(IEnumerable<JobOrderStateEnum> collection) : base(collection) {} #endregion #region Static Operators /// <summary> /// Converts an array to a collection. /// </summary> public static implicit operator JobOrderStateEnumCollection(JobOrderStateEnum[] values) { if (values != null) { return new JobOrderStateEnumCollection(values); } return new JobOrderStateEnumCollection(); } /// <summary> /// Converts a collection to an array. /// </summary> public static explicit operator JobOrderStateEnum[](JobOrderStateEnumCollection values) { if (values != null) { return values.ToArray(); } return null; } #endregion #if !NET_STANDARD #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> public object Clone() { return (JobOrderStateEnumCollection)this.MemberwiseClone(); } #endregion #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { JobOrderStateEnumCollection clone = new JobOrderStateEnumCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((JobOrderStateEnum)Utils.Clone(this[ii])); } return clone; } } #endregion #endif #endregion #region OPENSCSReturnEnum Enumeration #if (!OPCUA_EXCLUDE_OPENSCSReturnEnum) /// <summary> /// A description for the OPENSCSReturnEnum DataType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [DataContract(Namespace = Prefix2.Namespaces.Name2Xsd)] public enum OPENSCSReturnEnum { /// <summary> /// Undefined value, should never be seen. /// </summary> [EnumMember(Value = "Undefined0_0")] Undefined0 = 0, /// <summary> /// There were no errors in processing the method. /// </summary> [EnumMember(Value = "NoError1_1")] NoError1 = 1, /// <summary> /// The Serial Number Collection ID does not match a Serial Number Collection managed by the server. /// </summary> [EnumMember(Value = "InvalidSerialNumberCollection2_2")] InvalidSerialNumberCollection2 = 2, /// <summary> /// Fewer Serial Numbers are available from the pool, then are requested. /// </summary> [EnumMember(Value = "InsufficientSerialNumbers3_3")] InsufficientSerialNumbers3 = 3, /// <summary> /// The serial number format is not known or defined in the server /// </summary> [EnumMember(Value = "InvalidSerialNumbersFormat4_4")] InvalidSerialNumbersFormat4 = 4, /// <summary> /// The Request Token has a value not understood by the server. /// </summary> [EnumMember(Value = "InvalidRequestToken5_5")] InvalidRequestToken5 = 5, /// <summary> /// The Selection Criteria is not known or defined in the server. /// </summary> [EnumMember(Value = "InvalidSelectionCriteria6_6")] InvalidSelectionCriteria6 = 6, /// <summary> /// The server cannot accept Serial Number events. /// </summary> [EnumMember(Value = "UnableToAcceptSerialNumberEvents7_7")] UnableToAcceptSerialNumberEvents7 = 7, /// <summary> /// The server cannot accept Label events. /// </summary> [EnumMember(Value = "UnableToAcceptLabelEvents8_8")] UnableToAcceptLabelEvents8 = 8, /// <summary> /// The server cannot accept SID events. /// </summary> [EnumMember(Value = "UnableToAcceptSIDEvents9_9")] UnableToAcceptSIDEvents9 = 9, /// <summary> /// The SID of the aggregation for packing or unpacking is unknown. /// </summary> [EnumMember(Value = "UnknownAggregationSID10_10")] UnknownAggregationSID10 = 10, /// <summary> /// The server has determined that the client does not have sufficient privilege for the method to execute. /// </summary> [EnumMember(Value = "InsufficientPrivilegeToExecute11_11")] InsufficientPrivilegeToExecute11 = 11, } #region OPENSCSReturnEnumCollection Class /// <summary> /// A collection of OPENSCSReturnEnum objects. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfOPENSCSReturnEnum", Namespace = Prefix2.Namespaces.Name2Xsd, ItemName = "OPENSCSReturnEnum")] #if !NET_STANDARD public partial class OPENSCSReturnEnumCollection : List<OPENSCSReturnEnum>, ICloneable #else public partial class OPENSCSReturnEnumCollection : List<OPENSCSReturnEnum> #endif { #region Constructors /// <summary> /// Initializes the collection with default values. /// </summary> public OPENSCSReturnEnumCollection() {} /// <summary> /// Initializes the collection with an initial capacity. /// </summary> public OPENSCSReturnEnumCollection(int capacity) : base(capacity) {} /// <summary> /// Initializes the collection with another collection. /// </summary> public OPENSCSReturnEnumCollection(IEnumerable<OPENSCSReturnEnum> collection) : base(collection) {} #endregion #region Static Operators /// <summary> /// Converts an array to a collection. /// </summary> public static implicit operator OPENSCSReturnEnumCollection(OPENSCSReturnEnum[] values) { if (values != null) { return new OPENSCSReturnEnumCollection(values); } return new OPENSCSReturnEnumCollection(); } /// <summary> /// Converts a collection to an array. /// </summary> public static explicit operator OPENSCSReturnEnum[](OPENSCSReturnEnumCollection values) { if (values != null) { return values.ToArray(); } return null; } #endregion #if !NET_STANDARD #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> public object Clone() { return (OPENSCSReturnEnumCollection)this.MemberwiseClone(); } #endregion #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSReturnEnumCollection clone = new OPENSCSReturnEnumCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((OPENSCSReturnEnum)Utils.Clone(this[ii])); } return clone; } } #endregion #endif #endregion #region OPENSCSSerialNumberStateEnum Enumeration #if (!OPCUA_EXCLUDE_OPENSCSSerialNumberStateEnum) /// <summary> /// A description for the OPENSCSSerialNumberStateEnum DataType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [DataContract(Namespace = Prefix2.Namespaces.Name2Xsd)] public enum OPENSCSSerialNumberStateEnum { /// <summary> /// The Serial Number has not been assigned to production or a packaging run. /// </summary> [EnumMember(Value = "Unassigned0_0")] Unassigned0 = 0, /// <summary> /// As Serial Number has been assigned to production or a packaging run, but it has not yet been allocated for use a specific production run of a product or aggregation. /// </summary> [EnumMember(Value = "Unallocated1_1")] Unallocated1 = 1, /// <summary> /// The Serial Number has been assigned to a specific product or aggregation production run. /// </summary> [EnumMember(Value = "Allocated2_2")] Allocated2 = 2, /// <summary> /// The Serial Number is no longer viable, and the related serial number is no longer defined. /// </summary> [EnumMember(Value = "SNInvalid3_3")] SNInvalid3 = 3, /// <summary> /// The Serial Number has been written to a barcode or RFID tag, but not yet commissioned. /// </summary> [EnumMember(Value = "Encoded4_4")] Encoded4 = 4, /// <summary> /// The printed label has been retained and is not associated with a physical product or aggregation. /// </summary> [EnumMember(Value = "LabelSampled5_5")] LabelSampled5 = 5, /// <summary> /// A label was encoded with a Serial Number, but was made unusable before being applied to a product or aggregation. /// </summary> [EnumMember(Value = "LabelScrapped6_6")] LabelScrapped6 = 6, /// <summary> /// The Serial Number has been associated with a physical product or aggregation, but has not yet left the responsibility of production /// </summary> [EnumMember(Value = "Commissioned7_7")] Commissioned7 = 7, /// <summary> /// The product or aggregation is to be used as a sample for testing or other use, not to be made active. /// </summary> [EnumMember(Value = "Sampled8_8")] Sampled8 = 8, /// <summary> /// The product or aggregation is no longer active, but may not have been destroyed. /// </summary> [EnumMember(Value = "Inactive9_9")] Inactive9 = 9, /// <summary> /// The product or aggregation was has been fully rendered non-usable. /// </summary> [EnumMember(Value = "Destroyed10_10")] Destroyed10 = 10, /// <summary> /// The Serial Number has been associated with a physical product or aggregation, and has left the responsibility of production. /// </summary> [EnumMember(Value = "Released11_11")] Released11 = 11, } #region OPENSCSSerialNumberStateEnumCollection Class /// <summary> /// A collection of OPENSCSSerialNumberStateEnum objects. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfOPENSCSSerialNumberStateEnum", Namespace = Prefix2.Namespaces.Name2Xsd, ItemName = "OPENSCSSerialNumberStateEnum")] #if !NET_STANDARD public partial class OPENSCSSerialNumberStateEnumCollection : List<OPENSCSSerialNumberStateEnum>, ICloneable #else public partial class OPENSCSSerialNumberStateEnumCollection : List<OPENSCSSerialNumberStateEnum> #endif { #region Constructors /// <summary> /// Initializes the collection with default values. /// </summary> public OPENSCSSerialNumberStateEnumCollection() {} /// <summary> /// Initializes the collection with an initial capacity. /// </summary> public OPENSCSSerialNumberStateEnumCollection(int capacity) : base(capacity) {} /// <summary> /// Initializes the collection with another collection. /// </summary> public OPENSCSSerialNumberStateEnumCollection(IEnumerable<OPENSCSSerialNumberStateEnum> collection) : base(collection) {} #endregion #region Static Operators /// <summary> /// Converts an array to a collection. /// </summary> public static implicit operator OPENSCSSerialNumberStateEnumCollection(OPENSCSSerialNumberStateEnum[] values) { if (values != null) { return new OPENSCSSerialNumberStateEnumCollection(values); } return new OPENSCSSerialNumberStateEnumCollection(); } /// <summary> /// Converts a collection to an array. /// </summary> public static explicit operator OPENSCSSerialNumberStateEnum[](OPENSCSSerialNumberStateEnumCollection values) { if (values != null) { return values.ToArray(); } return null; } #endregion #if !NET_STANDARD #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> public object Clone() { return (OPENSCSSerialNumberStateEnumCollection)this.MemberwiseClone(); } #endregion #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSSerialNumberStateEnumCollection clone = new OPENSCSSerialNumberStateEnumCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((OPENSCSSerialNumberStateEnum)Utils.Clone(this[ii])); } return clone; } } #endregion #endif #endregion #region OPENSCSAggregationDataType Class #if (!OPCUA_EXCLUDE_OPENSCSAggregationDataType) /// <summary> /// Iidentifies a parent element and a collection of packed elements. This is used in the aggregation packing and unpacking methods. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [DataContract(Namespace = Prefix2.Namespaces.Name2Xsd)] public partial class OPENSCSAggregationDataType : IEncodeable { #region Constructors /// <summary> /// The default constructor. /// </summary> public OPENSCSAggregationDataType() { Initialize(); } /// <summary> /// Called by the .NET framework during deserialization. /// </summary> [OnDeserializing] private void Initialize(StreamingContext context) { Initialize(); } /// <summary> /// Sets private members to default values. /// </summary> private void Initialize() { m_parentElement = new OPENSCSLabelDataType(); m_parentElementCollection = new OPENSCSLabelCollectionDataType(); } #endregion #region Public Properties /// <summary> /// Identifies the single serial number representing the aggregation which acts as the parent /// </summary> [DataMember(Name = "ParentElement", IsRequired = false, Order = 1)] public OPENSCSLabelDataType ParentElement { get { return m_parentElement; } set { m_parentElement = value; if (value == null) { m_parentElement = new OPENSCSLabelDataType(); } } } /// <summary> /// Identifies the Serial Number Collection that was added to, or removed from, the parent element. /// </summary> [DataMember(Name = "ParentElementCollection", IsRequired = false, Order = 2)] public OPENSCSLabelCollectionDataType ParentElementCollection { get { return m_parentElementCollection; } set { m_parentElementCollection = value; if (value == null) { m_parentElementCollection = new OPENSCSLabelCollectionDataType(); } } } #endregion #region IEncodeable Members /// <summary cref="IEncodeable.TypeId" /> public virtual ExpandedNodeId TypeId { get { return DataTypeIds.OPENSCSAggregationDataType; } } /// <summary cref="IEncodeable.BinaryEncodingId" /> public virtual ExpandedNodeId BinaryEncodingId { get { return ObjectIds.OPENSCSAggregationDataType_Encoding_DefaultBinary; } } /// <summary cref="IEncodeable.XmlEncodingId" /> public virtual ExpandedNodeId XmlEncodingId { get { return ObjectIds.OPENSCSAggregationDataType_Encoding_DefaultXml; } } /// <summary cref="IEncodeable.Encode(IEncoder)" /> public virtual void Encode(IEncoder encoder) { encoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); encoder.WriteEncodeable("ParentElement", ParentElement, typeof(OPENSCSLabelDataType)); encoder.WriteEncodeable("ParentElementCollection", ParentElementCollection, typeof(OPENSCSLabelCollectionDataType)); encoder.PopNamespace(); } /// <summary cref="IEncodeable.Decode(IDecoder)" /> public virtual void Decode(IDecoder decoder) { decoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); ParentElement = (OPENSCSLabelDataType)decoder.ReadEncodeable("ParentElement", typeof(OPENSCSLabelDataType)); ParentElementCollection = (OPENSCSLabelCollectionDataType)decoder.ReadEncodeable("ParentElementCollection", typeof(OPENSCSLabelCollectionDataType)); decoder.PopNamespace(); } /// <summary cref="IEncodeable.IsEqual(IEncodeable)" /> public virtual bool IsEqual(IEncodeable encodeable) { if (Object.ReferenceEquals(this, encodeable)) { return true; } OPENSCSAggregationDataType value = encodeable as OPENSCSAggregationDataType; if (value == null) { return false; } if (!Utils.IsEqual(m_parentElement, value.m_parentElement)) return false; if (!Utils.IsEqual(m_parentElementCollection, value.m_parentElementCollection)) return false; return true; } #if !NET_STANDARD /// <summary cref="ICloneable.Clone" /> public virtual object Clone() { return (OPENSCSAggregationDataType)this.MemberwiseClone(); } #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSAggregationDataType clone = (OPENSCSAggregationDataType)base.MemberwiseClone(); clone.m_parentElement = (OPENSCSLabelDataType)Utils.Clone(this.m_parentElement); clone.m_parentElementCollection = (OPENSCSLabelCollectionDataType)Utils.Clone(this.m_parentElementCollection); return clone; } #endregion #region Private Fields private OPENSCSLabelDataType m_parentElement; private OPENSCSLabelCollectionDataType m_parentElementCollection; #endregion } #region OPENSCSAggregationDataTypeCollection Class /// <summary> /// A collection of OPENSCSAggregationDataType objects. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfOPENSCSAggregationDataType", Namespace = Prefix2.Namespaces.Name2Xsd, ItemName = "OPENSCSAggregationDataType")] #if !NET_STANDARD public partial class OPENSCSAggregationDataTypeCollection : List<OPENSCSAggregationDataType>, ICloneable #else public partial class OPENSCSAggregationDataTypeCollection : List<OPENSCSAggregationDataType> #endif { #region Constructors /// <summary> /// Initializes the collection with default values. /// </summary> public OPENSCSAggregationDataTypeCollection() {} /// <summary> /// Initializes the collection with an initial capacity. /// </summary> public OPENSCSAggregationDataTypeCollection(int capacity) : base(capacity) {} /// <summary> /// Initializes the collection with another collection. /// </summary> public OPENSCSAggregationDataTypeCollection(IEnumerable<OPENSCSAggregationDataType> collection) : base(collection) {} #endregion #region Static Operators /// <summary> /// Converts an array to a collection. /// </summary> public static implicit operator OPENSCSAggregationDataTypeCollection(OPENSCSAggregationDataType[] values) { if (values != null) { return new OPENSCSAggregationDataTypeCollection(values); } return new OPENSCSAggregationDataTypeCollection(); } /// <summary> /// Converts a collection to an array. /// </summary> public static explicit operator OPENSCSAggregationDataType[](OPENSCSAggregationDataTypeCollection values) { if (values != null) { return values.ToArray(); } return null; } #endregion #if !NET_STANDARD #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> public object Clone() { return (OPENSCSAggregationDataTypeCollection)this.MemberwiseClone(); } #endregion #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSAggregationDataTypeCollection clone = new OPENSCSAggregationDataTypeCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((OPENSCSAggregationDataType)Utils.Clone(this[ii])); } return clone; } } #endregion #endif #endregion #region OPENSCSCollectionDataType Class #if (!OPCUA_EXCLUDE_OPENSCSCollectionDataType) /// <summary> /// A description for the OPENSCSCollectionDataType DataType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [DataContract(Namespace = Prefix2.Namespaces.Name2Xsd)] public partial class OPENSCSCollectionDataType : IEncodeable { #region Constructors /// <summary> /// The default constructor. /// </summary> public OPENSCSCollectionDataType() { Initialize(); } /// <summary> /// Called by the .NET framework during deserialization. /// </summary> [OnDeserializing] private void Initialize(StreamingContext context) { Initialize(); } /// <summary> /// Sets private members to default values. /// </summary> private void Initialize() { m_ıD = null; m_description = null; m_state = OPENSCSSerialNumberStateEnum.Unassigned0; m_associatedPoolID = null; m_serialNumbers = new StringCollection(); } #endregion #region Public Properties /// <summary> /// An identification of the Collection. It usually refers to a specific packaging level of a specific product. /// </summary> [DataMember(Name = "ID", IsRequired = false, Order = 1)] public string ID { get { return m_ıD; } set { m_ıD = value; } } /// <summary> /// Additional information and description about the Collection. /// </summary> [DataMember(Name = "Description", IsRequired = false, Order = 2)] public string Description { get { return m_description; } set { m_description = value; } } /// <summary> /// State of the Serial Numbers in the Collection. /// </summary> [DataMember(Name = "State", IsRequired = false, Order = 3)] public OPENSCSSerialNumberStateEnum State { get { return m_state; } set { m_state = value; } } /// <summary> /// An identification of the Serial Number Pool from which the Serial Numbers were obtained. /// </summary> [DataMember(Name = "AssociatedPoolID", IsRequired = false, Order = 4)] public string AssociatedPoolID { get { return m_associatedPoolID; } set { m_associatedPoolID = value; } } /// <summary> /// Array of Serial Numbers in the collection. /// </summary> [DataMember(Name = "SerialNumbers", IsRequired = false, Order = 5)] public StringCollection SerialNumbers { get { return m_serialNumbers; } set { m_serialNumbers = value; if (value == null) { m_serialNumbers = new StringCollection(); } } } #endregion #region IEncodeable Members /// <summary cref="IEncodeable.TypeId" /> public virtual ExpandedNodeId TypeId { get { return DataTypeIds.OPENSCSCollectionDataType; } } /// <summary cref="IEncodeable.BinaryEncodingId" /> public virtual ExpandedNodeId BinaryEncodingId { get { return ObjectIds.OPENSCSCollectionDataType_Encoding_DefaultBinary; } } /// <summary cref="IEncodeable.XmlEncodingId" /> public virtual ExpandedNodeId XmlEncodingId { get { return ObjectIds.OPENSCSCollectionDataType_Encoding_DefaultXml; } } /// <summary cref="IEncodeable.Encode(IEncoder)" /> public virtual void Encode(IEncoder encoder) { encoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); encoder.WriteString("ID", ID); encoder.WriteString("Description", Description); encoder.WriteEnumerated("State", State); encoder.WriteString("AssociatedPoolID", AssociatedPoolID); encoder.WriteStringArray("SerialNumbers", SerialNumbers); encoder.PopNamespace(); } /// <summary cref="IEncodeable.Decode(IDecoder)" /> public virtual void Decode(IDecoder decoder) { decoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); ID = decoder.ReadString("ID"); Description = decoder.ReadString("Description"); State = (OPENSCSSerialNumberStateEnum)decoder.ReadEnumerated("State", typeof(OPENSCSSerialNumberStateEnum)); AssociatedPoolID = decoder.ReadString("AssociatedPoolID"); SerialNumbers = decoder.ReadStringArray("SerialNumbers"); decoder.PopNamespace(); } /// <summary cref="IEncodeable.IsEqual(IEncodeable)" /> public virtual bool IsEqual(IEncodeable encodeable) { if (Object.ReferenceEquals(this, encodeable)) { return true; } OPENSCSCollectionDataType value = encodeable as OPENSCSCollectionDataType; if (value == null) { return false; } if (!Utils.IsEqual(m_ıD, value.m_ıD)) return false; if (!Utils.IsEqual(m_description, value.m_description)) return false; if (!Utils.IsEqual(m_state, value.m_state)) return false; if (!Utils.IsEqual(m_associatedPoolID, value.m_associatedPoolID)) return false; if (!Utils.IsEqual(m_serialNumbers, value.m_serialNumbers)) return false; return true; } #if !NET_STANDARD /// <summary cref="ICloneable.Clone" /> public virtual object Clone() { return (OPENSCSCollectionDataType)this.MemberwiseClone(); } #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSCollectionDataType clone = (OPENSCSCollectionDataType)base.MemberwiseClone(); clone.m_ıD = (string)Utils.Clone(this.m_ıD); clone.m_description = (string)Utils.Clone(this.m_description); clone.m_state = (OPENSCSSerialNumberStateEnum)Utils.Clone(this.m_state); clone.m_associatedPoolID = (string)Utils.Clone(this.m_associatedPoolID); clone.m_serialNumbers = (StringCollection)Utils.Clone(this.m_serialNumbers); return clone; } #endregion #region Private Fields private string m_ıD; private string m_description; private OPENSCSSerialNumberStateEnum m_state; private string m_associatedPoolID; private StringCollection m_serialNumbers; #endregion } #region OPENSCSCollectionDataTypeCollection Class /// <summary> /// A collection of OPENSCSCollectionDataType objects. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfOPENSCSCollectionDataType", Namespace = Prefix2.Namespaces.Name2Xsd, ItemName = "OPENSCSCollectionDataType")] #if !NET_STANDARD public partial class OPENSCSCollectionDataTypeCollection : List<OPENSCSCollectionDataType>, ICloneable #else public partial class OPENSCSCollectionDataTypeCollection : List<OPENSCSCollectionDataType> #endif { #region Constructors /// <summary> /// Initializes the collection with default values. /// </summary> public OPENSCSCollectionDataTypeCollection() {} /// <summary> /// Initializes the collection with an initial capacity. /// </summary> public OPENSCSCollectionDataTypeCollection(int capacity) : base(capacity) {} /// <summary> /// Initializes the collection with another collection. /// </summary> public OPENSCSCollectionDataTypeCollection(IEnumerable<OPENSCSCollectionDataType> collection) : base(collection) {} #endregion #region Static Operators /// <summary> /// Converts an array to a collection. /// </summary> public static implicit operator OPENSCSCollectionDataTypeCollection(OPENSCSCollectionDataType[] values) { if (values != null) { return new OPENSCSCollectionDataTypeCollection(values); } return new OPENSCSCollectionDataTypeCollection(); } /// <summary> /// Converts a collection to an array. /// </summary> public static explicit operator OPENSCSCollectionDataType[](OPENSCSCollectionDataTypeCollection values) { if (values != null) { return values.ToArray(); } return null; } #endregion #if !NET_STANDARD #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> public object Clone() { return (OPENSCSCollectionDataTypeCollection)this.MemberwiseClone(); } #endregion #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSCollectionDataTypeCollection clone = new OPENSCSCollectionDataTypeCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((OPENSCSCollectionDataType)Utils.Clone(this[ii])); } return clone; } } #endregion #endif #endregion #region OPENSCSLabelCollectionDataType Class #if (!OPCUA_EXCLUDE_OPENSCSLabelCollectionDataType) /// <summary> /// A description for the OPENSCSLabelCollectionDataType DataType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [DataContract(Namespace = Prefix2.Namespaces.Name2Xsd)] public partial class OPENSCSLabelCollectionDataType : OPENSCSCollectionDataType { #region Constructors /// <summary> /// The default constructor. /// </summary> public OPENSCSLabelCollectionDataType() { Initialize(); } /// <summary> /// Called by the .NET framework during deserialization. /// </summary> [OnDeserializing] private void Initialize(StreamingContext context) { Initialize(); } /// <summary> /// Sets private members to default values. /// </summary> private void Initialize() { m_labelCollection = new OPENSCSLabelDataTypeCollection(); m_labelCollectionProperties = new OPENSCSKeyValueDataTypeCollection(); } #endregion #region Public Properties /// <summary> /// The collections of labels with serial numbers. /// </summary> [DataMember(Name = "LabelCollection", IsRequired = false, Order = 1)] public OPENSCSLabelDataTypeCollection LabelCollection { get { return m_labelCollection; } set { m_labelCollection = value; if (value == null) { m_labelCollection = new OPENSCSLabelDataTypeCollection(); } } } /// <summary> /// An optional array of additional properties in the form of Key/Value pairs which are valid for the whole collection. /// </summary> [DataMember(Name = "LabelCollectionProperties", IsRequired = false, Order = 2)] public OPENSCSKeyValueDataTypeCollection LabelCollectionProperties { get { return m_labelCollectionProperties; } set { m_labelCollectionProperties = value; if (value == null) { m_labelCollectionProperties = new OPENSCSKeyValueDataTypeCollection(); } } } #endregion #region IEncodeable Members /// <summary cref="IEncodeable.TypeId" /> public override ExpandedNodeId TypeId { get { return DataTypeIds.OPENSCSLabelCollectionDataType; } } /// <summary cref="IEncodeable.BinaryEncodingId" /> public override ExpandedNodeId BinaryEncodingId { get { return ObjectIds.OPENSCSLabelCollectionDataType_Encoding_DefaultBinary; } } /// <summary cref="IEncodeable.XmlEncodingId" /> public override ExpandedNodeId XmlEncodingId { get { return ObjectIds.OPENSCSLabelCollectionDataType_Encoding_DefaultXml; } } /// <summary cref="IEncodeable.Encode(IEncoder)" /> public override void Encode(IEncoder encoder) { base.Encode(encoder); encoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); encoder.WriteEncodeableArray("LabelCollection", LabelCollection.ToArray(), typeof(OPENSCSLabelDataType)); encoder.WriteEncodeableArray("LabelCollectionProperties", LabelCollectionProperties.ToArray(), typeof(OPENSCSKeyValueDataType)); encoder.PopNamespace(); } /// <summary cref="IEncodeable.Decode(IDecoder)" /> public override void Decode(IDecoder decoder) { base.Decode(decoder); decoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); LabelCollection = (OPENSCSLabelDataTypeCollection)decoder.ReadEncodeableArray("LabelCollection", typeof(OPENSCSLabelDataType)); LabelCollectionProperties = (OPENSCSKeyValueDataTypeCollection)decoder.ReadEncodeableArray("LabelCollectionProperties", typeof(OPENSCSKeyValueDataType)); decoder.PopNamespace(); } /// <summary cref="IEncodeable.IsEqual(IEncodeable)" /> public override bool IsEqual(IEncodeable encodeable) { if (Object.ReferenceEquals(this, encodeable)) { return true; } OPENSCSLabelCollectionDataType value = encodeable as OPENSCSLabelCollectionDataType; if (value == null) { return false; } if (!base.IsEqual(encodeable)) return false; if (!Utils.IsEqual(m_labelCollection, value.m_labelCollection)) return false; if (!Utils.IsEqual(m_labelCollectionProperties, value.m_labelCollectionProperties)) return false; return true; } #if !NET_STANDARD /// <summary cref="ICloneable.Clone" /> public override object Clone() { return (OPENSCSLabelCollectionDataType)this.MemberwiseClone(); } #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSLabelCollectionDataType clone = (OPENSCSLabelCollectionDataType)base.MemberwiseClone(); clone.m_labelCollection = (OPENSCSLabelDataTypeCollection)Utils.Clone(this.m_labelCollection); clone.m_labelCollectionProperties = (OPENSCSKeyValueDataTypeCollection)Utils.Clone(this.m_labelCollectionProperties); return clone; } #endregion #region Private Fields private OPENSCSLabelDataTypeCollection m_labelCollection; private OPENSCSKeyValueDataTypeCollection m_labelCollectionProperties; #endregion } #region OPENSCSLabelCollectionDataTypeCollection Class /// <summary> /// A collection of OPENSCSLabelCollectionDataType objects. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfOPENSCSLabelCollectionDataType", Namespace = Prefix2.Namespaces.Name2Xsd, ItemName = "OPENSCSLabelCollectionDataType")] #if !NET_STANDARD public partial class OPENSCSLabelCollectionDataTypeCollection : List<OPENSCSLabelCollectionDataType>, ICloneable #else public partial class OPENSCSLabelCollectionDataTypeCollection : List<OPENSCSLabelCollectionDataType> #endif { #region Constructors /// <summary> /// Initializes the collection with default values. /// </summary> public OPENSCSLabelCollectionDataTypeCollection() {} /// <summary> /// Initializes the collection with an initial capacity. /// </summary> public OPENSCSLabelCollectionDataTypeCollection(int capacity) : base(capacity) {} /// <summary> /// Initializes the collection with another collection. /// </summary> public OPENSCSLabelCollectionDataTypeCollection(IEnumerable<OPENSCSLabelCollectionDataType> collection) : base(collection) {} #endregion #region Static Operators /// <summary> /// Converts an array to a collection. /// </summary> public static implicit operator OPENSCSLabelCollectionDataTypeCollection(OPENSCSLabelCollectionDataType[] values) { if (values != null) { return new OPENSCSLabelCollectionDataTypeCollection(values); } return new OPENSCSLabelCollectionDataTypeCollection(); } /// <summary> /// Converts a collection to an array. /// </summary> public static explicit operator OPENSCSLabelCollectionDataType[](OPENSCSLabelCollectionDataTypeCollection values) { if (values != null) { return values.ToArray(); } return null; } #endregion #if !NET_STANDARD #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> public object Clone() { return (OPENSCSLabelCollectionDataTypeCollection)this.MemberwiseClone(); } #endregion #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSLabelCollectionDataTypeCollection clone = new OPENSCSLabelCollectionDataTypeCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((OPENSCSLabelCollectionDataType)Utils.Clone(this[ii])); } return clone; } } #endregion #endif #endregion #region OPENSCSSNCollectionDataType Class #if (!OPCUA_EXCLUDE_OPENSCSSNCollectionDataType) /// <summary> /// A description for the OPENSCSSNCollectionDataType DataType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [DataContract(Namespace = Prefix2.Namespaces.Name2Xsd)] public partial class OPENSCSSNCollectionDataType : OPENSCSCollectionDataType { #region Constructors /// <summary> /// The default constructor. /// </summary> public OPENSCSSNCollectionDataType() { Initialize(); } /// <summary> /// Called by the .NET framework during deserialization. /// </summary> [OnDeserializing] private void Initialize(StreamingContext context) { Initialize(); } /// <summary> /// Sets private members to default values. /// </summary> private void Initialize() { } #endregion #region Public Properties #endregion #region IEncodeable Members /// <summary cref="IEncodeable.TypeId" /> public override ExpandedNodeId TypeId { get { return DataTypeIds.OPENSCSSNCollectionDataType; } } /// <summary cref="IEncodeable.BinaryEncodingId" /> public override ExpandedNodeId BinaryEncodingId { get { return ObjectIds.OPENSCSSNCollectionDataType_Encoding_DefaultBinary; } } /// <summary cref="IEncodeable.XmlEncodingId" /> public override ExpandedNodeId XmlEncodingId { get { return ObjectIds.OPENSCSSNCollectionDataType_Encoding_DefaultXml; } } /// <summary cref="IEncodeable.Encode(IEncoder)" /> public override void Encode(IEncoder encoder) { base.Encode(encoder); encoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); encoder.PopNamespace(); } /// <summary cref="IEncodeable.Decode(IDecoder)" /> public override void Decode(IDecoder decoder) { base.Decode(decoder); decoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); decoder.PopNamespace(); } /// <summary cref="IEncodeable.IsEqual(IEncodeable)" /> public override bool IsEqual(IEncodeable encodeable) { if (Object.ReferenceEquals(this, encodeable)) { return true; } OPENSCSSNCollectionDataType value = encodeable as OPENSCSSNCollectionDataType; if (value == null) { return false; } return true; } #if !NET_STANDARD /// <summary cref="ICloneable.Clone" /> public override object Clone() { return (OPENSCSSNCollectionDataType)this.MemberwiseClone(); } #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSSNCollectionDataType clone = (OPENSCSSNCollectionDataType)base.MemberwiseClone(); return clone; } #endregion #region Private Fields #endregion } #region OPENSCSSNCollectionDataTypeCollection Class /// <summary> /// A collection of OPENSCSSNCollectionDataType objects. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfOPENSCSSNCollectionDataType", Namespace = Prefix2.Namespaces.Name2Xsd, ItemName = "OPENSCSSNCollectionDataType")] #if !NET_STANDARD public partial class OPENSCSSNCollectionDataTypeCollection : List<OPENSCSSNCollectionDataType>, ICloneable #else public partial class OPENSCSSNCollectionDataTypeCollection : List<OPENSCSSNCollectionDataType> #endif { #region Constructors /// <summary> /// Initializes the collection with default values. /// </summary> public OPENSCSSNCollectionDataTypeCollection() {} /// <summary> /// Initializes the collection with an initial capacity. /// </summary> public OPENSCSSNCollectionDataTypeCollection(int capacity) : base(capacity) {} /// <summary> /// Initializes the collection with another collection. /// </summary> public OPENSCSSNCollectionDataTypeCollection(IEnumerable<OPENSCSSNCollectionDataType> collection) : base(collection) {} #endregion #region Static Operators /// <summary> /// Converts an array to a collection. /// </summary> public static implicit operator OPENSCSSNCollectionDataTypeCollection(OPENSCSSNCollectionDataType[] values) { if (values != null) { return new OPENSCSSNCollectionDataTypeCollection(values); } return new OPENSCSSNCollectionDataTypeCollection(); } /// <summary> /// Converts a collection to an array. /// </summary> public static explicit operator OPENSCSSNCollectionDataType[](OPENSCSSNCollectionDataTypeCollection values) { if (values != null) { return values.ToArray(); } return null; } #endregion #if !NET_STANDARD #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> public object Clone() { return (OPENSCSSNCollectionDataTypeCollection)this.MemberwiseClone(); } #endregion #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSSNCollectionDataTypeCollection clone = new OPENSCSSNCollectionDataTypeCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((OPENSCSSNCollectionDataType)Utils.Clone(this[ii])); } return clone; } } #endregion #endif #endregion #region OPENSCSEventStreamArgumentDataType Class #if (!OPCUA_EXCLUDE_OPENSCSEventStreamArgumentDataType) /// <summary> /// Defines the generateOptions argument for an EPCISStream GenerateFileForWrite method. It defines the serial number format information for object events and for aggregation events, and event context information. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [DataContract(Namespace = Prefix2.Namespaces.Name2Xsd)] public partial class OPENSCSEventStreamArgumentDataType : IEncodeable { #region Constructors /// <summary> /// The default constructor. /// </summary> public OPENSCSEventStreamArgumentDataType() { Initialize(); } /// <summary> /// Called by the .NET framework during deserialization. /// </summary> [OnDeserializing] private void Initialize(StreamingContext context) { Initialize(); } /// <summary> /// Sets private members to default values. /// </summary> private void Initialize() { m_sNFormat = null; m_parentSNFormat = null; m_packedElementSNFormat = null; m_eventContext = new OPENSCSKeyValueDataTypeCollection(); } #endregion #region Public Properties /// <summary> /// The format for of serial numbers in object events, can be a null string if there are no object events in the transferred events. /// </summary> [DataMember(Name = "SNFormat", IsRequired = false, Order = 1)] public string SNFormat { get { return m_sNFormat; } set { m_sNFormat = value; } } /// <summary> /// The format for of parent serial numbers in aggregation events, can be a null string if there are no aggregation events in the transferred events. /// </summary> [DataMember(Name = "ParentSNFormat", IsRequired = false, Order = 2)] public string ParentSNFormat { get { return m_parentSNFormat; } set { m_parentSNFormat = value; } } /// <summary> /// The format for of packed element serial numbers in aggregation events, can be a null string if there are no aggregation events in the transferred events. /// </summary> [DataMember(Name = "PackedElementSNFormat", IsRequired = false, Order = 3)] public string PackedElementSNFormat { get { return m_packedElementSNFormat; } set { m_packedElementSNFormat = value; } } /// <summary> /// Zero or more key value pairs that define additional context information for the event, such as order number or lot number. /// </summary> [DataMember(Name = "EventContext", IsRequired = false, Order = 4)] public OPENSCSKeyValueDataTypeCollection EventContext { get { return m_eventContext; } set { m_eventContext = value; if (value == null) { m_eventContext = new OPENSCSKeyValueDataTypeCollection(); } } } #endregion #region IEncodeable Members /// <summary cref="IEncodeable.TypeId" /> public virtual ExpandedNodeId TypeId { get { return DataTypeIds.OPENSCSEventStreamArgumentDataType; } } /// <summary cref="IEncodeable.BinaryEncodingId" /> public virtual ExpandedNodeId BinaryEncodingId { get { return ObjectIds.OPENSCSEventStreamArgumentDataType_Encoding_DefaultBinary; } } /// <summary cref="IEncodeable.XmlEncodingId" /> public virtual ExpandedNodeId XmlEncodingId { get { return ObjectIds.OPENSCSEventStreamArgumentDataType_Encoding_DefaultXml; } } /// <summary cref="IEncodeable.Encode(IEncoder)" /> public virtual void Encode(IEncoder encoder) { encoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); encoder.WriteString("SNFormat", SNFormat); encoder.WriteString("ParentSNFormat", ParentSNFormat); encoder.WriteString("PackedElementSNFormat", PackedElementSNFormat); encoder.WriteEncodeableArray("EventContext", EventContext.ToArray(), typeof(OPENSCSKeyValueDataType)); encoder.PopNamespace(); } /// <summary cref="IEncodeable.Decode(IDecoder)" /> public virtual void Decode(IDecoder decoder) { decoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); SNFormat = decoder.ReadString("SNFormat"); ParentSNFormat = decoder.ReadString("ParentSNFormat"); PackedElementSNFormat = decoder.ReadString("PackedElementSNFormat"); EventContext = (OPENSCSKeyValueDataTypeCollection)decoder.ReadEncodeableArray("EventContext", typeof(OPENSCSKeyValueDataType)); decoder.PopNamespace(); } /// <summary cref="IEncodeable.IsEqual(IEncodeable)" /> public virtual bool IsEqual(IEncodeable encodeable) { if (Object.ReferenceEquals(this, encodeable)) { return true; } OPENSCSEventStreamArgumentDataType value = encodeable as OPENSCSEventStreamArgumentDataType; if (value == null) { return false; } if (!Utils.IsEqual(m_sNFormat, value.m_sNFormat)) return false; if (!Utils.IsEqual(m_parentSNFormat, value.m_parentSNFormat)) return false; if (!Utils.IsEqual(m_packedElementSNFormat, value.m_packedElementSNFormat)) return false; if (!Utils.IsEqual(m_eventContext, value.m_eventContext)) return false; return true; } #if !NET_STANDARD /// <summary cref="ICloneable.Clone" /> public virtual object Clone() { return (OPENSCSEventStreamArgumentDataType)this.MemberwiseClone(); } #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSEventStreamArgumentDataType clone = (OPENSCSEventStreamArgumentDataType)base.MemberwiseClone(); clone.m_sNFormat = (string)Utils.Clone(this.m_sNFormat); clone.m_parentSNFormat = (string)Utils.Clone(this.m_parentSNFormat); clone.m_packedElementSNFormat = (string)Utils.Clone(this.m_packedElementSNFormat); clone.m_eventContext = (OPENSCSKeyValueDataTypeCollection)Utils.Clone(this.m_eventContext); return clone; } #endregion #region Private Fields private string m_sNFormat; private string m_parentSNFormat; private string m_packedElementSNFormat; private OPENSCSKeyValueDataTypeCollection m_eventContext; #endregion } #region OPENSCSEventStreamArgumentDataTypeCollection Class /// <summary> /// A collection of OPENSCSEventStreamArgumentDataType objects. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfOPENSCSEventStreamArgumentDataType", Namespace = Prefix2.Namespaces.Name2Xsd, ItemName = "OPENSCSEventStreamArgumentDataType")] #if !NET_STANDARD public partial class OPENSCSEventStreamArgumentDataTypeCollection : List<OPENSCSEventStreamArgumentDataType>, ICloneable #else public partial class OPENSCSEventStreamArgumentDataTypeCollection : List<OPENSCSEventStreamArgumentDataType> #endif { #region Constructors /// <summary> /// Initializes the collection with default values. /// </summary> public OPENSCSEventStreamArgumentDataTypeCollection() {} /// <summary> /// Initializes the collection with an initial capacity. /// </summary> public OPENSCSEventStreamArgumentDataTypeCollection(int capacity) : base(capacity) {} /// <summary> /// Initializes the collection with another collection. /// </summary> public OPENSCSEventStreamArgumentDataTypeCollection(IEnumerable<OPENSCSEventStreamArgumentDataType> collection) : base(collection) {} #endregion #region Static Operators /// <summary> /// Converts an array to a collection. /// </summary> public static implicit operator OPENSCSEventStreamArgumentDataTypeCollection(OPENSCSEventStreamArgumentDataType[] values) { if (values != null) { return new OPENSCSEventStreamArgumentDataTypeCollection(values); } return new OPENSCSEventStreamArgumentDataTypeCollection(); } /// <summary> /// Converts a collection to an array. /// </summary> public static explicit operator OPENSCSEventStreamArgumentDataType[](OPENSCSEventStreamArgumentDataTypeCollection values) { if (values != null) { return values.ToArray(); } return null; } #endregion #if !NET_STANDARD #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> public object Clone() { return (OPENSCSEventStreamArgumentDataTypeCollection)this.MemberwiseClone(); } #endregion #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSEventStreamArgumentDataTypeCollection clone = new OPENSCSEventStreamArgumentDataTypeCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((OPENSCSEventStreamArgumentDataType)Utils.Clone(this[ii])); } return clone; } } #endregion #endif #endregion #region OPENSCSKeyValueDataType Class #if (!OPCUA_EXCLUDE_OPENSCSKeyValueDataType) /// <summary> /// A description for the OPENSCSKeyValueDataType DataType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [DataContract(Namespace = Prefix2.Namespaces.Name2Xsd)] public partial class OPENSCSKeyValueDataType : IEncodeable { #region Constructors /// <summary> /// The default constructor. /// </summary> public OPENSCSKeyValueDataType() { Initialize(); } /// <summary> /// Called by the .NET framework during deserialization. /// </summary> [OnDeserializing] private void Initialize(StreamingContext context) { Initialize(); } /// <summary> /// Sets private members to default values. /// </summary> private void Initialize() { m_key = null; m_value = null; } #endregion #region Public Properties /// <summary> /// A string defining the key for the pair /// </summary> [DataMember(Name = "Key", IsRequired = false, Order = 1)] public string Key { get { return m_key; } set { m_key = value; } } /// <summary> /// A variant for the value of the pair structure /// </summary> [DataMember(Name = "Value", IsRequired = false, Order = 2)] public string Value { get { return m_value; } set { m_value = value; } } #endregion #region IEncodeable Members /// <summary cref="IEncodeable.TypeId" /> public virtual ExpandedNodeId TypeId { get { return DataTypeIds.OPENSCSKeyValueDataType; } } /// <summary cref="IEncodeable.BinaryEncodingId" /> public virtual ExpandedNodeId BinaryEncodingId { get { return ObjectIds.OPENSCSKeyValueDataType_Encoding_DefaultBinary; } } /// <summary cref="IEncodeable.XmlEncodingId" /> public virtual ExpandedNodeId XmlEncodingId { get { return ObjectIds.OPENSCSKeyValueDataType_Encoding_DefaultXml; } } /// <summary cref="IEncodeable.Encode(IEncoder)" /> public virtual void Encode(IEncoder encoder) { encoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); encoder.WriteString("Key", Key); encoder.WriteString("Value", Value); encoder.PopNamespace(); } /// <summary cref="IEncodeable.Decode(IDecoder)" /> public virtual void Decode(IDecoder decoder) { decoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); Key = decoder.ReadString("Key"); Value = decoder.ReadString("Value"); decoder.PopNamespace(); } /// <summary cref="IEncodeable.IsEqual(IEncodeable)" /> public virtual bool IsEqual(IEncodeable encodeable) { if (Object.ReferenceEquals(this, encodeable)) { return true; } OPENSCSKeyValueDataType value = encodeable as OPENSCSKeyValueDataType; if (value == null) { return false; } if (!Utils.IsEqual(m_key, value.m_key)) return false; if (!Utils.IsEqual(m_value, value.m_value)) return false; return true; } #if !NET_STANDARD /// <summary cref="ICloneable.Clone" /> public virtual object Clone() { return (OPENSCSKeyValueDataType)this.MemberwiseClone(); } #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSKeyValueDataType clone = (OPENSCSKeyValueDataType)base.MemberwiseClone(); clone.m_key = (string)Utils.Clone(this.m_key); clone.m_value = (string)Utils.Clone(this.m_value); return clone; } #endregion #region Private Fields private string m_key; private string m_value; #endregion } #region OPENSCSKeyValueDataTypeCollection Class /// <summary> /// A collection of OPENSCSKeyValueDataType objects. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfOPENSCSKeyValueDataType", Namespace = Prefix2.Namespaces.Name2Xsd, ItemName = "OPENSCSKeyValueDataType")] #if !NET_STANDARD public partial class OPENSCSKeyValueDataTypeCollection : List<OPENSCSKeyValueDataType>, ICloneable #else public partial class OPENSCSKeyValueDataTypeCollection : List<OPENSCSKeyValueDataType> #endif { #region Constructors /// <summary> /// Initializes the collection with default values. /// </summary> public OPENSCSKeyValueDataTypeCollection() {} /// <summary> /// Initializes the collection with an initial capacity. /// </summary> public OPENSCSKeyValueDataTypeCollection(int capacity) : base(capacity) {} /// <summary> /// Initializes the collection with another collection. /// </summary> public OPENSCSKeyValueDataTypeCollection(IEnumerable<OPENSCSKeyValueDataType> collection) : base(collection) {} #endregion #region Static Operators /// <summary> /// Converts an array to a collection. /// </summary> public static implicit operator OPENSCSKeyValueDataTypeCollection(OPENSCSKeyValueDataType[] values) { if (values != null) { return new OPENSCSKeyValueDataTypeCollection(values); } return new OPENSCSKeyValueDataTypeCollection(); } /// <summary> /// Converts a collection to an array. /// </summary> public static explicit operator OPENSCSKeyValueDataType[](OPENSCSKeyValueDataTypeCollection values) { if (values != null) { return values.ToArray(); } return null; } #endregion #if !NET_STANDARD #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> public object Clone() { return (OPENSCSKeyValueDataTypeCollection)this.MemberwiseClone(); } #endregion #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSKeyValueDataTypeCollection clone = new OPENSCSKeyValueDataTypeCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((OPENSCSKeyValueDataType)Utils.Clone(this[ii])); } return clone; } } #endregion #endif #endregion #region OPENSCSLabelDataType Class #if (!OPCUA_EXCLUDE_OPENSCSLabelDataType) /// <summary> /// Defines a single serial number and label, which may be associated with an SID, and collection of properties in the form of OPENSCSKeyValueDataType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [DataContract(Namespace = Prefix2.Namespaces.Name2Xsd)] public partial class OPENSCSLabelDataType : IEncodeable { #region Constructors /// <summary> /// The default constructor. /// </summary> public OPENSCSLabelDataType() { Initialize(); } /// <summary> /// Called by the .NET framework during deserialization. /// </summary> [OnDeserializing] private void Initialize(StreamingContext context) { Initialize(); } /// <summary> /// Sets private members to default values. /// </summary> private void Initialize() { m_ıD = null; m_labelProperties = new OPENSCSKeyValueDataTypeCollection(); } #endregion #region Public Properties /// <summary> /// The serial number of the label in the SID or EPC format. /// </summary> [DataMember(Name = "ID", IsRequired = false, Order = 1)] public string ID { get { return m_ıD; } set { m_ıD = value; } } /// <summary> /// An optional array of additional properties in the form of Key/Value pairs /// </summary> [DataMember(Name = "LabelProperties", IsRequired = false, Order = 2)] public OPENSCSKeyValueDataTypeCollection LabelProperties { get { return m_labelProperties; } set { m_labelProperties = value; if (value == null) { m_labelProperties = new OPENSCSKeyValueDataTypeCollection(); } } } #endregion #region IEncodeable Members /// <summary cref="IEncodeable.TypeId" /> public virtual ExpandedNodeId TypeId { get { return DataTypeIds.OPENSCSLabelDataType; } } /// <summary cref="IEncodeable.BinaryEncodingId" /> public virtual ExpandedNodeId BinaryEncodingId { get { return ObjectIds.OPENSCSLabelDataType_Encoding_DefaultBinary; } } /// <summary cref="IEncodeable.XmlEncodingId" /> public virtual ExpandedNodeId XmlEncodingId { get { return ObjectIds.OPENSCSLabelDataType_Encoding_DefaultXml; } } /// <summary cref="IEncodeable.Encode(IEncoder)" /> public virtual void Encode(IEncoder encoder) { encoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); encoder.WriteString("ID", ID); encoder.WriteEncodeableArray("LabelProperties", LabelProperties.ToArray(), typeof(OPENSCSKeyValueDataType)); encoder.PopNamespace(); } /// <summary cref="IEncodeable.Decode(IDecoder)" /> public virtual void Decode(IDecoder decoder) { decoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); ID = decoder.ReadString("ID"); LabelProperties = (OPENSCSKeyValueDataTypeCollection)decoder.ReadEncodeableArray("LabelProperties", typeof(OPENSCSKeyValueDataType)); decoder.PopNamespace(); } /// <summary cref="IEncodeable.IsEqual(IEncodeable)" /> public virtual bool IsEqual(IEncodeable encodeable) { if (Object.ReferenceEquals(this, encodeable)) { return true; } OPENSCSLabelDataType value = encodeable as OPENSCSLabelDataType; if (value == null) { return false; } if (!Utils.IsEqual(m_ıD, value.m_ıD)) return false; if (!Utils.IsEqual(m_labelProperties, value.m_labelProperties)) return false; return true; } #if !NET_STANDARD /// <summary cref="ICloneable.Clone" /> public virtual object Clone() { return (OPENSCSLabelDataType)this.MemberwiseClone(); } #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSLabelDataType clone = (OPENSCSLabelDataType)base.MemberwiseClone(); clone.m_ıD = (string)Utils.Clone(this.m_ıD); clone.m_labelProperties = (OPENSCSKeyValueDataTypeCollection)Utils.Clone(this.m_labelProperties); return clone; } #endregion #region Private Fields private string m_ıD; private OPENSCSKeyValueDataTypeCollection m_labelProperties; #endregion } #region OPENSCSLabelDataTypeCollection Class /// <summary> /// A collection of OPENSCSLabelDataType objects. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfOPENSCSLabelDataType", Namespace = Prefix2.Namespaces.Name2Xsd, ItemName = "OPENSCSLabelDataType")] #if !NET_STANDARD public partial class OPENSCSLabelDataTypeCollection : List<OPENSCSLabelDataType>, ICloneable #else public partial class OPENSCSLabelDataTypeCollection : List<OPENSCSLabelDataType> #endif { #region Constructors /// <summary> /// Initializes the collection with default values. /// </summary> public OPENSCSLabelDataTypeCollection() {} /// <summary> /// Initializes the collection with an initial capacity. /// </summary> public OPENSCSLabelDataTypeCollection(int capacity) : base(capacity) {} /// <summary> /// Initializes the collection with another collection. /// </summary> public OPENSCSLabelDataTypeCollection(IEnumerable<OPENSCSLabelDataType> collection) : base(collection) {} #endregion #region Static Operators /// <summary> /// Converts an array to a collection. /// </summary> public static implicit operator OPENSCSLabelDataTypeCollection(OPENSCSLabelDataType[] values) { if (values != null) { return new OPENSCSLabelDataTypeCollection(values); } return new OPENSCSLabelDataTypeCollection(); } /// <summary> /// Converts a collection to an array. /// </summary> public static explicit operator OPENSCSLabelDataType[](OPENSCSLabelDataTypeCollection values) { if (values != null) { return values.ToArray(); } return null; } #endregion #if !NET_STANDARD #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> public object Clone() { return (OPENSCSLabelDataTypeCollection)this.MemberwiseClone(); } #endregion #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSLabelDataTypeCollection clone = new OPENSCSLabelDataTypeCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((OPENSCSLabelDataType)Utils.Clone(this[ii])); } return clone; } } #endregion #endif #endregion #region OPENSCSLabelPropertyDataType Class #if (!OPCUA_EXCLUDE_OPENSCSLabelPropertyDataType) /// <summary> /// A description for the OPENSCSLabelPropertyDataType DataType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [DataContract(Namespace = Prefix2.Namespaces.Name2Xsd)] public partial class OPENSCSLabelPropertyDataType : IEncodeable { #region Constructors /// <summary> /// The default constructor. /// </summary> public OPENSCSLabelPropertyDataType() { Initialize(); } /// <summary> /// Called by the .NET framework during deserialization. /// </summary> [OnDeserializing] private void Initialize(StreamingContext context) { Initialize(); } /// <summary> /// Sets private members to default values. /// </summary> private void Initialize() { m_propertyID = null; m_propertyDescription = null; m_propertyValue = null; } #endregion #region Public Properties /// <summary> /// The identification of a property associated with a label. /// </summary> [DataMember(Name = "PropertyID", IsRequired = false, Order = 1)] public string PropertyID { get { return m_propertyID; } set { m_propertyID = value; } } /// <summary> /// An optional description of the property associated with the label /// </summary> [DataMember(Name = "PropertyDescription", IsRequired = false, Order = 2)] public string PropertyDescription { get { return m_propertyDescription; } set { m_propertyDescription = value; } } /// <summary> /// A value for the property, if defined this may be considered a default property value. /// </summary> [DataMember(Name = "PropertyValue", IsRequired = false, Order = 3)] public string PropertyValue { get { return m_propertyValue; } set { m_propertyValue = value; } } #endregion #region IEncodeable Members /// <summary cref="IEncodeable.TypeId" /> public virtual ExpandedNodeId TypeId { get { return DataTypeIds.OPENSCSLabelPropertyDataType; } } /// <summary cref="IEncodeable.BinaryEncodingId" /> public virtual ExpandedNodeId BinaryEncodingId { get { return ObjectIds.OPENSCSLabelPropertyDataType_Encoding_DefaultBinary; } } /// <summary cref="IEncodeable.XmlEncodingId" /> public virtual ExpandedNodeId XmlEncodingId { get { return ObjectIds.OPENSCSLabelPropertyDataType_Encoding_DefaultXml; } } /// <summary cref="IEncodeable.Encode(IEncoder)" /> public virtual void Encode(IEncoder encoder) { encoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); encoder.WriteString("PropertyID", PropertyID); encoder.WriteString("PropertyDescription", PropertyDescription); encoder.WriteString("PropertyValue", PropertyValue); encoder.PopNamespace(); } /// <summary cref="IEncodeable.Decode(IDecoder)" /> public virtual void Decode(IDecoder decoder) { decoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); PropertyID = decoder.ReadString("PropertyID"); PropertyDescription = decoder.ReadString("PropertyDescription"); PropertyValue = decoder.ReadString("PropertyValue"); decoder.PopNamespace(); } /// <summary cref="IEncodeable.IsEqual(IEncodeable)" /> public virtual bool IsEqual(IEncodeable encodeable) { if (Object.ReferenceEquals(this, encodeable)) { return true; } OPENSCSLabelPropertyDataType value = encodeable as OPENSCSLabelPropertyDataType; if (value == null) { return false; } if (!Utils.IsEqual(m_propertyID, value.m_propertyID)) return false; if (!Utils.IsEqual(m_propertyDescription, value.m_propertyDescription)) return false; if (!Utils.IsEqual(m_propertyValue, value.m_propertyValue)) return false; return true; } #if !NET_STANDARD /// <summary cref="ICloneable.Clone" /> public virtual object Clone() { return (OPENSCSLabelPropertyDataType)this.MemberwiseClone(); } #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSLabelPropertyDataType clone = (OPENSCSLabelPropertyDataType)base.MemberwiseClone(); clone.m_propertyID = (string)Utils.Clone(this.m_propertyID); clone.m_propertyDescription = (string)Utils.Clone(this.m_propertyDescription); clone.m_propertyValue = (string)Utils.Clone(this.m_propertyValue); return clone; } #endregion #region Private Fields private string m_propertyID; private string m_propertyDescription; private string m_propertyValue; #endregion } #region OPENSCSLabelPropertyDataTypeCollection Class /// <summary> /// A collection of OPENSCSLabelPropertyDataType objects. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfOPENSCSLabelPropertyDataType", Namespace = Prefix2.Namespaces.Name2Xsd, ItemName = "OPENSCSLabelPropertyDataType")] #if !NET_STANDARD public partial class OPENSCSLabelPropertyDataTypeCollection : List<OPENSCSLabelPropertyDataType>, ICloneable #else public partial class OPENSCSLabelPropertyDataTypeCollection : List<OPENSCSLabelPropertyDataType> #endif { #region Constructors /// <summary> /// Initializes the collection with default values. /// </summary> public OPENSCSLabelPropertyDataTypeCollection() {} /// <summary> /// Initializes the collection with an initial capacity. /// </summary> public OPENSCSLabelPropertyDataTypeCollection(int capacity) : base(capacity) {} /// <summary> /// Initializes the collection with another collection. /// </summary> public OPENSCSLabelPropertyDataTypeCollection(IEnumerable<OPENSCSLabelPropertyDataType> collection) : base(collection) {} #endregion #region Static Operators /// <summary> /// Converts an array to a collection. /// </summary> public static implicit operator OPENSCSLabelPropertyDataTypeCollection(OPENSCSLabelPropertyDataType[] values) { if (values != null) { return new OPENSCSLabelPropertyDataTypeCollection(values); } return new OPENSCSLabelPropertyDataTypeCollection(); } /// <summary> /// Converts a collection to an array. /// </summary> public static explicit operator OPENSCSLabelPropertyDataType[](OPENSCSLabelPropertyDataTypeCollection values) { if (values != null) { return values.ToArray(); } return null; } #endregion #if !NET_STANDARD #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> public object Clone() { return (OPENSCSLabelPropertyDataTypeCollection)this.MemberwiseClone(); } #endregion #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSLabelPropertyDataTypeCollection clone = new OPENSCSLabelPropertyDataTypeCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((OPENSCSLabelPropertyDataType)Utils.Clone(this[ii])); } return clone; } } #endregion #endif #endregion #region OPENSCSSIDClassPropertyDataType Class #if (!OPCUA_EXCLUDE_OPENSCSSIDClassPropertyDataType) /// <summary> /// A description for the OPENSCSSIDClassPropertyDataType DataType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [DataContract(Namespace = Prefix2.Namespaces.Name2Xsd)] public partial class OPENSCSSIDClassPropertyDataType : IEncodeable { #region Constructors /// <summary> /// The default constructor. /// </summary> public OPENSCSSIDClassPropertyDataType() { Initialize(); } /// <summary> /// Called by the .NET framework during deserialization. /// </summary> [OnDeserializing] private void Initialize(StreamingContext context) { Initialize(); } /// <summary> /// Sets private members to default values. /// </summary> private void Initialize() { m_propertyID = null; m_propertyDescription = null; m_propertyValue = null; m_labelProperty = new OPENSCSLabelPropertyDataTypeCollection(); } #endregion #region Public Properties /// <summary> /// An identification of the SID Class Property. /// </summary> [DataMember(Name = "PropertyID", IsRequired = false, Order = 1)] public string PropertyID { get { return m_propertyID; } set { m_propertyID = value; } } /// <summary> /// Additional information and description about the SID Class Property. /// </summary> [DataMember(Name = "PropertyDescription", IsRequired = false, Order = 2)] public string PropertyDescription { get { return m_propertyDescription; } set { m_propertyDescription = value; } } /// <summary> /// Defines value for the specific SID Class Property. The format is not defined in this specification and must be negotiated between Information Providers and Information Requesters during design or change management of a system. /// </summary> [DataMember(Name = "PropertyValue", IsRequired = false, Order = 3)] public string PropertyValue { get { return m_propertyValue; } set { m_propertyValue = value; } } /// <summary> /// An array of property elements, each of which may have associated label property definitions. /// </summary> [DataMember(Name = "LabelProperty", IsRequired = false, Order = 4)] public OPENSCSLabelPropertyDataTypeCollection LabelProperty { get { return m_labelProperty; } set { m_labelProperty = value; if (value == null) { m_labelProperty = new OPENSCSLabelPropertyDataTypeCollection(); } } } #endregion #region IEncodeable Members /// <summary cref="IEncodeable.TypeId" /> public virtual ExpandedNodeId TypeId { get { return DataTypeIds.OPENSCSSIDClassPropertyDataType; } } /// <summary cref="IEncodeable.BinaryEncodingId" /> public virtual ExpandedNodeId BinaryEncodingId { get { return ObjectIds.OPENSCSSIDClassPropertyDataType_Encoding_DefaultBinary; } } /// <summary cref="IEncodeable.XmlEncodingId" /> public virtual ExpandedNodeId XmlEncodingId { get { return ObjectIds.OPENSCSSIDClassPropertyDataType_Encoding_DefaultXml; } } /// <summary cref="IEncodeable.Encode(IEncoder)" /> public virtual void Encode(IEncoder encoder) { encoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); encoder.WriteString("PropertyID", PropertyID); encoder.WriteString("PropertyDescription", PropertyDescription); encoder.WriteString("PropertyValue", PropertyValue); encoder.WriteEncodeableArray("LabelProperty", LabelProperty.ToArray(), typeof(OPENSCSLabelPropertyDataType)); encoder.PopNamespace(); } /// <summary cref="IEncodeable.Decode(IDecoder)" /> public virtual void Decode(IDecoder decoder) { decoder.PushNamespace(Prefix2.Namespaces.Name2Xsd); PropertyID = decoder.ReadString("PropertyID"); PropertyDescription = decoder.ReadString("PropertyDescription"); PropertyValue = decoder.ReadString("PropertyValue"); LabelProperty = (OPENSCSLabelPropertyDataTypeCollection)decoder.ReadEncodeableArray("LabelProperty", typeof(OPENSCSLabelPropertyDataType)); decoder.PopNamespace(); } /// <summary cref="IEncodeable.IsEqual(IEncodeable)" /> public virtual bool IsEqual(IEncodeable encodeable) { if (Object.ReferenceEquals(this, encodeable)) { return true; } OPENSCSSIDClassPropertyDataType value = encodeable as OPENSCSSIDClassPropertyDataType; if (value == null) { return false; } if (!Utils.IsEqual(m_propertyID, value.m_propertyID)) return false; if (!Utils.IsEqual(m_propertyDescription, value.m_propertyDescription)) return false; if (!Utils.IsEqual(m_propertyValue, value.m_propertyValue)) return false; if (!Utils.IsEqual(m_labelProperty, value.m_labelProperty)) return false; return true; } #if !NET_STANDARD /// <summary cref="ICloneable.Clone" /> public virtual object Clone() { return (OPENSCSSIDClassPropertyDataType)this.MemberwiseClone(); } #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSSIDClassPropertyDataType clone = (OPENSCSSIDClassPropertyDataType)base.MemberwiseClone(); clone.m_propertyID = (string)Utils.Clone(this.m_propertyID); clone.m_propertyDescription = (string)Utils.Clone(this.m_propertyDescription); clone.m_propertyValue = (string)Utils.Clone(this.m_propertyValue); clone.m_labelProperty = (OPENSCSLabelPropertyDataTypeCollection)Utils.Clone(this.m_labelProperty); return clone; } #endregion #region Private Fields private string m_propertyID; private string m_propertyDescription; private string m_propertyValue; private OPENSCSLabelPropertyDataTypeCollection m_labelProperty; #endregion } #region OPENSCSSIDClassPropertyDataTypeCollection Class /// <summary> /// A collection of OPENSCSSIDClassPropertyDataType objects. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] [CollectionDataContract(Name = "ListOfOPENSCSSIDClassPropertyDataType", Namespace = Prefix2.Namespaces.Name2Xsd, ItemName = "OPENSCSSIDClassPropertyDataType")] #if !NET_STANDARD public partial class OPENSCSSIDClassPropertyDataTypeCollection : List<OPENSCSSIDClassPropertyDataType>, ICloneable #else public partial class OPENSCSSIDClassPropertyDataTypeCollection : List<OPENSCSSIDClassPropertyDataType> #endif { #region Constructors /// <summary> /// Initializes the collection with default values. /// </summary> public OPENSCSSIDClassPropertyDataTypeCollection() {} /// <summary> /// Initializes the collection with an initial capacity. /// </summary> public OPENSCSSIDClassPropertyDataTypeCollection(int capacity) : base(capacity) {} /// <summary> /// Initializes the collection with another collection. /// </summary> public OPENSCSSIDClassPropertyDataTypeCollection(IEnumerable<OPENSCSSIDClassPropertyDataType> collection) : base(collection) {} #endregion #region Static Operators /// <summary> /// Converts an array to a collection. /// </summary> public static implicit operator OPENSCSSIDClassPropertyDataTypeCollection(OPENSCSSIDClassPropertyDataType[] values) { if (values != null) { return new OPENSCSSIDClassPropertyDataTypeCollection(values); } return new OPENSCSSIDClassPropertyDataTypeCollection(); } /// <summary> /// Converts a collection to an array. /// </summary> public static explicit operator OPENSCSSIDClassPropertyDataType[](OPENSCSSIDClassPropertyDataTypeCollection values) { if (values != null) { return values.ToArray(); } return null; } #endregion #if !NET_STANDARD #region ICloneable Methods /// <summary> /// Creates a deep copy of the collection. /// </summary> public object Clone() { return (OPENSCSSIDClassPropertyDataTypeCollection)this.MemberwiseClone(); } #endregion #endif /// <summary cref="Object.MemberwiseClone" /> public new object MemberwiseClone() { OPENSCSSIDClassPropertyDataTypeCollection clone = new OPENSCSSIDClassPropertyDataTypeCollection(this.Count); for (int ii = 0; ii < this.Count; ii++) { clone.Add((OPENSCSSIDClassPropertyDataType)Utils.Clone(this[ii])); } return clone; } } #endregion #endif #endregion #region OPENSCSAggregationManagerObjectState Class #if (!OPCUA_EXCLUDE_OPENSCSAggregationManagerObjectState) /// <summary> /// Stores an instance of the OPENSCSAggregationManagerObjectType ObjectType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public partial class OPENSCSAggregationManagerObjectState : BaseObjectState { #region Constructors /// <summary> /// Initializes the type with its default attribute values. /// </summary> public OPENSCSAggregationManagerObjectState(NodeState parent) : base(parent) { } /// <summary> /// Returns the id of the default type definition node for the instance. /// </summary> protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris) { return Opc.Ua.NodeId.Create(Prefix2.ObjectTypes.OPENSCSAggregationManagerObjectType, Prefix2.Namespaces.Name2, namespaceUris); } #if (!OPCUA_EXCLUDE_InitializationStrings) /// <summary> /// Initializes the instance. /// </summary> protected override void Initialize(ISystemContext context) { Initialize(context, InitializationString); InitializeOptionalChildren(context); } protected override void Initialize(ISystemContext context, NodeState source) { InitializeOptionalChildren(context); base.Initialize(context, source); } /// <summary> /// Initializes the any option children defined for the instance. /// </summary> protected override void InitializeOptionalChildren(ISystemContext context) { base.InitializeOptionalChildren(context); } #region Initialization String private const string InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////wRggAABAAAA" + "AQArAAAAT1BFTlNDU0FnZ3JlZ2F0aW9uTWFuYWdlck9iamVjdFR5cGVJbnN0YW5jZQEBFgABARYA////" + "/wMAAAAEYYIKBAAAAAEAFwAAAEFnZ3JlZ2F0aW9uUGFja2luZ0V2ZW50AQEXAAAvAQEXABcAAAABAf//" + "//8CAAAAF2CpCgIAAAAAAA4AAABJbnB1dEFyZ3VtZW50cwEBGAAALgBEGAAAAJYAAAAAAQAoAQEAAAAB" + "AAAABAAAAAEB/////wAAAAAXYKkKAgAAAAAADwAAAE91dHB1dEFyZ3VtZW50cwEBGQAALgBEGQAAAJYA" + "AAAAAQAoAQEAAAABAAAAAAAAAAEB/////wAAAAAEYYIKBAAAAAEAGQAAAEFnZ3JlZ2F0aW9uVW5wYWNr" + "aW5nRXZlbnQBARoAAC8BARoAGgAAAAEB/////wIAAAAXYKkKAgAAAAAADgAAAElucHV0QXJndW1lbnRz" + "AQEbAAAuAEQbAAAAlgAAAAABACgBAQAAAAEAAAAEAAAAAQH/////AAAAABdgqQoCAAAAAAAPAAAAT3V0" + "cHV0QXJndW1lbnRzAQEcAAAuAEQcAAAAlgAAAAABACgBAQAAAAEAAAABAAAAAQH/////AAAAABVgiQoC" + "AAAAAQAUAAAATWF4QWdncmVnYXRpb25FdmVudHMBAR0AAC4ARB0AAAAAB/////8BAf////8AAAAA"; #endregion #endif #endregion #region Public Properties /// <summary> /// A description for the AggregationPackingEvent Method. /// </summary> public MethodState AggregationPackingEvent { get { return m_aggregationPackingEventMethod; } set { if (!Object.ReferenceEquals(m_aggregationPackingEventMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_aggregationPackingEventMethod = value; } } /// <summary> /// A description for the AggregationUnpackingEvent Method. /// </summary> public MethodState AggregationUnpackingEvent { get { return m_aggregationUnpackingEventMethod; } set { if (!Object.ReferenceEquals(m_aggregationUnpackingEventMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_aggregationUnpackingEventMethod = value; } } /// <summary> /// A description for the MaxAggregationEvents Property. /// </summary> public PropertyState<uint> MaxAggregationEvents { get { return m_maxAggregationEvents; } set { if (!Object.ReferenceEquals(m_maxAggregationEvents, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_maxAggregationEvents = value; } } #endregion #region Overridden Methods /// <summary> /// Populates a list with the children that belong to the node. /// </summary> /// <param name="context">The context for the system being accessed.</param> /// <param name="children">The list of children to populate.</param> public override void GetChildren( ISystemContext context, IList<BaseInstanceState> children) { if (m_aggregationPackingEventMethod != null) { children.Add(m_aggregationPackingEventMethod); } if (m_aggregationUnpackingEventMethod != null) { children.Add(m_aggregationUnpackingEventMethod); } if (m_maxAggregationEvents != null) { children.Add(m_maxAggregationEvents); } base.GetChildren(context, children); } /// <summary> /// Finds the child with the specified browse name. /// </summary> protected override BaseInstanceState FindChild( ISystemContext context, QualifiedName browseName, bool createOrReplace, BaseInstanceState replacement) { if (QualifiedName.IsNull(browseName)) { return null; } BaseInstanceState instance = null; switch (browseName.Name) { case Prefix2.BrowseNames.AggregationPackingEvent: { if (createOrReplace) { if (AggregationPackingEvent == null) { if (replacement == null) { AggregationPackingEvent = new MethodState(this); } else { AggregationPackingEvent = (MethodState)replacement; } } } instance = AggregationPackingEvent; break; } case Prefix2.BrowseNames.AggregationUnpackingEvent: { if (createOrReplace) { if (AggregationUnpackingEvent == null) { if (replacement == null) { AggregationUnpackingEvent = new MethodState(this); } else { AggregationUnpackingEvent = (MethodState)replacement; } } } instance = AggregationUnpackingEvent; break; } case Prefix2.BrowseNames.MaxAggregationEvents: { if (createOrReplace) { if (MaxAggregationEvents == null) { if (replacement == null) { MaxAggregationEvents = new PropertyState<uint>(this); } else { MaxAggregationEvents = (PropertyState<uint>)replacement; } } } instance = MaxAggregationEvents; break; } } if (instance != null) { return instance; } return base.FindChild(context, browseName, createOrReplace, replacement); } #endregion #region Private Fields private MethodState m_aggregationPackingEventMethod; private MethodState m_aggregationUnpackingEventMethod; private PropertyState<uint> m_maxAggregationEvents; #endregion } #endif #endregion #region OPENSCSEventManagerObjectState Class #if (!OPCUA_EXCLUDE_OPENSCSEventManagerObjectState) /// <summary> /// Stores an instance of the OPENSCSEventManagerObjectType ObjectType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public partial class OPENSCSEventManagerObjectState : BaseObjectState { #region Constructors /// <summary> /// Initializes the type with its default attribute values. /// </summary> public OPENSCSEventManagerObjectState(NodeState parent) : base(parent) { } /// <summary> /// Returns the id of the default type definition node for the instance. /// </summary> protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris) { return Opc.Ua.NodeId.Create(Prefix2.ObjectTypes.OPENSCSEventManagerObjectType, Prefix2.Namespaces.Name2, namespaceUris); } #if (!OPCUA_EXCLUDE_InitializationStrings) /// <summary> /// Initializes the instance. /// </summary> protected override void Initialize(ISystemContext context) { Initialize(context, InitializationString); InitializeOptionalChildren(context); } protected override void Initialize(ISystemContext context, NodeState source) { InitializeOptionalChildren(context); base.Initialize(context, source); } /// <summary> /// Initializes the any option children defined for the instance. /// </summary> protected override void InitializeOptionalChildren(ISystemContext context) { base.InitializeOptionalChildren(context); if (EPCISStream != null) { EPCISStream.Initialize(context, EPCISStream_InitializationString); } if (LabelsEncodingEvent != null) { LabelsEncodingEvent.Initialize(context, LabelsEncodingEvent_InitializationString); } if (LabelsInspectingEvent != null) { LabelsInspectingEvent.Initialize(context, LabelsInspectingEvent_InitializationString); } if (LabelsSamplingEvent != null) { LabelsSamplingEvent.Initialize(context, LabelsSamplingEvent_InitializationString); } if (LabelsScrappingEvent != null) { LabelsScrappingEvent.Initialize(context, LabelsScrappingEvent_InitializationString); } if (SIDCommissioningEvent != null) { SIDCommissioningEvent.Initialize(context, SIDCommissioningEvent_InitializationString); } if (SIDDecommissioningEvent != null) { SIDDecommissioningEvent.Initialize(context, SIDDecommissioningEvent_InitializationString); } if (SIDDestroyingEvent != null) { SIDDestroyingEvent.Initialize(context, SIDDestroyingEvent_InitializationString); } if (SIDInspectingEvent != null) { SIDInspectingEvent.Initialize(context, SIDInspectingEvent_InitializationString); } if (SIDShippingEvent != null) { SIDShippingEvent.Initialize(context, SIDShippingEvent_InitializationString); } if (SNInvalidatingEvent != null) { SNInvalidatingEvent.Initialize(context, SNInvalidatingEvent_InitializationString); } } #region Initialization String private const string EPCISStream_InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////wRggAoBAAAA" + "AQALAAAARVBDSVNTdHJlYW0BAR8AAC8BAIA9HwAAAP////8EAAAAFWCJCgIAAAAAABcAAABDbGllbnRQ" + "cm9jZXNzaW5nVGltZW91dAEBIAAALgBEIAAAAAEAIgH/////AQH/////AAAAAARhggoEAAAAAAATAAAA" + "R2VuZXJhdGVGaWxlRm9yUmVhZAEBIQAALwEAgj0hAAAAAQH/////AgAAABdgqQoCAAAAAAAOAAAASW5w" + "dXRBcmd1bWVudHMBASIAAC4ARCIAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAAF2CpCgIA" + "AAAAAA8AAABPdXRwdXRBcmd1bWVudHMBASMAAC4ARCMAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf//" + "//8AAAAABGGCCgQAAAAAABQAAABHZW5lcmF0ZUZpbGVGb3JXcml0ZQEBJAAALwEAhT0kAAAAAQH/////" + "AgAAABdgqQoCAAAAAAAOAAAASW5wdXRBcmd1bWVudHMBASUAAC4ARCUAAACWAAAAAAEAKAEBAAAAAQAA" + "AAAAAAABAf////8AAAAAF2CpCgIAAAAAAA8AAABPdXRwdXRBcmd1bWVudHMBASYAAC4ARCYAAACWAAAA" + "AAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAABGGCCgQAAAAAAA4AAABDbG9zZUFuZENvbW1pdAEBJwAA" + "LwEAhz0nAAAAAQH/////AgAAABdgqQoCAAAAAAAOAAAASW5wdXRBcmd1bWVudHMBASgAAC4ARCgAAACW" + "AAAAAAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAAF2CpCgIAAAAAAA8AAABPdXRwdXRBcmd1bWVudHMB" + "ASkAAC4ARCkAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAA"; private const string LabelsEncodingEvent_InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////wRhggoEAAAA" + "AQATAAAATGFiZWxzRW5jb2RpbmdFdmVudAEBKgAALwEBKgAqAAAAAQH/////AgAAABdgqQoCAAAAAAAO" + "AAAASW5wdXRBcmd1bWVudHMBASsAAC4ARCsAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAA" + "F2CpCgIAAAAAAA8AAABPdXRwdXRBcmd1bWVudHMBASwAAC4ARCwAAACWAAAAAAEAKAEBAAAAAQAAAAAA" + "AAABAf////8AAAAA"; private const string LabelsInspectingEvent_InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////wRhggoEAAAA" + "AQAVAAAATGFiZWxzSW5zcGVjdGluZ0V2ZW50AQEtAAAvAQEtAC0AAAABAf////8CAAAAF2CpCgIAAAAA" + "AA4AAABJbnB1dEFyZ3VtZW50cwEBLgAALgBELgAAAJYAAAAAAQAoAQEAAAABAAAAAAAAAAEB/////wAA" + "AAAXYKkKAgAAAAAADwAAAE91dHB1dEFyZ3VtZW50cwEBLwAALgBELwAAAJYAAAAAAQAoAQEAAAABAAAA" + "AAAAAAEB/////wAAAAA="; private const string LabelsSamplingEvent_InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////wRhggoEAAAA" + "AQATAAAATGFiZWxzU2FtcGxpbmdFdmVudAEBMAAALwEBMAAwAAAAAQH/////AgAAABdgqQoCAAAAAAAO" + "AAAASW5wdXRBcmd1bWVudHMBATEAAC4ARDEAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAA" + "F2CpCgIAAAAAAA8AAABPdXRwdXRBcmd1bWVudHMBATIAAC4ARDIAAACWAAAAAAEAKAEBAAAAAQAAAAAA" + "AAABAf////8AAAAA"; private const string LabelsScrappingEvent_InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////wRhggoEAAAA" + "AQAUAAAATGFiZWxzU2NyYXBwaW5nRXZlbnQBATMAAC8BATMAMwAAAAEB/////wIAAAAXYKkKAgAAAAAA" + "DgAAAElucHV0QXJndW1lbnRzAQE0AAAuAEQ0AAAAlgAAAAABACgBAQAAAAEAAAAAAAAAAQH/////AAAA" + "ABdgqQoCAAAAAAAPAAAAT3V0cHV0QXJndW1lbnRzAQE1AAAuAEQ1AAAAlgAAAAABACgBAQAAAAEAAAAA" + "AAAAAQH/////AAAAAA=="; private const string SIDCommissioningEvent_InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////wRhggoEAAAA" + "AQAVAAAAU0lEQ29tbWlzc2lvbmluZ0V2ZW50AQE5AAAvAQE5ADkAAAABAf////8CAAAAF2CpCgIAAAAA" + "AA4AAABJbnB1dEFyZ3VtZW50cwEBOgAALgBEOgAAAJYAAAAAAQAoAQEAAAABAAAAAAAAAAEB/////wAA" + "AAAXYKkKAgAAAAAADwAAAE91dHB1dEFyZ3VtZW50cwEBOwAALgBEOwAAAJYAAAAAAQAoAQEAAAABAAAA" + "AAAAAAEB/////wAAAAA="; private const string SIDDecommissioningEvent_InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////wRhggoEAAAA" + "AQAXAAAAU0lERGVjb21taXNzaW9uaW5nRXZlbnQBATwAAC8BATwAPAAAAAEB/////wIAAAAXYKkKAgAA" + "AAAADgAAAElucHV0QXJndW1lbnRzAQE9AAAuAEQ9AAAAlgAAAAABACgBAQAAAAEAAAAAAAAAAQH/////" + "AAAAABdgqQoCAAAAAAAPAAAAT3V0cHV0QXJndW1lbnRzAQE+AAAuAEQ+AAAAlgAAAAABACgBAQAAAAEA" + "AAAAAAAAAQH/////AAAAAA=="; private const string SIDDestroyingEvent_InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////wRhggoEAAAA" + "AQASAAAAU0lERGVzdHJveWluZ0V2ZW50AQE/AAAvAQE/AD8AAAABAf////8CAAAAF2CpCgIAAAAAAA4A" + "AABJbnB1dEFyZ3VtZW50cwEBQAAALgBEQAAAAJYAAAAAAQAoAQEAAAABAAAAAAAAAAEB/////wAAAAAX" + "YKkKAgAAAAAADwAAAE91dHB1dEFyZ3VtZW50cwEBQQAALgBEQQAAAJYAAAAAAQAoAQEAAAABAAAAAAAA" + "AAEB/////wAAAAA="; private const string SIDInspectingEvent_InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////wRhggoEAAAA" + "AQASAAAAU0lESW5zcGVjdGluZ0V2ZW50AQFCAAAvAQFCAEIAAAABAf////8CAAAAF2CpCgIAAAAAAA4A" + "AABJbnB1dEFyZ3VtZW50cwEBQwAALgBEQwAAAJYAAAAAAQAoAQEAAAABAAAAAAAAAAEB/////wAAAAAX" + "YKkKAgAAAAAADwAAAE91dHB1dEFyZ3VtZW50cwEBRAAALgBERAAAAJYAAAAAAQAoAQEAAAABAAAAAAAA" + "AAEB/////wAAAAA="; private const string SIDShippingEvent_InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////wRhggoEAAAA" + "AQAQAAAAU0lEU2hpcHBpbmdFdmVudAEBRQAALwEBRQBFAAAAAQH/////AgAAABdgqQoCAAAAAAAOAAAA" + "SW5wdXRBcmd1bWVudHMBAUYAAC4AREYAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAAF2Cp" + "CgIAAAAAAA8AAABPdXRwdXRBcmd1bWVudHMBAUcAAC4AREcAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAAB" + "Af////8AAAAA"; private const string SNInvalidatingEvent_InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////wRhggoEAAAA" + "AQATAAAAU05JbnZhbGlkYXRpbmdFdmVudAEBSAAALwEBSABIAAAAAQH/////AgAAABdgqQoCAAAAAAAO" + "AAAASW5wdXRBcmd1bWVudHMBAUkAAC4AREkAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAA" + "F2CpCgIAAAAAAA8AAABPdXRwdXRBcmd1bWVudHMBAUoAAC4AREoAAACWAAAAAAEAKAEBAAAAAQAAAAAA" + "AAABAf////8AAAAA"; private const string InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////wRggAABAAAA" + "AQAlAAAAT1BFTlNDU0V2ZW50TWFuYWdlck9iamVjdFR5cGVJbnN0YW5jZQEBHgABAR4A/////w4AAAAE" + "YIAKAQAAAAEACwAAAEVQQ0lTU3RyZWFtAQEfAAAvAQCAPR8AAAD/////BAAAABVgiQoCAAAAAAAXAAAA" + "Q2xpZW50UHJvY2Vzc2luZ1RpbWVvdXQBASAAAC4ARCAAAAABACIB/////wEB/////wAAAAAEYYIKBAAA" + "AAAAEwAAAEdlbmVyYXRlRmlsZUZvclJlYWQBASEAAC8BAII9IQAAAAEB/////wIAAAAXYKkKAgAAAAAA" + "DgAAAElucHV0QXJndW1lbnRzAQEiAAAuAEQiAAAAlgAAAAABACgBAQAAAAEAAAAAAAAAAQH/////AAAA" + "ABdgqQoCAAAAAAAPAAAAT3V0cHV0QXJndW1lbnRzAQEjAAAuAEQjAAAAlgAAAAABACgBAQAAAAEAAAAA" + "AAAAAQH/////AAAAAARhggoEAAAAAAAUAAAAR2VuZXJhdGVGaWxlRm9yV3JpdGUBASQAAC8BAIU9JAAA" + "AAEB/////wIAAAAXYKkKAgAAAAAADgAAAElucHV0QXJndW1lbnRzAQElAAAuAEQlAAAAlgAAAAABACgB" + "AQAAAAEAAAAAAAAAAQH/////AAAAABdgqQoCAAAAAAAPAAAAT3V0cHV0QXJndW1lbnRzAQEmAAAuAEQm" + "AAAAlgAAAAABACgBAQAAAAEAAAAAAAAAAQH/////AAAAAARhggoEAAAAAAAOAAAAQ2xvc2VBbmRDb21t" + "aXQBAScAAC8BAIc9JwAAAAEB/////wIAAAAXYKkKAgAAAAAADgAAAElucHV0QXJndW1lbnRzAQEoAAAu" + "AEQoAAAAlgAAAAABACgBAQAAAAEAAAAAAAAAAQH/////AAAAABdgqQoCAAAAAAAPAAAAT3V0cHV0QXJn" + "dW1lbnRzAQEpAAAuAEQpAAAAlgAAAAABACgBAQAAAAEAAAAAAAAAAQH/////AAAAAARhggoEAAAAAQAT" + "AAAATGFiZWxzRW5jb2RpbmdFdmVudAEBKgAALwEBKgAqAAAAAQH/////AgAAABdgqQoCAAAAAAAOAAAA" + "SW5wdXRBcmd1bWVudHMBASsAAC4ARCsAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAAF2Cp" + "CgIAAAAAAA8AAABPdXRwdXRBcmd1bWVudHMBASwAAC4ARCwAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAAB" + "Af////8AAAAABGGCCgQAAAABABUAAABMYWJlbHNJbnNwZWN0aW5nRXZlbnQBAS0AAC8BAS0ALQAAAAEB" + "/////wIAAAAXYKkKAgAAAAAADgAAAElucHV0QXJndW1lbnRzAQEuAAAuAEQuAAAAlgAAAAABACgBAQAA" + "AAEAAAAAAAAAAQH/////AAAAABdgqQoCAAAAAAAPAAAAT3V0cHV0QXJndW1lbnRzAQEvAAAuAEQvAAAA" + "lgAAAAABACgBAQAAAAEAAAAAAAAAAQH/////AAAAAARhggoEAAAAAQATAAAATGFiZWxzU2FtcGxpbmdF" + "dmVudAEBMAAALwEBMAAwAAAAAQH/////AgAAABdgqQoCAAAAAAAOAAAASW5wdXRBcmd1bWVudHMBATEA" + "AC4ARDEAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAAF2CpCgIAAAAAAA8AAABPdXRwdXRB" + "cmd1bWVudHMBATIAAC4ARDIAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAABGGCCgQAAAAB" + "ABQAAABMYWJlbHNTY3JhcHBpbmdFdmVudAEBMwAALwEBMwAzAAAAAQH/////AgAAABdgqQoCAAAAAAAO" + "AAAASW5wdXRBcmd1bWVudHMBATQAAC4ARDQAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAA" + "F2CpCgIAAAAAAA8AAABPdXRwdXRBcmd1bWVudHMBATUAAC4ARDUAAACWAAAAAAEAKAEBAAAAAQAAAAAA" + "AAABAf////8AAAAAFWCJCgIAAAABABkAAABNYXhFUENJU2FnZ3JlZ2F0aW9uRXZlbnRzAQE2AAAuAEQ2" + "AAAAAAf/////AwP/////AAAAABVgiQoCAAAAAQAXAAAATWF4RVBDSVNPYmplY3RFdmVudFNJRHMBATcA" + "AC4ARDcAAAAAB/////8DA/////8AAAAAFWCJCgIAAAABAAkAAABNYXhFdmVudHMBATgAAC4ARDgAAAAA" + "B/////8BAf////8AAAAABGGCCgQAAAABABUAAABTSURDb21taXNzaW9uaW5nRXZlbnQBATkAAC8BATkA" + "OQAAAAEB/////wIAAAAXYKkKAgAAAAAADgAAAElucHV0QXJndW1lbnRzAQE6AAAuAEQ6AAAAlgAAAAAB" + "ACgBAQAAAAEAAAAAAAAAAQH/////AAAAABdgqQoCAAAAAAAPAAAAT3V0cHV0QXJndW1lbnRzAQE7AAAu" + "AEQ7AAAAlgAAAAABACgBAQAAAAEAAAAAAAAAAQH/////AAAAAARhggoEAAAAAQAXAAAAU0lERGVjb21t" + "aXNzaW9uaW5nRXZlbnQBATwAAC8BATwAPAAAAAEB/////wIAAAAXYKkKAgAAAAAADgAAAElucHV0QXJn" + "dW1lbnRzAQE9AAAuAEQ9AAAAlgAAAAABACgBAQAAAAEAAAAAAAAAAQH/////AAAAABdgqQoCAAAAAAAP" + "AAAAT3V0cHV0QXJndW1lbnRzAQE+AAAuAEQ+AAAAlgAAAAABACgBAQAAAAEAAAAAAAAAAQH/////AAAA" + "AARhggoEAAAAAQASAAAAU0lERGVzdHJveWluZ0V2ZW50AQE/AAAvAQE/AD8AAAABAf////8CAAAAF2Cp" + "CgIAAAAAAA4AAABJbnB1dEFyZ3VtZW50cwEBQAAALgBEQAAAAJYAAAAAAQAoAQEAAAABAAAAAAAAAAEB" + "/////wAAAAAXYKkKAgAAAAAADwAAAE91dHB1dEFyZ3VtZW50cwEBQQAALgBEQQAAAJYAAAAAAQAoAQEA" + "AAABAAAAAAAAAAEB/////wAAAAAEYYIKBAAAAAEAEgAAAFNJREluc3BlY3RpbmdFdmVudAEBQgAALwEB" + "QgBCAAAAAQH/////AgAAABdgqQoCAAAAAAAOAAAASW5wdXRBcmd1bWVudHMBAUMAAC4AREMAAACWAAAA" + "AAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAAF2CpCgIAAAAAAA8AAABPdXRwdXRBcmd1bWVudHMBAUQA" + "AC4AREQAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAABGGCCgQAAAABABAAAABTSURTaGlw" + "cGluZ0V2ZW50AQFFAAAvAQFFAEUAAAABAf////8CAAAAF2CpCgIAAAAAAA4AAABJbnB1dEFyZ3VtZW50" + "cwEBRgAALgBERgAAAJYAAAAAAQAoAQEAAAABAAAAAAAAAAEB/////wAAAAAXYKkKAgAAAAAADwAAAE91" + "dHB1dEFyZ3VtZW50cwEBRwAALgBERwAAAJYAAAAAAQAoAQEAAAABAAAAAAAAAAEB/////wAAAAAEYYIK" + "BAAAAAEAEwAAAFNOSW52YWxpZGF0aW5nRXZlbnQBAUgAAC8BAUgASAAAAAEB/////wIAAAAXYKkKAgAA" + "AAAADgAAAElucHV0QXJndW1lbnRzAQFJAAAuAERJAAAAlgAAAAABACgBAQAAAAEAAAAAAAAAAQH/////" + "AAAAABdgqQoCAAAAAAAPAAAAT3V0cHV0QXJndW1lbnRzAQFKAAAuAERKAAAAlgAAAAABACgBAQAAAAEA" + "AAAAAAAAAQH/////AAAAAA=="; #endregion #endif #endregion #region Public Properties /// <summary> /// A description for the EPCISStream Object. /// </summary> public TemporaryFileTransferState EPCISStream { get { return m_ePCISStream; } set { if (!Object.ReferenceEquals(m_ePCISStream, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_ePCISStream = value; } } /// <summary> /// A description for the LabelsEncodingEvent Method. /// </summary> public MethodState LabelsEncodingEvent { get { return m_labelsEncodingEventMethod; } set { if (!Object.ReferenceEquals(m_labelsEncodingEventMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_labelsEncodingEventMethod = value; } } /// <summary> /// A description for the LabelsInspectingEvent Method. /// </summary> public MethodState LabelsInspectingEvent { get { return m_labelsInspectingEventMethod; } set { if (!Object.ReferenceEquals(m_labelsInspectingEventMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_labelsInspectingEventMethod = value; } } /// <summary> /// A description for the LabelsSamplingEvent Method. /// </summary> public MethodState LabelsSamplingEvent { get { return m_labelsSamplingEventMethod; } set { if (!Object.ReferenceEquals(m_labelsSamplingEventMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_labelsSamplingEventMethod = value; } } /// <summary> /// A description for the LabelsScrappingEvent Method. /// </summary> public MethodState LabelsScrappingEvent { get { return m_labelsScrappingEventMethod; } set { if (!Object.ReferenceEquals(m_labelsScrappingEventMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_labelsScrappingEventMethod = value; } } /// <summary> /// A description for the MaxEPCISaggregationEvents Property. /// </summary> public PropertyState<uint> MaxEPCISaggregationEvents { get { return m_maxEPCISaggregationEvents; } set { if (!Object.ReferenceEquals(m_maxEPCISaggregationEvents, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_maxEPCISaggregationEvents = value; } } /// <summary> /// A description for the MaxEPCISObjectEventSIDs Property. /// </summary> public PropertyState<uint> MaxEPCISObjectEventSIDs { get { return m_maxEPCISObjectEventSIDs; } set { if (!Object.ReferenceEquals(m_maxEPCISObjectEventSIDs, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_maxEPCISObjectEventSIDs = value; } } /// <summary> /// A description for the MaxEvents Property. /// </summary> public PropertyState<uint> MaxEvents { get { return m_maxEvents; } set { if (!Object.ReferenceEquals(m_maxEvents, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_maxEvents = value; } } /// <summary> /// A description for the SIDCommissioningEvent Method. /// </summary> public MethodState SIDCommissioningEvent { get { return m_sIDCommissioningEventMethod; } set { if (!Object.ReferenceEquals(m_sIDCommissioningEventMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sIDCommissioningEventMethod = value; } } /// <summary> /// A description for the SIDDecommissioningEvent Method. /// </summary> public MethodState SIDDecommissioningEvent { get { return m_sIDDecommissioningEventMethod; } set { if (!Object.ReferenceEquals(m_sIDDecommissioningEventMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sIDDecommissioningEventMethod = value; } } /// <summary> /// A description for the SIDDestroyingEvent Method. /// </summary> public MethodState SIDDestroyingEvent { get { return m_sIDDestroyingEventMethod; } set { if (!Object.ReferenceEquals(m_sIDDestroyingEventMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sIDDestroyingEventMethod = value; } } /// <summary> /// A description for the SIDInspectingEvent Method. /// </summary> public MethodState SIDInspectingEvent { get { return m_sIDInspectingEventMethod; } set { if (!Object.ReferenceEquals(m_sIDInspectingEventMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sIDInspectingEventMethod = value; } } /// <summary> /// A description for the SIDShippingEvent Method. /// </summary> public MethodState SIDShippingEvent { get { return m_sIDShippingEventMethod; } set { if (!Object.ReferenceEquals(m_sIDShippingEventMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sIDShippingEventMethod = value; } } /// <summary> /// A description for the SNInvalidatingEvent Method. /// </summary> public MethodState SNInvalidatingEvent { get { return m_sNInvalidatingEventMethod; } set { if (!Object.ReferenceEquals(m_sNInvalidatingEventMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sNInvalidatingEventMethod = value; } } #endregion #region Overridden Methods /// <summary> /// Populates a list with the children that belong to the node. /// </summary> /// <param name="context">The context for the system being accessed.</param> /// <param name="children">The list of children to populate.</param> public override void GetChildren( ISystemContext context, IList<BaseInstanceState> children) { if (m_ePCISStream != null) { children.Add(m_ePCISStream); } if (m_labelsEncodingEventMethod != null) { children.Add(m_labelsEncodingEventMethod); } if (m_labelsInspectingEventMethod != null) { children.Add(m_labelsInspectingEventMethod); } if (m_labelsSamplingEventMethod != null) { children.Add(m_labelsSamplingEventMethod); } if (m_labelsScrappingEventMethod != null) { children.Add(m_labelsScrappingEventMethod); } if (m_maxEPCISaggregationEvents != null) { children.Add(m_maxEPCISaggregationEvents); } if (m_maxEPCISObjectEventSIDs != null) { children.Add(m_maxEPCISObjectEventSIDs); } if (m_maxEvents != null) { children.Add(m_maxEvents); } if (m_sIDCommissioningEventMethod != null) { children.Add(m_sIDCommissioningEventMethod); } if (m_sIDDecommissioningEventMethod != null) { children.Add(m_sIDDecommissioningEventMethod); } if (m_sIDDestroyingEventMethod != null) { children.Add(m_sIDDestroyingEventMethod); } if (m_sIDInspectingEventMethod != null) { children.Add(m_sIDInspectingEventMethod); } if (m_sIDShippingEventMethod != null) { children.Add(m_sIDShippingEventMethod); } if (m_sNInvalidatingEventMethod != null) { children.Add(m_sNInvalidatingEventMethod); } base.GetChildren(context, children); } /// <summary> /// Finds the child with the specified browse name. /// </summary> protected override BaseInstanceState FindChild( ISystemContext context, QualifiedName browseName, bool createOrReplace, BaseInstanceState replacement) { if (QualifiedName.IsNull(browseName)) { return null; } BaseInstanceState instance = null; switch (browseName.Name) { case Prefix2.BrowseNames.EPCISStream: { if (createOrReplace) { if (EPCISStream == null) { if (replacement == null) { EPCISStream = new TemporaryFileTransferState(this); } else { EPCISStream = (TemporaryFileTransferState)replacement; } } } instance = EPCISStream; break; } case Prefix2.BrowseNames.LabelsEncodingEvent: { if (createOrReplace) { if (LabelsEncodingEvent == null) { if (replacement == null) { LabelsEncodingEvent = new MethodState(this); } else { LabelsEncodingEvent = (MethodState)replacement; } } } instance = LabelsEncodingEvent; break; } case Prefix2.BrowseNames.LabelsInspectingEvent: { if (createOrReplace) { if (LabelsInspectingEvent == null) { if (replacement == null) { LabelsInspectingEvent = new MethodState(this); } else { LabelsInspectingEvent = (MethodState)replacement; } } } instance = LabelsInspectingEvent; break; } case Prefix2.BrowseNames.LabelsSamplingEvent: { if (createOrReplace) { if (LabelsSamplingEvent == null) { if (replacement == null) { LabelsSamplingEvent = new MethodState(this); } else { LabelsSamplingEvent = (MethodState)replacement; } } } instance = LabelsSamplingEvent; break; } case Prefix2.BrowseNames.LabelsScrappingEvent: { if (createOrReplace) { if (LabelsScrappingEvent == null) { if (replacement == null) { LabelsScrappingEvent = new MethodState(this); } else { LabelsScrappingEvent = (MethodState)replacement; } } } instance = LabelsScrappingEvent; break; } case Prefix2.BrowseNames.MaxEPCISaggregationEvents: { if (createOrReplace) { if (MaxEPCISaggregationEvents == null) { if (replacement == null) { MaxEPCISaggregationEvents = new PropertyState<uint>(this); } else { MaxEPCISaggregationEvents = (PropertyState<uint>)replacement; } } } instance = MaxEPCISaggregationEvents; break; } case Prefix2.BrowseNames.MaxEPCISObjectEventSIDs: { if (createOrReplace) { if (MaxEPCISObjectEventSIDs == null) { if (replacement == null) { MaxEPCISObjectEventSIDs = new PropertyState<uint>(this); } else { MaxEPCISObjectEventSIDs = (PropertyState<uint>)replacement; } } } instance = MaxEPCISObjectEventSIDs; break; } case Prefix2.BrowseNames.MaxEvents: { if (createOrReplace) { if (MaxEvents == null) { if (replacement == null) { MaxEvents = new PropertyState<uint>(this); } else { MaxEvents = (PropertyState<uint>)replacement; } } } instance = MaxEvents; break; } case Prefix2.BrowseNames.SIDCommissioningEvent: { if (createOrReplace) { if (SIDCommissioningEvent == null) { if (replacement == null) { SIDCommissioningEvent = new MethodState(this); } else { SIDCommissioningEvent = (MethodState)replacement; } } } instance = SIDCommissioningEvent; break; } case Prefix2.BrowseNames.SIDDecommissioningEvent: { if (createOrReplace) { if (SIDDecommissioningEvent == null) { if (replacement == null) { SIDDecommissioningEvent = new MethodState(this); } else { SIDDecommissioningEvent = (MethodState)replacement; } } } instance = SIDDecommissioningEvent; break; } case Prefix2.BrowseNames.SIDDestroyingEvent: { if (createOrReplace) { if (SIDDestroyingEvent == null) { if (replacement == null) { SIDDestroyingEvent = new MethodState(this); } else { SIDDestroyingEvent = (MethodState)replacement; } } } instance = SIDDestroyingEvent; break; } case Prefix2.BrowseNames.SIDInspectingEvent: { if (createOrReplace) { if (SIDInspectingEvent == null) { if (replacement == null) { SIDInspectingEvent = new MethodState(this); } else { SIDInspectingEvent = (MethodState)replacement; } } } instance = SIDInspectingEvent; break; } case Prefix2.BrowseNames.SIDShippingEvent: { if (createOrReplace) { if (SIDShippingEvent == null) { if (replacement == null) { SIDShippingEvent = new MethodState(this); } else { SIDShippingEvent = (MethodState)replacement; } } } instance = SIDShippingEvent; break; } case Prefix2.BrowseNames.SNInvalidatingEvent: { if (createOrReplace) { if (SNInvalidatingEvent == null) { if (replacement == null) { SNInvalidatingEvent = new MethodState(this); } else { SNInvalidatingEvent = (MethodState)replacement; } } } instance = SNInvalidatingEvent; break; } } if (instance != null) { return instance; } return base.FindChild(context, browseName, createOrReplace, replacement); } #endregion #region Private Fields private TemporaryFileTransferState m_ePCISStream; private MethodState m_labelsEncodingEventMethod; private MethodState m_labelsInspectingEventMethod; private MethodState m_labelsSamplingEventMethod; private MethodState m_labelsScrappingEventMethod; private PropertyState<uint> m_maxEPCISaggregationEvents; private PropertyState<uint> m_maxEPCISObjectEventSIDs; private PropertyState<uint> m_maxEvents; private MethodState m_sIDCommissioningEventMethod; private MethodState m_sIDDecommissioningEventMethod; private MethodState m_sIDDestroyingEventMethod; private MethodState m_sIDInspectingEventMethod; private MethodState m_sIDShippingEventMethod; private MethodState m_sNInvalidatingEventMethod; #endregion } #endif #endregion #region OPENSCSPoolManagerObjectState Class #if (!OPCUA_EXCLUDE_OPENSCSPoolManagerObjectState) /// <summary> /// Stores an instance of the OPENSCSPoolManagerObjectType ObjectType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public partial class OPENSCSPoolManagerObjectState : BaseObjectState { #region Constructors /// <summary> /// Initializes the type with its default attribute values. /// </summary> public OPENSCSPoolManagerObjectState(NodeState parent) : base(parent) { } /// <summary> /// Returns the id of the default type definition node for the instance. /// </summary> protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris) { return Opc.Ua.NodeId.Create(Prefix2.ObjectTypes.OPENSCSPoolManagerObjectType, Prefix2.Namespaces.Name2, namespaceUris); } #if (!OPCUA_EXCLUDE_InitializationStrings) /// <summary> /// Initializes the instance. /// </summary> protected override void Initialize(ISystemContext context) { Initialize(context, InitializationString); InitializeOptionalChildren(context); } protected override void Initialize(ISystemContext context, NodeState source) { InitializeOptionalChildren(context); base.Initialize(context, source); } /// <summary> /// Initializes the any option children defined for the instance. /// </summary> protected override void InitializeOptionalChildren(ISystemContext context) { base.InitializeOptionalChildren(context); } #region Initialization String private const string InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////wRggAABAAAA" + "AQAkAAAAT1BFTlNDU1Bvb2xNYW5hZ2VyT2JqZWN0VHlwZUluc3RhbmNlAQFLAAEBSwD/////DQAAABVg" + "iQoCAAAAAQANAAAATWF4U05QdXNoYWJsZQEBTAAALgBETAAAAAAH/////wEB/////wAAAAAVYIkKAgAA" + "AAEAEAAAAE1heFNOUmVxdWVzdGFibGUBAU0AAC4ARE0AAAAAB/////8BAf////8AAAAAFWCJCgIAAAAB" + "AA8AAABNYXhTTlJldHVybmFibGUBAU4AAC4ARE4AAAAAB/////8BAf////8AAAAAF2CJCgIAAAABABUA" + "AABQb29sU2VsZWN0aW9uQ3JpdGVyaWEBAU8AAC4ARE8AAAABARIAAQAAAAEAAAAAAAAAAQH/////AAAA" + "ABdgiQoCAAAAAQAIAAAAU05Gb3JtYXQBAVAAAC4ARFAAAAAADAEAAAABAAAAAAAAAAEB/////wAAAAAE" + "YYIKBAAAAAEAEgAAAFNOUmVxdWVzdEFsbG9jYXRlZAEBUQAALwEBUQBRAAAAAQH/////AgAAABdgqQoC" + "AAAAAAAOAAAASW5wdXRBcmd1bWVudHMBAVIAAC4ARFIAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf//" + "//8AAAAAF2CpCgIAAAAAAA8AAABPdXRwdXRBcmd1bWVudHMBAVMAAC4ARFMAAACWAAAAAAEAKAEBAAAA" + "AQAAAAAAAAABAf////8AAAAABGGCCgQAAAABABQAAABTTlJlcXVlc3RVbmFsbG9jYXRlZAEBVAAALwEB" + "VABUAAAAAQH/////AgAAABdgqQoCAAAAAAAOAAAASW5wdXRBcmd1bWVudHMBAVUAAC4ARFUAAACWAAAA" + "AAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAAF2CpCgIAAAAAAA8AAABPdXRwdXRBcmd1bWVudHMBAVYA" + "AC4ARFYAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAABGGCCgQAAAABABMAAABTTlJlcXVl" + "c3RVbmFzc2lnbmVkAQFXAAAvAQFXAFcAAAABAf////8CAAAAF2CpCgIAAAAAAA4AAABJbnB1dEFyZ3Vt" + "ZW50cwEBWAAALgBEWAAAAJYAAAAAAQAoAQEAAAABAAAAAAAAAAEB/////wAAAAAXYKkKAgAAAAAADwAA" + "AE91dHB1dEFyZ3VtZW50cwEBWQAALgBEWQAAAJYAAAAAAQAoAQEAAAABAAAAAAAAAAEB/////wAAAAAE" + "YYIKBAAAAAEAEQAAAFNOUmV0dXJuQWxsb2NhdGVkAQFaAAAvAQFaAFoAAAABAf////8CAAAAF2CpCgIA" + "AAAAAA4AAABJbnB1dEFyZ3VtZW50cwEBWwAALgBEWwAAAJYAAAAAAQAoAQEAAAABAAAAAAAAAAEB////" + "/wAAAAAXYKkKAgAAAAAADwAAAE91dHB1dEFyZ3VtZW50cwEBXAAALgBEXAAAAJYAAAAAAQAoAQEAAAAB" + "AAAAAAAAAAEB/////wAAAAAEYYIKBAAAAAEAEwAAAFNOUmV0dXJuVW5hbGxvY2F0ZWQBAV0AAC8BAV0A" + "XQAAAAEB/////wIAAAAXYKkKAgAAAAAADgAAAElucHV0QXJndW1lbnRzAQFeAAAuAEReAAAAlgAAAAAB" + "ACgBAQAAAAEAAAAAAAAAAQH/////AAAAABdgqQoCAAAAAAAPAAAAT3V0cHV0QXJndW1lbnRzAQFfAAAu" + "AERfAAAAlgAAAAABACgBAQAAAAEAAAAAAAAAAQH/////AAAAAARhggoEAAAAAQANAAAAU050b0FsbG9j" + "YXRlZAEBYAAALwEBYABgAAAAAQH/////AgAAABdgqQoCAAAAAAAOAAAASW5wdXRBcmd1bWVudHMBAWEA" + "AC4ARGEAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAAF2CpCgIAAAAAAA8AAABPdXRwdXRB" + "cmd1bWVudHMBAWIAAC4ARGIAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf////8AAAAABGGCCgQAAAAB" + "AAsAAABTTnRvRW5jb2RlZAEBYwAALwEBYwBjAAAAAQH/////AgAAABdgqQoCAAAAAAAOAAAASW5wdXRB" + "cmd1bWVudHMBAWQAAC4ARGQAAACWAAAAAAEAKAEBAAAAAQAAAAMAAAABAf////8AAAAAF2CpCgIAAAAA" + "AA8AAABPdXRwdXRBcmd1bWVudHMBAWUAAC4ARGUAAACWAAAAAAEAKAEBAAAAAQAAAAAAAAABAf////8A" + "AAAABGGCCgQAAAABAA8AAABTTnRvVW5hbGxvY2F0ZWQBAWYAAC8BAWYAZgAAAAEB/////wIAAAAXYKkK" + "AgAAAAAADgAAAElucHV0QXJndW1lbnRzAQFnAAAuAERnAAAAlgAAAAABACgBAQAAAAEAAAAAAAAAAQH/" + "////AAAAABdgqQoCAAAAAAAPAAAAT3V0cHV0QXJndW1lbnRzAQFoAAAuAERoAAAAlgAAAAABACgBAQAA" + "AAEAAAAAAAAAAQH/////AAAAAA=="; #endregion #endif #endregion #region Public Properties /// <summary> /// A description for the MaxSNPushable Property. /// </summary> public PropertyState<uint> MaxSNPushable { get { return m_maxSNPushable; } set { if (!Object.ReferenceEquals(m_maxSNPushable, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_maxSNPushable = value; } } /// <summary> /// A description for the MaxSNRequestable Property. /// </summary> public PropertyState<uint> MaxSNRequestable { get { return m_maxSNRequestable; } set { if (!Object.ReferenceEquals(m_maxSNRequestable, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_maxSNRequestable = value; } } /// <summary> /// A description for the MaxSNReturnable Property. /// </summary> public PropertyState<uint> MaxSNReturnable { get { return m_maxSNReturnable; } set { if (!Object.ReferenceEquals(m_maxSNReturnable, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_maxSNReturnable = value; } } /// <summary> /// A description for the PoolSelectionCriteria Property. /// </summary> public PropertyState<OPENSCSKeyValueDataType[]> PoolSelectionCriteria { get { return m_poolSelectionCriteria; } set { if (!Object.ReferenceEquals(m_poolSelectionCriteria, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_poolSelectionCriteria = value; } } /// <summary> /// A description for the SNFormat Property. /// </summary> public PropertyState<string[]> SNFormat { get { return m_sNFormat; } set { if (!Object.ReferenceEquals(m_sNFormat, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sNFormat = value; } } /// <summary> /// A description for the SNRequestAllocated Method. /// </summary> public MethodState SNRequestAllocated { get { return m_sNRequestAllocatedMethod; } set { if (!Object.ReferenceEquals(m_sNRequestAllocatedMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sNRequestAllocatedMethod = value; } } /// <summary> /// A description for the SNRequestUnallocated Method. /// </summary> public MethodState SNRequestUnallocated { get { return m_sNRequestUnallocatedMethod; } set { if (!Object.ReferenceEquals(m_sNRequestUnallocatedMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sNRequestUnallocatedMethod = value; } } /// <summary> /// A description for the SNRequestUnassigned Method. /// </summary> public MethodState SNRequestUnassigned { get { return m_sNRequestUnassignedMethod; } set { if (!Object.ReferenceEquals(m_sNRequestUnassignedMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sNRequestUnassignedMethod = value; } } /// <summary> /// A description for the SNReturnAllocated Method. /// </summary> public MethodState SNReturnAllocated { get { return m_sNReturnAllocatedMethod; } set { if (!Object.ReferenceEquals(m_sNReturnAllocatedMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sNReturnAllocatedMethod = value; } } /// <summary> /// A description for the SNReturnUnallocated Method. /// </summary> public MethodState SNReturnUnallocated { get { return m_sNReturnUnallocatedMethod; } set { if (!Object.ReferenceEquals(m_sNReturnUnallocatedMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sNReturnUnallocatedMethod = value; } } /// <summary> /// A description for the SNtoAllocated Method. /// </summary> public MethodState SNtoAllocated { get { return m_sNtoAllocatedMethod; } set { if (!Object.ReferenceEquals(m_sNtoAllocatedMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sNtoAllocatedMethod = value; } } /// <summary> /// A description for the SNtoEncoded Method. /// </summary> public MethodState SNtoEncoded { get { return m_sNtoEncodedMethod; } set { if (!Object.ReferenceEquals(m_sNtoEncodedMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sNtoEncodedMethod = value; } } /// <summary> /// A description for the SNtoUnallocated Method. /// </summary> public MethodState SNtoUnallocated { get { return m_sNtoUnallocatedMethod; } set { if (!Object.ReferenceEquals(m_sNtoUnallocatedMethod, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sNtoUnallocatedMethod = value; } } #endregion #region Overridden Methods /// <summary> /// Populates a list with the children that belong to the node. /// </summary> /// <param name="context">The context for the system being accessed.</param> /// <param name="children">The list of children to populate.</param> public override void GetChildren( ISystemContext context, IList<BaseInstanceState> children) { if (m_maxSNPushable != null) { children.Add(m_maxSNPushable); } if (m_maxSNRequestable != null) { children.Add(m_maxSNRequestable); } if (m_maxSNReturnable != null) { children.Add(m_maxSNReturnable); } if (m_poolSelectionCriteria != null) { children.Add(m_poolSelectionCriteria); } if (m_sNFormat != null) { children.Add(m_sNFormat); } if (m_sNRequestAllocatedMethod != null) { children.Add(m_sNRequestAllocatedMethod); } if (m_sNRequestUnallocatedMethod != null) { children.Add(m_sNRequestUnallocatedMethod); } if (m_sNRequestUnassignedMethod != null) { children.Add(m_sNRequestUnassignedMethod); } if (m_sNReturnAllocatedMethod != null) { children.Add(m_sNReturnAllocatedMethod); } if (m_sNReturnUnallocatedMethod != null) { children.Add(m_sNReturnUnallocatedMethod); } if (m_sNtoAllocatedMethod != null) { children.Add(m_sNtoAllocatedMethod); } if (m_sNtoEncodedMethod != null) { children.Add(m_sNtoEncodedMethod); } if (m_sNtoUnallocatedMethod != null) { children.Add(m_sNtoUnallocatedMethod); } base.GetChildren(context, children); } /// <summary> /// Finds the child with the specified browse name. /// </summary> protected override BaseInstanceState FindChild( ISystemContext context, QualifiedName browseName, bool createOrReplace, BaseInstanceState replacement) { if (QualifiedName.IsNull(browseName)) { return null; } BaseInstanceState instance = null; switch (browseName.Name) { case Prefix2.BrowseNames.MaxSNPushable: { if (createOrReplace) { if (MaxSNPushable == null) { if (replacement == null) { MaxSNPushable = new PropertyState<uint>(this); } else { MaxSNPushable = (PropertyState<uint>)replacement; } } } instance = MaxSNPushable; break; } case Prefix2.BrowseNames.MaxSNRequestable: { if (createOrReplace) { if (MaxSNRequestable == null) { if (replacement == null) { MaxSNRequestable = new PropertyState<uint>(this); } else { MaxSNRequestable = (PropertyState<uint>)replacement; } } } instance = MaxSNRequestable; break; } case Prefix2.BrowseNames.MaxSNReturnable: { if (createOrReplace) { if (MaxSNReturnable == null) { if (replacement == null) { MaxSNReturnable = new PropertyState<uint>(this); } else { MaxSNReturnable = (PropertyState<uint>)replacement; } } } instance = MaxSNReturnable; break; } case Prefix2.BrowseNames.PoolSelectionCriteria: { if (createOrReplace) { if (PoolSelectionCriteria == null) { if (replacement == null) { PoolSelectionCriteria = new PropertyState<OPENSCSKeyValueDataType[]>(this); } else { PoolSelectionCriteria = (PropertyState<OPENSCSKeyValueDataType[]>)replacement; } } } instance = PoolSelectionCriteria; break; } case Prefix2.BrowseNames.SNFormat: { if (createOrReplace) { if (SNFormat == null) { if (replacement == null) { SNFormat = new PropertyState<string[]>(this); } else { SNFormat = (PropertyState<string[]>)replacement; } } } instance = SNFormat; break; } case Prefix2.BrowseNames.SNRequestAllocated: { if (createOrReplace) { if (SNRequestAllocated == null) { if (replacement == null) { SNRequestAllocated = new MethodState(this); } else { SNRequestAllocated = (MethodState)replacement; } } } instance = SNRequestAllocated; break; } case Prefix2.BrowseNames.SNRequestUnallocated: { if (createOrReplace) { if (SNRequestUnallocated == null) { if (replacement == null) { SNRequestUnallocated = new MethodState(this); } else { SNRequestUnallocated = (MethodState)replacement; } } } instance = SNRequestUnallocated; break; } case Prefix2.BrowseNames.SNRequestUnassigned: { if (createOrReplace) { if (SNRequestUnassigned == null) { if (replacement == null) { SNRequestUnassigned = new MethodState(this); } else { SNRequestUnassigned = (MethodState)replacement; } } } instance = SNRequestUnassigned; break; } case Prefix2.BrowseNames.SNReturnAllocated: { if (createOrReplace) { if (SNReturnAllocated == null) { if (replacement == null) { SNReturnAllocated = new MethodState(this); } else { SNReturnAllocated = (MethodState)replacement; } } } instance = SNReturnAllocated; break; } case Prefix2.BrowseNames.SNReturnUnallocated: { if (createOrReplace) { if (SNReturnUnallocated == null) { if (replacement == null) { SNReturnUnallocated = new MethodState(this); } else { SNReturnUnallocated = (MethodState)replacement; } } } instance = SNReturnUnallocated; break; } case Prefix2.BrowseNames.SNtoAllocated: { if (createOrReplace) { if (SNtoAllocated == null) { if (replacement == null) { SNtoAllocated = new MethodState(this); } else { SNtoAllocated = (MethodState)replacement; } } } instance = SNtoAllocated; break; } case Prefix2.BrowseNames.SNtoEncoded: { if (createOrReplace) { if (SNtoEncoded == null) { if (replacement == null) { SNtoEncoded = new MethodState(this); } else { SNtoEncoded = (MethodState)replacement; } } } instance = SNtoEncoded; break; } case Prefix2.BrowseNames.SNtoUnallocated: { if (createOrReplace) { if (SNtoUnallocated == null) { if (replacement == null) { SNtoUnallocated = new MethodState(this); } else { SNtoUnallocated = (MethodState)replacement; } } } instance = SNtoUnallocated; break; } } if (instance != null) { return instance; } return base.FindChild(context, browseName, createOrReplace, replacement); } #endregion #region Private Fields private PropertyState<uint> m_maxSNPushable; private PropertyState<uint> m_maxSNRequestable; private PropertyState<uint> m_maxSNReturnable; private PropertyState<OPENSCSKeyValueDataType[]> m_poolSelectionCriteria; private PropertyState<string[]> m_sNFormat; private MethodState m_sNRequestAllocatedMethod; private MethodState m_sNRequestUnallocatedMethod; private MethodState m_sNRequestUnassignedMethod; private MethodState m_sNReturnAllocatedMethod; private MethodState m_sNReturnUnallocatedMethod; private MethodState m_sNtoAllocatedMethod; private MethodState m_sNtoEncodedMethod; private MethodState m_sNtoUnallocatedMethod; #endregion } #endif #endregion #region OPENSCSSIDClassObjectState Class #if (!OPCUA_EXCLUDE_OPENSCSSIDClassObjectState) /// <summary> /// Stores an instance of the OPENSCSSIDClassObjectType ObjectType. /// </summary> /// <exclude /> [System.CodeDom.Compiler.GeneratedCodeAttribute("Opc.Ua.ModelCompiler", "1.0.0.0")] public partial class OPENSCSSIDClassObjectState : BaseObjectState { #region Constructors /// <summary> /// Initializes the type with its default attribute values. /// </summary> public OPENSCSSIDClassObjectState(NodeState parent) : base(parent) { } /// <summary> /// Returns the id of the default type definition node for the instance. /// </summary> protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris) { return Opc.Ua.NodeId.Create(Prefix2.ObjectTypes.OPENSCSSIDClassObjectType, Prefix2.Namespaces.Name2, namespaceUris); } #if (!OPCUA_EXCLUDE_InitializationStrings) /// <summary> /// Initializes the instance. /// </summary> protected override void Initialize(ISystemContext context) { Initialize(context, InitializationString); InitializeOptionalChildren(context); } protected override void Initialize(ISystemContext context, NodeState source) { InitializeOptionalChildren(context); base.Initialize(context, source); } /// <summary> /// Initializes the any option children defined for the instance. /// </summary> protected override void InitializeOptionalChildren(ISystemContext context) { base.InitializeOptionalChildren(context); if (IntendedUse != null) { IntendedUse.Initialize(context, IntendedUse_InitializationString); } if (SIDClassDescription != null) { SIDClassDescription.Initialize(context, SIDClassDescription_InitializationString); } if (SIDClassProperty != null) { SIDClassProperty.Initialize(context, SIDClassProperty_InitializationString); } } #region Initialization String private const string IntendedUse_InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////xVgiQoCAAAA" + "AQALAAAASW50ZW5kZWRVc2UBAWsAAC4ARGsAAAAADP////8BAf////8AAAAA"; private const string SIDClassDescription_InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////xVgiQoCAAAA" + "AQATAAAAU0lEQ2xhc3NEZXNjcmlwdGlvbgEBbAAALgBEbAAAAAAM/////wEB/////wAAAAA="; private const string SIDClassProperty_InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////xdgiQoCAAAA" + "AQAQAAAAU0lEQ2xhc3NQcm9wZXJ0eQEBbwAALgBEbwAAAAEBFQABAAAAAQAAAAAAAAADA/////8AAAAA"; private const string InitializationString = "AQAAACgAAABodHRwOi8vb3BjZm91bmRhdGlvbi5vcmcvVUEvT1BFTlNDUy1TRVIv/////wRggAABAAAA" + "AQAhAAAAT1BFTlNDU1NJRENsYXNzT2JqZWN0VHlwZUluc3RhbmNlAQFpAAEBaQD/////BwAAABVgiQoC" + "AAAAAQATAAAAQWxsb3dlZENoYXJhY3RlclNldAEBagAALgBEagAAAAAM/////wEB/////wAAAAAVYIkK" + "AgAAAAEACwAAAEludGVuZGVkVXNlAQFrAAAuAERrAAAAAAz/////AQH/////AAAAABVgiQoCAAAAAQAT" + "AAAAU0lEQ2xhc3NEZXNjcmlwdGlvbgEBbAAALgBEbAAAAAAM/////wEB/////wAAAAAVYIkKAgAAAAEA" + "CgAAAFNJRENsYXNzSUQBAW0AAC4ARG0AAAAADP////8BAf////8AAAAAFWCJCgIAAAABAA0AAABTSURD" + "bGFzc093bmVyAQFuAAAuAERuAAAAAAz/////AQH/////AAAAABdgiQoCAAAAAQAQAAAAU0lEQ2xhc3NQ" + "cm9wZXJ0eQEBbwAALgBEbwAAAAEBFQABAAAAAQAAAAAAAAADA/////8AAAAAFWCJCgIAAAABABMAAABT" + "eW50YXhTcGVjaWZpY2F0aW9uAQFwAAAuAERwAAAAAAz/////AQH/////AAAAAA=="; #endregion #endif #endregion #region Public Properties /// <summary> /// A description for the AllowedCharacterSet Property. /// </summary> public PropertyState<string> AllowedCharacterSet { get { return m_allowedCharacterSet; } set { if (!Object.ReferenceEquals(m_allowedCharacterSet, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_allowedCharacterSet = value; } } /// <summary> /// A description for the IntendedUse Property. /// </summary> public PropertyState<string> IntendedUse { get { return m_ıntendedUse; } set { if (!Object.ReferenceEquals(m_ıntendedUse, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_ıntendedUse = value; } } /// <summary> /// A description for the SIDClassDescription Property. /// </summary> public PropertyState<string> SIDClassDescription { get { return m_sIDClassDescription; } set { if (!Object.ReferenceEquals(m_sIDClassDescription, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sIDClassDescription = value; } } /// <summary> /// A description for the SIDClassID Property. /// </summary> public PropertyState<string> SIDClassID { get { return m_sIDClassID; } set { if (!Object.ReferenceEquals(m_sIDClassID, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sIDClassID = value; } } /// <summary> /// A description for the SIDClassOwner Property. /// </summary> public PropertyState<string> SIDClassOwner { get { return m_sIDClassOwner; } set { if (!Object.ReferenceEquals(m_sIDClassOwner, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sIDClassOwner = value; } } /// <summary> /// A description for the SIDClassProperty Property. /// </summary> public PropertyState<OPENSCSSIDClassPropertyDataType[]> SIDClassProperty { get { return m_sIDClassProperty; } set { if (!Object.ReferenceEquals(m_sIDClassProperty, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_sIDClassProperty = value; } } /// <summary> /// A description for the SyntaxSpecification Property. /// </summary> public PropertyState<string> SyntaxSpecification { get { return m_syntaxSpecification; } set { if (!Object.ReferenceEquals(m_syntaxSpecification, value)) { ChangeMasks |= NodeStateChangeMasks.Children; } m_syntaxSpecification = value; } } #endregion #region Overridden Methods /// <summary> /// Populates a list with the children that belong to the node. /// </summary> /// <param name="context">The context for the system being accessed.</param> /// <param name="children">The list of children to populate.</param> public override void GetChildren( ISystemContext context, IList<BaseInstanceState> children) { if (m_allowedCharacterSet != null) { children.Add(m_allowedCharacterSet); } if (m_ıntendedUse != null) { children.Add(m_ıntendedUse); } if (m_sIDClassDescription != null) { children.Add(m_sIDClassDescription); } if (m_sIDClassID != null) { children.Add(m_sIDClassID); } if (m_sIDClassOwner != null) { children.Add(m_sIDClassOwner); } if (m_sIDClassProperty != null) { children.Add(m_sIDClassProperty); } if (m_syntaxSpecification != null) { children.Add(m_syntaxSpecification); } base.GetChildren(context, children); } /// <summary> /// Finds the child with the specified browse name. /// </summary> protected override BaseInstanceState FindChild( ISystemContext context, QualifiedName browseName, bool createOrReplace, BaseInstanceState replacement) { if (QualifiedName.IsNull(browseName)) { return null; } BaseInstanceState instance = null; switch (browseName.Name) { case Prefix2.BrowseNames.AllowedCharacterSet: { if (createOrReplace) { if (AllowedCharacterSet == null) { if (replacement == null) { AllowedCharacterSet = new PropertyState<string>(this); } else { AllowedCharacterSet = (PropertyState<string>)replacement; } } } instance = AllowedCharacterSet; break; } case Prefix2.BrowseNames.IntendedUse: { if (createOrReplace) { if (IntendedUse == null) { if (replacement == null) { IntendedUse = new PropertyState<string>(this); } else { IntendedUse = (PropertyState<string>)replacement; } } } instance = IntendedUse; break; } case Prefix2.BrowseNames.SIDClassDescription: { if (createOrReplace) { if (SIDClassDescription == null) { if (replacement == null) { SIDClassDescription = new PropertyState<string>(this); } else { SIDClassDescription = (PropertyState<string>)replacement; } } } instance = SIDClassDescription; break; } case Prefix2.BrowseNames.SIDClassID: { if (createOrReplace) { if (SIDClassID == null) { if (replacement == null) { SIDClassID = new PropertyState<string>(this); } else { SIDClassID = (PropertyState<string>)replacement; } } } instance = SIDClassID; break; } case Prefix2.BrowseNames.SIDClassOwner: { if (createOrReplace) { if (SIDClassOwner == null) { if (replacement == null) { SIDClassOwner = new PropertyState<string>(this); } else { SIDClassOwner = (PropertyState<string>)replacement; } } } instance = SIDClassOwner; break; } case Prefix2.BrowseNames.SIDClassProperty: { if (createOrReplace) { if (SIDClassProperty == null) { if (replacement == null) { SIDClassProperty = new PropertyState<OPENSCSSIDClassPropertyDataType[]>(this); } else { SIDClassProperty = (PropertyState<OPENSCSSIDClassPropertyDataType[]>)replacement; } } } instance = SIDClassProperty; break; } case Prefix2.BrowseNames.SyntaxSpecification: { if (createOrReplace) { if (SyntaxSpecification == null) { if (replacement == null) { SyntaxSpecification = new PropertyState<string>(this); } else { SyntaxSpecification = (PropertyState<string>)replacement; } } } instance = SyntaxSpecification; break; } } if (instance != null) { return instance; } return base.FindChild(context, browseName, createOrReplace, replacement); } #endregion #region Private Fields private PropertyState<string> m_allowedCharacterSet; private PropertyState<string> m_ıntendedUse; private PropertyState<string> m_sIDClassDescription; private PropertyState<string> m_sIDClassID; private PropertyState<string> m_sIDClassOwner; private PropertyState<OPENSCSSIDClassPropertyDataType[]> m_sIDClassProperty; private PropertyState<string> m_syntaxSpecification; #endregion } #endif #endregion }
39.434712
404
0.618301
[ "MIT" ]
mertyusaatag/UA-Nodeset
OpenSCS/ModelDesign/Opc.Ua.OPENSCS.Model/Prefix2.Classes.cs
291,760
C#
namespace CodeComb.CodeAnalysis.OmniSharp.Models { public class PackageRestoreMessage { public string FileName { get; set; } public bool Succeeded { get; set; } } }
24
48
0.661458
[ "Apache-2.0" ]
CodeComb/CodeComb.CodeAnalysis.OmniSharp
src/CodeComb.CodeAnalysis.OmniSharp/Models/v1/PackageRestoreMessage.cs
192
C#
using System; using System.Data.OleDb; using System.Text; using Tortuga.Chain.Core; using Tortuga.Chain.Materializers; namespace Tortuga.Chain.SqlServer.CommandBuilders { /// <summary> /// Class SqlServerDeleteObject. /// </summary> internal sealed class OleDbSqlServerDeleteObject<TArgument> : OleDbSqlServerObjectCommand<TArgument> where TArgument : class { readonly DeleteOptions m_Options; /// <summary> /// Initializes a new instance of the <see cref="OleDbSqlServerDeleteObject{TArgument}"/> class. /// </summary> /// <param name="dataSource">The data source.</param> /// <param name="tableName">Name of the table.</param> /// <param name="argumentValue">The argument value.</param> /// <param name="options">The options.</param> public OleDbSqlServerDeleteObject(OleDbSqlServerDataSourceBase dataSource, SqlServerObjectName tableName, TArgument argumentValue, DeleteOptions options) : base(dataSource, tableName, argumentValue) { m_Options = options; } /// <summary> /// Prepares the command for execution by generating any necessary SQL. /// </summary> /// <param name="materializer">The materializer.</param> /// <returns>ExecutionToken&lt;TCommand&gt;.</returns> public override CommandExecutionToken<OleDbCommand, OleDbParameter> Prepare(Materializer<OleDbCommand, OleDbParameter> materializer) { if (materializer == null) throw new ArgumentNullException(nameof(materializer), $"{nameof(materializer)} is null."); var sqlBuilder = Table.CreateSqlBuilder(StrictMode); var desiredColumns = materializer.DesiredColumns(); sqlBuilder.ApplyArgumentValue(DataSource, ArgumentValue, m_Options, desiredColumns == Materializer.NoColumns); sqlBuilder.ApplyDesiredColumns(desiredColumns); if (KeyColumns.Count > 0) sqlBuilder.OverrideKeys(KeyColumns); var sql = new StringBuilder(); string? header; string? intoClause; string? footer; sqlBuilder.UseTableVariable(Table, out header, out intoClause, out footer); sql.Append(header); sql.Append("DELETE FROM " + Table.Name.ToQuotedString()); sqlBuilder.BuildSelectClause(sql, " OUTPUT ", "Deleted.", intoClause); sqlBuilder.BuildAnonymousWhereClause(sql, " WHERE ", null, true); sql.Append(";"); sql.Append(footer); return new OleDbCommandExecutionToken(DataSource, "Delete from " + Table.Name, sql.ToString(), sqlBuilder.GetParameters()).CheckDeleteRowCount(m_Options); } } }
37.615385
200
0.743967
[ "MIT" ]
TortugaResearch/Chain
Tortuga.Chain/Tortuga.Chain.SqlServer.OleDb/SqlServer/CommandBuilders/OleDbSqlServerDeleteObject.cs
2,447
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Threading; // FROM http://stackoverflow.com/questions/18922985/concurrent-hashsett-in-net-framework namespace Sidekick.AuditLog { [DebuggerDisplay("Count = {Count}")] [Serializable] public class ConcurrentHashSet<T> : ISet<T> { private readonly ReaderWriterLockSlim _lock = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); private readonly SortedSet<T> _hashSet = new SortedSet<T>(); public ConcurrentHashSet() { } public ConcurrentHashSet(IEnumerable<T> collection) { _hashSet = new SortedSet<T>(collection); } #region Dispose public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) if (_lock != null) _lock.Dispose(); } public IEnumerator<T> GetEnumerator() { return _hashSet.GetEnumerator(); } ~ConcurrentHashSet() { Dispose(false); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion public void Add(T item) { _lock.EnterWriteLock(); try { _hashSet.Add(item); } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); } } public void UnionWith(IEnumerable<T> other) { _lock.EnterWriteLock(); _lock.EnterReadLock(); try { _hashSet.UnionWith(other); } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); if (_lock.IsReadLockHeld) _lock.ExitReadLock(); } } public void IntersectWith(IEnumerable<T> other) { _lock.EnterWriteLock(); _lock.EnterReadLock(); try { _hashSet.IntersectWith(other); } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); if (_lock.IsReadLockHeld) _lock.ExitReadLock(); } } public void ExceptWith(IEnumerable<T> other) { _lock.EnterWriteLock(); _lock.EnterReadLock(); try { _hashSet.ExceptWith(other); } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); if (_lock.IsReadLockHeld) _lock.ExitReadLock(); } } public void SymmetricExceptWith(IEnumerable<T> other) { _lock.EnterWriteLock(); try { _hashSet.SymmetricExceptWith(other); } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); } } public bool IsSubsetOf(IEnumerable<T> other) { _lock.EnterWriteLock(); try { return _hashSet.IsSubsetOf(other); } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); } } public bool IsSupersetOf(IEnumerable<T> other) { _lock.EnterWriteLock(); try { return _hashSet.IsSupersetOf(other); } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); } } public bool IsProperSupersetOf(IEnumerable<T> other) { _lock.EnterWriteLock(); try { return _hashSet.IsProperSupersetOf(other); } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); } } public bool IsProperSubsetOf(IEnumerable<T> other) { _lock.EnterWriteLock(); try { return _hashSet.IsProperSubsetOf(other); } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); } } public bool Overlaps(IEnumerable<T> other) { _lock.EnterWriteLock(); try { return _hashSet.Overlaps(other); } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); } } public bool SetEquals(IEnumerable<T> other) { _lock.EnterWriteLock(); try { return _hashSet.SetEquals(other); } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); } } bool ISet<T>.Add(T item) { _lock.EnterWriteLock(); try { return _hashSet.Add(item); } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); } } public void Clear() { _lock.EnterWriteLock(); try { _hashSet.Clear(); } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); } } public bool Contains(T item) { _lock.EnterWriteLock(); try { return _hashSet.Contains(item); } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); } } public void CopyTo(T[] array, int arrayIndex) { _lock.EnterWriteLock(); try { _hashSet.CopyTo(array, arrayIndex); } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); } } public bool Remove(T item) { _lock.EnterWriteLock(); try { return _hashSet.Remove(item); } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); } } public int Count { get { _lock.EnterWriteLock(); try { return _hashSet.Count; } finally { if (_lock.IsWriteLockHeld) _lock.ExitWriteLock(); } } } public bool IsReadOnly => false; } }
16.696246
112
0.643295
[ "MIT" ]
JeffDarchuk/SitecoreSidekick
ScsAuditLog/ConcurrentHashSet.cs
4,894
C#
/* MapleLib - A general-purpose MapleStory library * Copyright (C) 2009, 2010, 2015 Snow and haha01haha01 * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.*/ using System.Collections.Generic; using System.IO; using MapleLib.WzLib.Util; using System; using System.Drawing; namespace MapleLib.WzLib.WzProperties { /// <summary> /// A property that can contain sub properties and has one png image /// </summary> public class WzCanvasProperty : WzExtended, IPropertyContainer { #region Constants /// <summary> /// The propertyname used for inlink /// </summary> public const string InlinkPropertyName = "_inlink"; public const string OutlinkPropertyName = "_outlink"; public const string OriginPropertyName = "origin"; public const string HeadPropertyName = "head"; public const string LtPropertyName = "lt"; public const string AnimationDelayPropertyName = "delay"; #endregion #region Fields internal List<WzImageProperty> properties = new List<WzImageProperty>(); internal WzPngProperty imageProp; internal string name; internal WzObject parent; //internal WzImage imgParent; #endregion #region Inherited Members public override void SetValue(object value) { imageProp.SetValue(value); } public override WzImageProperty DeepClone() { WzCanvasProperty clone = new WzCanvasProperty(name); foreach (WzImageProperty prop in properties) { clone.AddProperty(prop.DeepClone()); } clone.imageProp = (WzPngProperty)imageProp.DeepClone(); return clone; } public override object WzValue { get { return PngProperty; } } /// <summary> /// The parent of the object /// </summary> public override WzObject Parent { get { return parent; } internal set { parent = value; } } /// <summary> /// The WzPropertyType of the property /// </summary> public override WzPropertyType PropertyType { get { return WzPropertyType.Canvas; } } /// <summary> /// The properties contained in this property /// </summary> public override List<WzImageProperty> WzProperties { get { return properties; } } /// <summary> /// The name of the property /// </summary> public override string Name { get { return name; } set { name = value; } } /// <summary> /// Gets a wz property by it's name /// </summary> /// <param name="name">The name of the property</param> /// <returns>The wz property with the specified name</returns> public override WzImageProperty this[string name] { get { if (name == "PNG") return imageProp; foreach (WzImageProperty iwp in properties) if (iwp.Name.ToLower() == name.ToLower()) return iwp; return null; } set { if (value != null) { if (name == "PNG") { imageProp = (WzPngProperty)value; return; } value.Name = name; AddProperty(value); } } } public WzImageProperty GetProperty(string name) { foreach (WzImageProperty iwp in properties) if (iwp.Name.ToLower() == name.ToLower()) return iwp; return null; } /// Gets a wz property by a path name /// </summary> /// <param name="path">path to property</param> /// <returns>the wz property with the specified name</returns> public override WzImageProperty GetFromPath(string path) { string[] segments = path.Split(new char[1] { '/' }, System.StringSplitOptions.RemoveEmptyEntries); if (segments[0] == "..") { return ((WzImageProperty)Parent)[path.Substring(name.IndexOf('/') + 1)]; } WzImageProperty ret = this; for (int x = 0; x < segments.Length; x++) { bool foundChild = false; if (segments[x] == "PNG") { return imageProp; } foreach (WzImageProperty iwp in ret.WzProperties) { if (iwp.Name == segments[x]) { ret = iwp; foundChild = true; break; } } if (!foundChild) { return null; } } return ret; } public override void WriteValue(MapleLib.WzLib.Util.WzBinaryWriter writer) { writer.WriteStringValue("Canvas", 0x73, 0x1B); writer.Write((byte)0); if (properties.Count > 0) // subproperty in the canvas { writer.Write((byte)1); WzImageProperty.WritePropertyList(writer, properties); } else { writer.Write((byte)0); } // Image info writer.WriteCompressedInt(PngProperty.Width); writer.WriteCompressedInt(PngProperty.Height); writer.WriteCompressedInt(PngProperty.Format); writer.Write((byte)PngProperty.Format2); writer.Write((Int32)0); // Write image byte[] bytes = PngProperty.GetCompressedBytes(false); writer.Write(bytes.Length + 1); writer.Write((byte)0); // header? see WzImageProperty.ParseExtendedProp "0x00" writer.Write(bytes); } public override void ExportXml(StreamWriter writer, int level) { writer.WriteLine(XmlUtil.Indentation(level) + XmlUtil.OpenNamedTag("WzCanvas", this.Name, false, false) + XmlUtil.Attrib("width", PngProperty.Width.ToString()) + XmlUtil.Attrib("height", PngProperty.Height.ToString(), true, false)); WzImageProperty.DumpPropertyList(writer, level, this.WzProperties); writer.WriteLine(XmlUtil.Indentation(level) + XmlUtil.CloseTag("WzCanvas")); } /// <summary> /// Dispose the object /// </summary> public override void Dispose() { name = null; imageProp.Dispose(); imageProp = null; foreach (WzImageProperty prop in properties) { prop.Dispose(); } properties.Clear(); properties = null; } #endregion #region Custom Members /// <summary> /// Gets the 'origin' position of the Canvas /// If not available, it defaults to xy of 0, 0 /// </summary> /// <returns></returns> public PointF GetCanvasOriginPosition() { WzVectorProperty originPos = (WzVectorProperty)this[OriginPropertyName]; if (originPos != null) return new PointF(originPos.X.Value, originPos.Y.Value); return new PointF(0, 0); } /// <summary> /// Gets the 'head' position of the Canvas /// If not available, it defaults to xy of 0, 0 /// </summary> /// <returns></returns> public PointF GetCanvasHeadPosition() { WzVectorProperty headPos = (WzVectorProperty)this[HeadPropertyName]; if (headPos != null) return new PointF(headPos.X.Value, headPos.Y.Value); return new PointF(0, 0); } /// <summary> /// Gets the 'head' position of the Canvas /// If not available, it defaults to xy of 0, 0 /// </summary> /// <returns></returns> public PointF GetCanvasLtPosition() { WzVectorProperty headPos = (WzVectorProperty)this[LtPropertyName]; if (headPos != null) return new PointF(headPos.X.Value, headPos.Y.Value); return new PointF(0, 0); } /// <summary> /// Gets whether this WzCanvasProperty contains an '_inlink' for modern maplestory version. v150++ /// </summary> /// <returns></returns> public bool HaveInlinkProperty() { return this[InlinkPropertyName] != null; } /// <summary> /// Gets whether this WzCanvasProperty contains an '_outlink' for modern maplestory version. v150++ /// </summary> /// <returns></returns> public bool HaveOutlinkProperty() { return this[OutlinkPropertyName] != null; } /// <summary> /// Gets the '_inlink' WzCanvasProperty of this. /// /// '_inlink' is not implemented as part of WzCanvasProperty as I dont want to override existing Wz structure. /// It will be handled via HaRepackerMainPanel instead. /// </summary> /// <returns></returns> public Bitmap GetLinkedWzCanvasBitmap() { return GetLinkedWzImageProperty().GetBitmap(); } /// <summary> /// Gets the '_inlink' WzCanvasProperty of this. /// /// '_inlink' is not implemented as part of WzCanvasProperty as I dont want to override existing Wz structure. /// It will be handled via HaRepackerMainPanel instead. /// </summary> /// <returns></returns> public WzImageProperty GetLinkedWzImageProperty() { string _inlink = ((WzStringProperty)this[InlinkPropertyName])?.Value; // could get nexon'd here. In case they place an _inlink that's not WzStringProperty string _outlink = ((WzStringProperty)this[OutlinkPropertyName])?.Value; // could get nexon'd here. In case they place an _outlink that's not WzStringProperty if (_inlink != null) { WzObject currentWzObj = this; // first object to work with while ((currentWzObj = currentWzObj.Parent) != null) { if (!(currentWzObj is WzImage)) // keep looping if its not a WzImage continue; WzImage wzImageParent = (WzImage)currentWzObj; WzImageProperty foundProperty = wzImageParent.GetFromPath(_inlink); if (foundProperty != null && foundProperty is WzImageProperty property) { return property; } } } else if (_outlink != null) { WzObject currentWzObj = this; // first object to work with while ((currentWzObj = currentWzObj.Parent) != null) { if (!(currentWzObj is WzDirectory)) // keep looping if its not a WzImage continue; WzFile wzFileParent = ((WzDirectory)currentWzObj).wzFile; WzObject foundProperty = wzFileParent.GetObjectFromPath(_outlink); if (foundProperty != null && foundProperty is WzImageProperty property) { return property; } } } return this; } /// <summary> /// The png image for this canvas property /// </summary> public WzPngProperty PngProperty { get { return imageProp; } set { imageProp = value; } } /// <summary> /// Creates a blank WzCanvasProperty /// </summary> public WzCanvasProperty() { } /// <summary> /// Creates a WzCanvasProperty with the specified name /// </summary> /// <param name="name">The name of the property</param> public WzCanvasProperty(string name) { this.name = name; } /// <summary> /// Adds a property to the property list of this property /// </summary> /// <param name="prop">The property to add</param> public void AddProperty(WzImageProperty prop) { prop.Parent = this; properties.Add(prop); } public void AddProperties(List<WzImageProperty> props) { foreach (WzImageProperty prop in props) { AddProperty(prop); } } /// <summary> /// Remove a property /// </summary> /// <param name="name">Name of Property</param> public void RemoveProperty(WzImageProperty prop) { prop.Parent = null; properties.Remove(prop); } /// <summary> /// Clears the list of properties /// </summary> public void ClearProperties() { foreach (WzImageProperty prop in properties) prop.Parent = null; properties.Clear(); } #endregion #region Cast Values public override Bitmap GetBitmap() { return imageProp.GetImage(false); } #endregion } }
35.080685
169
0.531642
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
MapleSeraph/Harepacker-resurrected
MapleLib/WzLib/WzProperties/WzCanvasProperty.cs
14,350
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the transfer-2018-11-05.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Transfer.Model { /// <summary> /// Describes the properties of a file transfer protocol-enabled server that was specified. /// </summary> public partial class DescribedServer { private string _arn; private string _certificate; private EndpointDetails _endpointDetails; private EndpointType _endpointType; private string _hostKeyFingerprint; private IdentityProviderDetails _identityProviderDetails; private IdentityProviderType _identityProviderType; private string _loggingRole; private List<string> _protocols = new List<string>(); private string _securityPolicyName; private string _serverId; private State _state; private List<Tag> _tags = new List<Tag>(); private int? _userCount; /// <summary> /// Gets and sets the property Arn. /// <para> /// Specifies the unique Amazon Resource Name (ARN) of the server. /// </para> /// </summary> [AWSProperty(Required=true, Min=20, Max=1600)] public string Arn { get { return this._arn; } set { this._arn = value; } } // Check to see if Arn property is set internal bool IsSetArn() { return this._arn != null; } /// <summary> /// Gets and sets the property Certificate. /// <para> /// Specifies the ARN of the AWS Certificate Manager (ACM) certificate. Required when /// <code>Protocols</code> is set to <code>FTPS</code>. /// </para> /// </summary> [AWSProperty(Max=1600)] public string Certificate { get { return this._certificate; } set { this._certificate = value; } } // Check to see if Certificate property is set internal bool IsSetCertificate() { return this._certificate != null; } /// <summary> /// Gets and sets the property EndpointDetails. /// <para> /// Specifies the virtual private cloud (VPC) endpoint settings that you configured for /// your server. /// </para> /// </summary> public EndpointDetails EndpointDetails { get { return this._endpointDetails; } set { this._endpointDetails = value; } } // Check to see if EndpointDetails property is set internal bool IsSetEndpointDetails() { return this._endpointDetails != null; } /// <summary> /// Gets and sets the property EndpointType. /// <para> /// Defines the type of endpoint that your server is connected to. If your server is connected /// to a VPC endpoint, your server isn't accessible over the public internet. /// </para> /// </summary> public EndpointType EndpointType { get { return this._endpointType; } set { this._endpointType = value; } } // Check to see if EndpointType property is set internal bool IsSetEndpointType() { return this._endpointType != null; } /// <summary> /// Gets and sets the property HostKeyFingerprint. /// <para> /// Specifies the Base64-encoded SHA256 fingerprint of the server's host key. This value /// is equivalent to the output of the <code>ssh-keygen -l -f my-new-server-key</code> /// command. /// </para> /// </summary> public string HostKeyFingerprint { get { return this._hostKeyFingerprint; } set { this._hostKeyFingerprint = value; } } // Check to see if HostKeyFingerprint property is set internal bool IsSetHostKeyFingerprint() { return this._hostKeyFingerprint != null; } /// <summary> /// Gets and sets the property IdentityProviderDetails. /// <para> /// Specifies information to call a customer-supplied authentication API. This field is /// not populated when the <code>IdentityProviderType</code> of a server is <code>SERVICE_MANAGED</code>. /// </para> /// </summary> public IdentityProviderDetails IdentityProviderDetails { get { return this._identityProviderDetails; } set { this._identityProviderDetails = value; } } // Check to see if IdentityProviderDetails property is set internal bool IsSetIdentityProviderDetails() { return this._identityProviderDetails != null; } /// <summary> /// Gets and sets the property IdentityProviderType. /// <para> /// Specifies the mode of authentication method enabled for this service. A value of <code>SERVICE_MANAGED</code> /// means that you are using this server to store and access user credentials within the /// service. A value of <code>API_GATEWAY</code> indicates that you have integrated an /// API Gateway endpoint that will be invoked for authenticating your user into the service. /// </para> /// </summary> public IdentityProviderType IdentityProviderType { get { return this._identityProviderType; } set { this._identityProviderType = value; } } // Check to see if IdentityProviderType property is set internal bool IsSetIdentityProviderType() { return this._identityProviderType != null; } /// <summary> /// Gets and sets the property LoggingRole. /// <para> /// Specifies the AWS Identity and Access Management (IAM) role that allows a server to /// turn on Amazon CloudWatch logging for Amazon S3 events. When set, user activity can /// be viewed in your CloudWatch logs. /// </para> /// </summary> [AWSProperty(Min=20, Max=2048)] public string LoggingRole { get { return this._loggingRole; } set { this._loggingRole = value; } } // Check to see if LoggingRole property is set internal bool IsSetLoggingRole() { return this._loggingRole != null; } /// <summary> /// Gets and sets the property Protocols. /// <para> /// Specifies the file transfer protocol or protocols over which your file transfer protocol /// client can connect to your server's endpoint. The available protocols are: /// </para> /// <ul> <li> /// <para> /// <code>SFTP</code> (Secure Shell (SSH) File Transfer Protocol): File transfer over /// SSH /// </para> /// </li> <li> /// <para> /// <code>FTPS</code> (File Transfer Protocol Secure): File transfer with TLS encryption /// </para> /// </li> <li> /// <para> /// <code>FTP</code> (File Transfer Protocol): Unencrypted file transfer /// </para> /// </li> </ul> /// </summary> [AWSProperty(Min=1, Max=3)] public List<string> Protocols { get { return this._protocols; } set { this._protocols = value; } } // Check to see if Protocols property is set internal bool IsSetProtocols() { return this._protocols != null && this._protocols.Count > 0; } /// <summary> /// Gets and sets the property SecurityPolicyName. /// <para> /// Specifies the name of the security policy that is attached to the server. /// </para> /// </summary> [AWSProperty(Max=100)] public string SecurityPolicyName { get { return this._securityPolicyName; } set { this._securityPolicyName = value; } } // Check to see if SecurityPolicyName property is set internal bool IsSetSecurityPolicyName() { return this._securityPolicyName != null; } /// <summary> /// Gets and sets the property ServerId. /// <para> /// Specifies the unique system-assigned identifier for a server that you instantiate. /// </para> /// </summary> [AWSProperty(Min=19, Max=19)] public string ServerId { get { return this._serverId; } set { this._serverId = value; } } // Check to see if ServerId property is set internal bool IsSetServerId() { return this._serverId != null; } /// <summary> /// Gets and sets the property State. /// <para> /// Specifies the condition of a server for the server that was described. A value of /// <code>ONLINE</code> indicates that the server can accept jobs and transfer files. /// A <code>State</code> value of <code>OFFLINE</code> means that the server cannot perform /// file transfer operations. /// </para> /// /// <para> /// The states of <code>STARTING</code> and <code>STOPPING</code> indicate that the server /// is in an intermediate state, either not fully able to respond, or not fully offline. /// The values of <code>START_FAILED</code> or <code>STOP_FAILED</code> can indicate an /// error condition. /// </para> /// </summary> public State State { get { return this._state; } set { this._state = value; } } // Check to see if State property is set internal bool IsSetState() { return this._state != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// Specifies the key-value pairs that you can use to search for and group servers that /// were assigned to the server that was described. /// </para> /// </summary> [AWSProperty(Min=1, Max=50)] public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property UserCount. /// <para> /// Specifies the number of users that are assigned to a server you specified with the /// <code>ServerId</code>. /// </para> /// </summary> public int UserCount { get { return this._userCount.GetValueOrDefault(); } set { this._userCount = value; } } // Check to see if UserCount property is set internal bool IsSetUserCount() { return this._userCount.HasValue; } } }
34.269341
121
0.573662
[ "Apache-2.0" ]
Singh400/aws-sdk-net
sdk/src/Services/Transfer/Generated/Model/DescribedServer.cs
11,960
C#
using Newtonsoft.Json; using System; namespace EthereumChain { [Serializable] public sealed class Erc20Transaction : IEtherScanTransaction { [JsonProperty] private readonly string blockNumber; [JsonProperty] private readonly string timeStamp; [JsonProperty] private readonly string hash; [JsonProperty] private readonly string nonce; [JsonProperty] private readonly string blockHash; [JsonProperty] private readonly string from; [JsonProperty] private readonly string contractAddress; [JsonProperty] private readonly string to; [JsonProperty] private readonly string value; [JsonProperty] private readonly string tokenName; [JsonProperty] private readonly string tokenSymbol; [JsonProperty] private readonly string tokenDecimal; [JsonProperty] private readonly string transactionIndex; [JsonProperty] private readonly string gas; [JsonProperty] private readonly string gasPrice; [JsonProperty] private readonly string gasUsed; [JsonProperty] private readonly string cumulativeGasUsed; [JsonProperty] private readonly string input; [JsonProperty] private readonly string confirmations; public string BlockNumber => blockNumber; public DateTime TimeStamp { get { DateTime epoch = new DateTime(1970, 1, 1); if (long.TryParse(timeStamp, out long secondsFromEpoch)) { return epoch.AddSeconds(secondsFromEpoch); } return epoch; } } public string Hash => hash; public string Nonce => nonce; public string BlockHash => blockHash; public string TransactionIndex => transactionIndex; public string From => from; public string To => to; public decimal Value { get { if (int.TryParse(tokenDecimal, out int decimals)) { int dividedBy = 10.Pow(decimals); if (decimal.TryParse(value, out decimal result)) { return result / dividedBy; } } return decimal.Zero; } } public string Gas => gas; public string GasPrice => gasPrice; public string Input => input; public string ContractAddress => contractAddress; public string CumulativeGasUsed => cumulativeGasUsed; public string GasUsed => gasUsed; public string Confirmations => confirmations; public string TokenName => tokenName; public string TokenSymbol => tokenSymbol; } }
22.953846
72
0.566689
[ "MIT" ]
Mathias-Hedelund-Larsen/Crypto_Transaction_Assistant
Assets/Scripts/Other/JsonModels/EthereumChain/Erc20Transaction.cs
2,986
C#
using UnityEngine; public class ToggleMonitors : MonoBehaviour { void Update() { if (Input.GetKeyDown(KeyCode.Tab)) { var texture = GetComponent<uDesktopDuplication.Texture>(); var id = texture.monitorId; var n = uDesktopDuplication.Manager.monitorCount; if (Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift)) { texture.monitorId = (id - 1 < 0) ? 0 : (id - 1); } else { texture.monitorId = (id + 1 >= n) ? (n - 1) : (id + 1); } } } }
29.35
86
0.531516
[ "MIT", "Unlicense" ]
gatosyocora/VRSpace
Assets/uDesktopDuplication/Examples/Scripts/ToggleMonitors.cs
589
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; namespace PowerUtilities { public static class GraphicsEx { /// <summary> /// texture(src) blit to texture dest, ignore width,height matches. /// </summary> /// <param name="src"></param> /// <param name="dest"></param> public static void Blit(Texture src, Texture2D dest,Material mat, int destX = 0, int destY = 0, int destBlockWidth = -1, int destBlockHeight = -1) { if (!src || !dest) return; var width = destBlockWidth < 1 ? dest.width : destBlockWidth; var height = destBlockHeight < 1 ? dest.height : destBlockHeight; var rt = RenderTexture.GetTemporary(width, height, 0); if (!mat) Graphics.Blit(src, rt); else { Graphics.Blit(src, rt, mat); } //Graphics.SetRenderTarget(rt); dest.ReadPixels(new Rect(0, 0, width, height), destX, destY); Graphics.SetRenderTarget(null); RenderTexture.ReleaseTemporary(rt); } } }
29.261905
154
0.566314
[ "Apache-2.0" ]
redcool/PowerUtilities
PowerUtilities/CoreTools/EX/GraphicsEx.cs
1,231
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("EngineInfrastructure")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [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("fd22d681-f843-4c37-8f7b-99fc063b417a")] // 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.*")]
38.34375
85
0.729421
[ "ECL-2.0", "Apache-2.0" ]
Bebere/JustDecompileEngine
EngineInfrastructure/Properties/AssemblyInfo.cs
1,229
C#
namespace Miruken.Mvc.Console { public enum HorizontalAlignment { Unknown, Left, Center, Right, Stretch } }
14.545455
35
0.525
[ "MIT" ]
Miruken-DotNet/miruken.mvc
Source/Miruken.Mvc.Console/Infrastructure/HorizontalAlignment.cs
162
C#
using Prism.Mvvm; using System.Windows; namespace CodeHubDesktop.ViewModels { public class MainWindowViewModel : BindableBase { private string _title = "CodeHub"; public string Title { get => _title; set => SetProperty(ref _title, value); } private FlowDirection _MainFlowDirection; public FlowDirection MainFlowDirection { get => _MainFlowDirection; set => SetProperty(ref _MainFlowDirection, value); } public MainWindowViewModel() { SetFlowDirection(); } public FlowDirection SetFlowDirection() { return MainFlowDirection = GlobalData.Config.Lang.Equals("fa-IR") ? FlowDirection.RightToLeft : FlowDirection.LeftToRight; } } }
25.121212
134
0.60193
[ "MIT" ]
CodeHub-Contributors/CodeHubDesktop
CodeHubDesktop/ViewModels/MainWindowViewModel.cs
831
C#
namespace Elect.Notification.OneSignal.Models.App { public class AppEditModel : AppAddModel { } }
18.166667
49
0.715596
[ "MIT" ]
anglesen1120/Elect
src/Notification/Elect.Notification.OneSignal/Models/App/AppEditModel.cs
109
C#
using ET; using ProtoBuf; using System.Collections.Generic; namespace ET { [ResponseType(typeof(M2C_TestResponse))] [Message(OuterOpcode_Map.C2M_TestRequest)] [ProtoContract] public partial class C2M_TestRequest: Object, IActorLocationRequest { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } [ProtoMember(1)] public string request { get; set; } } [Message(OuterOpcode_Map.M2C_TestResponse)] [ProtoContract] public partial class M2C_TestResponse: Object, IActorLocationResponse { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(91)] public int Error { get; set; } [ProtoMember(92)] public string Message { get; set; } [ProtoMember(1)] public string response { get; set; } } [ResponseType(typeof(Actor_TransferResponse))] [Message(OuterOpcode_Map.Actor_TransferRequest)] [ProtoContract] public partial class Actor_TransferRequest: Object, IActorLocationRequest { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } [ProtoMember(1)] public int MapIndex { get; set; } } [Message(OuterOpcode_Map.Actor_TransferResponse)] [ProtoContract] public partial class Actor_TransferResponse: Object, IActorLocationResponse { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(91)] public int Error { get; set; } [ProtoMember(92)] public string Message { get; set; } } [ResponseType(typeof(M2C_Reload))] [Message(OuterOpcode_Map.C2M_Reload)] [ProtoContract] public partial class C2M_Reload: Object, IRequest { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(1)] public string Account { get; set; } [ProtoMember(2)] public string Password { get; set; } } [Message(OuterOpcode_Map.M2C_Reload)] [ProtoContract] public partial class M2C_Reload: Object, IResponse { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(91)] public int Error { get; set; } [ProtoMember(92)] public string Message { get; set; } } [ResponseType(typeof(M2C_TestRobotCase))] [Message(OuterOpcode_Map.C2M_TestRobotCase)] [ProtoContract] public partial class C2M_TestRobotCase: Object, IActorLocationRequest { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } [ProtoMember(1)] public int N { get; set; } } [Message(OuterOpcode_Map.M2C_TestRobotCase)] [ProtoContract] public partial class M2C_TestRobotCase: Object, IActorLocationResponse { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(91)] public int Error { get; set; } [ProtoMember(92)] public string Message { get; set; } [ProtoMember(1)] public int N { get; set; } } [Message(OuterOpcode_Map.M2C_EndBattleSettle)] [ProtoContract] public partial class M2C_EndBattleSettle: Object, IActorMessage { [ProtoMember(1)] public List<PlayerBattlePoint> settleAccount = new List<PlayerBattlePoint>(); } [Message(OuterOpcode_Map.M2C_KillEvent)] [ProtoContract] public partial class M2C_KillEvent: Object, IActorMessage { [ProtoMember(1)] public PlayerBattlePoint killer { get; set; } [ProtoMember(2)] public PlayerBattlePoint deadPlayer { get; set; } } [Message(OuterOpcode_Map.UnitInfo)] [ProtoContract] public partial class UnitInfo: Object { [ProtoMember(1)] public long UnitId { get; set; } [ProtoMember(2)] public int ConfigId { get; set; } // 所属的玩家id // 所属的玩家id [ProtoMember(99)] public long BelongToPlayerId { get; set; } [ProtoMember(3)] public float X { get; set; } [ProtoMember(4)] public float Y { get; set; } [ProtoMember(5)] public float Z { get; set; } [ProtoMember(6)] public int RoleCamp { get; set; } } [Message(OuterOpcode_Map.M2C_CreateUnits)] [ProtoContract] public partial class M2C_CreateUnits: Object, IActorMessage { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } [ProtoMember(94)] public long PlayerId { get; set; } [ProtoMember(95)] public long RoomId { get; set; } [ProtoMember(2)] public List<UnitInfo> Units = new List<UnitInfo>(); } [Message(OuterOpcode_Map.M2C_UnitDestoryed)] [ProtoContract] public partial class M2C_UnitDestoryed: Object, IActorMessage { [ProtoMember(93)] public long ActorId { get; set; } //被破坏的UnitId //被破坏的UnitId [ProtoMember(94)] public long DestoryedUnitId { get; set; } } [Message(OuterOpcode_Map.C2M_PathfindingResult)] [ProtoContract] public partial class C2M_PathfindingResult: Object, IActorLocationMessage { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } [ProtoMember(1)] public float X { get; set; } [ProtoMember(2)] public float Y { get; set; } [ProtoMember(3)] public float Z { get; set; } } [Message(OuterOpcode_Map.C2M_Stop)] [ProtoContract] public partial class C2M_Stop: Object, IActorLocationMessage { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } } [Message(OuterOpcode_Map.M2C_PathfindingResult)] [ProtoContract] public partial class M2C_PathfindingResult: Object, IActorMessage { [ProtoMember(93)] public long ActorId { get; set; } [ProtoMember(1)] public long Id { get; set; } [ProtoMember(2)] public float X { get; set; } [ProtoMember(3)] public float Y { get; set; } [ProtoMember(4)] public float Z { get; set; } [ProtoMember(6)] public float Speed { get; set; } [ProtoMember(7)] public List<float> Xs = new List<float>(); [ProtoMember(8)] public List<float> Ys = new List<float>(); [ProtoMember(9)] public List<float> Zs = new List<float>(); } [Message(OuterOpcode_Map.M2C_Stop)] [ProtoContract] public partial class M2C_Stop: Object, IActorMessage { [ProtoMember(1)] public int Error { get; set; } [ProtoMember(2)] public long Id { get; set; } [ProtoMember(3)] public float X { get; set; } [ProtoMember(4)] public float Y { get; set; } [ProtoMember(5)] public float Z { get; set; } [ProtoMember(6)] public float A { get; set; } [ProtoMember(7)] public float B { get; set; } [ProtoMember(8)] public float C { get; set; } [ProtoMember(9)] public float W { get; set; } } [Message(OuterOpcode_Map.M2C_ReceiveDamage)] [ProtoContract] public partial class M2C_ReceiveDamage: Object, IActorMessage { [ProtoMember(1)] public int Error { get; set; } [ProtoMember(2)] public long UnitId { get; set; } [ProtoMember(4)] public float FinalValue { get; set; } } [Message(OuterOpcode_Map.M2C_ChangeProperty)] [ProtoContract] public partial class M2C_ChangeProperty: Object, IActorMessage { [ProtoMember(1)] public int Error { get; set; } [ProtoMember(2)] public long UnitId { get; set; } [ProtoMember(3)] public int NumicType { get; set; } [ProtoMember(4)] public float FinalValue { get; set; } } [Message(OuterOpcode_Map.C2M_CastHeroSkill)] [ProtoContract] public partial class C2M_CastHeroSkill: Object, IActorLocationMessage { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } } [Message(OuterOpcode_Map.M2C_CastHeroSkill)] [ProtoContract] public partial class M2C_CastHeroSkill: Object, IActorMessage { [ProtoMember(1)] public long UnitId { get; set; } } [Message(OuterOpcode_Map.M2C_RecoverHP)] [ProtoContract] public partial class M2C_RecoverHP: Object, IActorMessage { [ProtoMember(1)] public long SpriteUnitId { get; set; } [ProtoMember(2)] public float RecoverHPValue { get; set; } } //请求攻击 [Message(OuterOpcode_Map.C2M_CommonAttack)] [ProtoContract] public partial class C2M_CommonAttack: Object, IActorLocationMessage { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } [ProtoMember(1)] public long TargetUnitId { get; set; } } //请求攻击 [Message(OuterOpcode_Map.M2C_CancelCommonAttack)] [ProtoContract] public partial class M2C_CancelCommonAttack: Object, IActorMessage { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } [ProtoMember(1)] public long TargetUnitId { get; set; } } //服务器返回攻击指令,开始播放动画 [Message(OuterOpcode_Map.M2C_CommonAttack)] [ProtoContract] public partial class M2C_CommonAttack: Object, IActorMessage { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } [ProtoMember(4)] public long AttackCasterId { get; set; } [ProtoMember(3)] public long TargetUnitId { get; set; } [ProtoMember(2)] public bool CanAttack { get; set; } } [Message(OuterOpcode_Map.M2C_BuffInfo)] [ProtoContract] public partial class M2C_BuffInfo: Object, IActorMessage { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } [ProtoMember(1)] public long UnitId { get; set; } [ProtoMember(96)] public long SkillId { get; set; } [ProtoMember(2)] public string BBKey { get; set; } [ProtoMember(95)] public long TheUnitBelongToId { get; set; } [ProtoMember(91)] public long TheUnitFromId { get; set; } [ProtoMember(3)] public int BuffLayers { get; set; } [ProtoMember(4)] public float BuffMaxLimitTime { get; set; } } [Message(OuterOpcode_Map.C2M_UserInputSkillCmd)] [ProtoContract] public partial class C2M_UserInputSkillCmd: Object, IActorLocationMessage { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } [ProtoMember(64)] public string VK { get; set; } } //同步行为树bool黑板变量 [Message(OuterOpcode_Map.M2C_SyncNPBehaveBoolData)] [ProtoContract] public partial class M2C_SyncNPBehaveBoolData: Object, IActorMessage { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } [ProtoMember(94)] public long UnitId { get; set; } //黑板键 //黑板键 [ProtoMember(2)] public string BBKey { get; set; } [ProtoMember(5)] public bool Value { get; set; } } //同步CD信息 [Message(OuterOpcode_Map.M2C_SyncCDData)] [ProtoContract] public partial class M2C_SyncCDData: Object, IActorMessage { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } [ProtoMember(94)] public long UnitId { get; set; } //CD名称 //CD名称 [ProtoMember(2)] public string CDName { get; set; } //CD总时长 //CD总时长 [ProtoMember(3)] public long CDLength { get; set; } //剩余CD时长 //剩余CD时长 [ProtoMember(5)] public long RemainCDLength { get; set; } } [Message(OuterOpcode_Map.C2M_CreateSpiling)] [ProtoContract] public partial class C2M_CreateSpiling: Object, IActorLocationMessage { [ProtoMember(2)] public float X { get; set; } [ProtoMember(3)] public float Y { get; set; } [ProtoMember(4)] public float Z { get; set; } //所归属的父实体id //所归属的父实体id [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } } [Message(OuterOpcode_Map.M2C_CreateSpilings)] [ProtoContract] public partial class M2C_CreateSpilings: Object, IActorMessage { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } [ProtoMember(95)] public long RoomId { get; set; } [ProtoMember(2)] public UnitInfo Unit { get; set; } } [Message(OuterOpcode_Map.M2C_SyncUnitAttribute)] [ProtoContract] public partial class M2C_SyncUnitAttribute: Object, IActorMessage { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } [ProtoMember(94)] public long UnitId { get; set; } [ProtoMember(95)] public int NumericType { get; set; } [ProtoMember(3)] public float FinalValue { get; set; } } [Message(OuterOpcode_Map.M2C_ChangeUnitAttribute)] [ProtoContract] public partial class M2C_ChangeUnitAttribute: Object, IActorMessage { [ProtoMember(90)] public int RpcId { get; set; } [ProtoMember(93)] public long ActorId { get; set; } [ProtoMember(94)] public long UnitId { get; set; } [ProtoMember(95)] public int NumericType { get; set; } [ProtoMember(2)] public float ChangeValue { get; set; } } ////////////////////////////////////////////// 战斗相关 END /////////////////////////////////////////////////////////////// }
19.94586
119
0.687131
[ "MIT" ]
futouyiba/ClubET
Server/Model/Generate/Message/OuterMessage_Map.cs
12,720
C#
using System; using mc.CodeAlalysis.Syntax; namespace mc.CodeAlalysis.Binding { internal sealed class BoundBinaryOperator { private BoundBinaryOperator( SyntaxKind syntaxKind, BoundBinaryOperatorKind kind, Type leftType, Type rightType, Type resultType) { SyntaxKind = syntaxKind; Kind = kind; LeftType = leftType; RightType = rightType; ResultType = resultType; } private BoundBinaryOperator( SyntaxKind syntaxKind, BoundBinaryOperatorKind kind, Type operandType, Type resultType) : this(syntaxKind, kind, operandType, operandType, resultType) { } private BoundBinaryOperator( SyntaxKind syntaxKind, BoundBinaryOperatorKind kind, Type type ) : this(syntaxKind, kind, type, type, type) { } public SyntaxKind SyntaxKind { get; } public BoundBinaryOperatorKind Kind { get; } public Type LeftType { get; } public Type RightType { get; } public Type ResultType { get; } private static BoundBinaryOperator[] _operators = { new BoundBinaryOperator( SyntaxKind.PlusToken, BoundBinaryOperatorKind.Addition, typeof(int)), new BoundBinaryOperator( SyntaxKind.MinusToken, BoundBinaryOperatorKind.Subtraction, typeof(int)), new BoundBinaryOperator( SyntaxKind.StarToken, BoundBinaryOperatorKind.Multiplication, typeof(int)), new BoundBinaryOperator( SyntaxKind.SlashToken, BoundBinaryOperatorKind.Division, typeof(int)), new BoundBinaryOperator( SyntaxKind.PipePipeToken, BoundBinaryOperatorKind.LogicalOr, typeof(bool)), new BoundBinaryOperator( SyntaxKind.AmpersandAmpersandToken, BoundBinaryOperatorKind.LogicalAnd, typeof(bool)), new BoundBinaryOperator( SyntaxKind.EqualsToken, BoundBinaryOperatorKind.Equal, typeof(int), typeof(bool)), new BoundBinaryOperator( SyntaxKind.BangEqualsToken, BoundBinaryOperatorKind.BangEquals, typeof(int), typeof(bool)), new BoundBinaryOperator( SyntaxKind.BangEqualsToken, BoundBinaryOperatorKind.BangEquals, typeof(bool)), new BoundBinaryOperator( SyntaxKind.EqualsToken, BoundBinaryOperatorKind.Equal, typeof(bool)), new BoundBinaryOperator( SyntaxKind.AmpersandToken, BoundBinaryOperatorKind.MathmaticalAnd, typeof(int)), new BoundBinaryOperator( SyntaxKind.PipeToken, BoundBinaryOperatorKind.MathmaticalOr, typeof(int)), new BoundBinaryOperator( SyntaxKind.LesserCompareToken, BoundBinaryOperatorKind.LessCompare, typeof(int), typeof(int), typeof(bool)), new BoundBinaryOperator( SyntaxKind.BiggerCompareToken, BoundBinaryOperatorKind.BiggerCompare, typeof(int), typeof(int), typeof(bool)), new BoundBinaryOperator( SyntaxKind.LeftShiftToken, BoundBinaryOperatorKind.LeftShift, typeof(int)), new BoundBinaryOperator( SyntaxKind.RightShiftToken, BoundBinaryOperatorKind.RIghtShift, typeof(int)) }; public static BoundBinaryOperator Bind(SyntaxKind syntaxKind, Type leftType, Type rightType) { foreach (var op in _operators) { if (op.SyntaxKind == syntaxKind && op.LeftType == leftType && op.RightType == rightType) return op; } return null; } } }
34.456
104
0.552124
[ "MIT" ]
chenyekun1/mc
sm/CodeAnalysis/Bingding/BoundBinaryOperator.cs
4,307
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Text.RegularExpressions; public class _PlayCondition { protected MatchController mMatchController; public _PlayCondition() { mMatchController = GameObject.Find ("Match Controller").GetComponent<MatchController> (); } public virtual bool IsFulfilled() { return true; } }
19.842105
91
0.782493
[ "Apache-2.0" ]
cvogit/Progression-Card-Game
Assets/Scripts/Card/PlayConditions/_PlayCondition.cs
379
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Taschenrechner { public partial class Form1 : Form { double zahl1; double zahl2; string op; public Form1() { InitializeComponent(); } private void Btn_ziffern_Click(object sender, EventArgs e) { Button btn = (Button)sender; if (tb_display.Text == "0" & btn.Text != "," ) { tb_display.Text = ""; } tb_display.Text += btn.Text; } private void btn_add_Click(object sender, EventArgs e) { zahl1 = Convert.ToDouble(tb_display.Text); tb_display.Text = "0"; op = "+"; } private void btn_gleich_Click(object sender, EventArgs e) { zahl2 = Convert.ToDouble(tb_display.Text); switch (op) { case "+": tb_display.Text = Convert.ToString(zahl1 + zahl2); break; case "-": tb_display.Text = Convert.ToString(zahl1 - zahl2); break; case "*": tb_display.Text = Convert.ToString(zahl1 * zahl2); break; case "/": tb_display.Text = Convert.ToString(zahl1 / zahl2); break; } } } }
25.852459
70
0.504756
[ "MIT" ]
MaikHo/C-_erste_schritte
C# Snippets/Taschenrechner/Taschenrechner/Form1.cs
1,579
C#
using System.Collections.Generic; using System.Linq; using System.Windows; using QuickGraph; using System; using System.Diagnostics.Contracts; namespace GraphSharp.Algorithms.Layout.Compound.FDP { public partial class CompoundFDPLayoutAlgorithm<TVertex, TEdge, TGraph> where TVertex : class where TEdge : IEdge<TVertex> where TGraph : IBidirectionalGraph<TVertex, TEdge> { private static void RemoveAll<T>(ICollection<T> set, IEnumerable<T> elements) { foreach (var e in elements) { set.Remove(e); } } /// <summary> /// <list type="ul"> /// <listheader> /// Initializes the algorithm, and the following things: /// </listheader> /// <item>the nodes sizes (of the compound vertices)</item> /// <item>the thresholds for the convergence</item> /// <item>random initial positions (if the position is not null)</item> /// <item>remove the 'tree-nodes' from the root graph (level 0)</item> /// </list> /// </summary> /// <param name="vertexSizes">The dictionary of the inner canvas sizes /// of the compound vertices.</param> /// <param name="vertexBorders">The dictionary of the border thickness of /// the compound vertices.</param> /// <param name="layoutTypes">The dictionary of the layout types of /// the compound vertices.</param> private void Init(IDictionary<TVertex, Size> vertexSizes, IDictionary<TVertex, Thickness> vertexBorders, IDictionary<TVertex, CompoundVertexInnerLayoutType> layoutTypes) { InitializeWithRandomPositions(100, 100); var movableParentUpdateQueue = new Queue<TVertex>(); _rootCompoundVertex.Children = new HashSet<VertexData>(); InitialLevels(); InitSimpleVertices(vertexSizes); InitCompoundVertices(vertexBorders, vertexSizes, layoutTypes, /*out*/ movableParentUpdateQueue); SetLevelIndices(); //TODO do we need this? InitMovableParentOfFixedVertices(movableParentUpdateQueue); RemoveTreeNodesFromRootGraph(); InitGravitationMagnitude(); } private void InitGravitationMagnitude() { //get the average width and height double sumWidth = 0, sumHeight = 0; foreach (var vertex in _levels[0]) { var v = _vertexDatas[vertex]; sumWidth += v.Size.Width; sumHeight += v.Size.Height; } if (_levels[0].Count > 0) _gravityForceMagnitude = Math.Min(sumWidth, sumHeight) / _levels[0].Count; } private void RemoveTreeNodesFromRootGraph() { bool removed = true; for (int i = 0; removed; i++) { removed = false; foreach (var vertex in _levels[0]) { if (_compoundGraph.Degree(vertex) != 1 || _compoundGraph.IsCompoundVertex(vertex)) continue; TEdge edge = default(TEdge); if (_compoundGraph.InDegree(vertex) > 0) edge = _compoundGraph.InEdge(vertex, 0); else edge = _compoundGraph.OutEdge(vertex, 0); if (_removedRootTreeEdges.Contains(edge)) continue; //the vertex is a leaf tree node removed = true; while (_removedRootTreeNodeLevels.Count <= i) _removedRootTreeNodeLevels.Push(new List<RemovedTreeNodeData>()); //add to the removed vertices _removedRootTreeNodeLevels.Peek().Add(new RemovedTreeNodeData(vertex, edge)); _removedRootTreeNodes.Add(vertex); _removedRootTreeEdges.Add(edge); } if (removed && _removedRootTreeNodeLevels.Count > 0) //remove from the level foreach (var tnd in _removedRootTreeNodeLevels.Peek()) { _levels[0].Remove(tnd.Vertex); //remove the vertex from the graph _compoundGraph.RemoveEdge(tnd.Edge); _compoundGraph.RemoveVertex(tnd.Vertex); } } } private void InitMovableParentOfFixedVertices(Queue<TVertex> movableParentUpdateQueue) { while (movableParentUpdateQueue.Count > 0) { //geth the compound vertex with the fixed layout var fixedLayoutedCompoundVertex = movableParentUpdateQueue.Dequeue(); //find the not fixed predecessor TVertex movableVertex = fixedLayoutedCompoundVertex; for (; ; ) { //if the vertex hasn't parent if (movableVertex == null) break; TVertex parent = _compoundGraph.GetParent(movableVertex); if (parent == null) break; //if the parent's layout type is fixed if (_compoundVertexDatas[parent].InnerVertexLayoutType != CompoundVertexInnerLayoutType.Fixed) break; movableVertex = parent; } //the movable vertex is the ancestor of the children of the vertex //that could be moved //fix the child vertices and set the movable parent foreach (var childVertex in _compoundGraph.GetChildrenVertices(fixedLayoutedCompoundVertex)) { var data = _vertexDatas[childVertex]; data.IsFixedToParent = true; data.MovableParent = _vertexDatas[movableVertex]; } } } /// <summary> /// Initializes the data of the simple vertices. /// </summary> /// <param name="vertexSizes">Dictionary of the vertex sizes.</param> private void InitSimpleVertices(IDictionary<TVertex, Size> vertexSizes) { foreach (var vertex in _compoundGraph.SimpleVertices) { Size vertexSize; vertexSizes.TryGetValue(vertex, out vertexSize); var position = new Point(); VertexPositions.TryGetValue(vertex, out position); //create the information container for this simple vertex var dataContainer = new SimpleVertexData(vertex, _rootCompoundVertex, false, position, vertexSize); dataContainer.Parent = _rootCompoundVertex; _simpleVertexDatas[vertex] = dataContainer; _vertexDatas[vertex] = dataContainer; _rootCompoundVertex.Children.Add(dataContainer); } } /// <summary> /// Initializes the data of the compound vertices. /// </summary> /// <param name="vertexBorders">Dictionary of the border thicknesses.</param> /// <param name="vertexSizes">Dictionary of the vertex sizes.</param> /// <param name="layoutTypes">Dictionary of the layout types.</param> /// <param name="movableParentUpdateQueue">The compound vertices with fixed layout /// should be added to this queue.</param> private void InitCompoundVertices( IDictionary<TVertex, Thickness> vertexBorders, IDictionary<TVertex, Size> vertexSizes, IDictionary<TVertex, CompoundVertexInnerLayoutType> layoutTypes, Queue<TVertex> movableParentUpdateQueue) { for (int i = _levels.Count - 1; i >= 0; i--) { foreach (var vertex in _levels[i]) { if (!_compoundGraph.IsCompoundVertex(vertex)) continue; //get the data of the vertex Thickness border; vertexBorders.TryGetValue(vertex, out border); Size vertexSize; vertexSizes.TryGetValue(vertex, out vertexSize); var layoutType = CompoundVertexInnerLayoutType.Automatic; layoutTypes.TryGetValue(vertex, out layoutType); if (layoutType == CompoundVertexInnerLayoutType.Fixed) { movableParentUpdateQueue.Enqueue(vertex); } var position = new Point(); VertexPositions.TryGetValue(vertex, out position); //create the information container for this compound vertex var dataContainer = new CompoundVertexData(vertex, _rootCompoundVertex, false, position, vertexSize, border, layoutType); if (i == 0) { dataContainer.Parent = _rootCompoundVertex; _rootCompoundVertex.Children.Add(dataContainer); } _compoundVertexDatas[vertex] = dataContainer; _vertexDatas[vertex] = dataContainer; //add the datas of the childrens var children = _compoundGraph.GetChildrenVertices(vertex); var childrenData = children.Select(v => _vertexDatas[v]).ToList(); dataContainer.Children = childrenData; foreach (var child in dataContainer.Children) { _rootCompoundVertex.Children.Remove(child); child.Parent = dataContainer; } } } } private void InitialLevels() { var verticesLeft = new HashSet<TVertex>(VisitedGraph.Vertices); //initial 0th level _levels.Add(new HashSet<TVertex>(VisitedGraph.Vertices.Where(v => _compoundGraph.GetParent(v) == default(TVertex)))); RemoveAll(verticesLeft, _levels[0]); //other layers for (int i = 1; verticesLeft.Count > 0; i++) { var nextLevel = new HashSet<TVertex>(); foreach (var parent in _levels[i - 1]) { if (_compoundGraph.GetChildrenCount(parent) <= 0) continue; foreach (var children in _compoundGraph.GetChildrenVertices(parent)) nextLevel.Add(children); } _levels.Add(nextLevel); RemoveAll(verticesLeft, nextLevel); } } private void SetLevelIndices() { //set the level indexes in the vertex datas for (int i = 0; i < _levels.Count; i++) { foreach (var v in _levels[i]) _vertexDatas[v].Level = i; } } } }
40.699275
177
0.542598
[ "Apache-2.0" ]
highway-it/graphsharp
src/GraphSharp/Algorithms/Layout/Compound/FDP/CompoundFDPLayoutAlgorithm.Init.cs
11,235
C#
using System; namespace NAppUpdate.Framework.Conditions { [AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)] public class UpdateConditionAliasAttribute : Attribute { private readonly string _alias; public UpdateConditionAliasAttribute(string alias) { this._alias = alias; } public string Alias { [System.Diagnostics.DebuggerStepThrough] get { return this._alias; } } } }
23.363636
85
0.63035
[ "Apache-2.0" ]
Aaronontheweb/NAppUpdate
src/NAppUpdate.Framework/Conditions/UpdateConditionAliasAttribute.cs
516
C#
namespace SolidPrinciples.OpenClosedPrinciple.WithPrinciple; public class TomatoPizza : Pizza { public TomatoPizza() : base(PizzaType.Tomato) { } protected override void SetIngredients() { base.SetIngredients(); Console.WriteLine("Tomato pizza ingredients set"); } }
25.416667
61
0.698361
[ "MIT" ]
pncsoares/dotnet-solid-principles
OpenClosedPrinciple/WithPrinciple/TomatoPizza.cs
307
C#
using System; using System.IO; using System.Numerics; using System.Collections.Generic; using Veldrid; using Veldrid.Utilities; using Unsafe = System.Runtime.CompilerServices.Unsafe; namespace Enigma.Graphics { public static class Util { public static uint SizeInBytes<T>(this T[] array) { return (uint)(array.Length * Unsafe.SizeOf<T>()); } public static uint SizeOf<T>() => (uint)Unsafe.SizeOf<T>(); // Code adapted from https://bitbucket.org/sinbad/ogre/src/9db75e3ba05c/OgreMain/include/OgreVector3.h public static Quaternion FromToRotation(Vector3 from, Vector3 to, Vector3 fallbackAxis = default) { // Based on Stan Melax's article in Game Programming Gems Quaternion q; // Copy, since cannot modify local Vector3 v0 = from; Vector3 v1 = to; v0 = Vector3.Normalize(v0); v1 = Vector3.Normalize(v1); float d = Vector3.Dot(v0, v1); // If dot == 1, vectors are the same if (d >= 1.0f) { return Quaternion.Identity; } if (d < (1e-6f - 1.0f)) { if (fallbackAxis != Vector3.Zero) { // rotate 180 degrees about the fallback axis q = Quaternion.CreateFromAxisAngle(fallbackAxis, (float)Math.PI); } else { // Generate an axis Vector3 axis = Vector3.Cross(Vector3.UnitX, from); if (axis.LengthSquared() == 0) // pick another if colinear { axis = Vector3.Cross(Vector3.UnitY, from); } axis = Vector3.Normalize(axis); q = Quaternion.CreateFromAxisAngle(axis, (float)Math.PI); } } else { float s = (float)Math.Sqrt((1 + d) * 2); float invs = 1.0f / s; Vector3 c = Vector3.Cross(v0, v1); q.X = c.X * invs; q.Y = c.Y * invs; q.Z = c.Z * invs; q.W = s * 0.5f; q = Quaternion.Normalize(q); } return q; } // modifies projection matrix in place // clipPlane is in camera space public static void CalculateObliqueMatrixPerspective(ref Matrix4x4 projection, Matrix4x4 view, Plane clipPlane) { Matrix4x4 invTransposeView = VdUtilities.CalculateInverseTranspose(view); Vector4 clipV4 = new Vector4(clipPlane.Normal, clipPlane.D); clipV4 = Vector4.Transform(clipV4, invTransposeView); Vector4 q = new Vector4( (Math.Sign(clipV4.X) + projection.M13) / projection.M11, (Math.Sign(clipV4.Y) + projection.M23) / projection.M22, -1f, (1 + projection.M33) / projection.M34); Vector4 c = clipV4 * (1f / Vector4.Dot(clipV4, q)); projection.M31 = c.X; projection.M32 = c.Y; projection.M33 = c.Z; projection.M34 = c.W; } public static Matrix4x4 Inverse(this Matrix4x4 src) { Matrix4x4.Invert(src, out Matrix4x4 result); return result; } public static Matrix4x4 CreatePerspective( GraphicsDevice gd, bool useReverseDepth, float fov, float aspectRatio, float near, float far) { Matrix4x4 persp; if (useReverseDepth) { persp = CreatePerspective(fov, aspectRatio, far, near); } else { persp = CreatePerspective(fov, aspectRatio, near, far); } if (gd.IsClipSpaceYInverted) { persp *= new Matrix4x4( 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } return persp; } public static Matrix4x4 CreatePerspective(float fov, float aspectRatio, float near, float far) { if (fov <= 0.0f || fov >= MathF.PI) throw new ArgumentOutOfRangeException(nameof(fov)); if (near <= 0.0f) throw new ArgumentOutOfRangeException(nameof(near)); if (far <= 0.0f) throw new ArgumentOutOfRangeException(nameof(far)); float yScale = 1.0f / MathF.Tan(fov * 0.5f); float xScale = yScale / aspectRatio; Matrix4x4 result; result.M11 = xScale; result.M12 = result.M13 = result.M14 = 0.0f; result.M22 = yScale; result.M21 = result.M23 = result.M24 = 0.0f; result.M31 = result.M32 = 0.0f; var negFarRange = float.IsPositiveInfinity(far) ? -1.0f : far / (near - far); result.M33 = negFarRange; result.M34 = -1.0f; result.M41 = result.M42 = result.M44 = 0.0f; result.M43 = near * negFarRange; return result; } public static Matrix4x4 CreateOrtho( GraphicsDevice gd, bool useReverseDepth, float left, float right, float bottom, float top, float near, float far) { Matrix4x4 ortho; if (useReverseDepth) { ortho = Matrix4x4.CreateOrthographicOffCenter(left, right, bottom, top, far, near); } else { ortho = Matrix4x4.CreateOrthographicOffCenter(left, right, bottom, top, near, far); } if (gd.IsClipSpaceYInverted) { ortho *= new Matrix4x4( 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } return ortho; } public static float[] GetFullScreenQuadVerts(GraphicsDevice gd) { if (gd.IsClipSpaceYInverted) { return new float[] { -1, -1, 0, 0, 1, -1, 1, 0, 1, 1, 1, 1, -1, 1, 0, 1 }; } else { return new float[] { -1, 1, 0, 0, 1, 1, 1, 0, 1, -1, 1, 1, -1, -1, 0, 1 }; } } internal static Stream OpenResourcesStream() => typeof(Util).Assembly.GetManifestResourceStream(typeof(Util).Assembly.GetManifestResourceNames()[0]); internal static byte[] ReadBytesFromResources(string name) { return (byte[])Properties.Resources.ResourceManager.GetObject(name); } public static Vector3 ToNumerics(this Assimp.Vector3D vector) { return new Vector3(vector.X, vector.Y, vector.Z); } public static Vector3[] ConvertToVectorArray(this List<Assimp.Vector3D> vectors) { Vector3[] v = new Vector3[vectors.Count]; for (int i = 0; i < vectors.Count; i++) { v[i] = vectors[i].ToNumerics(); } return v; } } }
31.94958
119
0.475013
[ "MIT" ]
wings-studio/Enigma.Graphics
Enigma.Graphics/Util.cs
7,606
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("TodoMVC.Specs")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TodoMVC.Specs")] [assembly: AssemblyCopyright("Copyright © 2018")] [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("414c848d-c3fc-4b6c-9f15-6c0c65c8c339")] // 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.675676
84
0.746772
[ "MIT" ]
LirazShay/TodoMVC
TodoMVC.Specs/Properties/AssemblyInfo.cs
1,397
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace VeraWAF.WebPages.Controls { public partial class UserProfileField { /// <summary> /// litMarkup control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.WebControls.Literal litMarkup; } }
31.2
84
0.475641
[ "ECL-2.0", "Apache-2.0" ]
SysSurge/vera
WebPages/Controls/UserProfileField.ascx.designer.cs
782
C#
 namespace Elaina { partial class ElainaLaunch3r { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ElainaLaunch3r)); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.button2 = new System.Windows.Forms.Button(); this.button3 = new System.Windows.Forms.Button(); this.button6 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.pictureBox3 = new System.Windows.Forms.PictureBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.label4 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).BeginInit(); this.SuspendLayout(); // // pictureBox2 // this.pictureBox2.BackColor = System.Drawing.Color.Transparent; this.pictureBox2.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("pictureBox2.BackgroundImage"))); this.pictureBox2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.pictureBox2.Location = new System.Drawing.Point(-31, 26); this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.Size = new System.Drawing.Size(290, 290); this.pictureBox2.TabIndex = 1; this.pictureBox2.TabStop = false; // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.Transparent; this.label1.Font = new System.Drawing.Font("Poppins SemiBold", 20F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.Fuchsia; this.label1.Location = new System.Drawing.Point(271, 49); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(238, 48); this.label1.TabIndex = 2; this.label1.Text = "Elaina Launcher"; // // label2 // this.label2.AutoSize = true; this.label2.BackColor = System.Drawing.Color.Transparent; this.label2.Font = new System.Drawing.Font("Poppins", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.ForeColor = System.Drawing.Color.White; this.label2.Location = new System.Drawing.Point(4, 326); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(126, 19); this.label2.TabIndex = 7; this.label2.Text = "Beta Test | Version 0.1"; this.label2.Click += new System.EventHandler(this.label2_Click); // // button2 // this.button2.BackColor = System.Drawing.Color.Transparent; this.button2.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center; this.button2.FlatAppearance.BorderSize = 0; this.button2.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent; this.button2.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent; this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button2.Font = new System.Drawing.Font("Poppins", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button2.ForeColor = System.Drawing.Color.White; this.button2.ImageAlign = System.Drawing.ContentAlignment.TopCenter; this.button2.Location = new System.Drawing.Point(484, -3); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(24, 24); this.button2.TabIndex = 8; this.button2.Text = "_"; this.button2.UseVisualStyleBackColor = false; this.button2.Click += new System.EventHandler(this.button2_Click); // // button3 // this.button3.BackColor = System.Drawing.Color.Transparent; this.button3.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center; this.button3.FlatAppearance.BorderSize = 0; this.button3.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Transparent; this.button3.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Transparent; this.button3.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button3.Font = new System.Drawing.Font("Poppins", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button3.ForeColor = System.Drawing.Color.White; this.button3.ImageAlign = System.Drawing.ContentAlignment.TopCenter; this.button3.Location = new System.Drawing.Point(512, 2); this.button3.Name = "button3"; this.button3.Size = new System.Drawing.Size(24, 24); this.button3.TabIndex = 9; this.button3.Text = "X"; this.button3.UseVisualStyleBackColor = false; this.button3.Click += new System.EventHandler(this.button3_Click); // // button6 // this.button6.BackColor = System.Drawing.Color.Transparent; this.button6.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center; this.button6.FlatAppearance.BorderColor = System.Drawing.Color.Fuchsia; this.button6.FlatAppearance.MouseDownBackColor = System.Drawing.Color.Fuchsia; this.button6.FlatAppearance.MouseOverBackColor = System.Drawing.Color.Fuchsia; this.button6.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.button6.Font = new System.Drawing.Font("Poppins", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.button6.ForeColor = System.Drawing.Color.White; this.button6.Location = new System.Drawing.Point(329, 236); this.button6.Name = "button6"; this.button6.Size = new System.Drawing.Size(111, 32); this.button6.TabIndex = 12; this.button6.Text = "Login"; this.button6.UseVisualStyleBackColor = false; this.button6.Click += new System.EventHandler(this.button6_Click); // // textBox1 // this.textBox1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.textBox1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.textBox1.Font = new System.Drawing.Font("Poppins", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox1.ForeColor = System.Drawing.Color.WhiteSmoke; this.textBox1.Location = new System.Drawing.Point(289, 148); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(192, 17); this.textBox1.TabIndex = 13; this.textBox1.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged_2); // // pictureBox1 // this.pictureBox1.BackColor = System.Drawing.Color.Fuchsia; this.pictureBox1.Location = new System.Drawing.Point(289, 166); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(192, 2); this.pictureBox1.TabIndex = 14; this.pictureBox1.TabStop = false; // // pictureBox3 // this.pictureBox3.BackColor = System.Drawing.Color.Fuchsia; this.pictureBox3.Location = new System.Drawing.Point(289, 218); this.pictureBox3.Name = "pictureBox3"; this.pictureBox3.Size = new System.Drawing.Size(192, 2); this.pictureBox3.TabIndex = 16; this.pictureBox3.TabStop = false; // // textBox2 // this.textBox2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.textBox2.BorderStyle = System.Windows.Forms.BorderStyle.None; this.textBox2.Font = new System.Drawing.Font("Poppins", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.textBox2.ForeColor = System.Drawing.Color.WhiteSmoke; this.textBox2.Location = new System.Drawing.Point(289, 200); this.textBox2.Name = "textBox2"; this.textBox2.PasswordChar = '*'; this.textBox2.Size = new System.Drawing.Size(192, 17); this.textBox2.TabIndex = 15; this.textBox2.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.textBox2.UseSystemPasswordChar = true; this.textBox2.TextChanged += new System.EventHandler(this.textBox2_TextChanged); // // label3 // this.label3.AutoSize = true; this.label3.BackColor = System.Drawing.Color.Transparent; this.label3.Font = new System.Drawing.Font("Poppins", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label3.ForeColor = System.Drawing.Color.Silver; this.label3.Location = new System.Drawing.Point(284, 126); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(70, 19); this.label3.TabIndex = 17; this.label3.Text = " Username:"; // // label4 // this.label4.AutoSize = true; this.label4.BackColor = System.Drawing.Color.Transparent; this.label4.Font = new System.Drawing.Font("Poppins", 8F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label4.ForeColor = System.Drawing.Color.Silver; this.label4.Location = new System.Drawing.Point(286, 178); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(63, 19); this.label4.TabIndex = 18; this.label4.Text = "Password:"; // // ElainaLaunch3r // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.Black; this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch; this.CausesValidation = false; this.ClientSize = new System.Drawing.Size(541, 343); this.ControlBox = false; this.Controls.Add(this.label4); this.Controls.Add(this.label3); this.Controls.Add(this.pictureBox3); this.Controls.Add(this.textBox2); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.textBox1); this.Controls.Add(this.button6); this.Controls.Add(this.button3); this.Controls.Add(this.button2); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.pictureBox2); this.DoubleBuffered = true; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "ElainaLaunch3r"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "ElainaLauncherF"; this.Load += new System.EventHandler(this.Form1_Load); this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown); this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseMove); this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseUp); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox3)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PictureBox pictureBox2; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button6; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.PictureBox pictureBox3; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; } }
55.8
160
0.611111
[ "MIT" ]
mnikhwan/Elaina-Launcher
Elaina/Elaina/Elaina.Designer.cs
15,068
C#
using Caliburn.Micro; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace TFSMergingTool.Resources.FolderTree { public partial class FolderTreeViewModel : PropertyChangedBase, IFolderTreeViewModel { public IObservableCollection<FolderViewModel> Folders { get; set; } /// <summary> /// Get or set the currently selected folder. Only the FullPath is considered when setting. /// </summary> public DirectoryInfo SelectedFolder { get { foreach (var folder in Folders) { FolderViewModel foundFolder = folder.FindSelectedFolder(); if (foundFolder != null) return new DirectoryInfo(foundFolder.Path); } return null; } set { if (!Directory.Exists(value.FullName)) throw new ArgumentException("Directory " + value.FullName + " does not exist."); FolderViewModel desiredFolder = null; foreach (var folder in Folders) { var foundFolder = folder.FindFolderWithPath(value.FullName); if (foundFolder != null) desiredFolder = foundFolder; } if (desiredFolder != null) { foreach (var folder in Folders) { folder.CloseAll(); folder.DeselectAll(); } desiredFolder.ExpandParents(); desiredFolder.IsSelected = true; } } } public FolderTreeViewModel(string basePath) { if (!Directory.Exists(basePath)) throw new ArgumentException("Directory " + basePath + " does not exist."); var basefolder = new FolderViewModel(basePath); Folders = new BindableCollection<FolderViewModel>(); Folders.Add(basefolder); } public FolderTreeViewModel(string[] basePaths) { Folders = new BindableCollection<FolderViewModel>(); foreach (var basePath in basePaths) { if (!Directory.Exists(basePath)) throw new ArgumentException("Directory " + basePath + " does not exist."); var basefolder = new FolderViewModel(basePath); Folders.Add(basefolder); } } public void SelectedChanged(object selectedItem) { string name; string path; if (selectedItem != null) { var selected = selectedItem as FolderViewModel; name = selected.Name; path = selected.Path; } else { name = string.Empty; path = string.Empty; } var args = new TreeViewSelectionChangedEventArgs() { Name = name, FullPath = path }; OnSelectionChanged(args); } public event EventHandler<TreeViewSelectionChangedEventArgs> SelectionChanged; protected virtual void OnSelectionChanged(TreeViewSelectionChangedEventArgs e) { var handler = SelectionChanged; if (handler != null) { handler(this, e); } } } }
32.294643
100
0.508985
[ "MIT" ]
jamesin-tili/tfs-merge
TFSMergingTool/src/Resources/Old/FolderTreeViewModel.cs
3,619
C#
using FoxTunes.Interfaces; using System; using System.Diagnostics; using System.IO; using System.Threading.Tasks; namespace FoxTunes { public static class LogManager { public static string FileName = Path.Combine( Publication.StoragePath, "Log.txt" ); public static void Open() { try { var fileName = Path.Combine( Path.GetTempPath(), string.Format("Log-{0}.txt", DateTime.Now.ToFileTimeUtc()) ); File.Copy(FileName, fileName, true); Process.Start(fileName).WaitForExit(); File.Delete(fileName); } catch { //Nothing can be done. If we can't see the log there's no point writing to it.... } } private static ILogger _Logger { get; set; } public static ILogger Logger { get { if (_Logger == null) { return NullLogger.Instance; } return _Logger; } set { _Logger = value; } } private class NullLogger : BaseComponent, ILogger { public bool IsTraceEnabled(IBaseComponent component) { #if DEBUG return true; #else return false; #endif } public bool IsDebugEnabled(IBaseComponent component) { #if DEBUG return true; #else return false; #endif } public bool IsInfoEnabled(IBaseComponent component) { #if DEBUG return true; #else return false; #endif } public bool IsWarnEnabled(IBaseComponent component) { #if DEBUG return true; #else return false; #endif } public bool IsErrorEnabled(IBaseComponent component) { #if DEBUG return true; #else return false; #endif } public bool IsFatalEnabled(IBaseComponent component) { #if DEBUG return true; #else return false; #endif } public bool IsTraceEnabled(Type type) { #if DEBUG return true; #else return false; #endif } public bool IsDebugEnabled(Type type) { #if DEBUG return true; #else return false; #endif } public bool IsInfoEnabled(Type type) { #if DEBUG return true; #else return false; #endif } public bool IsWarnEnabled(Type type) { #if DEBUG return true; #else return false; #endif } public bool IsErrorEnabled(Type type) { #if DEBUG return true; #else return false; #endif } public bool IsFatalEnabled(Type type) { #if DEBUG return true; #else return false; #endif } public void Write(IBaseComponent component, LogLevel level, string message, params object[] args) { #if DEBUG global::System.Diagnostics.Debug.WriteLine(this.FormatMessage(component.GetType(), level, message, args)); #endif } public void Write(Type type, LogLevel level, string message, params object[] args) { #if DEBUG global::System.Diagnostics.Debug.WriteLine(this.FormatMessage(type, level, message, args)); #endif } public Task WriteAsync(IBaseComponent component, LogLevel level, string message, params object[] args) { #if DEBUG global::System.Diagnostics.Debug.WriteLine(this.FormatMessage(component.GetType(), level, message, args)); #endif #if NET40 return TaskEx.FromResult(false); #else return Task.CompletedTask; #endif } public Task WriteAsync(Type type, LogLevel level, string message, params object[] args) { #if DEBUG global::System.Diagnostics.Debug.WriteLine(this.FormatMessage(type, level, message, args)); #endif #if NET40 return TaskEx.FromResult(false); #else return Task.CompletedTask; #endif } protected virtual string FormatMessage(Type type, LogLevel level, string message, object[] args) { if (args != null && args.Length > 0) { message = string.Format(message, args); } return string.Format( "{0} {1} {2} : {3}", DateTime.Now.Ticks, type.FullName, Enum.GetName(typeof(LogLevel), level), message ); } public void Dispose() { //Nothing to do. } public static readonly ILogger Instance = new NullLogger(); } } }
25
123
0.467857
[ "MIT" ]
DJCALIEND/FoxTunes
FoxTunes.Core/LogManager.cs
5,602
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ // Generation date: 9/11/2020 3:24:26 PM namespace Microsoft.Dynamics.DataEntities { /// <summary> /// There are no comments for RAssetType in the schema. /// </summary> public enum RAssetType { Tangible = 0, Intangible = 1, Financial = 2, LandBuilding = 3, Goodwill = 4, Vehicle = 6, Land = 7, Other = 5, Cloths = 8, Rigging = 9, LowCostAssets = 10 } }
27
81
0.461806
[ "MIT" ]
NathanClouseAX/AAXDataEntityPerfTest
Projects/AAXDataEntityPerfTest/ConsoleApp1/Connected Services/D365/RAssetType.cs
866
C#
using System; using System.Collections.Generic; using System.Linq; using System.Globalization; using System.Text; using System.Threading.Tasks; namespace _01.CountWorkingDays { class Program { static void Main(string[] args) { string startDateText = Console.ReadLine(); string endDateText = Console.ReadLine(); DateTime startDate = DateTime.ParseExact(startDateText, "dd-MM-yyyy", CultureInfo.InvariantCulture); DateTime endDate = DateTime.ParseExact(endDateText, "dd-MM-yyyy", CultureInfo.InvariantCulture); DateTime[] holidays = new DateTime[12]; holidays[0] = new DateTime(4, 01, 01); holidays[1] = new DateTime(4, 03, 03); holidays[2] = new DateTime(4, 05, 01); holidays[3] = new DateTime(4, 05, 06); holidays[4] = new DateTime(4, 05, 24); holidays[5] = new DateTime(4, 09, 06); holidays[6] = new DateTime(4, 09, 22); holidays[7] = new DateTime(4, 11, 01); holidays[9] = new DateTime(4, 12, 24); holidays[10] = new DateTime(4, 12, 25); holidays[11] = new DateTime(4, 12, 26); int workingDayCounter = 0; for (DateTime i = startDate; i <= endDate; i = i.AddDays(1)) { DayOfWeek day = i.DayOfWeek; DateTime temp = new DateTime(4, i.Month, i.Day); if (!holidays.Contains(temp) && (!day.Equals(DayOfWeek.Saturday) && !day.Equals(DayOfWeek.Sunday))) { workingDayCounter++; } } Console.WriteLine(workingDayCounter); } } }
33.647059
115
0.556527
[ "MIT" ]
RumenNovachkov/ProgrammingFundamentalsCSharp
ObjectsAndClasses-Exercises/01.CountWorkingDays/Program.cs
1,718
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BallScript : MonoBehaviour { public GameObject spawnpt; public GameObject SceneManager; public float minimumForwardVelocity = 0.0f; public float maximumVelocity = 5.0f; protected Rigidbody _rb; protected Collider _col; public static bool startGame; private void Start() { _rb = gameObject.GetComponent<Rigidbody>(); _col = gameObject.GetComponent<Collider>(); startGame = false; } private void FixedUpdate() { if(_rb.velocity.sqrMagnitude > maximumVelocity * maximumVelocity) { _rb.velocity = _rb.velocity.normalized * maximumVelocity; } //starts game if(_rb.isKinematic == false) { startGame = true; } } private void OnCollisionEnter(Collision collision) { if (collision.gameObject.name == "backwall") { Debug.Log(collision.gameObject.name); //gameObject.GetComponent<BallScript>().enabled = false; Manager sm = SceneManager.GetComponent<Manager>(); sm.Lost(); } } //Old min velocity code /*private void OnCollisionStay(Collision collision) { if (_rb && minimumForwardVelocity != 0.0f) { if (Mathf.Abs(_rb.velocity.z) < minimumForwardVelocity) { float zVel = minimumForwardVelocity; if (_rb.velocity.z <= 0.0f) { zVel *= -1.0f; } _rb.velocity = new Vector3(_rb.velocity.x, _rb.velocity.y, zVel); } } }*/ }
26.318182
81
0.569372
[ "MIT" ]
Fornan-II/AG231_VRMinigame_Lab01
Assets/Script/BallScript.cs
1,739
C#
using DataFlareClient; using micro_c_app.Models; using micro_c_app.Views; using micro_c_app.Views.CollectionFile; using MicroCLib.Models; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Xamarin.Essentials; using Xamarin.Forms; namespace micro_c_app.ViewModels { public class QuotePageViewModel : BaseViewModel { public static QuotePageViewModel Instance; public INavigation Navigation; private bool notBusy; private Item? selectedItem; public Item? SelectedItem { get => selectedItem; set { SetProperty(ref selectedItem, value); } } public ObservableCollection<Item> Items { get => items; set => SetProperty(ref items, value); } public ICommand OnProductFound { get; } public ICommand OnProductError { get; } public ICommand IncreaseQuantity { get; } public ICommand DecreaseQuantity { get; } public ICommand RemoveItem { get; } public ICommand DetailItem { get; } public ICommand SendQuote { get; } public ICommand ExportQuote { get; } public ICommand ImportQuote { get; } public ICommand Reset { get; } public ICommand Save { get; } public ICommand Load { get; } public ICommand ImportWeb { get; } public ICommand ExportWeb { get; } public ICommand BatchScan { get; } protected override Dictionary<string, ICommand> Actions => new Dictionary<string, ICommand>() { {"Save", Save }, {"Load", Load }, {"Import", ImportWeb }, {"Batch Scan", BatchScan }, {"Reset", Reset } }; public bool NotBusy { get => notBusy; set { SetProperty(ref notBusy, value); } } public float Subtotal => Items.Sum(i => i.Price * i.Quantity); public string TaxedTotal => $"({SettingsPage.TaxRate()})% ${Subtotal * SettingsPage.TaxRateFactor():#0.00}"; private Item lastItem; private ObservableCollection<Item> items; public Item LastItem { get => lastItem; set => SetProperty(ref lastItem, value); } public QuotePageViewModel() { Instance = this; Title = "Quote"; NotBusy = true; if (RestoreState.Instance.QuoteItems != null) { Items = new ObservableCollection<Item>(RestoreState.Instance.QuoteItems); } else { Items = new ObservableCollection<Item>(); } //for (int i = 0; i < 10; i++) //{ // var item = new Item() // { // Name = "ITEM", // SKU = "123456", // OriginalPrice = 100, // Price = 90, // Stock = "5 in stock", // }; // Items.Add(item); //} Items.CollectionChanged += (sender, args) => { UpdateProperties(); }; OnProductFound = new Command<Item>((Item item) => { Items.Add(item); item.PropertyChanged += (sender, args) => { UpdateProperties(); }; LastItem = item; }); OnProductError = new Command<string>(async (string message) => { if (Shell.Current != null) { await Shell.Current.DisplayAlert("Error", message, "Ok"); } }); IncreaseQuantity = new Command<Item>((Item item) => { item.Quantity++; UpdateProperties(); }); DecreaseQuantity = new Command<Item>((Item item) => { if (item.Quantity > 1) { item.Quantity--; UpdateProperties(); } }); RemoveItem = new Command<Item>(async (Item item) => { /* * * I am not sure if this a xaml bug or not, but the layout for the elements that * toggle display visibility on selected break if the list of items is not cleared * and reset when removing... * * * Ideally we just call Items.Remove(item) and are done with it, worth investigating longer * * Also see RemindersPageViewModel */ await Device.InvokeOnMainThreadAsync(async () => { if (item != null) { var reset = await Shell.Current.DisplayAlert("Remove", $"Are you sure you want to remove {item.Name}", "Yes", "No"); if (reset) { Items.Remove(item); var tmp = Items.ToList(); Items.Clear(); foreach (var i in tmp) { Items.Add(i); } } } }); }); ImportQuote = new Command(async () => await ImportQuoteAction()); MessagingCenter.Subscribe<SettingsPageViewModel>(this, SettingsPageViewModel.SETTINGS_UPDATED_MESSAGE, (_) => { UpdateProperties(); }); Reset = new Command(async () => { await Device.InvokeOnMainThreadAsync(async () => { var reset = await Shell.Current.DisplayAlert("Reset", "Are you sure you want to reset the quote?", "Yes", "No"); if (reset) { Items.Clear(); UpdateProperties(); } }); }); DetailItem = new Command(async () => { await Device.InvokeOnMainThreadAsync(async () => { var detailsPage = new ItemDetailsPageViewModel() { Item = SelectedItem }; await Shell.Current.Navigation.PushAsync(new ItemDetailsPage() { BindingContext = detailsPage, Item = SelectedItem }); }); }); Load = new Command(async () => { var page = await ImportPage.Create<Item>("quote"); page.OnImportResults += (sender) => { if (sender.BindingContext is ImportPageViewModel<Item> vm && vm.Result != null) { Items = new ObservableCollection<Item>(vm.Result); } }; }); ImportWeb = new Command(async () => { var shortCode = await Shell.Current.DisplayPromptAsync("Import", "Enter the code from Micro-C-Builder to import a quote", keyboard: Keyboard.Numeric); if (string.IsNullOrWhiteSpace(shortCode)) { return; } var flare = await Flare.GetShortCode("https://dataflare.bbarrett.me/api/Flare", shortCode); if (flare == null || string.IsNullOrWhiteSpace(flare.Data)) { return; } Items.Clear(); var components = JsonConvert.DeserializeObject<List<BuildComponent>>(flare.Data); foreach (var comp in components) { if (comp.Item != null) { Items.Add(comp.Item); } } }); Save = new Command(async () => { await ExportPage.Create(Items.Select(i => new BuildComponent() { Item = i }).ToList(), "quote"); }); BatchScan = new Command(() => DoBatchScan()); } public static void AddItem(Item item) { if(Instance == null) { if (RestoreState.Instance != null) { RestoreState.Instance.QuoteItems.Add(item); RestoreState.Save(); } } else { Instance.Items.Add(item); item.PropertyChanged += (sender, args) => { Instance.UpdateProperties(); }; Instance.LastItem = item; } } private void DoLoad(CollectionLoadPageViewModel<Item> obj) { Items.Clear(); foreach (var i in obj.Result) { Items.Add(i); } UpdateProperties(); } public static async Task DoSendQuote(IEnumerable<Item> Items) { try { var message = new EmailMessage() { Subject = $"MicroCenter Quote - {DateTime.Today.ToShortDateString()}", Body = ExportTxtTable(Items), }; if (SettingsPage.IncludeCSVWithQuote()) { var file = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "quote.csv"); File.WriteAllText(file, ExportCsv(Items)); var attach = new EmailAttachment(file); message.Attachments = new List<EmailAttachment>() { attach }; } //await Email.ComposeAsync(message); foreach (var line in message.Body.Split('\n')) { Console.WriteLine(line); } await Share.RequestAsync(new ShareTextRequest() { Title = message.Subject, Text = message.Body, }); } catch (Exception e) { await Device.InvokeOnMainThreadAsync(async () => { await Shell.Current.DisplayAlert("Error", e.ToString(), "Ok"); }); } } public static string ExportCsv(IEnumerable<Item> items) { StringBuilder b = new StringBuilder(); b.AppendLine($"SKU,Name,Qty,Unit,Price"); foreach (var item in items) { b.AppendLine($"{item.SKU},{item.Name},{item.Quantity},${item.Price:#0.00},${item.Price * item.Quantity:#0.00}"); } var Subtotal = items.Sum(i => i.Price * i.Quantity); var TaxedTotal = Subtotal * SettingsPage.TaxRateFactor(); b.AppendLine(); b.AppendLine($"Subtotal,${Subtotal:#0.00}"); b.AppendLine($"Total ({SettingsPage.TaxRate()}),${TaxedTotal:#0.00}"); return b.ToString(); } public static string ExportTxtTable(IEnumerable<Item> items) { StringBuilder b = new StringBuilder(); b.AppendLine($"SKU {string.Format("{0,-50}", "Name")} Qty Unit Price"); b.AppendLine(); foreach (var item in items) { b.AppendLine($"{item.SKU} {string.Format("{0,-40}", item.Name.Substring(0, Math.Min(item.Name.Length, 30)))} {item.Quantity} ${item.Price:#0.00} ${item.Price * item.Quantity:#0.00}"); } var Subtotal = items.Sum(i => i.Price * i.Quantity); var TaxedTotal = Subtotal * SettingsPage.TaxRateFactor(); b.AppendLine(); b.AppendLine(string.Format("{0,78}", $"Sub ${Subtotal:#0.00}")); b.AppendLine(string.Format("{0,78}", $"Total ${TaxedTotal:#0.00}")); b.AppendLine(); var salesId = Preferences.Get("sales_id", "SALESID"); if (!string.IsNullOrWhiteSpace(salesId)) { //b.AppendLine($"Quote created by {salesId} for additional help contact me at {salesId}@microcenter.com"); } return b.ToString(); } public static async Task DoExportQuote(IEnumerable<Item> Items) { var page = new ExportQRPage(); if (page.BindingContext is ExportQRPageViewModel vm) { foreach (var i in Items) { vm.Items.Add(i); } } await Shell.Current.Navigation.PushAsync(page); } private async Task ImportQuoteAction() { NotBusy = false; await DoImportQuote( new Command<Item>(async (Item i) => { await Device.InvokeOnMainThreadAsync(async () => { await Shell.Current.DisplayAlert("Title", i.Name, "Ok"); }); }), new Command<Item>(async (Item i) => { await Device.InvokeOnMainThreadAsync(async () => { await Shell.Current.DisplayAlert("ERROR", i.Name, "Ok"); }); }) ); NotBusy = true; } public static async Task DoImportQuote(Command<Item> productFound, Command error) { var view = new SearchView(); view.ProductFound = productFound; view.Error = error; await view.OnSubmit("951970"); } private void DoBatchScan() { SearchView.DoScan(Navigation, async (result, progress) => { System.Diagnostics.Debug.WriteLine(result); try { int queryAttempts = 0; //go back here on error, so that we can retry the request a few times const int NUM_RETRY_ATTEMPTS = 5; var storeId = SettingsPage.StoreID(); startQuery: queryAttempts++; try { var results = await Search.LoadQuery(result, storeId, null, Search.OrderByMode.match, 1, progress: progress); if (results.Items.Count == 1) { var stub = results.Items.First(); var item = await Item.FromUrl(stub.URL, storeId, progress: progress); if (item != null) { Items.Add(item); item.PropertyChanged += (sender, args) => { UpdateProperties(); }; LastItem = item; return; } } } catch (Exception e) { if (queryAttempts > NUM_RETRY_ATTEMPTS) { await Shell.Current.DisplayAlert("Error", e.Message, "Ok"); return; } } if (queryAttempts > NUM_RETRY_ATTEMPTS) { await Shell.Current.DisplayAlert("Error", $"Failed to find item \"{result}\"", "Ok"); } else { progress?.Report(new ProgressInfo($"Retrying query...{queryAttempts}/{NUM_RETRY_ATTEMPTS}", 0)); await Task.Delay(1000); goto startQuery; } } catch (Exception e) { await Shell.Current.DisplayAlert("Error", e.Message, "Ok"); } }, batchMode: true); } public void UpdateProperties() { OnPropertyChanged(nameof(Subtotal)); OnPropertyChanged(nameof(TaxedTotal)); RestoreState.Instance.QuoteItems = Items.ToList(); RestoreState.Save(); } } }
36.641469
210
0.449219
[ "MIT" ]
blaxbb/Micro-C-App
micro-c-app/micro-c-app/ViewModels/QuotePageViewModel.cs
16,967
C#
namespace CRM.Areas.AppPage.ModelDescriptions { public class CollectionModelDescription : ModelDescription { public ModelDescription ElementDescription { get; set; } } }
27
64
0.740741
[ "MIT" ]
araucanosland/MDN
CRM/Areas/AppPage/ModelDescriptions/CollectionModelDescription.cs
189
C#
// Copyright (c) 2021 Samuel Abraham using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using TypeCache.Business; using TypeCache.Data.Requests; namespace TypeCache.Web.Middleware { public class SelectSqlMiddleware : DataMiddleware { public SelectSqlMiddleware(RequestDelegate _, IMediator mediator) : base(mediator) { } public async Task Invoke(HttpContext httpContext) => await this.HandleSqlRequest<SelectRequest>(httpContext); } }
22.285714
67
0.779915
[ "MIT" ]
sam987883/TypeCache
src/TypeCache.Web/Middleware/SelectSqlMiddleware.cs
470
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using AIM.Data; using AIM.Models.Nodes; using AIM.Plugins.Analyzers; using AIM.Plugins.Core; using Microsoft.Extensions.Logging; namespace AIM.Plugins.Visualizers { public class PetriNetVis : Visualizer { public override string Name => "PetriVis"; private readonly Neo4JContext _context; private readonly ILogger _logger; private readonly PetriNet _petriNet; public PetriNetVis(PetriNet petriNet, ILogger logger) { _petriNet = petriNet; _context = new Neo4JContext(logger); _logger = logger; } public override async Task<string> RunAsync() { // Empty the current database _context.ClearDb(); // Create a list of all the nodes var nodeTypes = _petriNet.Nodes.GroupBy(x => x.Type); var watch = new Stopwatch(); watch.Start(); // Insert all the nodes foreach (IGrouping<NodeType, SimpleNodeModel> nodeList in nodeTypes) { await _context.CsvInsertNodes(nodeList.ToList(), nodeList.Key.ToString()); } _logger.LogDebug($"{DateTime.Now}\tNodes inserted\ttime taken: {watch.ElapsedMilliseconds/1000f:N}s\t{_petriNet.Nodes.Count} nodes inserted"); watch.Restart(); List<Operator> operators = (from start in _petriNet.Edges from end in start.Value select end.Value).ToList(); foreach (var type in operators.GroupBy(x => x.Type)) { await _context.InsertEdgesByID( type.Select(x => x.Start).ToList(), type.Select(x => x.End).ToList(), type.Select(x => x.Weight).ToList(), type.Key.ToString()); } _logger.LogDebug($"{DateTime.Now}\tEdges inserted\ttime taken: {watch.ElapsedMilliseconds/1000f:N}s\tedges inserted: {operators.Count}"); return $"The run found {this._petriNet.Nodes.Count} objects! \n " + $"Check the local Neo4j client for results (default http://localhost:7474/browser/)."; } } }
33.75
154
0.604357
[ "Apache-2.0" ]
RensR/AIM-ArchitectureCity
Plugins/Visualizers/PetriNetVis.cs
2,297
C#
using AutoFixture; using FluentAssertions; using Moq; using NUnit.Framework; using SFA.DAS.Common.Domain.Types; using SFA.DAS.EmployerIncentives.Commands.ApprenticeshipIncentive.LearnerChangeOfCircumstance; using SFA.DAS.EmployerIncentives.Commands.Persistence; using SFA.DAS.EmployerIncentives.Domain.ApprenticeshipIncentives; using SFA.DAS.EmployerIncentives.Domain.ApprenticeshipIncentives.Events; using SFA.DAS.EmployerIncentives.Domain.ApprenticeshipIncentives.Models; using SFA.DAS.EmployerIncentives.Domain.ApprenticeshipIncentives.ValueTypes; using SFA.DAS.EmployerIncentives.Domain.Factories; using SFA.DAS.EmployerIncentives.Domain.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SFA.DAS.EmployerIncentives.Commands.UnitTests.ApprenticeshipIncentive.LearnerChangeOfCircumstance { public class WhenHandlingLearnerChangeOfCircumstanceCommand { private LearnerChangeOfCircumstanceCommandHandler _sut; private Mock<IApprenticeshipIncentiveDomainRepository> _mockIncentiveDomainRespository; private Fixture _fixture; private Mock<ILearnerDomainRepository> _mockLearnerDomainRespository; private Domain.ApprenticeshipIncentives.ApprenticeshipIncentive _incentive; private Learner _learner; [SetUp] public void Arrange() { _fixture = new Fixture(); _mockIncentiveDomainRespository = new Mock<IApprenticeshipIncentiveDomainRepository>(); _mockLearnerDomainRespository = new Mock<ILearnerDomainRepository>(); var incentive = new ApprenticeshipIncentiveFactory() .CreateNew(_fixture.Create<Guid>(), _fixture.Create<Guid>(), _fixture.Create<Account>(), new Apprenticeship( _fixture.Create<long>(), _fixture.Create<string>(), _fixture.Create<string>(), DateTime.Today.AddYears(-26), _fixture.Create<long>(), ApprenticeshipEmployerType.Levy, _fixture.Create<string>() ), DateTime.Today, _fixture.Create<DateTime>(), _fixture.Create<string>()); incentive.SetHasPossibleChangeOfCircumstances(true); incentive.Apprenticeship.SetProvider(_fixture.Create<Provider>()); _fixture.Register(() => incentive); _sut = new LearnerChangeOfCircumstanceCommandHandler(_mockIncentiveDomainRespository.Object, _mockLearnerDomainRespository.Object); _incentive = _fixture.Create<Domain.ApprenticeshipIncentives.ApprenticeshipIncentive>(); _learner = new LearnerFactory().GetExisting( _fixture.Build<LearnerModel>() .With(x => x.SubmissionData, _fixture.Create<SubmissionData>()) .With(x=> x.ApprenticeshipIncentiveId, _incentive.Id) .Create()); _mockIncentiveDomainRespository.Setup(x => x.Find(incentive.Id)).ReturnsAsync(_incentive); _mockLearnerDomainRespository.Setup(m => m.GetOrCreate(incentive)).ReturnsAsync(_learner); } [Test] public async Task Then_the_start_date_is_updated() { //Arrange var command = new LearnerChangeOfCircumstanceCommand(_incentive.Id); _learner.SubmissionData.SetSubmissionDate(_fixture.Create<DateTime>()); _learner.SubmissionData.SetLearningData(new LearningData(true)); _learner.SubmissionData.LearningData.SetStartDate(_fixture.Create<DateTime>()); // Act await _sut.Handle(command); // Assert _incentive.StartDate.Should().Be(_learner.SubmissionData.LearningData.StartDate.Value); } [Test] public async Task Then_the_StartdateChanged_event_is_raised() { //Arrange var command = new LearnerChangeOfCircumstanceCommand(_incentive.Id); _learner.SubmissionData.SetSubmissionDate(_fixture.Create<DateTime>()); _learner.SubmissionData.SetLearningData(new LearningData(true)); var newStartDate = _incentive.StartDate.AddMonths(2); var previousStartDate = _incentive.StartDate; _learner.SubmissionData.LearningData.SetStartDate(newStartDate); // Act await _sut.Handle(command); // Assert var @event = _incentive.FlushEvents().Single(e => e is StartDateChanged) as StartDateChanged; @event.ApprenticeshipIncentiveId.Should().Be(_incentive.Id); @event.NewStartDate.Should().Be(newStartDate); @event.PreviousStartDate.Should().Be(previousStartDate); } [Test] public async Task Then_the_StartdateChanged_event_is_not_raised_if_the_start_date_is_the_same_as_the_previous_start_date() { //Arrange var command = new LearnerChangeOfCircumstanceCommand(_incentive.Id); _learner.SubmissionData.SetSubmissionDate(_fixture.Create<DateTime>()); _learner.SubmissionData.SetLearningData(new LearningData(true)); _learner.SubmissionData.LearningData.SetStartDate(_incentive.StartDate); // Act await _sut.Handle(command); // Assert _incentive.FlushEvents().Count(e => e is StartDateChanged).Should().Be(0); } [Test] public async Task Then_the_changes_are_persisted() { //Arrange var command = new LearnerChangeOfCircumstanceCommand(_incentive.Id); _learner.SubmissionData.LearningData.SetStartDate(_fixture.Create<DateTime>()); int itemsPersisted = 0; _mockIncentiveDomainRespository.Setup(m => m.Save(It.Is<Domain.ApprenticeshipIncentives.ApprenticeshipIncentive>(a => a.Id == command.ApprenticeshipIncentiveId))) .Callback(() => { itemsPersisted++; }); // Act await _sut.Handle(command); // Assert itemsPersisted.Should().Be(1); } [Test] public async Task Then_the_start_date_is_not_updated_when_submission_data_was_not_found() { //Arrange var originalStartDate = _incentive.StartDate; var command = new LearnerChangeOfCircumstanceCommand(_incentive.Id); _learner.SetSubmissionData(null); // Act await _sut.Handle(command); // Assert _incentive.StartDate.Should().Be(originalStartDate); } [Test] public async Task Then_the_start_date_is_not_updated_when_submission_has_no_start_date() { //Arrange var originalStartDate = _incentive.StartDate; var command = new LearnerChangeOfCircumstanceCommand(_incentive.Id); _learner.SubmissionData.LearningData.SetStartDate(null); // Act await _sut.Handle(command); // Assert _incentive.StartDate.Should().Be(originalStartDate); } [Test] public async Task Then_HasPossibleChangeOfCircumstances_set_to_false_when_change_of_circs_complete() { //Arrange var command = new LearnerChangeOfCircumstanceCommand(_incentive.Id); // Act await _sut.Handle(command); // Assert _incentive.HasPossibleChangeOfCircumstances.Should().BeFalse(); } [Test] public async Task Then_process_should_exit_if_no_possible_change_of_circumstances() { //Arrange _incentive.SetHasPossibleChangeOfCircumstances(false); var command = new LearnerChangeOfCircumstanceCommand(_incentive.Id); // Act await _sut.Handle(command); // Assert _mockLearnerDomainRespository.Verify(x => x.GetOrCreate(It.IsAny<Domain.ApprenticeshipIncentives.ApprenticeshipIncentive>()), Times.Never); _mockIncentiveDomainRespository.Verify(x => x.Save(It.IsAny<Domain.ApprenticeshipIncentives.ApprenticeshipIncentive>()), Times.Never); } } }
40.533654
174
0.650931
[ "MIT" ]
uk-gov-mirror/SkillsFundingAgency.das-employer-incentives
src/tests/SFA.DAS.EmployerIncentives.Commands.UnitTests/ApprenticeshipIncentive/LearnerChangeOfCircumstance/WhenHandlingLearnerChangeOfCircumstanceCommand.cs
8,433
C#
using System; using ChargifyDotNetTests.Base; using System.Linq; using ChargifyNET; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ChargifyDotNetTests { [TestClass] public class ReferralCodeTests : ChargifyTestBase { [DataTestMethod] [DataRow("xml")] [DataRow("json")] [TestMethod] public void ReferralCode_Validate(string method) { var isJson = method == "json"; SetJson(isJson); // Arrange var subscription = Chargify.GetSubscriptionList().FirstOrDefault(s => s.Value.State == ChargifyNET.SubscriptionState.Active).Value; Assert.IsNotNull(subscription, "No suitable subscription found."); // Act var result = Chargify.ValidateReferralCode(subscription.ReferralCode); // Assert Assert.IsNotNull(result); Assert.AreEqual(subscription.ReferralCode, result.Code); Assert.AreEqual(subscription.SubscriptionID, result.SubscriptionID); SetJson(!isJson); } } }
29.513514
143
0.638278
[ "MIT" ]
kfrancis/chargify-dot-net
Source/ChargifyDotNet.Tests/ReferralCodeTests.cs
1,094
C#
using System; using System.Linq; using System.Reflection; using Harald.WebApi.Domain; namespace Harald.WebApi.Features.Connections.Domain.Model { public class ClientType : StringSubstitutable { public ClientType(string value) : base(value) { } public static explicit operator ClientType(string input) { return Create(input); } public static ClientType Create(string clientType) { var validClientTypes = Assembly .GetAssembly(typeof(ClientType)) .GetTypes() .Where(t => t.IsSubclassOf(typeof(ClientType))) .Select(t => (ClientType) Activator.CreateInstance(t)) .ToList(); var returnChannelType = validClientTypes.SingleOrDefault(c => clientType.Equals(c, StringComparison.OrdinalIgnoreCase)); if (returnChannelType == null) { throw new ValidationException( $"Invalid client type: '{clientType}'. Your options are: '{String.Join("', '", validClientTypes)}'"); } return returnChannelType; } } public class ClientTypeCapability : ClientType { public ClientTypeCapability() : base("capability") { } } }
29.106383
121
0.565789
[ "MIT" ]
dfds/harald
src/Harald.WebApi/Features/Connections/Domain/Model/ClientType.cs
1,368
C#
/* Copyright (c) 2012 GFT Appverse, S.L., Sociedad Unipersonal. This Source Code Form is subject to the terms of the Appverse Public License Version 2.0 (“APL v2.0”). If a copy of the APL was not distributed with this file, You can obtain one at http://appverse.org/legal/appverse-license/. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the conditions of the AppVerse Public License v2.0 are met. 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. EXCEPT IN CASE OF WILLFUL MISCONDUCT OR GROSS NEGLIGENCE, IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using Unity.Core.System.Server.Net; using Unity.Core.System.Service; using Unity.Core.IO; namespace Unity.Core.System.Resource { public class RemoteResourceHandler : IHttpHandler { private static string REMOTE_RESOURCE_URI = "/proxy/"; private static string UNITY_IO_SERVICE_NAME = "io"; private IServiceLocator serviceLocator = null; public RemoteResourceHandler (IServiceLocator _serviceLocator) { serviceLocator = _serviceLocator; } #region IHttpHandler implementation public bool Process (HttpServer server, HttpRequest request, HttpResponse response) { SystemLogger.Log (SystemLogger.Module .CORE, " ############## " + this.GetType () + " -> " + request.Url); if (request.Url.StartsWith (REMOTE_RESOURCE_URI)) { SystemLogger.Log (SystemLogger.Module .CORE, "Remote resource protocol."); try { string commandParams = request.Url.Substring (REMOTE_RESOURCE_URI.Length); string[] commandParamsArray = commandParams.Split (new char[] { '/' }); if (commandParamsArray.Length > 0) { string ioServiceName = commandParamsArray [0]; Object unityIOService = serviceLocator.GetService (UNITY_IO_SERVICE_NAME); if (unityIOService != null && ioServiceName != null) { IIo io = (IIo)unityIOService; string parameters = commandParams.Substring (ioServiceName.Length + 1); IORequest ioRequest = new IORequest (); ioRequest.Content = parameters; IOResponse ioResponse = io.InvokeService (ioRequest, ioServiceName); if (ioResponse != null) { response.ContentType = ioResponse.ContentType; response.RawContent = ioResponse.ContentBinary; } } } if (response.RawContent == null) { response.Content = "No content available."; SystemLogger.Log (SystemLogger.Module .CORE, "No content available for request [" + request.Url + "," + request.Method + "]. Continue to next handler..."); return false; } return true; } catch (Exception e) { SystemLogger.Log (SystemLogger.Module .CORE, "Exception when parsing request [" + request.Url + "]", e); response.Content = "Malformed request."; return false; } } else { SystemLogger.Log (SystemLogger.Module .CORE, "Non remote resource protocol. Continue to next handler..."); return false; } } #endregion } }
42.108696
162
0.683789
[ "MPL-2.0" ]
Appverse-Archive/appverse-mobile
appverse-core/src/csharp/Unity/Core/System/Resource/RemoteResourceHandler.cs
3,878
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.WafV2.Inputs { public sealed class WebAclRuleStatementAndStatementStatementNotStatementStatementSizeConstraintStatementGetArgs : Pulumi.ResourceArgs { /// <summary> /// Operator to use to compare the request part to the size setting. Valid values include: `EQ`, `NE`, `LE`, `LT`, `GE`, or `GT`. /// </summary> [Input("comparisonOperator", required: true)] public Input<string> ComparisonOperator { get; set; } = null!; /// <summary> /// Part of a web request that you want AWS WAF to inspect. See Field to Match below for details. /// </summary> [Input("fieldToMatch")] public Input<Inputs.WebAclRuleStatementAndStatementStatementNotStatementStatementSizeConstraintStatementFieldToMatchGetArgs>? FieldToMatch { get; set; } /// <summary> /// Size, in bytes, to compare to the request part, after any transformations. Valid values are integers between 0 and 21474836480, inclusive. /// </summary> [Input("size", required: true)] public Input<int> Size { get; set; } = null!; [Input("textTransformations", required: true)] private InputList<Inputs.WebAclRuleStatementAndStatementStatementNotStatementStatementSizeConstraintStatementTextTransformationGetArgs>? _textTransformations; /// <summary> /// Text transformations eliminate some of the unusual formatting that attackers use in web requests in an effort to bypass detection. See Text Transformation below for details. /// </summary> public InputList<Inputs.WebAclRuleStatementAndStatementStatementNotStatementStatementSizeConstraintStatementTextTransformationGetArgs> TextTransformations { get => _textTransformations ?? (_textTransformations = new InputList<Inputs.WebAclRuleStatementAndStatementStatementNotStatementStatementSizeConstraintStatementTextTransformationGetArgs>()); set => _textTransformations = value; } public WebAclRuleStatementAndStatementStatementNotStatementStatementSizeConstraintStatementGetArgs() { } } }
49.36
202
0.720421
[ "ECL-2.0", "Apache-2.0" ]
chivandikwa/pulumi-aws
sdk/dotnet/WafV2/Inputs/WebAclRuleStatementAndStatementStatementNotStatementStatementSizeConstraintStatementGetArgs.cs
2,468
C#
// <auto-generated /> using System; using MAVN.Service.CustomerProfile.MsSqlRepositories; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace MAVN.Service.CustomerProfile.MsSqlRepositories.Migrations { [DbContext(typeof(CustomerProfileContext))] [Migration("20191129114316_AddReferralFriend")] partial class AddReferralFriend { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasDefaultSchema("customer_profile") .HasAnnotation("ProductVersion", "2.2.4-servicing-10062") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("MAVN.Service.CustomerProfile.MsSqlRepositories.Entities.AdminProfileArchiveEntity", b => { b.Property<Guid>("AdminId") .ValueGeneratedOnAdd() .HasColumnName("admin_id"); b.Property<string>("Company") .IsRequired() .HasColumnName("company"); b.Property<string>("Department") .IsRequired() .HasColumnName("department"); b.Property<string>("Email") .IsRequired() .HasColumnName("email"); b.Property<string>("FirstName") .IsRequired() .HasColumnName("first_name"); b.Property<string>("JobTitle") .IsRequired() .HasColumnName("job_title"); b.Property<string>("LastName") .IsRequired() .HasColumnName("last_name"); b.Property<string>("PhoneNumber") .IsRequired() .HasColumnName("phone_number"); b.HasKey("AdminId"); b.ToTable("admin_profiles_archive"); }); modelBuilder.Entity("MAVN.Service.CustomerProfile.MsSqlRepositories.Entities.AdminProfileEntity", b => { b.Property<Guid>("AdminId") .ValueGeneratedOnAdd() .HasColumnName("admin_id"); b.Property<string>("Company") .IsRequired() .HasColumnName("company"); b.Property<string>("Department") .IsRequired() .HasColumnName("department"); b.Property<string>("Email") .IsRequired() .HasColumnName("email"); b.Property<string>("FirstName") .IsRequired() .HasColumnName("first_name"); b.Property<string>("JobTitle") .IsRequired() .HasColumnName("job_title"); b.Property<string>("LastName") .IsRequired() .HasColumnName("last_name"); b.Property<string>("PhoneNumber") .IsRequired() .HasColumnName("phone_number"); b.HasKey("AdminId"); b.HasIndex("Email"); b.ToTable("admin_profiles"); }); modelBuilder.Entity("MAVN.Service.CustomerProfile.MsSqlRepositories.Entities.CustomerProfileArchiveEntity", b => { b.Property<string>("CustomerId") .ValueGeneratedOnAdd() .HasColumnName("customer_id"); b.Property<int>("CountryOfNationalityId") .HasColumnName("country_of_nationality_id"); b.Property<int?>("CountryOfResidenceId") .HasColumnName("country_of_residence_id"); b.Property<int?>("CountryPhoneCodeId") .HasColumnName("country_phone_code_id"); b.Property<string>("Email") .IsRequired() .HasColumnName("email"); b.Property<string>("FirstName") .HasColumnName("first_name"); b.Property<bool>("IsEmailVerified") .HasColumnName("email_verified"); b.Property<bool>("IsPhoneVerified") .HasColumnName("phone_verified"); b.Property<string>("LastName") .HasColumnName("last_name"); b.Property<string>("PhoneNumber") .HasColumnName("phone_number"); b.Property<DateTime>("Registered") .HasColumnName("registered_at"); b.Property<string>("ShortPhoneNumber") .HasColumnName("short_phone_number"); b.Property<string>("TierId") .HasColumnName("tier_id"); b.Property<bool>("WasPhoneEverVerified") .HasColumnName("was_phone_ever_verified"); b.HasKey("CustomerId"); b.HasIndex("Email"); b.ToTable("customer_profile_archive"); }); modelBuilder.Entity("MAVN.Service.CustomerProfile.MsSqlRepositories.Entities.CustomerProfileEntity", b => { b.Property<string>("CustomerId") .ValueGeneratedOnAdd() .HasColumnName("customer_id"); b.Property<int>("CountryOfNationalityId") .HasColumnName("country_of_nationality_id"); b.Property<int?>("CountryOfResidenceId") .HasColumnName("country_of_residence_id"); b.Property<int?>("CountryPhoneCodeId") .HasColumnName("country_phone_code_id"); b.Property<string>("Email") .IsRequired() .HasColumnName("email"); b.Property<string>("FirstName") .HasColumnName("first_name"); b.Property<bool>("IsEmailVerified") .HasColumnName("email_verified"); b.Property<bool>("IsPhoneVerified") .HasColumnName("phone_verified"); b.Property<string>("LastName") .HasColumnName("last_name"); b.Property<string>("LowerCasedEmail") .IsRequired() .HasColumnName("lower_cased_email"); b.Property<string>("PhoneNumber") .HasColumnName("phone_number"); b.Property<DateTime>("Registered") .HasColumnName("registered_at"); b.Property<string>("ShortPhoneNumber") .HasColumnName("short_phone_number"); b.Property<string>("TierId") .HasColumnName("tier_id"); b.Property<bool>("WasEmailEverVerified") .HasColumnName("was_email_ever_verified"); b.Property<bool>("WasPhoneEverVerified") .HasColumnName("was_phone_ever_verified"); b.HasKey("CustomerId"); b.HasIndex("Email") .IsUnique(); b.HasIndex("LowerCasedEmail") .IsUnique(); b.ToTable("customer_profile"); }); modelBuilder.Entity("MAVN.Service.CustomerProfile.MsSqlRepositories.Entities.LoginProviderEntity", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasColumnName("id") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("CustomerId") .IsRequired() .HasColumnName("customer_id"); b.Property<int>("LoginProvider") .HasColumnName("login_provider"); b.HasKey("Id"); b.HasIndex("CustomerId"); b.ToTable("login_providers"); }); modelBuilder.Entity("MAVN.Service.CustomerProfile.MsSqlRepositories.Entities.PartnerContactArchiveEntity", b => { b.Property<string>("LocationId") .ValueGeneratedOnAdd() .HasColumnName("location_id"); b.Property<string>("Email") .IsRequired() .HasColumnName("email"); b.Property<string>("FirstName") .HasColumnName("first_name"); b.Property<string>("LastName") .HasColumnName("last_name"); b.Property<string>("PhoneNumber") .HasColumnName("phone_number"); b.HasKey("LocationId"); b.ToTable("partner_contact_archive"); }); modelBuilder.Entity("MAVN.Service.CustomerProfile.MsSqlRepositories.Entities.PartnerContactEntity", b => { b.Property<string>("LocationId") .ValueGeneratedOnAdd() .HasColumnName("location_id"); b.Property<string>("Email") .IsRequired() .HasColumnName("email"); b.Property<string>("FirstName") .HasColumnName("first_name"); b.Property<string>("LastName") .HasColumnName("last_name"); b.Property<string>("PhoneNumber") .HasColumnName("phone_number"); b.HasKey("LocationId"); b.HasIndex("Email"); b.HasIndex("PhoneNumber"); b.ToTable("partner_contact"); }); modelBuilder.Entity("MAVN.Service.CustomerProfile.MsSqlRepositories.Entities.ReferralFriendProfileArchiveEntity", b => { b.Property<Guid>("ReferralFriendId") .ValueGeneratedOnAdd() .HasColumnName("referral_friend_id"); b.Property<string>("Email") .IsRequired() .HasColumnName("email"); b.Property<string>("FirstName") .IsRequired() .HasColumnName("first_name"); b.Property<string>("LastName") .IsRequired() .HasColumnName("last_name"); b.Property<Guid>("ReferrerId") .HasColumnName("referrer_id"); b.HasKey("ReferralFriendId"); b.ToTable("referral_friend_profiles_archive"); }); modelBuilder.Entity("MAVN.Service.CustomerProfile.MsSqlRepositories.Entities.ReferralFriendProfileEntity", b => { b.Property<Guid>("ReferralFriendId") .ValueGeneratedOnAdd() .HasColumnName("referral_friend_id"); b.Property<string>("Email") .IsRequired() .HasColumnName("email"); b.Property<string>("FirstName") .IsRequired() .HasColumnName("first_name"); b.Property<string>("LastName") .IsRequired() .HasColumnName("last_name"); b.Property<Guid>("ReferrerId") .HasColumnName("referrer_id"); b.HasKey("ReferralFriendId"); b.ToTable("referral_friend_profiles"); }); modelBuilder.Entity("MAVN.Service.CustomerProfile.MsSqlRepositories.Entities.ReferralHotelProfileArchiveEntity", b => { b.Property<Guid>("ReferralHotelId") .ValueGeneratedOnAdd() .HasColumnName("referral_hotel_id"); b.Property<string>("Email") .IsRequired() .HasColumnName("email"); b.HasKey("ReferralHotelId"); b.ToTable("referral_hotel_profiles_archive"); }); modelBuilder.Entity("MAVN.Service.CustomerProfile.MsSqlRepositories.Entities.ReferralHotelProfileEntity", b => { b.Property<Guid>("ReferralHotelId") .ValueGeneratedOnAdd() .HasColumnName("referral_hotel_id"); b.Property<string>("Email") .IsRequired() .HasColumnName("email"); b.Property<string>("Name") .IsRequired() .HasColumnName("name"); b.Property<string>("PhoneNumber") .IsRequired() .HasColumnName("phone_number"); b.HasKey("ReferralHotelId"); b.HasIndex("Email"); b.ToTable("referral_hotel_profiles"); }); modelBuilder.Entity("MAVN.Service.CustomerProfile.MsSqlRepositories.Entities.ReferralLeadProfileArchiveEntity", b => { b.Property<Guid>("ReferralLeadId") .ValueGeneratedOnAdd() .HasColumnName("referral_lead_id"); b.Property<string>("Email") .IsRequired() .HasColumnName("email"); b.Property<string>("FirstName") .IsRequired() .HasColumnName("first_name"); b.Property<string>("LastName") .IsRequired() .HasColumnName("last_name"); b.Property<string>("Note") .HasColumnName("note"); b.Property<string>("PhoneNumber") .IsRequired() .HasColumnName("phone_number"); b.HasKey("ReferralLeadId"); b.ToTable("referral_lead_profiles_archive"); }); modelBuilder.Entity("MAVN.Service.CustomerProfile.MsSqlRepositories.Entities.ReferralLeadProfileEntity", b => { b.Property<Guid>("ReferralLeadId") .ValueGeneratedOnAdd() .HasColumnName("referral_lead_id"); b.Property<string>("Email") .IsRequired() .HasColumnName("email"); b.Property<string>("FirstName") .IsRequired() .HasColumnName("first_name"); b.Property<string>("LastName") .IsRequired() .HasColumnName("last_name"); b.Property<string>("Note") .HasColumnName("note"); b.Property<string>("PhoneNumber") .IsRequired() .HasColumnName("phone_number"); b.HasKey("ReferralLeadId"); b.HasIndex("Email"); b.HasIndex("PhoneNumber"); b.ToTable("referral_lead_profiles"); }); modelBuilder.Entity("MAVN.Service.CustomerProfile.MsSqlRepositories.Entities.LoginProviderEntity", b => { b.HasOne("MAVN.Service.CustomerProfile.MsSqlRepositories.Entities.CustomerProfileEntity", "CustomerProfile") .WithMany("LoginProviders") .HasForeignKey("CustomerId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
37.121212
130
0.472478
[ "MIT" ]
HannaAndreevna/MAVN.Service.CustomerProfile
src/MAVN.Service.CustomerProfile.MsSqlRepositories/Migrations/20191129114316_AddReferralFriend.Designer.cs
17,150
C#
using System.Collections.Generic; using Domain.Models; using Microsoft.AspNetCore.Mvc; using Services.Interfaces; using WorkforceManagerAPI.ViewModels; namespace WorkforceManagerAPI.Controllers { [Route("api/[controller]")] [ApiController] public class SkillController : ControllerBase { private readonly ISkillService _skillService; public SkillController(ISkillService skillService) { _skillService = skillService; } // GET: api/Skill [HttpGet] public ActionResult<IEnumerable<Skill>> GetSkills() { var getResult = _skillService.GetAll(); if (getResult.Success) { return getResult.Data; } return NotFound(); } // GET: api/Skill/id [HttpGet("{id}")] public ActionResult<SkillViewModel> GetSkill(int id) { var getResult = _skillService.GetSkillById(id); if (!getResult.Success) { return NotFound(); } var skill = getResult.Data; return new SkillViewModel(skill); } // POST: api/Skill [HttpPost] public ActionResult<Skill> SaveSkill(Skill skill) { var saveEmployeeResult = _skillService.SaveSkill(skill); if (!saveEmployeeResult.Success) { return BadRequest(); } return Ok(); } // DELETE: api/Skill/id [HttpDelete("{id}")] public ActionResult<Skill> DeleteSkill(int id) { var removeResult = _skillService.RemoveSkill(id); if (removeResult.Success) return Ok(); if(removeResult.Message.Equals("NotFound")) return NotFound(); return BadRequest(); } // DELETE: api/Skill/MassRemoveSkills [HttpDelete] [Route("MassRemoveSkills")] public ActionResult<Skill> MassDelete(List<int> ids) { var removeResult = _skillService.MassRemoveSkills(ids); if(removeResult.Success) return Ok(); return BadRequest(); } } }
24.868132
68
0.548387
[ "MIT" ]
thiseasm/WorkforceManagerAPI
WorkforceManagerAPI/Controllers/SkillController.cs
2,265
C#
// ------------------------------------------------------------------------------ // <auto-generated> // This code was generated by SpecFlow (https://www.specflow.org/). // SpecFlow Version:3.9.0.0 // SpecFlow Generator Version:3.9.0.0 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> // ------------------------------------------------------------------------------ #region Designer generated code #pragma warning disable namespace Sfa.Tl.ResultsAndCertificationAutomation.Tests.Features.StatementOfAchievement { using TechTalk.SpecFlow; using System; using System.Linq; [System.CodeDom.Compiler.GeneratedCodeAttribute("TechTalk.SpecFlow", "3.9.0.0")] [System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [NUnit.Framework.TestFixtureAttribute()] [NUnit.Framework.DescriptionAttribute("3103_Statement of Achievement - \'Statements of achievement are not yet available\'" + "")] public partial class _3103_StatementOfAchievement_StatementsOfAchievementAreNotYetAvailableFeature { private TechTalk.SpecFlow.ITestRunner testRunner; private string[] _featureTags = ((string[])(null)); #line 1 "3103_SOANotAvailableYet.feature" #line hidden [NUnit.Framework.OneTimeSetUpAttribute()] public virtual void FeatureSetup() { testRunner = TechTalk.SpecFlow.TestRunnerManager.GetTestRunner(); TechTalk.SpecFlow.FeatureInfo featureInfo = new TechTalk.SpecFlow.FeatureInfo(new System.Globalization.CultureInfo("en-US"), "Tests/Features/StatementOfAchievement", "3103_Statement of Achievement - \'Statements of achievement are not yet available\'" + "", @" As a provider if I click on ‘Request a statement of achievement’ on my dashboard, if the date is before 10 August 2021 then display the following page: 'statements-of-achievement-not-available' so that I know I have to come back and request this when the printing is available from 10 August 2021", ProgrammingLanguage.CSharp, ((string[])(null))); testRunner.OnFeatureStart(featureInfo); } [NUnit.Framework.OneTimeTearDownAttribute()] public virtual void FeatureTearDown() { testRunner.OnFeatureEnd(); testRunner = null; } [NUnit.Framework.SetUpAttribute()] public virtual void TestInitialize() { } [NUnit.Framework.TearDownAttribute()] public virtual void TestTearDown() { testRunner.OnScenarioEnd(); } public virtual void ScenarioInitialize(TechTalk.SpecFlow.ScenarioInfo scenarioInfo) { testRunner.OnScenarioInitialize(scenarioInfo); testRunner.ScenarioContext.ScenarioContainer.RegisterInstanceAs<NUnit.Framework.TestContext>(NUnit.Framework.TestContext.CurrentContext); } public virtual void ScenarioStart() { testRunner.OnScenarioStart(); } public virtual void ScenarioCleanup() { testRunner.CollectScenarioErrors(); } public virtual void FeatureBackground() { #line 8 #line hidden #line 9 testRunner.Given("I have logged in as a \"ProviderBarnsleyPA\" user", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Given "); #line hidden } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("3103_Verify SOA not available yet page and Back link")] [NUnit.Framework.IgnoreAttribute("Ignored scenario")] [NUnit.Framework.CategoryAttribute("RegressionTest")] [NUnit.Framework.CategoryAttribute("SOA")] public virtual void _3103_VerifySOANotAvailableYetPageAndBackLink() { string[] tagsOfScenario = new string[] { "RegressionTest", "SOA", "Ignore"}; System.Collections.Specialized.OrderedDictionary argumentsOfScenario = new System.Collections.Specialized.OrderedDictionary(); TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("3103_Verify SOA not available yet page and Back link", null, tagsOfScenario, argumentsOfScenario, this._featureTags); #line 12 this.ScenarioInitialize(scenarioInfo); #line hidden bool isScenarioIgnored = default(bool); bool isFeatureIgnored = default(bool); if ((tagsOfScenario != null)) { isScenarioIgnored = tagsOfScenario.Where(__entry => __entry != null).Where(__entry => String.Equals(__entry, "ignore", StringComparison.CurrentCultureIgnoreCase)).Any(); } if ((this._featureTags != null)) { isFeatureIgnored = this._featureTags.Where(__entry => __entry != null).Where(__entry => String.Equals(__entry, "ignore", StringComparison.CurrentCultureIgnoreCase)).Any(); } if ((isScenarioIgnored || isFeatureIgnored)) { testRunner.SkipScenario(); } else { this.ScenarioStart(); #line 8 this.FeatureBackground(); #line hidden #line 13 testRunner.And("I click on \"Request statement of achievement\" link", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden #line 14 testRunner.Then("I am navigated to the SOA not yet available page if the date is less than 10th Au" + "gust 2021", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden #line 15 testRunner.When("I click the back link on the SOA not yet available page then I am taken back to t" + "he dashboard", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line hidden #line 16 testRunner.Then("I will be navigated to the T Levels Dashboard page", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden } this.ScenarioCleanup(); } [NUnit.Framework.TestAttribute()] [NUnit.Framework.DescriptionAttribute("3103_Verify Back to home button on SOA not yet available page")] [NUnit.Framework.IgnoreAttribute("Ignored scenario")] [NUnit.Framework.CategoryAttribute("RegressionTest")] [NUnit.Framework.CategoryAttribute("SOA")] public virtual void _3103_VerifyBackToHomeButtonOnSOANotYetAvailablePage() { string[] tagsOfScenario = new string[] { "RegressionTest", "SOA", "Ignore"}; System.Collections.Specialized.OrderedDictionary argumentsOfScenario = new System.Collections.Specialized.OrderedDictionary(); TechTalk.SpecFlow.ScenarioInfo scenarioInfo = new TechTalk.SpecFlow.ScenarioInfo("3103_Verify Back to home button on SOA not yet available page", null, tagsOfScenario, argumentsOfScenario, this._featureTags); #line 19 this.ScenarioInitialize(scenarioInfo); #line hidden bool isScenarioIgnored = default(bool); bool isFeatureIgnored = default(bool); if ((tagsOfScenario != null)) { isScenarioIgnored = tagsOfScenario.Where(__entry => __entry != null).Where(__entry => String.Equals(__entry, "ignore", StringComparison.CurrentCultureIgnoreCase)).Any(); } if ((this._featureTags != null)) { isFeatureIgnored = this._featureTags.Where(__entry => __entry != null).Where(__entry => String.Equals(__entry, "ignore", StringComparison.CurrentCultureIgnoreCase)).Any(); } if ((isScenarioIgnored || isFeatureIgnored)) { testRunner.SkipScenario(); } else { this.ScenarioStart(); #line 8 this.FeatureBackground(); #line hidden #line 20 testRunner.And("I click on \"Request statement of achievement\" link", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "And "); #line hidden #line 21 testRunner.Then("I am navigated to the SOA not yet available page if the date is less than 10th Au" + "gust 2021", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden #line 22 testRunner.When("I click the Back to home button on the SOA not yet available page then I am taken" + " back to the dashboard", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "When "); #line hidden #line 23 testRunner.Then("I will be navigated to the T Levels Dashboard page", ((string)(null)), ((TechTalk.SpecFlow.Table)(null)), "Then "); #line hidden } this.ScenarioCleanup(); } } } #pragma warning restore #endregion
44.277228
265
0.633609
[ "MIT" ]
SkillsFundingAgency/tl-results-and-certification-automation-suite
src/Sfa.Tl.ResultsAndCertificationAutomation/Tests/Features/StatementOfAchievement/3103_SOANotAvailableYet.feature.cs
8,950
C#
/* * EasyBimehLanding.Standard * * This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). */ using System; using System.IO; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using EasyBimehLanding.Standard; using EasyBimehLanding.Standard.Utilities; namespace EasyBimehLanding.Standard.Models { public class BaseModelUpload : BaseModel { // These fields hold the values for the public properties. private bool isSuccess; private int status; private object message; private string extraData; private string exception; /// <summary> /// وضعیت موفقیت درخواست /// </summary> [JsonProperty("isSuccess")] public bool IsSuccess { get { return this.isSuccess; } set { this.isSuccess = value; onPropertyChanged("IsSuccess"); } } /// <summary> /// کد وضعیت درخواست /// </summary> [JsonProperty("status")] public int Status { get { return this.status; } set { this.status = value; onPropertyChanged("Status"); } } /// <summary> /// بدنه ی اصلی درخواست که با توجه به نوع درخواست، تغییر می کند /// </summary> [JsonProperty("message")] public object Message { get { return this.message; } set { this.message = value; onPropertyChanged("Message"); } } /// <summary> /// اطلاعات اضافه ی درخواست /// </summary> [JsonProperty("extraData")] public string ExtraData { get { return this.extraData; } set { this.extraData = value; onPropertyChanged("ExtraData"); } } /// <summary> /// اطلاعات خطاهای رخ داده /// </summary> [JsonProperty("exception")] public string Exception { get { return this.exception; } set { this.exception = value; onPropertyChanged("Exception"); } } } }
24.478261
83
0.449378
[ "MIT" ]
kmelodi/EasyBimehLanding_.NET
EasyBimehLanding.Standard/Models/BaseModelUpload.cs
2,933
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; /// <summary> /// System.Boolean.IConvertible.ToSingle /// </summary> public class BooleanIConvertibleToSingle { public static int Main() { BooleanIConvertibleToSingle testCase = new BooleanIConvertibleToSingle(); TestLibrary.TestFramework.BeginTestCase("Boolean.IConvertible.ToSingle"); if (testCase.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; return retVal; } public bool PosTest1() { bool retVal = true; try { if ((true as IConvertible).ToSingle(null) != 1.0f) { TestLibrary.TestFramework.LogError("001", "expect (true as IConvertible).ToSingle(null) == 1.0f"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("001", "Unexpected exception: " + e); retVal = false; } return retVal; } public bool PosTest2() { bool retVal = true; try { if ((false as IConvertible).ToSingle(null) != 0.0f) { TestLibrary.TestFramework.LogError("002", "expect (false as IConvertible).ToSingle(null) == 0.0f"); retVal = false; } } catch (Exception e) { TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e); retVal = false; } return retVal; } }
27.2875
115
0.558864
[ "MIT" ]
AaronRobinsonMSFT/coreclr
tests/src/CoreMangLib/cti/system/boolean/booleaniconvertibletosingle.cs
2,183
C#
using System; using System.Collections.Generic; using System.Linq; namespace _03.LegendaryFarming { class Program { static void Main(string[] args) { Dictionary<string, int> keyMaterials = new Dictionary<string, int>(); Dictionary<string, int> junkItems = new Dictionary<string, int>(); bool isLegendary = true; while (isLegendary) { string[] input = Console.ReadLine().Split().ToArray(); // 6 leathers 255 fragments 7 Shards for (int i = 0; i < input.Length - 1; i++) { int quantity = 0; string material = string.Empty; if (i % 2 == 0) { quantity = int.Parse(input[i]); material = input[i + 1].ToLower(); if (material == "shards" || material == "fragments" || material == "motes") { if (!keyMaterials.ContainsKey("shards") || !keyMaterials.ContainsKey("fragments") || !keyMaterials.ContainsKey("motes")) { keyMaterials.Add("shards", 0); keyMaterials.Add("fragments", 0); keyMaterials.Add("motes", 0); } if (keyMaterials.ContainsKey(material)) { keyMaterials[material] += quantity; } if (keyMaterials[material] >= 250) { PrintLegendaryItem(material); keyMaterials[material] -= 250; isLegendary = false; } if (!isLegendary) { break; } } else { if (junkItems.ContainsKey(material)) { junkItems[material] += quantity; } else { junkItems.Add(material, quantity); } } } } } var sortedMaterials = keyMaterials .OrderByDescending(x => x.Value) .ThenBy(x => x.Key) .ToList(); foreach (var pair in sortedMaterials) { Console.WriteLine(pair.Key + ": " + pair.Value); } var sortedJunkItems = junkItems .OrderBy(x => x.Key) .ToList(); foreach (var pair in sortedJunkItems) { Console.WriteLine(pair.Key + ": " + pair.Value); } } static void PrintLegendaryItem(string item) { if (item == "shards") { Console.WriteLine("Shadowmourne obtained!"); } else if (item == "fragments") { Console.WriteLine("Valanyr obtained!"); } else if (item == "motes") { Console.WriteLine("Dragonwrath obtained!"); } } } }
34.252336
109
0.361255
[ "MIT" ]
yovko93/CSharp-Repo
CSharp_Fundamentals/AssociativeArraysExercise/03.LegendaryFarming/Program.cs
3,667
C#
using System; using System.Diagnostics; using Microsoft.AspNetCore.Mvc; namespace app.Controllers { public class FileAccessController : Controller { [HttpGet] public IActionResult Index() { var filename = HttpContext.Request.Query["filename"].ToString(); if (filename.Length > 0) { ViewBag.FileContent = System.IO.File.ReadAllText(filename); } return View(); } } }
22.136364
76
0.577002
[ "MIT" ]
mawinkler/c1-app-sec-dotnet-vulnerable
Controllers/FileAccessController.cs
487
C#
namespace Rhino.Etl.Tests.Joins { using System.Collections.Generic; using Core; public class ComplexUsersToPeopleJoinProcess : EtlProcess { private readonly IEnumerable<Row> left; private readonly IEnumerable<Row> right; public List<Row> Results = new List<Row>(); public ComplexUsersToPeopleJoinProcess(IEnumerable<Row> left, IEnumerable<Row> right) { this.left = left; this.right = right; } protected override void Initialize() { Register( new RightJoinUsersToPeopleByEmail() .Left(Partial .Register(new GenericEnumerableOperation(left)) .Register(new AllStringsToUpperCase())) .Right(Partial .Register(new GenericEnumerableOperation(right)) .Register(new AllStringsToUpperCase())) ); Register(new AddToResults(Results)); } } }
34.090909
94
0.52
[ "BSD-3-Clause" ]
brumschlag/rhino-tools
rhino-etl/Rhino.Etl.Tests/Joins/ComplexUsersToPeopleJoinProcess.cs
1,125
C#
using System; using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using DhtReadService; namespace Tests { [TestClass] public class UnitTest1 { public object BitVector { get; private set; } [TestMethod] public void BitVector_starts_in_false() { BitVector v = new BitVector(40); for (uint i = 0; i < 40; i++) { Assert.IsFalse(v[i]); } } [TestMethod] public void BitVector_the_bit_is_set() { BitVector v = new BitVector(40); v[0] = true; Assert.IsTrue(v[0]); for (uint i = 1; i < 40; i++) { Assert.IsFalse(v[i]); } } [TestMethod] public void BitVector_any_bit_is_set_and_reset() { BitVector v = new BitVector(40); for (uint i = 1; i < 40; i++) { v[i] = true; Assert.IsTrue(v[i]); } for (uint i = 1; i < 40; i++) { v[i] = false; Assert.IsFalse(v[i]); } } [TestMethod] public void BitVector_conversion_gets_correct_array_length() { BitVector v = new BitVector(40); uint[] value = v.ToUintValues(); Assert.AreEqual(2, value.Length); Assert.AreEqual((uint)0, value[0]); ulong[] longvalues = v.ToULongValues(); Assert.AreEqual(1, longvalues.Length); Assert.AreEqual((ulong)0, longvalues[0]); } [TestMethod] public void BitVector_conversion_gets_correct_long_values() { BitVector v = new BitVector(40); v[0] = true; Assert.AreEqual((ulong)1, v.ToULongValues()[0]); v[1] = true; Assert.AreEqual((ulong)3, v.ToULongValues()[0]); v[0] = false; Assert.AreEqual((ulong)2, v.ToULongValues()[0]); v[1] = false; v[32] = true; Assert.AreEqual((ulong)4294967296, v.ToULongValues()[0]); } [TestMethod] public void BitVector_conversion_gets_correct_int_values() { BitVector v = new BitVector(40); v[0] = true; Assert.AreEqual((uint)1, v.ToUintValues()[0]); v[1] = true; Assert.AreEqual((uint)3, v.ToUintValues()[0]); v[0] = false; Assert.AreEqual((uint)2, v.ToUintValues()[0]); v[1] = false; v[32] = true; Assert.AreEqual((uint)0, v.ToUintValues()[0]); Assert.AreEqual((uint)1, v.ToUintValues()[1]); } } }
26.09434
69
0.481562
[ "MIT" ]
jmservera/IoTHubDemo
IoTSensors/Tests/UnitTest.cs
2,768
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using Dot.Net.DevFast.Extensions; using Dot.Net.DevFast.Extensions.JsonExt; using Newtonsoft.Json; namespace Dot.Net.DevFast.Sample.JsonSample.JsonEnumeration { public static class LatencyFileDeserializationZeroComputation { public static void Run() { Console.Out.WriteLine("-------JsonEnumeration Deserialization-------"); Console.Out.WriteLine("x64 App: " + Environment.Is64BitProcess); //Small Object serialization in 10M loops RunBoth(); } private static void RunBoth() { //warm up var jsonFile = new FileInfo(@"C:\Temp\jsonEnumTest.json"); //jsonFile.MeasureJsonConvert(false); var jsonTime = jsonFile.MeasureJsonConvert(); GC.Collect(); GC.WaitForFullGCApproach(); GC.WaitForFullGCComplete(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForFullGCApproach(); GC.WaitForFullGCComplete(); GC.WaitForPendingFinalizers(); //warm up var devFastJsonFile = new FileInfo(@"C:\Temp\jsonEnumDfTest.json"); //devFastJsonFile.MeasureDevFast(false); var devfastTime = devFastJsonFile.MeasureDevFast(); var dfFastness = ((int)((100 - (devfastTime / jsonTime * 100)) * 100)) / 100.0; Console.Out.WriteLine("DevFast " + Math.Abs(dfFastness) + (dfFastness < 0 ? " % Slower" : " % Faster")); Console.Out.WriteLine(); } private static double MeasureJsonConvert(this FileInfo jsonFile, bool print = true) { var sw = Stopwatch.StartNew(); //We deserialize and loop on the array. var count = JsonConvert.DeserializeObject<LargeObj[]>(File.ReadAllText(jsonFile.FullName)).Count(); sw.Stop(); if (print) { Console.Out.WriteLine("JsonConvert Total Time: " + sw.Elapsed.TotalMilliseconds); jsonFile.Refresh(); Console.Out.WriteLine("FileLen: " + jsonFile.Length); Console.Out.WriteLine("Count: " + count); } return sw.Elapsed.TotalMilliseconds; } private static double MeasureDevFast(this FileInfo jsonFile, bool print = true) { var sw = Stopwatch.StartNew(); //We deserialize the IEnumerable and loop var count = jsonFile.CreateStream(FileMode.Open, options: FileOptions.SequentialScan, bufferSize:32*1024) .FromJsonAsEnumerable<LargeObj>(new JsonSerializer(), bufferSize: 32 * 1024) .Count(); sw.Stop(); if (print) { Console.Out.WriteLine("DevFast Total Time: " + sw.Elapsed.TotalMilliseconds); jsonFile.Refresh(); Console.Out.WriteLine("FileLen: " + jsonFile.Length); Console.Out.WriteLine("Count: " + count); } return sw.Elapsed.TotalMilliseconds; } private static readonly LargeObj LargeObj = new LargeObj { Address = "123, Json street", Age = 20, Name = "Json Born", City = "LDN", Country = "Macedonia", AboutMe = "A small world" }; } }
37.478723
116
0.57224
[ "MIT" ]
samaysar/dotdotnet
samples/Dot.Net.DevFast.Sample/Dot.Net.DevFast.Sample/JsonSample/JsonEnumeration/LatencyFileDeserializationZeroComputation.cs
3,525
C#
namespace TeamServer.Models { public class ImplantData { public string ID { get; set; } public string HostName { get; set; } public string User { get; set; } public string ProcName { get; set; } public int ProcID { get; set; } public string Integrity { get; set; } public string Arch { get; set; } public string IPAddr { get; set; } } }
27.6
45
0.567633
[ "MIT" ]
Gr1mmie/AtlasC2
TeamServer/Models/Implants/ImplantData.cs
416
C#
using System; using System.Collections.Generic; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.IdentityModel.Tokens; using Senai.AutoPecas.WebApi.Domains; using Senai.AutoPecas.WebApi.Interfaces; using Senai.AutoPecas.WebApi.Repositories; using Senai.AutoPecas.WebApi.ViewModels; namespace Senai.AutoPecas.WebApi.Controllers { [Route("api/[controller]")] [Produces("application/json")] [ApiController] public class LoginController : ControllerBase { private IUsuarioRepository UsuarioRepository { get; set; } public LoginController() { UsuarioRepository = new UsuarioRepository(); } [HttpPost] public IActionResult Login(LoginViewModel login) { try { Usuarios usuarioBuscado = UsuarioRepository.BuscarPorEmailESenha(login); if (usuarioBuscado == null) return NotFound(new { mensagem = "Email ou Senha Inválidos." }); // informacoes referentes ao usuarios var claims = new[] { new Claim("chave", "0123456789"), new Claim(JwtRegisteredClaimNames.Email, usuarioBuscado.Email), new Claim(JwtRegisteredClaimNames.Jti, usuarioBuscado.IdUsuario.ToString()), new Claim(ClaimTypes.Role, usuarioBuscado.Permissao), }; var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes("autopecas-chave-autenticacao")); var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken( issuer: "AutoPecas.WebApi", audience: "AutoPecas.WebApi", claims: claims, expires: DateTime.Now.AddMinutes(30), signingCredentials: creds); return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) }); } catch (Exception ex) { return BadRequest(new { mensagem = "Erro ao logar." }); } } } }
33.722222
119
0.596787
[ "MIT" ]
geovannanogueira/Senai.AutoPecas
Api/Senai.AutoPecas.WebApi/Senai.AutoPecas.WebApi/Controllers/LoginController.cs
2,431
C#
namespace ClearHl7.Codes.V281 { /// <summary> /// HL7 Version 2 Table 0918 - PCA Type. /// </summary> /// <remarks>https://www.hl7.org/fhir/v2/0918</remarks> public enum CodePcaType { /// <summary> /// C - Continuous. /// </summary> Continuous, /// <summary> /// P - PCA Only. /// </summary> PcaOnly, /// <summary> /// PC - PCA + Continuous. /// </summary> PcaContinuous } }
20.08
59
0.462151
[ "MIT" ]
kamlesh-microsoft/clear-hl7-net
src/ClearHl7.Codes/V281/CodePcaType.cs
504
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace AutoCompleteTextBox.Demo.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AutoCompleteTextBox.Demo.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
44.921875
191
0.602783
[ "MIT" ]
Bartizan/WPF-AutoComplete-TextBox
AutoCompleteTextBox/AutoCompleteTextBox.Demo/Properties/Resources.Designer.cs
2,877
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Reflection; using Microsoft.Internal; namespace System.ComponentModel.Composition.ReflectionModel { internal class ReflectionField : ReflectionWritableMember { private readonly FieldInfo _field; public ReflectionField(FieldInfo field) { if (field == null) { throw new ArgumentNullException(nameof(field)); } _field = field; } public FieldInfo UndelyingField { get { return _field; } } public override MemberInfo UnderlyingMember { get { return UndelyingField; } } public override bool CanRead { get { return true; } } public override bool CanWrite { get { return !UndelyingField.IsInitOnly; } } public override bool RequiresInstance { get { return !UndelyingField.IsStatic; } } public override Type ReturnType { get { return UndelyingField.FieldType; } } public override ReflectionItemType ItemType { get { return ReflectionItemType.Field; } } public override object? GetValue(object? instance) { return UndelyingField.SafeGetValue(instance); } public override void SetValue(object? instance, object? value) { UndelyingField.SafeSetValue(instance, value); } } }
24.614286
71
0.583865
[ "MIT" ]
06needhamt/runtime
src/libraries/System.ComponentModel.Composition/src/System/ComponentModel/Composition/ReflectionModel/ReflectionField.cs
1,723
C#
using System; using System.Linq; using UnityEngine; using UnityEngine.Timeline; namespace UnityEditor.Timeline { class TrimItemModeMix : ITrimItemMode, ITrimItemDrawer { ITrimmable m_Item; double m_Min; double m_Max; public void OnBeforeTrim(ITrimmable item, TrimEdge trimDirection) { m_Item = item; var sortedItems = ItemsUtils.GetItemsExcept(item.parentTrack, new[] { item }) .OfType<ITrimmable>() .OrderBy(c => c.start); var itemStart = (DiscreteTime)item.start; var itemEnd = (DiscreteTime)item.end; var overlapped = sortedItems.LastOrDefault(c => (DiscreteTime)c.start == itemStart && (DiscreteTime)c.end == itemEnd); ITrimmable nextItem; ITrimmable prevItem; m_Min = 0.0; m_Max = double.PositiveInfinity; var blendableItem = item as IBlendable; if (blendableItem != null && blendableItem.supportsBlending) { if (trimDirection == TrimEdge.Start) { nextItem = sortedItems.FirstOrDefault(c => (DiscreteTime)c.start >= itemStart && (DiscreteTime)c.end > itemEnd); prevItem = sortedItems.LastOrDefault(c => (DiscreteTime)c.start <= itemStart && (DiscreteTime)c.end < itemEnd); if (prevItem != null) m_Min = prevItem.start + EditModeUtils.BlendDuration(prevItem, TrimEdge.Start); if (nextItem != null) m_Max = nextItem.start; } else { nextItem = sortedItems.FirstOrDefault(c => c != overlapped && (DiscreteTime)c.start >= itemStart && (DiscreteTime)c.end >= itemEnd); prevItem = sortedItems.LastOrDefault(c => c != overlapped && (DiscreteTime)c.start <= itemStart && (DiscreteTime)c.end <= itemEnd); if (prevItem != null) m_Min = prevItem.end; if (nextItem != null) m_Max = nextItem.end - EditModeUtils.BlendDuration(nextItem, TrimEdge.End); } } else { nextItem = sortedItems.FirstOrDefault(c => (DiscreteTime)c.start > itemStart); prevItem = sortedItems.LastOrDefault(c => (DiscreteTime)c.start < itemStart); if (prevItem != null) m_Min = prevItem.end; if (nextItem != null) m_Max = nextItem.start; } } public void TrimStart(ITrimmable item, double time, bool affectTimeScale) { time = Math.Min(Math.Max(time, m_Min), m_Max); item.SetStart(time, affectTimeScale); } public void TrimEnd(ITrimmable item, double time, bool affectTimeScale) { time = Math.Min(Math.Max(time, m_Min), m_Max); item.SetEnd(time, affectTimeScale); } public void DrawGUI(WindowState state, Rect bounds, Color color, TrimEdge edge) { if (EditModeUtils.HasBlends(m_Item, edge)) { EditModeGUIUtils.DrawBoundsEdge(bounds, color, edge); var cursorType = (edge == TrimEdge.End) ? TimelineCursors.CursorType.MixRight : TimelineCursors.CursorType.MixLeft; TimelineCursors.SetCursor(cursorType); } else { TimelineCursors.ClearCursor(); } } } }
35.582524
152
0.538881
[ "Apache-2.0" ]
ASlugin/Homework-2sem
SCP-087/Library/PackageCache/com.unity.timeline@1.6.4/Editor/Manipulators/Trim/TrimItemModeMix.cs
3,665
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using StructureMap.Pipeline; using StructureMap.Query; using StructureMap.TypeRules; namespace StructureMap.Diagnostics { public class PipelineGraphValidator { private readonly IList<Guid> _buildPlanFailureIds = new List<Guid>(); private readonly IList<ProfileReport> _reports = new List<ProfileReport>(); public static void AssertNoErrors(IPipelineGraph graph) { var validator = new PipelineGraphValidator(); findPipelines(graph).Each(x => validator.Validate(graph, graph.Policies)); validator.AssertIsValid(); } public void AssertIsValid() { var reports = _reports.Where(x => x.HasAnyErrors()).ToArray(); if (reports.Any()) { var errorCount = reports.Sum(x => x.Errors.Count()); var validationCount = reports.Sum(x => x.Validations.Count()); var title = "StructureMap Failures: {0} Build/Configuration Failures and {1} Validation Errors".ToFormat( errorCount, validationCount); var writer = new StringWriter(); reports.Each(x => x.WriteErrorMessages(writer)); var ex = new StructureMapConfigurationException(title) {Context = writer.ToString()}; throw ex; } } private static IEnumerable<IPipelineGraph> findPipelines(IPipelineGraph graph) { yield return graph; if (graph.Role == ContainerRole.Root) { foreach (var profile in graph.Profiles.AllProfiles()) { yield return profile; } } } public void Validate(IPipelineGraph pipeline, Policies policies) { var report = new ProfileReport(pipeline); _reports.Add(report); var closedTypes = pipeline.ToModel().PluginTypes.Where(x => !x.PluginType.IsOpenGeneric()).ToArray(); closedTypes.Each( family => { family.Instances.Each(i => { tryCreateBuildPlan(family.PluginType, i, policies, report); }); }); closedTypes.Each( family => { family.Instances.Where(x => !_buildPlanFailureIds.Contains(x.Instance.Id)) .Each(i => { tryBuildInstance(family.PluginType, i.Instance, pipeline, report); }); }); } private void tryBuildInstance(Type pluginType, Instance instance, IPipelineGraph pipeline, ProfileReport report) { var session = new BuildSession(pipeline, instance.Name); try { var @object = session.FindObject(pluginType, instance); validate(pluginType, instance, @object, report); } catch (StructureMapException ex) { ex.Instances.Each(x => _buildPlanFailureIds.Fill(x)); report.AddError(pluginType, instance, ex); } } private void tryCreateBuildPlan(Type pluginType, InstanceRef instanceRef, Policies policies, ProfileReport report) { try { instanceRef.Instance.ResolveBuildPlan(pluginType, policies); } catch (StructureMapException e) { _buildPlanFailureIds.Add(instanceRef.Instance.Id); e.Instances.Fill(instanceRef.Instance.Id); report.AddError(pluginType, instanceRef.Instance, e); } } private void validate(Type pluginType, Instance instance, object builtObject, ProfileReport report) { if (builtObject == null) return; var methods = ValidationMethodAttribute.GetValidationMethods(builtObject.GetType()); foreach (var method in methods) { try { method.Invoke(builtObject, new object[0]); } catch (Exception ex) { var error = new ValidationError(pluginType, instance, ex.InnerException, method); report.AddValidationError(error); } } } } }
35
120
0.55613
[ "Apache-2.0" ]
CurufinweU/structuremap
src/StructureMap/Diagnostics/PipelineGraphValidator.cs
4,447
C#
using System; using System.Data; using Microsoft.Data.SqlClient; namespace Infrastructure.SqlConnections { public class SqlConnectionFactory : ISqlConnectionFactory, IDisposable { private readonly string _connectionString; private IDbConnection _connection; public SqlConnectionFactory(string connectionString) { _connectionString = connectionString; } public void Dispose() { if (ConnectionOpened()) _connection.Dispose(); } public IDbConnection GetConnection() { if (ConnectionOpened()) return _connection; _connection = new SqlConnection(_connectionString); _connection.Open(); return _connection; } private bool ConnectionOpened() { return _connection != null && _connection.State == ConnectionState.Open; } } }
26.805556
85
0.603109
[ "MIT" ]
marcinlovescode/CQRS.SingleDatabase
Infrastructure/SqlConnections/SQLConnectionFactory.cs
967
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text.RegularExpressions; using Abp.Auditing; using Abp.Authorization.Users; using Abp.Extensions; namespace Volo.PostgreSqlDemo.Web.Models.Account { public class RegisterViewModel : IValidatableObject { [Required] [StringLength(AbpUserBase.MaxNameLength)] public string Name { get; set; } [Required] [StringLength(AbpUserBase.MaxSurnameLength)] public string Surname { get; set; } [StringLength(AbpUserBase.MaxUserNameLength)] public string UserName { get; set; } [Required] [EmailAddress] [StringLength(AbpUserBase.MaxEmailAddressLength)] public string EmailAddress { get; set; } [StringLength(AbpUserBase.MaxPlainPasswordLength)] [DisableAuditing] public string Password { get; set; } public bool IsExternalLogin { get; set; } public string ExternalLoginAuthSchema { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (!UserName.IsNullOrEmpty()) { var emailRegex = new Regex(@"^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"); if (!UserName.Equals(EmailAddress) && emailRegex.IsMatch(UserName)) { yield return new ValidationResult("Username cannot be an email address unless it's the same as your email address!"); } } } } }
32
137
0.624362
[ "MIT" ]
OzBob/aspnetboilerplate-samples
PostgreSqlDemo/aspnet-core/src/Volo.PostgreSqlDemo.Web.Mvc/Models/Account/RegisterViewModel.cs
1,568
C#
/* The MIT License (MIT) Copyright 2021 Adam Reilly, Call to Action Software LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ namespace Cta { /// <summary> /// Definitions for commonly used data across multiple systems /// </summary> static public class Defines { public const string CallToActionMenuItem = "Call to Action"; public const string AIMenuItem = "AI"; public const string AnimationMenuItem = "Animation"; public const string AudioMenuItem = "Audio"; public const string EffectsMenuItem = "Effects"; public const string EventsMenuItem = "Events"; public const string UIMenuItem = "UI"; public const string IOMenuItem = "IO"; public const string UIElementsMenuItem = "Elements"; public const string UIMenusMenuItem = "Menus"; public const string CombatMenuItem = "Combat"; public const string MovementMenuItem = "Movement"; public const string LocalizationMenuItem = "Localization"; public const string LoggingMenuItem = "Logging"; public const string NetworkMenuItem = "Network"; public const string UtilsMenuItem = "Utils"; public const string PhysicsMenuItem = "Physics"; public const string RenderingMenuItem = "Rendering"; public const string TerrainMenuItem = "Terrain"; public const string InputMenuItem = "Input"; public const string ScenarioMenuItem = "Scenario"; public const string CoreMenuItem = "Core"; public const string MathMenuItem = "Math"; public const string EasingMenuItem = "Easing"; public const string GameplayMenuItem = "Gameplay"; public const string TmtMenuItem = "Tmt"; public const string XRMenuItem = "XR"; public const string AppConfigDefaultName = "app_config_default"; public const string AppConfigName = "app_config"; } static public class CommandLineArgs { /// <summary> /// specifies the starting scene /// </summary> public const string Scene = "scene"; /// <summary> /// specifies the port of communication for training management tools /// </summary> public const string TmtPort = "tmtport"; /// <summary> /// specifies the port of communication for networked games /// </summary> public const string GamePort = "gameport"; /// <summary> /// specifies the port of communication for google remote procedure calls /// </summary> public const string GRpcPort = "grpcport"; /// <summary> /// specifies whether to immediately start the game server or not /// </summary> public const string StartServer = "startserver"; /// <summary> /// Specifies the password of the server /// </summary> public const string ServerName = "servername"; /// <summary> /// Specifies the display name of the server /// </summary> public const string ServerPassword = "serverpassword"; /// <summary> /// The rotation sequence that should be output to TMT /// </summary> public const string TmtRotSeqOutput = "tmt_rotseq_output"; } /// <summary> /// Used for controlling simulations /// </summary> public enum SimulationControlType { /// <summary> /// Begin the simulation /// </summary> Begin, /// <summary> /// End the simulation /// </summary> End, /// <summary> /// Pause the simulation /// </summary> Pause, /// <summary> /// Resume the simulation /// </summary> Resume } public enum WeatherType { Clear, Fog, Overcast, Rain } /// <summary> /// The level of quality /// </summary> public enum Fidelity { Low, Medium, High, } public enum SystemPriority { High = -50, Normal = 0, Low = 50, } }
35.618056
460
0.633067
[ "MIT" ]
areilly711/CtaApi
Unity/CtaApi/Packages/com.calltoaction.ctaapi/CtaApi/Runtime/Scripts/Core/Defines.cs
5,129
C#
using System.Collections.Generic; using System.IO; using Datadog.Trace.PlatformHelpers; using Xunit; namespace Datadog.Trace.Tests.PlatformHelpers { public class ContainerMetadataTests { public const string Docker = @" 13:name=systemd:/docker/3726184226f5d3147c25fdeab5b60097e378e8a720503a5e19ecfdf29f869860 12:pids:/docker/3726184226f5d3147c25fdeab5b60097e378e8a720503a5e19ecfdf29f869860 11:hugetlb:/docker/3726184226f5d3147c25fdeab5b60097e378e8a720503a5e19ecfdf29f869860 10:net_prio:/docker/3726184226f5d3147c25fdeab5b60097e378e8a720503a5e19ecfdf29f869860 9:perf_event:/docker/3726184226f5d3147c25fdeab5b60097e378e8a720503a5e19ecfdf29f869860 8:net_cls:/docker/3726184226f5d3147c25fdeab5b60097e378e8a720503a5e19ecfdf29f869860 7:freezer:/docker/3726184226f5d3147c25fdeab5b60097e378e8a720503a5e19ecfdf29f869860 6:devices:/docker/3726184226f5d3147c25fdeab5b60097e378e8a720503a5e19ecfdf29f869860 5:memory:/docker/3726184226f5d3147c25fdeab5b60097e378e8a720503a5e19ecfdf29f869860 4:blkio:/docker/3726184226f5d3147c25fdeab5b60097e378e8a720503a5e19ecfdf29f869860 3:cpuacct:/docker/3726184226f5d3147c25fdeab5b60097e378e8a720503a5e19ecfdf29f869860 2:cpu:/docker/3726184226f5d3147c25fdeab5b60097e378e8a720503a5e19ecfdf29f869860 1:cpuset:/docker/3726184226f5d3147c25fdeab5b60097e378e8a720503a5e19ecfdf29f869860"; public const string Kubernetes = @" 11:perf_event:/kubepods/besteffort/pod3d274242-8ee0-11e9-a8a6-1e68d864ef1a/3e74d3fd9db4c9dd921ae05c2502fb984d0cde1b36e581b13f79c639da4518a1 10:pids:/kubepods/besteffort/pod3d274242-8ee0-11e9-a8a6-1e68d864ef1a/3e74d3fd9db4c9dd921ae05c2502fb984d0cde1b36e581b13f79c639da4518a1 9:memory:/kubepods/besteffort/pod3d274242-8ee0-11e9-a8a6-1e68d864ef1a/3e74d3fd9db4c9dd921ae05c2502fb984d0cde1b36e581b13f79c639da4518a1 8:cpu,cpuacct:/kubepods/besteffort/pod3d274242-8ee0-11e9-a8a6-1e68d864ef1a/3e74d3fd9db4c9dd921ae05c2502fb984d0cde1b36e581b13f79c639da4518a1 7:blkio:/kubepods/besteffort/pod3d274242-8ee0-11e9-a8a6-1e68d864ef1a/3e74d3fd9db4c9dd921ae05c2502fb984d0cde1b36e581b13f79c639da4518a1 6:cpuset:/kubepods/besteffort/pod3d274242-8ee0-11e9-a8a6-1e68d864ef1a/3e74d3fd9db4c9dd921ae05c2502fb984d0cde1b36e581b13f79c639da4518a1 5:devices:/kubepods/besteffort/pod3d274242-8ee0-11e9-a8a6-1e68d864ef1a/3e74d3fd9db4c9dd921ae05c2502fb984d0cde1b36e581b13f79c639da4518a1 4:freezer:/kubepods/besteffort/pod3d274242-8ee0-11e9-a8a6-1e68d864ef1a/3e74d3fd9db4c9dd921ae05c2502fb984d0cde1b36e581b13f79c639da4518a1 3:net_cls,net_prio:/kubepods/besteffort/pod3d274242-8ee0-11e9-a8a6-1e68d864ef1a/3e74d3fd9db4c9dd921ae05c2502fb984d0cde1b36e581b13f79c639da4518a1 2:hugetlb:/kubepods/besteffort/pod3d274242-8ee0-11e9-a8a6-1e68d864ef1a/3e74d3fd9db4c9dd921ae05c2502fb984d0cde1b36e581b13f79c639da4518a1 1:name=systemd:/kubepods/besteffort/pod3d274242-8ee0-11e9-a8a6-1e68d864ef1a/3e74d3fd9db4c9dd921ae05c2502fb984d0cde1b36e581b13f79c639da4518a1 "; public const string Ecs = @" 9:perf_event:/ecs/haissam-ecs-classic/5a0d5ceddf6c44c1928d367a815d890f/38fac3e99302b3622be089dd41e7ccf38aff368a86cc339972075136ee2710ce 8:memory:/ecs/haissam-ecs-classic/5a0d5ceddf6c44c1928d367a815d890f/38fac3e99302b3622be089dd41e7ccf38aff368a86cc339972075136ee2710ce 7:hugetlb:/ecs/haissam-ecs-classic/5a0d5ceddf6c44c1928d367a815d890f/38fac3e99302b3622be089dd41e7ccf38aff368a86cc339972075136ee2710ce 6:freezer:/ecs/haissam-ecs-classic/5a0d5ceddf6c44c1928d367a815d890f/38fac3e99302b3622be089dd41e7ccf38aff368a86cc339972075136ee2710ce 5:devices:/ecs/haissam-ecs-classic/5a0d5ceddf6c44c1928d367a815d890f/38fac3e99302b3622be089dd41e7ccf38aff368a86cc339972075136ee2710ce 4:cpuset:/ecs/haissam-ecs-classic/5a0d5ceddf6c44c1928d367a815d890f/38fac3e99302b3622be089dd41e7ccf38aff368a86cc339972075136ee2710ce 3:cpuacct:/ecs/haissam-ecs-classic/5a0d5ceddf6c44c1928d367a815d890f/38fac3e99302b3622be089dd41e7ccf38aff368a86cc339972075136ee2710ce 2:cpu:/ecs/haissam-ecs-classic/5a0d5ceddf6c44c1928d367a815d890f/38fac3e99302b3622be089dd41e7ccf38aff368a86cc339972075136ee2710ce 1:blkio:/ecs/haissam-ecs-classic/5a0d5ceddf6c44c1928d367a815d890f/38fac3e99302b3622be089dd41e7ccf38aff368a86cc339972075136ee2710ce "; public const string Fargate1Dot3 = @" 11:hugetlb:/ecs/55091c13-b8cf-4801-b527-f4601742204d/432624d2150b349fe35ba397284dea788c2bf66b885d14dfc1569b01890ca7da 10:pids:/ecs/55091c13-b8cf-4801-b527-f4601742204d/432624d2150b349fe35ba397284dea788c2bf66b885d14dfc1569b01890ca7da 9:cpuset:/ecs/55091c13-b8cf-4801-b527-f4601742204d/432624d2150b349fe35ba397284dea788c2bf66b885d14dfc1569b01890ca7da 8:net_cls,net_prio:/ecs/55091c13-b8cf-4801-b527-f4601742204d/432624d2150b349fe35ba397284dea788c2bf66b885d14dfc1569b01890ca7da 7:cpu,cpuacct:/ecs/55091c13-b8cf-4801-b527-f4601742204d/432624d2150b349fe35ba397284dea788c2bf66b885d14dfc1569b01890ca7da 6:perf_event:/ecs/55091c13-b8cf-4801-b527-f4601742204d/432624d2150b349fe35ba397284dea788c2bf66b885d14dfc1569b01890ca7da 5:freezer:/ecs/55091c13-b8cf-4801-b527-f4601742204d/432624d2150b349fe35ba397284dea788c2bf66b885d14dfc1569b01890ca7da 4:devices:/ecs/55091c13-b8cf-4801-b527-f4601742204d/432624d2150b349fe35ba397284dea788c2bf66b885d14dfc1569b01890ca7da 3:blkio:/ecs/55091c13-b8cf-4801-b527-f4601742204d/432624d2150b349fe35ba397284dea788c2bf66b885d14dfc1569b01890ca7da 2:memory:/ecs/55091c13-b8cf-4801-b527-f4601742204d/432624d2150b349fe35ba397284dea788c2bf66b885d14dfc1569b01890ca7da 1:name=systemd:/ecs/55091c13-b8cf-4801-b527-f4601742204d/432624d2150b349fe35ba397284dea788c2bf66b885d14dfc1569b01890ca7da "; public const string Fargate1Dot4 = @" 11:hugetlb:/ecs/34dc0b5e626f2c5c4c5170e34b10e765-1234567890 10:pids:/ecs/34dc0b5e626f2c5c4c5170e34b10e765-1234567890 9:cpuset:/ecs/34dc0b5e626f2c5c4c5170e34b10e765-1234567890 8:net_cls,net_prio:/ecs/34dc0b5e626f2c5c4c5170e34b10e765-1234567890 7:cpu,cpuacct:/ecs/34dc0b5e626f2c5c4c5170e34b10e765-1234567890 6:perf_event:/ecs/34dc0b5e626f2c5c4c5170e34b10e765-1234567890 5:freezer:/ecs/34dc0b5e626f2c5c4c5170e34b10e765-1234567890 4:devices:/ecs/34dc0b5e626f2c5c4c5170e34b10e765-1234567890 3:blkio:/ecs/34dc0b5e626f2c5c4c5170e34b10e765-1234567890 2:memory:/ecs/34dc0b5e626f2c5c4c5170e34b10e765-1234567890 1:name=systemd:/ecs/34dc0b5e626f2c5c4c5170e34b10e765-1234567890 "; public static IEnumerable<object[]> GetCgroupFiles() { yield return new object[] { Docker, "3726184226f5d3147c25fdeab5b60097e378e8a720503a5e19ecfdf29f869860" }; yield return new object[] { Kubernetes, "3e74d3fd9db4c9dd921ae05c2502fb984d0cde1b36e581b13f79c639da4518a1" }; yield return new object[] { Ecs, "38fac3e99302b3622be089dd41e7ccf38aff368a86cc339972075136ee2710ce" }; yield return new object[] { Fargate1Dot3, "432624d2150b349fe35ba397284dea788c2bf66b885d14dfc1569b01890ca7da" }; yield return new object[] { Fargate1Dot4, "34dc0b5e626f2c5c4c5170e34b10e765-1234567890" }; } /// <summary> /// Splits multi-line string into individual strings, one string per line. /// </summary> /// <param name="contents">The multi-line string.</param> /// <returns>An enumerable that returns each line from <paramref name="contents"/> when iterated.</returns> public static IEnumerable<string> SplitLines(string contents) { if (contents == null) { yield break; } using (var reader = new StringReader(contents)) { while (true) { string line = reader.ReadLine(); if (line == null) { yield break; } yield return line; } } } [Theory] [MemberData(nameof(GetCgroupFiles))] public void Parse_ContainerId_From_Cgroup_File(string file, string expected) { // arrange var lines = SplitLines(file); // act string actual = ContainerMetadata.ParseCgroupLines(lines); // assert Assert.Equal(expected, actual); } } }
61.847328
144
0.822266
[ "Apache-2.0" ]
backjo/dd-trace-dotnet
test/Datadog.Trace.Tests/PlatformHelpers/ContainerMetadataTests.cs
8,102
C#
using System; using System.Collections.Generic; using System.Text; using System.ComponentModel.Design; using GuruComponents.Netrix.WebEditing.Elements; using System.ComponentModel; using System.Collections; using System.Reflection; using GuruComponents.Netrix.Events; using System.Web.UI.Design; namespace GuruComponents.Netrix.Designer { /// <summary> /// Default designer support class. /// </summary> /// <remarks> /// Primarily, this class supports the elements infrastructur behavior. User can replace this class /// by adding the <see cref="DesignerAttribute"/> to element derived from <see cref="Element"/> as well other inheritable classes, /// which derive from <see cref="Element"/>. /// <seealso cref="IElement"/> /// <seealso cref="Element"/> /// </remarks> public class ElementDesigner : ComponentDesigner { IElement component; /// <summary> /// The element which is currently assigned to this designer. /// </summary> public IElement Element { get { return component; } set { component = value; } } /// <summary> /// Just override to avoid null ref exception in case of UI calls (like PropertyGrid). /// </summary> [Obsolete()] public override void OnSetComponentDefaults() { // just override to avoid null ref exception in case of UI calls (like PropertyGrid) } /// <summary> /// Called by internal designer host to initialize the designer. /// </summary> /// <exception cref="ArgumentOutOfRangeException">Thrown if the default event attribute is being used, but the exposed event did not exists.</exception> /// <param name="component"></param> public override void Initialize(System.ComponentModel.IComponent component) { this.component = (IElement)component; object[] attr = this.component.GetType().GetCustomAttributes(typeof(DefaultEventAttribute), true); if (attr != null && attr.Length >= 1) { DefaultEventAttribute dea = (DefaultEventAttribute)attr[0]; EventInfo ei = this.component.GetType().GetEvent(dea.Name); if (ei != null) { ei.AddEventHandler(component, new GuruComponents.Netrix.Events.DocumentEventHandler(component_Action)); } else { throw new ArgumentOutOfRangeException("The default event defined by the element's class does not exist in that element. Event: " + dea.Name); } } //this.component.DblClick -= new GuruComponents.Netrix.Events.DocumentEventHandler(component_DblClick); //this.component.DblClick += new GuruComponents.Netrix.Events.DocumentEventHandler(component_DblClick); } void component_Action(object sender, GuruComponents.Netrix.Events.DocumentEventArgs e) { DoDefaultAction(); } /// <summary> /// The default action for the component. /// </summary> /// <remarks> /// The default event on an element causes this method to be called. Override this method to change the default /// behavior. In an application which behaves like Visual Studio a double click might open the code editor /// and add a event handler for the default event of the element. /// <para> /// The abstract base class, <see cref="GuruComponents.Netrix.WebEditing.Elements.Element">Element</see> defines the /// attribute <see cref="DefaultEventAttribute"/> with the value "Click". This makes the click event the default /// event for any element. If one writes a new element class, which derives from <see cref="GuruComponents.Netrix.WebEditing.Elements.Element">Element</see> /// or which implements <see cref="GuruComponents.Netrix.WebEditing.Elements.IElement">IElement</see>, the attribute could /// be overwritten with each other handler name. /// </para> /// <para> /// To fully implement this behavior one must: /// <list type="bullet"> /// <item>1. Add the DefaultEventAttribute to the component's class.</item> /// <item>2. Override the DoDefaultAction method to receive the event at design time.</item> /// </list> /// At design time, the user may issue the event by some action. Then the event manager receives the event and calles /// the attached handler, which in turn calles DoDefaultAction. /// </para> /// <para> /// <b>Important Note to implementors:</b> Some events, like MouseMove, PropertyChange, or Resize are called very /// frequently and using these event in the scenario described above could slow the performance drastically. It's strongly /// recommended to use only events which have slow performance impact (so called single event actions). This is the case /// for events like Click, ResizeStart, ResizeEnd, MoveStart, MoveEnd, DblClick, MouseUp, MouseDown. It could be critical /// for key events and several mixed events, like those for drag 'n drop, for editing (cut/copy/paste) and selection. /// </para> /// </remarks> public override void DoDefaultAction() { base.DoDefaultAction(); } /// <summary> /// Allows adding properties to the properties which show up in the PropertyGrid. /// </summary> /// <remarks> /// Allows a designer to add to the set of properties that it exposes through /// a <see cref="System.ComponentModel.TypeDescriptor"/>. /// </remarks> /// <param name="properties">List of properties defined by the component.</param> protected override void PreFilterProperties(System.Collections.IDictionary properties) { Hashtable ht = new Hashtable(properties); foreach (DictionaryEntry de in properties) { PropertyDescriptor pd = (PropertyDescriptor)de.Value; if (pd.Name == "EnableViewState") { ht.Remove(pd); } } base.PreFilterProperties(properties); } /// <summary> /// Allows change or modify properties to the properties which show up in the PropertyGrid. /// </summary> /// <remarks> /// Allows a designer to change or modify to the set of properties that it exposes through /// a <see cref="System.ComponentModel.TypeDescriptor"/>. /// </remarks> /// <param name="properties">List of properties defined by the component.</param> protected override void PostFilterProperties(IDictionary properties) { Hashtable ht = new Hashtable(properties); foreach (DictionaryEntry de in properties) { PropertyDescriptor pd = (PropertyDescriptor)de.Value; if (pd.Name == "Expression" || pd.Name == "EnableViewState" || pd.Name == "ID") { ht.Remove(pd); } } base.PostFilterProperties(ht); } /// <summary> /// Gets the parent element in the element's hierarchy. /// </summary> protected override IComponent ParentComponent { get { return component.GetParent() as IComponent; } } /// <summary> /// Gets the children of the element in the element's hierarchy. /// </summary> public override ICollection AssociatedComponents { get { return component.ElementDom.GetChildNodes(); } } /// <summary> /// This property provides commands. /// </summary> /// <remarks> /// Command apperar in PropertyGrid's command area or a IMenuCommandService driven context menu, if the /// host makes use of the designer host. Inheritors should override this property and either add commands /// or replace the existing command. /// </remarks> /// <example> /// The following example shows how to create new commands: /// <code> /// <![CDATA[ /// DesignerVerbCollection verbs = new DesignerVerbCollection(); /// verbs.Add(new DesignerVerb("This Name appears in the menu", OnAction)); /// ]]> /// </code> /// <c>OnAction</c> is a default event handler (<see cref="System.EventHandler"/>). To access the component which /// later issues the command one can get the <see cref="Element"/>. /// </example> public override DesignerVerbCollection Verbs { get { DesignerVerbCollection verbs = new DesignerVerbCollection(); return verbs; } } /// <summary> /// Called from event chain before any internal processing. /// </summary> /// <remarks> /// Inheritors may implement here private behavior to change the default event handling. /// Returning <c>True</c> will cause the internal chain to stop event processing. /// </remarks> /// <param name="sender">The EditHost which received and re-fired the event.</param> /// <param name="e">Information about the event.</param> /// <returns>Return <c>true</c> to inform the caller that any default handling has to be suppressed. Default is <c>false</c>.</returns> public virtual bool OnPreHandleEvent(object sender, DocumentEventArgs e) { return false; } /// <summary> /// Called from event chain after default internal processing. /// </summary> /// <remarks> /// Inheritors may implement here private behavior to change the default event handling. /// Returning <c>True</c> will cause the internal chain to stop event processing. /// </remarks> /// <param name="sender">The EditHost which received and re-fired the event.</param> /// <param name="e">Information about the event.</param> /// <returns>Return <c>true</c> to inform the caller that any default handling has to be suppressed. Default is <c>false</c>.</returns> public virtual bool OnPostHandleEvent(object sender, DocumentEventArgs e) { return false; } /// <summary> /// Called from event chain before any internal and external processing. /// </summary> /// <remarks> /// This is to inform the designer that any internal processing is done. The purpose is to check the results of any /// previous action or refresh the state of an object after finishing the event chain. /// </remarks> /// <param name="sender">The EditHost which received and re-fired the event.</param> /// <param name="e">Information about the event.</param> public virtual void OnPostEditorNotify(object sender, DocumentEventArgs e) { } } }
44.166023
164
0.603287
[ "MIT" ]
andydunkel/netrix
Netrix2.0/NetRixMain/NetRix/Designer/Elements/ElementDesigner.cs
11,439
C#
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData // package to your project. ////#define Handle_PageResultOfT using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net.Http.Headers; using System.Reflection; using System.Web; using System.Web.Http; #if Handle_PageResultOfT using System.Web.Http.OData; #endif namespace WebApiReferenceImpl.Areas.HelpPage { /// <summary> /// Use this class to customize the Help Page. /// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation /// or you can provide the samples for the requests/responses. /// </summary> public static class HelpPageConfig { [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "WebApiReferenceImpl.Areas.HelpPage.TextSample.#ctor(System.String)", Justification = "End users may choose to merge this string with existing localized resources.")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "bsonspec", Justification = "Part of a URI.")] public static void Register(HttpConfiguration config) { //// Uncomment the following to use the documentation from XML documentation file. //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml"))); //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type. //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type //// formats by the available formatters. //config.SetSampleObjects(new Dictionary<Type, object> //{ // {typeof(string), "sample string"}, // {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}} //}); // Extend the following to provide factories for types not handled automatically (those lacking parameterless // constructors) or for which you prefer to use non-default property values. Line below provides a fallback // since automatic handling will fail and GeneratePageResult handles only a single type. #if Handle_PageResultOfT config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult); #endif // Extend the following to use a preset object directly as the sample for all actions that support a media // type, regardless of the body parameter or return type. The lines below avoid display of binary content. // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object. config.SetSampleForMediaType( new TextSample("Binary JSON content. See http://bsonspec.org for details."), new MediaTypeHeaderValue("application/bson")); //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format //// and have IEnumerable<string> as the body parameter or return type. //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>)); //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values" //// and action named "Put". //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put"); //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png" //// on the controller named "Values" and action named "Get" with parameter "id". //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id"); //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>. //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter. //config.SetActualRequestType(typeof(string), "Values", "Get"); //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>. //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string. //config.SetActualResponseType(typeof(string), "Values", "Post"); } #if Handle_PageResultOfT private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type) { if (type.IsGenericType) { Type openGenericType = type.GetGenericTypeDefinition(); if (openGenericType == typeof(PageResult<>)) { // Get the T in PageResult<T> Type[] typeParameters = type.GetGenericArguments(); Debug.Assert(typeParameters.Length == 1); // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor Type itemsType = typeof(List<>).MakeGenericType(typeParameters); object items = sampleGenerator.GetSampleObject(itemsType); // Fill in the other information needed to invoke the PageResult<T> constuctor Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), }; object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, }; // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor ConstructorInfo constructor = type.GetConstructor(parameterTypes); return constructor.Invoke(parameters); } } return null; } #endif } }
57.60177
149
0.666769
[ "MIT" ]
cosoria/WebApiReferenceImpl
src/Api/Areas/HelpPage/App_Start/HelpPageConfig.cs
6,509
C#
namespace Application.Dto { public class AuthorMergeDto { public AuthorDto Author { get; set; } public int[] Authors { get; set; } } }
18.222222
45
0.591463
[ "MIT" ]
ita-social-projects/Bookcrossing-Back-End
src/Application/Dto/AuthorMergeDto.cs
166
C#
using System; using System.Collections.Generic; using Substrate.Nbt; namespace NBTModel.Interop { public static class FormRegistry { public delegate bool EditStringAction (StringFormData data); public delegate bool EditRestrictedStringAction (RestrictedStringFormData data); public delegate bool EditTagScalarAction (TagScalarFormData data); public delegate bool EditByteArrayAction (ByteArrayFormData data); public delegate bool CreateNodeAction (CreateTagFormData data); public static EditStringAction EditString { get; set; } public static EditRestrictedStringAction RenameTag { get; set; } public static EditTagScalarAction EditTagScalar { get; set; } public static EditByteArrayAction EditByteArray { get; set; } public static CreateNodeAction CreateNode { get; set; } public static Action<string> MessageBox { get; set; } } public class TagScalarFormData { public TagScalarFormData (TagNode tag) { Tag = tag; } public TagNode Tag { get; private set; } } public class StringFormData { public StringFormData (String value) { Value = value; } public String Value { get; set; } public bool AllowEmpty { get; set; } } public class RestrictedStringFormData : StringFormData { private List<String> _restricted = new List<string>(); public RestrictedStringFormData (String value) : base(value) { } public List<String> RestrictedValues { get { return _restricted; } } } public class CreateTagFormData { public CreateTagFormData () { RestrictedNames = new List<string>(); } public TagType TagType { get; set; } public bool HasName { get; set; } public List<String> RestrictedNames { get; private set; } public TagNode TagNode { get; set; } public string TagName { get; set; } } public class ByteArrayFormData { public string NodeName { get; set; } public int BytesPerElement { get; set; } public byte[] Data { get; set; } } }
28.148148
88
0.621053
[ "MIT" ]
3prm3/NBTExplorer-Reloaded
NBTModel/Interop/FormRegistry.cs
2,282
C#
using System.Collections.Generic; namespace AGS.API { /// <summary> /// How did the list change? /// </summary> public enum ListChangeType { /// <summary> /// An item was added to the list. /// </summary> Add, /// <summary> /// An item was removed from the list. /// </summary> Remove, } /// <summary> /// Event arguments for a list change. /// </summary> public class AGSListChangedEventArgs<TItem> { private IEnumerable<AGSListItem<TItem>> _items; private AGSListItem<TItem> _singleItem; /// <summary> /// Initializes a new instance of the <see cref="T:AGS.API.AGSListChangedEventArgs`1"/> class. /// </summary> /// <param name="changeType">Change type.</param> /// <param name="item">Item.</param> public AGSListChangedEventArgs(ListChangeType changeType, AGSListItem<TItem> item) { ChangeType = changeType; _singleItem = item; } /// <summary> /// Initializes a new instance of the <see cref="T:AGS.API.AGSListChangedEventArgs`1"/> class. /// </summary> /// <param name="changeType">Change type.</param> /// <param name="items">Items.</param> public AGSListChangedEventArgs(ListChangeType changeType, IEnumerable<AGSListItem<TItem>> items) { ChangeType = changeType; _items = items; } /// <summary> /// How was the list changed? /// </summary> /// <value>The type of the change.</value> public ListChangeType ChangeType { get; private set; } /// <summary> /// Gets the items which were involved in the change (either added or removed depending on <see cref="ChangeType"/>). /// </summary> /// <value>The item.</value> public IEnumerable<AGSListItem<TItem>> Items { get { if (_items != null) return _items; return getSingleItem(); } } private IEnumerable<AGSListItem<TItem>> getSingleItem() { yield return _singleItem; } } }
29.520548
125
0.569838
[ "Artistic-2.0" ]
OwenMcDonnell/MonoAGS
Source/AGS.API/Misc/Collections/BindingList/AGSListChangedEventArgs.cs
2,157
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. #nullable disable #pragma warning disable 436 // SuppressUnmanagedCodeSecurityAttribute defined in source and mscorlib using System; using System.Runtime.InteropServices; using System.Security; namespace Microsoft.DiaSymReader { [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("B01FAFEB-C450-3A4D-BEEC-B4CEEC01E006"), SuppressUnmanagedCodeSecurity] internal unsafe interface ISymUnmanagedDocumentWriter { void SetSource(uint sourceSize, byte* source); void SetCheckSum(Guid algorithmId, uint checkSumSize, byte* checkSum); } }
35.909091
145
0.782278
[ "MIT" ]
333fred/roslyn
src/Compilers/Core/Portable/DiaSymReader/Writer/ISymUnmanagedDocumentWriter.cs
792
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by \generate-code.bat. // // Changes to this file will be lost when the code is regenerated. // The build server regenerates the code before each build and a pre-build // step will regenerate the code on each local build. // // See https://github.com/angularsen/UnitsNet/wiki/Adding-a-New-Unit for how to add or edit units. // // Add CustomCode\Quantities\MyQuantity.extra.cs files to add code to generated quantities. // Add UnitDefinitions\MyQuantity.json and run generate-code.bat to generate new units or quantities. // // </auto-generated> //------------------------------------------------------------------------------ // Licensed under MIT No Attribution, see LICENSE file at the root. // Copyright 2013 Andreas Gullberg Larsen (andreas.larsen84@gmail.com). Maintained at https://github.com/angularsen/UnitsNet. using System; using System.Globalization; using System.Linq; using JetBrains.Annotations; using UnitsNet.InternalHelpers; using UnitsNet.Units; #nullable enable // ReSharper disable once CheckNamespace namespace UnitsNet { /// <inheritdoc /> /// <summary> /// A way of representing a number of items. /// </summary> public partial struct Scalar : IQuantity<ScalarUnit>, IEquatable<Scalar>, IComparable, IComparable<Scalar>, IConvertible, IFormattable { /// <summary> /// The numeric value this quantity was constructed with. /// </summary> private readonly double _value; /// <summary> /// The unit this quantity was constructed with. /// </summary> private readonly ScalarUnit? _unit; static Scalar() { BaseDimensions = BaseDimensions.Dimensionless; Info = new QuantityInfo<ScalarUnit>("Scalar", new UnitInfo<ScalarUnit>[] { new UnitInfo<ScalarUnit>(ScalarUnit.Amount, BaseUnits.Undefined), }, BaseUnit, Zero, BaseDimensions, QuantityType.Scalar); } /// <summary> /// Creates the quantity with the given numeric value and unit. /// </summary> /// <param name="value">The numeric value to construct this quantity with.</param> /// <param name="unit">The unit representation to construct this quantity with.</param> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public Scalar(double value, ScalarUnit unit) { if(unit == ScalarUnit.Undefined) throw new ArgumentException("The quantity can not be created with an undefined unit.", nameof(unit)); _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = unit; } /// <summary> /// Creates an instance of the quantity with the given numeric value in units compatible with the given <see cref="UnitSystem"/>. /// If multiple compatible units were found, the first match is used. /// </summary> /// <param name="value">The numeric value to construct this quantity with.</param> /// <param name="unitSystem">The unit system to create the quantity with.</param> /// <exception cref="ArgumentNullException">The given <see cref="UnitSystem"/> is null.</exception> /// <exception cref="ArgumentException">No unit was found for the given <see cref="UnitSystem"/>.</exception> public Scalar(double value, UnitSystem unitSystem) { if(unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); _value = Guard.EnsureValidNumber(value, nameof(value)); _unit = firstUnitInfo?.Value ?? throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); } #region Static Properties /// <inheritdoc cref="IQuantity.QuantityInfo"/> public static QuantityInfo<ScalarUnit> Info { get; } /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> public static BaseDimensions BaseDimensions { get; } /// <summary> /// The base unit of Scalar, which is Amount. All conversions go via this value. /// </summary> public static ScalarUnit BaseUnit { get; } = ScalarUnit.Amount; /// <summary> /// Represents the largest possible value of Scalar /// </summary> public static Scalar MaxValue { get; } = new Scalar(double.MaxValue, BaseUnit); /// <summary> /// Represents the smallest possible value of Scalar /// </summary> public static Scalar MinValue { get; } = new Scalar(double.MinValue, BaseUnit); /// <summary> /// The <see cref="QuantityType" /> of this quantity. /// </summary> [Obsolete("QuantityType will be removed in the future. Use Info property instead.")] public static QuantityType QuantityType { get; } = QuantityType.Scalar; /// <summary> /// All units of measurement for the Scalar quantity. /// </summary> public static ScalarUnit[] Units { get; } = Enum.GetValues(typeof(ScalarUnit)).Cast<ScalarUnit>().Except(new ScalarUnit[]{ ScalarUnit.Undefined }).ToArray(); /// <summary> /// Gets an instance of this quantity with a value of 0 in the base unit Amount. /// </summary> public static Scalar Zero { get; } = new Scalar(0, BaseUnit); #endregion #region Properties /// <summary> /// The numeric value this quantity was constructed with. /// </summary> public double Value => _value; Enum IQuantity.Unit => Unit; /// <inheritdoc /> public ScalarUnit Unit => _unit.GetValueOrDefault(BaseUnit); /// <inheritdoc /> public QuantityInfo<ScalarUnit> QuantityInfo => Info; /// <inheritdoc cref="IQuantity.QuantityInfo"/> QuantityInfo IQuantity.QuantityInfo => Info; /// <summary> /// The <see cref="QuantityType" /> of this quantity. /// </summary> public QuantityType Type => Scalar.QuantityType; /// <summary> /// The <see cref="BaseDimensions" /> of this quantity. /// </summary> public BaseDimensions Dimensions => Scalar.BaseDimensions; #endregion #region Conversion Properties /// <summary> /// Get Scalar in Amount. /// </summary> public double Amount => As(ScalarUnit.Amount); #endregion #region Static Methods /// <summary> /// Get unit abbreviation string. /// </summary> /// <param name="unit">Unit to get abbreviation for.</param> /// <returns>Unit abbreviation string.</returns> public static string GetAbbreviation(ScalarUnit unit) { return GetAbbreviation(unit, null); } /// <summary> /// Get unit abbreviation string. /// </summary> /// <param name="unit">Unit to get abbreviation for.</param> /// <returns>Unit abbreviation string.</returns> /// <param name="provider">Format to use for localization. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> public static string GetAbbreviation(ScalarUnit unit, IFormatProvider? provider) { return UnitAbbreviationsCache.Default.GetDefaultAbbreviation(unit, provider); } #endregion #region Static Factory Methods /// <summary> /// Get Scalar from Amount. /// </summary> /// <exception cref="ArgumentException">If value is NaN or Infinity.</exception> public static Scalar FromAmount(QuantityValue amount) { double value = (double) amount; return new Scalar(value, ScalarUnit.Amount); } /// <summary> /// Dynamically convert from value and unit enum <see cref="ScalarUnit" /> to <see cref="Scalar" />. /// </summary> /// <param name="value">Value to convert from.</param> /// <param name="fromUnit">Unit to convert from.</param> /// <returns>Scalar unit value.</returns> public static Scalar From(QuantityValue value, ScalarUnit fromUnit) { return new Scalar((double)value, fromUnit); } #endregion #region Static Parse Methods /// <summary> /// Parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="ArgumentException"> /// Expected string to have one or two pairs of quantity and unit in the format /// "&lt;quantity&gt; &lt;unit&gt;". Eg. "5.5 m" or "1ft 2in" /// </exception> /// <exception cref="AmbiguousUnitParseException"> /// More than one unit is represented by the specified unit abbreviation. /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. /// </exception> /// <exception cref="UnitsNetException"> /// If anything else goes wrong, typically due to a bug or unhandled case. /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish /// Units.NET exceptions from other exceptions. /// </exception> public static Scalar Parse(string str) { return Parse(str, null); } /// <summary> /// Parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="ArgumentException"> /// Expected string to have one or two pairs of quantity and unit in the format /// "&lt;quantity&gt; &lt;unit&gt;". Eg. "5.5 m" or "1ft 2in" /// </exception> /// <exception cref="AmbiguousUnitParseException"> /// More than one unit is represented by the specified unit abbreviation. /// Example: Volume.Parse("1 cup") will throw, because it can refer to any of /// <see cref="VolumeUnit.MetricCup" />, <see cref="VolumeUnit.UsLegalCup" /> and <see cref="VolumeUnit.UsCustomaryCup" />. /// </exception> /// <exception cref="UnitsNetException"> /// If anything else goes wrong, typically due to a bug or unhandled case. /// We wrap exceptions in <see cref="UnitsNetException" /> to allow you to distinguish /// Units.NET exceptions from other exceptions. /// </exception> /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> public static Scalar Parse(string str, IFormatProvider? provider) { return QuantityParser.Default.Parse<Scalar, ScalarUnit>( str, provider, From); } /// <summary> /// Try to parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="result">Resulting unit quantity if successful.</param> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> public static bool TryParse(string? str, out Scalar result) { return TryParse(str, null, out result); } /// <summary> /// Try to parse a string with one or two quantities of the format "&lt;quantity&gt; &lt;unit&gt;". /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="result">Resulting unit quantity if successful.</param> /// <returns>True if successful, otherwise false.</returns> /// <example> /// Length.Parse("5.5 m", new CultureInfo("en-US")); /// </example> /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> public static bool TryParse(string? str, IFormatProvider? provider, out Scalar result) { return QuantityParser.Default.TryParse<Scalar, ScalarUnit>( str, provider, From, out result); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <example> /// Length.ParseUnit("m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="UnitsNetException">Error parsing string.</exception> public static ScalarUnit ParseUnit(string str) { return ParseUnit(str, null); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> /// <example> /// Length.ParseUnit("m", new CultureInfo("en-US")); /// </example> /// <exception cref="ArgumentNullException">The value of 'str' cannot be null. </exception> /// <exception cref="UnitsNetException">Error parsing string.</exception> public static ScalarUnit ParseUnit(string str, IFormatProvider? provider) { return UnitParser.Default.Parse<ScalarUnit>(str, provider); } /// <inheritdoc cref="TryParseUnit(string,IFormatProvider,out UnitsNet.Units.ScalarUnit)"/> public static bool TryParseUnit(string str, out ScalarUnit unit) { return TryParseUnit(str, null, out unit); } /// <summary> /// Parse a unit string. /// </summary> /// <param name="str">String to parse. Typically in the form: {number} {unit}</param> /// <param name="unit">The parsed unit if successful.</param> /// <returns>True if successful, otherwise false.</returns> /// <example> /// Length.TryParseUnit("m", new CultureInfo("en-US")); /// </example> /// <param name="provider">Format to use when parsing number and unit. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> public static bool TryParseUnit(string str, IFormatProvider? provider, out ScalarUnit unit) { return UnitParser.Default.TryParse<ScalarUnit>(str, provider, out unit); } #endregion #region Arithmetic Operators /// <summary>Negate the value.</summary> public static Scalar operator -(Scalar right) { return new Scalar(-right.Value, right.Unit); } /// <summary>Get <see cref="Scalar"/> from adding two <see cref="Scalar"/>.</summary> public static Scalar operator +(Scalar left, Scalar right) { return new Scalar(left.Value + right.GetValueAs(left.Unit), left.Unit); } /// <summary>Get <see cref="Scalar"/> from subtracting two <see cref="Scalar"/>.</summary> public static Scalar operator -(Scalar left, Scalar right) { return new Scalar(left.Value - right.GetValueAs(left.Unit), left.Unit); } /// <summary>Get <see cref="Scalar"/> from multiplying value and <see cref="Scalar"/>.</summary> public static Scalar operator *(double left, Scalar right) { return new Scalar(left * right.Value, right.Unit); } /// <summary>Get <see cref="Scalar"/> from multiplying value and <see cref="Scalar"/>.</summary> public static Scalar operator *(Scalar left, double right) { return new Scalar(left.Value * right, left.Unit); } /// <summary>Get <see cref="Scalar"/> from dividing <see cref="Scalar"/> by value.</summary> public static Scalar operator /(Scalar left, double right) { return new Scalar(left.Value / right, left.Unit); } /// <summary>Get ratio value from dividing <see cref="Scalar"/> by <see cref="Scalar"/>.</summary> public static double operator /(Scalar left, Scalar right) { return left.Amount / right.Amount; } #endregion #region Equality / IComparable /// <summary>Returns true if less or equal to.</summary> public static bool operator <=(Scalar left, Scalar right) { return left.Value <= right.GetValueAs(left.Unit); } /// <summary>Returns true if greater than or equal to.</summary> public static bool operator >=(Scalar left, Scalar right) { return left.Value >= right.GetValueAs(left.Unit); } /// <summary>Returns true if less than.</summary> public static bool operator <(Scalar left, Scalar right) { return left.Value < right.GetValueAs(left.Unit); } /// <summary>Returns true if greater than.</summary> public static bool operator >(Scalar left, Scalar right) { return left.Value > right.GetValueAs(left.Unit); } /// <summary>Returns true if exactly equal.</summary> /// <remarks>Consider using <see cref="Equals(Scalar, double, ComparisonType)"/> for safely comparing floating point values.</remarks> public static bool operator ==(Scalar left, Scalar right) { return left.Equals(right); } /// <summary>Returns true if not exactly equal.</summary> /// <remarks>Consider using <see cref="Equals(Scalar, double, ComparisonType)"/> for safely comparing floating point values.</remarks> public static bool operator !=(Scalar left, Scalar right) { return !(left == right); } /// <inheritdoc /> public int CompareTo(object obj) { if(obj is null) throw new ArgumentNullException(nameof(obj)); if(!(obj is Scalar objScalar)) throw new ArgumentException("Expected type Scalar.", nameof(obj)); return CompareTo(objScalar); } /// <inheritdoc /> public int CompareTo(Scalar other) { return _value.CompareTo(other.GetValueAs(this.Unit)); } /// <inheritdoc /> /// <remarks>Consider using <see cref="Equals(Scalar, double, ComparisonType)"/> for safely comparing floating point values.</remarks> public override bool Equals(object obj) { if(obj is null || !(obj is Scalar objScalar)) return false; return Equals(objScalar); } /// <inheritdoc /> /// <remarks>Consider using <see cref="Equals(Scalar, double, ComparisonType)"/> for safely comparing floating point values.</remarks> public bool Equals(Scalar other) { return _value.Equals(other.GetValueAs(this.Unit)); } /// <summary> /// <para> /// Compare equality to another Scalar within the given absolute or relative tolerance. /// </para> /// <para> /// Relative tolerance is defined as the maximum allowable absolute difference between this quantity's value and /// <paramref name="other"/> as a percentage of this quantity's value. <paramref name="other"/> will be converted into /// this quantity's unit for comparison. A relative tolerance of 0.01 means the absolute difference must be within +/- 1% of /// this quantity's value to be considered equal. /// <example> /// In this example, the two quantities will be equal if the value of b is within +/- 1% of a (0.02m or 2cm). /// <code> /// var a = Length.FromMeters(2.0); /// var b = Length.FromInches(50.0); /// a.Equals(b, 0.01, ComparisonType.Relative); /// </code> /// </example> /// </para> /// <para> /// Absolute tolerance is defined as the maximum allowable absolute difference between this quantity's value and /// <paramref name="other"/> as a fixed number in this quantity's unit. <paramref name="other"/> will be converted into /// this quantity's unit for comparison. /// <example> /// In this example, the two quantities will be equal if the value of b is within 0.01 of a (0.01m or 1cm). /// <code> /// var a = Length.FromMeters(2.0); /// var b = Length.FromInches(50.0); /// a.Equals(b, 0.01, ComparisonType.Absolute); /// </code> /// </example> /// </para> /// <para> /// Note that it is advised against specifying zero difference, due to the nature /// of floating point operations and using System.Double internally. /// </para> /// </summary> /// <param name="other">The other quantity to compare to.</param> /// <param name="tolerance">The absolute or relative tolerance value. Must be greater than or equal to 0.</param> /// <param name="comparisonType">The comparison type: either relative or absolute.</param> /// <returns>True if the absolute difference between the two values is not greater than the specified relative or absolute tolerance.</returns> public bool Equals(Scalar other, double tolerance, ComparisonType comparisonType) { if(tolerance < 0) throw new ArgumentOutOfRangeException("tolerance", "Tolerance must be greater than or equal to 0."); double thisValue = (double)this.Value; double otherValueInThisUnits = other.As(this.Unit); return UnitsNet.Comparison.Equals(thisValue, otherValueInThisUnits, tolerance, comparisonType); } /// <summary> /// Returns the hash code for this instance. /// </summary> /// <returns>A hash code for the current Scalar.</returns> public override int GetHashCode() { return new { Info.Name, Value, Unit }.GetHashCode(); } #endregion #region Conversion Methods /// <summary> /// Convert to the unit representation <paramref name="unit" />. /// </summary> /// <returns>Value converted to the specified unit.</returns> public double As(ScalarUnit unit) { if(Unit == unit) return Convert.ToDouble(Value); var converted = GetValueAs(unit); return Convert.ToDouble(converted); } /// <inheritdoc cref="IQuantity.As(UnitSystem)"/> public double As(UnitSystem unitSystem) { if(unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); if(firstUnitInfo == null) throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); return As(firstUnitInfo.Value); } /// <inheritdoc /> double IQuantity.As(Enum unit) { if(!(unit is ScalarUnit unitAsScalarUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ScalarUnit)} is supported.", nameof(unit)); return As(unitAsScalarUnit); } /// <summary> /// Converts this Scalar to another Scalar with the unit representation <paramref name="unit" />. /// </summary> /// <returns>A Scalar with the specified unit.</returns> public Scalar ToUnit(ScalarUnit unit) { var convertedValue = GetValueAs(unit); return new Scalar(convertedValue, unit); } /// <inheritdoc /> IQuantity IQuantity.ToUnit(Enum unit) { if(!(unit is ScalarUnit unitAsScalarUnit)) throw new ArgumentException($"The given unit is of type {unit.GetType()}. Only {typeof(ScalarUnit)} is supported.", nameof(unit)); return ToUnit(unitAsScalarUnit); } /// <inheritdoc cref="IQuantity.ToUnit(UnitSystem)"/> public Scalar ToUnit(UnitSystem unitSystem) { if(unitSystem is null) throw new ArgumentNullException(nameof(unitSystem)); var unitInfos = Info.GetUnitInfosFor(unitSystem.BaseUnits); var firstUnitInfo = unitInfos.FirstOrDefault(); if(firstUnitInfo == null) throw new ArgumentException("No units were found for the given UnitSystem.", nameof(unitSystem)); return ToUnit(firstUnitInfo.Value); } /// <inheritdoc /> IQuantity IQuantity.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); /// <inheritdoc /> IQuantity<ScalarUnit> IQuantity<ScalarUnit>.ToUnit(ScalarUnit unit) => ToUnit(unit); /// <inheritdoc /> IQuantity<ScalarUnit> IQuantity<ScalarUnit>.ToUnit(UnitSystem unitSystem) => ToUnit(unitSystem); /// <summary> /// Converts the current value + unit to the base unit. /// This is typically the first step in converting from one unit to another. /// </summary> /// <returns>The value in the base unit representation.</returns> private double GetValueInBaseUnit() { switch(Unit) { case ScalarUnit.Amount: return _value; default: throw new NotImplementedException($"Can not convert {Unit} to base units."); } } /// <summary> /// Converts the current value + unit to the base unit. /// This is typically the first step in converting from one unit to another. /// </summary> /// <returns>The value in the base unit representation.</returns> internal Scalar ToBaseUnit() { var baseUnitValue = GetValueInBaseUnit(); return new Scalar(baseUnitValue, BaseUnit); } private double GetValueAs(ScalarUnit unit) { if(Unit == unit) return _value; var baseUnitValue = GetValueInBaseUnit(); switch(unit) { case ScalarUnit.Amount: return baseUnitValue; default: throw new NotImplementedException($"Can not convert {Unit} to {unit}."); } } #endregion #region ToString Methods /// <summary> /// Gets the default string representation of value and unit. /// </summary> /// <returns>String representation.</returns> public override string ToString() { return ToString("g"); } /// <summary> /// Gets the default string representation of value and unit using the given format provider. /// </summary> /// <returns>String representation.</returns> /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> public string ToString(IFormatProvider? provider) { return ToString("g", provider); } /// <summary> /// Get string representation of value and unit. /// </summary> /// <param name="significantDigitsAfterRadix">The number of significant digits after the radix point.</param> /// <returns>String representation.</returns> /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> [Obsolete(@"This method is deprecated and will be removed at a future release. Please use ToString(""s2"") or ToString(""s2"", provider) where 2 is an example of the number passed to significantDigitsAfterRadix.")] public string ToString(IFormatProvider? provider, int significantDigitsAfterRadix) { var value = Convert.ToDouble(Value); var format = UnitFormatter.GetFormat(value, significantDigitsAfterRadix); return ToString(provider, format); } /// <summary> /// Get string representation of value and unit. /// </summary> /// <param name="format">String format to use. Default: "{0:0.##} {1} for value and unit abbreviation respectively."</param> /// <param name="args">Arguments for string format. Value and unit are implicitly included as arguments 0 and 1.</param> /// <returns>String representation.</returns> /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> [Obsolete("This method is deprecated and will be removed at a future release. Please use string.Format().")] public string ToString(IFormatProvider? provider, [NotNull] string format, [NotNull] params object[] args) { if (format == null) throw new ArgumentNullException(nameof(format)); if (args == null) throw new ArgumentNullException(nameof(args)); provider = provider ?? CultureInfo.CurrentUICulture; var value = Convert.ToDouble(Value); var formatArgs = UnitFormatter.GetFormatArgs(Unit, value, provider, args); return string.Format(provider, format, formatArgs); } /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> /// <summary> /// Gets the string representation of this instance in the specified format string using <see cref="CultureInfo.CurrentUICulture" />. /// </summary> /// <param name="format">The format string.</param> /// <returns>The string representation.</returns> public string ToString(string format) { return ToString(format, CultureInfo.CurrentUICulture); } /// <inheritdoc cref="QuantityFormatter.Format{TUnitType}(IQuantity{TUnitType}, string, IFormatProvider)"/> /// <summary> /// Gets the string representation of this instance in the specified format string using the specified format provider, or <see cref="CultureInfo.CurrentUICulture" /> if null. /// </summary> /// <param name="format">The format string.</param> /// <param name="provider">Format to use for localization and number formatting. Defaults to <see cref="CultureInfo.CurrentUICulture" /> if null.</param> /// <returns>The string representation.</returns> public string ToString(string format, IFormatProvider? provider) { return QuantityFormatter.Format<ScalarUnit>(this, format, provider); } #endregion #region IConvertible Methods TypeCode IConvertible.GetTypeCode() { return TypeCode.Object; } bool IConvertible.ToBoolean(IFormatProvider provider) { throw new InvalidCastException($"Converting {typeof(Scalar)} to bool is not supported."); } byte IConvertible.ToByte(IFormatProvider provider) { return Convert.ToByte(_value); } char IConvertible.ToChar(IFormatProvider provider) { throw new InvalidCastException($"Converting {typeof(Scalar)} to char is not supported."); } DateTime IConvertible.ToDateTime(IFormatProvider provider) { throw new InvalidCastException($"Converting {typeof(Scalar)} to DateTime is not supported."); } decimal IConvertible.ToDecimal(IFormatProvider provider) { return Convert.ToDecimal(_value); } double IConvertible.ToDouble(IFormatProvider provider) { return Convert.ToDouble(_value); } short IConvertible.ToInt16(IFormatProvider provider) { return Convert.ToInt16(_value); } int IConvertible.ToInt32(IFormatProvider provider) { return Convert.ToInt32(_value); } long IConvertible.ToInt64(IFormatProvider provider) { return Convert.ToInt64(_value); } sbyte IConvertible.ToSByte(IFormatProvider provider) { return Convert.ToSByte(_value); } float IConvertible.ToSingle(IFormatProvider provider) { return Convert.ToSingle(_value); } string IConvertible.ToString(IFormatProvider provider) { return ToString("g", provider); } object IConvertible.ToType(Type conversionType, IFormatProvider provider) { if(conversionType == typeof(Scalar)) return this; else if(conversionType == typeof(ScalarUnit)) return Unit; else if(conversionType == typeof(QuantityType)) return Scalar.QuantityType; else if(conversionType == typeof(QuantityInfo)) return Scalar.Info; else if(conversionType == typeof(BaseDimensions)) return Scalar.BaseDimensions; else throw new InvalidCastException($"Converting {typeof(Scalar)} to {conversionType} is not supported."); } ushort IConvertible.ToUInt16(IFormatProvider provider) { return Convert.ToUInt16(_value); } uint IConvertible.ToUInt32(IFormatProvider provider) { return Convert.ToUInt32(_value); } ulong IConvertible.ToUInt64(IFormatProvider provider) { return Convert.ToUInt64(_value); } #endregion } }
41.608645
222
0.595699
[ "MIT-feh" ]
generateui/UnitsNet
UnitsNet/GeneratedCode/Quantities/Scalar.g.cs
35,619
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AliCloud.Arms.Inputs { public sealed class DispatchRuleNotifyRuleGetArgs : Pulumi.ResourceArgs { [Input("notifyChannels", required: true)] private InputList<string>? _notifyChannels; /// <summary> /// The notification method. Valid values: dingTalk, sms, webhook, email, and wechat. /// </summary> public InputList<string> NotifyChannels { get => _notifyChannels ?? (_notifyChannels = new InputList<string>()); set => _notifyChannels = value; } [Input("notifyObjects", required: true)] private InputList<Inputs.DispatchRuleNotifyRuleNotifyObjectGetArgs>? _notifyObjects; /// <summary> /// Sets the notification object. See the following `Block notify_objects`. /// </summary> public InputList<Inputs.DispatchRuleNotifyRuleNotifyObjectGetArgs> NotifyObjects { get => _notifyObjects ?? (_notifyObjects = new InputList<Inputs.DispatchRuleNotifyRuleNotifyObjectGetArgs>()); set => _notifyObjects = value; } public DispatchRuleNotifyRuleGetArgs() { } } }
34.068182
122
0.661107
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-alicloud
sdk/dotnet/Arms/Inputs/DispatchRuleNotifyRuleGetArgs.cs
1,499
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AWSSDK.KinesisVideoArchivedMedia")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Kinesis Video Streams Archived Media. Announcing Amazon Kinesis Video Streams, a fully managed video ingestion and storage service. Kinesis Video Streams makes it easy to securely stream video from connected devices to AWS for machine learning, analytics, and processing. You can also stream other time-encoded data like RADAR and LIDAR signals using Kinesis Video Streams.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon Kinesis Video Streams Archived Media. Announcing Amazon Kinesis Video Streams, a fully managed video ingestion and storage service. Kinesis Video Streams makes it easy to securely stream video from connected devices to AWS for machine learning, analytics, and processing. You can also stream other time-encoded data like RADAR and LIDAR signals using Kinesis Video Streams.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - Amazon Kinesis Video Streams Archived Media. Announcing Amazon Kinesis Video Streams, a fully managed video ingestion and storage service. Kinesis Video Streams makes it easy to securely stream video from connected devices to AWS for machine learning, analytics, and processing. You can also stream other time-encoded data like RADAR and LIDAR signals using Kinesis Video Streams.")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - Amazon Kinesis Video Streams Archived Media. Announcing Amazon Kinesis Video Streams, a fully managed video ingestion and storage service. Kinesis Video Streams makes it easy to securely stream video from connected devices to AWS for machine learning, analytics, and processing. You can also stream other time-encoded data like RADAR and LIDAR signals using Kinesis Video Streams.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.7.0.108")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
67.901961
472
0.7892
[ "Apache-2.0" ]
jamieromanowski/aws-sdk-net
sdk/src/Services/KinesisVideoArchivedMedia/Properties/AssemblyInfo.cs
3,463
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shields.GraphViz.Models { public class Port { public static Port North { get { return new Port(null, CompassPoints.North); } } private readonly Id id; private readonly CompassPoints? compassPoint; public Id Id { get { return id; } } public CompassPoints? CompassPoint { get { return compassPoint; } } public Port(Id id, CompassPoints? compassPoint) { if (id == null && compassPoint == null) { throw new ArgumentException("A port must specify either an ID, a compass point, or both."); } this.id = id; this.compassPoint = compassPoint; } private static readonly IReadOnlyDictionary<CompassPoints, string> compassPointName = new Dictionary<CompassPoints, string> { { CompassPoints.North, "n" }, { CompassPoints.NorthEast, "ne" }, { CompassPoints.East, "e" }, { CompassPoints.SouthEast, "se" }, { CompassPoints.South, "s" }, { CompassPoints.SouthWest, "sw" }, { CompassPoints.West, "w" }, { CompassPoints.NorthWest, "nw" }, }; public void WriteTo(StreamWriter writer) { if (id != null) { writer.Write(':'); id.WriteTo(writer); } if (compassPoint != null) { writer.Write(':'); writer.Write(compassPointName[compassPoint.Value]); } } } }
26.485294
131
0.51749
[ "MIT" ]
kekyo/graphviz
Shields.GraphViz/Models/Port.cs
1,803
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.EntityFrameworkCore; using OdeToFood.Core; using OdeToFood.Data; namespace OdeToFood.Pages.R2 { public class DetailsModel : PageModel { private readonly OdeToFood.Data.OdeToFoodDbContext _context; public DetailsModel(OdeToFood.Data.OdeToFoodDbContext context) { _context = context; } public Restaurant Restaurant { get; set; } public async Task<IActionResult> OnGetAsync(int? id) { if (id == null) { return NotFound(); } Restaurant = await _context.Restaurants.FirstOrDefaultAsync(m => m.Id == id); if (Restaurant == null) { return NotFound(); } return Page(); } } }
23.853659
89
0.604294
[ "MIT" ]
Akchach/OdeToFood
OdeToFood/OdeToFood/Pages/R2/Details.cshtml.cs
980
C#
using Ryujinx.HLE.Utilities; using System.Runtime.InteropServices; namespace Ryujinx.HLE.HOS.Services.Friend.ServiceCreator.FriendService { [StructLayout(LayoutKind.Sequential, Pack = 0x8, Size = 0x200, CharSet = CharSet.Ansi)] struct Friend { public UInt128 UserId; public long NetworkUserId; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 0x21)] public string Nickname; public UserPresence presence; [MarshalAs(UnmanagedType.I1)] public bool IsFavourite; [MarshalAs(UnmanagedType.I1)] public bool IsNew; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x6)] char[] Unknown; [MarshalAs(UnmanagedType.I1)] public bool IsValid; } }
26.310345
91
0.668414
[ "MIT" ]
Danik2343/Ryujinx
Ryujinx.HLE/HOS/Services/Friend/ServiceCreator/FriendService/Types/Friend.cs
765
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Havit.Diagnostics.Contracts; using Havit.Web.UI; namespace Havit.Web.Bootstrap.UI.WebControls { /// <summary> /// Helper class for rendering Validator Extensions. /// </summary> internal static class ValidatorRenderExtender { /// <summary> /// Default CssClass for control with failed validation (validators sets this css class). /// </summary> internal const string DefaultControlToValidateInvalidCssClass = "validation-invalid"; /// <summary> /// Default CssClass for validation tooltip. /// </summary> internal const string DefaultControlToValidateInvalidToolTipCssClass = "validation-tooltip"; /// <summary> /// Sets up validator (used from constructor). /// Changes validator default values to: /// - Display = "None" /// </summary> internal static void Setup(System.Web.UI.WebControls.BaseValidator validator) { validator.Display = ValidatorDisplay.None; validator.SetFocusOnError = false; } /// <summary> /// Entends OnPreRender method. /// </summary> internal static void OnPreRender(IValidatorExtension validator) { System.Web.UI.WebControls.BaseValidator baseValidator = (System.Web.UI.WebControls.BaseValidator)validator; if (baseValidator.Enabled && validator.ShowToolTip && String.IsNullOrEmpty(validator.ControlToValidate) && HttpContext.Current.IsDebuggingEnabled) { throw new HttpException(String.Format("Validator '{0}' should show tooltip but ControlToValidate is not specified. Set ControlToValidate property or disable tooltip by setting ShowTooltip property to False.", baseValidator.ID)); } // ensure requirements ClientScripts.BootstrapClientScriptHelper.RegisterBootstrapClientScript(baseValidator.Page); // register Validators Extensions script ScriptManager.ScriptResourceMapping.EnsureScriptRegistration(baseValidator.Page, ClientScripts.BootstrapClientScriptHelper.WebUIValidationExtensionScriptResourceMappingName); // register hookup script - in every request (must be included also in asynchronnous requests!) ScriptManager.RegisterStartupScript(baseValidator, typeof(ValidatorRenderExtender), "StartUp", "$(function() { Havit_Validation_StartUp(); });", true); } /// <summary> /// Extends AddAttributesToRender method. /// </summary> internal static void AddAttributesToRender(IValidatorExtension validator, HtmlTextWriter writer) { // control to value invalid css class has meaning only when there is a control to validate if (!String.IsNullOrEmpty(validator.ControlToValidate)) { Control controlToValidate = ((Control)validator).NamingContainer.FindControl(validator.ControlToValidate); // no check needed - ControlToValidate already checked ValidationDisplayTargetAttribute validationDisplayTargetAttribute = controlToValidate.GetType().GetCustomAttributes(typeof(ValidationDisplayTargetAttribute), true).Cast<ValidationDisplayTargetAttribute>().FirstOrDefault(); if (validationDisplayTargetAttribute != null) { Control validationDisplayTarget = controlToValidate.FindControl(validationDisplayTargetAttribute.DisplayTargetControl); if (validationDisplayTarget == null) { throw new HttpException(String.Format("Control '{0}' defined in ValidationDisplayTargetAttribute not found in control '{1}'.", validationDisplayTargetAttribute.DisplayTargetControl, controlToValidate.ID)); } writer.AddAttribute("data-val-validationdisplaytarget", validationDisplayTarget.ClientID); } // ensure rendering control to value invalid css class if (!String.IsNullOrEmpty(validator.ControlToValidateInvalidCssClass)) { writer.AddAttribute("data-val-ctvinvalidclass", validator.ControlToValidateInvalidCssClass); // controltovalidate css class } // ensure rendering control to value invalid css class if (!String.IsNullOrEmpty(validator.ControlToValidateInvalidToolTipCssClass)) { writer.AddAttribute("data-val-ctvinvalidtooltipclass", validator.ControlToValidateInvalidToolTipCssClass); // controltovalidate css class } // ensure rendering tooltip data if (validator.ShowToolTip) { string tooltip = validator.ToolTip; if (String.IsNullOrEmpty(tooltip)) { tooltip = validator.Text; } if (String.IsNullOrEmpty(tooltip)) { tooltip = validator.ErrorMessage; } if (!String.IsNullOrEmpty(tooltip)) { writer.AddAttribute("data-val-tt-position", validator.ToolTipPosition.ToString().ToLower()); writer.AddAttribute("data-val-tt-text", tooltip); } } } } } }
39.064516
232
0.756813
[ "MIT" ]
havit/HavitFramework
Havit.Web/Bootstrap/UI/WebControls/ValidatorRenderExtender.cs
4,846
C#