content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type DeviceRequest. /// </summary> public partial class DeviceRequest : BaseRequest, IDeviceRequest { /// <summary> /// Constructs a new DeviceRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public DeviceRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified Device using POST. /// </summary> /// <param name="deviceToCreate">The Device to create.</param> /// <returns>The created Device.</returns> public System.Threading.Tasks.Task<Device> CreateAsync(Device deviceToCreate) { return this.CreateAsync(deviceToCreate, CancellationToken.None); } /// <summary> /// Creates the specified Device using POST. /// </summary> /// <param name="deviceToCreate">The Device to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Device.</returns> public async System.Threading.Tasks.Task<Device> CreateAsync(Device deviceToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<Device>(deviceToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified Device. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified Device. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<Device>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified Device. /// </summary> /// <returns>The Device.</returns> public System.Threading.Tasks.Task<Device> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified Device. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The Device.</returns> public async System.Threading.Tasks.Task<Device> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<Device>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified Device using PATCH. /// </summary> /// <param name="deviceToUpdate">The Device to update.</param> /// <returns>The updated Device.</returns> public System.Threading.Tasks.Task<Device> UpdateAsync(Device deviceToUpdate) { return this.UpdateAsync(deviceToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified Device using PATCH. /// </summary> /// <param name="deviceToUpdate">The Device to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated Device.</returns> public async System.Threading.Tasks.Task<Device> UpdateAsync(Device deviceToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<Device>(deviceToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IDeviceRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IDeviceRequest Expand(Expression<Func<Device, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IDeviceRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IDeviceRequest Select(Expression<Func<Device, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="deviceToInitialize">The <see cref="Device"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(Device deviceToInitialize) { if (deviceToInitialize != null && deviceToInitialize.AdditionalData != null) { if (deviceToInitialize.MemberOf != null && deviceToInitialize.MemberOf.CurrentPage != null) { deviceToInitialize.MemberOf.AdditionalData = deviceToInitialize.AdditionalData; object nextPageLink; deviceToInitialize.AdditionalData.TryGetValue("memberOf@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { deviceToInitialize.MemberOf.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (deviceToInitialize.RegisteredOwners != null && deviceToInitialize.RegisteredOwners.CurrentPage != null) { deviceToInitialize.RegisteredOwners.AdditionalData = deviceToInitialize.AdditionalData; object nextPageLink; deviceToInitialize.AdditionalData.TryGetValue("registeredOwners@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { deviceToInitialize.RegisteredOwners.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (deviceToInitialize.RegisteredUsers != null && deviceToInitialize.RegisteredUsers.CurrentPage != null) { deviceToInitialize.RegisteredUsers.AdditionalData = deviceToInitialize.AdditionalData; object nextPageLink; deviceToInitialize.AdditionalData.TryGetValue("registeredUsers@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { deviceToInitialize.RegisteredUsers.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (deviceToInitialize.TransitiveMemberOf != null && deviceToInitialize.TransitiveMemberOf.CurrentPage != null) { deviceToInitialize.TransitiveMemberOf.AdditionalData = deviceToInitialize.AdditionalData; object nextPageLink; deviceToInitialize.AdditionalData.TryGetValue("transitiveMemberOf@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { deviceToInitialize.TransitiveMemberOf.InitializeNextPageRequest( this.Client, nextPageLinkString); } } if (deviceToInitialize.Extensions != null && deviceToInitialize.Extensions.CurrentPage != null) { deviceToInitialize.Extensions.AdditionalData = deviceToInitialize.AdditionalData; object nextPageLink; deviceToInitialize.AdditionalData.TryGetValue("extensions@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { deviceToInitialize.Extensions.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
41.925424
153
0.576407
[ "MIT" ]
AzureMentor/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/DeviceRequest.cs
12,368
C#
using System; using Deeproxio.Asset.BLL.Contract.Services; namespace Deeproxio.Asset.BLL.Services { internal class StorageItemPathProvider : IStorageItemPathProvider { public string GeneratePath(string storePrefix) { return $"{storePrefix}:{Guid.NewGuid():N}".ToLowerInvariant(); } } }
24
74
0.681548
[ "MIT" ]
Deeproxio/dpio-file-management-api
Deeproxio.Asset.BLL/Services/StorageItemPathProvider.cs
338
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using JetBrains.Annotations; namespace Yargon.Parsing { /// <summary> /// A token. /// </summary> public interface IToken : ISymbol { /// <summary> /// Gets the location of the token in the source. /// </summary> /// <value>The token location; or <see langword="null"/> when the token is virtual.</value> [CanBeNull] SourceRange? Location { get; } /// <summary> /// Gets whether the token is virtual. /// </summary> /// <value><see langword="true"/> when the token is virtual; /// otherwise, <see langword="false"/>.</value> bool IsVirtual { get; } } }
26.4
99
0.585859
[ "Apache-2.0" ]
Virtlink/yargon-parser
src/Yargon.Parsing/IToken.cs
794
C#
using System; namespace Sharptile { [Serializable] public struct WangTile { public bool dflip; public bool hflip; public int tileid; public bool vflip; public int[] wangid; } }
15.6
28
0.581197
[ "MIT" ]
mminer/sharptile
WangTile.cs
234
C#
using System; using System.Diagnostics; using System.IO; using K4os.Compression.LZ4.Internal; using K4os.Compression.LZ4.Streams; using K4os.Hash.xxHash; namespace K4os.Compression.LZ4.Roundtrip { class Program { static void Main(string[] args) { foreach (var filename in args) foreach (var level in new[] { LZ4Level.L00_FAST, LZ4Level.L03_HC, LZ4Level.L09_HC, LZ4Level.L10_OPT, LZ4Level.L12_MAX, }) { var temp = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); Directory.CreateDirectory(temp); try { Roundtrip(temp, filename, level); } catch (Exception e) { Console.WriteLine($"{e.GetType().Name}: {e.Message}"); Console.WriteLine(e.StackTrace); } finally { Directory.Delete(temp, true); } } } private static void Roundtrip(string temp, string filename, LZ4Level level) { Console.WriteLine($"Architecture: {IntPtr.Size * 8}bit"); Console.WriteLine($"Roundtrip: {filename} @ {level}..."); Console.WriteLine($"Storage: {temp}"); var originalName = filename; var encodedName = Path.Combine(temp, "encoded.lz4"); var decodedName = Path.Combine(temp, "decoded.lz4"); using (var sourceFile = File.OpenRead(originalName)) using (var targetFile = LZ4Stream.Encode( File.Create(encodedName), level, Mem.M1)) { Console.WriteLine("Compression..."); var stopwatch = Stopwatch.StartNew(); sourceFile.CopyTo(targetFile); stopwatch.Stop(); Console.WriteLine($"Time: {stopwatch.Elapsed.TotalMilliseconds:0.00}ms"); } using (var sourceFile = LZ4Stream.Decode( File.OpenRead(encodedName), Mem.M1)) using (var targetFile = File.Create(decodedName)) { Console.WriteLine("Decompression..."); var stopwatch = Stopwatch.StartNew(); sourceFile.CopyTo(targetFile); stopwatch.Stop(); Console.WriteLine($"Time: {stopwatch.Elapsed.TotalMilliseconds:0.00}ms"); } using (var sourceFile = File.OpenRead(originalName)) using (var targetFile = File.OpenRead(decodedName)) { Console.WriteLine("Verification..."); if (sourceFile.Length != targetFile.Length) throw new InvalidDataException("Files have different length"); var sourceChecksum = Checksum(sourceFile); var targetChecksum = Checksum(targetFile); if (sourceChecksum != targetChecksum) throw new InvalidDataException("Files have different hash"); } } private static uint Checksum(Stream file) { var hash = new XXH32(); var buffer = new byte[0x10000]; while (true) { var read = file.Read(buffer, 0, buffer.Length); if (read == 0) break; hash.Update(buffer, 0, read); } return hash.Digest(); } } }
26.25
78
0.670696
[ "MIT" ]
MiloszKrajewski/K4os.Compression.LZ4
src/K4os.Compression.LZ4.Roundtrip/Program.cs
2,732
C#
using NSubstitute; using PactNet.Mocks.MockHttpService.Comparers; using PactNet.Mocks.MockHttpService.Models; using PactNet.Reporters; namespace PactNet.Tests.IntegrationTests.Specification.Models { public class ResponseTestCase : IVerifiable { private readonly IProviderServiceResponseComparer _responseComparer; private readonly IReporter _reporter; public bool Match { get; set; } public string Comment { get; set; } public ProviderServiceResponse Expected { get; set; } public ProviderServiceResponse Actual { get; set; } public ResponseTestCase() { _reporter = Substitute.For<IReporter>(); _responseComparer = new ProviderServiceResponseComparer(_reporter); } public void Verify() { _responseComparer.Compare(Expected, Actual); if (Match) { _reporter.DidNotReceive().ReportError(Arg.Any<string>(), Arg.Any<object>(), Arg.Any<object>()); } else { _reporter.Received(1).ReportError(Arg.Any<string>(), Arg.Any<object>(), Arg.Any<object>()); } } } }
32.657895
112
0.603546
[ "MIT" ]
xelibrion/pact-net
PactNet.Tests/IntegrationTests/Specification/Models/ResponseTestCase.cs
1,243
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; namespace ZubMvvmc.Core { public class ViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } }
24.210526
82
0.695652
[ "MIT" ]
ZubMadbrain/mvvm
ZubMvvmc/Core/ViewModel.cs
462
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal static class PrimaryWorkspace { private static readonly ReaderWriterLockSlim registryGate = new ReaderWriterLockSlim(LockRecursionPolicy.NoRecursion); private static Workspace primaryWorkspace; private static List<TaskCompletionSource<Workspace>> primaryWorkspaceTaskSourceList = new List<TaskCompletionSource<Workspace>>(); /// <summary> /// The primary workspace, usually set by the host environment. /// </summary> public static Workspace Workspace { get { using (registryGate.DisposableRead()) { return primaryWorkspace; } } } /// <summary> /// Register a workspace as the primary workspace. Only one workspace can be the primary. /// </summary> public static void Register(Workspace workspace) { if (workspace == null) { throw new ArgumentNullException("workspace"); } using (registryGate.DisposableWrite()) { primaryWorkspace = workspace; foreach (var taskSource in primaryWorkspaceTaskSourceList) { try { taskSource.TrySetResult(workspace); } catch { } } primaryWorkspaceTaskSourceList.Clear(); } } /// <summary> /// Get's the primary workspace asynchronously. /// </summary> public static Task<Workspace> GetWorkspaceAsync(CancellationToken cancellationToken = default(CancellationToken)) { using (registryGate.DisposableWrite()) { if (primaryWorkspace != null) { return Task<Workspace>.FromResult(primaryWorkspace); } else { var taskSource = new TaskCompletionSource<Workspace>(); if (cancellationToken.CanBeCanceled) { try { var registration = cancellationToken.Register(() => { taskSource.TrySetCanceled(); }); taskSource.Task.ContinueWith(_ => registration.Dispose(), CancellationToken.None, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } catch { } } primaryWorkspaceTaskSourceList.Add(taskSource); return taskSource.Task; } } } } }
31.836735
179
0.491346
[ "Apache-2.0" ]
pottereric/roslyn
src/Workspaces/Core/Portable/Workspace/PrimaryWorkspace.cs
3,122
C#
using System; using System.Collections.Generic; using System.Reflection; using Microsoft.VisualStudio.TestTools.UnitTesting; using RI.Framework.Collections; using RI.Framework.Composition.Model; namespace RI.Test.Framework { [Export] public abstract class TestModule { #region Instance Methods protected void Fail () { throw new TestAssertionException(); } protected void Fail (string message, params object[] args) { string finalMessage = string.Format(message, args); throw new TestAssertionException(finalMessage); } #endregion #region Virtuals public virtual List<MethodInfo> GetTestMethods () { List<MethodInfo> testMethods = new List<MethodInfo>(this.GetType().GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)); testMethods.RemoveWhere(x => { object[] attributes = x.GetCustomAttributes(typeof(TestMethodAttribute), false); return attributes.Length == 0; }); return testMethods; } public virtual void InvokeTestMethod (MethodInfo method, Action testContinuation) { method.Invoke(this, null); testContinuation?.Invoke(); } #endregion } }
19.516667
155
0.736123
[ "Apache-2.0" ]
gosystemsgmbh/RI_Framework
RI.Test.Framework.Unity/TestModule.cs
1,173
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v1/services/account_budget_service.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V1.Services { /// <summary>Holder for reflection information generated from google/ads/googleads/v1/services/account_budget_service.proto</summary> public static partial class AccountBudgetServiceReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v1/services/account_budget_service.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static AccountBudgetServiceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cj1nb29nbGUvYWRzL2dvb2dsZWFkcy92MS9zZXJ2aWNlcy9hY2NvdW50X2J1", "ZGdldF9zZXJ2aWNlLnByb3RvEiBnb29nbGUuYWRzLmdvb2dsZWFkcy52MS5z", "ZXJ2aWNlcxo2Z29vZ2xlL2Fkcy9nb29nbGVhZHMvdjEvcmVzb3VyY2VzL2Fj", "Y291bnRfYnVkZ2V0LnByb3RvGhxnb29nbGUvYXBpL2Fubm90YXRpb25zLnBy", "b3RvIjAKF0dldEFjY291bnRCdWRnZXRSZXF1ZXN0EhUKDXJlc291cmNlX25h", "bWUYASABKAky0gEKFEFjY291bnRCdWRnZXRTZXJ2aWNlErkBChBHZXRBY2Nv", "dW50QnVkZ2V0EjkuZ29vZ2xlLmFkcy5nb29nbGVhZHMudjEuc2VydmljZXMu", "R2V0QWNjb3VudEJ1ZGdldFJlcXVlc3QaMC5nb29nbGUuYWRzLmdvb2dsZWFk", "cy52MS5yZXNvdXJjZXMuQWNjb3VudEJ1ZGdldCI4gtPkkwIyEjAvdjEve3Jl", "c291cmNlX25hbWU9Y3VzdG9tZXJzLyovYWNjb3VudEJ1ZGdldHMvKn1CgAIK", "JGNvbS5nb29nbGUuYWRzLmdvb2dsZWFkcy52MS5zZXJ2aWNlc0IZQWNjb3Vu", "dEJ1ZGdldFNlcnZpY2VQcm90b1ABWkhnb29nbGUuZ29sYW5nLm9yZy9nZW5w", "cm90by9nb29nbGVhcGlzL2Fkcy9nb29nbGVhZHMvdjEvc2VydmljZXM7c2Vy", "dmljZXOiAgNHQUGqAiBHb29nbGUuQWRzLkdvb2dsZUFkcy5WMS5TZXJ2aWNl", "c8oCIEdvb2dsZVxBZHNcR29vZ2xlQWRzXFYxXFNlcnZpY2Vz6gIkR29vZ2xl", "OjpBZHM6Okdvb2dsZUFkczo6VjE6OlNlcnZpY2VzYgZwcm90bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Ads.GoogleAds.V1.Resources.AccountBudgetReflection.Descriptor, global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V1.Services.GetAccountBudgetRequest), global::Google.Ads.GoogleAds.V1.Services.GetAccountBudgetRequest.Parser, new[]{ "ResourceName" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Request message for /// [AccountBudgetService.GetAccountBudget][google.ads.googleads.v1.services.AccountBudgetService.GetAccountBudget]. /// </summary> public sealed partial class GetAccountBudgetRequest : pb::IMessage<GetAccountBudgetRequest> { private static readonly pb::MessageParser<GetAccountBudgetRequest> _parser = new pb::MessageParser<GetAccountBudgetRequest>(() => new GetAccountBudgetRequest()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetAccountBudgetRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V1.Services.AccountBudgetServiceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetAccountBudgetRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetAccountBudgetRequest(GetAccountBudgetRequest other) : this() { resourceName_ = other.resourceName_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetAccountBudgetRequest Clone() { return new GetAccountBudgetRequest(this); } /// <summary>Field number for the "resource_name" field.</summary> public const int ResourceNameFieldNumber = 1; private string resourceName_ = ""; /// <summary> /// The resource name of the account-level budget to fetch. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ResourceName { get { return resourceName_; } set { resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetAccountBudgetRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetAccountBudgetRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ResourceName != other.ResourceName) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ResourceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetAccountBudgetRequest other) { if (other == null) { return; } if (other.ResourceName.Length != 0) { ResourceName = other.ResourceName; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { ResourceName = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
39.438144
231
0.71324
[ "Apache-2.0" ]
chrisdunelm/google-ads-dotnet
src/V1/Stubs/AccountBudgetService.cs
7,651
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.LocationService")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon Location Service. Initial release of Amazon Location Service. A new geospatial service providing capabilities to render maps, geocode/reverse geocode, track device locations, and detect geofence entry/exit events.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon Location Service. Initial release of Amazon Location Service. A new geospatial service providing capabilities to render maps, geocode/reverse geocode, track device locations, and detect geofence entry/exit events.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - Amazon Location Service. Initial release of Amazon Location Service. A new geospatial service providing capabilities to render maps, geocode/reverse geocode, track device locations, and detect geofence entry/exit events.")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - Amazon Location Service. Initial release of Amazon Location Service. A new geospatial service providing capabilities to render maps, geocode/reverse geocode, track device locations, and detect geofence entry/exit events.")] #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.10.1")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
55.137255
312
0.780228
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/LocationService/Properties/AssemblyInfo.cs
2,812
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Jag.PillPressRegistry.Interfaces { using Microsoft.Rest; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// Customaddresscontactbusinessaddress operations. /// </summary> public partial class Customaddresscontactbusinessaddress : IServiceOperations<DynamicsClient>, ICustomaddresscontactbusinessaddress { /// <summary> /// Initializes a new instance of the Customaddresscontactbusinessaddress class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public Customaddresscontactbusinessaddress(DynamicsClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DynamicsClient /// </summary> public DynamicsClient Client { get; private set; } /// <summary> /// Get bcgov_customaddress_contact_BusinessAddress from bcgov_customaddresses /// </summary> /// <param name='bcgovCustomaddressid'> /// key: bcgov_customaddressid of bcgov_customaddress /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<MicrosoftDynamicsCRMcontactCollection>> GetWithHttpMessagesAsync(string bcgovCustomaddressid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (bcgovCustomaddressid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "bcgovCustomaddressid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("bcgovCustomaddressid", bcgovCustomaddressid); tracingParameters.Add("top", top); tracingParameters.Add("skip", skip); tracingParameters.Add("search", search); tracingParameters.Add("filter", filter); tracingParameters.Add("count", count); tracingParameters.Add("orderby", orderby); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bcgov_customaddresses({bcgov_customaddressid})/bcgov_customaddress_contact_BusinessAddress").ToString(); _url = _url.Replace("{bcgov_customaddressid}", System.Uri.EscapeDataString(bcgovCustomaddressid)); List<string> _queryParameters = new List<string>(); if (top != null) { _queryParameters.Add(string.Format("$top={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(top, Client.SerializationSettings).Trim('"')))); } if (skip != null) { _queryParameters.Add(string.Format("$skip={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(skip, Client.SerializationSettings).Trim('"')))); } if (search != null) { _queryParameters.Add(string.Format("$search={0}", System.Uri.EscapeDataString(search))); } if (filter != null) { _queryParameters.Add(string.Format("$filter={0}", System.Uri.EscapeDataString(filter))); } if (count != null) { _queryParameters.Add(string.Format("$count={0}", System.Uri.EscapeDataString(Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(count, Client.SerializationSettings).Trim('"')))); } if (orderby != null) { _queryParameters.Add(string.Format("$orderby={0}", System.Uri.EscapeDataString(string.Join(",", orderby)))); } if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<MicrosoftDynamicsCRMcontactCollection>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMcontactCollection>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get bcgov_customaddress_contact_BusinessAddress from bcgov_customaddresses /// </summary> /// <param name='bcgovCustomaddressid'> /// key: bcgov_customaddressid of bcgov_customaddress /// </param> /// <param name='contactid'> /// key: contactid of contact /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<HttpOperationResponse<MicrosoftDynamicsCRMcontact>> BusinessAddressByKeyWithHttpMessagesAsync(string bcgovCustomaddressid, string contactid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (bcgovCustomaddressid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "bcgovCustomaddressid"); } if (contactid == null) { throw new ValidationException(ValidationRules.CannotBeNull, "contactid"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("bcgovCustomaddressid", bcgovCustomaddressid); tracingParameters.Add("contactid", contactid); tracingParameters.Add("select", select); tracingParameters.Add("expand", expand); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "BusinessAddressByKey", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "bcgov_customaddresses({bcgov_customaddressid})/bcgov_customaddress_contact_BusinessAddress({contactid})").ToString(); _url = _url.Replace("{bcgov_customaddressid}", System.Uri.EscapeDataString(bcgovCustomaddressid)); _url = _url.Replace("{contactid}", System.Uri.EscapeDataString(contactid)); List<string> _queryParameters = new List<string>(); if (select != null) { _queryParameters.Add(string.Format("$select={0}", System.Uri.EscapeDataString(string.Join(",", select)))); } if (expand != null) { _queryParameters.Add(string.Format("$expand={0}", System.Uri.EscapeDataString(string.Join(",", expand)))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse<MicrosoftDynamicsCRMcontact>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<MicrosoftDynamicsCRMcontact>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
45.161593
553
0.570888
[ "Apache-2.0" ]
GeorgeWalker/jag-pill-press-registry
pill-press-interfaces/Dynamics-Autorest/Customaddresscontactbusinessaddress.cs
19,284
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Interpolation utility functions: easing, bezier, and catmull-rom. * Consider using Unity's Animation curve editor and AnimationCurve class * before scripting the desired behaviour using this utility. * * Interpolation functionality available at different levels of abstraction. * Low level access via individual easing functions (ex. EaseInOutCirc), * Bezier(), and CatmullRom(). High level access using sequence generators, * NewEase(), NewBezier(), and NewCatmullRom(). * * Sequence generators are typically used as follows: * * IEnumerable<Vector3> sequence = Interpolate.New[Ease|Bezier|CatmulRom](configuration); * foreach (Vector3 newPoint in sequence) { * transform.position = newPoint; * yield return WaitForSeconds(1.0f); * } * * Or: * * IEnumerator<Vector3> sequence = Interpolate.New[Ease|Bezier|CatmulRom](configuration).GetEnumerator(); * function Update() { * if (sequence.MoveNext()) { * transform.position = sequence.Current; * } * } * * The low level functions work similarly to Unity's built in Lerp and it is * up to you to track and pass in elapsedTime and duration on every call. The * functions take this form (or the logical equivalent for Bezier() and CatmullRom()). * * transform.position = ease(start, distance, elapsedTime, duration); * * For convenience in configuration you can use the Ease(EaseType) function to * look up a concrete easing function: * * [SerializeField] * Interpolate.EaseType easeType; // set using Unity's property inspector * Interpolate.Function ease; // easing of a particular EaseType * function Awake() { * ease = Interpolate.Ease(easeType); * } * * @author Fernando Zapata (fernando@cpudreams.com) * @Traduzione Andrea85cs (andrea85cs@dynematica.it) * *@source http://wiki.unity3d.com/index.php?title=Interpolate */ public class Interpolate { /** * Different methods of easing interpolation. */ public enum EaseType { Linear, EaseInQuad, EaseOutQuad, EaseInOutQuad, EaseInCubic, EaseOutCubic, EaseInOutCubic, EaseInQuart, EaseOutQuart, EaseInOutQuart, EaseInQuint, EaseOutQuint, EaseInOutQuint, EaseInSine, EaseOutSine, EaseInOutSine, EaseInExpo, EaseOutExpo, EaseInOutExpo, EaseInCirc, EaseOutCirc, EaseInOutCirc } /** * Sequence of eleapsedTimes until elapsedTime is >= duration. * * Note: elapsedTimes are calculated using the value of Time.deltatTime each * time a value is requested. */ static Vector3 Identity(Vector3 v) { return v; } static Vector3 TransformDotPosition(Transform t) { return t.position; } static IEnumerable<float> NewTimer(float duration) { float elapsedTime = 0.0f; while (elapsedTime < duration) { yield return elapsedTime; elapsedTime += Time.deltaTime; // make sure last value is never skipped if (elapsedTime >= duration) { yield return elapsedTime; } } } public delegate Vector3 ToVector3<T>(T v); public delegate float Function(float a, float b, float c, float d); /** * Generates sequence of integers from start to end (inclusive) one step * at a time. */ static IEnumerable<float> NewCounter(int start, int end, int step) { for (int i = start; i <= end; i += step) { yield return i; } } /** * Returns sequence generator from start to end over duration using the * given easing function. The sequence is generated as it is accessed * using the Time.deltaTime to calculate the portion of duration that has * elapsed. */ public static IEnumerator NewEase(Function ease, Vector3 start, Vector3 end, float duration) { IEnumerable<float> timer = Interpolate.NewTimer(duration); return NewEase(ease, start, end, duration, timer); } /** * Instead of easing based on time, generate n interpolated points (slices) * between the start and end positions. */ public static IEnumerator NewEase(Function ease, Vector3 start, Vector3 end, int slices) { IEnumerable<float> counter = Interpolate.NewCounter(0, slices + 1, 1); return NewEase(ease, start, end, slices + 1, counter); } /** * Generic easing sequence generator used to implement the time and * slice variants. Normally you would not use this function directly. */ static IEnumerator NewEase(Function ease, Vector3 start, Vector3 end, float total, IEnumerable<float> driver) { Vector3 distance = end - start; foreach (float i in driver) { yield return Ease(ease, start, distance, i, total); } } /** * Vector3 interpolation using given easing method. Easing is done independently * on all three vector axis. */ static Vector3 Ease(Function ease, Vector3 start, Vector3 distance, float elapsedTime, float duration) { start.x = ease(start.x, distance.x, elapsedTime, duration); start.y = ease(start.y, distance.y, elapsedTime, duration); start.z = ease(start.z, distance.z, elapsedTime, duration); return start; } /** * Returns the static method that implements the given easing type for scalars. * Use this method to easily switch between easing interpolation types. * * All easing methods clamp elapsedTime so that it is always <= duration. * * var ease = Interpolate.Ease(EaseType.EaseInQuad); * i = ease(start, distance, elapsedTime, duration); */ public static Function Ease(EaseType type) { // Source Flash easing functions: // http://gizma.com/easing/ // http://www.robertpenner.com/easing/easing_demo.html // // Changed to use more friendly variable names, that follow my Lerp // conventions: // start = b (start value) // distance = c (change in value) // elapsedTime = t (current time) // duration = d (time duration) Function f = null; switch (type) { case EaseType.Linear: f = Interpolate.Linear; break; case EaseType.EaseInQuad: f = Interpolate.EaseInQuad; break; case EaseType.EaseOutQuad: f = Interpolate.EaseOutQuad; break; case EaseType.EaseInOutQuad: f = Interpolate.EaseInOutQuad; break; case EaseType.EaseInCubic: f = Interpolate.EaseInCubic; break; case EaseType.EaseOutCubic: f = Interpolate.EaseOutCubic; break; case EaseType.EaseInOutCubic: f = Interpolate.EaseInOutCubic; break; case EaseType.EaseInQuart: f = Interpolate.EaseInQuart; break; case EaseType.EaseOutQuart: f = Interpolate.EaseOutQuart; break; case EaseType.EaseInOutQuart: f = Interpolate.EaseInOutQuart; break; case EaseType.EaseInQuint: f = Interpolate.EaseInQuint; break; case EaseType.EaseOutQuint: f = Interpolate.EaseOutQuint; break; case EaseType.EaseInOutQuint: f = Interpolate.EaseInOutQuint; break; case EaseType.EaseInSine: f = Interpolate.EaseInSine; break; case EaseType.EaseOutSine: f = Interpolate.EaseOutSine; break; case EaseType.EaseInOutSine: f = Interpolate.EaseInOutSine; break; case EaseType.EaseInExpo: f = Interpolate.EaseInExpo; break; case EaseType.EaseOutExpo: f = Interpolate.EaseOutExpo; break; case EaseType.EaseInOutExpo: f = Interpolate.EaseInOutExpo; break; case EaseType.EaseInCirc: f = Interpolate.EaseInCirc; break; case EaseType.EaseOutCirc: f = Interpolate.EaseOutCirc; break; case EaseType.EaseInOutCirc: f = Interpolate.EaseInOutCirc; break; } return f; } /** * Returns sequence generator from the first node to the last node over * duration time using the points in-between the first and last node * as control points of a bezier curve used to generate the interpolated points * in the sequence. If there are no control points (ie. only two nodes, first * and last) then this behaves exactly the same as NewEase(). In other words * a zero-degree bezier spline curve is just the easing method. The sequence * is generated as it is accessed using the Time.deltaTime to calculate the * portion of duration that has elapsed. */ public static IEnumerable<Vector3> NewBezier(Function ease, Transform[] nodes, float duration) { IEnumerable<float> timer = Interpolate.NewTimer(duration); return NewBezier<Transform>(ease, nodes, TransformDotPosition, duration, timer); } /** * Instead of interpolating based on time, generate n interpolated points * (slices) between the first and last node. */ public static IEnumerable<Vector3> NewBezier(Function ease, Transform[] nodes, int slices) { IEnumerable<float> counter = NewCounter(0, slices + 1, 1); return NewBezier<Transform>(ease, nodes, TransformDotPosition, slices + 1, counter); } /** * A Vector3[] variation of the Transform[] NewBezier() function. * Same functionality but using Vector3s to define bezier curve. */ public static IEnumerable<Vector3> NewBezier(Function ease, Vector3[] points, float duration) { IEnumerable<float> timer = NewTimer(duration); return NewBezier<Vector3>(ease, points, Identity, duration, timer); } /** * A Vector3[] variation of the Transform[] NewBezier() function. * Same functionality but using Vector3s to define bezier curve. */ public static IEnumerable<Vector3> NewBezier(Function ease, Vector3[] points, int slices) { IEnumerable<float> counter = NewCounter(0, slices + 1, 1); return NewBezier<Vector3>(ease, points, Identity, slices + 1, counter); } /** * Generic bezier spline sequence generator used to implement the time and * slice variants. Normally you would not use this function directly. */ static IEnumerable<Vector3> NewBezier<T>(Function ease, IList nodes, ToVector3<T> toVector3, float maxStep, IEnumerable<float> steps) { // need at least two nodes to spline between if (nodes.Count >= 2) { // copy nodes array since Bezier is destructive Vector3[] points = new Vector3[nodes.Count]; foreach (float step in steps) { // re-initialize copy before each destructive call to Bezier for (int i = 0; i < nodes.Count; i++) { points[i] = toVector3((T)nodes[i]); } yield return Bezier(ease, points, step, maxStep); // make sure last value is always generated } } } /** * A Vector3 n-degree bezier spline. * * WARNING: The points array is modified by Bezier. See NewBezier() for a * safe and user friendly alternative. * * You can pass zero control points, just the start and end points, for just * plain easing. In other words a zero-degree bezier spline curve is just the * easing method. * * @param points start point, n control points, end point */ static Vector3 Bezier(Function ease, Vector3[] points, float elapsedTime, float duration) { // Reference: http://ibiblio.org/e-notes/Splines/Bezier.htm // Interpolate the n starting points to generate the next j = (n - 1) points, // then interpolate those n - 1 points to generate the next n - 2 points, // continue this until we have generated the last point (n - (n - 1)), j = 1. // We store the next set of output points in the same array as the // input points used to generate them. This works because we store the // result in the slot of the input point that is no longer used for this // iteration. for (int j = points.Length - 1; j > 0; j--) { for (int i = 0; i < j; i++) { points[i].x = ease(points[i].x, points[i + 1].x - points[i].x, elapsedTime, duration); points[i].y = ease(points[i].y, points[i + 1].y - points[i].y, elapsedTime, duration); points[i].z = ease(points[i].z, points[i + 1].z - points[i].z, elapsedTime, duration); } } return points[0]; } /** * Returns sequence generator from the first node, through each control point, * and to the last node. N points are generated between each node (slices) * using Catmull-Rom. */ public static IEnumerable<Vector3> NewCatmullRom(Transform[] nodes, int slices, bool loop) { return NewCatmullRom<Transform>(nodes, TransformDotPosition, slices, loop); } /** * A Vector3[] variation of the Transform[] NewCatmullRom() function. * Same functionality but using Vector3s to define curve. */ public static IEnumerable<Vector3> NewCatmullRom(Vector3[] points, int slices, bool loop) { return NewCatmullRom<Vector3>(points, Identity, slices, loop); } /** * Generic catmull-rom spline sequence generator used to implement the * Vector3[] and Transform[] variants. Normally you would not use this * function directly. */ static IEnumerable<Vector3> NewCatmullRom<T>(IList nodes, ToVector3<T> toVector3, int slices, bool loop) { // need at least two nodes to spline between if (nodes.Count >= 2) { // yield the first point explicitly, if looping the first point // will be generated again in the step for loop when interpolating // from last point back to the first point yield return toVector3((T)nodes[0]); int last = nodes.Count - 1; for (int current = 0; loop || current < last; current++) { // wrap around when looping if (loop && current > last) { current = 0; } // handle edge cases for looping and non-looping scenarios // when looping we wrap around, when not looping use start for previous // and end for next when you at the ends of the nodes array int previous = (current == 0) ? ((loop) ? last : current) : current - 1; int start = current; int end = (current == last) ? ((loop) ? 0 : current) : current + 1; int next = (end == last) ? ((loop) ? 0 : end) : end + 1; // adding one guarantees yielding at least the end point int stepCount = slices + 1; for (int step = 1; step <= stepCount; step++) { yield return CatmullRom(toVector3((T)nodes[previous]), toVector3((T)nodes[start]), toVector3((T)nodes[end]), toVector3((T)nodes[next]), step, stepCount); } } } } /** * A Vector3 Catmull-Rom spline. Catmull-Rom splines are similar to bezier * splines but have the useful property that the generated curve will go * through each of the control points. * * NOTE: The NewCatmullRom() functions are an easier to use alternative to this * raw Catmull-Rom implementation. * * @param previous the point just before the start point or the start point * itself if no previous point is available * @param start generated when elapsedTime == 0 * @param end generated when elapsedTime >= duration * @param next the point just after the end point or the end point itself if no * next point is available */ static Vector3 CatmullRom(Vector3 previous, Vector3 start, Vector3 end, Vector3 next, float elapsedTime, float duration) { // References used: // p.266 GemsV1 // // tension is often set to 0.5 but you can use any reasonable value: // http://www.cs.cmu.edu/~462/projects/assn2/assn2/catmullRom.pdf // // bias and tension controls: // http://local.wasp.uwa.edu.au/~pbourke/miscellaneous/interpolation/ float percentComplete = elapsedTime / duration; float percentCompleteSquared = percentComplete * percentComplete; float percentCompleteCubed = percentCompleteSquared * percentComplete; return previous * (-0.5f * percentCompleteCubed + percentCompleteSquared - 0.5f * percentComplete) + start * (1.5f * percentCompleteCubed + -2.5f * percentCompleteSquared + 1.0f) + end * (-1.5f * percentCompleteCubed + 2.0f * percentCompleteSquared + 0.5f * percentComplete) + next * (0.5f * percentCompleteCubed - 0.5f * percentCompleteSquared); } /** * Linear interpolation (same as Mathf.Lerp) */ static float Linear(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime to be <= duration if (elapsedTime > duration) { elapsedTime = duration; } return distance * (elapsedTime / duration) + start; } /** * quadratic easing in - accelerating from zero velocity */ static float EaseInQuad(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return distance * elapsedTime * elapsedTime + start; } /** * quadratic easing out - decelerating to zero velocity */ static float EaseOutQuad(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return -distance * elapsedTime * (elapsedTime - 2) + start; } /** * quadratic easing in/out - acceleration until halfway, then deceleration */ static float EaseInOutQuad(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2); if (elapsedTime < 1) return distance / 2 * elapsedTime * elapsedTime + start; elapsedTime--; return -distance / 2 * (elapsedTime * (elapsedTime - 2) - 1) + start; } /** * cubic easing in - accelerating from zero velocity */ static float EaseInCubic(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return distance * elapsedTime * elapsedTime * elapsedTime + start; } /** * cubic easing out - decelerating to zero velocity */ static float EaseOutCubic(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; elapsedTime--; return distance * (elapsedTime * elapsedTime * elapsedTime + 1) + start; } /** * cubic easing in/out - acceleration until halfway, then deceleration */ static float EaseInOutCubic(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2); if (elapsedTime < 1) return distance / 2 * elapsedTime * elapsedTime * elapsedTime + start; elapsedTime -= 2; return distance / 2 * (elapsedTime * elapsedTime * elapsedTime + 2) + start; } /** * quartic easing in - accelerating from zero velocity */ static float EaseInQuart(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return distance * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start; } /** * quartic easing out - decelerating to zero velocity */ static float EaseOutQuart(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; elapsedTime--; return -distance * (elapsedTime * elapsedTime * elapsedTime * elapsedTime - 1) + start; } /** * quartic easing in/out - acceleration until halfway, then deceleration */ static float EaseInOutQuart(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2); if (elapsedTime < 1) return distance / 2 * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start; elapsedTime -= 2; return -distance / 2 * (elapsedTime * elapsedTime * elapsedTime * elapsedTime - 2) + start; } /** * quintic easing in - accelerating from zero velocity */ static float EaseInQuint(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return distance * elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start; } /** * quintic easing out - decelerating to zero velocity */ static float EaseOutQuint(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; elapsedTime--; return distance * (elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + 1) + start; } /** * quintic easing in/out - acceleration until halfway, then deceleration */ static float EaseInOutQuint(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2f); if (elapsedTime < 1) return distance / 2 * elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + start; elapsedTime -= 2; return distance / 2 * (elapsedTime * elapsedTime * elapsedTime * elapsedTime * elapsedTime + 2) + start; } /** * sinusoidal easing in - accelerating from zero velocity */ static float EaseInSine(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime to be <= duration if (elapsedTime > duration) { elapsedTime = duration; } return -distance * Mathf.Cos(elapsedTime / duration * (Mathf.PI / 2)) + distance + start; } /** * sinusoidal easing out - decelerating to zero velocity */ static float EaseOutSine(float start, float distance, float elapsedTime, float duration) { if (elapsedTime > duration) { elapsedTime = duration; } return distance * Mathf.Sin(elapsedTime / duration * (Mathf.PI / 2)) + start; } /** * sinusoidal easing in/out - accelerating until halfway, then decelerating */ static float EaseInOutSine(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime to be <= duration if (elapsedTime > duration) { elapsedTime = duration; } return -distance / 2 * (Mathf.Cos(Mathf.PI * elapsedTime / duration) - 1) + start; } /** * exponential easing in - accelerating from zero velocity */ static float EaseInExpo(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime to be <= duration if (elapsedTime > duration) { elapsedTime = duration; } return distance * Mathf.Pow(2, 10 * (elapsedTime / duration - 1)) + start; } /** * exponential easing out - decelerating to zero velocity */ static float EaseOutExpo(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime to be <= duration if (elapsedTime > duration) { elapsedTime = duration; } return distance * (-Mathf.Pow(2, -10 * elapsedTime / duration) + 1) + start; } /** * exponential easing in/out - accelerating until halfway, then decelerating */ static float EaseInOutExpo(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2); if (elapsedTime < 1) return distance / 2 * Mathf.Pow(2, 10 * (elapsedTime - 1)) + start; elapsedTime--; return distance / 2 * (-Mathf.Pow(2, -10 * elapsedTime) + 2) + start; } /** * circular easing in - accelerating from zero velocity */ static float EaseInCirc(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; return -distance * (Mathf.Sqrt(1 - elapsedTime * elapsedTime) - 1) + start; } /** * circular easing out - decelerating to zero velocity */ static float EaseOutCirc(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 1.0f : elapsedTime / duration; elapsedTime--; return distance * Mathf.Sqrt(1 - elapsedTime * elapsedTime) + start; } /** * circular easing in/out - acceleration until halfway, then deceleration */ static float EaseInOutCirc(float start, float distance, float elapsedTime, float duration) { // clamp elapsedTime so that it cannot be greater than duration elapsedTime = (elapsedTime > duration) ? 2.0f : elapsedTime / (duration / 2); if (elapsedTime < 1) return -distance / 2 * (Mathf.Sqrt(1 - elapsedTime * elapsedTime) - 1) + start; elapsedTime -= 2; return distance / 2 * (Mathf.Sqrt(1 - elapsedTime * elapsedTime) + 1) + start; } }
41.283212
138
0.614201
[ "MIT" ]
Seth-W/SmallMarlin
Assets/Scripts/Libraries/Interpolate.cs
28,281
C#
namespace teknikservis.Migrations { using System; using System.Data.Entity; using System.Data.Entity.Migrations; using System.Linq; internal sealed class Configuration : DbMigrationsConfiguration<TeknikServis.Data.DataContext.TeknikContext> { public Configuration() { AutomaticMigrationsEnabled = false; } protected override void Seed(TeknikServis.Data.DataContext.TeknikContext context) { // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. E.g. // // context.People.AddOrUpdate( // p => p.FullName, // new Person { FullName = "Andrew Peters" }, // new Person { FullName = "Brice Lambson" }, // new Person { FullName = "Rowan Miller" } // ); // } } }
32.1875
112
0.568932
[ "MIT" ]
necipcanguler/teknik-servis
teknikservis/Migrations/Configuration.cs
1,030
C#
using GostCryptography.Tests.Properties; using GostCryptography.Xml; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Security.Cryptography.X509Certificates; using System.Security.Cryptography.Xml; using System.Text; using System.Threading.Tasks; using System.Xml; namespace GostCryptography.Tests.Xml.Sign { [TestFixture(Description = "Подпись и проверка подписи XML-документа с использованием сертификата 2012-256")] public sealed class SignedXmlCertificate2012_256_Test { [Test] public void ShouldSignXml() { GostCryptography.Cryptography.GostCryptoConfig.ProviderType = Cryptography.ProviderTypes.CryptoPro_2012_256; // Given var signingCertificate = TestCertificates.GetCertificate3410_2012_256(); var xmlDocument = CreateXmlDocument(); // When var signedXmlDocument = SignXmlDocument(xmlDocument, signingCertificate); // Then Assert.IsTrue(VerifyXmlDocumentSignature(signedXmlDocument)); } private static XmlDocument CreateXmlDocument() { var document = new XmlDocument(); document.LoadXml(Resources.SignedXmlExample); return document; } private static XmlDocument SignXmlDocument(XmlDocument xmlDocument, X509Certificate2 signingCertificate) { // Создание подписчика XML-документа var signedXml = new GostSignedXml(xmlDocument); // Установка ключа для создания подписи signedXml.SetSigningCertificate(signingCertificate); // Ссылка на узел, который нужно подписать, с указанием алгоритма хэширования var dataReference = new Reference { Uri = "#Id1", DigestMethod = GostSignedXml.XmlDsigGost3411_2012_256Url }; // Установка ссылки на узел signedXml.AddReference(dataReference); // Установка информации о сертификате, который использовался для создания подписи var keyInfo = new KeyInfo(); keyInfo.AddClause(new KeyInfoX509Data(signingCertificate)); signedXml.KeyInfo = keyInfo; // Вычисление подписи signedXml.ComputeSignature(); // Получение XML-представления подписи var signatureXml = signedXml.GetXml(); // Добавление подписи в исходный документ xmlDocument.DocumentElement.AppendChild(xmlDocument.ImportNode(signatureXml, true)); return xmlDocument; } private static bool VerifyXmlDocumentSignature(XmlDocument signedXmlDocument) { // Создание подписчика XML-документа var signedXml = new GostSignedXml(signedXmlDocument); // Поиск узла с подписью var nodeList = signedXmlDocument.GetElementsByTagName("Signature", SignedXml.XmlDsigNamespaceUrl); // Загрузка найденной подписи signedXml.LoadXml((XmlElement)nodeList[0]); // Проверка подписи return signedXml.CheckSignature(); } } }
36.103448
121
0.672397
[ "MIT" ]
IronRate/GostCryptography
Source/GostCryptography.Tests/Xml/Sign/SignedXmlCertificate2012_256_Test.cs
3,577
C#
using System; using System.Collections.Generic; using System.Text; namespace Domain.Enumeration { public enum MessageRecordSendMethod { Undefined = 0, EMail = 1, SMS = 2 } }
15.142857
39
0.632075
[ "MIT" ]
asheng71/WebProjectTemplate
Domain/Enumeration/MessageRecordSendMethod.cs
214
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Xml.Linq; namespace Something { /// <summary> /// Interaction logic for MainPage.xaml /// </summary> public partial class MainPage : Page { public MainPage() { InitializeComponent(); } private void OpenAboutWindow(object sender, RoutedEventArgs e) => new About().ShowDialog(); private void TheStart(object sender, RoutedEventArgs e) { NavigationService.Navigate(new GameSelect(ComboxVal)); } int ComboxVal; private void ComboBoxSelect(object sender, SelectionChangedEventArgs e) => ComboxVal = MenuEffComboBox.SelectedIndex; private void MouseColorEffect(object sender, MouseEventArgs e) { if (ComboxVal != 3) { double hue = (Math.Atan2(e.GetPosition(centerPoint).X, e.GetPosition(centerPoint).Y) * 180 / Math.PI) + 180; Brush x = new SolidColorBrush(Common.HtoRGB(hue)); if (ComboxVal == 0) { //default Btn_Abt.Margin = new Thickness(0, 40, 60, 0); OpeningScreen.Background = Btn_Main.Foreground = x; ellipse1.Visibility = ellipse2.Visibility = ellipse3.Visibility = rect1.Visibility = Visibility.Visible; ellipse1.Fill = ellipse2.Fill = ellipse3.Fill = rect1.Fill = new SolidColorBrush(Color.FromRgb(0, 0, 0)); } else if (ComboxVal == 1) { //inverted Btn_Abt.Margin = new Thickness(0, 40, 60, 0); ellipse1.Visibility = ellipse2.Visibility = ellipse3.Visibility = rect1.Visibility = Visibility.Visible; ellipse1.Fill = ellipse2.Fill = ellipse3.Fill = rect1.Fill = Btn_Main.Foreground = x; OpeningScreen.Background = new SolidColorBrush(Color.FromRgb(0, 0, 0)); } else if (ComboxVal == 2) { //plain Btn_Abt.Margin = new Thickness(0, 5, 85, 0); OpeningScreen.Background = Btn_Main.Foreground = x; ellipse1.Visibility = ellipse2.Visibility = ellipse3.Visibility = rect1.Visibility = Visibility.Collapsed; } } } private void Editorbtn_Click(object sender, RoutedEventArgs e) => MessageBox.Show("Coming Soon!!!"); } }
40.239437
126
0.59398
[ "MIT" ]
U-C-S/Something
Something/MainPage.xaml.cs
2,859
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\IEntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface ITermsAndConditionsAcceptanceStatusesCollectionRequest. /// </summary> public partial interface ITermsAndConditionsAcceptanceStatusesCollectionRequest : IBaseRequest { /// <summary> /// Adds the specified TermsAndConditionsAcceptanceStatus to the collection via POST. /// </summary> /// <param name="termsAndConditionsAcceptanceStatus">The TermsAndConditionsAcceptanceStatus to add.</param> /// <returns>The created TermsAndConditionsAcceptanceStatus.</returns> System.Threading.Tasks.Task<TermsAndConditionsAcceptanceStatus> AddAsync(TermsAndConditionsAcceptanceStatus termsAndConditionsAcceptanceStatus); /// <summary> /// Adds the specified TermsAndConditionsAcceptanceStatus to the collection via POST. /// </summary> /// <param name="termsAndConditionsAcceptanceStatus">The TermsAndConditionsAcceptanceStatus to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created TermsAndConditionsAcceptanceStatus.</returns> System.Threading.Tasks.Task<TermsAndConditionsAcceptanceStatus> AddAsync(TermsAndConditionsAcceptanceStatus termsAndConditionsAcceptanceStatus, CancellationToken cancellationToken); /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> System.Threading.Tasks.Task<ITermsAndConditionsAcceptanceStatusesCollectionPage> GetAsync(); /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> System.Threading.Tasks.Task<ITermsAndConditionsAcceptanceStatusesCollectionPage> GetAsync(CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> ITermsAndConditionsAcceptanceStatusesCollectionRequest Expand(string value); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> ITermsAndConditionsAcceptanceStatusesCollectionRequest Expand(Expression<Func<TermsAndConditionsAcceptanceStatus, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> ITermsAndConditionsAcceptanceStatusesCollectionRequest Select(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> ITermsAndConditionsAcceptanceStatusesCollectionRequest Select(Expression<Func<TermsAndConditionsAcceptanceStatus, object>> selectExpression); /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> ITermsAndConditionsAcceptanceStatusesCollectionRequest Top(int value); /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> ITermsAndConditionsAcceptanceStatusesCollectionRequest Filter(string value); /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> ITermsAndConditionsAcceptanceStatusesCollectionRequest Skip(int value); /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> ITermsAndConditionsAcceptanceStatusesCollectionRequest OrderBy(string value); } }
49.523364
189
0.66371
[ "MIT" ]
AzureMentor/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/ITermsAndConditionsAcceptanceStatusesCollectionRequest.cs
5,299
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.Linq; using System.Reflection.Internal; using System.Text; using Xunit; namespace System.Reflection.Metadata.Tests { public class MemoryBlockTests { [Fact] public unsafe void Utf8NullTerminatedStringStartsWithAsciiPrefix() { byte[] heap; fixed (byte* heapPtr = (heap = new byte[] { 0 })) { Assert.True( new MemoryBlock( heapPtr, heap.Length ).Utf8NullTerminatedStringStartsWithAsciiPrefix(0, "") ); } fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes("Hello World!\0"))) { Assert.True( new MemoryBlock( heapPtr, heap.Length ).Utf8NullTerminatedStringStartsWithAsciiPrefix("Hello ".Length, "World") ); Assert.False( new MemoryBlock( heapPtr, heap.Length ).Utf8NullTerminatedStringStartsWithAsciiPrefix("Hello ".Length, "World?") ); } fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes("x\0"))) { Assert.False( new MemoryBlock( heapPtr, heap.Length ).Utf8NullTerminatedStringStartsWithAsciiPrefix(0, "xyz") ); Assert.True( new MemoryBlock( heapPtr, heap.Length ).Utf8NullTerminatedStringStartsWithAsciiPrefix(0, "x") ); } // bad metadata (#String heap is not nul-terminated): fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes("abcx"))) { Assert.True( new MemoryBlock( heapPtr, heap.Length ).Utf8NullTerminatedStringStartsWithAsciiPrefix(3, "x") ); Assert.False( new MemoryBlock( heapPtr, heap.Length ).Utf8NullTerminatedStringStartsWithAsciiPrefix(3, "xyz") ); } } [Fact] public unsafe void EncodingLightUpHasSucceededAndTestsStillPassWithPortableFallbackAsWell() { Assert.True(EncodingHelper.TestOnly_LightUpEnabled); // tests run on .NET Framework only right now. try { // Re-run them with forced portable implementation. EncodingHelper.TestOnly_LightUpEnabled = false; DefaultDecodingFallbackMatchesBcl(); DecodingSuccessMatchesBcl(); DecoderIsUsedCorrectly(); LightUpTrickFromDifferentAssemblyWorks(); } finally { EncodingHelper.TestOnly_LightUpEnabled = true; } } [Fact] public unsafe void DefaultDecodingFallbackMatchesBcl() { byte[] buffer; int bytesRead; var decoder = MetadataStringDecoder.DefaultUTF8; // dangling lead byte fixed (byte* ptr = (buffer = new byte[] { 0xC0 })) { string s = new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated( 0, null, decoder, out bytesRead ); Assert.Equal( "\uFFFD", new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated( 0, null, decoder, out bytesRead ) ); Assert.Equal(s, Encoding.UTF8.GetString(buffer)); Assert.Equal(buffer.Length, bytesRead); s = new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated( 0, Encoding.UTF8.GetBytes("Hello"), decoder, out bytesRead ); Assert.Equal("Hello\uFFFD", s); Assert.Equal(s, "Hello" + Encoding.UTF8.GetString(buffer)); Assert.Equal(buffer.Length, bytesRead); Assert.Equal( "\uFFFD", new MemoryBlock(ptr, buffer.Length).PeekUtf8(0, buffer.Length) ); } // overlong encoding fixed (byte* ptr = (buffer = new byte[] { (byte)'a', 0xC0, 0xAF, (byte)'b', 0x0 })) { var block = new MemoryBlock(ptr, buffer.Length); Assert.Equal( "a\uFFFD\uFFFDb", block.PeekUtf8NullTerminated(0, null, decoder, out bytesRead) ); Assert.Equal(buffer.Length, bytesRead); } // TODO: There are a bunch more error cases of course, but this is enough to break the old code // and we now just call the BCL, so from a white box perspective, we needn't get carried away. } [Fact] public unsafe void DecodingSuccessMatchesBcl() { var utf8 = Encoding.GetEncoding( "utf-8", EncoderFallback.ExceptionFallback, DecoderFallback.ExceptionFallback ); byte[] buffer; int bytesRead; string str = "\u4F60\u597D. Comment \u00E7a va?"; var decoder = MetadataStringDecoder.DefaultUTF8; fixed (byte* ptr = (buffer = utf8.GetBytes(str))) { Assert.Equal( str, new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated( 0, null, decoder, out bytesRead ) ); Assert.Equal(buffer.Length, bytesRead); Assert.Equal( str + str, new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated( 0, buffer, decoder, out bytesRead ) ); Assert.Equal(buffer.Length, bytesRead); Assert.Equal(str, new MemoryBlock(ptr, buffer.Length).PeekUtf8(0, buffer.Length)); } // To cover to big to pool case. str = string.Concat(Enumerable.Repeat(str, 10000)); fixed (byte* ptr = (buffer = utf8.GetBytes(str))) { Assert.Equal( str, new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated( 0, null, decoder, out bytesRead ) ); Assert.Equal(buffer.Length, bytesRead); Assert.Equal( str + str, new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated( 0, buffer, decoder, out bytesRead ) ); Assert.Equal(buffer.Length, bytesRead); Assert.Equal(str, new MemoryBlock(ptr, buffer.Length).PeekUtf8(0, buffer.Length)); } } [Fact] public unsafe void LightUpTrickFromDifferentAssemblyWorks() { // This is a trick to use our portable light up outside the reader assembly (that // I will use in Roslyn). Check that it works with encoding other than UTF8 and that it // validates arguments like the real thing. var decoder = new MetadataStringDecoder(Encoding.Unicode); Assert.Throws<ArgumentNullException>(() => decoder.GetString(null, 0)); Assert.Throws<ArgumentOutOfRangeException>(() => decoder.GetString((byte*)1, -1)); byte[] bytes; fixed ( byte* ptr = (bytes = Encoding.Unicode.GetBytes("\u00C7a marche tr\u00E8s bien.")) ) { Assert.Equal( "\u00C7a marche tr\u00E8s bien.", decoder.GetString(ptr, bytes.Length) ); } } [Fact] public unsafe void DecoderIsUsedCorrectly() { byte* ptr = null; byte[] buffer = null; int bytesRead; bool prefixed = false; var decoder = new TestMetadataStringDecoder( Encoding.UTF8, (bytes, byteCount) => { Assert.True(ptr != null); Assert.True(prefixed != (ptr == bytes)); Assert.Equal(prefixed ? "PrefixTest".Length : "Test".Length, byteCount); string s = Encoding.UTF8.GetString(bytes, byteCount); Assert.Equal(s, prefixed ? "PrefixTest" : "Test"); return "Intercepted"; } ); fixed (byte* fixedPtr = (buffer = Encoding.UTF8.GetBytes("Test"))) { ptr = fixedPtr; Assert.Equal( "Intercepted", new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated( 0, null, decoder, out bytesRead ) ); Assert.Equal(buffer.Length, bytesRead); prefixed = true; Assert.Equal( "Intercepted", new MemoryBlock(ptr, buffer.Length).PeekUtf8NullTerminated( 0, Encoding.UTF8.GetBytes("Prefix"), decoder, out bytesRead ) ); Assert.Equal(buffer.Length, bytesRead); } // decoder will fail to intercept because we don't bother calling it for empty strings. Assert.Same( string.Empty, new MemoryBlock(null, 0).PeekUtf8NullTerminated(0, null, decoder, out bytesRead) ); Assert.Equal(0, bytesRead); Assert.Same( string.Empty, new MemoryBlock(null, 0).PeekUtf8NullTerminated( 0, new byte[0], decoder, out bytesRead ) ); Assert.Equal(0, bytesRead); } private unsafe void TestComparisons( string heapValue, int offset, string value, bool unicode = false, bool ignoreCase = false ) { byte[] heap; MetadataStringDecoder decoder = MetadataStringDecoder.DefaultUTF8; fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes(heapValue))) { var block = new MemoryBlock(heapPtr, heap.Length); string heapSubstr = GetStringHeapValue(heapValue, offset); // compare: if (!unicode) { int actualCmp = block.CompareUtf8NullTerminatedStringWithAsciiString( offset, value ); int expectedCmp = StringComparer.Ordinal.Compare(heapSubstr, value); Assert.Equal(Math.Sign(expectedCmp), Math.Sign(actualCmp)); } if (!ignoreCase) { TestComparison(block, offset, value, heapSubstr, decoder, ignoreCase: true); } TestComparison(block, offset, value, heapSubstr, decoder, ignoreCase); } } private static unsafe void TestComparison( MemoryBlock block, int offset, string value, string heapSubstr, MetadataStringDecoder decoder, bool ignoreCase ) { // equals: bool actualEq = block.Utf8NullTerminatedEquals( offset, value, decoder, terminator: '\0', ignoreCase: ignoreCase ); bool expectedEq = string.Equals( heapSubstr, value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal ); Assert.Equal(expectedEq, actualEq); // starts with: bool actualSW = block.Utf8NullTerminatedStartsWith( offset, value, decoder, terminator: '\0', ignoreCase: ignoreCase ); bool expectedSW = heapSubstr.StartsWith( value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal ); Assert.Equal(actualSW, expectedSW); } [Fact] public unsafe void ComparisonToInvalidByteSequenceMatchesFallback() { MetadataStringDecoder decoder = MetadataStringDecoder.DefaultUTF8; // dangling lead byte byte[] buffer; fixed (byte* ptr = (buffer = new byte[] { 0xC0 })) { var block = new MemoryBlock(ptr, buffer.Length); Assert.False( block.Utf8NullTerminatedStartsWith( 0, new string((char)0xC0, 1), decoder, terminator: '\0', ignoreCase: false ) ); Assert.False( block.Utf8NullTerminatedEquals( 0, new string((char)0xC0, 1), decoder, terminator: '\0', ignoreCase: false ) ); Assert.True( block.Utf8NullTerminatedStartsWith( 0, "\uFFFD", decoder, terminator: '\0', ignoreCase: false ) ); Assert.True( block.Utf8NullTerminatedEquals( 0, "\uFFFD", decoder, terminator: '\0', ignoreCase: false ) ); } // overlong encoding fixed (byte* ptr = (buffer = new byte[] { (byte)'a', 0xC0, 0xAF, (byte)'b', 0x0 })) { var block = new MemoryBlock(ptr, buffer.Length); Assert.False( block.Utf8NullTerminatedStartsWith( 0, "a\\", decoder, terminator: '\0', ignoreCase: false ) ); Assert.False( block.Utf8NullTerminatedEquals( 0, "a\\b", decoder, terminator: '\0', ignoreCase: false ) ); Assert.True( block.Utf8NullTerminatedStartsWith( 0, "a\uFFFD", decoder, terminator: '\0', ignoreCase: false ) ); Assert.True( block.Utf8NullTerminatedEquals( 0, "a\uFFFD\uFFFDb", decoder, terminator: '\0', ignoreCase: false ) ); } } private string GetStringHeapValue(string heapValue, int offset) { int heapEnd = heapValue.IndexOf('\0'); return (heapEnd < 0) ? heapValue.Substring(offset) : heapValue.Substring(offset, heapEnd - offset); } [Fact] public void Utf8NullTerminatedString_Comparisons() { TestComparisons("\0", 0, ""); TestComparisons("Foo\0", 0, "Foo"); TestComparisons("Foo\0", 1, "oo"); TestComparisons("Foo\0", 1, "oops"); TestComparisons("Foo", 1, "oo"); TestComparisons("Foo", 1, "oops"); TestComparisons("x", 1, ""); TestComparisons("hello\0", 0, "h"); TestComparisons("hello\0", 0, "he"); TestComparisons("hello\0", 0, "hel"); TestComparisons("hello\0", 0, "hell"); TestComparisons("hello\0", 0, "hello"); TestComparisons("hello\0", 0, "hello!"); TestComparisons("IVector`1\0", 0, "IVectorView`1"); TestComparisons("IVector`1\0", 0, "IVector"); TestComparisons("IVectorView`1\0", 0, "IVector`1"); TestComparisons("Matrix\0", 0, "Matrix3D"); TestComparisons("Matrix3D\0", 0, "Matrix"); TestComparisons("\u1234\0", 0, "\u1234", unicode: true); TestComparisons("a\u1234\0", 0, "a", unicode: true); TestComparisons("\u1001\u1002\u1003\0", 0, "\u1001\u1002", unicode: true); TestComparisons("\u1001a\u1002\u1003\0", 0, "\u1001a\u1002", unicode: true); TestComparisons("\u1001\u1002\u1003\0", 0, "\u1001a\u1002", unicode: true); TestComparisons("\uD808\uDF45abc\0", 0, "\uD808\uDF45", unicode: true); TestComparisons("abc\u1234", 0, "abc\u1234", unicode: true); TestComparisons("abc\u1234", 0, "abc\u1235", unicode: true); TestComparisons("abc\u1234", 0, "abcd", unicode: true); TestComparisons("abcd", 0, "abc\u1234", unicode: true); TestComparisons("AAaa\0", 0, "aAAa"); TestComparisons("A\0", 0, "a", ignoreCase: true); TestComparisons("AAaa\0", 0, "aAAa", ignoreCase: true); TestComparisons("matrix3d\0", 0, "Matrix3D", ignoreCase: true); } [Fact] public unsafe void Utf8NullTerminatedFastCompare() { byte[] heap; MetadataStringDecoder decoder = MetadataStringDecoder.DefaultUTF8; const bool HonorCase = false; const bool IgnoreCase = true; const char terminator_0 = '\0'; const char terminator_F = 'F'; const char terminator_X = 'X'; const char terminator_x = 'x'; fixed ( byte* heapPtr = ( heap = new byte[] { (byte)'F', 0, (byte)'X', (byte)'Y', /* U+12345 (\ud808\udf45) */ 0xf0, 0x92, 0x8d, 0x85 } ) ) { var block = new MemoryBlock(heapPtr, heap.Length); TestUtf8NullTerminatedFastCompare( block, 0, terminator_0, "F", 0, HonorCase, MemoryBlock.FastComparisonResult.Equal, 1 ); TestUtf8NullTerminatedFastCompare( block, 0, terminator_0, "f", 0, IgnoreCase, MemoryBlock.FastComparisonResult.Equal, 1 ); TestUtf8NullTerminatedFastCompare( block, 0, terminator_F, "", 0, IgnoreCase, MemoryBlock.FastComparisonResult.Equal, 0 ); TestUtf8NullTerminatedFastCompare( block, 0, terminator_F, "*", 1, IgnoreCase, MemoryBlock.FastComparisonResult.Equal, 1 ); TestUtf8NullTerminatedFastCompare( block, 0, terminator_0, "FF", 0, HonorCase, MemoryBlock.FastComparisonResult.TextStartsWithBytes, 1 ); TestUtf8NullTerminatedFastCompare( block, 0, terminator_0, "fF", 0, IgnoreCase, MemoryBlock.FastComparisonResult.TextStartsWithBytes, 1 ); TestUtf8NullTerminatedFastCompare( block, 0, terminator_0, "F\0", 0, HonorCase, MemoryBlock.FastComparisonResult.TextStartsWithBytes, 1 ); TestUtf8NullTerminatedFastCompare( block, 0, terminator_X, "F\0", 0, HonorCase, MemoryBlock.FastComparisonResult.TextStartsWithBytes, 1 ); TestUtf8NullTerminatedFastCompare( block, 2, terminator_0, "X", 0, HonorCase, MemoryBlock.FastComparisonResult.BytesStartWithText, 1 ); TestUtf8NullTerminatedFastCompare( block, 2, terminator_0, "x", 0, IgnoreCase, MemoryBlock.FastComparisonResult.BytesStartWithText, 1 ); TestUtf8NullTerminatedFastCompare( block, 2, terminator_x, "XY", 0, IgnoreCase, MemoryBlock.FastComparisonResult.BytesStartWithText, 2 ); TestUtf8NullTerminatedFastCompare( block, 3, terminator_0, "yZ", 0, IgnoreCase, MemoryBlock.FastComparisonResult.Unequal, 1 ); TestUtf8NullTerminatedFastCompare( block, 4, terminator_0, "a", 0, HonorCase, MemoryBlock.FastComparisonResult.Unequal, 0 ); TestUtf8NullTerminatedFastCompare( block, 4, terminator_0, "\ud808", 0, HonorCase, MemoryBlock.FastComparisonResult.Inconclusive, 0 ); TestUtf8NullTerminatedFastCompare( block, 4, terminator_0, "\ud808\udf45", 0, HonorCase, MemoryBlock.FastComparisonResult.Inconclusive, 0 ); } } private void TestUtf8NullTerminatedFastCompare( MemoryBlock block, int offset, char terminator, string comparand, int comparandOffset, bool ignoreCase, MemoryBlock.FastComparisonResult expectedResult, int expectedFirstDifferenceIndex ) { int actualFirstDifferenceIndex; var actualResult = block.Utf8NullTerminatedFastCompare( offset, comparand, comparandOffset, out actualFirstDifferenceIndex, terminator, ignoreCase ); Assert.Equal(expectedResult, actualResult); Assert.Equal(expectedFirstDifferenceIndex, actualFirstDifferenceIndex); } private unsafe void TestSearch(string heapValue, int offset, string[] values) { byte[] heap; fixed (byte* heapPtr = (heap = Encoding.UTF8.GetBytes(heapValue))) { int actual = new MemoryBlock(heapPtr, heap.Length).BinarySearch(values, offset); string heapSubstr = GetStringHeapValue(heapValue, offset); int expected = Array.BinarySearch(values, heapSubstr); Assert.Equal(expected, actual); } } [Fact] public void BinarySearch() { TestSearch("a\0", 0, new string[0]); TestSearch("a\0", 0, new[] { "b" }); TestSearch("b\0", 0, new[] { "b" }); TestSearch("c\0", 0, new[] { "b" }); TestSearch("a\0", 0, new[] { "b", "d" }); TestSearch("b\0", 0, new[] { "b", "d" }); TestSearch("c\0", 0, new[] { "b", "d" }); TestSearch("d\0", 0, new[] { "b", "d" }); TestSearch("e\0", 0, new[] { "b", "d" }); TestSearch("a\0", 0, new[] { "b", "d", "f" }); TestSearch("b\0", 0, new[] { "b", "d", "f" }); TestSearch("c\0", 0, new[] { "b", "d", "f" }); TestSearch("d\0", 0, new[] { "b", "d", "f" }); TestSearch("e\0", 0, new[] { "b", "d", "f" }); TestSearch("f\0", 0, new[] { "b", "d", "f" }); TestSearch("g\0", 0, new[] { "b", "d", "f" }); TestSearch("a\0", 0, new[] { "b", "d", "f", "m" }); TestSearch("b\0", 0, new[] { "b", "d", "f", "m" }); TestSearch("c\0", 0, new[] { "b", "d", "f", "m" }); TestSearch("d\0", 0, new[] { "b", "d", "f", "m" }); TestSearch("e\0", 0, new[] { "b", "d", "f", "m" }); TestSearch("f\0", 0, new[] { "b", "d", "f", "m" }); TestSearch("g\0", 0, new[] { "b", "d", "f", "m" }); TestSearch("m\0", 0, new[] { "b", "d", "f", "m" }); TestSearch("n\0", 0, new[] { "b", "d", "f", "m" }); TestSearch("z\0", 0, new[] { "b", "d", "f", "m" }); } [Fact] public unsafe void BuildPtrTable_SmallRefs() { const int rowSize = 4; const int secondColumnOffset = 2; var table = new byte[] { 0xAA, 0xAA, 0x05, 0x00, 0xBB, 0xBB, 0x04, 0x00, 0xCC, 0xCC, 0x02, 0x01, 0xDD, 0xDD, 0x02, 0x00, 0xEE, 0xEE, 0x01, 0x01, }; int rowCount = table.Length / rowSize; fixed (byte* tablePtr = table) { var block = new MemoryBlock(tablePtr, table.Length); Assert.Equal(0x0004, block.PeekReference(6, smallRefSize: true)); var actual = block.BuildPtrTable( rowCount, rowSize, secondColumnOffset, isReferenceSmall: true ); var expected = new int[] { 4, 2, 1, 5, 3 }; Assert.Equal(expected, actual); } } [Fact] public unsafe void BuildPtrTable_LargeRefs() { const int rowSize = 6; const int secondColumnOffset = 2; var table = new byte[] { 0xAA, 0xAA, 0x10, 0x00, 0x05, 0x00, 0xBB, 0xBB, 0x10, 0x00, 0x04, 0x00, 0xCC, 0xCC, 0x10, 0x00, 0x02, 0x01, 0xDD, 0xDD, 0x10, 0x00, 0x02, 0x00, 0xEE, 0xEE, 0x10, 0x00, 0x01, 0x01, }; int rowCount = table.Length / rowSize; fixed (byte* tablePtr = table) { var block = new MemoryBlock(tablePtr, table.Length); Assert.Equal(0x00040010, block.PeekReference(8, smallRefSize: false)); var actual = block.BuildPtrTable( rowCount, rowSize, secondColumnOffset, isReferenceSmall: false ); var expected = new int[] { 4, 2, 1, 5, 3 }; Assert.Equal(expected, actual); } } [Fact] public unsafe void PeekReference() { var table = new byte[] { 0xff, 0xff, 0xff, 0x00, // offset 0 0xff, 0xff, 0xff, 0x01, // offset 4 0xff, 0xff, 0xff, 0x1f, // offset 8 0xff, 0xff, 0xff, 0x2f, // offset 12 0xff, 0xff, 0xff, 0xff, // offset 16 }; fixed (byte* tablePtr = table) { var block = new MemoryBlock(tablePtr, table.Length); Assert.Equal(0x0000ffff, block.PeekReference(0, smallRefSize: true)); Assert.Equal(0x0000ffff, block.PeekHeapReference(0, smallRefSize: true)); Assert.Equal(0x0000ffffu, block.PeekReferenceUnchecked(0, smallRefSize: true)); Assert.Equal(0x00ffffff, block.PeekReference(0, smallRefSize: false)); Assert.Throws<BadImageFormatException>( () => block.PeekReference(4, smallRefSize: false) ); Assert.Throws<BadImageFormatException>( () => block.PeekReference(16, smallRefSize: false) ); Assert.Equal(0x1fffffff, block.PeekHeapReference(8, smallRefSize: false)); Assert.Throws<BadImageFormatException>( () => block.PeekHeapReference(12, smallRefSize: false) ); Assert.Throws<BadImageFormatException>( () => block.PeekHeapReference(16, smallRefSize: false) ); Assert.Equal(0x01ffffffu, block.PeekReferenceUnchecked(4, smallRefSize: false)); Assert.Equal(0x1fffffffu, block.PeekReferenceUnchecked(8, smallRefSize: false)); Assert.Equal(0x2fffffffu, block.PeekReferenceUnchecked(12, smallRefSize: false)); Assert.Equal(0xffffffffu, block.PeekReferenceUnchecked(16, smallRefSize: false)); } } } }
34.471264
111
0.421565
[ "MIT" ]
belav/runtime
src/libraries/System.Reflection.Metadata/tests/Utilities/MemoryBlockTests.cs
32,989
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Ef_GoldBehavior : MonoBehaviour { private int carryGold; private Transform goldCollecter; public int CarryGold { get { return carryGold; } set { carryGold = value; } } void Start() { goldCollecter = GameObject.Find("Canvas_90/GoldCollecter").GetComponent<Transform>(); } void Update() { transform.position = Vector3.MoveTowards(transform.position, goldCollecter.transform.position, 20 * Time.deltaTime); } }
19.333333
124
0.615987
[ "MIT" ]
shien091090/FishMaster
Assets/Scnipts/Effect/Ef_GoldBehavior.cs
640
C#
using System; using System.Windows.Forms; namespace EmployeeRegister { // Generated when form is created, it is public, partial which means there is another file with // additional code, and it inherits from a class called form which is part of .NET public partial class FrmEmployeeDetails : Form { // Member variable of type ClsEmloyeeDetails, this is a reference variables and allocate only // enough memory to hold an address to an object // This must be protected so that the inherited forms can access it protected ClsEmployeeDetails _EmployeeDetails; // Constructor public FrmEmployeeDetails() { InitializeComponent(); } // Execute when we want this form to display itself, we now have show dialog to return a boolean rather than a dialog result due to the classes now call show dialog, // If we continue to use dialog result in our classes then we would need a refernce to window forms which is called talking to strangers and is poor style public bool ShowDialog(ClsEmployeeDetails prEmployeeDetails) { // Storing the parameter value in our member variable _EmployeeDetails _EmployeeDetails = prEmployeeDetails; // Calling the update display method UpdateDisplay(); // Default method, this will return OK or cancel depends on what the user clicks on // This now returns a bool true/false return ShowDialog() == DialogResult.OK; } // Updates the text boxes with the employee details // Must be protected and virtual so that the inherited forms can override them protected virtual void UpdateDisplay() { TxtEmployeeID.Text = _EmployeeDetails.ID; TxtEmployeeName.Text = _EmployeeDetails.Name; DtpEmployeeDOB.Value = _EmployeeDetails.DOB; TxtEmployeeAddress.Text = _EmployeeDetails.Address; TxtEmployeePhoneNumber.Text = _EmployeeDetails.PhoneNo; TxtEmployeeEmail.Text = _EmployeeDetails.Email; TxtEmployeeEmergencyContactPerson.Text = _EmployeeDetails.EmergencyContactPerson; TxtEmployeeEmergencyContactNumber.Text = _EmployeeDetails.EmergencyContactNo; TxtEmployeeEmergencyRelationship.Text = _EmployeeDetails.EmergencyContactRelationship; DtpEmployeeStartDate.Value = _EmployeeDetails.StartDate; TxtEmployeePosition.Text = _EmployeeDetails.Position; TxtEmployeeLocation.Text = _EmployeeDetails.Location; TxtEmployeeWorkNo.Text = _EmployeeDetails.WorkNo; TxtEmployeeWorkEmail.Text = _EmployeeDetails.WorkEmail; TxtEmployeeID.Enabled = String.IsNullOrEmpty(_EmployeeDetails.ID); } // Assigning the contents of the textboxes on the form to the employee properties when the OK button is clicked private void BtnOK_Click(object sender, EventArgs e) { // If the ID textbox is enabled then we are adding a new employee so we need to check if the ID already exists if (TxtEmployeeID.Enabled && ClsEmployeeList.EmployeeList.ContainsKey(TxtEmployeeID.Text)) { // If it does exist then we display a message MessageBox.Show("Employee with that ID already exists", "Duplicate ID"); } else { // Calling push data method PushData(); DialogResult = DialogResult.OK; } } // Push data method, this is so the form can work with inherited forms // Must be protected and virtual so that the inherited forms can override them protected virtual void PushData() { _EmployeeDetails.ID = TxtEmployeeID.Text; _EmployeeDetails.Name = TxtEmployeeName.Text; _EmployeeDetails.DOB = DtpEmployeeDOB.Value; _EmployeeDetails.Address = TxtEmployeeAddress.Text; _EmployeeDetails.PhoneNo = TxtEmployeePhoneNumber.Text; _EmployeeDetails.Email = TxtEmployeeEmail.Text; _EmployeeDetails.EmergencyContactPerson = TxtEmployeeEmergencyContactPerson.Text; _EmployeeDetails.EmergencyContactNo = TxtEmployeeEmergencyContactNumber.Text; _EmployeeDetails.EmergencyContactRelationship = TxtEmployeeEmergencyRelationship.Text; _EmployeeDetails.StartDate = DtpEmployeeStartDate.Value; _EmployeeDetails.Position = TxtEmployeePosition.Text; _EmployeeDetails.Location = TxtEmployeeLocation.Text; _EmployeeDetails.WorkNo = TxtEmployeeWorkNo.Text; _EmployeeDetails.WorkEmail = TxtEmployeeWorkEmail.Text; } // Cancel button private void BtnCancel_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; } } }
51.212121
174
0.662327
[ "CC0-1.0" ]
bob-mccone/Employee-Register
EmployeeRegister/FrmEmployeeDetails.cs
5,072
C#
using Minimundo.Domain.Entities.Authentication; using Minimundo.Domain.Interfaces.Repositories; using Minimundo.Domain.Interfaces.Services; namespace Minimundo.Service.Service { public class CredencialService : BaseService<credencial>, ICredencialService { private readonly ICredencialRepository _repository; public CredencialService(ICredencialRepository repository) { _repository = repository; } } }
28.75
80
0.745652
[ "MIT" ]
Gerjunior/MinimundoV2
Minimundo.Service/Service/CredencialService.cs
462
C#
// Copyright 2018 by JCoder58. See License.txt for license // Auto-generated --- Do not modify. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UE4.Core; using UE4.CoreUObject; using UE4.CoreUObject.Native; using UE4.InputCore; using UE4.Native; namespace UE4.AIModule { ///<summary>EAILock Source</summary> public enum EAILockSource { Animation = 0x00000000, Logic = 0x00000001, Script = 0x00000002, Gameplay = 0x00000003, MAX = 0x00000004 } }
24.863636
59
0.696527
[ "MIT" ]
UE4DotNet/Plugin
DotNet/DotNet/UE4/Generated/AIModule/EAILockSource.cs
547
C#
// ------------------------------------------------------------------------------------------------- // <copyright file="ReqIFHeaderTestFixture.cs" company="RHEA System S.A."> // // Copyright 2017 RHEA System S.A. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // </copyright> // ------------------------------------------------------------------------------------------------ namespace ReqIFSharp.Tests { using System; using System.IO; using System.Threading; using System.Xml; using NUnit.Framework; using System.Runtime.Serialization; /// <summary> /// Suite of tests for the <see cref="ReqIFHeader"/> class /// </summary> [TestFixture] public class ReqIFHeaderTestFixture { [Test] public void Verify_that_ReadXmlAsync_throws_exception_when_cancelled() { var reqifPath = Path.Combine(TestContext.CurrentContext.TestDirectory, "TestData", "Datatype-Demo.reqif"); var cts = new CancellationTokenSource(); cts.Cancel(); using var fileStream = File.OpenRead(reqifPath); using var xmlReader = XmlReader.Create(fileStream, new XmlReaderSettings { Async = true }); var reqIfHeader = new ReqIFHeader(); Assert.That( async () => await reqIfHeader.ReadXmlAsync(xmlReader, cts.Token), Throws.Exception.TypeOf<OperationCanceledException>()); } [Test] public void Verify_That_WriteXmlAsync_throws_exception_when_cancelled() { using var memoryStream = new MemoryStream(); using var writer = XmlWriter.Create(memoryStream, new XmlWriterSettings { Indent = true }); var reqIfHeader = new ReqIFHeader(); var cts = new CancellationTokenSource(); cts.Cancel(); Assert.That( async () => await reqIfHeader.WriteXmlAsync(writer, cts.Token), Throws.Exception.TypeOf<OperationCanceledException>()); } } }
37.070423
119
0.581307
[ "Apache-2.0" ]
RHEAGROUP/reqifsharp
ReqIFSharp.Tests/ReqIFHeaderTestFixture.cs
2,634
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.AppConfiguration.Latest.Outputs { [OutputType] public sealed class UserIdentityResponse { /// <summary> /// The client ID of the user-assigned identity. /// </summary> public readonly string ClientId; /// <summary> /// The principal ID of the user-assigned identity. /// </summary> public readonly string PrincipalId; [OutputConstructor] private UserIdentityResponse( string clientId, string principalId) { ClientId = clientId; PrincipalId = principalId; } } }
26.444444
81
0.632353
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/AppConfiguration/Latest/Outputs/UserIdentityResponse.cs
952
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 ViqetDesktop.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", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public 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)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ViqetDesktop.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)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to About. /// </summary> public static string About { get { return ResourceManager.GetString("About", resourceCulture); } } /// <summary> /// Looks up a localized string similar to VQEG Image Quality Evaluation Tool (VIQET) is a free and open source tool for evaluating quality of consumer photos. VIQET is easy to use and based on objective no-reference image quality evaluation methods. More information about VQEG projects is available at www.vqeg.org. /// </summary> public static string AboutPageText { get { return ResourceManager.GetString("AboutPageText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Analyze. /// </summary> public static string Analyze { get { return ResourceManager.GetString("Analyze", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Download our Android app and enjoy instant analysis of your photos without the hassle of syncing your photos to your PC!. /// </summary> public static string AndroidIsAvailableToo { get { return ResourceManager.GetString("AndroidIsAvailableToo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Back. /// </summary> public static string Back { get { return ResourceManager.GetString("Back", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Back to home page. /// </summary> public static string BackToMainScreenWarning { get { return ResourceManager.GetString("BackToMainScreenWarning", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 1. /// </summary> public static string BreadCrumb1 { get { return ResourceManager.GetString("BreadCrumb1", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 2. /// </summary> public static string BreadCrumb2 { get { return ResourceManager.GetString("BreadCrumb2", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 3. /// </summary> public static string BreadCrumb3 { get { return ResourceManager.GetString("BreadCrumb3", resourceCulture); } } /// <summary> /// Looks up a localized string similar to 4. /// </summary> public static string BreadCrumb4 { get { return ResourceManager.GetString("BreadCrumb4", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Home. /// </summary> public static string BreadCrumbTitle1 { get { return ResourceManager.GetString("BreadCrumbTitle1", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Import Photos. /// </summary> public static string BreadCrumbTitle2 { get { return ResourceManager.GetString("BreadCrumbTitle2", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Processing. /// </summary> public static string BreadCrumbTitle3 { get { return ResourceManager.GetString("BreadCrumbTitle3", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Results. /// </summary> public static string BreadCrumbTitle4 { get { return ResourceManager.GetString("BreadCrumbTitle4", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Cancel. /// </summary> public static string Cancel { get { return ResourceManager.GetString("Cancel", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Clear All. /// </summary> public static string ClearAll { get { return ResourceManager.GetString("ClearAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Click here to read more. /// </summary> public static string ClickToReadMore { get { return ResourceManager.GetString("ClickToReadMore", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Close. /// </summary> public static string Close { get { return ResourceManager.GetString("Close", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Collapse Visualization. /// </summary> public static string CollapsePhotos { get { return ResourceManager.GetString("CollapsePhotos", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Enter Test Name Here. /// </summary> public static string DefaultTestName { get { return ResourceManager.GetString("DefaultTestName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Delete Multiple Items. /// </summary> public static string DeleteMultipleItems { get { return ResourceManager.GetString("DeleteMultipleItems", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Are you sure you want to remove these photos from the test?. /// </summary> public static string DeletePhotosConfirmationMessage { get { return ResourceManager.GetString("DeletePhotosConfirmationMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Delete. /// </summary> public static string DeleteSelected { get { return ResourceManager.GetString("DeleteSelected", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Are you sure you want to permanently delete these tests?. /// </summary> public static string DeleteTestsConfirmationMessage { get { return ResourceManager.GetString("DeleteTestsConfirmationMessage", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Detailed Results. /// </summary> public static string DetailedResults { get { return ResourceManager.GetString("DetailedResults", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Did you know?. /// </summary> public static string DidYouKnow { get { return ResourceManager.GetString("DidYouKnow", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Display individual photo MOS. /// </summary> public static string DisplayPhotoMOS { get { return ResourceManager.GetString("DisplayPhotoMOS", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Edit Current Test. /// </summary> public static string EditCurrentTest { get { return ResourceManager.GetString("EditCurrentTest", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Edit. /// </summary> public static string EditSelected { get { return ResourceManager.GetString("EditSelected", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Check for minimum number of photos. /// </summary> public static string EnforceMethodology { get { return ResourceManager.GetString("EnforceMethodology", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Error. /// </summary> public static string Error { get { return ResourceManager.GetString("Error", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Exception Details:. /// </summary> public static string ExceptionDetails { get { return ResourceManager.GetString("ExceptionDetails", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Are you sure you want to go back to the main screen? Any changes made to this test will be lost. /// </summary> public static string ExitSelectPhotosWarning { get { return ResourceManager.GetString("ExitSelectPhotosWarning", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Expand Visualization. /// </summary> public static string ExpandPhotos { get { return ResourceManager.GetString("ExpandPhotos", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Export as. /// </summary> public static string ExportAsLabel { get { return ResourceManager.GetString("ExportAsLabel", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Export as CSV. /// </summary> public static string ExportCSV { get { return ResourceManager.GetString("ExportCSV", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Export as PDF. /// </summary> public static string ExportPDF { get { return ResourceManager.GetString("ExportPDF", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Export as XML. /// </summary> public static string ExportXML { get { return ResourceManager.GetString("ExportXML", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Finished. /// </summary> public static string Finished { get { return ResourceManager.GetString("Finished", resourceCulture); } } /// <summary> /// Looks up a localized string similar to VIQET was not able to identify flat regions in some test photos. This may be because those test photos do not follow VIQET methodology or might have high noise. . /// </summary> public static string FlatRegionError { get { return ResourceManager.GetString("FlatRegionError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Guidelines. /// </summary> public static string GeneralGuidelines { get { return ResourceManager.GetString("GeneralGuidelines", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Help. /// </summary> public static string Help { get { return ResourceManager.GetString("Help", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Home. /// </summary> public static string HomeButton { get { return ResourceManager.GetString("HomeButton", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Images. /// </summary> public static string ImageDetails { get { return ResourceManager.GetString("ImageDetails", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Import More Photos. /// </summary> public static string ImportMorePhotos { get { return ResourceManager.GetString("ImportMorePhotos", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Import Photos. /// </summary> public static string ImportPhotos { get { return ResourceManager.GetString("ImportPhotos", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Please enter a test name. /// </summary> public static string IncorrectName { get { return ResourceManager.GetString("IncorrectName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Methodology not followed. /// </summary> public static string MethodologyNotFollowed { get { return ResourceManager.GetString("MethodologyNotFollowed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to More Info. /// </summary> public static string MoreInfo { get { return ResourceManager.GetString("MoreInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to MOS. /// </summary> public static string MOS { get { return ResourceManager.GetString("MOS", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Mean Opinion Scores. /// </summary> public static string MOSAbbr { get { return ResourceManager.GetString("MOSAbbr", resourceCulture); } } /// <summary> /// Looks up a localized string similar to N/A. /// </summary> public static string NA { get { return ResourceManager.GetString("NA", resourceCulture); } } /// <summary> /// Looks up a localized string similar to New Test. /// </summary> public static string NewTest { get { return ResourceManager.GetString("NewTest", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Next. /// </summary> public static string Next { get { return ResourceManager.GetString("Next", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Please add photos. /// </summary> public static string NoPhotosSelected { get { return ResourceManager.GetString("NoPhotosSelected", resourceCulture); } } /// <summary> /// Looks up a localized string similar to At least 5 photos in each input category are required to calculate overall scores. /// </summary> public static string NoteAboutMinPhotos { get { return ResourceManager.GetString("NoteAboutMinPhotos", resourceCulture); } } /// <summary> /// Looks up a localized string similar to At least 5 photos in each input category are required to calculate category scores. /// </summary> public static string NoteAboutMinPhotosCategory { get { return ResourceManager.GetString("NoteAboutMinPhotosCategory", resourceCulture); } } /// <summary> /// Looks up a localized string similar to of. /// </summary> public static string Of { get { return ResourceManager.GetString("Of", resourceCulture); } } /// <summary> /// Looks up a localized string similar to OK. /// </summary> public static string OK { get { return ResourceManager.GetString("OK", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Open. /// </summary> public static string OpenSelected { get { return ResourceManager.GetString("OpenSelected", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Category. /// </summary> public static string OutputCategory { get { return ResourceManager.GetString("OutputCategory", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Categories. /// </summary> public static string OverallInfo { get { return ResourceManager.GetString("OverallInfo", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Overall. /// </summary> public static string OverallMOS { get { return ResourceManager.GetString("OverallMOS", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Photo Count. /// </summary> public static string PhotoCount { get { return ResourceManager.GetString("PhotoCount", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Error: Backend DLL threw an exception while processing photo. /// </summary> public static string PhotoProcessingError { get { return ResourceManager.GetString("PhotoProcessingError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Prev. /// </summary> public static string Prev { get { return ResourceManager.GetString("Prev", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Processing Photo. /// </summary> public static string ProcessingPhoto { get { return ResourceManager.GetString("ProcessingPhoto", resourceCulture); } } /// <summary> /// Looks up a localized string similar to VQEG Image Quality Evaluation Tool (VIQET). /// </summary> public static string ProductDescription { get { return ResourceManager.GetString("ProductDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to VIQET. /// </summary> public static string ProductName { get { return ResourceManager.GetString("ProductName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Desktop. /// </summary> public static string ProductType { get { return ResourceManager.GetString("ProductType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Pro Mode. /// </summary> public static string ProMode { get { return ResourceManager.GetString("ProMode", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Error: Result has been deleted. /// </summary> public static string ResultDeletedError { get { return ResourceManager.GetString("ResultDeletedError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to The result you clicked has been deleted by another instance of the application. Click OK to refresh this window.. /// </summary> public static string ResultDoesntExistError { get { return ResourceManager.GetString("ResultDoesntExistError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Estimated Mean Opinion Scores (MOS) +/- Standard Error. /// </summary> public static string ResultPageOverallHeader { get { return ResourceManager.GetString("ResultPageOverallHeader", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Save. /// </summary> public static string SaveSettings { get { return ResourceManager.GetString("SaveSettings", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Settings. /// </summary> public static string Settings { get { return ResourceManager.GetString("Settings", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Stop. /// </summary> public static string Stop { get { return ResourceManager.GetString("Stop", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Stopping. /// </summary> public static string Stopping { get { return ResourceManager.GetString("Stopping", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Submit Score. /// </summary> public static string SubmitScore { get { return ResourceManager.GetString("SubmitScore", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Test Name. /// </summary> public static string TestName { get { return ResourceManager.GetString("TestName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Version. /// </summary> public static string Version { get { return ResourceManager.GetString("Version", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Error: Backend DLL threw an exception while fetching version info. /// </summary> public static string VersionFetchError { get { return ResourceManager.GetString("VersionFetchError", resourceCulture); } } /// <summary> /// Looks up a localized string similar to . /// </summary> public static string VersionName { get { return ResourceManager.GetString("VersionName", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Visualization. /// </summary> public static string Visualization { get { return ResourceManager.GetString("Visualization", resourceCulture); } } } }
34.404878
327
0.528676
[ "EPL-1.0" ]
VIQET/VIQET-Desktop
VIQET-UI/ViqetDesktop/Properties/Resources.Designer.cs
28,214
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.Concurrent; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Text; using System.Text.RegularExpressions; using Windows.UI.Text; using Microsoft.UI.Xaml; namespace UnitTests.Markdown { /// <summary> /// The base class for our unit tests. /// </summary> public abstract class TestBase { /// <summary> /// Removes a column of whitespace from the start of each line. /// </summary> /// <param name="input"> The text to process. </param> /// <returns> The input text, but with some whitespace removed. </returns> protected static string CollapseWhitespace(string input) { // Count the minimum number of spaces. int spacesToRemove = int.MaxValue; foreach (Match match in Regex.Matches(input, @"^[ ]*(?=[^\s])", RegexOptions.Multiline)) spacesToRemove = Math.Min(spacesToRemove, match.Length); if (spacesToRemove < int.MaxValue) { // Remove that many spaces from every line, and convert other spaces to tabs. input = input.Replace("\r\n" + new string(' ', spacesToRemove), "\r\n"); } // Remove first blank line. if (input.StartsWith(Environment.NewLine)) input = input.Substring(Environment.NewLine.Length); return input; } private static ConcurrentDictionary<Type, Dictionary<string, object>> defaultValueCache = new ConcurrentDictionary<Type, Dictionary<string, object>>(); /// <summary> /// Serializes the given object. /// </summary> /// <param name="result"> The StringBuilder to output to. </param> /// <param name="obj"> The object to serialize. </param> /// <param name="indentLevel"> The indent level. </param> protected static void SerializeElement(StringBuilder result, object obj, int indentLevel) { var type = obj.GetType(); if (result.Length > 0) { result.Append("\r\n"); for (int i = 0; i < indentLevel; i++) result.Append(" "); } result.Append(type.Name); // Look up default values using the static dependency properties. Dictionary<string, object> defaultValues; if (!defaultValueCache.TryGetValue(type, out defaultValues)) { defaultValues = new Dictionary<string, object>(); Type baseType = type; while (baseType != null) { foreach (var propertyInfo in baseType.GetProperties(BindingFlags.Public | BindingFlags.Static)) { if (propertyInfo.Name.EndsWith("Property") && propertyInfo.PropertyType == typeof(DependencyProperty)) { var dp = (DependencyProperty)propertyInfo.GetValue(obj); defaultValues.Add(propertyInfo.Name.Substring(0, propertyInfo.Name.Length - "Property".Length), dp.GetMetadata(type).DefaultValue); } } baseType = baseType.GetTypeInfo().BaseType; } // Override some defaults. if (defaultValues.ContainsKey("FontSize")) defaultValues["FontSize"] = 15.0; if (defaultValues.ContainsKey("TextAlignment")) defaultValues["TextAlignment"] = TextAlignment.Left; if (defaultValues.ContainsKey("Margin")) defaultValues["Margin"] = new Thickness(0, 12, 0, 0); // Cache it. defaultValueCache.TryAdd(type, defaultValues); } // Now look up all the instance properties. var complexProperties = new List<PropertyInfo>(); bool first = true; foreach (var propertyInfo in type.GetProperties(BindingFlags.Public | BindingFlags.Instance).OrderBy(pi => pi.Name)) { // Only read-write properties... if (propertyInfo.CanRead == false || propertyInfo.CanWrite == false) { // ...but read-only enumerables are okay. if (!typeof(IEnumerable<object>).IsAssignableFrom(propertyInfo.PropertyType)) continue; } object value = propertyInfo.GetValue(obj); // Check if it's the same as the default value. object defaultValue; if (defaultValues.TryGetValue(propertyInfo.Name, out defaultValue) && object.Equals(value, defaultValue)) continue; if (value == null) { result.AppendFormat("{0} {1}: null", first ? "" : ",", propertyInfo.Name); first = false; } else if (value is int || value is double || value is bool || value is byte || value is Enum) { result.AppendFormat("{0} {1}: {2}", first ? "" : ",", propertyInfo.Name, value.ToString()); first = false; } else if (value is string || value is Thickness) { result.AppendFormat("{0} {1}: '{2}'", first ? "" : ",", propertyInfo.Name, value.ToString()); first = false; } else if (value is FontWeight) { result.AppendFormat("{0} {1}: {2}", first ? "" : ",", propertyInfo.Name, ((FontWeight)value).Weight); first = false; } else { // Do these later. complexProperties.Add(propertyInfo); } } // Do the complex properties that we skipped before. foreach (var propertyInfo in complexProperties) { object value = propertyInfo.GetValue(obj); if (typeof(IEnumerable<object>).IsAssignableFrom(propertyInfo.PropertyType)) { // Enumerable. foreach (var child in (IEnumerable<object>)propertyInfo.GetValue(obj)) SerializeElement(result, child, indentLevel + 1); } else { // Complex type. SerializeElement(result, value, indentLevel + 1); } } } } }
42.802469
159
0.527113
[ "MIT" ]
ehtick/Uno.WindowsCommunityToolkit
UnitTests/UnitTests.UWP/Markdown/TestBase.cs
6,934
C#
namespace Husky.TaskRunner; public enum ArgumentTypes { Static, CustomArgument, File, StagedFile, CustomVariable }
11.909091
27
0.725191
[ "MIT" ]
Xemrox/Husky.Net
src/Husky/TaskRunner/ArgumentTypes.cs
131
C#
namespace DataManager.Models.CarraraSQL { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.Spatial; public partial class ApplicationError { public int ApplicationErrorID { get; set; } public string Message { get; set; } public string StackTrace { get; set; } [StringLength(50)] public string Username { get; set; } public DateTime? Date { get; set; } public string Source { get; set; } } }
24.2
55
0.657851
[ "Apache-2.0" ]
kazunetakeda25/data-manager
DataManager/Models/CarraraSQL/ApplicationError.cs
605
C#
namespace HireAProfessional.Services.Data { using System; using System.Collections.Generic; using System.Text; using HireAProfessional.Web.ViewModels.Countries; public interface ICountriesService { IEnumerable<T> GetAllCountries<T>(); } }
19.857143
53
0.708633
[ "MIT" ]
TodorNedkovski/HireAProfessional
src/Services/HireAProfessional.Services.Data/ICountriesService.cs
280
C#
namespace Spect.Net.SpectrumEmu.Abstraction.Configuration { /// <summary> /// This interface defines the configuration data for the ROM /// </summary> public interface IRomConfiguration: IDeviceConfiguration { /// <summary> /// The number of ROM banks /// </summary> int NumberOfRoms { get; } /// <summary> /// The name of the ROM file /// </summary> string RomName { get; } /// <summary> /// The index of the Spectrum 48K BASIC ROM /// </summary> int Spectrum48RomIndex { get; } } }
26.347826
65
0.556106
[ "MIT" ]
Dotneteer/spectnetide
Core/Spect.Net.SpectrumEmu/Abstraction/Configuration/IRomConfiguration.cs
608
C#
using System; using System.Globalization; using System.Windows; using System.Windows.Data; namespace TumblThree.Presentation.Converters { public class NullToVisibilityConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { bool invert = ConverterHelper.IsParameterSet("invert", parameter); if (invert) { return value == null ? Visibility.Visible : Visibility.Collapsed; } return value != null ? Visibility.Visible : Visibility.Collapsed; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) => throw new NotSupportedException(); } }
32.083333
141
0.672727
[ "Apache-2.0", "MIT" ]
Grukz/TumblThree
src/TumblThree/TumblThree.Presentation/Converters/NullToVisibilityConverter.cs
772
C#
using Newtonsoft.Json; using System; namespace Stripe { public class StripeEventListOptions { [JsonProperty("type")] public string Type { get; set; } [JsonProperty("created")] public StripeDateFilter Created { get; set; } } }
17.285714
47
0.702479
[ "Apache-2.0" ]
iATN/stripe.net
src/Stripe/Services/Events/StripeEventListOptions.cs
244
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SMLHelperExamples")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SMLHelperExamples")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("1862aec1-34f6-48e8-a2e9-5cdcf1b140f3")] // 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("2.1.0.0")] [assembly: AssemblyVersion("2.1.0.0")] [assembly: AssemblyFileVersion("2.1.0.0")]
38.971429
84
0.747067
[ "MIT" ]
Metious/MrPurple6411-Subnautica-Mods
CustomHullPlates/Properties/AssemblyInfo.cs
1,367
C#
using Library; using LiteDB; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; using System.Timers; namespace Jira_Monitor { public partial class Service1 : ServiceBase { Timer timer = new Timer(); string LocalDB = string.Empty; public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { LocalDB = $@"{Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory)}\Local.db"; timer.Interval = Properties.Settings.Default.Tempo; timer.Elapsed += new ElapsedEventHandler(this.OnTimer); timer.Start(); } private async void OnTimer(object sender, ElapsedEventArgs e) { await Monitor(); } private async Task Monitor() { Monitor monitor = new Monitor { UserName = Properties.Settings.Default.Username, Password = Properties.Settings.Default.Password }; try { using (var db = new LiteDatabase($@"Filename={LocalDB}; Connection=shared")) { var SyncFileCollection = db.GetCollection<Alerta>(); var alertas = SyncFileCollection.FindAll().ToList(); await monitor.Notify(alertas); db.DropCollection(nameof(Alerta)); SyncFileCollection.InsertBulk(alertas); } } catch (AggregateException ex) { throw ex.Flatten(); } catch (Exception) { throw; } } protected override void OnStop() { timer.Stop(); } } }
21.625
99
0.633526
[ "MIT" ]
douglasilva/jira-monitor
Jira-Monitor/Service1.cs
1,732
C#
using GWebsite.AbpZeroTemplate.Application.Share.AssetCategories.Dto; namespace GWebsite.AbpZeroTemplate.Application.Share.AssetCategories.Dto { public class UpdateAssetCategoryInput : CreateAssetCategoryInput { } }
25.555556
72
0.813043
[ "Apache-2.0" ]
NTD98/ASP_ANGULAR
asset-management-api/src/GWebsite.AbpZeroTemplate.Application.Share/AssetCategories/Dto/UpdateAssetCategoryInput.cs
232
C#
namespace MyApp.Tasks { #region Using Directives using MyApp.Domain; using MyApp.Domain.Contracts.Tasks; using MyApp.Infrastructure; #endregion public class PersonTasks : IPersonTasks { public void Process(Person person) { new PersonRepository().Save(person); } } }
18.722222
48
0.626113
[ "BSD-3-Clause" ]
5eba51ian/Sharp-Architecture
Artefacts/package-samples/sample-mvc-app/files/MyApp/MyApp.Tasks/PersonTasks.cs
339
C#
using Avalonia.Media; using AvalonStudio.Languages; using AvalonStudio.MVVM; namespace AvalonStudio.Controls.Standard.CodeEditor.Completion { public class CompletionDataViewModel : ViewModel<CodeCompletionData> { public CompletionDataViewModel(CodeCompletionData model) : base(model) { Overloads = 0; Icon = model.Kind.ToDrawingGroup(); } public int Overloads { get; set; } public string OverloadText { get { if (Overloads == 0) { return string.Empty; } else if (Overloads == 1) { return $"(+ {Overloads} overload)"; } else { return $"(+ {Overloads} overloads)"; } } } public string Title { get { return Model.DisplayText; } } public int Priority { get { return Model.Priority; } } public string Kind { get { return Model.Kind.ToString(); } } public DrawingGroup Icon { get; private set; } public string Hint { get { return Model?.DisplayText; } } public string Comment { get { return Model?.BriefComment; } } } }
22.546875
78
0.465696
[ "MIT" ]
juanfranblanco/AvalonStudio
AvalonStudio/AvalonStudio.Controls.Standard/CodeEditor/Completion/CompletionDataViewModel.cs
1,443
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 NextPlan.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
34.290323
151
0.580433
[ "MIT" ]
add1ct3d/BruteEth
NextPlan/Properties/Settings.Designer.cs
1,065
C#
//------------------------------------------------------------------------------ // 此代码版权(除特别声明或在RRQMCore.XREF命名空间的代码)归作者本人若汝棋茗所有 // 源代码使用协议遵循本仓库的开源协议及附加协议,若本仓库没有设置,则按MIT开源协议授权 // CSDN博客:https://blog.csdn.net/qq_40374647 // 哔哩哔哩视频:https://space.bilibili.com/94253567 // Gitee源代码仓库:https://gitee.com/RRQM_Home // Github源代码仓库:https://github.com/RRQM // 交流QQ群:234762506 // 感谢您的下载和使用 //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ #region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion License using System; using System.Collections.Generic; #if HAVE_BIG_INTEGER using System.Numerics; #endif using RRQMCore.XREF.Newtonsoft.Json.Utilities; using System.Globalization; #if !HAVE_LINQ using RRQMCore.XREF.Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace RRQMCore.XREF.Newtonsoft.Json { /// <summary> /// Represents a writer that provides a fast, non-cached, forward-only way of generating JSON data. /// </summary> public abstract partial class JsonWriter : IDisposable { internal enum State { Start = 0, Property = 1, ObjectStart = 2, Object = 3, ArrayStart = 4, Array = 5, ConstructorStart = 6, Constructor = 7, Closed = 8, Error = 9 } // array that gives a new state based on the current state an the token being written private static readonly State[][] StateArray; internal static readonly State[][] StateArrayTempate = new[] { // Start PropertyName ObjectStart Object ArrayStart Array ConstructorStart Constructor Closed Error // /* None */new[] { State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, /* StartObject */new[] { State.ObjectStart, State.ObjectStart, State.Error, State.Error, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.ObjectStart, State.Error, State.Error }, /* StartArray */new[] { State.ArrayStart, State.ArrayStart, State.Error, State.Error, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.ArrayStart, State.Error, State.Error }, /* StartConstructor */new[] { State.ConstructorStart, State.ConstructorStart, State.Error, State.Error, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.ConstructorStart, State.Error, State.Error }, /* Property */new[] { State.Property, State.Error, State.Property, State.Property, State.Error, State.Error, State.Error, State.Error, State.Error, State.Error }, /* Comment */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, /* Raw */new[] { State.Start, State.Property, State.ObjectStart, State.Object, State.ArrayStart, State.Array, State.Constructor, State.Constructor, State.Error, State.Error }, /* Value (this will be copied) */new[] { State.Start, State.Object, State.Error, State.Error, State.Array, State.Array, State.Constructor, State.Constructor, State.Error, State.Error } }; internal static State[][] BuildStateArray() { List<State[]> allStates = StateArrayTempate.ToList(); State[] errorStates = StateArrayTempate[0]; State[] valueStates = StateArrayTempate[7]; EnumInfo enumValuesAndNames = EnumUtils.GetEnumValuesAndNames(typeof(JsonToken)); foreach (ulong valueToken in enumValuesAndNames.Values) { if (allStates.Count <= (int)valueToken) { JsonToken token = (JsonToken)valueToken; switch (token) { case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Null: case JsonToken.Undefined: case JsonToken.Date: case JsonToken.Bytes: allStates.Add(valueStates); break; default: allStates.Add(errorStates); break; } } } return allStates.ToArray(); } static JsonWriter() { StateArray = BuildStateArray(); } private List<JsonPosition> _stack; private JsonPosition _currentPosition; private State _currentState; private Formatting _formatting; /// <summary> /// Gets or sets a value indicating whether the destination should be closed when this writer is closed. /// </summary> /// <value> /// <c>true</c> to close the destination when this writer is closed; otherwise <c>false</c>. The default is <c>true</c>. /// </value> public bool CloseOutput { get; set; } /// <summary> /// Gets or sets a value indicating whether the JSON should be auto-completed when this writer is closed. /// </summary> /// <value> /// <c>true</c> to auto-complete the JSON when this writer is closed; otherwise <c>false</c>. The default is <c>true</c>. /// </value> public bool AutoCompleteOnClose { get; set; } /// <summary> /// Gets the top. /// </summary> /// <value>The top.</value> protected internal int Top { get { int depth = _stack?.Count ?? 0; if (Peek() != JsonContainerType.None) { depth++; } return depth; } } /// <summary> /// Gets the state of the writer. /// </summary> public WriteState WriteState { get { switch (_currentState) { case State.Error: return WriteState.Error; case State.Closed: return WriteState.Closed; case State.Object: case State.ObjectStart: return WriteState.Object; case State.Array: case State.ArrayStart: return WriteState.Array; case State.Constructor: case State.ConstructorStart: return WriteState.Constructor; case State.Property: return WriteState.Property; case State.Start: return WriteState.Start; default: throw JsonWriterException.Create(this, "Invalid state: " + _currentState, null); } } } internal string ContainerPath { get { if (_currentPosition.Type == JsonContainerType.None || _stack == null) { return string.Empty; } return JsonPosition.BuildPath(_stack, null); } } /// <summary> /// Gets the path of the writer. /// </summary> public string Path { get { if (_currentPosition.Type == JsonContainerType.None) { return string.Empty; } bool insideContainer = (_currentState != State.ArrayStart && _currentState != State.ConstructorStart && _currentState != State.ObjectStart); JsonPosition? current = insideContainer ? (JsonPosition?)_currentPosition : null; return JsonPosition.BuildPath(_stack, current); } } private DateFormatHandling _dateFormatHandling; private DateTimeZoneHandling _dateTimeZoneHandling; private StringEscapeHandling _stringEscapeHandling; private FloatFormatHandling _floatFormatHandling; private string _dateFormatString; private CultureInfo _culture; /// <summary> /// Gets or sets a value indicating how JSON text output should be formatted. /// </summary> public Formatting Formatting { get => _formatting; set { if (value < Formatting.None || value > Formatting.Indented) { throw new ArgumentOutOfRangeException(nameof(value)); } _formatting = value; } } /// <summary> /// Gets or sets how dates are written to JSON text. /// </summary> public DateFormatHandling DateFormatHandling { get => _dateFormatHandling; set { if (value < DateFormatHandling.IsoDateFormat || value > DateFormatHandling.MicrosoftDateFormat) { throw new ArgumentOutOfRangeException(nameof(value)); } _dateFormatHandling = value; } } /// <summary> /// Gets or sets how <see cref="DateTime"/> time zones are handled when writing JSON text. /// </summary> public DateTimeZoneHandling DateTimeZoneHandling { get => _dateTimeZoneHandling; set { if (value < DateTimeZoneHandling.Local || value > DateTimeZoneHandling.RoundtripKind) { throw new ArgumentOutOfRangeException(nameof(value)); } _dateTimeZoneHandling = value; } } /// <summary> /// Gets or sets how strings are escaped when writing JSON text. /// </summary> public StringEscapeHandling StringEscapeHandling { get => _stringEscapeHandling; set { if (value < StringEscapeHandling.Default || value > StringEscapeHandling.EscapeHtml) { throw new ArgumentOutOfRangeException(nameof(value)); } _stringEscapeHandling = value; OnStringEscapeHandlingChanged(); } } internal virtual void OnStringEscapeHandlingChanged() { // hacky but there is a calculated value that relies on StringEscapeHandling } /// <summary> /// Gets or sets how special floating point numbers, e.g. <see cref="Double.NaN"/>, /// <see cref="Double.PositiveInfinity"/> and <see cref="Double.NegativeInfinity"/>, /// are written to JSON text. /// </summary> public FloatFormatHandling FloatFormatHandling { get => _floatFormatHandling; set { if (value < FloatFormatHandling.String || value > FloatFormatHandling.DefaultValue) { throw new ArgumentOutOfRangeException(nameof(value)); } _floatFormatHandling = value; } } /// <summary> /// Gets or sets how <see cref="DateTime"/> and <see cref="DateTimeOffset"/> values are formatted when writing JSON text. /// </summary> public string DateFormatString { get => _dateFormatString; set => _dateFormatString = value; } /// <summary> /// Gets or sets the culture used when writing JSON. Defaults to <see cref="CultureInfo.InvariantCulture"/>. /// </summary> public CultureInfo Culture { get => _culture ?? CultureInfo.InvariantCulture; set => _culture = value; } /// <summary> /// Initializes a new instance of the <see cref="JsonWriter"/> class. /// </summary> protected JsonWriter() { _currentState = State.Start; _formatting = Formatting.None; _dateTimeZoneHandling = DateTimeZoneHandling.RoundtripKind; CloseOutput = true; AutoCompleteOnClose = true; } internal void UpdateScopeWithFinishedValue() { if (_currentPosition.HasIndex) { _currentPosition.Position++; } } private void Push(JsonContainerType value) { if (_currentPosition.Type != JsonContainerType.None) { if (_stack == null) { _stack = new List<JsonPosition>(); } _stack.Add(_currentPosition); } _currentPosition = new JsonPosition(value); } private JsonContainerType Pop() { JsonPosition oldPosition = _currentPosition; if (_stack != null && _stack.Count > 0) { _currentPosition = _stack[_stack.Count - 1]; _stack.RemoveAt(_stack.Count - 1); } else { _currentPosition = new JsonPosition(); } return oldPosition.Type; } private JsonContainerType Peek() { return _currentPosition.Type; } /// <summary> /// Flushes whatever is in the buffer to the destination and also flushes the destination. /// </summary> public abstract void Flush(); /// <summary> /// Closes this writer. /// If <see cref="CloseOutput"/> is set to <c>true</c>, the destination is also closed. /// If <see cref="AutoCompleteOnClose"/> is set to <c>true</c>, the JSON is auto-completed. /// </summary> public virtual void Close() { if (AutoCompleteOnClose) { AutoCompleteAll(); } } /// <summary> /// Writes the beginning of a JSON object. /// </summary> public virtual void WriteStartObject() { InternalWriteStart(JsonToken.StartObject, JsonContainerType.Object); } /// <summary> /// Writes the end of a JSON object. /// </summary> public virtual void WriteEndObject() { InternalWriteEnd(JsonContainerType.Object); } /// <summary> /// Writes the beginning of a JSON array. /// </summary> public virtual void WriteStartArray() { InternalWriteStart(JsonToken.StartArray, JsonContainerType.Array); } /// <summary> /// Writes the end of an array. /// </summary> public virtual void WriteEndArray() { InternalWriteEnd(JsonContainerType.Array); } /// <summary> /// Writes the start of a constructor with the given name. /// </summary> /// <param name="name">The name of the constructor.</param> public virtual void WriteStartConstructor(string name) { InternalWriteStart(JsonToken.StartConstructor, JsonContainerType.Constructor); } /// <summary> /// Writes the end constructor. /// </summary> public virtual void WriteEndConstructor() { InternalWriteEnd(JsonContainerType.Constructor); } /// <summary> /// Writes the property name of a name/value pair of a JSON object. /// </summary> /// <param name="name">The name of the property.</param> public virtual void WritePropertyName(string name) { InternalWritePropertyName(name); } /// <summary> /// Writes the property name of a name/value pair of a JSON object. /// </summary> /// <param name="name">The name of the property.</param> /// <param name="escape">A flag to indicate whether the text should be escaped when it is written as a JSON property name.</param> public virtual void WritePropertyName(string name, bool escape) { WritePropertyName(name); } /// <summary> /// Writes the end of the current JSON object or array. /// </summary> public virtual void WriteEnd() { WriteEnd(Peek()); } /// <summary> /// Writes the current <see cref="JsonReader"/> token and its children. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param> public void WriteToken(JsonReader reader) { WriteToken(reader, true); } /// <summary> /// Writes the current <see cref="JsonReader"/> token. /// </summary> /// <param name="reader">The <see cref="JsonReader"/> to read the token from.</param> /// <param name="writeChildren">A flag indicating whether the current token's children should be written.</param> public void WriteToken(JsonReader reader, bool writeChildren) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); WriteToken(reader, writeChildren, true, true); } /// <summary> /// Writes the <see cref="JsonToken"/> token and its value. /// </summary> /// <param name="token">The <see cref="JsonToken"/> to write.</param> /// <param name="value"> /// The value to write. /// A value is only required for tokens that have an associated value, e.g. the <see cref="String"/> property name for <see cref="JsonToken.PropertyName"/>. /// <c>null</c> can be passed to the method for tokens that don't have a value, e.g. <see cref="JsonToken.StartObject"/>. /// </param> public void WriteToken(JsonToken token, object value) { switch (token) { case JsonToken.None: // read to next break; case JsonToken.StartObject: WriteStartObject(); break; case JsonToken.StartArray: WriteStartArray(); break; case JsonToken.StartConstructor: ValidationUtils.ArgumentNotNull(value, nameof(value)); WriteStartConstructor(value.ToString()); break; case JsonToken.PropertyName: ValidationUtils.ArgumentNotNull(value, nameof(value)); WritePropertyName(value.ToString()); break; case JsonToken.Comment: WriteComment(value?.ToString()); break; case JsonToken.Integer: ValidationUtils.ArgumentNotNull(value, nameof(value)); #if HAVE_BIG_INTEGER if (value is BigInteger integer) { WriteValue(integer); } else #endif { WriteValue(Convert.ToInt64(value, CultureInfo.InvariantCulture)); } break; case JsonToken.Float: ValidationUtils.ArgumentNotNull(value, nameof(value)); if (value is decimal d) { WriteValue(d); } else if (value is double) { WriteValue((double)value); } else if (value is float) { WriteValue((float)value); } else { WriteValue(Convert.ToDouble(value, CultureInfo.InvariantCulture)); } break; case JsonToken.String: ValidationUtils.ArgumentNotNull(value, nameof(value)); WriteValue(value.ToString()); break; case JsonToken.Boolean: ValidationUtils.ArgumentNotNull(value, nameof(value)); WriteValue(Convert.ToBoolean(value, CultureInfo.InvariantCulture)); break; case JsonToken.Null: WriteNull(); break; case JsonToken.Undefined: WriteUndefined(); break; case JsonToken.EndObject: WriteEndObject(); break; case JsonToken.EndArray: WriteEndArray(); break; case JsonToken.EndConstructor: WriteEndConstructor(); break; case JsonToken.Date: ValidationUtils.ArgumentNotNull(value, nameof(value)); #if HAVE_DATE_TIME_OFFSET if (value is DateTimeOffset dt) { WriteValue(dt); } else #endif { WriteValue(Convert.ToDateTime(value, CultureInfo.InvariantCulture)); } break; case JsonToken.Raw: WriteRawValue(value?.ToString()); break; case JsonToken.Bytes: ValidationUtils.ArgumentNotNull(value, nameof(value)); if (value is Guid guid) { WriteValue(guid); } else { WriteValue((byte[])value); } break; default: throw MiscellaneousUtils.CreateArgumentOutOfRangeException(nameof(token), token, "Unexpected token type."); } } /// <summary> /// Writes the <see cref="JsonToken"/> token. /// </summary> /// <param name="token">The <see cref="JsonToken"/> to write.</param> public void WriteToken(JsonToken token) { WriteToken(token, null); } internal virtual void WriteToken(JsonReader reader, bool writeChildren, bool writeDateConstructorAsDate, bool writeComments) { int initialDepth = CalculateWriteTokenInitialDepth(reader); do { // write a JValue date when the constructor is for a date if (writeDateConstructorAsDate && reader.TokenType == JsonToken.StartConstructor && string.Equals(reader.Value.ToString(), "Date", StringComparison.Ordinal)) { WriteConstructorDate(reader); } else { if (writeComments || reader.TokenType != JsonToken.Comment) { WriteToken(reader.TokenType, reader.Value); } } } while ( // stop if we have reached the end of the token being read initialDepth - 1 < reader.Depth - (JsonTokenUtils.IsEndToken(reader.TokenType) ? 1 : 0) && writeChildren && reader.Read()); if (initialDepth < CalculateWriteTokenFinalDepth(reader)) { throw JsonWriterException.Create(this, "Unexpected end when reading token.", null); } } private int CalculateWriteTokenInitialDepth(JsonReader reader) { JsonToken type = reader.TokenType; if (type == JsonToken.None) { return -1; } return JsonTokenUtils.IsStartToken(type) ? reader.Depth : reader.Depth + 1; } private int CalculateWriteTokenFinalDepth(JsonReader reader) { JsonToken type = reader.TokenType; if (type == JsonToken.None) { return -1; } return JsonTokenUtils.IsEndToken(type) ? reader.Depth - 1 : reader.Depth; } private void WriteConstructorDate(JsonReader reader) { if (!reader.Read()) { throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null); } if (reader.TokenType != JsonToken.Integer) { throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected Integer, got " + reader.TokenType, null); } long ticks = (long)reader.Value; DateTime date = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks); if (!reader.Read()) { throw JsonWriterException.Create(this, "Unexpected end when reading date constructor.", null); } if (reader.TokenType != JsonToken.EndConstructor) { throw JsonWriterException.Create(this, "Unexpected token when reading date constructor. Expected EndConstructor, got " + reader.TokenType, null); } WriteValue(date); } private void WriteEnd(JsonContainerType type) { switch (type) { case JsonContainerType.Object: WriteEndObject(); break; case JsonContainerType.Array: WriteEndArray(); break; case JsonContainerType.Constructor: WriteEndConstructor(); break; default: throw JsonWriterException.Create(this, "Unexpected type when writing end: " + type, null); } } private void AutoCompleteAll() { while (Top > 0) { WriteEnd(); } } private JsonToken GetCloseTokenForType(JsonContainerType type) { switch (type) { case JsonContainerType.Object: return JsonToken.EndObject; case JsonContainerType.Array: return JsonToken.EndArray; case JsonContainerType.Constructor: return JsonToken.EndConstructor; default: throw JsonWriterException.Create(this, "No close token for type: " + type, null); } } private void AutoCompleteClose(JsonContainerType type) { int levelsToComplete = CalculateLevelsToComplete(type); for (int i = 0; i < levelsToComplete; i++) { JsonToken token = GetCloseTokenForType(Pop()); if (_currentState == State.Property) { WriteNull(); } if (_formatting == Formatting.Indented) { if (_currentState != State.ObjectStart && _currentState != State.ArrayStart) { WriteIndent(); } } WriteEnd(token); UpdateCurrentState(); } } private int CalculateLevelsToComplete(JsonContainerType type) { int levelsToComplete = 0; if (_currentPosition.Type == type) { levelsToComplete = 1; } else { int top = Top - 2; for (int i = top; i >= 0; i--) { int currentLevel = top - i; if (_stack[currentLevel].Type == type) { levelsToComplete = i + 2; break; } } } if (levelsToComplete == 0) { throw JsonWriterException.Create(this, "No token to close.", null); } return levelsToComplete; } private void UpdateCurrentState() { JsonContainerType currentLevelType = Peek(); switch (currentLevelType) { case JsonContainerType.Object: _currentState = State.Object; break; case JsonContainerType.Array: _currentState = State.Array; break; case JsonContainerType.Constructor: _currentState = State.Array; break; case JsonContainerType.None: _currentState = State.Start; break; default: throw JsonWriterException.Create(this, "Unknown JsonType: " + currentLevelType, null); } } /// <summary> /// Writes the specified end token. /// </summary> /// <param name="token">The end token to write.</param> protected virtual void WriteEnd(JsonToken token) { } /// <summary> /// Writes indent characters. /// </summary> protected virtual void WriteIndent() { } /// <summary> /// Writes the JSON value delimiter. /// </summary> protected virtual void WriteValueDelimiter() { } /// <summary> /// Writes an indent space. /// </summary> protected virtual void WriteIndentSpace() { } internal void AutoComplete(JsonToken tokenBeingWritten) { // gets new state based on the current state and what is being written State newState = StateArray[(int)tokenBeingWritten][(int)_currentState]; if (newState == State.Error) { throw JsonWriterException.Create(this, "Token {0} in state {1} would result in an invalid JSON object.".FormatWith(CultureInfo.InvariantCulture, tokenBeingWritten.ToString(), _currentState.ToString()), null); } if ((_currentState == State.Object || _currentState == State.Array || _currentState == State.Constructor) && tokenBeingWritten != JsonToken.Comment) { WriteValueDelimiter(); } if (_formatting == Formatting.Indented) { if (_currentState == State.Property) { WriteIndentSpace(); } // don't indent a property when it is the first token to be written (i.e. at the start) if ((_currentState == State.Array || _currentState == State.ArrayStart || _currentState == State.Constructor || _currentState == State.ConstructorStart) || (tokenBeingWritten == JsonToken.PropertyName && _currentState != State.Start)) { WriteIndent(); } } _currentState = newState; } #region WriteValue methods /// <summary> /// Writes a null value. /// </summary> public virtual void WriteNull() { InternalWriteValue(JsonToken.Null); } /// <summary> /// Writes an undefined value. /// </summary> public virtual void WriteUndefined() { InternalWriteValue(JsonToken.Undefined); } /// <summary> /// Writes raw JSON without changing the writer's state. /// </summary> /// <param name="json">The raw JSON to write.</param> public virtual void WriteRaw(string json) { InternalWriteRaw(); } /// <summary> /// Writes raw JSON where a value is expected and updates the writer's state. /// </summary> /// <param name="json">The raw JSON to write.</param> public virtual void WriteRawValue(string json) { // hack. want writer to change state as if a value had been written UpdateScopeWithFinishedValue(); AutoComplete(JsonToken.Undefined); WriteRaw(json); } /// <summary> /// Writes a <see cref="String"/> value. /// </summary> /// <param name="value">The <see cref="String"/> value to write.</param> public virtual void WriteValue(string value) { InternalWriteValue(JsonToken.String); } /// <summary> /// Writes a <see cref="Int32"/> value. /// </summary> /// <param name="value">The <see cref="Int32"/> value to write.</param> public virtual void WriteValue(int value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt32"/> value. /// </summary> /// <param name="value">The <see cref="UInt32"/> value to write.</param> public virtual void WriteValue(uint value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Int64"/> value. /// </summary> /// <param name="value">The <see cref="Int64"/> value to write.</param> public virtual void WriteValue(long value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt64"/> value. /// </summary> /// <param name="value">The <see cref="UInt64"/> value to write.</param> public virtual void WriteValue(ulong value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Single"/> value. /// </summary> /// <param name="value">The <see cref="Single"/> value to write.</param> public virtual void WriteValue(float value) { InternalWriteValue(JsonToken.Float); } /// <summary> /// Writes a <see cref="Double"/> value. /// </summary> /// <param name="value">The <see cref="Double"/> value to write.</param> public virtual void WriteValue(double value) { InternalWriteValue(JsonToken.Float); } /// <summary> /// Writes a <see cref="Boolean"/> value. /// </summary> /// <param name="value">The <see cref="Boolean"/> value to write.</param> public virtual void WriteValue(bool value) { InternalWriteValue(JsonToken.Boolean); } /// <summary> /// Writes a <see cref="Int16"/> value. /// </summary> /// <param name="value">The <see cref="Int16"/> value to write.</param> public virtual void WriteValue(short value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="UInt16"/> value. /// </summary> /// <param name="value">The <see cref="UInt16"/> value to write.</param> public virtual void WriteValue(ushort value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Char"/> value. /// </summary> /// <param name="value">The <see cref="Char"/> value to write.</param> public virtual void WriteValue(char value) { InternalWriteValue(JsonToken.String); } /// <summary> /// Writes a <see cref="Byte"/> value. /// </summary> /// <param name="value">The <see cref="Byte"/> value to write.</param> public virtual void WriteValue(byte value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="SByte"/> value. /// </summary> /// <param name="value">The <see cref="SByte"/> value to write.</param> public virtual void WriteValue(sbyte value) { InternalWriteValue(JsonToken.Integer); } /// <summary> /// Writes a <see cref="Decimal"/> value. /// </summary> /// <param name="value">The <see cref="Decimal"/> value to write.</param> public virtual void WriteValue(decimal value) { InternalWriteValue(JsonToken.Float); } /// <summary> /// Writes a <see cref="DateTime"/> value. /// </summary> /// <param name="value">The <see cref="DateTime"/> value to write.</param> public virtual void WriteValue(DateTime value) { InternalWriteValue(JsonToken.Date); } #if HAVE_DATE_TIME_OFFSET /// <summary> /// Writes a <see cref="DateTimeOffset"/> value. /// </summary> /// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param> public virtual void WriteValue(DateTimeOffset value) { InternalWriteValue(JsonToken.Date); } #endif /// <summary> /// Writes a <see cref="Guid"/> value. /// </summary> /// <param name="value">The <see cref="Guid"/> value to write.</param> public virtual void WriteValue(Guid value) { InternalWriteValue(JsonToken.String); } /// <summary> /// Writes a <see cref="TimeSpan"/> value. /// </summary> /// <param name="value">The <see cref="TimeSpan"/> value to write.</param> public virtual void WriteValue(TimeSpan value) { InternalWriteValue(JsonToken.String); } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Int32"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Int32"/> value to write.</param> public virtual void WriteValue(int? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="UInt32"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="UInt32"/> value to write.</param> public virtual void WriteValue(uint? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Int64"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Int64"/> value to write.</param> public virtual void WriteValue(long? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="UInt64"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="UInt64"/> value to write.</param> public virtual void WriteValue(ulong? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Single"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Single"/> value to write.</param> public virtual void WriteValue(float? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Double"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Double"/> value to write.</param> public virtual void WriteValue(double? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Boolean"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Boolean"/> value to write.</param> public virtual void WriteValue(bool? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Int16"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Int16"/> value to write.</param> public virtual void WriteValue(short? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="UInt16"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="UInt16"/> value to write.</param> public virtual void WriteValue(ushort? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Char"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Char"/> value to write.</param> public virtual void WriteValue(char? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Byte"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Byte"/> value to write.</param> public virtual void WriteValue(byte? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="SByte"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="SByte"/> value to write.</param> public virtual void WriteValue(sbyte? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Decimal"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Decimal"/> value to write.</param> public virtual void WriteValue(decimal? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="DateTime"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="DateTime"/> value to write.</param> public virtual void WriteValue(DateTime? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } #if HAVE_DATE_TIME_OFFSET /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/> value to write.</param> public virtual void WriteValue(DateTimeOffset? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } #endif /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="Guid"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="Guid"/> value to write.</param> public virtual void WriteValue(Guid? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Nullable{T}"/> of <see cref="TimeSpan"/> value. /// </summary> /// <param name="value">The <see cref="Nullable{T}"/> of <see cref="TimeSpan"/> value to write.</param> public virtual void WriteValue(TimeSpan? value) { if (value == null) { WriteNull(); } else { WriteValue(value.GetValueOrDefault()); } } /// <summary> /// Writes a <see cref="Byte"/>[] value. /// </summary> /// <param name="value">The <see cref="Byte"/>[] value to write.</param> public virtual void WriteValue(byte[] value) { if (value == null) { WriteNull(); } else { InternalWriteValue(JsonToken.Bytes); } } /// <summary> /// Writes a <see cref="Uri"/> value. /// </summary> /// <param name="value">The <see cref="Uri"/> value to write.</param> public virtual void WriteValue(Uri value) { if (value == null) { WriteNull(); } else { InternalWriteValue(JsonToken.String); } } /// <summary> /// Writes a <see cref="Object"/> value. /// An error will raised if the value cannot be written as a single JSON token. /// </summary> /// <param name="value">The <see cref="Object"/> value to write.</param> public virtual void WriteValue(object value) { if (value == null) { WriteNull(); } else { #if HAVE_BIG_INTEGER // this is here because adding a WriteValue(BigInteger) to JsonWriter will // mean the user has to add a reference to System.Numerics.dll if (value is BigInteger) { throw CreateUnsupportedTypeException(this, value); } #endif WriteValue(this, ConvertUtils.GetTypeCode(value.GetType()), value); } } #endregion WriteValue methods /// <summary> /// Writes a comment <c>/*...*/</c> containing the specified text. /// </summary> /// <param name="text">Text to place inside the comment.</param> public virtual void WriteComment(string text) { InternalWriteComment(); } /// <summary> /// Writes the given white space. /// </summary> /// <param name="ws">The string of white space characters.</param> public virtual void WriteWhitespace(string ws) { InternalWriteWhitespace(ws); } void IDisposable.Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (_currentState != State.Closed && disposing) { Close(); } } internal static void WriteValue(JsonWriter writer, PrimitiveTypeCode typeCode, object value) { while (true) { switch (typeCode) { case PrimitiveTypeCode.Char: writer.WriteValue((char)value); return; case PrimitiveTypeCode.CharNullable: writer.WriteValue((value == null) ? (char?)null : (char)value); return; case PrimitiveTypeCode.Boolean: writer.WriteValue((bool)value); return; case PrimitiveTypeCode.BooleanNullable: writer.WriteValue((value == null) ? (bool?)null : (bool)value); return; case PrimitiveTypeCode.SByte: writer.WriteValue((sbyte)value); return; case PrimitiveTypeCode.SByteNullable: writer.WriteValue((value == null) ? (sbyte?)null : (sbyte)value); return; case PrimitiveTypeCode.Int16: writer.WriteValue((short)value); return; case PrimitiveTypeCode.Int16Nullable: writer.WriteValue((value == null) ? (short?)null : (short)value); return; case PrimitiveTypeCode.UInt16: writer.WriteValue((ushort)value); return; case PrimitiveTypeCode.UInt16Nullable: writer.WriteValue((value == null) ? (ushort?)null : (ushort)value); return; case PrimitiveTypeCode.Int32: writer.WriteValue((int)value); return; case PrimitiveTypeCode.Int32Nullable: writer.WriteValue((value == null) ? (int?)null : (int)value); return; case PrimitiveTypeCode.Byte: writer.WriteValue((byte)value); return; case PrimitiveTypeCode.ByteNullable: writer.WriteValue((value == null) ? (byte?)null : (byte)value); return; case PrimitiveTypeCode.UInt32: writer.WriteValue((uint)value); return; case PrimitiveTypeCode.UInt32Nullable: writer.WriteValue((value == null) ? (uint?)null : (uint)value); return; case PrimitiveTypeCode.Int64: writer.WriteValue((long)value); return; case PrimitiveTypeCode.Int64Nullable: writer.WriteValue((value == null) ? (long?)null : (long)value); return; case PrimitiveTypeCode.UInt64: writer.WriteValue((ulong)value); return; case PrimitiveTypeCode.UInt64Nullable: writer.WriteValue((value == null) ? (ulong?)null : (ulong)value); return; case PrimitiveTypeCode.Single: writer.WriteValue((float)value); return; case PrimitiveTypeCode.SingleNullable: writer.WriteValue((value == null) ? (float?)null : (float)value); return; case PrimitiveTypeCode.Double: writer.WriteValue((double)value); return; case PrimitiveTypeCode.DoubleNullable: writer.WriteValue((value == null) ? (double?)null : (double)value); return; case PrimitiveTypeCode.DateTime: writer.WriteValue((DateTime)value); return; case PrimitiveTypeCode.DateTimeNullable: writer.WriteValue((value == null) ? (DateTime?)null : (DateTime)value); return; #if HAVE_DATE_TIME_OFFSET case PrimitiveTypeCode.DateTimeOffset: writer.WriteValue((DateTimeOffset)value); return; case PrimitiveTypeCode.DateTimeOffsetNullable: writer.WriteValue((value == null) ? (DateTimeOffset?)null : (DateTimeOffset)value); return; #endif case PrimitiveTypeCode.Decimal: writer.WriteValue((decimal)value); return; case PrimitiveTypeCode.DecimalNullable: writer.WriteValue((value == null) ? (decimal?)null : (decimal)value); return; case PrimitiveTypeCode.Guid: writer.WriteValue((Guid)value); return; case PrimitiveTypeCode.GuidNullable: writer.WriteValue((value == null) ? (Guid?)null : (Guid)value); return; case PrimitiveTypeCode.TimeSpan: writer.WriteValue((TimeSpan)value); return; case PrimitiveTypeCode.TimeSpanNullable: writer.WriteValue((value == null) ? (TimeSpan?)null : (TimeSpan)value); return; #if HAVE_BIG_INTEGER case PrimitiveTypeCode.BigInteger: // this will call to WriteValue(object) writer.WriteValue((BigInteger)value); return; case PrimitiveTypeCode.BigIntegerNullable: // this will call to WriteValue(object) writer.WriteValue((value == null) ? (BigInteger?)null : (BigInteger)value); return; #endif case PrimitiveTypeCode.Uri: writer.WriteValue((Uri)value); return; case PrimitiveTypeCode.String: writer.WriteValue((string)value); return; case PrimitiveTypeCode.Bytes: writer.WriteValue((byte[])value); return; #if HAVE_DB_NULL_TYPE_CODE case PrimitiveTypeCode.DBNull: writer.WriteNull(); return; #endif default: #if HAVE_ICONVERTIBLE if (value is IConvertible convertible) { ResolveConvertibleValue(convertible, out typeCode, out value); continue; } #endif // write an unknown null value, fix https://github.com/JamesNK/RRQMCore.XREF.Newtonsoft.Json/issues/1460 if (value == null) { writer.WriteNull(); return; } throw CreateUnsupportedTypeException(writer, value); } } } #if HAVE_ICONVERTIBLE private static void ResolveConvertibleValue(IConvertible convertible, out PrimitiveTypeCode typeCode, out object value) { // the value is a non-standard IConvertible // convert to the underlying value and retry TypeInformation typeInformation = ConvertUtils.GetTypeInformation(convertible); // if convertible has an underlying typecode of Object then attempt to convert it to a string typeCode = typeInformation.TypeCode == PrimitiveTypeCode.Object ? PrimitiveTypeCode.String : typeInformation.TypeCode; Type resolvedType = typeInformation.TypeCode == PrimitiveTypeCode.Object ? typeof(string) : typeInformation.Type; value = convertible.ToType(resolvedType, CultureInfo.InvariantCulture); } #endif private static JsonWriterException CreateUnsupportedTypeException(JsonWriter writer, object value) { return JsonWriterException.Create(writer, "Unsupported type: {0}. Use the JsonSerializer class to get the object's JSON representation.".FormatWith(CultureInfo.InvariantCulture, value.GetType()), null); } /// <summary> /// Sets the state of the <see cref="JsonWriter"/>. /// </summary> /// <param name="token">The <see cref="JsonToken"/> being written.</param> /// <param name="value">The value being written.</param> protected void SetWriteState(JsonToken token, object value) { switch (token) { case JsonToken.StartObject: InternalWriteStart(token, JsonContainerType.Object); break; case JsonToken.StartArray: InternalWriteStart(token, JsonContainerType.Array); break; case JsonToken.StartConstructor: InternalWriteStart(token, JsonContainerType.Constructor); break; case JsonToken.PropertyName: if (!(value is string)) { throw new ArgumentException("A name is required when setting property name state.", nameof(value)); } InternalWritePropertyName((string)value); break; case JsonToken.Comment: InternalWriteComment(); break; case JsonToken.Raw: InternalWriteRaw(); break; case JsonToken.Integer: case JsonToken.Float: case JsonToken.String: case JsonToken.Boolean: case JsonToken.Date: case JsonToken.Bytes: case JsonToken.Null: case JsonToken.Undefined: InternalWriteValue(token); break; case JsonToken.EndObject: InternalWriteEnd(JsonContainerType.Object); break; case JsonToken.EndArray: InternalWriteEnd(JsonContainerType.Array); break; case JsonToken.EndConstructor: InternalWriteEnd(JsonContainerType.Constructor); break; default: throw new ArgumentOutOfRangeException(nameof(token)); } } internal void InternalWriteEnd(JsonContainerType container) { AutoCompleteClose(container); } internal void InternalWritePropertyName(string name) { _currentPosition.PropertyName = name; AutoComplete(JsonToken.PropertyName); } internal void InternalWriteRaw() { } internal void InternalWriteStart(JsonToken token, JsonContainerType container) { UpdateScopeWithFinishedValue(); AutoComplete(token); Push(container); } internal void InternalWriteValue(JsonToken token) { UpdateScopeWithFinishedValue(); AutoComplete(token); } internal void InternalWriteWhitespace(string ws) { if (ws != null) { if (!StringUtils.IsWhiteSpace(ws)) { throw JsonWriterException.Create(this, "Only white space characters should be used.", null); } } } internal void InternalWriteComment() { AutoComplete(JsonToken.Comment); } } }
34.365591
262
0.495792
[ "Apache-2.0" ]
850wyb/RRQMSocket
RRQMCore/XREF/Newtonsoft.Json/JsonWriter.cs
64,134
C#
namespace TCC.Controls.Classes { /// <summary> /// Logica di interazione per BerserkerBar.xaml /// </summary> public partial class BerserkerBar { public BerserkerBar() { InitializeComponent(); } } }
18.571429
51
0.561538
[ "MIT" ]
Seyuna/Tera-custom-cooldowns
TCC.Core/Controls/Classes/BerserkerBar.xaml.cs
262
C#
/* Copyright 2010-2016 MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace MongoDB.Bson { /// <summary> /// Represents the type of a BSON element. /// </summary> #if NET45 [Serializable] #endif public enum BsonType { /// <summary> /// Not a real BSON type. Used to signal the end of a document. /// </summary> EndOfDocument = 0x00, // no values of this type exist, it marks the end of a document /// <summary> /// A BSON double. /// </summary> Double = 0x01, /// <summary> /// A BSON string. /// </summary> String = 0x02, /// <summary> /// A BSON document. /// </summary> Document = 0x03, /// <summary> /// A BSON array. /// </summary> Array = 0x04, /// <summary> /// BSON binary data. /// </summary> Binary = 0x05, /// <summary> /// A BSON undefined value. /// </summary> Undefined = 0x06, /// <summary> /// A BSON ObjectId. /// </summary> ObjectId = 0x07, /// <summary> /// A BSON bool. /// </summary> Boolean = 0x08, /// <summary> /// A BSON DateTime. /// </summary> DateTime = 0x09, /// <summary> /// A BSON null value. /// </summary> Null = 0x0a, /// <summary> /// A BSON regular expression. /// </summary> RegularExpression = 0x0b, /// <summary> /// BSON JavaScript code. /// </summary> JavaScript = 0x0d, /// <summary> /// A BSON symbol. /// </summary> Symbol = 0x0e, /// <summary> /// BSON JavaScript code with a scope (a set of variables with values). /// </summary> JavaScriptWithScope = 0x0f, /// <summary> /// A BSON 32-bit integer. /// </summary> Int32 = 0x10, /// <summary> /// A BSON timestamp. /// </summary> Timestamp = 0x11, /// <summary> /// A BSON 64-bit integer. /// </summary> Int64 = 0x12, /// <summary> /// A BSON MinKey value. /// </summary> MinKey = 0xff, /// <summary> /// A BSON MaxKey value. /// </summary> MaxKey = 0x7f } }
26.863636
93
0.503215
[ "Apache-2.0" ]
joeenzminger/mongo-csharp-driver
src/MongoDB.Bson/ObjectModel/BsonType.cs
2,957
C#
using Cpp2IL.Core; namespace Cpp2IL { public struct Cpp2IlRuntimeArgs { //To determine easily if this struct is the default one or not. public bool Valid; //Core variables public int[] UnityVersion; public string PathToAssembly; public string PathToMetadata; public string AssemblyToRunAnalysisFor; public bool AnalyzeAllAssemblies; public string? WasmFrameworkJsFile; //Feature flags public bool EnableAnalysis; public bool EnableMetadataGeneration; public bool EnableRegistrationPrompts; public bool EnableIlToAsm; public bool IlToAsmContinueThroughErrors; public bool SuppressAttributes; public bool Parallel; public bool SimpleAttributeRestoration; public bool DisableMethodDumps; public bool EnableVerboseLogging; public AnalysisLevel AnalysisLevel; public string OutputRootDirectory; } }
27.916667
71
0.671642
[ "MIT" ]
NeoZion/Cpp2IL
Cpp2IL/Cpp2IlRuntimeArgs.cs
1,007
C#
using Abp.Authorization.Users; using Abp.Extensions; using FuelWerx.MultiTenancy; using Microsoft.AspNet.Identity; using System; using System.Runtime.CompilerServices; namespace FuelWerx.Authorization.Users { public class User : AbpUser<FuelWerx.MultiTenancy.Tenant, User> { public const int MinPlainPasswordLength = 6; public virtual Guid? ProfilePictureId { get; set; } public virtual bool ShouldChangePasswordOnNextLogin { get; set; } public User() { } public static string CreateRandomPassword() { Guid guid = Guid.NewGuid(); return guid.ToString("N").Truncate(16); } public static User CreateTenantAdminUser(int tenantId, string emailAddress, string password) { return new User() { TenantId = new int?(tenantId), UserName = "admin", Name = "admin", Surname = "admin", EmailAddress = emailAddress, Password = (new PasswordHasher()).HashPassword(password) }; } } }
19.571429
94
0.701773
[ "MIT" ]
zberg007/fuelwerx
src/FuelWerx.Core/Authorization/Users/User.cs
959
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Response { /// <summary> /// AlipaySocialBaseChatGmemberDeleteResponse. /// </summary> public class AlipaySocialBaseChatGmemberDeleteResponse : AopResponse { /// <summary> /// 删除结果 /// </summary> [XmlElement("result_delete")] public bool ResultDelete { get; set; } } }
22.111111
72
0.623116
[ "Apache-2.0" ]
Varorbc/alipay-sdk-net-all
AlipaySDKNet/Response/AlipaySocialBaseChatGmemberDeleteResponse.cs
406
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Tke.V20180525.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class AddVpcCniSubnetsRequest : AbstractModel { /// <summary> /// 集群ID /// </summary> [JsonProperty("ClusterId")] public string ClusterId{ get; set; } /// <summary> /// 为集群容器网络增加的子网列表 /// </summary> [JsonProperty("SubnetIds")] public string[] SubnetIds{ get; set; } /// <summary> /// 集群所属的VPC的ID /// </summary> [JsonProperty("VpcId")] public string VpcId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "ClusterId", this.ClusterId); this.SetParamArraySimple(map, prefix + "SubnetIds.", this.SubnetIds); this.SetParamSimple(map, prefix + "VpcId", this.VpcId); } } }
30.034483
81
0.623995
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet
TencentCloud/Tke/V20180525/Models/AddVpcCniSubnetsRequest.cs
1,786
C#
using Domain; namespace MadMaxGui.Helper { public class ParamCreator { private string param; public ParamCreator() { } public string Create(Config config) { if (config is null) return null; param += config.NumberOfPLots is not null ? "-n " + config.NumberOfPLots : "-n 1"; param += config.Threads is not null ? " -r " + config.Threads : " -r 4"; param += config.Buckets is not null ? " -u " + config.Buckets : " -u 256"; param += config.BucketsPhaseThreeAndFour is not null ? " -v " + config.BucketsPhaseThreeAndFour : ""; param += config.TempDir is not null ? " -t " + config.TempDir : " -t "; param += config.TempDir2 is not null ? " -2 " + config.TempDir2 : ""; param += config.FinalDir is not null ? " -d " + config.FinalDir : " -d "; param += config.ContractKey is not null ? " -c " + config.ContractKey : " -c "; param += config.FarmerKey is not null ? " -f " + config.FarmerKey : " -f "; return param; } } }
35.78125
113
0.525764
[ "MIT" ]
Muslix/MadMaxGui_byMuslix
MadMaxGui/Helper/ParamCreator.cs
1,147
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Text; namespace Xania.Graphs.EntityFramework.Tests.Relational.Queries { public class VertexQuery : IQueryable<Elements.Vertex> { private readonly IQueryable<Vertex> _vertices; public VertexQuery(IQueryable<Relational.Vertex> vertices) { _vertices = vertices; } public IEnumerator<Elements.Vertex> GetEnumerator() { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public Type ElementType => _vertices.ElementType; public Expression Expression => _vertices.Expression; public IQueryProvider Provider => _vertices.Provider; } }
25.852941
66
0.67008
[ "MIT" ]
ibrahimbensalah/Xania
Xania.Graphs.EntityFramework.Tests/Relational/Queries/VertexQuery.cs
881
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.Redis.Models { /// <summary> /// Defines values for PrivateEndpointConnectionProvisioningState. /// </summary> public static class PrivateEndpointConnectionProvisioningState { public const string Succeeded = "Succeeded"; public const string Creating = "Creating"; public const string Deleting = "Deleting"; public const string Failed = "Failed"; } }
31.88
74
0.711418
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/redis/Microsoft.Azure.Management.Redis/src/Generated/Models/PrivateEndpointConnectionProvisioningState.cs
797
C#
using System; namespace PlusCommon.Log { /// <summary> /// BaseLog 的摘要说明 /// 保存日志到文本的接口类 /// </summary> public class BaseLog { /// <summary> /// 文件夹名称 /// </summary> protected string MFolderName = string.Empty; /// <summary> /// 缺省构造器 /// </summary> public BaseLog() { // } /// <summary> /// 接收日志目录信息构造器 /// </summary> /// <param name="folderName">日志目录信息</param> public BaseLog(string folderName) { this.MFolderName = folderName; } /// <summary> /// 记录一些基本信息(非异常日志) /// </summary> /// <param name="message">记录的消息内容</param> public void SaveLog(String message) { LogHelper.WriteInfo(string.Format("{0}消息:{1}", this.MFolderName, message)); } /// <summary> /// 记录异常日志信息 /// </summary> /// <param name="aExObj">异常对象</param> public void SaveLog(Exception aExObj) { if (aExObj == null) { LogHelper.WriteException(string.Format("{0}发生异常:{1}", this.MFolderName, "aExObj Is Null"), aExObj); } else { LogHelper.WriteException(string.Format("{0}发生异常:{1}", this.MFolderName, aExObj.Message), aExObj); } } /// <summary> /// 记录异常日志信息 /// </summary> /// <param name="message">消息内容</param> /// <param name="aExObj">异常对象</param> public void SaveLog(string message, Exception aExObj) { if (aExObj == null) { LogHelper.WriteException(string.Format("{0};消息:{1}发生异常:{2}", this.MFolderName, message, "aExObj Is Null"), aExObj); } else { LogHelper.WriteException(string.Format("{0};消息:{1}发生异常:{2}", this.MFolderName, message, aExObj.Message), aExObj); } } /// <summary> /// 记录异常日志到Debug目录 /// </summary> /// <param name="message"></param> public void SaveDebugLog(string message) { LogHelper.WriteDebug(string.Format("{0};消息:{1}", this.MFolderName, message)); } /// <summary> /// 记录异常日志到Fatal目录 /// </summary> /// <param name="message"></param> public void SaveFatalLog(string message) { LogHelper.WriteFatal(string.Format("{0};消息:{1}", this.MFolderName, message)); } /// <summary> /// 记录异常日志到Warn目录 /// </summary> /// <param name="message"></param> public void SaveWarnLog(string message) { LogHelper.WriteWarn(string.Format("{0};消息:{1}", this.MFolderName, message)); } /// <summary> /// 记录异常日志到Warn目录 /// </summary> /// <param name="message"></param> /// <param name="ex"></param> public void SaveWarnLog(string message, Exception ex) { LogHelper.WriteWarn(string.Format("{0};消息:{1}", this.MFolderName, message), ex); } /// <summary> /// 记录异常日志到Complement目录 /// </summary> /// <param name="message"></param> public void SaveComplementLog(string message) { LogHelper.WriteComplement(string.Format("{0};消息:{1}", this.MFolderName, message)); } /// <summary> /// 记录异常日志到Complement目录 /// </summary> /// <param name="message"></param> /// <param name="ex"></param> public void SaveComplementLog(string message, Exception ex) { LogHelper.WriteComplement(string.Format("{0};消息:{1}", this.MFolderName, message), ex); } } }
30.685484
131
0.498817
[ "MIT" ]
jessegame/plusgame
PlusCommon/Log/BaseLog.cs
4,211
C#
// <copyright file="OtlpMetricExporterExtensions.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using OpenTelemetry.Exporter; using OpenTelemetry.Internal; namespace OpenTelemetry.Metrics { /// <summary> /// Extension methods to simplify registering of the OpenTelemetry Protocol (OTLP) exporter. /// </summary> public static class OtlpMetricExporterExtensions { private const int DefaultExportIntervalMilliseconds = 60000; private const int DefaultExportTimeoutMilliseconds = 30000; /// <summary> /// Adds <see cref="OtlpMetricExporter"/> to the <see cref="MeterProviderBuilder"/> using default options. /// </summary> /// <param name="builder"><see cref="MeterProviderBuilder"/> builder to use.</param> /// <returns>The instance of <see cref="MeterProviderBuilder"/> to chain the calls.</returns> public static MeterProviderBuilder AddOtlpExporter(this MeterProviderBuilder builder) { return AddOtlpExporter(builder, options => { }); } /// <summary> /// Adds <see cref="OtlpMetricExporter"/> to the <see cref="MeterProviderBuilder"/>. /// </summary> /// <param name="builder"><see cref="MeterProviderBuilder"/> builder to use.</param> /// <param name="configureExporter">Exporter configuration options.</param> /// <returns>The instance of <see cref="MeterProviderBuilder"/> to chain the calls.</returns> public static MeterProviderBuilder AddOtlpExporter(this MeterProviderBuilder builder, Action<OtlpExporterOptions> configureExporter) { Guard.ThrowIfNull(builder); if (builder is IDeferredMeterProviderBuilder deferredMeterProviderBuilder) { return deferredMeterProviderBuilder.Configure((sp, builder) => { AddOtlpExporter(builder, sp.GetOptions<OtlpExporterOptions>(), sp.GetOptions<MetricReaderOptions>(), configureExporter, null, sp); }); } return AddOtlpExporter(builder, new OtlpExporterOptions(), new MetricReaderOptions(), configureExporter, null, serviceProvider: null); } /// <summary> /// Adds <see cref="OtlpMetricExporter"/> to the <see cref="MeterProviderBuilder"/>. /// </summary> /// <param name="builder"><see cref="MeterProviderBuilder"/> builder to use.</param> /// <param name="configureExporterAndMetricReader">Exporter and <see cref="MetricReader"/> configuration options.</param> /// <returns>The instance of <see cref="MeterProviderBuilder"/> to chain the calls.</returns> public static MeterProviderBuilder AddOtlpExporter( this MeterProviderBuilder builder, Action<OtlpExporterOptions, MetricReaderOptions> configureExporterAndMetricReader) { Guard.ThrowIfNull(builder, nameof(builder)); if (builder is IDeferredMeterProviderBuilder deferredMeterProviderBuilder) { return deferredMeterProviderBuilder.Configure((sp, builder) => { AddOtlpExporter(builder, sp.GetOptions<OtlpExporterOptions>(), sp.GetOptions<MetricReaderOptions>(), null, configureExporterAndMetricReader, sp); }); } return AddOtlpExporter(builder, new OtlpExporterOptions(), new MetricReaderOptions(), null, configureExporterAndMetricReader, serviceProvider: null); } private static MeterProviderBuilder AddOtlpExporter( MeterProviderBuilder builder, OtlpExporterOptions exporterOptions, MetricReaderOptions metricReaderOptions, Action<OtlpExporterOptions> configureExporter, Action<OtlpExporterOptions, MetricReaderOptions> configureExporterAndMetricReader, IServiceProvider serviceProvider) { if (configureExporterAndMetricReader != null) { configureExporterAndMetricReader.Invoke(exporterOptions, metricReaderOptions); } else { configureExporter?.Invoke(exporterOptions); } exporterOptions.TryEnableIHttpClientFactoryIntegration(serviceProvider, "OtlpMetricExporter"); exporterOptions.AppendExportPath(OtlpExporterOptions.MetricsExportPath); var metricExporter = new OtlpMetricExporter(exporterOptions); var metricReader = PeriodicExportingMetricReaderHelper.CreatePeriodicExportingMetricReader( metricExporter, metricReaderOptions, DefaultExportIntervalMilliseconds, DefaultExportTimeoutMilliseconds); return builder.AddReader(metricReader); } } }
46.135593
165
0.673953
[ "Apache-2.0" ]
TylerHelmuth/opentelemetry-dotnet
src/OpenTelemetry.Exporter.OpenTelemetryProtocol/OtlpMetricExporterExtensions.cs
5,444
C#
using System.Text; namespace PaySharp.Core.Utils { public enum StringCase { /// <summary> /// 蛇形策略 /// </summary> Snake, /// <summary> /// 骆驼策略 /// </summary> Camel, /// <summary> /// 小写策略 /// </summary> Lower, /// <summary> /// 不执行策略 /// </summary> None } internal enum SnakeCaseState { Start, Lower, Upper, NewWord } public static class StringUtil { /// <summary> /// 将字符串转换为蛇形策略 /// </summary> /// <param name="s">字符串</param> /// <returns></returns> public static string ToSnakeCase(this string s) { if (string.IsNullOrEmpty(s)) { return s; } var sb = new StringBuilder(); var state = SnakeCaseState.Start; for (var i = 0; i < s.Length; i++) { if (s[i] == ' ') { if (state != SnakeCaseState.Start) { state = SnakeCaseState.NewWord; } } else if (char.IsUpper(s[i])) { switch (state) { case SnakeCaseState.Upper: var hasNext = i + 1 < s.Length; if (i > 0 && hasNext) { var nextChar = s[i + 1]; if (!char.IsUpper(nextChar) && nextChar != '_') { sb.Append('_'); } } break; case SnakeCaseState.Lower: case SnakeCaseState.NewWord: sb.Append('_'); break; } sb.Append(char.ToLowerInvariant(s[i])); state = SnakeCaseState.Upper; } else if (s[i] == '_') { sb.Append('_'); state = SnakeCaseState.Start; } else { if (state == SnakeCaseState.NewWord) { sb.Append('_'); } sb.Append(s[i]); state = SnakeCaseState.Lower; } } return sb.ToString(); } /// <summary> /// 将字符串转换为骆驼策略 /// </summary> /// <param name="s">字符串</param> /// <returns></returns> public static string ToCamelCase(this string s) { if (string.IsNullOrEmpty(s) || !char.IsUpper(s[0])) { return s; } var chars = s.ToCharArray(); for (var i = 0; i < chars.Length; i++) { if (i == 1 && !char.IsUpper(chars[i])) { break; } var hasNext = i + 1 < chars.Length; if (i > 0 && hasNext && !char.IsUpper(chars[i + 1])) { if (char.IsSeparator(chars[i + 1])) { chars[i] = char.ToLowerInvariant(chars[i]); } break; } chars[i] = char.ToLowerInvariant(chars[i]); } return new string(chars); } } }
25.609589
79
0.33057
[ "MIT" ]
Abbotton/PaySharp
src/PaySharp.Core/Utils/StringUtil.cs
3,831
C#
// // Utilities.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2010 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using Mono.Cecil.Metadata; namespace Mono.Cecil { static partial class Mixin { public static uint ReadCompressedUInt32 (this byte [] data, ref int position) { uint integer; if ((data [position] & 0x80) == 0) { integer = data [position]; position++; } else if ((data [position] & 0x40) == 0) { integer = (uint) (data [position] & ~0x80) << 8; integer |= data [position + 1]; position += 2; } else { integer = (uint) (data [position] & ~0xc0) << 24; integer |= (uint) data [position + 1] << 16; integer |= (uint) data [position + 2] << 8; integer |= (uint) data [position + 3]; position += 4; } return integer; } public static MetadataToken GetMetadataToken (this CodedIndex self, uint data) { uint rid; TokenType token_type; switch (self) { case CodedIndex.TypeDefOrRef: rid = data >> 2; switch (data & 3) { case 0: token_type = TokenType.TypeDef; goto ret; case 1: token_type = TokenType.TypeRef; goto ret; case 2: token_type = TokenType.TypeSpec; goto ret; default: goto exit; } case CodedIndex.HasConstant: rid = data >> 2; switch (data & 3) { case 0: token_type = TokenType.Field; goto ret; case 1: token_type = TokenType.Param; goto ret; case 2: token_type = TokenType.Property; goto ret; default: goto exit; } case CodedIndex.HasCustomAttribute: rid = data >> 5; switch (data & 31) { case 0: token_type = TokenType.Method; goto ret; case 1: token_type = TokenType.Field; goto ret; case 2: token_type = TokenType.TypeRef; goto ret; case 3: token_type = TokenType.TypeDef; goto ret; case 4: token_type = TokenType.Param; goto ret; case 5: token_type = TokenType.InterfaceImpl; goto ret; case 6: token_type = TokenType.MemberRef; goto ret; case 7: token_type = TokenType.Module; goto ret; case 8: token_type = TokenType.Permission; goto ret; case 9: token_type = TokenType.Property; goto ret; case 10: token_type = TokenType.Event; goto ret; case 11: token_type = TokenType.Signature; goto ret; case 12: token_type = TokenType.ModuleRef; goto ret; case 13: token_type = TokenType.TypeSpec; goto ret; case 14: token_type = TokenType.Assembly; goto ret; case 15: token_type = TokenType.AssemblyRef; goto ret; case 16: token_type = TokenType.File; goto ret; case 17: token_type = TokenType.ExportedType; goto ret; case 18: token_type = TokenType.ManifestResource; goto ret; case 19: token_type = TokenType.GenericParam; goto ret; default: goto exit; } case CodedIndex.HasFieldMarshal: rid = data >> 1; switch (data & 1) { case 0: token_type = TokenType.Field; goto ret; case 1: token_type = TokenType.Param; goto ret; default: goto exit; } case CodedIndex.HasDeclSecurity: rid = data >> 2; switch (data & 3) { case 0: token_type = TokenType.TypeDef; goto ret; case 1: token_type = TokenType.Method; goto ret; case 2: token_type = TokenType.Assembly; goto ret; default: goto exit; } case CodedIndex.MemberRefParent: rid = data >> 3; switch (data & 7) { case 0: token_type = TokenType.TypeDef; goto ret; case 1: token_type = TokenType.TypeRef; goto ret; case 2: token_type = TokenType.ModuleRef; goto ret; case 3: token_type = TokenType.Method; goto ret; case 4: token_type = TokenType.TypeSpec; goto ret; default: goto exit; } case CodedIndex.HasSemantics: rid = data >> 1; switch (data & 1) { case 0: token_type = TokenType.Event; goto ret; case 1: token_type = TokenType.Property; goto ret; default: goto exit; } case CodedIndex.MethodDefOrRef: rid = data >> 1; switch (data & 1) { case 0: token_type = TokenType.Method; goto ret; case 1: token_type = TokenType.MemberRef; goto ret; default: goto exit; } case CodedIndex.MemberForwarded: rid = data >> 1; switch (data & 1) { case 0: token_type = TokenType.Field; goto ret; case 1: token_type = TokenType.Method; goto ret; default: goto exit; } case CodedIndex.Implementation: rid = data >> 2; switch (data & 3) { case 0: token_type = TokenType.File; goto ret; case 1: token_type = TokenType.AssemblyRef; goto ret; case 2: token_type = TokenType.ExportedType; goto ret; default: goto exit; } case CodedIndex.CustomAttributeType: rid = data >> 3; switch (data & 7) { case 2: token_type = TokenType.Method; goto ret; case 3: token_type = TokenType.MemberRef; goto ret; default: goto exit; } case CodedIndex.ResolutionScope: rid = data >> 2; switch (data & 3) { case 0: token_type = TokenType.Module; goto ret; case 1: token_type = TokenType.ModuleRef; goto ret; case 2: token_type = TokenType.AssemblyRef; goto ret; case 3: token_type = TokenType.TypeRef; goto ret; default: goto exit; } case CodedIndex.TypeOrMethodDef: rid = data >> 1; switch (data & 1) { case 0: token_type = TokenType.TypeDef; goto ret; case 1: token_type = TokenType.Method; goto ret; default: goto exit; } default: goto exit; } ret: return new MetadataToken (token_type, rid); exit: return MetadataToken.Zero; } #if !READ_ONLY public static uint CompressMetadataToken (this CodedIndex self, MetadataToken token) { uint ret = 0; if (token.RID == 0) return ret; switch (self) { case CodedIndex.TypeDefOrRef: ret = token.RID << 2; switch (token.TokenType) { case TokenType.TypeDef: return ret | 0; case TokenType.TypeRef: return ret | 1; case TokenType.TypeSpec: return ret | 2; default: goto exit; } case CodedIndex.HasConstant: ret = token.RID << 2; switch (token.TokenType) { case TokenType.Field: return ret | 0; case TokenType.Param: return ret | 1; case TokenType.Property: return ret | 2; default: goto exit; } case CodedIndex.HasCustomAttribute: ret = token.RID << 5; switch (token.TokenType) { case TokenType.Method: return ret | 0; case TokenType.Field: return ret | 1; case TokenType.TypeRef: return ret | 2; case TokenType.TypeDef: return ret | 3; case TokenType.Param: return ret | 4; case TokenType.InterfaceImpl: return ret | 5; case TokenType.MemberRef: return ret | 6; case TokenType.Module: return ret | 7; case TokenType.Permission: return ret | 8; case TokenType.Property: return ret | 9; case TokenType.Event: return ret | 10; case TokenType.Signature: return ret | 11; case TokenType.ModuleRef: return ret | 12; case TokenType.TypeSpec: return ret | 13; case TokenType.Assembly: return ret | 14; case TokenType.AssemblyRef: return ret | 15; case TokenType.File: return ret | 16; case TokenType.ExportedType: return ret | 17; case TokenType.ManifestResource: return ret | 18; case TokenType.GenericParam: return ret | 19; default: goto exit; } case CodedIndex.HasFieldMarshal: ret = token.RID << 1; switch (token.TokenType) { case TokenType.Field: return ret | 0; case TokenType.Param: return ret | 1; default: goto exit; } case CodedIndex.HasDeclSecurity: ret = token.RID << 2; switch (token.TokenType) { case TokenType.TypeDef: return ret | 0; case TokenType.Method: return ret | 1; case TokenType.Assembly: return ret | 2; default: goto exit; } case CodedIndex.MemberRefParent: ret = token.RID << 3; switch (token.TokenType) { case TokenType.TypeDef: return ret | 0; case TokenType.TypeRef: return ret | 1; case TokenType.ModuleRef: return ret | 2; case TokenType.Method: return ret | 3; case TokenType.TypeSpec: return ret | 4; default: goto exit; } case CodedIndex.HasSemantics: ret = token.RID << 1; switch (token.TokenType) { case TokenType.Event: return ret | 0; case TokenType.Property: return ret | 1; default: goto exit; } case CodedIndex.MethodDefOrRef: ret = token.RID << 1; switch (token.TokenType) { case TokenType.Method: return ret | 0; case TokenType.MemberRef: return ret | 1; default: goto exit; } case CodedIndex.MemberForwarded: ret = token.RID << 1; switch (token.TokenType) { case TokenType.Field: return ret | 0; case TokenType.Method: return ret | 1; default: goto exit; } case CodedIndex.Implementation: ret = token.RID << 2; switch (token.TokenType) { case TokenType.File: return ret | 0; case TokenType.AssemblyRef: return ret | 1; case TokenType.ExportedType: return ret | 2; default: goto exit; } case CodedIndex.CustomAttributeType: ret = token.RID << 3; switch (token.TokenType) { case TokenType.Method: return ret | 2; case TokenType.MemberRef: return ret | 3; default: goto exit; } case CodedIndex.ResolutionScope: ret = token.RID << 2; switch (token.TokenType) { case TokenType.Module: return ret | 0; case TokenType.ModuleRef: return ret | 1; case TokenType.AssemblyRef: return ret | 2; case TokenType.TypeRef: return ret | 3; default: goto exit; } case CodedIndex.TypeOrMethodDef: ret = token.RID << 1; switch (token.TokenType) { case TokenType.TypeDef: return ret | 0; case TokenType.Method: return ret | 1; default: goto exit; } default: goto exit; } exit: throw new ArgumentException (); } #endif public static int GetSize (this CodedIndex self, Func<Table, int> counter) { int bits; Table [] tables; switch (self) { case CodedIndex.TypeDefOrRef: bits = 2; tables = new [] { Table.TypeDef, Table.TypeRef, Table.TypeSpec }; break; case CodedIndex.HasConstant: bits = 2; tables = new [] { Table.Field, Table.Param, Table.Property }; break; case CodedIndex.HasCustomAttribute: bits = 5; tables = new [] { Table.Method, Table.Field, Table.TypeRef, Table.TypeDef, Table.Param, Table.InterfaceImpl, Table.MemberRef, Table.Module, Table.DeclSecurity, Table.Property, Table.Event, Table.StandAloneSig, Table.ModuleRef, Table.TypeSpec, Table.Assembly, Table.AssemblyRef, Table.File, Table.ExportedType, Table.ManifestResource, Table.GenericParam }; break; case CodedIndex.HasFieldMarshal: bits = 1; tables = new [] { Table.Field, Table.Param }; break; case CodedIndex.HasDeclSecurity: bits = 2; tables = new [] { Table.TypeDef, Table.Method, Table.Assembly }; break; case CodedIndex.MemberRefParent: bits = 3; tables = new [] { Table.TypeDef, Table.TypeRef, Table.ModuleRef, Table.Method, Table.TypeSpec }; break; case CodedIndex.HasSemantics: bits = 1; tables = new [] { Table.Event, Table.Property }; break; case CodedIndex.MethodDefOrRef: bits = 1; tables = new [] { Table.Method, Table.MemberRef }; break; case CodedIndex.MemberForwarded: bits = 1; tables = new [] { Table.Field, Table.Method }; break; case CodedIndex.Implementation: bits = 2; tables = new [] { Table.File, Table.AssemblyRef, Table.ExportedType }; break; case CodedIndex.CustomAttributeType: bits = 3; tables = new [] { Table.Method, Table.MemberRef }; break; case CodedIndex.ResolutionScope: bits = 2; tables = new [] { Table.Module, Table.ModuleRef, Table.AssemblyRef, Table.TypeRef }; break; case CodedIndex.TypeOrMethodDef: bits = 1; tables = new [] { Table.TypeDef, Table.Method }; break; default: throw new ArgumentException (); } int max = 0; for (int i = 0; i < tables.Length; i++) { max = System.Math.Max (counter (tables [i]), max); } return max < (1 << (16 - bits)) ? 2 : 4; } } }
25.881132
112
0.629219
[ "Apache-2.0" ]
Sectoid/debian-mono
mcs/class/Mono.Cecil/Mono.Cecil.Metadata/Utilities.cs
13,717
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Devices.Midi { #if false || false || false || false || false || false || false [global::Uno.NotImplemented] #endif public partial class MidiControlChangeMessage : global::Windows.Devices.Midi.IMidiMessage { // Skipping already declared property Channel // Skipping already declared property ControlValue // Skipping already declared property Controller // Skipping already declared property RawData // Skipping already declared property Timestamp // Skipping already declared property Type // Skipping already declared method Windows.Devices.Midi.MidiControlChangeMessage.MidiControlChangeMessage(byte, byte, byte) // Forced skipping of method Windows.Devices.Midi.MidiControlChangeMessage.MidiControlChangeMessage(byte, byte, byte) // Forced skipping of method Windows.Devices.Midi.MidiControlChangeMessage.Channel.get // Forced skipping of method Windows.Devices.Midi.MidiControlChangeMessage.Controller.get // Forced skipping of method Windows.Devices.Midi.MidiControlChangeMessage.ControlValue.get // Forced skipping of method Windows.Devices.Midi.MidiControlChangeMessage.Timestamp.get // Forced skipping of method Windows.Devices.Midi.MidiControlChangeMessage.RawData.get // Forced skipping of method Windows.Devices.Midi.MidiControlChangeMessage.Type.get // Processing: Windows.Devices.Midi.IMidiMessage } }
54.444444
126
0.803401
[ "Apache-2.0" ]
AbdalaMask/uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.Midi/MidiControlChangeMessage.cs
1,470
C#
namespace WSF.Shell.Interop { using WSF.Shell.Enums; using System; /// <summary> /// Contains information used by ShellExecuteEx. /// </summary> internal struct SHELLEXECUTEINFO { /// <summary> /// Required. The size of this structure, in bytes. /// </summary> public int cbSize; /// <summary> /// Flags that indicate the content and validity of the other structure members. /// </summary> public SEE fMask; /// <summary> /// Optional. A handle to the parent window, used to display any message boxes that the system might produce while executing this function. This value can be NULL. /// </summary> public IntPtr hwnd; /// <summary> /// A string, referred to as a verb, that specifies the action to be performed. The set of available verbs depends on the particular file or folder. Generally, the actions available from an object's shortcut menu are available verbs. This parameter can be NULL, in which case the default verb is used if available. If not, the "open" verb is used. If neither verb is available, the system uses the first verb listed in the registry. /// </summary> public string lpVerb; /// <summary> /// The address of a null-terminated string that specifies the name of the file or object on which ShellExecuteEx will perform the action specified by the lpVerb parameter. The system registry verbs that are supported by the ShellExecuteEx function include "open" for executable files and document files and "print" for document files for which a print handler has been registered. Other applications might have added Shell verbs through the system registry, such as "play" for .avi and .wav files. To specify a Shell namespace object, pass the fully qualified parse name and set the SEE_MASK_INVOKEIDLIST flag in the fMask parameter. /// </summary> public string lpFile; /// <summary> /// Optional. The address of a null-terminated string that contains the application parameters. The parameters must be separated by spaces. If the lpFile member specifies a document file, lpParameters should be NULL. /// </summary> public string lpParameters; /// <summary> /// Optional. The address of a null-terminated string that specifies the name of the working directory. If this member is NULL, the current directory is used as the working directory. /// </summary> public string lpDirectory; /// <summary> /// Required. Flags that specify how an application is to be shown when it is opened; one of the SW_ values listed for the ShellExecute function. If lpFile specifies a document file, the flag is simply passed to the associated application. It is up to the application to decide how to handle it. /// </summary> public int nShow; /// <summary> /// [out] If SEE_MASK_NOCLOSEPROCESS is set and the ShellExecuteEx call succeeds, it sets this member to a value greater than 32. If the function fails, it is set to an SE_ERR_XXX error value that indicates the cause of the failure. Although hInstApp is declared as an HINSTANCE for compatibility with 16-bit Windows applications, it is not a true HINSTANCE. It can be cast only to an int and compared to either 32 or the following SE_ERR_XXX error codes. /// </summary> public IntPtr hInstApp; /// <summary> /// The address of an absolute ITEMIDLIST structure (PCIDLIST_ABSOLUTE) to contain an item identifier list that uniquely identifies the file to execute. This member is ignored if the fMask member does not include SEE_MASK_IDLIST or SEE_MASK_INVOKEIDLIST. /// </summary> public IntPtr lpIDList; /// <summary> /// The address of a null-terminated string that specifies one of the following: /// A ProgId. For example, "Paint.Picture". /// A URI protocol scheme. For example, "http". /// A file extension. For example, ".txt". /// A registry path under HKEY_CLASSES_ROOT that names a subkey that contains one or more Shell verbs. This key will have a subkey that conforms to the Shell verb registry schema, such as /// shell\verb name /// </summary> public string lpClass; /// <summary> /// A handle to the registry key for the file type. The access rights for this registry key should be set to KEY_READ. This member is ignored if fMask does not include SEE_MASK_CLASSKEY. /// </summary> public IntPtr hkeyClass; /// <summary> /// A keyboard shortcut to associate with the application. The low-order word is the virtual key code, and the high-order word is a modifier flag (HOTKEYF_). For a list of modifier flags, see the description of the WM_SETHOTKEY message. This member is ignored if fMask does not include SEE_MASK_HOTKEY. /// </summary> public int dwHotKey; /// <summary> /// A handle to the icon for the file type. This member is ignored if fMask does not include SEE_MASK_ICON. This value is used only in Windows XP and earlier. It is ignored as of Windows Vista. /// </summary> public IntPtr hIcon; /// <summary> /// A handle to the monitor upon which the document is to be displayed. This member is ignored if fMask does not include SEE_MASK_HMONITOR. /// </summary> public IntPtr hProcess; } }
61.131868
642
0.683983
[ "MIT" ]
Dirkster99/WSF
source/WSF/Shell/Interop/SHELLEXECUTEINFO.cs
5,565
C#
// CodeContracts // // Copyright (c) Microsoft Corporation // // All rights reserved. // // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // File System.Security.Principal.IIdentity.cs // Automatically generated contract file. using System.Collections.Generic; using System.IO; using System.Text; using System.Diagnostics.Contracts; using System; // Disable the "this variable is not used" warning as every field would imply it. #pragma warning disable 0414 // Disable the "this variable is never assigned to". #pragma warning disable 0067 // Disable the "this event is never assigned to". #pragma warning disable 0649 // Disable the "this variable is never used". #pragma warning disable 0169 // Disable the "new keyword not required" warning. #pragma warning disable 0109 // Disable the "extern without DllImport" warning. #pragma warning disable 0626 // Disable the "could hide other member" warning, can happen on certain properties. #pragma warning disable 0108 namespace System.Security.Principal { public partial interface IIdentity { #region Properties and indexers string AuthenticationType { get; } bool IsAuthenticated { get; } string Name { get; } #endregion } }
37.065574
463
0.755418
[ "MIT" ]
Acidburn0zzz/CodeContracts
Microsoft.Research/Contracts/MsCorlib/Sources/System.Security.Principal.IIdentity.cs
2,261
C#
using System; using System.IO; namespace Protobuild { internal class DefaultCommand : ICommand { private readonly IActionDispatch m_ActionDispatch; private readonly IKnownToolProvider _knownToolProvider; private readonly ExecuteCommand _executeCommand; private readonly IAutomatedBuildController _automatedBuildController; public DefaultCommand(IActionDispatch actionDispatch, IKnownToolProvider knownToolProvider, ExecuteCommand executeCommand, IAutomatedBuildController automatedBuildController) { this.m_ActionDispatch = actionDispatch; _knownToolProvider = knownToolProvider; _executeCommand = executeCommand; _automatedBuildController = automatedBuildController; } public void Encounter(Execution pendingExecution, string[] args) { throw new NotSupportedException(); } public int Execute(Execution execution) { if (!File.Exists(Path.Combine(execution.WorkingDirectory, "Build", "Module.xml"))) { _knownToolProvider.GetToolExecutablePath("Protobuild.Manager"); var subexecution = new Execution(); subexecution.WorkingDirectory = execution.WorkingDirectory; subexecution.ExecuteProjectName = "Protobuild.Manager"; subexecution.ExecuteProjectArguments = new string[0]; return _executeCommand.Execute(subexecution); } var module = ModuleInfo.Load(Path.Combine(execution.WorkingDirectory, "Build", "Module.xml")); if (module.DefaultAction == "automated-build") { return _automatedBuildController.Execute(execution.WorkingDirectory, "automated.build"); } return this.m_ActionDispatch.DefaultAction( execution.WorkingDirectory, module, null, execution.EnabledServices.ToArray(), execution.DisabledServices.ToArray(), execution.ServiceSpecificationPath, execution.DebugServiceResolution, execution.DisablePackageResolution, execution.DisableHostProjectGeneration, execution.UseTaskParallelisation, execution.SafePackageResolution, execution.DebugProjectGeneration) ? 0 : 1; } public string GetShortCategory() { return "Internal use"; } public string GetShortDescription() { throw new NotSupportedException(); } public string GetDescription() { throw new NotSupportedException(); } public string[] GetShortArgNames() { return GetArgNames(); } public int GetArgCount() { throw new NotSupportedException(); } public string[] GetArgNames() { throw new NotSupportedException(); } public bool IsInternal() { return false; } public bool IsRecognised() { return true; } public bool IsIgnored() { return false; } } }
30.236364
182
0.597715
[ "MIT" ]
Protobuild/Protobuild
Protobuild.Internal/CommandLine/DefaultCommand.cs
3,328
C#
using Box2DSharp.Collision.Shapes; using Box2DSharp.Dynamics; using OpenToolkit.Windowing.Common; using OpenToolkit.Windowing.Common.Input; using Testbed.Basics; using Debug = System.Diagnostics.Debug; using Vector2 = System.Numerics.Vector2; namespace Testbed.Tests { [TestCase("Stacking", "Boxes")] public class BoxStack : Test { private const int ColumnCount = 1; private const int RowCount = 15; private Body _bullet; private readonly Body[] _bodies = new Body [RowCount * ColumnCount]; private readonly int[] _indices = new int[RowCount * ColumnCount]; public BoxStack() { { var bd = new BodyDef(); var ground = World.CreateBody(bd); var shape = new EdgeShape(); shape.SetTwoSided(new V2(-40.0f, 0.0f), new V2(40.0f, 0.0f)); ground.CreateFixture(shape, 0.0f); shape.SetTwoSided(new V2(20.0f, 0.0f), new V2(20.0f, 20.0f)); ground.CreateFixture(shape, 0.0f); } var xs = new float[5] { 0.0f, -10.0f, -5.0f, 5.0f, 10.0f }; for (var j = 0; j < ColumnCount; ++j) { var shape = new PolygonShape(); shape.SetAsBox(0.5f, 0.5f); var fd = new FixtureDef { Shape = shape, Density = 1.0f, Friction = 0.3f }; for (var i = 0; i < RowCount; ++i) { var bd = new BodyDef {BodyType = BodyType.DynamicBody}; var n = j * RowCount + i; Debug.Assert(n < RowCount * ColumnCount); _indices[n] = n; bd.UserData = _indices[n]; var x = 0.0f; //var x = RandomFloat(-0.02f, 0.02f); //var x = i % 2 == 0 ? -0.01f : 0.01f; bd.Position = new V2(xs[j] + x, 0.55f + 1.1f * i); var body = World.CreateBody(bd); _bodies[n] = body; body.CreateFixture(fd); } } _bullet = null; } /// <inheritdoc /> /// <inheritdoc /> public override void OnKeyDown(KeyboardKeyEventArgs key) { if (key.Key == Key.F) { if (_bullet != null) { World.DestroyBody(_bullet); _bullet = null; } { var shape = new CircleShape {Radius = 0.25f}; var fd = new FixtureDef { Shape = shape, Density = 20.0f, Restitution = 0.05f }; var bd = new BodyDef { BodyType = BodyType.DynamicBody, Bullet = true, Position = new V2(-31.0f, 5.0f) }; _bullet = World.CreateBody(bd); _bullet.CreateFixture(fd); _bullet.SetLinearVelocity(new V2(400.0f, 0.0f)); } } } protected override void OnRender() { DrawString("Press F to launch a bullet"); } } }
29.186441
77
0.434379
[ "MIT" ]
Lordinarius/Box2DSharp
test/Testbed/Tests/BoxStack.cs
3,444
C#
using System; namespace sistema_bodega.Data { public class ProductoBodegaEmpleado { public int Id { get; set; } public int ProductoId { get; set; } public Producto Producto { get; set; } public int BodegaId { get; set; } public Bodega Bodega { get; set; } public int EmpleadoId { get; set; } public Empleado Empleado { get; set; } public DateTime Fecha { get; set; } public int Cantidad { get; set; } } }
28.764706
46
0.591002
[ "MIT" ]
Matthew-Gonzalez/sistema-bodega-middleware
sistema_bodega/Data/ProductoBodegaEmpleado.cs
489
C#
namespace Arduino.Firmata.Protocol.Firmata { /// <summary> /// Identifies the Arduino board's firmware. /// </summary> public struct Firmware { /// <summary> /// Gets the major version number. /// </summary> public int MajorVersion { get; internal set; } /// <summary> /// Gets the minor version number. /// </summary> public int MinorVersion { get; internal set; } /// <summary> /// Gets the name of the board's firmware. /// </summary> public string Name { get; internal set; } public override string ToString() { return $"{Name} V {MajorVersion}.{MinorVersion}"; } } }
26.107143
61
0.534884
[ "BSD-2-Clause" ]
mccj/Arduino.Firmata
src/Arduino.Firmata/Protocol/Firmata/Response/Firmware.cs
733
C#
using Microsoft.Sample.Automation.Scheduling.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Sample.Automation.Scheduling { public class ToolRepository : GenericRepository<Tool> { public ToolRepository(SchedulingContext context) : base(context) { } public override void Insert(Tool entity) { entity.LastModifiedDateTimeUtc = DateTime.UtcNow; dbSet.Add(entity); } public override void Update(Tool entityToUpdate) { var ori = this.context.Tools.Single(t => t.Id == entityToUpdate.Id); var entry = this.context.Entry(ori); entry.CurrentValues.SetValues(entityToUpdate); ori.CreatedDateTimeUtc = entry.Property(p => p.CreatedDateTimeUtc).OriginalValue; ori.LastModifiedDateTimeUtc = DateTime.UtcNow; } } }
31.866667
93
0.67364
[ "Apache-2.0" ]
leo-leong/wwt-scheduler
Microsoft.Sample.Automation/Scheduling/ToolRepository.cs
958
C#
// -------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. // -------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using Microsoft.Oryx.BuildScriptGenerator.Common; using Microsoft.Oryx.Integration.Tests.Fixtures; using Microsoft.Oryx.Tests.Common; using Xunit; using Xunit.Abstractions; namespace Microsoft.Oryx.Integration.Tests { [Trait("category", "php-5")] [Trait("db", "sqlserver")] public class PhpSqlServerIntegrationTests : PlatformEndToEndTestsBase { private const int ContainerPort = 3000; private const string DefaultStartupFilePath = "./run.sh"; public PhpSqlServerIntegrationTests(ITestOutputHelper output) : base(output, null) { } [Theory] [InlineData("7.3", "github-actions")] [InlineData("7.3", "github-actions-buster")] [InlineData("7.3", "latest")] [InlineData("7.4", "github-actions")] [InlineData("7.4", "github-actions-buster")] [InlineData("7.4", "latest")] [InlineData("8.0", "github-actions")] [InlineData("8.0", "github-actions-buster")] [InlineData("8.0", "latest")] // pdo_sqlsrv only supports PHP >= 7.3 public async Task PhpApp_UsingPdo(string phpVersion, string imageTag) { // Arrange var appName = "sqlsrv-example"; var hostDir = Path.Combine(_hostSamplesDir, "php", appName); var volume = DockerVolume.CreateMirror(hostDir); var appDir = volume.ContainerDir; var script = new ShellScriptBuilder() .AddCommand($"oryx create-script -appPath {appDir} -bindPort {ContainerPort}") .AddCommand(DefaultStartupFilePath) .ToString(); await EndToEndTestHelper.BuildRunAndAssertAppAsync( appName, _output, new List<DockerVolume> { volume }, _imageHelper.GetBuildImage(imageTag), "oryx", new[] { "build", appDir, "--platform", "php", "--platform-version", phpVersion }, _imageHelper.GetRuntimeImage("php", phpVersion), SqlServerDbTestHelper.GetEnvironmentVariables(), ContainerPort, "/bin/bash", new[] { "-c", script }, async (hostPort) => { var data = await _httpClient.GetStringAsync($"http://localhost:{hostPort}/"); Assert.Equal( DbContainerFixtureBase.GetSampleDataAsJson(), data.Trim(), ignoreLineEndingDifferences: true, ignoreWhiteSpaceDifferences: true); }); } } }
39.8
98
0.518216
[ "MIT" ]
carlosanjos/Oryx
tests/Oryx.Integration.Tests/Php/PhpSqlServerIntegrationTests.cs
3,107
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the cloudfront-2017-03-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.CloudFront.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using System.Xml; namespace Amazon.CloudFront.Model.Internal.MarshallTransformations { /// <summary> /// UpdateDistribution Request Marshaller /// </summary> public class UpdateDistributionRequestMarshaller : IMarshaller<IRequest, UpdateDistributionRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((UpdateDistributionRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(UpdateDistributionRequest publicRequest) { var request = new DefaultRequest(publicRequest, "Amazon.CloudFront"); request.HttpMethod = "PUT"; string uriResourcePath = "/2017-03-25/distribution/{Id}/config"; if(publicRequest.IsSetIfMatch()) request.Headers["If-Match"] = publicRequest.IfMatch; if (!publicRequest.IsSetId()) throw new AmazonCloudFrontException("Request object does not have required field Id set"); uriResourcePath = uriResourcePath.Replace("{Id}", StringUtils.FromString(publicRequest.Id)); request.ResourcePath = uriResourcePath; var stringWriter = new StringWriter(CultureInfo.InvariantCulture); using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings() { Encoding = System.Text.Encoding.UTF8, OmitXmlDeclaration = true })) { xmlWriter.WriteStartElement("DistributionConfig", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if (publicRequest.DistributionConfig.Aliases != null) { xmlWriter.WriteStartElement("Aliases", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigAliasesItems = publicRequest.DistributionConfig.Aliases.Items; if (publicRequestDistributionConfigAliasesItems != null && publicRequestDistributionConfigAliasesItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigAliasesItemsValue in publicRequestDistributionConfigAliasesItems) { xmlWriter.WriteStartElement("CNAME", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); xmlWriter.WriteValue(publicRequestDistributionConfigAliasesItemsValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.Aliases.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequest.DistributionConfig.Aliases.Quantity)); xmlWriter.WriteEndElement(); } if (publicRequest.DistributionConfig.CacheBehaviors != null) { xmlWriter.WriteStartElement("CacheBehaviors", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigCacheBehaviorsItems = publicRequest.DistributionConfig.CacheBehaviors.Items; if (publicRequestDistributionConfigCacheBehaviorsItems != null && publicRequestDistributionConfigCacheBehaviorsItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigCacheBehaviorsItemsValue in publicRequestDistributionConfigCacheBehaviorsItems) { if (publicRequestDistributionConfigCacheBehaviorsItemsValue != null) { xmlWriter.WriteStartElement("CacheBehavior", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if (publicRequestDistributionConfigCacheBehaviorsItemsValue.AllowedMethods != null) { xmlWriter.WriteStartElement("AllowedMethods", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if (publicRequestDistributionConfigCacheBehaviorsItemsValue.AllowedMethods.CachedMethods != null) { xmlWriter.WriteStartElement("CachedMethods", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsCachedMethodsItems = publicRequestDistributionConfigCacheBehaviorsItemsValue.AllowedMethods.CachedMethods.Items; if (publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsCachedMethodsItems != null && publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsCachedMethodsItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsCachedMethodsItemsValue in publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsCachedMethodsItems) { xmlWriter.WriteStartElement("Method", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); xmlWriter.WriteValue(publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsCachedMethodsItemsValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequestDistributionConfigCacheBehaviorsItemsValue.AllowedMethods.CachedMethods.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequestDistributionConfigCacheBehaviorsItemsValue.AllowedMethods.CachedMethods.Quantity)); xmlWriter.WriteEndElement(); } var publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsItems = publicRequestDistributionConfigCacheBehaviorsItemsValue.AllowedMethods.Items; if (publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsItems != null && publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsItemsValue in publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsItems) { xmlWriter.WriteStartElement("Method", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); xmlWriter.WriteValue(publicRequestDistributionConfigCacheBehaviorsItemsValueAllowedMethodsItemsValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequestDistributionConfigCacheBehaviorsItemsValue.AllowedMethods.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequestDistributionConfigCacheBehaviorsItemsValue.AllowedMethods.Quantity)); xmlWriter.WriteEndElement(); } if(publicRequestDistributionConfigCacheBehaviorsItemsValue.IsSetCompress()) xmlWriter.WriteElementString("Compress", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromBool(publicRequestDistributionConfigCacheBehaviorsItemsValue.Compress)); if(publicRequestDistributionConfigCacheBehaviorsItemsValue.IsSetDefaultTTL()) xmlWriter.WriteElementString("DefaultTTL", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromLong(publicRequestDistributionConfigCacheBehaviorsItemsValue.DefaultTTL)); if (publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues != null) { xmlWriter.WriteStartElement("ForwardedValues", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if (publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Cookies != null) { xmlWriter.WriteStartElement("Cookies", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Cookies.IsSetForward()) xmlWriter.WriteElementString("Forward", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Cookies.Forward)); if (publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Cookies.WhitelistedNames != null) { xmlWriter.WriteStartElement("WhitelistedNames", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesCookiesWhitelistedNamesItems = publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Cookies.WhitelistedNames.Items; if (publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesCookiesWhitelistedNamesItems != null && publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesCookiesWhitelistedNamesItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesCookiesWhitelistedNamesItemsValue in publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesCookiesWhitelistedNamesItems) { xmlWriter.WriteStartElement("Name", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); xmlWriter.WriteValue(publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesCookiesWhitelistedNamesItemsValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Cookies.WhitelistedNames.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Cookies.WhitelistedNames.Quantity)); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if (publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Headers != null) { xmlWriter.WriteStartElement("Headers", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesHeadersItems = publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Headers.Items; if (publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesHeadersItems != null && publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesHeadersItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesHeadersItemsValue in publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesHeadersItems) { xmlWriter.WriteStartElement("Name", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); xmlWriter.WriteValue(publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesHeadersItemsValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Headers.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.Headers.Quantity)); xmlWriter.WriteEndElement(); } if(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.IsSetQueryString()) xmlWriter.WriteElementString("QueryString", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromBool(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.QueryString)); if (publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.QueryStringCacheKeys != null) { xmlWriter.WriteStartElement("QueryStringCacheKeys", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesQueryStringCacheKeysItems = publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.QueryStringCacheKeys.Items; if (publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesQueryStringCacheKeysItems != null && publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesQueryStringCacheKeysItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesQueryStringCacheKeysItemsValue in publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesQueryStringCacheKeysItems) { xmlWriter.WriteStartElement("Name", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); xmlWriter.WriteValue(publicRequestDistributionConfigCacheBehaviorsItemsValueForwardedValuesQueryStringCacheKeysItemsValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.QueryStringCacheKeys.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequestDistributionConfigCacheBehaviorsItemsValue.ForwardedValues.QueryStringCacheKeys.Quantity)); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if (publicRequestDistributionConfigCacheBehaviorsItemsValue.LambdaFunctionAssociations != null) { xmlWriter.WriteStartElement("LambdaFunctionAssociations", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigCacheBehaviorsItemsValueLambdaFunctionAssociationsItems = publicRequestDistributionConfigCacheBehaviorsItemsValue.LambdaFunctionAssociations.Items; if (publicRequestDistributionConfigCacheBehaviorsItemsValueLambdaFunctionAssociationsItems != null && publicRequestDistributionConfigCacheBehaviorsItemsValueLambdaFunctionAssociationsItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigCacheBehaviorsItemsValueLambdaFunctionAssociationsItemsValue in publicRequestDistributionConfigCacheBehaviorsItemsValueLambdaFunctionAssociationsItems) { if (publicRequestDistributionConfigCacheBehaviorsItemsValueLambdaFunctionAssociationsItemsValue != null) { xmlWriter.WriteStartElement("LambdaFunctionAssociation", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if(publicRequestDistributionConfigCacheBehaviorsItemsValueLambdaFunctionAssociationsItemsValue.IsSetEventType()) xmlWriter.WriteElementString("EventType", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigCacheBehaviorsItemsValueLambdaFunctionAssociationsItemsValue.EventType)); if(publicRequestDistributionConfigCacheBehaviorsItemsValueLambdaFunctionAssociationsItemsValue.IsSetLambdaFunctionARN()) xmlWriter.WriteElementString("LambdaFunctionARN", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigCacheBehaviorsItemsValueLambdaFunctionAssociationsItemsValue.LambdaFunctionARN)); xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } if(publicRequestDistributionConfigCacheBehaviorsItemsValue.LambdaFunctionAssociations.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequestDistributionConfigCacheBehaviorsItemsValue.LambdaFunctionAssociations.Quantity)); xmlWriter.WriteEndElement(); } if(publicRequestDistributionConfigCacheBehaviorsItemsValue.IsSetMaxTTL()) xmlWriter.WriteElementString("MaxTTL", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromLong(publicRequestDistributionConfigCacheBehaviorsItemsValue.MaxTTL)); if(publicRequestDistributionConfigCacheBehaviorsItemsValue.IsSetMinTTL()) xmlWriter.WriteElementString("MinTTL", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromLong(publicRequestDistributionConfigCacheBehaviorsItemsValue.MinTTL)); if(publicRequestDistributionConfigCacheBehaviorsItemsValue.IsSetPathPattern()) xmlWriter.WriteElementString("PathPattern", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigCacheBehaviorsItemsValue.PathPattern)); if(publicRequestDistributionConfigCacheBehaviorsItemsValue.IsSetSmoothStreaming()) xmlWriter.WriteElementString("SmoothStreaming", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromBool(publicRequestDistributionConfigCacheBehaviorsItemsValue.SmoothStreaming)); if(publicRequestDistributionConfigCacheBehaviorsItemsValue.IsSetTargetOriginId()) xmlWriter.WriteElementString("TargetOriginId", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigCacheBehaviorsItemsValue.TargetOriginId)); if (publicRequestDistributionConfigCacheBehaviorsItemsValue.TrustedSigners != null) { xmlWriter.WriteStartElement("TrustedSigners", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if(publicRequestDistributionConfigCacheBehaviorsItemsValue.TrustedSigners.IsSetEnabled()) xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromBool(publicRequestDistributionConfigCacheBehaviorsItemsValue.TrustedSigners.Enabled)); var publicRequestDistributionConfigCacheBehaviorsItemsValueTrustedSignersItems = publicRequestDistributionConfigCacheBehaviorsItemsValue.TrustedSigners.Items; if (publicRequestDistributionConfigCacheBehaviorsItemsValueTrustedSignersItems != null && publicRequestDistributionConfigCacheBehaviorsItemsValueTrustedSignersItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigCacheBehaviorsItemsValueTrustedSignersItemsValue in publicRequestDistributionConfigCacheBehaviorsItemsValueTrustedSignersItems) { xmlWriter.WriteStartElement("AwsAccountNumber", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); xmlWriter.WriteValue(publicRequestDistributionConfigCacheBehaviorsItemsValueTrustedSignersItemsValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequestDistributionConfigCacheBehaviorsItemsValue.TrustedSigners.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequestDistributionConfigCacheBehaviorsItemsValue.TrustedSigners.Quantity)); xmlWriter.WriteEndElement(); } if(publicRequestDistributionConfigCacheBehaviorsItemsValue.IsSetViewerProtocolPolicy()) xmlWriter.WriteElementString("ViewerProtocolPolicy", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigCacheBehaviorsItemsValue.ViewerProtocolPolicy)); xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.CacheBehaviors.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequest.DistributionConfig.CacheBehaviors.Quantity)); xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.IsSetCallerReference()) xmlWriter.WriteElementString("CallerReference", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.CallerReference)); if(publicRequest.DistributionConfig.IsSetComment()) xmlWriter.WriteElementString("Comment", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.Comment)); if (publicRequest.DistributionConfig.CustomErrorResponses != null) { xmlWriter.WriteStartElement("CustomErrorResponses", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigCustomErrorResponsesItems = publicRequest.DistributionConfig.CustomErrorResponses.Items; if (publicRequestDistributionConfigCustomErrorResponsesItems != null && publicRequestDistributionConfigCustomErrorResponsesItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigCustomErrorResponsesItemsValue in publicRequestDistributionConfigCustomErrorResponsesItems) { if (publicRequestDistributionConfigCustomErrorResponsesItemsValue != null) { xmlWriter.WriteStartElement("CustomErrorResponse", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if(publicRequestDistributionConfigCustomErrorResponsesItemsValue.IsSetErrorCachingMinTTL()) xmlWriter.WriteElementString("ErrorCachingMinTTL", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromLong(publicRequestDistributionConfigCustomErrorResponsesItemsValue.ErrorCachingMinTTL)); if(publicRequestDistributionConfigCustomErrorResponsesItemsValue.IsSetErrorCode()) xmlWriter.WriteElementString("ErrorCode", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequestDistributionConfigCustomErrorResponsesItemsValue.ErrorCode)); if(publicRequestDistributionConfigCustomErrorResponsesItemsValue.IsSetResponseCode()) xmlWriter.WriteElementString("ResponseCode", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigCustomErrorResponsesItemsValue.ResponseCode)); if(publicRequestDistributionConfigCustomErrorResponsesItemsValue.IsSetResponsePagePath()) xmlWriter.WriteElementString("ResponsePagePath", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigCustomErrorResponsesItemsValue.ResponsePagePath)); xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.CustomErrorResponses.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequest.DistributionConfig.CustomErrorResponses.Quantity)); xmlWriter.WriteEndElement(); } if (publicRequest.DistributionConfig.DefaultCacheBehavior != null) { xmlWriter.WriteStartElement("DefaultCacheBehavior", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if (publicRequest.DistributionConfig.DefaultCacheBehavior.AllowedMethods != null) { xmlWriter.WriteStartElement("AllowedMethods", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if (publicRequest.DistributionConfig.DefaultCacheBehavior.AllowedMethods.CachedMethods != null) { xmlWriter.WriteStartElement("CachedMethods", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsCachedMethodsItems = publicRequest.DistributionConfig.DefaultCacheBehavior.AllowedMethods.CachedMethods.Items; if (publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsCachedMethodsItems != null && publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsCachedMethodsItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsCachedMethodsItemsValue in publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsCachedMethodsItems) { xmlWriter.WriteStartElement("Method", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); xmlWriter.WriteValue(publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsCachedMethodsItemsValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.DefaultCacheBehavior.AllowedMethods.CachedMethods.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequest.DistributionConfig.DefaultCacheBehavior.AllowedMethods.CachedMethods.Quantity)); xmlWriter.WriteEndElement(); } var publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsItems = publicRequest.DistributionConfig.DefaultCacheBehavior.AllowedMethods.Items; if (publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsItems != null && publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsItemsValue in publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsItems) { xmlWriter.WriteStartElement("Method", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); xmlWriter.WriteValue(publicRequestDistributionConfigDefaultCacheBehaviorAllowedMethodsItemsValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.DefaultCacheBehavior.AllowedMethods.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequest.DistributionConfig.DefaultCacheBehavior.AllowedMethods.Quantity)); xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.DefaultCacheBehavior.IsSetCompress()) xmlWriter.WriteElementString("Compress", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromBool(publicRequest.DistributionConfig.DefaultCacheBehavior.Compress)); if(publicRequest.DistributionConfig.DefaultCacheBehavior.IsSetDefaultTTL()) xmlWriter.WriteElementString("DefaultTTL", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromLong(publicRequest.DistributionConfig.DefaultCacheBehavior.DefaultTTL)); if (publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues != null) { xmlWriter.WriteStartElement("ForwardedValues", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if (publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies != null) { xmlWriter.WriteStartElement("Cookies", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.IsSetForward()) xmlWriter.WriteElementString("Forward", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.Forward)); if (publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.WhitelistedNames != null) { xmlWriter.WriteStartElement("WhitelistedNames", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesItems = publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.WhitelistedNames.Items; if (publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesItems != null && publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesItemsValue in publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesItems) { xmlWriter.WriteStartElement("Name", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); xmlWriter.WriteValue(publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesCookiesWhitelistedNamesItemsValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.WhitelistedNames.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Cookies.WhitelistedNames.Quantity)); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if (publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Headers != null) { xmlWriter.WriteStartElement("Headers", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesHeadersItems = publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Headers.Items; if (publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesHeadersItems != null && publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesHeadersItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesHeadersItemsValue in publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesHeadersItems) { xmlWriter.WriteStartElement("Name", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); xmlWriter.WriteValue(publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesHeadersItemsValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Headers.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.Headers.Quantity)); xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.IsSetQueryString()) xmlWriter.WriteElementString("QueryString", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromBool(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.QueryString)); if (publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.QueryStringCacheKeys != null) { xmlWriter.WriteStartElement("QueryStringCacheKeys", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesQueryStringCacheKeysItems = publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.QueryStringCacheKeys.Items; if (publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesQueryStringCacheKeysItems != null && publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesQueryStringCacheKeysItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesQueryStringCacheKeysItemsValue in publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesQueryStringCacheKeysItems) { xmlWriter.WriteStartElement("Name", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); xmlWriter.WriteValue(publicRequestDistributionConfigDefaultCacheBehaviorForwardedValuesQueryStringCacheKeysItemsValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.QueryStringCacheKeys.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequest.DistributionConfig.DefaultCacheBehavior.ForwardedValues.QueryStringCacheKeys.Quantity)); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if (publicRequest.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations != null) { xmlWriter.WriteStartElement("LambdaFunctionAssociations", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigDefaultCacheBehaviorLambdaFunctionAssociationsItems = publicRequest.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations.Items; if (publicRequestDistributionConfigDefaultCacheBehaviorLambdaFunctionAssociationsItems != null && publicRequestDistributionConfigDefaultCacheBehaviorLambdaFunctionAssociationsItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigDefaultCacheBehaviorLambdaFunctionAssociationsItemsValue in publicRequestDistributionConfigDefaultCacheBehaviorLambdaFunctionAssociationsItems) { if (publicRequestDistributionConfigDefaultCacheBehaviorLambdaFunctionAssociationsItemsValue != null) { xmlWriter.WriteStartElement("LambdaFunctionAssociation", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if(publicRequestDistributionConfigDefaultCacheBehaviorLambdaFunctionAssociationsItemsValue.IsSetEventType()) xmlWriter.WriteElementString("EventType", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigDefaultCacheBehaviorLambdaFunctionAssociationsItemsValue.EventType)); if(publicRequestDistributionConfigDefaultCacheBehaviorLambdaFunctionAssociationsItemsValue.IsSetLambdaFunctionARN()) xmlWriter.WriteElementString("LambdaFunctionARN", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigDefaultCacheBehaviorLambdaFunctionAssociationsItemsValue.LambdaFunctionARN)); xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequest.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations.Quantity)); xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.DefaultCacheBehavior.IsSetMaxTTL()) xmlWriter.WriteElementString("MaxTTL", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromLong(publicRequest.DistributionConfig.DefaultCacheBehavior.MaxTTL)); if(publicRequest.DistributionConfig.DefaultCacheBehavior.IsSetMinTTL()) xmlWriter.WriteElementString("MinTTL", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromLong(publicRequest.DistributionConfig.DefaultCacheBehavior.MinTTL)); if(publicRequest.DistributionConfig.DefaultCacheBehavior.IsSetSmoothStreaming()) xmlWriter.WriteElementString("SmoothStreaming", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromBool(publicRequest.DistributionConfig.DefaultCacheBehavior.SmoothStreaming)); if(publicRequest.DistributionConfig.DefaultCacheBehavior.IsSetTargetOriginId()) xmlWriter.WriteElementString("TargetOriginId", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.DefaultCacheBehavior.TargetOriginId)); if (publicRequest.DistributionConfig.DefaultCacheBehavior.TrustedSigners != null) { xmlWriter.WriteStartElement("TrustedSigners", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if(publicRequest.DistributionConfig.DefaultCacheBehavior.TrustedSigners.IsSetEnabled()) xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromBool(publicRequest.DistributionConfig.DefaultCacheBehavior.TrustedSigners.Enabled)); var publicRequestDistributionConfigDefaultCacheBehaviorTrustedSignersItems = publicRequest.DistributionConfig.DefaultCacheBehavior.TrustedSigners.Items; if (publicRequestDistributionConfigDefaultCacheBehaviorTrustedSignersItems != null && publicRequestDistributionConfigDefaultCacheBehaviorTrustedSignersItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigDefaultCacheBehaviorTrustedSignersItemsValue in publicRequestDistributionConfigDefaultCacheBehaviorTrustedSignersItems) { xmlWriter.WriteStartElement("AwsAccountNumber", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); xmlWriter.WriteValue(publicRequestDistributionConfigDefaultCacheBehaviorTrustedSignersItemsValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.DefaultCacheBehavior.TrustedSigners.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequest.DistributionConfig.DefaultCacheBehavior.TrustedSigners.Quantity)); xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.DefaultCacheBehavior.IsSetViewerProtocolPolicy()) xmlWriter.WriteElementString("ViewerProtocolPolicy", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.DefaultCacheBehavior.ViewerProtocolPolicy)); xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.IsSetDefaultRootObject()) xmlWriter.WriteElementString("DefaultRootObject", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.DefaultRootObject)); if(publicRequest.DistributionConfig.IsSetEnabled()) xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromBool(publicRequest.DistributionConfig.Enabled)); if(publicRequest.DistributionConfig.IsSetHttpVersion()) xmlWriter.WriteElementString("HttpVersion", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.HttpVersion)); if(publicRequest.DistributionConfig.IsSetIsIPV6Enabled()) xmlWriter.WriteElementString("IsIPV6Enabled", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromBool(publicRequest.DistributionConfig.IsIPV6Enabled)); if (publicRequest.DistributionConfig.Logging != null) { xmlWriter.WriteStartElement("Logging", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if(publicRequest.DistributionConfig.Logging.IsSetBucket()) xmlWriter.WriteElementString("Bucket", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.Logging.Bucket)); if(publicRequest.DistributionConfig.Logging.IsSetEnabled()) xmlWriter.WriteElementString("Enabled", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromBool(publicRequest.DistributionConfig.Logging.Enabled)); if(publicRequest.DistributionConfig.Logging.IsSetIncludeCookies()) xmlWriter.WriteElementString("IncludeCookies", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromBool(publicRequest.DistributionConfig.Logging.IncludeCookies)); if(publicRequest.DistributionConfig.Logging.IsSetPrefix()) xmlWriter.WriteElementString("Prefix", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.Logging.Prefix)); xmlWriter.WriteEndElement(); } if (publicRequest.DistributionConfig.Origins != null) { xmlWriter.WriteStartElement("Origins", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigOriginsItems = publicRequest.DistributionConfig.Origins.Items; if (publicRequestDistributionConfigOriginsItems != null && publicRequestDistributionConfigOriginsItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigOriginsItemsValue in publicRequestDistributionConfigOriginsItems) { if (publicRequestDistributionConfigOriginsItemsValue != null) { xmlWriter.WriteStartElement("Origin", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if (publicRequestDistributionConfigOriginsItemsValue.CustomHeaders != null) { xmlWriter.WriteStartElement("CustomHeaders", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigOriginsItemsValueCustomHeadersItems = publicRequestDistributionConfigOriginsItemsValue.CustomHeaders.Items; if (publicRequestDistributionConfigOriginsItemsValueCustomHeadersItems != null && publicRequestDistributionConfigOriginsItemsValueCustomHeadersItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigOriginsItemsValueCustomHeadersItemsValue in publicRequestDistributionConfigOriginsItemsValueCustomHeadersItems) { if (publicRequestDistributionConfigOriginsItemsValueCustomHeadersItemsValue != null) { xmlWriter.WriteStartElement("OriginCustomHeader", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if(publicRequestDistributionConfigOriginsItemsValueCustomHeadersItemsValue.IsSetHeaderName()) xmlWriter.WriteElementString("HeaderName", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigOriginsItemsValueCustomHeadersItemsValue.HeaderName)); if(publicRequestDistributionConfigOriginsItemsValueCustomHeadersItemsValue.IsSetHeaderValue()) xmlWriter.WriteElementString("HeaderValue", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigOriginsItemsValueCustomHeadersItemsValue.HeaderValue)); xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } if(publicRequestDistributionConfigOriginsItemsValue.CustomHeaders.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequestDistributionConfigOriginsItemsValue.CustomHeaders.Quantity)); xmlWriter.WriteEndElement(); } if (publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig != null) { xmlWriter.WriteStartElement("CustomOriginConfig", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.IsSetHTTPPort()) xmlWriter.WriteElementString("HTTPPort", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.HTTPPort)); if(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.IsSetHTTPSPort()) xmlWriter.WriteElementString("HTTPSPort", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.HTTPSPort)); if(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.IsSetOriginKeepaliveTimeout()) xmlWriter.WriteElementString("OriginKeepaliveTimeout", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.OriginKeepaliveTimeout)); if(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.IsSetOriginProtocolPolicy()) xmlWriter.WriteElementString("OriginProtocolPolicy", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.OriginProtocolPolicy)); if(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.IsSetOriginReadTimeout()) xmlWriter.WriteElementString("OriginReadTimeout", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.OriginReadTimeout)); if (publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.OriginSslProtocols != null) { xmlWriter.WriteStartElement("OriginSslProtocols", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigOriginsItemsValueCustomOriginConfigOriginSslProtocolsItems = publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.OriginSslProtocols.Items; if (publicRequestDistributionConfigOriginsItemsValueCustomOriginConfigOriginSslProtocolsItems != null && publicRequestDistributionConfigOriginsItemsValueCustomOriginConfigOriginSslProtocolsItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigOriginsItemsValueCustomOriginConfigOriginSslProtocolsItemsValue in publicRequestDistributionConfigOriginsItemsValueCustomOriginConfigOriginSslProtocolsItems) { xmlWriter.WriteStartElement("SslProtocol", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); xmlWriter.WriteValue(publicRequestDistributionConfigOriginsItemsValueCustomOriginConfigOriginSslProtocolsItemsValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.OriginSslProtocols.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequestDistributionConfigOriginsItemsValue.CustomOriginConfig.OriginSslProtocols.Quantity)); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequestDistributionConfigOriginsItemsValue.IsSetDomainName()) xmlWriter.WriteElementString("DomainName", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigOriginsItemsValue.DomainName)); if(publicRequestDistributionConfigOriginsItemsValue.IsSetId()) xmlWriter.WriteElementString("Id", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigOriginsItemsValue.Id)); if(publicRequestDistributionConfigOriginsItemsValue.IsSetOriginPath()) xmlWriter.WriteElementString("OriginPath", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigOriginsItemsValue.OriginPath)); if (publicRequestDistributionConfigOriginsItemsValue.S3OriginConfig != null) { xmlWriter.WriteStartElement("S3OriginConfig", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if(publicRequestDistributionConfigOriginsItemsValue.S3OriginConfig.IsSetOriginAccessIdentity()) xmlWriter.WriteElementString("OriginAccessIdentity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequestDistributionConfigOriginsItemsValue.S3OriginConfig.OriginAccessIdentity)); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } } xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.Origins.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequest.DistributionConfig.Origins.Quantity)); xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.IsSetPriceClass()) xmlWriter.WriteElementString("PriceClass", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.PriceClass)); if (publicRequest.DistributionConfig.Restrictions != null) { xmlWriter.WriteStartElement("Restrictions", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if (publicRequest.DistributionConfig.Restrictions.GeoRestriction != null) { xmlWriter.WriteStartElement("GeoRestriction", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); var publicRequestDistributionConfigRestrictionsGeoRestrictionItems = publicRequest.DistributionConfig.Restrictions.GeoRestriction.Items; if (publicRequestDistributionConfigRestrictionsGeoRestrictionItems != null && publicRequestDistributionConfigRestrictionsGeoRestrictionItems.Count > 0) { xmlWriter.WriteStartElement("Items", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); foreach (var publicRequestDistributionConfigRestrictionsGeoRestrictionItemsValue in publicRequestDistributionConfigRestrictionsGeoRestrictionItems) { xmlWriter.WriteStartElement("Location", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); xmlWriter.WriteValue(publicRequestDistributionConfigRestrictionsGeoRestrictionItemsValue); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.Restrictions.GeoRestriction.IsSetQuantity()) xmlWriter.WriteElementString("Quantity", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromInt(publicRequest.DistributionConfig.Restrictions.GeoRestriction.Quantity)); if(publicRequest.DistributionConfig.Restrictions.GeoRestriction.IsSetRestrictionType()) xmlWriter.WriteElementString("RestrictionType", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.Restrictions.GeoRestriction.RestrictionType)); xmlWriter.WriteEndElement(); } xmlWriter.WriteEndElement(); } if (publicRequest.DistributionConfig.ViewerCertificate != null) { xmlWriter.WriteStartElement("ViewerCertificate", "http://cloudfront.amazonaws.com/doc/2017-03-25/"); if(publicRequest.DistributionConfig.ViewerCertificate.IsSetACMCertificateArn()) xmlWriter.WriteElementString("ACMCertificateArn", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.ViewerCertificate.ACMCertificateArn)); if(publicRequest.DistributionConfig.ViewerCertificate.IsSetCertificate()) xmlWriter.WriteElementString("Certificate", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.ViewerCertificate.Certificate)); if(publicRequest.DistributionConfig.ViewerCertificate.IsSetCertificateSource()) xmlWriter.WriteElementString("CertificateSource", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.ViewerCertificate.CertificateSource)); if(publicRequest.DistributionConfig.ViewerCertificate.IsSetCloudFrontDefaultCertificate()) xmlWriter.WriteElementString("CloudFrontDefaultCertificate", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromBool(publicRequest.DistributionConfig.ViewerCertificate.CloudFrontDefaultCertificate)); if(publicRequest.DistributionConfig.ViewerCertificate.IsSetIAMCertificateId()) xmlWriter.WriteElementString("IAMCertificateId", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.ViewerCertificate.IAMCertificateId)); if(publicRequest.DistributionConfig.ViewerCertificate.IsSetMinimumProtocolVersion()) xmlWriter.WriteElementString("MinimumProtocolVersion", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.ViewerCertificate.MinimumProtocolVersion)); if(publicRequest.DistributionConfig.ViewerCertificate.IsSetSSLSupportMethod()) xmlWriter.WriteElementString("SSLSupportMethod", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.ViewerCertificate.SSLSupportMethod)); xmlWriter.WriteEndElement(); } if(publicRequest.DistributionConfig.IsSetWebACLId()) xmlWriter.WriteElementString("WebACLId", "http://cloudfront.amazonaws.com/doc/2017-03-25/", StringUtils.FromString(publicRequest.DistributionConfig.WebACLId)); xmlWriter.WriteEndElement(); } try { string content = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(content); request.Headers["Content-Type"] = "application/xml"; } catch (EncoderFallbackException e) { throw new AmazonServiceException("Unable to marshall request to XML", e); } return request; } } }
91.925316
297
0.595902
[ "Apache-2.0" ]
Bynder/aws-sdk-net
sdk/src/Services/CloudFront/Generated/Model/Internal/MarshallTransformations/UpdateDistributionRequestMarshaller.cs
72,621
C#
using Ryujinx.Common; using Ryujinx.HLE.Utilities; using System; using System.IO; using System.Runtime.InteropServices; using System.Text; using static Ryujinx.HLE.HOS.Services.Time.TimeZone.TimeZoneRule; namespace Ryujinx.HLE.HOS.Services.Time.TimeZone { public class TimeZone { private const int TimeTypeSize = 8; private const int EpochYear = 1970; private const int YearBase = 1900; private const int EpochWeekDay = 4; private const int SecondsPerMinute = 60; private const int MinutesPerHour = 60; private const int HoursPerDays = 24; private const int DaysPerWekk = 7; private const int DaysPerNYear = 365; private const int DaysPerLYear = 366; private const int MonthsPerYear = 12; private const int SecondsPerHour = SecondsPerMinute * MinutesPerHour; private const int SecondsPerDay = SecondsPerHour * HoursPerDays; private const int YearsPerRepeat = 400; private const long AverageSecondsPerYear = 31556952; private const long SecondsPerRepeat = YearsPerRepeat * AverageSecondsPerYear; private static readonly int[] YearLengths = { DaysPerNYear, DaysPerLYear }; private static readonly int[][] MonthsLengths = new int[][] { new int[] { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, new int[] { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } }; private const string TimeZoneDefaultRule = ",M4.1.0,M10.5.0"; [StructLayout(LayoutKind.Sequential, Pack = 0x4, Size = 0x10)] private struct CalendarTimeInternal { // NOTE: On the IPC side this is supposed to be a 16 bits value but internally this need to be a 64 bits value for ToPosixTime. public long Year; public sbyte Month; public sbyte Day; public sbyte Hour; public sbyte Minute; public sbyte Second; public int CompareTo(CalendarTimeInternal other) { if (Year != other.Year) { if (Year < other.Year) { return -1; } return 1; } if (Month != other.Month) { return Month - other.Month; } if (Day != other.Day) { return Day - other.Day; } if (Hour != other.Hour) { return Hour - other.Hour; } if (Minute != other.Minute) { return Minute - other.Minute; } if (Second != other.Second) { return Second - other.Second; } return 0; } } private enum RuleType { JulianDay, DayOfYear, MonthNthDayOfWeek } private struct Rule { public RuleType Type; public int Day; public int Week; public int Month; public int TransitionTime; } private static int Detzcode32(byte[] bytes) { if (BitConverter.IsLittleEndian) { Array.Reverse(bytes, 0, bytes.Length); } return BitConverter.ToInt32(bytes, 0); } private static unsafe int Detzcode32(int* data) { int result = *data; if (BitConverter.IsLittleEndian) { byte[] bytes = BitConverter.GetBytes(result); Array.Reverse(bytes, 0, bytes.Length); result = BitConverter.ToInt32(bytes, 0); } return result; } private static unsafe long Detzcode64(long* data) { long result = *data; if (BitConverter.IsLittleEndian) { byte[] bytes = BitConverter.GetBytes(result); Array.Reverse(bytes, 0, bytes.Length); result = BitConverter.ToInt64(bytes, 0); } return result; } private static bool DifferByRepeat(long t1, long t0) { return (t1 - t0) == SecondsPerRepeat; } private static unsafe bool TimeTypeEquals(TimeZoneRule outRules, byte aIndex, byte bIndex) { if (aIndex < 0 || aIndex >= outRules.TypeCount || bIndex < 0 || bIndex >= outRules.TypeCount) { return false; } TimeTypeInfo a = outRules.Ttis[aIndex]; TimeTypeInfo b = outRules.Ttis[bIndex]; fixed (char* chars = outRules.Chars) { return a.GmtOffset == b.GmtOffset && a.IsDaySavingTime == b.IsDaySavingTime && a.IsStandardTimeDaylight == b.IsStandardTimeDaylight && a.IsGMT == b.IsGMT && StringUtils.CompareCStr(chars + a.AbbreviationListIndex, chars + b.AbbreviationListIndex) == 0; } } private static int GetQZName(char[] name, int namePosition, char delimiter) { int i = namePosition; while (name[i] != '\0' && name[i] != delimiter) { i++; } return i; } private static int GetTZName(char[] name, int namePosition) { int i = namePosition; char c = name[i]; while (c != '\0' && !char.IsDigit(c) && c != ',' && c != '-' && c != '+') { c = name[i]; i++; } return i; } private static bool GetNum(char[] name, ref int namePosition, out int num, int min, int max) { num = 0; if (namePosition >= name.Length) { return false; } char c = name[namePosition]; if (!char.IsDigit(c)) { return false; } do { num = num * 10 + (c - '0'); if (num > max) { return false; } if (++namePosition >= name.Length) { return false; } c = name[namePosition]; } while (char.IsDigit(c)); if (num < min) { return false; } return true; } private static bool GetSeconds(char[] name, ref int namePosition, out int seconds) { seconds = 0; bool isValid = GetNum(name, ref namePosition, out int num, 0, HoursPerDays * DaysPerWekk - 1); if (!isValid) { return false; } seconds = num * SecondsPerHour; if (namePosition >= name.Length) { return false; } if (name[namePosition] == ':') { namePosition++; isValid = GetNum(name, ref namePosition, out num, 0, MinutesPerHour - 1); if (!isValid) { return false; } seconds += num * SecondsPerMinute; if (namePosition >= name.Length) { return false; } if (name[namePosition] == ':') { namePosition++; isValid = GetNum(name, ref namePosition, out num, 0, SecondsPerMinute); if (!isValid) { return false; } seconds += num; } } return true; } private static bool GetOffset(char[] name, ref int namePosition, ref int offset) { bool isNegative = false; if (namePosition >= name.Length) { return false; } if (name[namePosition] == '-') { isNegative = true; namePosition++; } else if (name[namePosition] == '+') { namePosition++; } if (namePosition >= name.Length) { return false; } bool isValid = GetSeconds(name, ref namePosition, out offset); if (!isValid) { return false; } if (isNegative) { offset = -offset; } return true; } private static bool GetRule(char[] name, ref int namePosition, out Rule rule) { rule = new Rule(); bool isValid = false; if (name[namePosition] == 'J') { namePosition++; rule.Type = RuleType.JulianDay; isValid = GetNum(name, ref namePosition, out rule.Day, 1, DaysPerNYear); } else if (name[namePosition] == 'M') { namePosition++; rule.Type = RuleType.MonthNthDayOfWeek; isValid = GetNum(name, ref namePosition, out rule.Month, 1, MonthsPerYear); if (!isValid) { return false; } if (name[namePosition++] != '.') { return false; } isValid = GetNum(name, ref namePosition, out rule.Week, 1, 5); if (!isValid) { return false; } if (name[namePosition++] != '.') { return false; } isValid = GetNum(name, ref namePosition, out rule.Day, 0, DaysPerWekk - 1); } else if (char.IsDigit(name[namePosition])) { rule.Type = RuleType.DayOfYear; isValid = GetNum(name, ref namePosition, out rule.Day, 0, DaysPerLYear - 1); } else { return false; } if (!isValid) { return false; } if (name[namePosition] == '/') { namePosition++; return GetOffset(name, ref namePosition, ref rule.TransitionTime); } else { rule.TransitionTime = 2 * SecondsPerHour; } return true; } private static int IsLeap(int year) { if (((year) % 4) == 0 && (((year) % 100) != 0 || ((year) % 400) == 0)) { return 1; } return 0; } private static bool ParsePosixName(Span<char> name, out TimeZoneRule outRules, bool lastDitch) { outRules = new TimeZoneRule { Ats = new long[TzMaxTimes], Types = new byte[TzMaxTimes], Ttis = new TimeTypeInfo[TzMaxTypes], Chars = new char[TzCharsArraySize] }; int stdLen; Span<char> stdName = name; int namePosition = 0; int stdOffset = 0; if (lastDitch) { stdLen = 3; namePosition += stdLen; } else { if (name[namePosition] == '<') { namePosition++; stdName = name.Slice(namePosition); int stdNamePosition = namePosition; namePosition = GetQZName(name.ToArray(), namePosition, '>'); if (name[namePosition] != '>') { return false; } stdLen = namePosition - stdNamePosition; namePosition++; } else { namePosition = GetTZName(name.ToArray(), namePosition); stdLen = namePosition; } if (stdLen == 0) { return false; } bool isValid = GetOffset(name.ToArray(), ref namePosition, ref stdOffset); if (!isValid) { return false; } } int charCount = stdLen + 1; int destLen = 0; int dstOffset = 0; Span<char> destName = name.Slice(namePosition); if (TzCharsArraySize < charCount) { return false; } if (name[namePosition] != '\0') { if (name[namePosition] == '<') { destName = name.Slice(++namePosition); int destNamePosition = namePosition; namePosition = GetQZName(name.ToArray(), namePosition, '>'); if (name[namePosition] != '>') { return false; } destLen = namePosition - destNamePosition; namePosition++; } else { destName = name.Slice(namePosition); namePosition = GetTZName(name.ToArray(), namePosition); destLen = namePosition; } if (destLen == 0) { return false; } charCount += destLen + 1; if (TzCharsArraySize < charCount) { return false; } if (name[namePosition] != '\0' && name[namePosition] != ',' && name[namePosition] != ';') { bool isValid = GetOffset(name.ToArray(), ref namePosition, ref dstOffset); if (!isValid) { return false; } } else { dstOffset = stdOffset - SecondsPerHour; } if (name[namePosition] == '\0') { name = TimeZoneDefaultRule.ToCharArray(); namePosition = 0; } if (name[namePosition] == ',' || name[namePosition] == ';') { namePosition++; bool IsRuleValid = GetRule(name.ToArray(), ref namePosition, out Rule start); if (!IsRuleValid) { return false; } if (name[namePosition++] != ',') { return false; } IsRuleValid = GetRule(name.ToArray(), ref namePosition, out Rule end); if (!IsRuleValid) { return false; } if (name[namePosition] != '\0') { return false; } outRules.TypeCount = 2; outRules.Ttis[0] = new TimeTypeInfo { GmtOffset = -dstOffset, IsDaySavingTime = true, AbbreviationListIndex = stdLen + 1 }; outRules.Ttis[1] = new TimeTypeInfo { GmtOffset = -stdOffset, IsDaySavingTime = false, AbbreviationListIndex = 0 }; outRules.DefaultType = 0; int timeCount = 0; long janFirst = 0; int janOffset = 0; int yearBegining = EpochYear; do { int yearSeconds = YearLengths[IsLeap(yearBegining - 1)] * SecondsPerDay; yearBegining--; if (IncrementOverflow64(ref janFirst, -yearSeconds)) { janOffset = -yearSeconds; break; } } while (EpochYear - YearsPerRepeat / 2 < yearBegining); int yearLimit = yearBegining + YearsPerRepeat + 1; int year; for (year = yearBegining; year < yearLimit; year++) { int startTime = TransitionTime(year, start, stdOffset); int endTime = TransitionTime(year, end, dstOffset); int yearSeconds = YearLengths[IsLeap(year)] * SecondsPerDay; bool isReversed = endTime < startTime; if (isReversed) { int swap = startTime; startTime = endTime; endTime = swap; } if (isReversed || (startTime < endTime && (endTime - startTime < (yearSeconds + (stdOffset - dstOffset))))) { if (TzMaxTimes - 2 < timeCount) { break; } outRules.Ats[timeCount] = janFirst; if (!IncrementOverflow64(ref outRules.Ats[timeCount], janOffset + startTime)) { outRules.Types[timeCount++] = isReversed ? (byte)1 : (byte)0; } else if (janOffset != 0) { outRules.DefaultType = isReversed ? 1 : 0; } outRules.Ats[timeCount] = janFirst; if (!IncrementOverflow64(ref outRules.Ats[timeCount], janOffset + endTime)) { outRules.Types[timeCount++] = isReversed ? (byte)0 : (byte)1; yearLimit = year + YearsPerRepeat + 1; } else if (janOffset != 0) { outRules.DefaultType = isReversed ? 0 : 1; } } if (IncrementOverflow64(ref janFirst, janOffset + yearSeconds)) { break; } janOffset = 0; } outRules.TimeCount = timeCount; // There is no time variation, this is then a perpetual DST rule if (timeCount == 0) { outRules.TypeCount = 1; } else if (YearsPerRepeat < year - yearBegining) { outRules.GoBack = true; outRules.GoAhead = true; } } else { if (name[namePosition] == '\0') { return false; } long theirStdOffset = 0; for (int i = 0; i < outRules.TimeCount; i++) { int j = outRules.Types[i]; if (outRules.Ttis[j].IsStandardTimeDaylight) { theirStdOffset = -outRules.Ttis[j].GmtOffset; } } long theirDstOffset = 0; for (int i = 0; i < outRules.TimeCount; i++) { int j = outRules.Types[i]; if (outRules.Ttis[j].IsDaySavingTime) { theirDstOffset = -outRules.Ttis[j].GmtOffset; } } bool isDaySavingTime = false; long theirOffset = theirStdOffset; for (int i = 0; i < outRules.TimeCount; i++) { int j = outRules.Types[i]; outRules.Types[i] = outRules.Ttis[j].IsDaySavingTime ? (byte)1 : (byte)0; if (!outRules.Ttis[j].IsGMT) { if (isDaySavingTime && !outRules.Ttis[j].IsStandardTimeDaylight) { outRules.Ats[i] += dstOffset - theirStdOffset; } else { outRules.Ats[i] += stdOffset - theirStdOffset; } } theirOffset = -outRules.Ttis[j].GmtOffset; if (outRules.Ttis[j].IsDaySavingTime) { theirDstOffset = theirOffset; } else { theirStdOffset = theirOffset; } } outRules.Ttis[0] = new TimeTypeInfo { GmtOffset = -stdOffset, IsDaySavingTime = false, AbbreviationListIndex = 0 }; outRules.Ttis[1] = new TimeTypeInfo { GmtOffset = -dstOffset, IsDaySavingTime = true, AbbreviationListIndex = stdLen + 1 }; outRules.TypeCount = 2; outRules.DefaultType = 0; } } else { // default is perpetual standard time outRules.TypeCount = 1; outRules.TimeCount = 0; outRules.DefaultType = 0; outRules.Ttis[0] = new TimeTypeInfo { GmtOffset = -stdOffset, IsDaySavingTime = false, AbbreviationListIndex = 0 }; } outRules.CharCount = charCount; int charsPosition = 0; for (int i = 0; i < stdLen; i++) { outRules.Chars[i] = stdName[i]; } charsPosition += stdLen; outRules.Chars[charsPosition++] = '\0'; if (destLen != 0) { for (int i = 0; i < destLen; i++) { outRules.Chars[charsPosition + i] = destName[i]; } outRules.Chars[charsPosition + destLen] = '\0'; } return true; } private static int TransitionTime(int year, Rule rule, int offset) { int leapYear = IsLeap(year); int value; switch (rule.Type) { case RuleType.JulianDay: value = (rule.Day - 1) * SecondsPerDay; if (leapYear == 1 && rule.Day >= 60) { value += SecondsPerDay; } break; case RuleType.DayOfYear: value = rule.Day * SecondsPerDay; break; case RuleType.MonthNthDayOfWeek: // Here we use Zeller's Congruence to get the day of week of the first month. int m1 = (rule.Month + 9) % 12 + 1; int yy0 = (rule.Month <= 2) ? (year - 1) : year; int yy1 = yy0 / 100; int yy2 = yy0 % 100; int dayOfWeek = ((26 * m1 - 2) / 10 + 1 + yy2 + yy2 / 4 + yy1 / 4 - 2 * yy1) % 7; if (dayOfWeek < 0) { dayOfWeek += DaysPerWekk; } // Get the zero origin int d = rule.Day - dayOfWeek; if (d < 0) { d += DaysPerWekk; } for (int i = 1; i < rule.Week; i++) { if (d + DaysPerWekk >= MonthsLengths[leapYear][rule.Month - 1]) { break; } d += DaysPerWekk; } value = d * SecondsPerDay; for (int i = 0; i < rule.Month - 1; i++) { value += MonthsLengths[leapYear][i] * SecondsPerDay; } break; default: throw new NotImplementedException("Unknown time transition!"); } return value + rule.TransitionTime + offset; } private static bool NormalizeOverflow32(ref int ip, ref int unit, int baseValue) { int delta; if (unit >= 0) { delta = unit / baseValue; } else { delta = -1 - (-1 - unit) / baseValue; } unit -= delta * baseValue; return IncrementOverflow32(ref ip, delta); } private static bool NormalizeOverflow64(ref long ip, ref long unit, long baseValue) { long delta; if (unit >= 0) { delta = unit / baseValue; } else { delta = -1 - (-1 - unit) / baseValue; } unit -= delta * baseValue; return IncrementOverflow64(ref ip, delta); } private static bool IncrementOverflow32(ref int time, int j) { try { time = checked(time + j); return false; } catch (OverflowException) { return true; } } private static bool IncrementOverflow64(ref long time, long j) { try { time = checked(time + j); return false; } catch (OverflowException) { return true; } } internal static bool ParsePosixName(string name, out TimeZoneRule outRules) { return ParsePosixName(name.ToCharArray(), out outRules, false); } internal static unsafe bool ParseTimeZoneBinary(out TimeZoneRule outRules, Stream inputData) { outRules = new TimeZoneRule { Ats = new long[TzMaxTimes], Types = new byte[TzMaxTimes], Ttis = new TimeTypeInfo[TzMaxTypes], Chars = new char[TzCharsArraySize] }; BinaryReader reader = new BinaryReader(inputData); long streamLength = reader.BaseStream.Length; if (streamLength < Marshal.SizeOf<TzifHeader>()) { return false; } TzifHeader header = reader.ReadStruct<TzifHeader>(); streamLength -= Marshal.SizeOf<TzifHeader>(); int ttisGMTCount = Detzcode32(header.TtisGMTCount); int ttisSTDCount = Detzcode32(header.TtisSTDCount); int leapCount = Detzcode32(header.LeapCount); int timeCount = Detzcode32(header.TimeCount); int typeCount = Detzcode32(header.TypeCount); int charCount = Detzcode32(header.CharCount); if (!(0 <= leapCount && leapCount < TzMaxLeaps && 0 < typeCount && typeCount < TzMaxTypes && 0 <= timeCount && timeCount < TzMaxTimes && 0 <= charCount && charCount < TzMaxChars && (ttisSTDCount == typeCount || ttisSTDCount == 0) && (ttisGMTCount == typeCount || ttisGMTCount == 0))) { return false; } if (streamLength < (timeCount * TimeTypeSize + timeCount + typeCount * 6 + charCount + leapCount * (TimeTypeSize + 4) + ttisSTDCount + ttisGMTCount)) { return false; } outRules.TimeCount = timeCount; outRules.TypeCount = typeCount; outRules.CharCount = charCount; byte[] workBuffer = StreamUtils.StreamToBytes(inputData); timeCount = 0; fixed (byte* workBufferPtrStart = workBuffer) { byte* p = workBufferPtrStart; for (int i = 0; i < outRules.TimeCount; i++) { long at = Detzcode64((long*)p); outRules.Types[i] = 1; if (timeCount != 0 && at <= outRules.Ats[timeCount - 1]) { if (at < outRules.Ats[timeCount - 1]) { return false; } outRules.Types[i - 1] = 0; timeCount--; } outRules.Ats[timeCount++] = at; p += TimeTypeSize; } timeCount = 0; for (int i = 0; i < outRules.TimeCount; i++) { byte type = *p++; if (outRules.TypeCount <= type) { return false; } if (outRules.Types[i] != 0) { outRules.Types[timeCount++] = type; } } outRules.TimeCount = timeCount; for (int i = 0; i < outRules.TypeCount; i++) { TimeTypeInfo ttis = outRules.Ttis[i]; ttis.GmtOffset = Detzcode32((int*)p); p += 4; if (*p >= 2) { return false; } ttis.IsDaySavingTime = *p != 0; p++; int abbreviationListIndex = *p++; if (abbreviationListIndex >= outRules.CharCount) { return false; } ttis.AbbreviationListIndex = abbreviationListIndex; outRules.Ttis[i] = ttis; } fixed (char* chars = outRules.Chars) { Encoding.ASCII.GetChars(p, outRules.CharCount, chars, outRules.CharCount); } p += outRules.CharCount; outRules.Chars[outRules.CharCount] = '\0'; for (int i = 0; i < outRules.TypeCount; i++) { if (ttisSTDCount == 0) { outRules.Ttis[i].IsStandardTimeDaylight = false; } else { if (*p >= 2) { return false; } outRules.Ttis[i].IsStandardTimeDaylight = *p++ != 0; } } for (int i = 0; i < outRules.TypeCount; i++) { if (ttisSTDCount == 0) { outRules.Ttis[i].IsGMT = false; } else { if (*p >= 2) { return false; } outRules.Ttis[i].IsGMT = *p++ != 0; } } long position = (p - workBufferPtrStart); long nRead = streamLength - position; if (nRead < 0) { return false; } // Nintendo abort in case of a TzIf file with a POSIX TZ Name too long to fit inside a TimeZoneRule. // As it's impossible in normal usage to achive this, we also force a crash. if (nRead > (TzNameMax + 1)) { throw new InvalidOperationException(); } char[] tempName = new char[TzNameMax + 1]; Array.Copy(workBuffer, position, tempName, 0, nRead); if (nRead > 2 && tempName[0] == '\n' && tempName[nRead - 1] == '\n' && outRules.TypeCount + 2 <= TzMaxTypes) { tempName[nRead - 1] = '\0'; char[] name = new char[TzNameMax]; Array.Copy(tempName, 1, name, 0, nRead - 1); if (ParsePosixName(name, out TimeZoneRule tempRules, false)) { int abbreviationCount = 0; charCount = outRules.CharCount; fixed (char* chars = outRules.Chars) { for (int i = 0; i < tempRules.TypeCount; i++) { fixed (char* tempChars = tempRules.Chars) { char* tempAbbreviation = tempChars + tempRules.Ttis[i].AbbreviationListIndex; int j; for (j = 0; j < charCount; j++) { if (StringUtils.CompareCStr(chars + j, tempAbbreviation) == 0) { tempRules.Ttis[i].AbbreviationListIndex = j; abbreviationCount++; break; } } if (j >= charCount) { int abbreviationLength = StringUtils.LengthCstr(tempAbbreviation); if (j + abbreviationLength < TzMaxChars) { for (int x = 0; x < abbreviationLength; x++) { chars[j + x] = tempAbbreviation[x]; } charCount = j + abbreviationLength + 1; tempRules.Ttis[i].AbbreviationListIndex = j; abbreviationCount++; } } } } if (abbreviationCount == tempRules.TypeCount) { outRules.CharCount = charCount; // Remove trailing while (1 < outRules.TimeCount && (outRules.Types[outRules.TimeCount - 1] == outRules.Types[outRules.TimeCount - 2])) { outRules.TimeCount--; } int i; for (i = 0; i < tempRules.TimeCount; i++) { if (outRules.TimeCount == 0 || outRules.Ats[outRules.TimeCount - 1] < tempRules.Ats[i]) { break; } } while (i < tempRules.TimeCount && outRules.TimeCount < TzMaxTimes) { outRules.Ats[outRules.TimeCount] = tempRules.Ats[i]; outRules.Types[outRules.TimeCount] = (byte)(outRules.TypeCount + (byte)tempRules.Types[i]); outRules.TimeCount++; i++; } for (i = 0; i < tempRules.TypeCount; i++) { outRules.Ttis[outRules.TypeCount++] = tempRules.Ttis[i]; } } } } } if (outRules.TypeCount == 0) { return false; } if (outRules.TimeCount > 1) { for (int i = 1; i < outRules.TimeCount; i++) { if (TimeTypeEquals(outRules, outRules.Types[i], outRules.Types[0]) && DifferByRepeat(outRules.Ats[i], outRules.Ats[0])) { outRules.GoBack = true; break; } } for (int i = outRules.TimeCount - 2; i >= 0; i--) { if (TimeTypeEquals(outRules, outRules.Types[outRules.TimeCount - 1], outRules.Types[i]) && DifferByRepeat(outRules.Ats[outRules.TimeCount - 1], outRules.Ats[i])) { outRules.GoAhead = true; break; } } } int defaultType; for (defaultType = 0; defaultType < outRules.TimeCount; defaultType++) { if (outRules.Types[defaultType] == 0) { break; } } defaultType = defaultType < outRules.TimeCount ? -1 : 0; if (defaultType < 0 && outRules.TimeCount > 0 && outRules.Ttis[outRules.Types[0]].IsDaySavingTime) { defaultType = outRules.Types[0]; while (--defaultType >= 0) { if (!outRules.Ttis[defaultType].IsDaySavingTime) { break; } } } if (defaultType < 0) { defaultType = 0; while (outRules.Ttis[defaultType].IsDaySavingTime) { if (++defaultType >= outRules.TypeCount) { defaultType = 0; break; } } } outRules.DefaultType = defaultType; } return true; } private static long GetLeapDaysNotNeg(long year) { return year / 4 - year / 100 + year / 400; } private static long GetLeapDays(long year) { if (year < 0) { return -1 - GetLeapDaysNotNeg(-1 - year); } else { return GetLeapDaysNotNeg(year); } } private static ResultCode CreateCalendarTime(long time, int gmtOffset, out CalendarTimeInternal calendarTime, out CalendarAdditionalInfo calendarAdditionalInfo) { long year = EpochYear; long timeDays = time / SecondsPerDay; long remainingSeconds = time % SecondsPerDay; calendarTime = new CalendarTimeInternal(); calendarAdditionalInfo = new CalendarAdditionalInfo() { TimezoneName = new char[8] }; while (timeDays < 0 || timeDays >= YearLengths[IsLeap((int)year)]) { long timeDelta = timeDays / DaysPerLYear; long delta = timeDelta; if (delta == 0) { delta = timeDays < 0 ? -1 : 1; } long newYear = year; if (IncrementOverflow64(ref newYear, delta)) { return ResultCode.OutOfRange; } long leapDays = GetLeapDays(newYear - 1) - GetLeapDays(year - 1); timeDays -= (newYear - year) * DaysPerNYear; timeDays -= leapDays; year = newYear; } long dayOfYear = timeDays; remainingSeconds += gmtOffset; while (remainingSeconds < 0) { remainingSeconds += SecondsPerDay; dayOfYear -= 1; } while (remainingSeconds >= SecondsPerDay) { remainingSeconds -= SecondsPerDay; dayOfYear += 1; } while (dayOfYear < 0) { if (IncrementOverflow64(ref year, -1)) { return ResultCode.OutOfRange; } dayOfYear += YearLengths[IsLeap((int)year)]; } while (dayOfYear >= YearLengths[IsLeap((int)year)]) { dayOfYear -= YearLengths[IsLeap((int)year)]; if (IncrementOverflow64(ref year, 1)) { return ResultCode.OutOfRange; } } calendarTime.Year = year; calendarAdditionalInfo.DayOfYear = (uint)dayOfYear; long dayOfWeek = (EpochWeekDay + ((year - EpochYear) % DaysPerWekk) * (DaysPerNYear % DaysPerWekk) + GetLeapDays(year - 1) - GetLeapDays(EpochYear - 1) + dayOfYear) % DaysPerWekk; if (dayOfWeek < 0) { dayOfWeek += DaysPerWekk; } calendarAdditionalInfo.DayOfWeek = (uint)dayOfWeek; calendarTime.Hour = (sbyte)((remainingSeconds / SecondsPerHour) % SecondsPerHour); remainingSeconds %= SecondsPerHour; calendarTime.Minute = (sbyte)(remainingSeconds / SecondsPerMinute); calendarTime.Second = (sbyte)(remainingSeconds % SecondsPerMinute); int[] ip = MonthsLengths[IsLeap((int)year)]; for (calendarTime.Month = 0; dayOfYear >= ip[calendarTime.Month]; ++calendarTime.Month) { dayOfYear -= ip[calendarTime.Month]; } calendarTime.Day = (sbyte)(dayOfYear + 1); calendarAdditionalInfo.IsDaySavingTime = false; calendarAdditionalInfo.GmtOffset = gmtOffset; return 0; } private static ResultCode ToCalendarTimeInternal(TimeZoneRule rules, long time, out CalendarTimeInternal calendarTime, out CalendarAdditionalInfo calendarAdditionalInfo) { calendarTime = new CalendarTimeInternal(); calendarAdditionalInfo = new CalendarAdditionalInfo() { TimezoneName = new char[8] }; ResultCode result; if ((rules.GoAhead && time < rules.Ats[0]) || (rules.GoBack && time > rules.Ats[rules.TimeCount - 1])) { long newTime = time; long seconds; long years; if (time < rules.Ats[0]) { seconds = rules.Ats[0] - time; } else { seconds = time - rules.Ats[rules.TimeCount - 1]; } seconds -= 1; years = (seconds / SecondsPerRepeat + 1) * YearsPerRepeat; seconds = years * AverageSecondsPerYear; if (time < rules.Ats[0]) { newTime += seconds; } else { newTime -= seconds; } if (newTime < rules.Ats[0] && newTime > rules.Ats[rules.TimeCount - 1]) { return ResultCode.TimeNotFound; } result = ToCalendarTimeInternal(rules, newTime, out calendarTime, out calendarAdditionalInfo); if (result != 0) { return result; } if (time < rules.Ats[0]) { calendarTime.Year -= years; } else { calendarTime.Year += years; } return ResultCode.Success; } int ttiIndex; if (rules.TimeCount == 0 || time < rules.Ats[0]) { ttiIndex = rules.DefaultType; } else { int low = 1; int high = rules.TimeCount; while (low < high) { int mid = (low + high) >> 1; if (time < rules.Ats[mid]) { high = mid; } else { low = mid + 1; } } ttiIndex = rules.Types[low - 1]; } result = CreateCalendarTime(time, rules.Ttis[ttiIndex].GmtOffset, out calendarTime, out calendarAdditionalInfo); if (result == 0) { calendarAdditionalInfo.IsDaySavingTime = rules.Ttis[ttiIndex].IsDaySavingTime; unsafe { fixed (char* timeZoneAbbreviation = &rules.Chars[rules.Ttis[ttiIndex].AbbreviationListIndex]) { int timeZoneSize = Math.Min(StringUtils.LengthCstr(timeZoneAbbreviation), 8); for (int i = 0; i < timeZoneSize; i++) { calendarAdditionalInfo.TimezoneName[i] = timeZoneAbbreviation[i]; } } } } return result; } private static ResultCode ToPosixTimeInternal(TimeZoneRule rules, CalendarTimeInternal calendarTime, out long posixTime) { posixTime = 0; int hour = calendarTime.Hour; int minute = calendarTime.Minute; if (NormalizeOverflow32(ref hour, ref minute, MinutesPerHour)) { return ResultCode.Overflow; } calendarTime.Minute = (sbyte)minute; int day = calendarTime.Day; if (NormalizeOverflow32(ref day, ref hour, HoursPerDays)) { return ResultCode.Overflow; } calendarTime.Day = (sbyte)day; calendarTime.Hour = (sbyte)hour; long year = calendarTime.Year; long month = calendarTime.Month; if (NormalizeOverflow64(ref year, ref month, MonthsPerYear)) { return ResultCode.Overflow; } calendarTime.Month = (sbyte)month; if (IncrementOverflow64(ref year, YearBase)) { return ResultCode.Overflow; } while (day <= 0) { if (IncrementOverflow64(ref year, -1)) { return ResultCode.Overflow; } long li = year; if (1 < calendarTime.Month) { li++; } day += YearLengths[IsLeap((int)li)]; } while (day > DaysPerLYear) { long li = year; if (1 < calendarTime.Month) { li++; } day -= YearLengths[IsLeap((int)li)]; if (IncrementOverflow64(ref year, 1)) { return ResultCode.Overflow; } } while (true) { int i = MonthsLengths[IsLeap((int)year)][calendarTime.Month]; if (day <= i) { break; } day -= i; calendarTime.Month += 1; if (calendarTime.Month >= MonthsPerYear) { calendarTime.Month = 0; if (IncrementOverflow64(ref year, 1)) { return ResultCode.Overflow; } } } calendarTime.Day = (sbyte)day; if (IncrementOverflow64(ref year, -YearBase)) { return ResultCode.Overflow; } calendarTime.Year = year; int savedSeconds; if (calendarTime.Second >= 0 && calendarTime.Second < SecondsPerMinute) { savedSeconds = 0; } else if (year + YearBase < EpochYear) { int second = calendarTime.Second; if (IncrementOverflow32(ref second, 1 - SecondsPerMinute)) { return ResultCode.Overflow; } savedSeconds = second; calendarTime.Second = 1 - SecondsPerMinute; } else { savedSeconds = calendarTime.Second; calendarTime.Second = 0; } long low = long.MinValue; long high = long.MaxValue; while (true) { long pivot = low / 2 + high / 2; if (pivot < low) { pivot = low; } else if (pivot > high) { pivot = high; } int direction; ResultCode result = ToCalendarTimeInternal(rules, pivot, out CalendarTimeInternal candidateCalendarTime, out _); if (result != 0) { if (pivot > 0) { direction = 1; } else { direction = -1; } } else { direction = candidateCalendarTime.CompareTo(calendarTime); } if (direction == 0) { long timeResult = pivot + savedSeconds; if ((timeResult < pivot) != (savedSeconds < 0)) { return ResultCode.Overflow; } posixTime = timeResult; break; } else { if (pivot == low) { if (pivot == long.MaxValue) { return ResultCode.TimeNotFound; } pivot += 1; low += 1; } else if (pivot == high) { if (pivot == long.MinValue) { return ResultCode.TimeNotFound; } pivot -= 1; high -= 1; } if (low > high) { return ResultCode.TimeNotFound; } if (direction > 0) { high = pivot; } else { low = pivot; } } } return ResultCode.Success; } internal static ResultCode ToCalendarTime(TimeZoneRule rules, long time, out CalendarInfo calendar) { ResultCode result = ToCalendarTimeInternal(rules, time, out CalendarTimeInternal calendarTime, out CalendarAdditionalInfo calendarAdditionalInfo); calendar = new CalendarInfo() { Time = new CalendarTime() { Year = (short)calendarTime.Year, // NOTE: Nintendo's month range is 1-12, internal range is 0-11. Month = (sbyte)(calendarTime.Month + 1), Day = calendarTime.Day, Hour = calendarTime.Hour, Minute = calendarTime.Minute, Second = calendarTime.Second }, AdditionalInfo = calendarAdditionalInfo }; return result; } internal static ResultCode ToPosixTime(TimeZoneRule rules, CalendarTime calendarTime, out long posixTime) { CalendarTimeInternal calendarTimeInternal = new CalendarTimeInternal() { Year = calendarTime.Year, // NOTE: Nintendo's month range is 1-12, internal range is 0-11. Month = (sbyte)(calendarTime.Month - 1), Day = calendarTime.Day, Hour = calendarTime.Hour, Minute = calendarTime.Minute, Second = calendarTime.Second }; return ToPosixTimeInternal(rules, calendarTimeInternal, out posixTime); } } }
32.07303
191
0.391878
[ "MIT" ]
312811719/Ryujinx
Ryujinx.HLE/HOS/Services/Time/TimeZone/TimeZone.cs
55,777
C#
// Copyright (c) 2019 Lykke Corp. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Threading.Tasks; using JetBrains.Annotations; using MarginTrading.TradingHistory.Core.Domain; namespace MarginTrading.TradingHistory.Core.Repositories { public interface IDealsRepository { [ItemCanBeNull] Task<IDealWithCommissionParams> GetAsync(string id); Task<PaginatedResponse<IDealWithCommissionParams>> GetByPagesAsync(string accountId, string assetPairId, DateTime? closeTimeStart, DateTime? closeTimeEnd, int? skip = null, int? take = null, bool isAscending = true); Task<PaginatedResponse<IAggregatedDeal>> GetAggregated(string accountId, string assetPairId, DateTime? closeTimeStart, DateTime? closeTimeEnd, int? skip = null, int? take = null, bool isAscending = true); Task<IEnumerable<IDealWithCommissionParams>> GetAsync([CanBeNull] string accountId, [CanBeNull] string assetPairId, DateTime? closeTimeStart = null, DateTime? closeTimeEnd = null); Task<decimal> GetTotalPnlAsync([CanBeNull] string accountId, [CanBeNull] string assetPairId, DateTime? closeTimeStart = null, DateTime? closeTimeEnd = null); Task<decimal> GetTotalProfitAsync(string accountId, DateTime[] days); } }
41.285714
112
0.70519
[ "MIT-0" ]
LykkeBusiness/MarginTrading.TradingHistory
src/MarginTrading.TradingHistory.Core/Repositories/IDealsRepository.cs
1,447
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 CompanyServiceClient { public partial class CompanyFormclient { /// <summary> /// form1 control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::System.Web.UI.HtmlControls.HtmlForm form1; /// <summary> /// Button1 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.Button Button1; /// <summary> /// Label1 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.Label Label1; /// <summary> /// Button2 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.Button Button2; /// <summary> /// Label2 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.Label Label2; } }
33.180328
84
0.512352
[ "MIT" ]
leodark85/WCF-train
CompanyService/CompanyServiceClient/CompanyFormclient.aspx.designer.cs
2,026
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net.Mail; using System.Text; using System.Threading.Tasks; namespace OnceMi.Framework.Util.Api.Email { public class SendEmail { /// <summary> /// 邮件主机 /// </summary> private string Host { get; set; } /// <summary> /// 邮件地址 /// </summary> private string Address { get; set; } /// <summary> /// 邮件密码 /// </summary> private string Passwd { get; set; } /// <summary> /// 发送邮件 /// </summary> /// <param name="host">邮件主机</param> /// <param name="address">邮件地址</param> /// <param name="passwd">邮件密码</param> public SendEmail(string host, string address, string passwd) { this.Host = host; this.Address = address; this.Passwd = passwd; } /// <summary> /// 发送HTML邮件 /// </summary> /// <param name="subject">主题</param> /// <param name="sendto">发送给</param> /// <param name="body">邮件主体</param> /// <param name="ccto">抄送 可选</param> /// <returns></returns> public bool SendHtmlMail(string subject, string sendto, string body, string ccto = "") { if (string.IsNullOrEmpty(subject)) { return false; } if (string.IsNullOrEmpty(sendto)) { return false; } if (string.IsNullOrEmpty(body)) { return false; } //邮件发送客户端 MailClient mailClient = new MailClient(Host, Address, Passwd); //创建邮件对象 MailMessageBuilder buildMsg = new MailMessageBuilder(Address, subject, sendto, body, true); MailMessage msg = buildMsg.Message(); return mailClient.Send(msg); } /// <summary> /// 发送普通文本邮件 /// </summary> /// <param name="subject">主题</param> /// <param name="sendto">发送给</param> /// <param name="text">邮件主体</param> /// <param name="ccto">抄送 可选</param> /// <returns></returns> public bool SendTextMail(string subject, string sendto, string text, string ccto = "") { if (string.IsNullOrEmpty(subject)) { return false; } if (string.IsNullOrEmpty(sendto)) { return false; } if (string.IsNullOrEmpty(text)) { return false; } //邮件发送客户端 MailClient mailClient = new MailClient(Host, Address, Passwd); //创建邮件对象 MailMessageBuilder buildMsg = new MailMessageBuilder(Address, subject, sendto, text, false); MailMessage msg = buildMsg.Message(); return mailClient.Send(msg); } } }
29.39604
104
0.4968
[ "MIT" ]
oncemi/OnceMi.Framework
src/OnceMi.Framework.Util/Api/Email/SendEmail.cs
3,155
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Globalization; namespace ExtensionMethods { public static class StringExtensionMethods { //Tries to parse the string to a credit amount. Accepts formats: "x", "x,x", "x,xx" public static bool TryToCredit(this string str, out int credit) { //Splittes the string at the decimal separator var splittedString = str.Split(NumberFormatInfo.CurrentInfo.CurrencyDecimalSeparator.ToCharArray()); var count = splittedString.Count(); int res; //When the string array only has one element, then there were no decimal seperator if (count == 1) { if (int.TryParse(splittedString[0], out res)) { credit = res * 100; return true; } } else if (count == 2) { if (int.TryParse(splittedString[0], out res)) { credit = res * 100; //If format "x,x" if (splittedString[1].Length == 1) { if (int.TryParse(splittedString[1], out res)) { credit += res * 10; return true; } } //If format "x,xx" else if (splittedString[1].Length == 2) { if (int.TryParse(splittedString[1], out res)) { credit += res; return true; } } } } credit = 0; return false; } } }
32.655738
113
0.419679
[ "MIT" ]
Hejsil/2.-Semester-Examen
ExtensionMethods/StringExtensionMethods.cs
1,994
C#
using System; using System.Collections.Generic; namespace Project0.DataAccess.Entities { public partial class Inventory { public int InventoryId { get; set; } public int ProductId { get; set; } public int Stock { get; set; } public int? LocationId { get; set; } public virtual Location Location { get; set; } public virtual Product Product { get; set; } } }
24.764706
54
0.629454
[ "MIT" ]
1909-sep30-net/marielle-project0
Project0.DataAccess/Entities/Inventory.cs
423
C#
//Copyright 2019 Volodymyr Podshyvalov // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. using System; using System.IO; using System.Collections.Generic; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Xml.Serialization; namespace UniformQueries { /// <summary> /// Formated query that can be shared in binary view cross network. /// </summary> [System.Serializable] public class Query : ICloneable { /// <summary> /// Data that describe required or applied encryption. /// </summary> [Serializable] public class EncryptionInfo : ICloneable { /// <summary> /// Code of a symmetric encryption operator that applied to the query's content. /// </summary> public string contentEncrytpionOperatorCode; /// <summary> /// Symmetric key that used for content encryption. /// Encrupted by public key received from server. /// </summary> public byte[] encryptedSymmetricKey; /// <summary> /// Return cloned object of settings. /// </summary> /// <returns></returns> public object Clone() { var settigns = new EncryptionInfo() { contentEncrytpionOperatorCode = string.Copy(this.contentEncrytpionOperatorCode) }; if (encryptedSymmetricKey != null) { Array.Copy(this.encryptedSymmetricKey, encryptedSymmetricKey, this.encryptedSymmetricKey.Length); } return settigns; } } /// <summary> /// Encryption setting of that query. /// if null then messages would not encrypted. /// </summary> public EncryptionInfo EncryptionMeta { get; set; } = new EncryptionInfo(); /// <summary> /// Is that query has configurated encryption meta? /// If it is then system would mean that the content was or require to be encrypted and would to operate that. /// </summary> [XmlIgnore] public bool IsEncrypted { get { if (EncryptionMeta == null) return false; //if (string.IsNullOrEmpty(EncryptionMeta.contentEncrytpionOperatorCode)) return false; return true; } } /// <summary> /// Binary array with content. Could be encrypted. /// In normal state is List of QueryPart. /// </summary> [XmlIgnore] public byte[] Content { get { if(content == null) { if (listedContent != null) { _ = ListedContent; // Convert listed content ro binary format. } } return content; } set { content = value; listedContent = null; } } /// <summary> /// Binary data shared via that query. Can be encrypted. /// </summary> protected byte[] content; /// <summary> /// If true than output handler will wait for receiving answer input handler and /// only after that will start next query in queue. /// </summary> public bool WaitForAnswer { get; set; } = false; /// <summary> /// Returns first query part or QueryPart.None if not available. /// </summary> [XmlIgnore] public QueryPart First { get { if (ListedContent != null && listedContent.Count > 0) { return listedContent[0]; } return QueryPart.None; } } /// <summary> /// Returning content in listed format of possible. Null if not. /// Serialize listed content to binary format. /// </summary> [XmlIgnore] public List<QueryPart> ListedContent { get { if(listedContent == null) { try { listedContent = UniformDataOperator.Binary.BinaryHandler.FromByteArray<List<QueryPart>>(Content); } catch (Exception ex) { Console.WriteLine("Listed content not found. Details: " + ex.Message); } } return listedContent; } set { Content = UniformDataOperator.Binary.BinaryHandler.ToByteArray(value); listedContent = value; } } /// <summary> /// Bufer that contains deserialized binary content. /// </summary> [XmlIgnore] private List<QueryPart> listedContent; /// <summary> /// Default consructor. /// </summary> public Query() { } /// <summary> /// Creating query with message as content. /// </summary> /// <param name="message">Message that would be available via `value` param.</param> public Query(string message) { ListedContent = new List<QueryPart> { new QueryPart("value", message) }; } /// <summary> /// Creating query from parts. /// </summary> /// <param name="encrypted">Is that query myst be encrypted? /// Auto configurate QncryptionInfo.</param> /// <param name="parts">Query parts that would be used as Listed content.</param> public Query(bool encrypted, params QueryPart[] parts) { if (!encrypted) { // Drop current meta. EncryptionMeta = null; } // Creating listed content. ListedContent = new List<QueryPart>(parts); } /// <summary> /// Creating query from parts. /// </summary> /// <param name="meta">Encryption descriptor. Set at leas empty EncriptionInfor to /// requiest auto definition of settings.</param> /// <param name="parts">Query parts that would be used as Listed content.</param> public Query(EncryptionInfo meta, params QueryPart[] parts) { // Applying encryption descriptor. EncryptionMeta = meta; // Creating listed content. ListedContent = new List<QueryPart>(parts); } /// <summary> /// Creating query from parts. /// </summary> /// <param name="parts">Query parts that would be used as Listed content.</param> public Query(params QueryPart[] parts) { var lc = new List<QueryPart>(); foreach(QueryPart part in parts) { lc.Add(part); } ListedContent = lc; } /// <summary> /// Check existing of param in query parts. /// </summary> /// <param name="param">Parameter that would be looked in query.</param> /// <returns>Is parameter exist.</returns> public bool QueryParamExist(string param) { // Drop if isted content not exist. if (ListedContent == null) return false; // Try to find target param foreach (QueryPart part in ListedContent) { // If target param if (part.ParamNameEqual(param)) return true; } return false; } /// <summary> /// Try to find requested param's value among query parts. /// </summary> /// <param name="param">Parameter to search in listed content.</param> /// <param name="value">Query's part that found.</param> /// <returns>Result of search.</returns> public bool TryGetParamValue(string param, out QueryPart value) { // Drop if isted content not exist. if (ListedContent == null) { value = QueryPart.None; return false; } // Try to find target param foreach (QueryPart part in ListedContent) { // If target param if (part.ParamNameEqual(param)) { // Get value. value = part; // Mark as success. return true; } } // Inform that param not found. value = QueryPart.None; return false; } /// <summary> /// Setting part to listed content. /// Update existing if found. /// </summary> /// <param name="queryPart">Target query part.</param> public void SetParam(QueryPart queryPart) { // Try to get data in listed format. var lc = ListedContent; // If lsted data not found. if (lc == null) { // Drop if has a binary format of data. if(content != null && content.Length > 0) { throw new NotSupportedException("Your query contain binary data in not ListedContent compatible view." + " Adding query part not possible."); } // Init listed content. lc = new List<QueryPart> { queryPart }; ListedContent = lc; return; } else { // Looking for existed property. for(int i = 0; i < lc.Count; i++) { // Compare by name. if(lc[i].ParamNameEqual(queryPart.propertyName)) { lc[i] = queryPart; // Set new data. ListedContent = lc; // Convert to binary. return; } } // Add as new if not found. lc.Add(queryPart); ListedContent = lc; // Convert to binary. return; } } /// <summary> /// Returns copy of that object. /// </summary> /// <returns></returns> public object Clone() { var bufer = new Query() { EncryptionMeta = EncryptionMeta != null ? (EncryptionInfo)this.EncryptionMeta.Clone() : null, }; if (Content != null) { bufer.Content = new byte[Content.Length]; Array.Copy(Content, bufer.Content, Content.Length); } return bufer; } /// <summary> /// Return query in string format. /// </summary> /// <returns>String formtated query.</returns> public override string ToString() { if (ListedContent != null) { string query = ""; foreach(QueryPart qp in ListedContent) { if(!string.IsNullOrEmpty(query)) { query += API.SPLITTING_SYMBOL; } query += qp.ToString(); } return query; } else { return "Query content is not listed."; } } /// <summary> /// Converting query to string. /// </summary> /// <param name="query"></param> public static implicit operator string(Query query) { return query.ToString(); } } }
31.61
124
0.487346
[ "Apache-2.0" ]
ElbyFross/doloro-networking-framework
Core/UniformQueries/Query.cs
12,646
C#
// <auto-generated /> using System; using EPlast.DataAccess; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace EPlast.DataAccess.Migrations { [DbContext(typeof(EPlastDBContext))] [Migration("20200302143114_Init")] partial class Init { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.6-servicing-10079") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("EPlast.DataAccess.Entities.AdminType", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("AdminTypeName") .IsRequired() .HasMaxLength(30); b.HasKey("ID"); b.ToTable("AdminTypes"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.AnnualReport", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("AnnualReportStatusId"); b.Property<int>("CityId"); b.Property<int>("ContributionFunds"); b.Property<DateTime>("Date"); b.Property<int>("GovernmentFunds"); b.Property<string>("ImprovementNeeds") .IsRequired() .HasMaxLength(500); b.Property<int>("PlastFunds"); b.Property<string>("PropertyList") .IsRequired() .HasMaxLength(500); b.Property<int>("SponsorFunds"); b.HasKey("ID"); b.HasIndex("AnnualReportStatusId"); b.HasIndex("CityId"); b.ToTable("AnnualReports"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.AnnualReportStatus", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasMaxLength(50); b.HasKey("ID"); b.ToTable("AnnualReportStatuses"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Approver", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("UserId"); b.HasKey("ID"); b.HasIndex("UserId"); b.ToTable("Approvers"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.City", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("CityURL") .HasMaxLength(256); b.Property<string>("Description") .HasMaxLength(1024); b.Property<string>("Email") .HasMaxLength(50); b.Property<string>("HouseNumber") .IsRequired() .HasMaxLength(10); b.Property<string>("Name") .IsRequired() .HasMaxLength(50); b.Property<string>("OfficeNumber") .HasMaxLength(10); b.Property<string>("PhoneNumber") .HasMaxLength(16); b.Property<string>("PostIndex") .HasMaxLength(7); b.Property<int?>("RegionID"); b.Property<string>("Street") .IsRequired() .HasMaxLength(60); b.HasKey("ID"); b.HasIndex("RegionID"); b.ToTable("Cities"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.CityAdministration", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("AdminTypeID"); b.Property<int?>("CityID"); b.Property<DateTime?>("EndDate"); b.Property<DateTime>("StartDate"); b.Property<string>("UserId"); b.HasKey("ID"); b.HasIndex("AdminTypeID"); b.HasIndex("CityID"); b.HasIndex("UserId"); b.ToTable("CityAdministrations"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.CityDocumentType", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasMaxLength(50); b.HasKey("ID"); b.ToTable("CityDocumentTypes"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.CityDocuments", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("CityDocumentTypeID"); b.Property<int?>("CityID"); b.Property<string>("DocumentURL") .IsRequired() .HasMaxLength(256); b.Property<DateTime?>("SubmitDate"); b.HasKey("ID"); b.HasIndex("CityDocumentTypeID"); b.HasIndex("CityID"); b.ToTable("CityDocuments"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.CityMembers", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("CityID"); b.Property<DateTime?>("EndDate"); b.Property<DateTime>("StartDate"); b.Property<string>("UserId"); b.HasKey("ID"); b.HasIndex("CityID"); b.HasIndex("UserId"); b.ToTable("CityMembers"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Club", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClubName") .IsRequired() .HasMaxLength(50); b.Property<string>("ClubURL"); b.Property<string>("Description") .HasMaxLength(1024); b.HasKey("ID"); b.ToTable("Clubs"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.ClubAdministration", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("AdminTypeID"); b.Property<int?>("ClubID"); b.Property<int?>("ClubMembersID"); b.Property<DateTime?>("EndDate"); b.Property<DateTime>("StartDate"); b.HasKey("ID"); b.HasIndex("AdminTypeID"); b.HasIndex("ClubID"); b.HasIndex("ClubMembersID"); b.ToTable("ClubAdministrations"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.ClubMembers", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("ClubID"); b.Property<bool>("IsApproved"); b.Property<string>("UserId"); b.HasKey("ID"); b.HasIndex("ClubID"); b.HasIndex("UserId"); b.ToTable("ClubMembers"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.ConfirmedUser", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("ApproverID"); b.Property<DateTime>("ConfirmDate"); b.Property<string>("UserId") .IsRequired(); b.HasKey("ID"); b.HasIndex("ApproverID") .IsUnique() .HasFilter("[ApproverID] IS NOT NULL"); b.HasIndex("UserId"); b.ToTable("ConfirmedUsers"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Decesion", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("Date"); b.Property<int>("DecesionStatusID"); b.Property<int>("DecesionTargetID"); b.Property<string>("Description") .IsRequired(); b.Property<string>("Name") .IsRequired(); b.Property<int>("OrganizationID"); b.HasKey("ID"); b.HasIndex("DecesionStatusID"); b.HasIndex("DecesionTargetID"); b.HasIndex("OrganizationID"); b.ToTable("Decesions"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.DecesionStatus", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("DecesionStatusName") .IsRequired() .HasMaxLength(50); b.HasKey("ID"); b.ToTable("DecesionStatuses"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.DecesionTarget", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("TargetName") .IsRequired() .HasMaxLength(50); b.HasKey("ID"); b.ToTable("DecesionTargets"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Degree", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("DegreeName") .IsRequired() .HasMaxLength(50); b.HasKey("ID"); b.ToTable("Degrees"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.DocumentTemplate", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("DocumentFIleName") .IsRequired() .HasMaxLength(50); b.Property<string>("DocumentName") .IsRequired() .HasMaxLength(50); b.HasKey("ID"); b.ToTable("DocumentTemplates"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Education", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("DegreeID"); b.Property<string>("PlaceOfStudy") .IsRequired() .HasMaxLength(50); b.Property<string>("Speciality") .IsRequired() .HasMaxLength(50); b.HasKey("ID"); b.HasIndex("DegreeID"); b.ToTable("Educations"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Event", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Description") .IsRequired(); b.Property<int>("EventCategoryID"); b.Property<DateTime>("EventDateEnd"); b.Property<DateTime>("EventDateStart"); b.Property<string>("EventName") .IsRequired(); b.Property<int>("EventStatusID"); b.Property<string>("Eventlocation") .IsRequired(); b.HasKey("ID"); b.HasIndex("EventCategoryID"); b.HasIndex("EventStatusID"); b.ToTable("Events"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.EventAdmin", b => { b.Property<int>("EventID"); b.Property<string>("UserID"); b.HasKey("EventID", "UserID"); b.HasIndex("UserID"); b.ToTable("EventAdmin"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.EventCategory", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("EventCategoryName") .IsRequired(); b.HasKey("ID"); b.ToTable("EventCategories"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.EventGallary", b => { b.Property<int>("EventID"); b.Property<int>("GallaryID"); b.HasKey("EventID", "GallaryID"); b.HasIndex("GallaryID"); b.ToTable("EventGallarys"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.EventStatus", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("EventStatusName") .IsRequired(); b.HasKey("ID"); b.ToTable("EventStatuses"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Gallary", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("GalaryFileName") .IsRequired(); b.HasKey("ID"); b.ToTable("Gallarys"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Gender", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("GenderName") .IsRequired() .HasMaxLength(10); b.HasKey("ID"); b.ToTable("Genders"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Nationality", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Name") .IsRequired() .HasMaxLength(50); b.Property<string>("NationalityName"); b.HasKey("ID"); b.ToTable("Nationalities"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Organization", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("OrganizationName") .IsRequired() .HasMaxLength(50); b.HasKey("ID"); b.ToTable("Organization"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Participant", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("EventId"); b.Property<int>("ParticipantStatusId"); b.Property<string>("UserId"); b.HasKey("ID"); b.HasIndex("EventId"); b.HasIndex("ParticipantStatusId"); b.HasIndex("UserId"); b.ToTable("Participants"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.ParticipantStatus", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("UserEventStatusName") .IsRequired(); b.HasKey("ID"); b.ToTable("ParticipantStatuses"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Region", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Description") .HasMaxLength(1024); b.Property<string>("RegionName") .IsRequired() .HasMaxLength(50); b.HasKey("ID"); b.ToTable("Regions"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.RegionAdministration", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("AdminTypeID"); b.Property<DateTime?>("EndDate"); b.Property<int?>("RegionID"); b.Property<DateTime>("StartDate"); b.Property<string>("UserId"); b.HasKey("ID"); b.HasIndex("AdminTypeID"); b.HasIndex("RegionID"); b.HasIndex("UserId"); b.ToTable("RegionAdministrations"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Religion", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ReligionName") .IsRequired() .HasMaxLength(50); b.HasKey("ID"); b.ToTable("Religions"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.SubEventCategory", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("EventCategoryID"); b.Property<string>("SubEventCategoryName") .IsRequired(); b.HasKey("ID"); b.HasIndex("EventCategoryID"); b.ToTable("SubEventCategories"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.UnconfirmedCityMember", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int?>("CityID"); b.Property<string>("UserId"); b.HasKey("ID"); b.HasIndex("CityID"); b.HasIndex("UserId"); b.ToTable("UnconfirmedCityMember"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.User", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<string>("FatherName") .IsRequired() .HasMaxLength(50); b.Property<string>("FirstName") .IsRequired() .HasMaxLength(50); b.Property<string>("LastName") .IsRequired() .HasMaxLength(50); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<int?>("NationalityID"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<DateTime>("RegistredOn"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.Property<int>("UserProfileID"); b.HasKey("Id"); b.HasIndex("NationalityID"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.HasIndex("UserProfileID") .IsUnique(); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.UserProfile", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Address"); b.Property<DateTime>("DateTime"); b.Property<int?>("EducationID"); b.Property<int?>("GenderID"); b.Property<int?>("NationalityID"); b.Property<int>("PhoneNumber"); b.Property<int?>("ReligionID"); b.Property<int>("UserID"); b.Property<int?>("WorkID"); b.HasKey("ID"); b.HasIndex("EducationID"); b.HasIndex("GenderID"); b.HasIndex("NationalityID"); b.HasIndex("ReligionID"); b.HasIndex("WorkID"); b.ToTable("UserProfiles"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Work", b => { b.Property<int>("ID") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("PlaceOfwork") .IsRequired() .HasMaxLength(50); b.Property<string>("Position") .IsRequired() .HasMaxLength(50); b.HasKey("ID"); b.ToTable("Works"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.AnnualReport", b => { b.HasOne("EPlast.DataAccess.Entities.AnnualReportStatus", "Status") .WithMany("AnnualReports") .HasForeignKey("AnnualReportStatusId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("EPlast.DataAccess.Entities.City", "City") .WithMany("AnnualReports") .HasForeignKey("CityId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Approver", b => { b.HasOne("EPlast.DataAccess.Entities.User", "User") .WithMany("Approvers") .HasForeignKey("UserId"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.City", b => { b.HasOne("EPlast.DataAccess.Entities.Region", "Region") .WithMany("Cities") .HasForeignKey("RegionID"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.CityAdministration", b => { b.HasOne("EPlast.DataAccess.Entities.AdminType", "AdminType") .WithMany("CityAdministration") .HasForeignKey("AdminTypeID"); b.HasOne("EPlast.DataAccess.Entities.City", "City") .WithMany("CityAdministration") .HasForeignKey("CityID"); b.HasOne("EPlast.DataAccess.Entities.User", "User") .WithMany("CityAdministrations") .HasForeignKey("UserId"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.CityDocuments", b => { b.HasOne("EPlast.DataAccess.Entities.CityDocumentType", "CityDocumentType") .WithMany("CityDocuments") .HasForeignKey("CityDocumentTypeID"); b.HasOne("EPlast.DataAccess.Entities.City", "City") .WithMany("CityDocuments") .HasForeignKey("CityID"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.CityMembers", b => { b.HasOne("EPlast.DataAccess.Entities.City", "City") .WithMany("CityMembers") .HasForeignKey("CityID"); b.HasOne("EPlast.DataAccess.Entities.User", "User") .WithMany("CityMembers") .HasForeignKey("UserId"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.ClubAdministration", b => { b.HasOne("EPlast.DataAccess.Entities.AdminType", "AdminType") .WithMany("ClubAdministration") .HasForeignKey("AdminTypeID"); b.HasOne("EPlast.DataAccess.Entities.Club", "Club") .WithMany("ClubAdministration") .HasForeignKey("ClubID"); b.HasOne("EPlast.DataAccess.Entities.ClubMembers", "ClubMembers") .WithMany("ClubAdministration") .HasForeignKey("ClubMembersID"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.ClubMembers", b => { b.HasOne("EPlast.DataAccess.Entities.Club", "Club") .WithMany("ClubMembers") .HasForeignKey("ClubID"); b.HasOne("EPlast.DataAccess.Entities.User", "User") .WithMany("ClubMembers") .HasForeignKey("UserId"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.ConfirmedUser", b => { b.HasOne("EPlast.DataAccess.Entities.Approver", "Approver") .WithOne("ConfirmedUser") .HasForeignKey("EPlast.DataAccess.Entities.ConfirmedUser", "ApproverID"); b.HasOne("EPlast.DataAccess.Entities.User", "User") .WithMany("ConfirmedUsers") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Decesion", b => { b.HasOne("EPlast.DataAccess.Entities.DecesionStatus", "DecesionStatus") .WithMany() .HasForeignKey("DecesionStatusID") .OnDelete(DeleteBehavior.Cascade); b.HasOne("EPlast.DataAccess.Entities.DecesionTarget", "DecesionTarget") .WithMany() .HasForeignKey("DecesionTargetID") .OnDelete(DeleteBehavior.Cascade); b.HasOne("EPlast.DataAccess.Entities.Organization", "Organization") .WithMany() .HasForeignKey("OrganizationID") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Education", b => { b.HasOne("EPlast.DataAccess.Entities.Degree", "Degree") .WithMany("Educations") .HasForeignKey("DegreeID"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Event", b => { b.HasOne("EPlast.DataAccess.Entities.EventCategory", "EventCategory") .WithMany("Events") .HasForeignKey("EventCategoryID") .OnDelete(DeleteBehavior.Cascade); b.HasOne("EPlast.DataAccess.Entities.EventStatus", "EventStatus") .WithMany("Events") .HasForeignKey("EventStatusID") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("EPlast.DataAccess.Entities.EventAdmin", b => { b.HasOne("EPlast.DataAccess.Entities.Event", "Event") .WithMany("EventAdmins") .HasForeignKey("EventID") .OnDelete(DeleteBehavior.Cascade); b.HasOne("EPlast.DataAccess.Entities.User", "User") .WithMany("Events") .HasForeignKey("UserID") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("EPlast.DataAccess.Entities.EventGallary", b => { b.HasOne("EPlast.DataAccess.Entities.Event", "Event") .WithMany("EventGallarys") .HasForeignKey("EventID") .OnDelete(DeleteBehavior.Cascade); b.HasOne("EPlast.DataAccess.Entities.Gallary", "Gallary") .WithMany("Events") .HasForeignKey("GallaryID") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("EPlast.DataAccess.Entities.Participant", b => { b.HasOne("EPlast.DataAccess.Entities.Event", "Event") .WithMany("Participants") .HasForeignKey("EventId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("EPlast.DataAccess.Entities.ParticipantStatus", "ParticipantStatus") .WithMany("Participants") .HasForeignKey("ParticipantStatusId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("EPlast.DataAccess.Entities.User", "User") .WithMany("Participants") .HasForeignKey("UserId"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.RegionAdministration", b => { b.HasOne("EPlast.DataAccess.Entities.AdminType", "AdminType") .WithMany("RegionAdministration") .HasForeignKey("AdminTypeID") .OnDelete(DeleteBehavior.Cascade); b.HasOne("EPlast.DataAccess.Entities.Region", "Region") .WithMany("RegionAdministration") .HasForeignKey("RegionID"); b.HasOne("EPlast.DataAccess.Entities.User", "User") .WithMany("RegionAdministrations") .HasForeignKey("UserId"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.SubEventCategory", b => { b.HasOne("EPlast.DataAccess.Entities.EventCategory", "EventCategory") .WithMany("SubEventCategories") .HasForeignKey("EventCategoryID") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("EPlast.DataAccess.Entities.UnconfirmedCityMember", b => { b.HasOne("EPlast.DataAccess.Entities.City", "City") .WithMany("UnconfirmedCityMember") .HasForeignKey("CityID"); b.HasOne("EPlast.DataAccess.Entities.User", "User") .WithMany("UnconfirmedCityMembers") .HasForeignKey("UserId"); }); modelBuilder.Entity("EPlast.DataAccess.Entities.User", b => { b.HasOne("EPlast.DataAccess.Entities.Nationality") .WithMany("Users") .HasForeignKey("NationalityID"); b.HasOne("EPlast.DataAccess.Entities.UserProfile", "UserProfile") .WithOne("User") .HasForeignKey("EPlast.DataAccess.Entities.User", "UserProfileID") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("EPlast.DataAccess.Entities.UserProfile", b => { b.HasOne("EPlast.DataAccess.Entities.Education", "Education") .WithMany("UsersProfiles") .HasForeignKey("EducationID"); b.HasOne("EPlast.DataAccess.Entities.Gender", "Gender") .WithMany("UserProfiles") .HasForeignKey("GenderID"); b.HasOne("EPlast.DataAccess.Entities.Nationality", "Nationality") .WithMany("UserProfiles") .HasForeignKey("NationalityID"); b.HasOne("EPlast.DataAccess.Entities.Religion", "Religion") .WithMany("UserProfiles") .HasForeignKey("ReligionID"); b.HasOne("EPlast.DataAccess.Entities.Work", "Work") .WithMany("UserProfiles") .HasForeignKey("WorkID"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("EPlast.DataAccess.Entities.User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("EPlast.DataAccess.Entities.User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("EPlast.DataAccess.Entities.User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("EPlast.DataAccess.Entities.User") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
36.027451
125
0.46679
[ "MIT" ]
Toxa2202/plast
EPlast/EPlast.DataAccess/Migrations/20200302143114_Init.Designer.cs
45,937
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. // // // // Description: Figure length implementation // // // using MS.Internal; using System.ComponentModel; using System.Globalization; using MS.Internal.PtsHost.UnsafeNativeMethods; // PTS restrictions namespace System.Windows { /// <summary> /// FigureUnitType enum is used to indicate what kind of value the /// FigureLength is holding. /// </summary> public enum FigureUnitType { /// <summary> /// The value indicates that content should be calculated without constraints. /// </summary> Auto = 0, /// <summary> /// The value is expressed as a pixel. /// </summary> Pixel, /// <summary> /// The value is expressed as fraction of column width. /// </summary> Column, /// <summary> /// The value is expressed as a fraction of content width. /// </summary> Content, /// <summary> /// The value is expressed as a fraction of page width. /// </summary> Page, } /// <summary> /// FigureLength is the type used for height and width on figure element /// </summary> [TypeConverter(typeof(FigureLengthConverter))] public struct FigureLength : IEquatable<FigureLength> { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors /// <summary> /// Constructor, initializes the FigureLength as absolute value in pixels. /// </summary> /// <param name="pixels">Specifies the number of 'device-independent pixels' /// (96 pixels-per-inch).</param> /// <exception cref="ArgumentException"> /// If <c>pixels</c> parameter is <c>double.NaN</c> /// or <c>pixels</c> parameter is <c>double.NegativeInfinity</c> /// or <c>pixels</c> parameter is <c>double.PositiveInfinity</c>. /// or <c>value</c> parameter is <c>negative</c>. /// </exception> public FigureLength(double pixels) : this(pixels, FigureUnitType.Pixel) { } /// <summary> /// Constructor, initializes the FigureLength and specifies what kind of value /// it will hold. /// </summary> /// <param name="value">Value to be stored by this FigureLength /// instance.</param> /// <param name="type">Type of the value to be stored by this FigureLength /// instance.</param> /// <remarks> /// If the <c>type</c> parameter is <c>FigureUnitType.Auto</c>, /// then passed in value is ignored and replaced with <c>0</c>. /// </remarks> /// <exception cref="ArgumentException"> /// If <c>value</c> parameter is <c>double.NaN</c> /// or <c>value</c> parameter is <c>double.NegativeInfinity</c> /// or <c>value</c> parameter is <c>double.PositiveInfinity</c>. /// or <c>value</c> parameter is <c>negative</c>. /// </exception> public FigureLength(double value, FigureUnitType type) { double maxColumns = PTS.Restrictions.tscColumnRestriction; double maxPixel = Math.Min(1000000, PTS.MaxPageSize); if (DoubleUtil.IsNaN(value)) { throw new ArgumentException(SR.Get(SRID.InvalidCtorParameterNoNaN, "value")); } if (double.IsInfinity(value)) { throw new ArgumentException(SR.Get(SRID.InvalidCtorParameterNoInfinity, "value")); } if (value < 0.0) { throw new ArgumentOutOfRangeException(SR.Get(SRID.InvalidCtorParameterNoNegative, "value")); } if ( type != FigureUnitType.Auto && type != FigureUnitType.Pixel && type != FigureUnitType.Column && type != FigureUnitType.Content && type != FigureUnitType.Page ) { throw new ArgumentException(SR.Get(SRID.InvalidCtorParameterUnknownFigureUnitType, "type")); } if(value > 1.0 && (type == FigureUnitType.Content || type == FigureUnitType.Page)) { throw new ArgumentOutOfRangeException("value"); } if (value > maxColumns && type == FigureUnitType.Column) { throw new ArgumentOutOfRangeException("value"); } if (value > maxPixel && type == FigureUnitType.Pixel) { throw new ArgumentOutOfRangeException("value"); } _unitValue = (type == FigureUnitType.Auto) ? 0.0 : value; _unitType = type; } #endregion Constructors //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ #region Public Methods /// <summary> /// Overloaded operator, compares 2 FigureLengths. /// </summary> /// <param name="fl1">first FigureLength to compare.</param> /// <param name="fl2">second FigureLength to compare.</param> /// <returns>true if specified FigureLengths have same value /// and unit type.</returns> public static bool operator == (FigureLength fl1, FigureLength fl2) { return ( fl1.FigureUnitType == fl2.FigureUnitType && fl1.Value == fl2.Value ); } /// <summary> /// Overloaded operator, compares 2 FigureLengths. /// </summary> /// <param name="fl1">first FigureLength to compare.</param> /// <param name="fl2">second FigureLength to compare.</param> /// <returns>true if specified FigureLengths have either different value or /// unit type.</returns> public static bool operator != (FigureLength fl1, FigureLength fl2) { return ( fl1.FigureUnitType != fl2.FigureUnitType || fl1.Value != fl2.Value ); } /// <summary> /// Compares this instance of FigureLength with another object. /// </summary> /// <param name="oCompare">Reference to an object for comparison.</param> /// <returns><c>true</c>if this FigureLength instance has the same value /// and unit type as oCompare.</returns> override public bool Equals(object oCompare) { if(oCompare is FigureLength) { FigureLength l = (FigureLength)oCompare; return (this == l); } else return false; } /// <summary> /// Compares this instance of FigureLength with another object. /// </summary> /// <param name="figureLength">FigureLength to compare.</param> /// <returns><c>true</c>if this FigureLength instance has the same value /// and unit type as figureLength.</returns> public bool Equals(FigureLength figureLength) { return (this == figureLength); } /// <summary> /// <see cref="Object.GetHashCode"/> /// </summary> /// <returns><see cref="Object.GetHashCode"/></returns> public override int GetHashCode() { return ((int)_unitValue + (int)_unitType); } /// <summary> /// Returns <c>true</c> if this FigureLength instance holds /// an absolute (pixel) value. /// </summary> public bool IsAbsolute { get { return (_unitType == FigureUnitType.Pixel); } } /// <summary> /// Returns <c>true</c> if this FigureLength instance is /// automatic (not specified). /// </summary> public bool IsAuto { get { return (_unitType == FigureUnitType.Auto); } } /// <summary> /// Returns <c>true</c> if this FigureLength instance is column relative. /// </summary> public bool IsColumn { get { return (_unitType == FigureUnitType.Column); } } /// <summary> /// Returns <c>true</c> if this FigureLength instance is content relative. /// </summary> public bool IsContent { get { return (_unitType == FigureUnitType.Content); } } /// <summary> /// Returns <c>true</c> if this FigureLength instance is page relative. /// </summary> public bool IsPage { get { return (_unitType == FigureUnitType.Page); } } /// <summary> /// Returns value part of this FigureLength instance. /// </summary> public double Value { get { return ((_unitType == FigureUnitType.Auto) ? 1.0 : _unitValue); } } /// <summary> /// Returns unit type of this FigureLength instance. /// </summary> public FigureUnitType FigureUnitType { get { return (_unitType); } } /// <summary> /// Returns the string representation of this object. /// </summary> public override string ToString() { return FigureLengthConverter.ToString(this, CultureInfo.InvariantCulture); } #endregion Public Methods //------------------------------------------------------ // // Private Fields // //------------------------------------------------------ #region Private Fields private double _unitValue; // unit value storage private FigureUnitType _unitType; // unit type storage #endregion Private Fields } }
36.522059
108
0.538655
[ "MIT" ]
56hide/wpf
src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/figurelength.cs
9,934
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Http; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; namespace EvolFx.TMovie.Website { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } } }
27.875
70
0.713004
[ "Apache-2.0" ]
supernebula/evol-core
src/EvolFx.TMovie.Website/Global.asax.cs
671
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using Microsoft.Data.Entity.ChangeTracking.Internal; using Microsoft.Data.Entity.Infrastructure; using Microsoft.Data.Entity.Internal; using Microsoft.Data.Entity.Storage; using Microsoft.Data.Entity.Update; using Microsoft.Framework.DependencyInjection; using Xunit; namespace Microsoft.Data.Entity.Tests.Update { public class ModificationCommandComparerTest { [Fact] public void Compare_returns_0_only_for_commands_that_are_equal() { var model = new Entity.Metadata.Model(); var entityType = model.AddEntityType(typeof(object)); var optionsBuilder = new DbContextOptionsBuilder() .UseModel(model); optionsBuilder.UseInMemoryDatabase(persist: false); var contextServices = new DbContext(optionsBuilder.Options).GetService(); var stateManager = contextServices.GetRequiredService<IStateManager>(); var key = entityType.GetOrAddProperty("Id", typeof(int), shadowProperty: true); entityType.GetOrSetPrimaryKey(key); var entry1 = stateManager.GetOrCreateEntry(new object()); entry1[key] = 1; entry1.SetEntityState(EntityState.Added); var modificationCommandAdded = new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()); modificationCommandAdded.AddEntry(entry1); var entry2 = stateManager.GetOrCreateEntry(new object()); entry2[key] = 2; entry2.SetEntityState(EntityState.Modified); var modificationCommandModified = new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()); modificationCommandModified.AddEntry(entry2); var entry3 = stateManager.GetOrCreateEntry(new object()); entry3[key] = 3; entry3.SetEntityState(EntityState.Deleted); var modificationCommandDeleted = new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()); modificationCommandDeleted.AddEntry(entry3); var mCC = new ModificationCommandComparer(); Assert.True(0 == mCC.Compare(modificationCommandAdded, modificationCommandAdded)); Assert.True(0 == mCC.Compare(null, null)); Assert.True(0 == mCC.Compare( new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()), new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()))); Assert.True(0 > mCC.Compare(null, new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()))); Assert.True(0 < mCC.Compare(new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()), null)); Assert.True(0 > mCC.Compare( new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()), new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()))); Assert.True(0 < mCC.Compare( new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()), new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()))); Assert.True(0 > mCC.Compare( new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()), new ModificationCommand("A", "foo", new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()))); Assert.True(0 < mCC.Compare( new ModificationCommand("A", "foo", new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()), new ModificationCommand("A", "dbo", new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()))); Assert.True(0 > mCC.Compare( new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()), new ModificationCommand("B", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()))); Assert.True(0 < mCC.Compare( new ModificationCommand("B", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()), new ModificationCommand("A", null, new ParameterNameGenerator(), p => p.Relational(), new UntypedValueBufferFactoryFactory()))); Assert.True(0 > mCC.Compare(modificationCommandModified, modificationCommandAdded)); Assert.True(0 < mCC.Compare(modificationCommandAdded, modificationCommandModified)); Assert.True(0 > mCC.Compare(modificationCommandDeleted, modificationCommandAdded)); Assert.True(0 < mCC.Compare(modificationCommandAdded, modificationCommandDeleted)); Assert.True(0 > mCC.Compare(modificationCommandDeleted, modificationCommandModified)); Assert.True(0 < mCC.Compare(modificationCommandModified, modificationCommandDeleted)); } } }
62.210526
174
0.685956
[ "Apache-2.0" ]
suryasnath/csharp
test/EntityFramework.Relational.Tests/Update/ModificationCommandComparerTest.cs
5,910
C#
using System; using Automata.Properties; namespace Automata { public class Rule { private int[] _testCase = {0, 0, 0}; private string _name = "Rule"; /// <summary> /// Default constructor for Rule class. /// </summary> public Rule() { // Use default of all empty returns empty color. } /// <summary> /// Constructor for Rule class. /// </summary> /// <param name="testPattern">Color pattern that makes this rule return true.</param> /// <param name="trueColor">Color to return if rule pattern is matched.</param> public Rule(int[] testPattern, int trueColor) { if (testPattern.Length != 3) { throw new ArgumentException(Resources.error2 + testPattern.Length, nameof(testPattern)); } _testCase = testPattern; Color = trueColor; } /// <summary> /// Constructor for Rule class. /// </summary> /// <param name="testPattern">Color pattern that makes this rule return true.</param> /// <param name="trueColor">Color to return if rule pattern is matched.</param> /// <param name="ruleName">Name of rule.</param> public Rule(int[] testPattern, int trueColor, string ruleName) { if (testPattern.Length != 3) { throw new ArgumentException(Resources.error2 + testPattern.Length, nameof(testPattern)); } _testCase = testPattern; Color = trueColor; Name = ruleName; } /// <summary> /// Takes an nearest neighbors and checks against initialized rule pattern. /// </summary> /// <param name="blockLeft">Block up and to the left.</param> /// <param name="blockMid">Block directly above test square.</param> /// <param name="blockRight">Block up and to the right.</param> /// <returns>Result of test.</returns> public bool Test(int blockLeft, int blockMid, int blockRight) { return _testCase[0] == blockLeft && _testCase[1] == blockMid && _testCase[2] == blockRight; } /// <summary> /// Result color that should be set when rule returns true. /// </summary> public int Color { get; set; } /// <summary> /// Name of rule in GUI tool. /// </summary> public string Name { get { return _name; } set { if (value == "") { throw new ArgumentException(Resources.error3, nameof(value)); } _name = value; } } /// <summary> /// Test pattern for check function. /// </summary> public int[] Pattern { get { return _testCase; } set { if (value.Length != 3) { throw new ArgumentException(Resources.error2 + value.Length, nameof(value)); } _testCase = value; } } } }
31.831683
104
0.508865
[ "MIT" ]
ARMmaster17/Automata
Automata/Rule.cs
3,217
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 Sage.CA.SBS.ERP.Sage300.AP.Resources.Forms { 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", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class GLIntegrationResx { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal GLIntegrationResx() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Sage.CA.SBS.ERP.Sage300.AP.Resources.Forms.GLIntegrationResx", typeof(GLIntegrationResx).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)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Adding to an Existing Batch. /// </summary> public static string AddingToExistingBatch { get { return ResourceManager.GetString("AddingToExistingBatch", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Adjustment. /// </summary> public static string Adjustment { get { return ResourceManager.GetString("Adjustment", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Exclude. /// </summary> public static string BtnExclude { get { return ResourceManager.GetString("BtnExclude", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Include. /// </summary> public static string BtnInclude { get { return ResourceManager.GetString("BtnInclude", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Choose Segment From List. /// </summary> public static string ChooseSegmentFromList { get { return ResourceManager.GetString("ChooseSegmentFromList", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Available Segments. /// </summary> public static string ChooseSegmentsFromList { get { return ResourceManager.GetString("ChooseSegmentsFromList", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Consolidate by Posting Sequence, Account, and Fiscal Period. /// </summary> public static string ConsolidateByPostAccFisc { get { return ResourceManager.GetString("ConsolidateByPostAccFisc", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Consolidate by Posting Sequence, Account, Fiscal Period, and Source. /// </summary> public static string ConsolidateByPostAccFiscSource { get { return ResourceManager.GetString("ConsolidateByPostAccFiscSource", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Consolidate G/L Batches. /// </summary> public static string ConsolidateGLBatches { get { return ResourceManager.GetString("ConsolidateGLBatches", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Consolidation. /// </summary> public static string Consolidation { get { return ResourceManager.GetString("Consolidation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Creating and Posting a New Batch. /// </summary> public static string CreatingandPostingNewBatch { get { return ResourceManager.GetString("CreatingandPostingNewBatch", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Creating A New Batch. /// </summary> public static string CreatingNewBatch { get { return ResourceManager.GetString("CreatingNewBatch", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Credit Note. /// </summary> public static string CreditNote { get { return ResourceManager.GetString("CreditNote", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Debit Note. /// </summary> public static string DebitNote { get { return ResourceManager.GetString("DebitNote", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Discount. /// </summary> public static string Discount { get { return ResourceManager.GetString("Discount", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Do Not Consolidate. /// </summary> public static string DoNotConsolidate { get { return ResourceManager.GetString("DoNotConsolidate", resourceCulture); } } /// <summary> /// Looks up a localized string similar to During Posting. /// </summary> public static string DuringPosting { get { return ResourceManager.GetString("DuringPosting", resourceCulture); } } /// <summary> /// Looks up a localized string similar to A/P G/L Integration. /// </summary> public static string Entity { get { return ResourceManager.GetString("Entity", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Example. /// </summary> public static string Example { get { return ResourceManager.GetString("Example", resourceCulture); } } /// <summary> /// Looks up a localized string similar to G/L Detail Comment. /// </summary> public static string GLDetailComment { get { return ResourceManager.GetString("GLDetailComment", resourceCulture); } } /// <summary> /// Looks up a localized string similar to G/L Detail Description. /// </summary> public static string GLDetailDescription { get { return ResourceManager.GetString("GLDetailDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to G/L Detail Reference. /// </summary> public static string GLDetailReference { get { return ResourceManager.GetString("GLDetailReference", resourceCulture); } } /// <summary> /// Looks up a localized string similar to G/L Entry Description. /// </summary> public static string GLEntryDescription { get { return ResourceManager.GetString("GLEntryDescription", resourceCulture); } } /// <summary> /// Looks up a localized string similar to G/L Integration Detail. /// </summary> public static string GLIntegrationDetail { get { return ResourceManager.GetString("GLIntegrationDetail", resourceCulture); } } /// <summary> /// Looks up a localized string similar to G/L Source Codes. /// </summary> public static string GLSourceCodes { get { return ResourceManager.GetString("GLSourceCodes", resourceCulture); } } /// <summary> /// Looks up a localized string similar to G/L Transaction Field. /// </summary> public static string GLTransactionField { get { return ResourceManager.GetString("GLTransactionField", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Interest. /// </summary> public static string Interest { get { return ResourceManager.GetString("Interest", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Invoice. /// </summary> public static string Invoice { get { return ResourceManager.GetString("Invoice", resourceCulture); } } /// <summary> /// Looks up a localized string similar to On Request Using Create G/L Batch Screen. /// </summary> public static string OnRequestGLBatch { get { return ResourceManager.GetString("OnRequestGLBatch", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Payment. /// </summary> public static string Payment { get { return ResourceManager.GetString("Payment", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Payment Posting Sequence. /// </summary> public static string PaymentPostingSequence { get { return ResourceManager.GetString("PaymentPostingSequence", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Payment Reversal. /// </summary> public static string PaymentReversal { get { return ResourceManager.GetString("PaymentReversal", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Posting Sequence Number. /// </summary> public static string PostingSequenceNumber { get { return ResourceManager.GetString("PostingSequenceNumber", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Prepayment. /// </summary> public static string Prepayment { get { return ResourceManager.GetString("Prepayment", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Revaluation. /// </summary> public static string Revaluation { get { return ResourceManager.GetString("Revaluation", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Rounding. /// </summary> public static string Rounding { get { return ResourceManager.GetString("Rounding", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use Segments. /// </summary> public static string SegmentCurrentlyUsed { get { return ResourceManager.GetString("SegmentCurrentlyUsed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Segments Currently Used. /// </summary> public static string SegmentsCurrentlyUsed { get { return ResourceManager.GetString("SegmentsCurrentlyUsed", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Segment Separator. /// </summary> public static string SegmentSeparator { get { return ResourceManager.GetString("SegmentSeparator", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Source Ledger. /// </summary> public static string SourceLedger { get { return ResourceManager.GetString("SourceLedger", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Source Type. /// </summary> public static string SourceType { get { return ResourceManager.GetString("SourceType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Transaction Type. /// </summary> public static string TransactionType { get { return ResourceManager.GetString("TransactionType", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Transaction type &quot;{0}&quot; and G/L transaction field &quot;{1}&quot; cannot be combined.. /// </summary> public static string WarningApglrefInvalid { get { return ResourceManager.GetString("WarningApglrefInvalid", resourceCulture); } } } }
35.365854
213
0.541881
[ "MIT" ]
PeterSorokac/Sage300-SDK
resources/Sage300Resources/Sage.CA.SBS.ERP.Sage300.AP.Resources/Forms/GLIntegrationResx.Designer.cs
15,952
C#
using System.Text.Json.Serialization; using Jobba.Core.Extensions; using Jobba.MassTransit.Extensions; using Jobba.Redis; using Jobba.Store.Mongo.Extensions; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.OpenApi.Models; namespace Jobba.Web.Sample { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers() .AddJsonOptions(o => { o.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()); o.JsonSerializerOptions.Converters.Add(new TimeSpanStringConverter()); }); services.AddSwaggerGen(c => c.SwaggerDoc("v1", new OpenApiInfo { Title = "Jobba.Web.Sample", Version = "v1" })); services .AddLogging(o => o.AddSimpleConsole(c => c.TimestampFormat = "[yyyy-MM-dd HH:mm:ss] ")) .AddJobba(jobba => jobba.UsingMassTransit() .UsingMongo("mongodb://localhost:27017/jobba-web-sample", false) .UsingLitRedis("localhost:6379,defaultDatabase=0") .AddJob<SampleWebJob, SampleWebJobParameters, SampleWebJobState>() .AddJob<SampleFaultWebJob, SampleFaultWebJobParameters, SampleFaultWebJobState>() ) .AddJobbaSampleMassTransit("rabbitmq://guest:guest@localhost/"); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Jobba.Web.Sample v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => endpoints.MapControllers()); } } }
38.537313
124
0.623548
[ "MIT" ]
firebend/jobba
Jobba.Web.Sample/Startup.cs
2,582
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SensorTag { public static class ConversionExtensions { public static double ToFahrenheit(this double celcius) { return 32.0 + (celcius * 9) / 5; } } }
18.222222
62
0.655488
[ "Apache-2.0" ]
clovett/SensorTag-for-Windows
SensorTag/SharedControls/Helpers/ConversionExtensions.cs
330
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PauseGame : MonoBehaviour { public GameObject PausePanel; public bool paused = false; void Start() { PausePanel.SetActive (false); } void Update() { if (Input.GetButtonDown ("Pause")) { paused = !paused; } if (paused) { PausePanel.SetActive (true); Time.timeScale = 0; AudioListener.volume = 0; } if (!paused) { PausePanel.SetActive (false); Time.timeScale = 1; AudioListener.volume = 1; } } public void pauseButton() { paused = !paused; } public void Resume() { paused = false; } public void Restart() { //Application.LoadLevel (Application.loadedLevel); UnityEngine.SceneManagement.SceneManager.LoadScene ("Battle"); } public void MainMenu() { //Application.LoadLevel (0); UnityEngine.SceneManagement.SceneManager.LoadScene ("MenuInicial"); } public void SelectStage() { UnityEngine.SceneManagement.SceneManager.LoadScene ("SelectStage"); } public void Quit() { //Application.Quit(); UnityEngine.SceneManagement.SceneManager.LoadScene ("MenuInicial"); } }
18.688525
69
0.695614
[ "MIT" ]
gabrielgrs/Elementals
src/Assets/Scripts/UI/PauseGame.cs
1,142
C#
using FubuDocs; namespace FubuValidation.Docs.Customization { public class ConfiguringWhichRoutesHaveValidation : Topic { public ConfiguringWhichRoutesHaveValidation() : base("Configuring which routes have validation") { } } }
22
104
0.708333
[ "Apache-2.0" ]
DovetailSoftware/fubuvalidation
src/FubuValidation.Docs/Customization/ConfiguringWhichRoutesHaveValidation.cs
264
C#
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System; namespace DotNetNuke.ExtensionPoints { public interface IEditPagePanelControlActions { void SaveAction(int portalId, int tabId, int moduleId); void CancelAction(int portalId, int tabId, int moduleId); void BindAction(int portalId, int tabId, int moduleId); } }
29.875
101
0.717573
[ "MIT" ]
CMarius94/Dnn.Platform
DNN Platform/Library/ExtensionPoints/IEditPagePanelControlActions.cs
480
C#
// -------------------------------------------------------------------------------------------- #region // Copyright (c) 2022, SIL International. All Rights Reserved. // <copyright from='2011' to='2022' company='SIL International'> // Copyright (c) 2022, SIL International. All Rights Reserved. // // Distributable under the terms of the MIT License (https://sil.mit-license.org/) // </copyright> #endregion // -------------------------------------------------------------------------------------------- using System; using System.Windows.Forms; using HearThis.Publishing; namespace HearThis.Script { public class BookInfo { public readonly int ChapterCount; /// <summary> /// Constructs an object that holds information about a Scripture book in a particular project /// </summary> /// <param name="projectName">Name of project containing the book</param> /// <param name="number">0-based book number</param> /// <param name="scriptProvider">The object that supplies information about the translated text /// and the text of individual blocks</param> public BookInfo(string projectName, int number, IScriptProvider scriptProvider) { BookNumber = number; ProjectName = projectName; Name = scriptProvider.VersificationInfo.GetBookName(number); ChapterCount = scriptProvider.VersificationInfo.GetChaptersInBook(number); ScriptProvider = scriptProvider; } // TODO: Implement this - probably as part of making this a Paratext plugin public string LocalizedName => Name; /// <summary> /// 0-based book number /// </summary> public int BookNumber { get; } // That is, has some translated material (for the current character, if any) public bool HasVerses { get { for (int i = 0; i < ScriptProvider.VersificationInfo.GetChaptersInBook(BookNumber); i++) { if (ScriptProvider.GetTranslatedVerseCount(BookNumber, i + 1) > 0) { return true; } } return false; } } public ScriptLine GetBlock(int chapter, int block) { return ScriptProvider.GetBlock(BookNumber, chapter, block); } public ScriptLine GetUnfilteredBlock(int chapter, int block) { return ScriptProvider.GetUnfilteredBlock(BookNumber, chapter, block); } public string Name { get; } public bool HasIntroduction => ScriptProvider.GetUnfilteredScriptBlockCount(BookNumber, 0) > 0; internal string ProjectName { get; } /// <summary> /// [0] == intro, [1] == chapter 1, etc. /// </summary> internal IScriptProvider ScriptProvider { get; } /// <summary> /// Gets 0 if there is an intro before chapter 1; otherwise returns 1 /// </summary> internal int FirstChapterNumber => HasIntroduction ? 0 : 1; /// <summary> /// Gets intro or chapter 1, whichever comes first /// </summary> public ChapterInfo GetFirstChapter() { return GetChapter(FirstChapterNumber); } public ChapterInfo GetChapter(int chapterOneBased) { return ChapterInfo.Create(this, chapterOneBased); } public int CalculatePercentageRecorded() { int scriptBlockCount = ScriptProvider.GetScriptBlockCount(BookNumber); if (scriptBlockCount == 0) return 0; //should it be 0 or 100 or -1 or what? int countOfRecordingsForBook = ClipRepository.GetCountOfRecordingsForBook(ProjectName, Name, ScriptProvider); if (countOfRecordingsForBook == 0) return 0; return Math.Max(1, (int)(100.0 * countOfRecordingsForBook / scriptBlockCount)); } /// <summary> /// Indicates whether there is any content for this book. (Note: In the case of a multi-voice. /// script, this returns false if there is nothing in the book for the current character). /// </summary> public bool HasTranslatedContent { get { for (int chapter = 0; chapter < ScriptProvider.VersificationInfo.GetChaptersInBook(BookNumber); chapter++) { if (ScriptProvider.GetTranslatedVerseCount(BookNumber, chapter) > 0) return true; } return false; } } public ProblemType GetWorstProblemInBook() { var worst = ProblemType.None; for (var i = 0; i <= ChapterCount; i++) { var worstInChapter = GetChapter(i).WorstProblemInChapter; if (worstInChapter > worst) { // For our purposes, we treat all unresolved major problems as equally bad // (i.e., in need of attention). If a problem is minor or has been resolved, // it does not need attention, so we keep looking to see if we come across // something that does. if (worstInChapter.NeedsAttention()) return worstInChapter; worst = worstInChapter; } } return worst; } public void MakeDummyRecordings() { Cursor.Current = Cursors.WaitCursor; for (int c = 0 /*0 is introduction*/; c <= ChapterCount; c++) { GetChapter(c).MakeDummyRecordings(); } Cursor.Current = Cursors.Default; } /// <summary> /// Virtual for testing /// </summary> public virtual string GetChapterFolder(int chapterNumber) { return ClipRepository.GetChapterFolder(ProjectName, Name, chapterNumber); } public virtual int GetCountOfRecordingsForChapter(int chapterNumber) { return ClipRepository.GetCountOfRecordingsInFolder(GetChapterFolder(chapterNumber), ScriptProvider); } } }
30.596491
112
0.676606
[ "MIT" ]
sillsdev/HearThis
src/HearThis/Script/BookInfo.cs
5,232
C#
using System; using System.IO; using BenchmarkDotNet.Characteristics; using BenchmarkDotNet.Environments; using BenchmarkDotNet.Extensions; using BenchmarkDotNet.Jobs; using BenchmarkDotNet.Loggers; using BenchmarkDotNet.Running; using BenchmarkDotNet.Toolchains.DotNetCli; using JetBrains.Annotations; namespace BenchmarkDotNet.Toolchains.CsProj { [PublicAPI] public class CsProjCoreToolchain : Toolchain { [PublicAPI] public static readonly IToolchain NetCoreApp20 = From(NetCoreAppSettings.NetCoreApp20); [PublicAPI] public static readonly IToolchain NetCoreApp21 = From(NetCoreAppSettings.NetCoreApp21); [PublicAPI] public static readonly IToolchain NetCoreApp22 = From(NetCoreAppSettings.NetCoreApp22); [PublicAPI] public static readonly IToolchain NetCoreApp30 = From(NetCoreAppSettings.NetCoreApp30); [PublicAPI] public static readonly Lazy<IToolchain> Current = new Lazy<IToolchain>(() => From(NetCoreAppSettings.GetCurrentVersion())); private CsProjCoreToolchain(string name, IGenerator generator, IBuilder builder, IExecutor executor, string customDotNetCliPath) : base(name, generator, builder, executor) { CustomDotNetCliPath = customDotNetCliPath; } internal string CustomDotNetCliPath { get; } [PublicAPI] public static IToolchain From(NetCoreAppSettings settings) => new CsProjCoreToolchain(settings.Name, new CsProjGenerator(settings.TargetFrameworkMoniker, settings.CustomDotNetCliPath, settings.PackagesPath, settings.RuntimeFrameworkVersion), new DotNetCliBuilder(settings.TargetFrameworkMoniker, settings.CustomDotNetCliPath, settings.Timeout), new DotNetCliExecutor(settings.CustomDotNetCliPath), settings.CustomDotNetCliPath); public override bool IsSupported(BenchmarkCase benchmarkCase, ILogger logger, IResolver resolver) { if (!base.IsSupported(benchmarkCase, logger, resolver)) return false; if (InvalidCliPath(CustomDotNetCliPath, benchmarkCase, logger)) return false; if (benchmarkCase.Job.HasValue(EnvironmentMode.JitCharacteristic) && benchmarkCase.Job.ResolveValue(EnvironmentMode.JitCharacteristic, resolver) == Jit.LegacyJit) { logger.WriteLineError($"Currently dotnet cli toolchain supports only RyuJit, benchmark '{benchmarkCase.DisplayInfo}' will not be executed"); return false; } if (benchmarkCase.Job.ResolveValue(GcMode.CpuGroupsCharacteristic, resolver)) { logger.WriteLineError($"Currently project.json does not support CpuGroups (app.config does), benchmark '{benchmarkCase.DisplayInfo}' will not be executed"); return false; } if (benchmarkCase.Job.ResolveValue(GcMode.AllowVeryLargeObjectsCharacteristic, resolver)) { logger.WriteLineError($"Currently project.json does not support gcAllowVeryLargeObjects (app.config does), benchmark '{benchmarkCase.DisplayInfo}' will not be executed"); return false; } return true; } } }
48.985075
186
0.705058
[ "MIT" ]
kevinmiles/BenchmarkDotNet
src/BenchmarkDotNet/Toolchains/CsProj/CsProjCoreToolchain.cs
3,284
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\EntityCollectionRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type EducationRootUsersCollectionRequest. /// </summary> public partial class EducationRootUsersCollectionRequest : BaseRequest, IEducationRootUsersCollectionRequest { /// <summary> /// Constructs a new EducationRootUsersCollectionRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public EducationRootUsersCollectionRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Adds the specified EducationUser to the collection via POST. /// </summary> /// <param name="educationUser">The EducationUser to add.</param> /// <returns>The created EducationUser.</returns> public System.Threading.Tasks.Task<EducationUser> AddAsync(EducationUser educationUser) { return this.AddAsync(educationUser, CancellationToken.None); } /// <summary> /// Adds the specified EducationUser to the collection via POST. /// </summary> /// <param name="educationUser">The EducationUser to add.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created EducationUser.</returns> public System.Threading.Tasks.Task<EducationUser> AddAsync(EducationUser educationUser, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; return this.SendAsync<EducationUser>(educationUser, cancellationToken); } /// <summary> /// Gets the collection page. /// </summary> /// <returns>The collection page.</returns> public System.Threading.Tasks.Task<IEducationRootUsersCollectionPage> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the collection page. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The collection page.</returns> public async System.Threading.Tasks.Task<IEducationRootUsersCollectionPage> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var response = await this.SendAsync<EducationRootUsersCollectionResponse>(null, cancellationToken).ConfigureAwait(false); if (response != null && response.Value != null && response.Value.CurrentPage != null) { if (response.AdditionalData != null) { object nextPageLink; response.AdditionalData.TryGetValue("@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { response.Value.InitializeNextPageRequest( this.Client, nextPageLinkString); } // Copy the additional data collection to the page itself so that information is not lost response.Value.AdditionalData = response.AdditionalData; } return response.Value; } return null; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IEducationRootUsersCollectionRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IEducationRootUsersCollectionRequest Expand(Expression<Func<EducationUser, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IEducationRootUsersCollectionRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IEducationRootUsersCollectionRequest Select(Expression<Func<EducationUser, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Adds the specified top value to the request. /// </summary> /// <param name="value">The top value.</param> /// <returns>The request object to send.</returns> public IEducationRootUsersCollectionRequest Top(int value) { this.QueryOptions.Add(new QueryOption("$top", value.ToString())); return this; } /// <summary> /// Adds the specified filter value to the request. /// </summary> /// <param name="value">The filter value.</param> /// <returns>The request object to send.</returns> public IEducationRootUsersCollectionRequest Filter(string value) { this.QueryOptions.Add(new QueryOption("$filter", value)); return this; } /// <summary> /// Adds the specified skip value to the request. /// </summary> /// <param name="value">The skip value.</param> /// <returns>The request object to send.</returns> public IEducationRootUsersCollectionRequest Skip(int value) { this.QueryOptions.Add(new QueryOption("$skip", value.ToString())); return this; } /// <summary> /// Adds the specified orderby value to the request. /// </summary> /// <param name="value">The orderby value.</param> /// <returns>The request object to send.</returns> public IEducationRootUsersCollectionRequest OrderBy(string value) { this.QueryOptions.Add(new QueryOption("$orderby", value)); return this; } } }
40.228311
153
0.579909
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/EducationRootUsersCollectionRequest.cs
8,810
C#
using System; using System.Collections.Generic; using System.Linq; using FluentAssertions; using Rocks.SimpleInjector.NotThreadSafeCheck; using Rocks.SimpleInjector.NotThreadSafeCheck.Models; using SimpleInjector; using SimpleInjector.Diagnostics; using SimpleInjector.Lifestyles; using Xunit; namespace Rocks.Profiling.Tests { public class DependencyInjectionConfigTests { [Fact] public void Setup_Always_Verifiable_AndContainsNoDiagnosticWarnings() { // arrange var container = new Container { Options = { AllowOverridingRegistrations = true } }; ProfilingLibrary.Setup(() => null, container); // act, assert container.Verify(); var result = Analyzer.Analyze(container); result = result.Where(x => x.DiagnosticType != DiagnosticType.SingleResponsibilityViolation).ToArray(); result.Should().BeEmpty(because: Environment.NewLine + string.Join(Environment.NewLine, result.Select(x => x.Description))); } [Fact] public void Setup_Always_DoesNotHaveNonThreadSafeSingletons() { // arrange var container = new Container { Options = { AllowOverridingRegistrations = true } }; ProfilingLibrary.Setup(() => null, container); var assembly = typeof(ProfilingLibrary).Assembly; // act var result = container .GetRegistrationsInfo(x => x.Lifestyle == Lifestyle.Singleton && x.ServiceType.Assembly == assembly) .Where(x => !x.HasSingletonAttribute && x.HasNotThreadSafeMembers && !x.ImplementationType.Name.EndsWith("Configuration")) .Select(x => $"Potential non thread safe singleton {x.ImplementationType}:\n" + $"{string.Join(Environment.NewLine, x.NotThreadSafeMembers)}\n\n") .ToList(); // assert result.Should() .BeEmpty(because: Environment.NewLine + "there are potential non thread safe singleton registrations " + "which are not marked with [Singleton] attribute." + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, result)); } [Fact] public void Setup_Always_DoesNotHaveThreadSafeNonSingletons() { // arrange var container = new Container { Options = { AllowOverridingRegistrations = true } }; ProfilingLibrary.Setup(() => null, container); var assembly = typeof(ProfilingLibrary).Assembly; // act IList<SimpleInjectorRegistrationInfo> registration_infos; List<string> result; using (AsyncScopedLifestyle.BeginScope(container)) { registration_infos = container.GetRegistrationsInfo(x => x.Lifestyle != Lifestyle.Singleton && x.ServiceType.Assembly == assembly, x => x.KnownNotMutableTypes.Add(typeof(Container))); result = registration_infos .Where(x => !x.HasNotThreadSafeMembers && !x.HasNotSingletonAttribute) .Select(x => $"Potential thread safe non singleton: {x.ImplementationType}.") .OrderBy(x => x) .ToList(); } // assert result.Should() .BeEmpty(because: Environment.NewLine + "there are potential thread safe non singleton registrations " + "which are not marked with [NotSingleton] attribute." + Environment.NewLine + Environment.NewLine + string.Join(Environment.NewLine, result) + Environment.NewLine + Environment.NewLine); foreach (var message in registration_infos.Where(x => !x.HasNotSingletonAttribute) .Select(x => $"Not singleton: {x.ImplementationType}") .OrderBy(x => x)) Console.WriteLine(message); } } }
41.842593
136
0.545253
[ "MIT" ]
MichaelLogutov/Rocks.Profiling
src/Rocks.Profiling.Tests/DependencyInjectionConfigTests.cs
4,521
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.Azure.MariaDB { /// <summary> /// Manages a Firewall Rule for a MariaDB Server /// /// ## Example Usage (Single IP Address) /// /// ```csharp /// using Pulumi; /// using Azure = Pulumi.Azure; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var example = new Azure.MariaDB.FirewallRule("example", new Azure.MariaDB.FirewallRuleArgs /// { /// EndIpAddress = "40.112.8.12", /// ResourceGroupName = "test-rg", /// ServerName = "test-server", /// StartIpAddress = "40.112.8.12", /// }); /// } /// /// } /// ``` /// /// ## Example Usage (IP Range) /// /// ```csharp /// using Pulumi; /// using Azure = Pulumi.Azure; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var example = new Azure.MariaDB.FirewallRule("example", new Azure.MariaDB.FirewallRuleArgs /// { /// EndIpAddress = "40.112.255.255", /// ResourceGroupName = "test-rg", /// ServerName = "test-server", /// StartIpAddress = "40.112.0.0", /// }); /// } /// /// } /// ``` /// </summary> public partial class FirewallRule : Pulumi.CustomResource { /// <summary> /// Specifies the End IP Address associated with this Firewall Rule. Changing this forces a new resource to be created. /// </summary> [Output("endIpAddress")] public Output<string> EndIpAddress { get; private set; } = null!; /// <summary> /// Specifies the name of the MariaDB Firewall Rule. Changing this forces a new resource to be created. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The name of the resource group in which the MariaDB Server exists. Changing this forces a new resource to be created. /// </summary> [Output("resourceGroupName")] public Output<string> ResourceGroupName { get; private set; } = null!; /// <summary> /// Specifies the name of the MariaDB Server. Changing this forces a new resource to be created. /// </summary> [Output("serverName")] public Output<string> ServerName { get; private set; } = null!; /// <summary> /// Specifies the Start IP Address associated with this Firewall Rule. Changing this forces a new resource to be created. /// </summary> [Output("startIpAddress")] public Output<string> StartIpAddress { get; private set; } = null!; /// <summary> /// Create a FirewallRule resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public FirewallRule(string name, FirewallRuleArgs args, CustomResourceOptions? options = null) : base("azure:mariadb/firewallRule:FirewallRule", name, args ?? new FirewallRuleArgs(), MakeResourceOptions(options, "")) { } private FirewallRule(string name, Input<string> id, FirewallRuleState? state = null, CustomResourceOptions? options = null) : base("azure:mariadb/firewallRule:FirewallRule", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing FirewallRule resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static FirewallRule Get(string name, Input<string> id, FirewallRuleState? state = null, CustomResourceOptions? options = null) { return new FirewallRule(name, id, state, options); } } public sealed class FirewallRuleArgs : Pulumi.ResourceArgs { /// <summary> /// Specifies the End IP Address associated with this Firewall Rule. Changing this forces a new resource to be created. /// </summary> [Input("endIpAddress", required: true)] public Input<string> EndIpAddress { get; set; } = null!; /// <summary> /// Specifies the name of the MariaDB Firewall Rule. Changing this forces a new resource to be created. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The name of the resource group in which the MariaDB Server exists. Changing this forces a new resource to be created. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// Specifies the name of the MariaDB Server. Changing this forces a new resource to be created. /// </summary> [Input("serverName", required: true)] public Input<string> ServerName { get; set; } = null!; /// <summary> /// Specifies the Start IP Address associated with this Firewall Rule. Changing this forces a new resource to be created. /// </summary> [Input("startIpAddress", required: true)] public Input<string> StartIpAddress { get; set; } = null!; public FirewallRuleArgs() { } } public sealed class FirewallRuleState : Pulumi.ResourceArgs { /// <summary> /// Specifies the End IP Address associated with this Firewall Rule. Changing this forces a new resource to be created. /// </summary> [Input("endIpAddress")] public Input<string>? EndIpAddress { get; set; } /// <summary> /// Specifies the name of the MariaDB Firewall Rule. Changing this forces a new resource to be created. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// The name of the resource group in which the MariaDB Server exists. Changing this forces a new resource to be created. /// </summary> [Input("resourceGroupName")] public Input<string>? ResourceGroupName { get; set; } /// <summary> /// Specifies the name of the MariaDB Server. Changing this forces a new resource to be created. /// </summary> [Input("serverName")] public Input<string>? ServerName { get; set; } /// <summary> /// Specifies the Start IP Address associated with this Firewall Rule. Changing this forces a new resource to be created. /// </summary> [Input("startIpAddress")] public Input<string>? StartIpAddress { get; set; } public FirewallRuleState() { } } }
39.492823
141
0.588927
[ "ECL-2.0", "Apache-2.0" ]
pulumi-bot/pulumi-azure
sdk/dotnet/MariaDB/FirewallRule.cs
8,254
C#
using System; using Android.App; using Android.Content; using Android.Content.PM; using Android.Net.Wifi; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using Xamarin.Forms.Platform.Android; using ZeroconfTest.Xam; namespace ZeroconfTest.Xamarin.Droid { [Activity (Label = "ZeroconfTest.Xamarin", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)] public class MainActivity : FormsApplicationActivity { WifiManager wifi; WifiManager.MulticastLock mlock; protected override void OnCreate (Bundle savedInstanceState) { base.OnCreate (savedInstanceState); global::Xamarin.Forms.Forms.Init (this, savedInstanceState); wifi = (WifiManager)ApplicationContext.GetSystemService(Context.WifiService); mlock = wifi.CreateMulticastLock("Zeroconf lock"); mlock.Acquire(); #pragma warning disable CS0618 // Type or member is obsolete SetPage(App.GetMainPage ()); #pragma warning restore CS0618 // Type or member is obsolete } protected override void OnDestroy() { if (mlock != null) { mlock.Release(); mlock = null; } base.OnDestroy(); } } }
27.270833
142
0.677617
[ "MIT" ]
SpencerBurgess/Zeroconf
ZeroconfTest.Xamarin/ZeroconfTest.Xamarin.Android/MainActivity.cs
1,311
C#
#region License // Copyright(c) 2020 GrappTec // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System.Xml.Serialization; using DotNetAppBase.Std.Library; // ReSharper disable CheckNamespace public static partial class XObjectExtensions // ReSharper restore CheckNamespace { public static object NotNull(this object obj) { if (Equals(obj, null)) { return null; } var type = obj.GetType(); if (!type.IsEnum) { return obj.ToString(); } var memberInfo = XHelper.Reflections.Fields.GetStatic(type, obj.ToString()); var xmlEnumMember = XHelper.Reflections.Attributes.Get<XmlEnumAttribute>(memberInfo); return xmlEnumMember != null ? xmlEnumMember.Name : obj.ToString(); } }
34.830189
93
0.71506
[ "MIT" ]
GrappTec/DotNetAppBase
src/DotNetAppBase.Std.Extensions/XObjectExtensions.Value.cs
1,848
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using System.Text; using org.apache.plc4net.api.value; using org.apache.plc4net.spi.generation; using org.apache.plc4net.spi.model.values; // Code generated by code-generation. DO NOT EDIT. namespace org.apache.plc4net.drivers.mqtt.readwrite.model { public class MQTT_ControlPacket_DISCONNECT : MQTT_ControlPacket { // Accessors for discriminator values. public override MQTT_ControlPacketType PacketType => MQTT_ControlPacketType.DISCONNECT; // Properties. public byte RemainingLength { get; } public MQTT_ReasonCode Reason { get; } public MQTT_ControlPacket_DISCONNECT(byte remainingLength, MQTT_ReasonCode reason) { RemainingLength = remainingLength; Reason = reason; } } }
32.82
95
0.731261
[ "Apache-2.0" ]
LuthienTinuvielShouko/plc4x
sandbox/mqtt/mqtt-cs/drivers/mqtt/src/drivers/mqtt/readwrite/model/MQTT_ControlPacket_DISCONNECT.cs
1,641
C#
using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProAgil.Domain.Identity { public class Role : IdentityRole<int> { public List<UserRole> UserRoles { get; set; } } }
20.066667
53
0.730897
[ "MIT" ]
FelipeCabralz/ProAgil
ProAgil.Domain/Identity/Role.cs
303
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class LS_SetFont : MonoBehaviour { // instance variables public Font otherFont; public Color fontColor = new Color32(225, 188, 222, 255); // sets font to the font attached to the script public void SetFont(Font otherFont) { SendInfo.myFont = otherFont; } void Start() { // only runs on the first scene if (SendInfo.myFont is null) { SetFont(otherFont); } // changes the font color of each text object in scene var textObjects = FindObjectsOfType<Text>(); foreach (Text text in textObjects) { text.font = SendInfo.myFont; text.color = fontColor; } } }
24.235294
63
0.60801
[ "MIT" ]
rijdmc419/EducationalRecyclingGame
EducationalRecyclingGame/Assets/MenuAssets/LS_SetFont.cs
826
C#
namespace Sap.telas.login { partial class login { /// <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(login)); this.picglogin = new System.Windows.Forms.PictureBox(); this.picsenha = new System.Windows.Forms.PictureBox(); this.picusuario = new System.Windows.Forms.PictureBox(); this.txtusuario = new System.Windows.Forms.TextBox(); this.txtsenha = new System.Windows.Forms.TextBox(); this.picgif = new System.Windows.Forms.PictureBox(); this.picbarra = new System.Windows.Forms.PictureBox(); this.picfechar = new System.Windows.Forms.PictureBox(); this.picminimize = new System.Windows.Forms.PictureBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.picvi = new System.Windows.Forms.PictureBox(); this.picnvi = new System.Windows.Forms.PictureBox(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.piclogin = new System.Windows.Forms.PictureBox(); ((System.ComponentModel.ISupportInitialize)(this.picglogin)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picsenha)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picusuario)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picgif)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picbarra)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picfechar)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picminimize)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picvi)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.picnvi)).BeginInit(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.piclogin)).BeginInit(); this.SuspendLayout(); // // picglogin // this.picglogin.BackColor = System.Drawing.Color.LightSeaGreen; this.picglogin.Location = new System.Drawing.Point(429, 39); this.picglogin.Name = "picglogin"; this.picglogin.Size = new System.Drawing.Size(255, 273); this.picglogin.TabIndex = 6; this.picglogin.TabStop = false; this.picglogin.Click += new System.EventHandler(this.picglogin_Click); // // picsenha // this.picsenha.BackColor = System.Drawing.Color.MediumAquamarine; this.picsenha.Location = new System.Drawing.Point(512, 126); this.picsenha.Name = "picsenha"; this.picsenha.Size = new System.Drawing.Size(162, 37); this.picsenha.TabIndex = 13; this.picsenha.TabStop = false; // // picusuario // this.picusuario.BackColor = System.Drawing.Color.MediumAquamarine; this.picusuario.Location = new System.Drawing.Point(512, 85); this.picusuario.Name = "picusuario"; this.picusuario.Size = new System.Drawing.Size(162, 37); this.picusuario.TabIndex = 14; this.picusuario.TabStop = false; // // txtusuario // this.txtusuario.BackColor = System.Drawing.Color.MediumAquamarine; this.txtusuario.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtusuario.ForeColor = System.Drawing.Color.White; this.txtusuario.Location = new System.Drawing.Point(521, 97); this.txtusuario.Name = "txtusuario"; this.txtusuario.Size = new System.Drawing.Size(122, 13); this.txtusuario.TabIndex = 15; // // txtsenha // this.txtsenha.BackColor = System.Drawing.Color.MediumAquamarine; this.txtsenha.BorderStyle = System.Windows.Forms.BorderStyle.None; this.txtsenha.ForeColor = System.Drawing.Color.White; this.txtsenha.Location = new System.Drawing.Point(521, 138); this.txtsenha.Name = "txtsenha"; this.txtsenha.Size = new System.Drawing.Size(108, 13); this.txtsenha.TabIndex = 16; // // picgif // this.picgif.BackColor = System.Drawing.Color.Transparent; this.picgif.Image = ((System.Drawing.Image)(resources.GetObject("picgif.Image"))); this.picgif.Location = new System.Drawing.Point(13, 39); this.picgif.Name = "picgif"; this.picgif.Size = new System.Drawing.Size(391, 273); this.picgif.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.picgif.TabIndex = 7; this.picgif.TabStop = false; // // picbarra // this.picbarra.BackColor = System.Drawing.Color.LightSeaGreen; this.picbarra.Location = new System.Drawing.Point(-3, -2); this.picbarra.Name = "picbarra"; this.picbarra.Size = new System.Drawing.Size(711, 35); this.picbarra.TabIndex = 17; this.picbarra.TabStop = false; // // picfechar // this.picfechar.BackColor = System.Drawing.Color.LightSeaGreen; this.picfechar.Image = ((System.Drawing.Image)(resources.GetObject("picfechar.Image"))); this.picfechar.Location = new System.Drawing.Point(656, -2); this.picfechar.Name = "picfechar"; this.picfechar.Size = new System.Drawing.Size(41, 35); this.picfechar.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.picfechar.TabIndex = 19; this.picfechar.TabStop = false; this.picfechar.Click += new System.EventHandler(this.picfechar_Click); // // picminimize // this.picminimize.BackColor = System.Drawing.Color.LightSeaGreen; this.picminimize.Image = ((System.Drawing.Image)(resources.GetObject("picminimize.Image"))); this.picminimize.Location = new System.Drawing.Point(615, -2); this.picminimize.Name = "picminimize"; this.picminimize.Size = new System.Drawing.Size(39, 35); this.picminimize.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.picminimize.TabIndex = 20; this.picminimize.TabStop = false; this.picminimize.Click += new System.EventHandler(this.picminimize_Click); // // label1 // this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.MediumAquamarine; this.label1.ForeColor = System.Drawing.Color.White; this.label1.Location = new System.Drawing.Point(518, 97); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(33, 13); this.label1.TabIndex = 21; this.label1.Text = "Login"; this.label1.Click += new System.EventHandler(this.label1_Click); // // label2 // this.label2.AutoSize = true; this.label2.BackColor = System.Drawing.Color.MediumAquamarine; this.label2.ForeColor = System.Drawing.Color.White; this.label2.Location = new System.Drawing.Point(518, 138); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(38, 13); this.label2.TabIndex = 22; this.label2.Text = "Senha"; this.label2.Click += new System.EventHandler(this.label2_Click); // // pictureBox1 // this.pictureBox1.BackColor = System.Drawing.Color.LightSeaGreen; this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(468, 85); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(46, 37); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBox1.TabIndex = 23; this.pictureBox1.TabStop = false; // // pictureBox2 // this.pictureBox2.BackColor = System.Drawing.Color.LightSeaGreen; this.pictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox2.Image"))); this.pictureBox2.Location = new System.Drawing.Point(468, 126); this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.Size = new System.Drawing.Size(46, 37); this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBox2.TabIndex = 24; this.pictureBox2.TabStop = false; // // picvi // this.picvi.BackColor = System.Drawing.Color.MediumAquamarine; this.picvi.Image = ((System.Drawing.Image)(resources.GetObject("picvi.Image"))); this.picvi.Location = new System.Drawing.Point(635, 134); this.picvi.Name = "picvi"; this.picvi.Size = new System.Drawing.Size(28, 23); this.picvi.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.picvi.TabIndex = 25; this.picvi.TabStop = false; this.picvi.Visible = false; this.picvi.Click += new System.EventHandler(this.picvi_Click); // // picnvi // this.picnvi.BackColor = System.Drawing.Color.MediumAquamarine; this.picnvi.Image = ((System.Drawing.Image)(resources.GetObject("picnvi.Image"))); this.picnvi.Location = new System.Drawing.Point(635, 135); this.picnvi.Name = "picnvi"; this.picnvi.Size = new System.Drawing.Size(28, 21); this.picnvi.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.picnvi.TabIndex = 26; this.picnvi.TabStop = false; this.picnvi.Click += new System.EventHandler(this.picnvi_Click); // // groupBox1 // this.groupBox1.BackColor = System.Drawing.Color.LightSeaGreen; this.groupBox1.Controls.Add(this.piclogin); this.groupBox1.Location = new System.Drawing.Point(504, 180); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(139, 101); this.groupBox1.TabIndex = 27; this.groupBox1.TabStop = false; // // piclogin // this.piclogin.BackColor = System.Drawing.Color.LightSeaGreen; this.piclogin.Image = ((System.Drawing.Image)(resources.GetObject("piclogin.Image"))); this.piclogin.Location = new System.Drawing.Point(10, 12); this.piclogin.Name = "piclogin"; this.piclogin.Size = new System.Drawing.Size(123, 83); this.piclogin.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.piclogin.TabIndex = 28; this.piclogin.TabStop = false; this.piclogin.Click += new System.EventHandler(this.piclogin_Click_1); // // login // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.DarkCyan; this.ClientSize = new System.Drawing.Size(696, 324); this.Controls.Add(this.groupBox1); this.Controls.Add(this.picnvi); this.Controls.Add(this.picvi); this.Controls.Add(this.pictureBox2); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.picminimize); this.Controls.Add(this.picfechar); this.Controls.Add(this.picbarra); this.Controls.Add(this.txtsenha); this.Controls.Add(this.txtusuario); this.Controls.Add(this.picusuario); this.Controls.Add(this.picsenha); this.Controls.Add(this.picgif); this.Controls.Add(this.picglogin); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "login"; this.Text = "login"; this.Paint += new System.Windows.Forms.PaintEventHandler(this.login_Paint); ((System.ComponentModel.ISupportInitialize)(this.picglogin)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picsenha)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picusuario)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picgif)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picbarra)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picfechar)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picminimize)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picvi)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.picnvi)).EndInit(); this.groupBox1.ResumeLayout(false); ((System.ComponentModel.ISupportInitialize)(this.piclogin)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.PictureBox picglogin; private System.Windows.Forms.PictureBox picsenha; private System.Windows.Forms.PictureBox picusuario; private System.Windows.Forms.TextBox txtusuario; private System.Windows.Forms.TextBox txtsenha; private System.Windows.Forms.PictureBox picgif; private System.Windows.Forms.PictureBox picbarra; private System.Windows.Forms.PictureBox picfechar; private System.Windows.Forms.PictureBox picminimize; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.PictureBox pictureBox2; private System.Windows.Forms.PictureBox picvi; private System.Windows.Forms.PictureBox picnvi; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.PictureBox piclogin; } }
52.118211
137
0.613069
[ "Apache-2.0" ]
Learnandmake/Projetos-c-sharp
Sap/Sap/telas/login/login.Designer.cs
16,315
C#
//------------------------------------------------------------------------------ // <copyright file="DepthCamSensorTypes.cs" company="Microsoft Corporation"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Linq; using System.Text; using TrackRoamer.Robotics.Utility.LibSystem; namespace TrackRoamer.Robotics.Services.TrackRoamerBehaviors { using System.Windows; using kinect = Microsoft.Kinect; /// <summary> /// Joint information used in visualizing the skeletons /// </summary> public class VisualizableJoint { /// <summary> /// Gets or sets the tracking state. Is one of the following - Tracked, Inferred, Not Tracked /// </summary> public kinect.JointTrackingState TrackingState { get; set; } public bool IsJointOfInterest { get; set; } public kinect.JointType jointType; /// <summary> /// Visualizable coordinates of the joint, 2D in the window /// </summary> public Point JointCoordinates = new Point(); // original 3D data for driving and targeting. // Kinect Z goes straight forward, X - to the left side, Y - up: public double X { get; set; } // meters, relative to Kinect camera public double Y { get; set; } public double Z { get; set; } // Warning: ComputePanTilt() can set Pan or Tilt to NaN: public double Pan { get; set; } // relative bearing from the robot's point of view public double Tilt { get; set; } public VisualizableJoint(kinect.JointType jt) { this.TrackingState = kinect.JointTrackingState.NotTracked; this.jointType = jt; this.IsJointOfInterest = false; } /// <summary> /// Warning: ComputePanTilt() can set Pan or Tilt to NaN /// </summary> public void ComputePanTilt() { Pan = -toDegrees(Math.Atan2(X, Z)); Tilt = toDegrees(Math.Atan2(Y, Z)); //Console.WriteLine("********************************************************************** X=" + X + " Y=" + Y + " Z=" + Z + " Pan=" + Pan + " Tilt=" + Tilt); } public double toDegrees(double radians) { return radians * 180.0d / Math.PI; } } /// <summary> /// SkeletonPose, as detected, in the order of detection priority /// see http://www.rit.edu/innovationcenter/kinectatrit/glossary-common-gestures /// </summary> public enum SkeletonPose { NotDetected, None, HandsUp, LeftHandUp, RightHandUp, BothArmsForward, LeftArmForward, RightArmForward, BothArmsOut, LeftArmOut, RightArmOut, ArmsCrossed, LeftHandPointingRight, RightHandPointingLeft } /// <summary> /// Joint coordinates that will be used by UI to draw the seletons /// </summary> public class VisualizableSkeletonInformation { /// <summary> /// Gets or sets the skeleton quality. /// We'll parse out Skeletal information and put it here in a /// format that can be plopped into UI as is /// </summary> public string SkeletonQuality { get; set; } /// <summary> /// Gets or sets a value indicating whether or not this skeleton is tracked by Kinect /// </summary> public bool IsSkeletonActive { get; set; } /// <summary> /// Indicates the main target, usually the closest skeleton to the camera /// </summary> public bool IsMainSkeleton { get; set; } /// <summary> /// a number maintained by Kinect. See http://msdn.microsoft.com/en-us/library/jj131025.aspx#Active_User_Tracking /// </summary> public int TrackingId { get; set; } /// <summary> /// index in FrameProcessor preallocated array /// </summary> public int Index { get; set; } public SkeletonPose SkeletonPose { get; set; } public double? SkeletonSizeMeters { get; set; } // distance between head and feet public double DistanceMeters { get; set; } // distance to jointOfInterest (usually Spine) /// <summary> /// fills this.SkeletonPose - may leave it as NotDetected or fill None /// </summary> /// <param name="skel">Skeleton</param> public void detectSkeletonPose(kinect.Skeleton skel) { // We come here only when skeleton and its Head is tracked. For pose detection spine and both wrists must be tracked too. if (skel.Joints[kinect.JointType.WristLeft].TrackingState == kinect.JointTrackingState.Tracked && skel.Joints[kinect.JointType.WristRight].TrackingState == kinect.JointTrackingState.Tracked && skel.Joints[kinect.JointType.Spine].TrackingState == kinect.JointTrackingState.Tracked) { double sizeFactor = SkeletonSizeMeters.HasValue ? SkeletonSizeMeters.Value / 1.7d : 1.0d; // account for persons with height different from my 1.7 meters // coordinates in meters: //Tracer.Trace("Hands: " + skel.Joints[kinect.JointType.WristLeft].Position.X + " " + skel.Joints[kinect.JointType.WristRight].Position.X // + " - " + skel.Joints[kinect.JointType.WristLeft].Position.Y + " " + skel.Joints[kinect.JointType.WristRight].Position.Y // + " - " + skel.Joints[kinect.JointType.WristLeft].Position.Z + " " + skel.Joints[kinect.JointType.WristRight].Position.Z); bool leftHandUp = skel.Joints[kinect.JointType.WristLeft].Position.Y > skel.Joints[kinect.JointType.Head].Position.Y; bool rightHandUp = skel.Joints[kinect.JointType.WristRight].Position.Y > skel.Joints[kinect.JointType.Head].Position.Y; if (leftHandUp && rightHandUp) { this.SkeletonPose = SkeletonPose.HandsUp; } else if (leftHandUp) { this.SkeletonPose = SkeletonPose.LeftHandUp; } else if (rightHandUp) { this.SkeletonPose = SkeletonPose.RightHandUp; } else { bool leftHandForward = skel.Joints[kinect.JointType.WristLeft].Position.Z < skel.Joints[kinect.JointType.Spine].Position.Z - 0.4f * sizeFactor; bool leftHandToTheSide = skel.Joints[kinect.JointType.WristLeft].Position.X < skel.Joints[kinect.JointType.Spine].Position.X - 0.6f * sizeFactor; // meters bool leftHandPointingRight = skel.Joints[kinect.JointType.WristLeft].Position.X > skel.Joints[kinect.JointType.Spine].Position.X + 0.2f * sizeFactor; // meters bool rightHandForward = skel.Joints[kinect.JointType.WristRight].Position.Z < skel.Joints[kinect.JointType.Spine].Position.Z - 0.4f * sizeFactor; bool rightHandToTheSide = skel.Joints[kinect.JointType.WristRight].Position.X > skel.Joints[kinect.JointType.Spine].Position.X + 0.6f * sizeFactor; bool rightHandPointingLeft = skel.Joints[kinect.JointType.WristRight].Position.X < skel.Joints[kinect.JointType.Spine].Position.X - 0.2f * sizeFactor; bool HandsCrossed = skel.Joints[kinect.JointType.WristRight].Position.X < skel.Joints[kinect.JointType.WristLeft].Position.X - 0.2f * sizeFactor; // criteria looser than leftHandPointingRight && rightHandPointingLeft if (leftHandForward && rightHandForward) { this.SkeletonPose = SkeletonPose.BothArmsForward; } else if (leftHandForward) { this.SkeletonPose = SkeletonPose.LeftArmForward; } else if (rightHandForward) { this.SkeletonPose = SkeletonPose.RightArmForward; } else if (leftHandToTheSide && rightHandToTheSide) { this.SkeletonPose = SkeletonPose.BothArmsOut; } else if (leftHandToTheSide) { this.SkeletonPose = SkeletonPose.LeftArmOut; } else if (rightHandToTheSide) { this.SkeletonPose = SkeletonPose.RightArmOut; } else if (HandsCrossed) { this.SkeletonPose = SkeletonPose.ArmsCrossed; } else if (leftHandPointingRight) { this.SkeletonPose = SkeletonPose.LeftHandPointingRight; } else if (rightHandPointingLeft) { this.SkeletonPose = SkeletonPose.RightHandPointingLeft; } else { this.SkeletonPose = SkeletonPose.None; } } } } public VisualizableSkeletonInformation(int index) { Index = index; SkeletonPose = SkeletonPose.NotDetected; SkeletonSizeMeters = null; IsSkeletonActive = false; IsMainSkeleton = false; DistanceMeters = double.MaxValue; } public override string ToString() { return string.Format("{0}:{1}{2}{3}{4}\r\n{5:#.00}m away", Index, TrackingId, IsMainSkeleton ? "*" : string.Empty, SkeletonSizeMeters.HasValue ? string.Format("{0:#.00}m tall", SkeletonSizeMeters.Value) : string.Empty, this.SkeletonPose == TrackRoamerBehaviors.SkeletonPose.None ? string.Empty : (" " + this.SkeletonPose), DistanceMeters); } /// <summary> /// Pre-allocated joint points /// </summary> public Dictionary<kinect.JointType, VisualizableJoint> JointPoints = new Dictionary<kinect.JointType, VisualizableJoint>() { { kinect.JointType.AnkleLeft, new VisualizableJoint(kinect.JointType.AnkleLeft) }, { kinect.JointType.AnkleRight, new VisualizableJoint(kinect.JointType.AnkleRight) }, { kinect.JointType.ElbowLeft, new VisualizableJoint(kinect.JointType.ElbowLeft) }, { kinect.JointType.ElbowRight, new VisualizableJoint(kinect.JointType.ElbowRight) }, { kinect.JointType.FootLeft, new VisualizableJoint(kinect.JointType.FootLeft) }, { kinect.JointType.FootRight, new VisualizableJoint(kinect.JointType.FootRight) }, { kinect.JointType.HandLeft, new VisualizableJoint(kinect.JointType.HandLeft) }, { kinect.JointType.HandRight, new VisualizableJoint(kinect.JointType.HandRight) }, { kinect.JointType.Head, new VisualizableJoint(kinect.JointType.Head) }, { kinect.JointType.HipCenter, new VisualizableJoint(kinect.JointType.HipCenter) }, { kinect.JointType.HipLeft, new VisualizableJoint(kinect.JointType.HipLeft) }, { kinect.JointType.HipRight, new VisualizableJoint(kinect.JointType.HipRight) }, { kinect.JointType.KneeLeft, new VisualizableJoint(kinect.JointType.KneeLeft) }, { kinect.JointType.KneeRight, new VisualizableJoint(kinect.JointType.KneeRight) }, { kinect.JointType.ShoulderCenter, new VisualizableJoint(kinect.JointType.ShoulderCenter) }, { kinect.JointType.ShoulderLeft, new VisualizableJoint(kinect.JointType.ShoulderLeft) }, { kinect.JointType.ShoulderRight, new VisualizableJoint(kinect.JointType.ShoulderRight) }, { kinect.JointType.Spine, new VisualizableJoint(kinect.JointType.Spine) }, { kinect.JointType.WristLeft, new VisualizableJoint(kinect.JointType.WristLeft) }, { kinect.JointType.WristRight, new VisualizableJoint(kinect.JointType.WristRight) } }; } }
46.039568
237
0.567388
[ "MIT" ]
slgrobotics/TrackRoamer
src/TrackRoamer/TrackRoamerBehaviors/Kinect/SkeltonJointPoints.cs
12,801
C#
using AutoMapper; using X.Api.Entities; namespace X.Api.Source.Domain.UsesCases.Queries { public class GetAllStatesByProjectIdMapper : Profile { public GetAllStatesByProjectIdMapper() { CreateMap<State, GetAllStatesByProjectIdDto>() .ForMember(dest => dest.CanUpdate, opt => opt.MapFrom(src => src.StateName == "Backlog" || src.StateName == "DONE" ? false : true)) ; } } }
24.6875
135
0.711392
[ "MIT" ]
mfcguru/xsk.framework
X.Framework/X.Api/Source/Domain/UsesCases/Queries/GetAllStatesByProjectId/GetAllStatesByProjectIdMapper.cs
397
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace CSharp_Edition { static class Program { /// <summary> /// Główny punkt wejścia dla aplikacji. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new ekranPowitalny()); } } }
22.434783
65
0.620155
[ "MIT" ]
ParrotTeam/Rewolucja
CSharp_Edition/Program.cs
521
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Foundation; using UIKit; namespace MemoryLeakSample { public class DammyViewController : UIViewController { public override void ViewDidLoad() { base.ViewDidLoad(); var dismissViewButton = new UIButton(); dismissViewButton.TouchUpInside += DismissViewButton_TouchUpInside; } void DismissViewButton_TouchUpInside(object sender, EventArgs e) => DismissViewController(true, null); } }
22.84
79
0.67951
[ "MIT" ]
TomohiroSuzuki128/Xamarin-iOSLeakSample
MemoryLeakSample/Dammy.cs
573
C#
// Url: https://leetcode.com/problems/add-two-numbers/ /* 2. Add Two Numbers Medium You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. Example: Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807. */ using System; namespace InterviewPreperationGuide.Core.LeetCode.problem2 { public class ListNode { public int val; public ListNode next; public ListNode (int x) { val = x; } } public class Solution { public void Init () { ListNode l1 = new ListNode (2); l1.next = new ListNode (4); l1.next.next = new ListNode (3); ListNode l2 = new ListNode (5); l2.next = new ListNode (6); l2.next.next = new ListNode (4); Console.WriteLine (AddTwoNumbers (l1, l2)); ListNode l3 = new ListNode (1); l3.next = new ListNode (8); ListNode l4 = new ListNode (0); Console.WriteLine (AddTwoNumbers (l3, l4)); } public ListNode AddTwoNumbers (ListNode l1, ListNode l2) { ListNode result = new ListNode (0); ListNode a = l1; ListNode b = l2; ListNode current = result; int carry = 0; while (a != null || b != null) { int x = a != null ? a.val : 0; int y = b != null ? b.val : 0; int sum = carry + x + y; carry = sum / 10; current.next = new ListNode (sum % 10); current = current.next; if (a != null) { a = a.next; } if (b != null) { b = b.next; } } if (carry > 0) { current.next = new ListNode (carry); } return result.next; } } }
27.717949
219
0.504625
[ "MIT" ]
tarunbatta/ipg
core/leetcode/2.cs
2,162
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace RxReactiveStreamsCSharp.Disposables { public sealed class BooleanDisposable : IDisposable { Action action; static readonly Action DISPOSED = () => { }; public BooleanDisposable() : this(() => { }) { } public BooleanDisposable(Action action) { this.action = action; } public void Dispose() { Action d = Volatile.Read(ref action); if (d != DISPOSED) { d = Interlocked.Exchange(ref action, DISPOSED); if (d != DISPOSED) { d(); } } } public bool IsDisposed() { return Volatile.Read(ref action) == DISPOSED; } } }
20.608696
63
0.507384
[ "Apache-2.0" ]
akarnokd/RxReactiveStreamsCSharp
RxReactiveStreamsCSharp/RxReactiveStreamsCSharp/Disposables/BooleanDisposable.cs
950
C#
namespace Replay_sorter { public class Replay_info { public string clientVersionFromExe { get; set; } public byte battleType { get; set; } } }
21.375
56
0.631579
[ "MIT" ]
CWTracker/ReplaySorter
Replay_info.cs
173
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Общие сведения об этой сборке предоставляются следующим набором // набора атрибутов. Измените значения этих атрибутов для изменения сведений, // связанные с этой сборкой. [assembly: AssemblyTitle("ConsoleApp1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConsoleApp1")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми // для компонентов COM. Если необходимо обратиться к типу в этой сборке через // из модели COM задайте для атрибута ComVisible этого типа значение true. [assembly: ComVisible(false)] // Следующий GUID представляет идентификатор typelib, если этот проект доступен из модели COM [assembly: Guid("eefff7dc-bb6e-4768-8392-2455ca6becae")] // Сведения о версии сборки состоят из указанных ниже четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер сборки // Номер редакции // // Можно задать все значения или принять номера сборки и редакции по умолчанию // используя "*", как показано ниже: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.891892
93
0.763725
[ "MIT" ]
bsv798/dedupe-archiever
ConsoleApp1/Properties/AssemblyInfo.cs
2,023
C#