content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Net; using System.Net.Sockets; using Cytar.IO; namespace Cytar.Network { public class TCPSession : NetworkSession { public override bool Available { get { if (TcpClient == null) return false; return TcpClient.Connected; } protected set { } } public override uint SSID { get; protected set; } public TcpClient TcpClient { get; private set; } protected override Stream InnerStream { get; set; } public override InputStream InputStream { get ; protected set; } public override OutputStream OutputStream { get; protected set; } public override IPAddress RemoteIPAdress { get { return (TcpClient.Client.RemoteEndPoint as IPEndPoint).Address; } } public override int Read(byte[] buffer, int offset, int count) { lock (InputStream) { return InputStream.Read(buffer, offset, count); } } public override void Write(byte[] buffer, int offset, int count) { lock (OutputStream) { OutputStream.Write(buffer, offset, count); } } public override int ReadByte() { lock (InputStream) { return InputStream.ReadByte(); } } public override void WriteByte(byte value) { lock (OutputStream) { OutputStream.WriteByte(value); } } public override void Close() { TcpClient.Close(); } public TCPSession(TcpClient client) { TcpClient = client; InnerStream = client.GetStream(); InputStream = new InputStream(InnerStream); OutputStream = new OutputStream(InnerStream); } } }
25.905882
80
0.500454
[ "MIT" ]
SardineFish/Cytar
Cytar/Network/TCPSession.cs
2,204
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("02RectangleArea")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02RectangleArea")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9a5123e9-2fb7-4ba5-a85d-4f5bc466c022")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.756757
85
0.730126
[ "MIT" ]
martin1tasev/SecondRepo
TechModule CSharpBasics syntax/02RectangleArea/Properties/AssemblyInfo.cs
1,437
C#
using System; namespace APIView { class Program { static void Main(string[] args) { try { var renderer = new TextRendererAPIV(); Console.WriteLine(renderer.Render(AssemblyAPIV.AssemblyFromFile(args[0]))); } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } } } }
20.652174
91
0.473684
[ "MIT" ]
shahabhijeet/azure-sdk-tools
src/dotnet/APIView/APIView/Program.cs
477
C#
// Copyright 2019 Google LLC // // 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 // // https://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. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxgrpc = Google.Api.Gax.Grpc; using pb = Google.Protobuf; using pbwkt = Google.Protobuf.WellKnownTypes; using grpccore = Grpc.Core; using sys = System; using sc = System.Collections; using scg = System.Collections.Generic; using sco = System.Collections.ObjectModel; using st = System.Threading; using stt = System.Threading.Tasks; namespace Google.Cloud.Dataproc.V1 { /// <summary> /// Settings for a <see cref="JobControllerClient"/>. /// </summary> public sealed partial class JobControllerSettings : gaxgrpc::ServiceSettingsBase { /// <summary> /// Get a new instance of the default <see cref="JobControllerSettings"/>. /// </summary> /// <returns> /// A new instance of the default <see cref="JobControllerSettings"/>. /// </returns> public static JobControllerSettings GetDefault() => new JobControllerSettings(); /// <summary> /// Constructs a new <see cref="JobControllerSettings"/> object with default settings. /// </summary> public JobControllerSettings() { } private JobControllerSettings(JobControllerSettings existing) : base(existing) { gax::GaxPreconditions.CheckNotNull(existing, nameof(existing)); SubmitJobSettings = existing.SubmitJobSettings; GetJobSettings = existing.GetJobSettings; ListJobsSettings = existing.ListJobsSettings; UpdateJobSettings = existing.UpdateJobSettings; CancelJobSettings = existing.CancelJobSettings; DeleteJobSettings = existing.DeleteJobSettings; OnCopy(existing); } partial void OnCopy(JobControllerSettings existing); /// <summary> /// The filter specifying which RPC <see cref="grpccore::StatusCode"/>s are eligible for retry /// for "Idempotent" <see cref="JobControllerClient"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="grpccore::StatusCode"/>s for retry for "Idempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="grpccore::StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="grpccore::StatusCode.Internal"/></description></item> /// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static sys::Predicate<grpccore::RpcException> IdempotentRetryFilter { get; } = gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.DeadlineExceeded, grpccore::StatusCode.Internal, grpccore::StatusCode.Unavailable); /// <summary> /// The filter specifying which RPC <see cref="grpccore::StatusCode"/>s are eligible for retry /// for "NonIdempotent" <see cref="JobControllerClient"/> RPC methods. /// </summary> /// <remarks> /// The eligible RPC <see cref="grpccore::StatusCode"/>s for retry for "NonIdempotent" RPC methods are: /// <list type="bullet"> /// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item> /// </list> /// </remarks> public static sys::Predicate<grpccore::RpcException> NonIdempotentRetryFilter { get; } = gaxgrpc::RetrySettings.FilterForStatusCodes(grpccore::StatusCode.Unavailable); /// <summary> /// "Default" retry backoff for <see cref="JobControllerClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" retry backoff for <see cref="JobControllerClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" retry backoff for <see cref="JobControllerClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial delay: 100 milliseconds</description></item> /// <item><description>Maximum delay: 60000 milliseconds</description></item> /// <item><description>Delay multiplier: 1.3</description></item> /// </list> /// </remarks> public static gaxgrpc::BackoffSettings GetDefaultRetryBackoff() => new gaxgrpc::BackoffSettings( delay: sys::TimeSpan.FromMilliseconds(100), maxDelay: sys::TimeSpan.FromMilliseconds(60000), delayMultiplier: 1.3 ); /// <summary> /// "Default" timeout backoff for <see cref="JobControllerClient"/> RPC methods. /// </summary> /// <returns> /// The "Default" timeout backoff for <see cref="JobControllerClient"/> RPC methods. /// </returns> /// <remarks> /// The "Default" timeout backoff for <see cref="JobControllerClient"/> RPC methods is defined as: /// <list type="bullet"> /// <item><description>Initial timeout: 30000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Maximum timeout: 30000 milliseconds</description></item> /// </list> /// </remarks> public static gaxgrpc::BackoffSettings GetDefaultTimeoutBackoff() => new gaxgrpc::BackoffSettings( delay: sys::TimeSpan.FromMilliseconds(30000), maxDelay: sys::TimeSpan.FromMilliseconds(30000), delayMultiplier: 1.0 ); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>JobControllerClient.SubmitJob</c> and <c>JobControllerClient.SubmitJobAsync</c>. /// </summary> /// <remarks> /// The default <c>JobControllerClient.SubmitJob</c> and /// <c>JobControllerClient.SubmitJobAsync</c> <see cref="gaxgrpc::RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 30000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 30000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 900000 milliseconds. /// </remarks> public gaxgrpc::CallSettings SubmitJobSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming( gaxgrpc::CallTiming.FromRetry(new gaxgrpc::RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(900000)), retryFilter: NonIdempotentRetryFilter ))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>JobControllerClient.GetJob</c> and <c>JobControllerClient.GetJobAsync</c>. /// </summary> /// <remarks> /// The default <c>JobControllerClient.GetJob</c> and /// <c>JobControllerClient.GetJobAsync</c> <see cref="gaxgrpc::RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 30000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 30000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="grpccore::StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="grpccore::StatusCode.Internal"/></description></item> /// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 900000 milliseconds. /// </remarks> public gaxgrpc::CallSettings GetJobSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming( gaxgrpc::CallTiming.FromRetry(new gaxgrpc::RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(900000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>JobControllerClient.ListJobs</c> and <c>JobControllerClient.ListJobsAsync</c>. /// </summary> /// <remarks> /// The default <c>JobControllerClient.ListJobs</c> and /// <c>JobControllerClient.ListJobsAsync</c> <see cref="gaxgrpc::RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 30000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 30000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="grpccore::StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="grpccore::StatusCode.Internal"/></description></item> /// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 900000 milliseconds. /// </remarks> public gaxgrpc::CallSettings ListJobsSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming( gaxgrpc::CallTiming.FromRetry(new gaxgrpc::RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(900000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>JobControllerClient.UpdateJob</c> and <c>JobControllerClient.UpdateJobAsync</c>. /// </summary> /// <remarks> /// The default <c>JobControllerClient.UpdateJob</c> and /// <c>JobControllerClient.UpdateJobAsync</c> <see cref="gaxgrpc::RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 30000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 30000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 900000 milliseconds. /// </remarks> public gaxgrpc::CallSettings UpdateJobSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming( gaxgrpc::CallTiming.FromRetry(new gaxgrpc::RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(900000)), retryFilter: NonIdempotentRetryFilter ))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>JobControllerClient.CancelJob</c> and <c>JobControllerClient.CancelJobAsync</c>. /// </summary> /// <remarks> /// The default <c>JobControllerClient.CancelJob</c> and /// <c>JobControllerClient.CancelJobAsync</c> <see cref="gaxgrpc::RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 30000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 30000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="grpccore::StatusCode.DeadlineExceeded"/></description></item> /// <item><description><see cref="grpccore::StatusCode.Internal"/></description></item> /// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 900000 milliseconds. /// </remarks> public gaxgrpc::CallSettings CancelJobSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming( gaxgrpc::CallTiming.FromRetry(new gaxgrpc::RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(900000)), retryFilter: IdempotentRetryFilter ))); /// <summary> /// <see cref="gaxgrpc::CallSettings"/> for synchronous and asynchronous calls to /// <c>JobControllerClient.DeleteJob</c> and <c>JobControllerClient.DeleteJobAsync</c>. /// </summary> /// <remarks> /// The default <c>JobControllerClient.DeleteJob</c> and /// <c>JobControllerClient.DeleteJobAsync</c> <see cref="gaxgrpc::RetrySettings"/> are: /// <list type="bullet"> /// <item><description>Initial retry delay: 100 milliseconds</description></item> /// <item><description>Retry delay multiplier: 1.3</description></item> /// <item><description>Retry maximum delay: 60000 milliseconds</description></item> /// <item><description>Initial timeout: 30000 milliseconds</description></item> /// <item><description>Timeout multiplier: 1.0</description></item> /// <item><description>Timeout maximum delay: 30000 milliseconds</description></item> /// </list> /// Retry will be attempted on the following response status codes: /// <list> /// <item><description><see cref="grpccore::StatusCode.Unavailable"/></description></item> /// </list> /// Default RPC expiration is 900000 milliseconds. /// </remarks> public gaxgrpc::CallSettings DeleteJobSettings { get; set; } = gaxgrpc::CallSettings.FromCallTiming( gaxgrpc::CallTiming.FromRetry(new gaxgrpc::RetrySettings( retryBackoff: GetDefaultRetryBackoff(), timeoutBackoff: GetDefaultTimeoutBackoff(), totalExpiration: gax::Expiration.FromTimeout(sys::TimeSpan.FromMilliseconds(900000)), retryFilter: NonIdempotentRetryFilter ))); /// <summary> /// Creates a deep clone of this object, with all the same property values. /// </summary> /// <returns>A deep clone of this <see cref="JobControllerSettings"/> object.</returns> public JobControllerSettings Clone() => new JobControllerSettings(this); } /// <summary> /// Builder class for <see cref="JobControllerClient"/> to provide simple configuration of credentials, endpoint etc. /// </summary> public sealed partial class JobControllerClientBuilder : gaxgrpc::ClientBuilderBase<JobControllerClient> { /// <summary> /// The settings to use for RPCs, or null for the default settings. /// </summary> public JobControllerSettings Settings { get; set; } /// <inheritdoc/> public override JobControllerClient Build() { Validate(); grpccore::CallInvoker callInvoker = CreateCallInvoker(); return JobControllerClient.Create(callInvoker, Settings); } /// <inheritdoc /> public override async stt::Task<JobControllerClient> BuildAsync(st::CancellationToken cancellationToken = default) { Validate(); grpccore::CallInvoker callInvoker = await CreateCallInvokerAsync(cancellationToken).ConfigureAwait(false); return JobControllerClient.Create(callInvoker, Settings); } /// <inheritdoc /> protected override gaxgrpc::ServiceEndpoint GetDefaultEndpoint() => JobControllerClient.DefaultEndpoint; /// <inheritdoc /> protected override scg::IReadOnlyList<string> GetDefaultScopes() => JobControllerClient.DefaultScopes; /// <inheritdoc /> protected override gaxgrpc::ChannelPool GetChannelPool() => JobControllerClient.ChannelPool; } /// <summary> /// JobController client wrapper, for convenient use. /// </summary> public abstract partial class JobControllerClient { /// <summary> /// The default endpoint for the JobController service, which is a host of "dataproc.googleapis.com" and a port of 443. /// </summary> public static gaxgrpc::ServiceEndpoint DefaultEndpoint { get; } = new gaxgrpc::ServiceEndpoint("dataproc.googleapis.com", 443); /// <summary> /// The default JobController scopes. /// </summary> /// <remarks> /// The default JobController scopes are: /// <list type="bullet"> /// <item><description>"https://www.googleapis.com/auth/cloud-platform"</description></item> /// </list> /// </remarks> public static scg::IReadOnlyList<string> DefaultScopes { get; } = new sco::ReadOnlyCollection<string>(new string[] { "https://www.googleapis.com/auth/cloud-platform", }); private static readonly gaxgrpc::ChannelPool s_channelPool = new gaxgrpc::ChannelPool(DefaultScopes); internal static gaxgrpc::ChannelPool ChannelPool => s_channelPool; /// <summary> /// Asynchronously creates a <see cref="JobControllerClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. See the example for how to use custom credentials. /// </summary> /// <example> /// This sample shows how to create a client using default credentials: /// <code> /// using Google.Cloud.Dataproc.V1; /// ... /// // When running on Google Cloud Platform this will use the project Compute Credential. /// // Or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a JSON /// // credential file to use that credential. /// JobControllerClient client = await JobControllerClient.CreateAsync(); /// </code> /// This sample shows how to create a client using credentials loaded from a JSON file: /// <code> /// using Google.Cloud.Dataproc.V1; /// using Google.Apis.Auth.OAuth2; /// using Grpc.Auth; /// using Grpc.Core; /// ... /// GoogleCredential cred = GoogleCredential.FromFile("/path/to/credentials.json"); /// Channel channel = new Channel( /// JobControllerClient.DefaultEndpoint.Host, JobControllerClient.DefaultEndpoint.Port, cred.ToChannelCredentials()); /// JobControllerClient client = JobControllerClient.Create(channel); /// ... /// // Shutdown the channel when it is no longer required. /// await channel.ShutdownAsync(); /// </code> /// </example> /// <param name="endpoint">Optional <see cref="gaxgrpc::ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="JobControllerSettings"/>.</param> /// <returns>The task representing the created <see cref="JobControllerClient"/>.</returns> public static async stt::Task<JobControllerClient> CreateAsync(gaxgrpc::ServiceEndpoint endpoint = null, JobControllerSettings settings = null) { grpccore::Channel channel = await s_channelPool.GetChannelAsync(endpoint ?? DefaultEndpoint).ConfigureAwait(false); return Create(channel, settings); } /// <summary> /// Synchronously creates a <see cref="JobControllerClient"/>, applying defaults for all unspecified settings, /// and creating a channel connecting to the given endpoint with application default credentials where /// necessary. See the example for how to use custom credentials. /// </summary> /// <example> /// This sample shows how to create a client using default credentials: /// <code> /// using Google.Cloud.Dataproc.V1; /// ... /// // When running on Google Cloud Platform this will use the project Compute Credential. /// // Or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to the path of a JSON /// // credential file to use that credential. /// JobControllerClient client = JobControllerClient.Create(); /// </code> /// This sample shows how to create a client using credentials loaded from a JSON file: /// <code> /// using Google.Cloud.Dataproc.V1; /// using Google.Apis.Auth.OAuth2; /// using Grpc.Auth; /// using Grpc.Core; /// ... /// GoogleCredential cred = GoogleCredential.FromFile("/path/to/credentials.json"); /// Channel channel = new Channel( /// JobControllerClient.DefaultEndpoint.Host, JobControllerClient.DefaultEndpoint.Port, cred.ToChannelCredentials()); /// JobControllerClient client = JobControllerClient.Create(channel); /// ... /// // Shutdown the channel when it is no longer required. /// channel.ShutdownAsync().Wait(); /// </code> /// </example> /// <param name="endpoint">Optional <see cref="gaxgrpc::ServiceEndpoint"/>.</param> /// <param name="settings">Optional <see cref="JobControllerSettings"/>.</param> /// <returns>The created <see cref="JobControllerClient"/>.</returns> public static JobControllerClient Create(gaxgrpc::ServiceEndpoint endpoint = null, JobControllerSettings settings = null) { grpccore::Channel channel = s_channelPool.GetChannel(endpoint ?? DefaultEndpoint); return Create(channel, settings); } /// <summary> /// Creates a <see cref="JobControllerClient"/> which uses the specified channel for remote operations. /// </summary> /// <param name="channel">The <see cref="grpccore::Channel"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="JobControllerSettings"/>.</param> /// <returns>The created <see cref="JobControllerClient"/>.</returns> public static JobControllerClient Create(grpccore::Channel channel, JobControllerSettings settings = null) { gax::GaxPreconditions.CheckNotNull(channel, nameof(channel)); return Create(new grpccore::DefaultCallInvoker(channel), settings); } /// <summary> /// Creates a <see cref="JobControllerClient"/> which uses the specified call invoker for remote operations. /// </summary> /// <param name="callInvoker">The <see cref="grpccore::CallInvoker"/> for remote operations. Must not be null.</param> /// <param name="settings">Optional <see cref="JobControllerSettings"/>.</param> /// <returns>The created <see cref="JobControllerClient"/>.</returns> public static JobControllerClient Create(grpccore::CallInvoker callInvoker, JobControllerSettings settings = null) { gax::GaxPreconditions.CheckNotNull(callInvoker, nameof(callInvoker)); grpccore::Interceptors.Interceptor interceptor = settings?.Interceptor; if (interceptor != null) { callInvoker = grpccore::Interceptors.CallInvokerExtensions.Intercept(callInvoker, interceptor); } JobController.JobControllerClient grpcClient = new JobController.JobControllerClient(callInvoker); return new JobControllerClientImpl(grpcClient, settings); } /// <summary> /// Shuts down any channels automatically created by <see cref="Create(gaxgrpc::ServiceEndpoint, JobControllerSettings)"/> /// and <see cref="CreateAsync(gaxgrpc::ServiceEndpoint, JobControllerSettings)"/>. Channels which weren't automatically /// created are not affected. /// </summary> /// <remarks>After calling this method, further calls to <see cref="Create(gaxgrpc::ServiceEndpoint, JobControllerSettings)"/> /// and <see cref="CreateAsync(gaxgrpc::ServiceEndpoint, JobControllerSettings)"/> will create new channels, which could /// in turn be shut down by another call to this method.</remarks> /// <returns>A task representing the asynchronous shutdown operation.</returns> public static stt::Task ShutdownDefaultChannelsAsync() => s_channelPool.ShutdownChannelsAsync(); /// <summary> /// The underlying gRPC JobController client. /// </summary> public virtual JobController.JobControllerClient GrpcClient { get { throw new sys::NotImplementedException(); } } /// <summary> /// Submits a job to a cluster. /// </summary> /// <param name="projectId"> /// Required. The ID of the Google Cloud Platform project that the job /// belongs to. /// </param> /// <param name="region"> /// Required. The Cloud Dataproc region in which to handle the request. /// </param> /// <param name="job"> /// Required. The job resource. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<Job> SubmitJobAsync( string projectId, string region, Job job, gaxgrpc::CallSettings callSettings = null) => SubmitJobAsync( new SubmitJobRequest { ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), Job = gax::GaxPreconditions.CheckNotNull(job, nameof(job)), }, callSettings); /// <summary> /// Submits a job to a cluster. /// </summary> /// <param name="projectId"> /// Required. The ID of the Google Cloud Platform project that the job /// belongs to. /// </param> /// <param name="region"> /// Required. The Cloud Dataproc region in which to handle the request. /// </param> /// <param name="job"> /// Required. The job resource. /// </param> /// <param name="cancellationToken"> /// A <see cref="st::CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<Job> SubmitJobAsync( string projectId, string region, Job job, st::CancellationToken cancellationToken) => SubmitJobAsync( projectId, region, job, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Submits a job to a cluster. /// </summary> /// <param name="projectId"> /// Required. The ID of the Google Cloud Platform project that the job /// belongs to. /// </param> /// <param name="region"> /// Required. The Cloud Dataproc region in which to handle the request. /// </param> /// <param name="job"> /// Required. The job resource. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Job SubmitJob( string projectId, string region, Job job, gaxgrpc::CallSettings callSettings = null) => SubmitJob( new SubmitJobRequest { ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), Job = gax::GaxPreconditions.CheckNotNull(job, nameof(job)), }, callSettings); /// <summary> /// Submits a job to a cluster. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<Job> SubmitJobAsync( SubmitJobRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Submits a job to a cluster. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="cancellationToken"> /// A <see cref="st::CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<Job> SubmitJobAsync( SubmitJobRequest request, st::CancellationToken cancellationToken) => SubmitJobAsync( request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Submits a job to a cluster. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Job SubmitJob( SubmitJobRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Gets the resource representation for a job in a project. /// </summary> /// <param name="projectId"> /// Required. The ID of the Google Cloud Platform project that the job /// belongs to. /// </param> /// <param name="region"> /// Required. The Cloud Dataproc region in which to handle the request. /// </param> /// <param name="jobId"> /// Required. The job ID. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<Job> GetJobAsync( string projectId, string region, string jobId, gaxgrpc::CallSettings callSettings = null) => GetJobAsync( new GetJobRequest { ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), JobId = gax::GaxPreconditions.CheckNotNullOrEmpty(jobId, nameof(jobId)), }, callSettings); /// <summary> /// Gets the resource representation for a job in a project. /// </summary> /// <param name="projectId"> /// Required. The ID of the Google Cloud Platform project that the job /// belongs to. /// </param> /// <param name="region"> /// Required. The Cloud Dataproc region in which to handle the request. /// </param> /// <param name="jobId"> /// Required. The job ID. /// </param> /// <param name="cancellationToken"> /// A <see cref="st::CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<Job> GetJobAsync( string projectId, string region, string jobId, st::CancellationToken cancellationToken) => GetJobAsync( projectId, region, jobId, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets the resource representation for a job in a project. /// </summary> /// <param name="projectId"> /// Required. The ID of the Google Cloud Platform project that the job /// belongs to. /// </param> /// <param name="region"> /// Required. The Cloud Dataproc region in which to handle the request. /// </param> /// <param name="jobId"> /// Required. The job ID. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Job GetJob( string projectId, string region, string jobId, gaxgrpc::CallSettings callSettings = null) => GetJob( new GetJobRequest { ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), JobId = gax::GaxPreconditions.CheckNotNullOrEmpty(jobId, nameof(jobId)), }, callSettings); /// <summary> /// Gets the resource representation for a job in a project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<Job> GetJobAsync( GetJobRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Gets the resource representation for a job in a project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="cancellationToken"> /// A <see cref="st::CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<Job> GetJobAsync( GetJobRequest request, st::CancellationToken cancellationToken) => GetJobAsync( request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Gets the resource representation for a job in a project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Job GetJob( GetJobRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Lists regions/{region}/jobs in a project. /// </summary> /// <param name="projectId"> /// Required. The ID of the Google Cloud Platform project that the job /// belongs to. /// </param> /// <param name="region"> /// Required. The Cloud Dataproc region in which to handle the request. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="Job"/> resources. /// </returns> public virtual gax::PagedAsyncEnumerable<ListJobsResponse, Job> ListJobsAsync( string projectId, string region, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListJobsAsync( new ListJobsRequest { ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists regions/{region}/jobs in a project. /// </summary> /// <param name="projectId"> /// Required. The ID of the Google Cloud Platform project that the job /// belongs to. /// </param> /// <param name="region"> /// Required. The Cloud Dataproc region in which to handle the request. /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="Job"/> resources. /// </returns> public virtual gax::PagedEnumerable<ListJobsResponse, Job> ListJobs( string projectId, string region, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListJobs( new ListJobsRequest { ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists regions/{region}/jobs in a project. /// </summary> /// <param name="projectId"> /// Required. The ID of the Google Cloud Platform project that the job /// belongs to. /// </param> /// <param name="region"> /// Required. The Cloud Dataproc region in which to handle the request. /// </param> /// <param name="filter"> /// Optional. A filter constraining the jobs to list. Filters are /// case-sensitive and have the following syntax: /// /// [field = value] AND [field [= value]] ... /// /// where **field** is `status.state` or `labels.[KEY]`, and `[KEY]` is a label /// key. **value** can be `*` to match all values. /// `status.state` can be either `ACTIVE` or `NON_ACTIVE`. /// Only the logical `AND` operator is supported; space-separated items are /// treated as having an implicit `AND` operator. /// /// Example filter: /// /// status.state = ACTIVE AND labels.env = staging AND labels.starred = * /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="Job"/> resources. /// </returns> public virtual gax::PagedAsyncEnumerable<ListJobsResponse, Job> ListJobsAsync( string projectId, string region, string filter, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListJobsAsync( new ListJobsRequest { ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), Filter = filter ?? "", // Optional PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists regions/{region}/jobs in a project. /// </summary> /// <param name="projectId"> /// Required. The ID of the Google Cloud Platform project that the job /// belongs to. /// </param> /// <param name="region"> /// Required. The Cloud Dataproc region in which to handle the request. /// </param> /// <param name="filter"> /// Optional. A filter constraining the jobs to list. Filters are /// case-sensitive and have the following syntax: /// /// [field = value] AND [field [= value]] ... /// /// where **field** is `status.state` or `labels.[KEY]`, and `[KEY]` is a label /// key. **value** can be `*` to match all values. /// `status.state` can be either `ACTIVE` or `NON_ACTIVE`. /// Only the logical `AND` operator is supported; space-separated items are /// treated as having an implicit `AND` operator. /// /// Example filter: /// /// status.state = ACTIVE AND labels.env = staging AND labels.starred = * /// </param> /// <param name="pageToken"> /// The token returned from the previous request. /// A value of <c>null</c> or an empty string retrieves the first page. /// </param> /// <param name="pageSize"> /// The size of page to request. The response will not be larger than this, but may be smaller. /// A value of <c>null</c> or 0 uses a server-defined page size. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="Job"/> resources. /// </returns> public virtual gax::PagedEnumerable<ListJobsResponse, Job> ListJobs( string projectId, string region, string filter, string pageToken = null, int? pageSize = null, gaxgrpc::CallSettings callSettings = null) => ListJobs( new ListJobsRequest { ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), Filter = filter ?? "", // Optional PageToken = pageToken ?? "", PageSize = pageSize ?? 0, }, callSettings); /// <summary> /// Lists regions/{region}/jobs in a project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="Job"/> resources. /// </returns> public virtual gax::PagedAsyncEnumerable<ListJobsResponse, Job> ListJobsAsync( ListJobsRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Lists regions/{region}/jobs in a project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="Job"/> resources. /// </returns> public virtual gax::PagedEnumerable<ListJobsResponse, Job> ListJobs( ListJobsRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Updates a job in a project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<Job> UpdateJobAsync( UpdateJobRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Updates a job in a project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="cancellationToken"> /// A <see cref="st::CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<Job> UpdateJobAsync( UpdateJobRequest request, st::CancellationToken cancellationToken) => UpdateJobAsync( request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Updates a job in a project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Job UpdateJob( UpdateJobRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Starts a job cancellation request. To access the job resource /// after cancellation, call /// [regions/{region}/jobs.list](/dataproc/docs/reference/rest/v1/projects.regions.jobs/list) /// or /// [regions/{region}/jobs.get](/dataproc/docs/reference/rest/v1/projects.regions.jobs/get). /// </summary> /// <param name="projectId"> /// Required. The ID of the Google Cloud Platform project that the job /// belongs to. /// </param> /// <param name="region"> /// Required. The Cloud Dataproc region in which to handle the request. /// </param> /// <param name="jobId"> /// Required. The job ID. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<Job> CancelJobAsync( string projectId, string region, string jobId, gaxgrpc::CallSettings callSettings = null) => CancelJobAsync( new CancelJobRequest { ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), JobId = gax::GaxPreconditions.CheckNotNullOrEmpty(jobId, nameof(jobId)), }, callSettings); /// <summary> /// Starts a job cancellation request. To access the job resource /// after cancellation, call /// [regions/{region}/jobs.list](/dataproc/docs/reference/rest/v1/projects.regions.jobs/list) /// or /// [regions/{region}/jobs.get](/dataproc/docs/reference/rest/v1/projects.regions.jobs/get). /// </summary> /// <param name="projectId"> /// Required. The ID of the Google Cloud Platform project that the job /// belongs to. /// </param> /// <param name="region"> /// Required. The Cloud Dataproc region in which to handle the request. /// </param> /// <param name="jobId"> /// Required. The job ID. /// </param> /// <param name="cancellationToken"> /// A <see cref="st::CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<Job> CancelJobAsync( string projectId, string region, string jobId, st::CancellationToken cancellationToken) => CancelJobAsync( projectId, region, jobId, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Starts a job cancellation request. To access the job resource /// after cancellation, call /// [regions/{region}/jobs.list](/dataproc/docs/reference/rest/v1/projects.regions.jobs/list) /// or /// [regions/{region}/jobs.get](/dataproc/docs/reference/rest/v1/projects.regions.jobs/get). /// </summary> /// <param name="projectId"> /// Required. The ID of the Google Cloud Platform project that the job /// belongs to. /// </param> /// <param name="region"> /// Required. The Cloud Dataproc region in which to handle the request. /// </param> /// <param name="jobId"> /// Required. The job ID. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Job CancelJob( string projectId, string region, string jobId, gaxgrpc::CallSettings callSettings = null) => CancelJob( new CancelJobRequest { ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), JobId = gax::GaxPreconditions.CheckNotNullOrEmpty(jobId, nameof(jobId)), }, callSettings); /// <summary> /// Starts a job cancellation request. To access the job resource /// after cancellation, call /// [regions/{region}/jobs.list](/dataproc/docs/reference/rest/v1/projects.regions.jobs/list) /// or /// [regions/{region}/jobs.get](/dataproc/docs/reference/rest/v1/projects.regions.jobs/get). /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<Job> CancelJobAsync( CancelJobRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Starts a job cancellation request. To access the job resource /// after cancellation, call /// [regions/{region}/jobs.list](/dataproc/docs/reference/rest/v1/projects.regions.jobs/list) /// or /// [regions/{region}/jobs.get](/dataproc/docs/reference/rest/v1/projects.regions.jobs/get). /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="cancellationToken"> /// A <see cref="st::CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public virtual stt::Task<Job> CancelJobAsync( CancelJobRequest request, st::CancellationToken cancellationToken) => CancelJobAsync( request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Starts a job cancellation request. To access the job resource /// after cancellation, call /// [regions/{region}/jobs.list](/dataproc/docs/reference/rest/v1/projects.regions.jobs/list) /// or /// [regions/{region}/jobs.get](/dataproc/docs/reference/rest/v1/projects.regions.jobs/get). /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public virtual Job CancelJob( CancelJobRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Deletes the job from the project. If the job is active, the delete fails, /// and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="projectId"> /// Required. The ID of the Google Cloud Platform project that the job /// belongs to. /// </param> /// <param name="region"> /// Required. The Cloud Dataproc region in which to handle the request. /// </param> /// <param name="jobId"> /// Required. The job ID. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task that completes when the RPC has completed. /// </returns> public virtual stt::Task DeleteJobAsync( string projectId, string region, string jobId, gaxgrpc::CallSettings callSettings = null) => DeleteJobAsync( new DeleteJobRequest { ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), JobId = gax::GaxPreconditions.CheckNotNullOrEmpty(jobId, nameof(jobId)), }, callSettings); /// <summary> /// Deletes the job from the project. If the job is active, the delete fails, /// and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="projectId"> /// Required. The ID of the Google Cloud Platform project that the job /// belongs to. /// </param> /// <param name="region"> /// Required. The Cloud Dataproc region in which to handle the request. /// </param> /// <param name="jobId"> /// Required. The job ID. /// </param> /// <param name="cancellationToken"> /// A <see cref="st::CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task that completes when the RPC has completed. /// </returns> public virtual stt::Task DeleteJobAsync( string projectId, string region, string jobId, st::CancellationToken cancellationToken) => DeleteJobAsync( projectId, region, jobId, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes the job from the project. If the job is active, the delete fails, /// and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="projectId"> /// Required. The ID of the Google Cloud Platform project that the job /// belongs to. /// </param> /// <param name="region"> /// Required. The Cloud Dataproc region in which to handle the request. /// </param> /// <param name="jobId"> /// Required. The job ID. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> public virtual void DeleteJob( string projectId, string region, string jobId, gaxgrpc::CallSettings callSettings = null) => DeleteJob( new DeleteJobRequest { ProjectId = gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), Region = gax::GaxPreconditions.CheckNotNullOrEmpty(region, nameof(region)), JobId = gax::GaxPreconditions.CheckNotNullOrEmpty(jobId, nameof(jobId)), }, callSettings); /// <summary> /// Deletes the job from the project. If the job is active, the delete fails, /// and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task that completes when the RPC has completed. /// </returns> public virtual stt::Task DeleteJobAsync( DeleteJobRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } /// <summary> /// Deletes the job from the project. If the job is active, the delete fails, /// and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="cancellationToken"> /// A <see cref="st::CancellationToken"/> to use for this RPC. /// </param> /// <returns> /// A Task that completes when the RPC has completed. /// </returns> public virtual stt::Task DeleteJobAsync( DeleteJobRequest request, st::CancellationToken cancellationToken) => DeleteJobAsync( request, gaxgrpc::CallSettings.FromCancellationToken(cancellationToken)); /// <summary> /// Deletes the job from the project. If the job is active, the delete fails, /// and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> public virtual void DeleteJob( DeleteJobRequest request, gaxgrpc::CallSettings callSettings = null) { throw new sys::NotImplementedException(); } } /// <summary> /// JobController client wrapper implementation, for convenient use. /// </summary> public sealed partial class JobControllerClientImpl : JobControllerClient { private readonly gaxgrpc::ApiCall<SubmitJobRequest, Job> _callSubmitJob; private readonly gaxgrpc::ApiCall<GetJobRequest, Job> _callGetJob; private readonly gaxgrpc::ApiCall<ListJobsRequest, ListJobsResponse> _callListJobs; private readonly gaxgrpc::ApiCall<UpdateJobRequest, Job> _callUpdateJob; private readonly gaxgrpc::ApiCall<CancelJobRequest, Job> _callCancelJob; private readonly gaxgrpc::ApiCall<DeleteJobRequest, pbwkt::Empty> _callDeleteJob; /// <summary> /// Constructs a client wrapper for the JobController service, with the specified gRPC client and settings. /// </summary> /// <param name="grpcClient">The underlying gRPC client.</param> /// <param name="settings">The base <see cref="JobControllerSettings"/> used within this client </param> public JobControllerClientImpl(JobController.JobControllerClient grpcClient, JobControllerSettings settings) { GrpcClient = grpcClient; JobControllerSettings effectiveSettings = settings ?? JobControllerSettings.GetDefault(); gaxgrpc::ClientHelper clientHelper = new gaxgrpc::ClientHelper(effectiveSettings); _callSubmitJob = clientHelper.BuildApiCall<SubmitJobRequest, Job>( GrpcClient.SubmitJobAsync, GrpcClient.SubmitJob, effectiveSettings.SubmitJobSettings); _callGetJob = clientHelper.BuildApiCall<GetJobRequest, Job>( GrpcClient.GetJobAsync, GrpcClient.GetJob, effectiveSettings.GetJobSettings); _callListJobs = clientHelper.BuildApiCall<ListJobsRequest, ListJobsResponse>( GrpcClient.ListJobsAsync, GrpcClient.ListJobs, effectiveSettings.ListJobsSettings); _callUpdateJob = clientHelper.BuildApiCall<UpdateJobRequest, Job>( GrpcClient.UpdateJobAsync, GrpcClient.UpdateJob, effectiveSettings.UpdateJobSettings); _callCancelJob = clientHelper.BuildApiCall<CancelJobRequest, Job>( GrpcClient.CancelJobAsync, GrpcClient.CancelJob, effectiveSettings.CancelJobSettings); _callDeleteJob = clientHelper.BuildApiCall<DeleteJobRequest, pbwkt::Empty>( GrpcClient.DeleteJobAsync, GrpcClient.DeleteJob, effectiveSettings.DeleteJobSettings); Modify_ApiCall(ref _callSubmitJob); Modify_SubmitJobApiCall(ref _callSubmitJob); Modify_ApiCall(ref _callGetJob); Modify_GetJobApiCall(ref _callGetJob); Modify_ApiCall(ref _callListJobs); Modify_ListJobsApiCall(ref _callListJobs); Modify_ApiCall(ref _callUpdateJob); Modify_UpdateJobApiCall(ref _callUpdateJob); Modify_ApiCall(ref _callCancelJob); Modify_CancelJobApiCall(ref _callCancelJob); Modify_ApiCall(ref _callDeleteJob); Modify_DeleteJobApiCall(ref _callDeleteJob); OnConstruction(grpcClient, effectiveSettings, clientHelper); } // Partial methods are named to (mostly) ensure there cannot be conflicts with RPC method names. // Partial methods called for every ApiCall on construction. // Allows modification of all the underlying ApiCall objects. partial void Modify_ApiCall<TRequest, TResponse>(ref gaxgrpc::ApiCall<TRequest, TResponse> call) where TRequest : class, pb::IMessage<TRequest> where TResponse : class, pb::IMessage<TResponse>; // Partial methods called for each ApiCall on construction. // Allows per-RPC-method modification of the underlying ApiCall object. partial void Modify_SubmitJobApiCall(ref gaxgrpc::ApiCall<SubmitJobRequest, Job> call); partial void Modify_GetJobApiCall(ref gaxgrpc::ApiCall<GetJobRequest, Job> call); partial void Modify_ListJobsApiCall(ref gaxgrpc::ApiCall<ListJobsRequest, ListJobsResponse> call); partial void Modify_UpdateJobApiCall(ref gaxgrpc::ApiCall<UpdateJobRequest, Job> call); partial void Modify_CancelJobApiCall(ref gaxgrpc::ApiCall<CancelJobRequest, Job> call); partial void Modify_DeleteJobApiCall(ref gaxgrpc::ApiCall<DeleteJobRequest, pbwkt::Empty> call); partial void OnConstruction(JobController.JobControllerClient grpcClient, JobControllerSettings effectiveSettings, gaxgrpc::ClientHelper clientHelper); /// <summary> /// The underlying gRPC JobController client. /// </summary> public override JobController.JobControllerClient GrpcClient { get; } // Partial methods called on each request. // Allows per-RPC-call modification to the request and CallSettings objects, // before the underlying RPC is performed. partial void Modify_SubmitJobRequest(ref SubmitJobRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_GetJobRequest(ref GetJobRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_ListJobsRequest(ref ListJobsRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_UpdateJobRequest(ref UpdateJobRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_CancelJobRequest(ref CancelJobRequest request, ref gaxgrpc::CallSettings settings); partial void Modify_DeleteJobRequest(ref DeleteJobRequest request, ref gaxgrpc::CallSettings settings); /// <summary> /// Submits a job to a cluster. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override stt::Task<Job> SubmitJobAsync( SubmitJobRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_SubmitJobRequest(ref request, ref callSettings); return _callSubmitJob.Async(request, callSettings); } /// <summary> /// Submits a job to a cluster. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override Job SubmitJob( SubmitJobRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_SubmitJobRequest(ref request, ref callSettings); return _callSubmitJob.Sync(request, callSettings); } /// <summary> /// Gets the resource representation for a job in a project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override stt::Task<Job> GetJobAsync( GetJobRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetJobRequest(ref request, ref callSettings); return _callGetJob.Async(request, callSettings); } /// <summary> /// Gets the resource representation for a job in a project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override Job GetJob( GetJobRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_GetJobRequest(ref request, ref callSettings); return _callGetJob.Sync(request, callSettings); } /// <summary> /// Lists regions/{region}/jobs in a project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable asynchronous sequence of <see cref="Job"/> resources. /// </returns> public override gax::PagedAsyncEnumerable<ListJobsResponse, Job> ListJobsAsync( ListJobsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListJobsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedAsyncEnumerable<ListJobsRequest, ListJobsResponse, Job>(_callListJobs, request, callSettings); } /// <summary> /// Lists regions/{region}/jobs in a project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A pageable sequence of <see cref="Job"/> resources. /// </returns> public override gax::PagedEnumerable<ListJobsResponse, Job> ListJobs( ListJobsRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_ListJobsRequest(ref request, ref callSettings); return new gaxgrpc::GrpcPagedEnumerable<ListJobsRequest, ListJobsResponse, Job>(_callListJobs, request, callSettings); } /// <summary> /// Updates a job in a project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override stt::Task<Job> UpdateJobAsync( UpdateJobRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_UpdateJobRequest(ref request, ref callSettings); return _callUpdateJob.Async(request, callSettings); } /// <summary> /// Updates a job in a project. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override Job UpdateJob( UpdateJobRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_UpdateJobRequest(ref request, ref callSettings); return _callUpdateJob.Sync(request, callSettings); } /// <summary> /// Starts a job cancellation request. To access the job resource /// after cancellation, call /// [regions/{region}/jobs.list](/dataproc/docs/reference/rest/v1/projects.regions.jobs/list) /// or /// [regions/{region}/jobs.get](/dataproc/docs/reference/rest/v1/projects.regions.jobs/get). /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task containing the RPC response. /// </returns> public override stt::Task<Job> CancelJobAsync( CancelJobRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CancelJobRequest(ref request, ref callSettings); return _callCancelJob.Async(request, callSettings); } /// <summary> /// Starts a job cancellation request. To access the job resource /// after cancellation, call /// [regions/{region}/jobs.list](/dataproc/docs/reference/rest/v1/projects.regions.jobs/list) /// or /// [regions/{region}/jobs.get](/dataproc/docs/reference/rest/v1/projects.regions.jobs/get). /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// The RPC response. /// </returns> public override Job CancelJob( CancelJobRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_CancelJobRequest(ref request, ref callSettings); return _callCancelJob.Sync(request, callSettings); } /// <summary> /// Deletes the job from the project. If the job is active, the delete fails, /// and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> /// <returns> /// A Task that completes when the RPC has completed. /// </returns> public override stt::Task DeleteJobAsync( DeleteJobRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteJobRequest(ref request, ref callSettings); return _callDeleteJob.Async(request, callSettings); } /// <summary> /// Deletes the job from the project. If the job is active, the delete fails, /// and the response returns `FAILED_PRECONDITION`. /// </summary> /// <param name="request"> /// The request object containing all of the parameters for the API call. /// </param> /// <param name="callSettings"> /// If not null, applies overrides to this RPC call. /// </param> public override void DeleteJob( DeleteJobRequest request, gaxgrpc::CallSettings callSettings = null) { Modify_DeleteJobRequest(ref request, ref callSettings); _callDeleteJob.Sync(request, callSettings); } } // Partial classes to enable page-streaming public partial class ListJobsRequest : gaxgrpc::IPageRequest { } public partial class ListJobsResponse : gaxgrpc::IPageResponse<Job> { /// <summary> /// Returns an enumerator that iterates through the resources in this response. /// </summary> public scg::IEnumerator<Job> GetEnumerator() => Jobs.GetEnumerator(); /// <inheritdoc/> sc::IEnumerator sc::IEnumerable.GetEnumerator() => GetEnumerator(); } }
45.593201
160
0.593399
[ "Apache-2.0" ]
ArulMozhiVaradan/google-cloud-dotnet
apis/Google.Cloud.Dataproc.V1/Google.Cloud.Dataproc.V1/JobControllerClient.cs
80,472
C#
#if !NETSTANDARD1_3 namespace Oliviann.Data { #region Usings using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using Oliviann.Collections.Generic; using Oliviann.Linq; #endregion Usings /// <summary> /// Represents a collection of commonly used extension methods for extending /// data table objects. /// </summary> public static class DataTableExtensions { /// <summary> /// Retrieves all the values of the specified column name to a /// collection. /// </summary> /// <typeparam name="T">The type of objects in the column.</typeparam> /// <param name="table">The data table instance.</param> /// <param name="columnName">Name of the column. Case insensitive.</param> /// <returns>A collection of values in the specified column name. /// </returns> public static IReadOnlyCollection<T> ColumnValuesToCollection<T>(this DataTable table, string columnName) { if (table == null || table.Rows.Count < 1 || columnName.IsNullOrEmpty()) { return CollectionHelpers.CreateReadOnlyCollection<T>(); } int columnIndex = table.Columns.IndexOf(columnName); if (columnIndex < 0) { return CollectionHelpers.CreateReadOnlyCollection<T>(); } return table.Rows.OfType<DataRow>().Select(dr => dr.Field<T>(columnIndex)).ToListHelper(); } /// <summary> /// Sets all the columns of the table to read only if set to true. /// </summary> /// <param name="table">The data table instance.</param> /// <param name="readOnly">Optional. If set to true then all the columns /// of the data table will be set to read only. If set to false the all /// the columns will be set to not read only. Default value is true. /// </param> /// <returns>The updated data table instance; otherwise, null.</returns> public static DataTable SetColumnsReadOnly(this DataTable table, bool readOnly = true) { if (table == null) { return null; } table.Columns.OfType<DataColumn>().ForEach(column => column.ReadOnly = readOnly); return table; } /// <summary> /// Converts a data table into a comma separated value string. /// </summary> /// <param name="table">The data table to be read.</param> /// <returns>A comma separated value string that represents the data in /// the table.</returns> public static string ToCSV(this DataTable table) { // Return null if there are no columns in the table. if (table == null || table.Columns.Count == 0) { return string.Empty; } var builder = new StringBuilder(); Action cleanLineEndings = () => builder.Replace(",", Environment.NewLine, builder.Length - 1, 1); Action<string> addColumnToBuilder = col => { if (col.IsNullOrEmpty()) { builder.Append(','); return; } string cleanString = col.Replace("\"", "\"\""); builder.Append(cleanString.Contains(',') ? $"\"{cleanString}\"," : $"{cleanString},"); }; // Write the column headers. foreach (DataColumn column in table.Columns) { addColumnToBuilder(column.ColumnName); } cleanLineEndings(); // Write the column values. foreach (DataRow row in table.Rows) { foreach (object cell in row.ItemArray) { addColumnToBuilder(cell.ToString()); } cleanLineEndings(); } return builder.ToString(); } } } #endif
34.508333
113
0.541657
[ "Unlicense" ]
hype8912/Oliviann
source/Oliviann.Common/Data/DataTableExtensions.cs
4,143
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace MICCookBook { public partial class MainPage : ContentPage { public MainPage() { InitializeComponent(); } } }
17
47
0.660131
[ "MIT" ]
noobody23/MICCookBook
src/MICCookBook/MICCookBook/MICCookBook/MainPage.xaml.cs
308
C#
using PiTung; using PiTung.Components; using System; using UnityEngine; public class OversizeButtons : Mod { public override string Name => "Oversize Buttons"; public override string PackageName => "me.jimmy.GiantButtons"; public override string Author => "Iamsodarncool"; public override Version ModVersion => new Version("1.0"); public override void BeforePatch() { ComponentRegistry.CreateNew(this, "LargePanelButton", "Large Panel Button", CreatePanelButtonOfSize(3, 2)); ComponentRegistry.CreateNew(this, "GiantPanelButton", "Giant Panel Button", CreatePanelButtonOfSize(3, 3)); ComponentRegistry.CreateNew(this, "EnormousPanelButton", "Enormous Panel Button", CreatePanelButtonOfSize(15, 2)); // the world is not ready // ComponentRegistry.CreateNew("CollosalPanelButton", "Collosal Panel Button", CreatePanelButtonOfSize(51, 51)); // ComponentRegistry.CreateNew("TitanicPanelButton", "Titanic Panel Button", CreatePanelButtonOfSize(401, 601)); } private static CustomBuilder CreatePanelButtonOfSize(int x, int z) { return PrefabBuilder .Custom(() => { var obj = UnityEngine.Object.Instantiate(References.Prefabs.PanelButton); obj.transform.GetChild(0).localScale = new Vector3(x - 0.3f, 0.2f, z - 0.3f); // this is the collider of the button that you have to click on to press it obj.transform.GetChild(1).localScale = new Vector3(x - 0.3f, 0.2f, z - 0.3f); // this is the actual button itself that moves when you interact with it obj.transform.GetChild(2).localScale = new Vector3(x, 0.33333f, z); // this is the base of the button, the white part right below the brown part obj.transform.GetChild(4).localScale = new Vector3(x - 0.35f, 0.833333f, z - 0.35f); // this is the back panel that the output sits on top of. Dimensions carefully chosen so that mounts can fit between them // if it is an even number wide, we have to shift everything in the component so that it still lines up with the grid if (x % 2 == 0) { for (int i = 0; i < obj.transform.childCount; i++) { obj.transform.GetChild(i).transform.localPosition += new Vector3(0.5f, 0, 0); } } // ditto with height if (z % 2 == 0) { for (int i = 0; i < obj.transform.childCount; i++) { obj.transform.GetChild(i).transform.localPosition += new Vector3(0, 0, 0.5f); } } return obj; }); } }
50.875
223
0.591436
[ "MIT" ]
Iamsodarncool/Oversize-Buttons
OversizeButtonsMod.cs
2,851
C#
using System; using System.Collections.Generic; namespace Backlog.Domain.Models { public class HtmlContent { public Guid HtmlContentId { get; set; } public string Name { get; set; } } }
18.153846
55
0.597458
[ "MIT" ]
QuinntyneBrown/backlog
src/Backlog.Domain/Models/HtmlContent.cs
236
C#
using SanAndreasUnity.Behaviours.World; using UnityEngine; using SanAndreasUnity.UI; namespace SanAndreasUnity.Settings { public class WorldSettings : MonoBehaviour { private static WorldSettings Singleton { get; set; } private float _drawDistanceToApply = 0f; public const string DrawDistanceSerializationName = "max_draw_distance"; private OptionsWindow.FloatInput m_maxDrawDistanceInput = new OptionsWindow.FloatInput { serializationName = DrawDistanceSerializationName, description = "Max draw distance", minValue = WorldManager.MinMaxDrawDistance, maxValue = WorldManager.MaxMaxDrawDistance, getValue = () => WorldManager.Singleton.MaxDrawDistance, setValue = value => { Singleton.OnDrawDistanceChanged(value); }, persistType = OptionsWindow.InputPersistType.OnStart, }; public float overridenMaxDrawDistance = 0f; void Awake () { Singleton = this; if (this.overridenMaxDrawDistance > 0f) m_maxDrawDistanceInput.maxValue = this.overridenMaxDrawDistance; OptionsWindow.RegisterInputs ("WORLD", m_maxDrawDistanceInput); } void OnDrawDistanceChanged(float newValue) { this.CancelInvoke(nameof(ChangeDrawDistanceDelayed)); _drawDistanceToApply = newValue; this.Invoke(nameof(ChangeDrawDistanceDelayed), 0.2f); } void ChangeDrawDistanceDelayed() { WorldManager.Singleton.MaxDrawDistance = _drawDistanceToApply; } } }
26.622642
88
0.772502
[ "MIT" ]
CyberSys/SanAndreasUnity
Assets/Scripts/Settings/WorldSettings.cs
1,413
C#
using System.Windows; using System.Windows.Controls; using HandyControl.Data; namespace HandyControl.Controls { public class TextBlockAttach { public static readonly DependencyProperty AutoTooltipProperty = DependencyProperty.RegisterAttached( "AutoTooltip", typeof(bool), typeof(TextBlockAttach), new PropertyMetadata(ValueBoxes.FalseBox, OnAutoTooltipChanged)); private static void OnAutoTooltipChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { if (d is TextBlock ctl) { if ((bool) e.NewValue) { ctl.TextTrimming = TextTrimming.WordEllipsis; UpdateTooltip(ctl); ctl.SizeChanged += TextBlock_SizeChanged; } else { ctl.ClearValue(TextBlock.TextTrimmingProperty); ctl.SizeChanged -= TextBlock_SizeChanged; } } } public static void SetAutoTooltip(DependencyObject element, bool value) => element.SetValue(AutoTooltipProperty, ValueBoxes.BooleanBox(value)); public static bool GetAutoTooltip(DependencyObject element) => (bool) element.GetValue(AutoTooltipProperty); private static void TextBlock_SizeChanged(object sender, SizeChangedEventArgs e) { if (sender is TextBlock textBlock) { UpdateTooltip(textBlock); } } private static void UpdateTooltip(TextBlock textBlock) { textBlock.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); var width = textBlock.DesiredSize.Width - textBlock.Margin.Left - textBlock.Margin.Right; ToolTipService.SetToolTip(textBlock, textBlock.RenderSize.Width > width || textBlock.ActualWidth < width ? textBlock.Text : null); } } }
36.722222
131
0.618255
[ "MIT" ]
AlBannaTechno/HandyControl
src/Shared/HandyControl_Shared/Controls/Attach/TextBlockAttach.cs
1,985
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Allgemeine Informationen über eine Assembly werden über folgende // Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, // die einer Assembly zugeordnet sind. [assembly: AssemblyTitle("TextureFontTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("TextureFontTests")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Wenn ComVisible auf "false" festgelegt wird, sind die Typen innerhalb dieser Assembly // für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von // COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. [assembly: ComVisible(false)] // Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird [assembly: Guid("4629b7cf-cdcc-456c-a762-0d8c4dc7c86d")] // Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: // // Hauptversion // Nebenversion // Buildnummer // Revision // // Sie können alle Werte angeben oder die standardmäßigen Build- und Revisionsnummern // durch Einsatz von '*', wie in nachfolgendem Beispiel: // [Assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
41.189189
106
0.763123
[ "MIT" ]
Gartenschlaeger/TextureFont
TextureFontTests/Properties/AssemblyInfo.cs
1,540
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable disable using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeGeneration; using Microsoft.CodeAnalysis.Editor.UnitTests.Workspaces; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.PooledObjects; using Microsoft.CodeAnalysis.Simplification; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Roslyn.Utilities; using Xunit; using CS = Microsoft.CodeAnalysis.CSharp; using VB = Microsoft.CodeAnalysis.VisualBasic; namespace Microsoft.CodeAnalysis.Editor.UnitTests.CodeGeneration { [UseExportProvider] public partial class CodeGenerationTests { internal static async Task TestAddNamespaceAsync( string initial, string expected, string name = "N", IList<ISymbol> imports = null, IList<INamespaceOrTypeSymbol> members = null, CodeGenerationOptions codeGenerationOptions = null) { using var context = await TestContext.CreateAsync(initial, expected); var @namespace = CodeGenerationSymbolFactory.CreateNamespaceSymbol(name, imports, members); context.Result = await context.Service.AddNamespaceAsync(context.Solution, (INamespaceSymbol)context.GetDestination(), @namespace, codeGenerationOptions); } internal static async Task TestAddFieldAsync( string initial, string expected, Func<SemanticModel, ITypeSymbol> type = null, string name = "F", Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default, CodeGenerationOptions codeGenerationOptions = null, bool hasConstantValue = false, object constantValue = null, bool addToCompilationUnit = false) { using var context = await TestContext.CreateAsync(initial, expected); var typeSymbol = type != null ? type(context.SemanticModel) : null; var field = CodeGenerationSymbolFactory.CreateFieldSymbol( attributes: default, accessibility, modifiers, typeSymbol, name, hasConstantValue, constantValue); if (!addToCompilationUnit) { context.Result = await context.Service.AddFieldAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), field, codeGenerationOptions); } else { var newRoot = context.Service.AddField(await context.Document.GetSyntaxRootAsync(), field, codeGenerationOptions); context.Result = context.Document.WithSyntaxRoot(newRoot); } } internal static async Task TestAddConstructorAsync( string initial, string expected, string name = "C", Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default, ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default, ImmutableArray<SyntaxNode> statements = default, ImmutableArray<SyntaxNode> baseArguments = default, ImmutableArray<SyntaxNode> thisArguments = default, CodeGenerationOptions codeGenerationOptions = null) { using var context = await TestContext.CreateAsync(initial, expected); var parameterSymbols = GetParameterSymbols(parameters, context); var ctor = CodeGenerationSymbolFactory.CreateConstructorSymbol( attributes: default, accessibility, modifiers, name, parameterSymbols, statements, baseConstructorArguments: baseArguments, thisConstructorArguments: thisArguments); context.Result = await context.Service.AddMethodAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), ctor, codeGenerationOptions); } internal static async Task TestAddMethodAsync( string initial, string expected, string name = "M", Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default, Type returnType = null, Func<SemanticModel, ImmutableArray<IMethodSymbol>> getExplicitInterfaces = null, ImmutableArray<ITypeParameterSymbol> typeParameters = default, ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default, string statements = null, ImmutableArray<SyntaxNode> handlesExpressions = default, CodeGenerationOptions codeGenerationOptions = null) { if (statements != null) { expected = expected.Replace("$$", statements); } using var context = await TestContext.CreateAsync(initial, expected); var parameterSymbols = GetParameterSymbols(parameters, context); var parsedStatements = context.ParseStatements(statements); var explicitInterfaceImplementations = GetMethodSymbols(getExplicitInterfaces, context); var method = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, accessibility, modifiers, GetTypeSymbol(returnType)(context.SemanticModel), RefKind.None, explicitInterfaceImplementations, name, typeParameters, parameterSymbols, parsedStatements, handlesExpressions: handlesExpressions); context.Result = await context.Service.AddMethodAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), method, codeGenerationOptions); } internal static async Task TestAddOperatorsAsync( string initial, string expected, CodeGenerationOperatorKind[] operatorKinds, Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default, Type returnType = null, ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default, string statements = null, CodeGenerationOptions codeGenerationOptions = null) { if (statements != null) { while (expected.IndexOf("$$", StringComparison.Ordinal) != -1) { expected = expected.Replace("$$", statements); } } using var context = await TestContext.CreateAsync(initial, expected); var parameterSymbols = GetParameterSymbols(parameters, context); var parsedStatements = context.ParseStatements(statements); var methods = operatorKinds.Select(kind => CodeGenerationSymbolFactory.CreateOperatorSymbol( attributes: default, accessibility, modifiers, GetTypeSymbol(returnType)(context.SemanticModel), kind, parameterSymbols, parsedStatements)); context.Result = await context.Service.AddMembersAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), methods.ToArray(), codeGenerationOptions); } internal static async Task TestAddUnsupportedOperatorAsync( string initial, CodeGenerationOperatorKind operatorKind, Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default, Type returnType = null, ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default, string statements = null, CodeGenerationOptions codeGenerationOptions = null) { using var context = await TestContext.CreateAsync(initial, initial, ignoreResult: true); var parameterSymbols = GetParameterSymbols(parameters, context); var parsedStatements = context.ParseStatements(statements); var method = CodeGenerationSymbolFactory.CreateOperatorSymbol( attributes: default, accessibility, modifiers, GetTypeSymbol(returnType)(context.SemanticModel), operatorKind, parameterSymbols, parsedStatements); ArgumentException exception = null; try { await context.Service.AddMethodAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), method, codeGenerationOptions); } catch (ArgumentException e) { exception = e; } var expectedMessage = string.Format(WorkspacesResources.Cannot_generate_code_for_unsupported_operator_0, method.Name); Assert.True(exception != null && exception.Message.StartsWith(expectedMessage, StringComparison.Ordinal), string.Format("\r\nExpected exception: {0}\r\nActual exception: {1}\r\n", expectedMessage, exception == null ? "no exception" : exception.Message)); } internal static async Task TestAddConversionAsync( string initial, string expected, Type toType, Func<SemanticModel, IParameterSymbol> fromType, bool isImplicit = false, Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default, string statements = null, CodeGenerationOptions codeGenerationOptions = null) { if (statements != null) { expected = expected.Replace("$$", statements); } using var context = await TestContext.CreateAsync(initial, expected); var parsedStatements = context.ParseStatements(statements); var method = CodeGenerationSymbolFactory.CreateConversionSymbol( attributes: default, accessibility, modifiers, GetTypeSymbol(toType)(context.SemanticModel), fromType(context.SemanticModel), containingType: null, isImplicit, parsedStatements); context.Result = await context.Service.AddMethodAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), method, codeGenerationOptions); } internal static async Task TestAddStatementsAsync( string initial, string expected, string statements, CodeGenerationOptions codeGenerationOptions = null) { if (statements != null) { expected = expected.Replace("$$", statements); } using var context = await TestContext.CreateAsync(initial, expected); var parsedStatements = context.ParseStatements(statements); var oldSyntax = context.GetSelectedSyntax<SyntaxNode>(true); var newSyntax = context.Service.AddStatements(oldSyntax, parsedStatements, codeGenerationOptions); context.Result = context.Document.WithSyntaxRoot((await context.Document.GetSyntaxRootAsync()).ReplaceNode(oldSyntax, newSyntax)); } internal static async Task TestAddParametersAsync( string initial, string expected, ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters, CodeGenerationOptions codeGenerationOptions = null) { using var context = await TestContext.CreateAsync(initial, expected); var parameterSymbols = GetParameterSymbols(parameters, context); var oldMemberSyntax = context.GetSelectedSyntax<SyntaxNode>(true); var newMemberSyntax = context.Service.AddParameters(oldMemberSyntax, parameterSymbols, codeGenerationOptions); context.Result = context.Document.WithSyntaxRoot((await context.Document.GetSyntaxRootAsync()).ReplaceNode(oldMemberSyntax, newMemberSyntax)); } internal static async Task TestAddDelegateTypeAsync( string initial, string expected, string name = "D", Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default, Type returnType = null, ImmutableArray<ITypeParameterSymbol> typeParameters = default, ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default, CodeGenerationOptions codeGenerationOptions = null) { using var context = await TestContext.CreateAsync(initial, expected); var parameterSymbols = GetParameterSymbols(parameters, context); var type = CodeGenerationSymbolFactory.CreateDelegateTypeSymbol( attributes: default, accessibility, modifiers, GetTypeSymbol(returnType)(context.SemanticModel), RefKind.None, name, typeParameters, parameterSymbols); context.Result = await context.Service.AddNamedTypeAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), type, codeGenerationOptions); } internal static async Task TestAddEventAsync( string initial, string expected, string name = "E", ImmutableArray<AttributeData> attributes = default, Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default, ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default, Type type = null, Func<SemanticModel, ImmutableArray<IEventSymbol>> getExplicitInterfaceImplementations = null, IMethodSymbol addMethod = null, IMethodSymbol removeMethod = null, IMethodSymbol raiseMethod = null, CodeGenerationOptions codeGenerationOptions = null) { using var context = await TestContext.CreateAsync(initial, expected); type ??= typeof(Action); var parameterSymbols = GetParameterSymbols(parameters, context); var typeSymbol = GetTypeSymbol(type)(context.SemanticModel); var @event = CodeGenerationSymbolFactory.CreateEventSymbol( attributes, accessibility, modifiers, typeSymbol, getExplicitInterfaceImplementations?.Invoke(context.SemanticModel) ?? default, name, addMethod, removeMethod, raiseMethod); context.Result = await context.Service.AddEventAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), @event, codeGenerationOptions); } internal static async Task TestAddPropertyAsync( string initial, string expected, string name = "P", Accessibility defaultAccessibility = Accessibility.Public, Accessibility setterAccessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default, string getStatements = null, string setStatements = null, Type type = null, ImmutableArray<IPropertySymbol> explicitInterfaceImplementations = default, ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters = default, bool isIndexer = false, CodeGenerationOptions codeGenerationOptions = null, IDictionary<OptionKey2, object> options = null) { // This assumes that tests will not use place holders for get/set statements at the same time if (getStatements != null) { expected = expected.Replace("$$", getStatements); } if (setStatements != null) { expected = expected.Replace("$$", setStatements); } using var context = await TestContext.CreateAsync(initial, expected); var workspace = context.Workspace; if (options != null) { var optionSet = workspace.Options; foreach (var (key, value) in options) optionSet = optionSet.WithChangedOption(key, value); workspace.TryApplyChanges(workspace.CurrentSolution.WithOptions(optionSet)); } var typeSymbol = GetTypeSymbol(type)(context.SemanticModel); var getParameterSymbols = GetParameterSymbols(parameters, context); var setParameterSymbols = getParameterSymbols == null ? default : getParameterSymbols.Add(Parameter(type, "value")(context.SemanticModel)); var getAccessor = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, defaultAccessibility, new Editing.DeclarationModifiers(isAbstract: getStatements == null), typeSymbol, RefKind.None, explicitInterfaceImplementations: default, "get_" + name, typeParameters: default, getParameterSymbols, statements: context.ParseStatements(getStatements)); var setAccessor = CodeGenerationSymbolFactory.CreateMethodSymbol( attributes: default, setterAccessibility, new Editing.DeclarationModifiers(isAbstract: setStatements == null), GetTypeSymbol(typeof(void))(context.SemanticModel), RefKind.None, explicitInterfaceImplementations: default, "set_" + name, typeParameters: default, setParameterSymbols, statements: context.ParseStatements(setStatements)); // If get is provided but set isn't, we don't want an accessor for set if (getStatements != null && setStatements == null) { setAccessor = null; } // If set is provided but get isn't, we don't want an accessor for get if (getStatements == null && setStatements != null) { getAccessor = null; } var property = CodeGenerationSymbolFactory.CreatePropertySymbol( attributes: default, defaultAccessibility, modifiers, typeSymbol, RefKind.None, explicitInterfaceImplementations, name, getParameterSymbols, getAccessor, setAccessor, isIndexer); codeGenerationOptions ??= new CodeGenerationOptions(); codeGenerationOptions = codeGenerationOptions.With(options: codeGenerationOptions.Options ?? workspace.Options); context.Result = await context.Service.AddPropertyAsync(context.Solution, (INamedTypeSymbol)context.GetDestination(), property, codeGenerationOptions); } internal static async Task TestAddNamedTypeAsync( string initial, string expected, string name = "C", Accessibility accessibility = Accessibility.Public, Editing.DeclarationModifiers modifiers = default, TypeKind typeKind = TypeKind.Class, ImmutableArray<ITypeParameterSymbol> typeParameters = default, INamedTypeSymbol baseType = null, ImmutableArray<INamedTypeSymbol> interfaces = default, SpecialType specialType = SpecialType.None, ImmutableArray<Func<SemanticModel, ISymbol>> members = default, CodeGenerationOptions codeGenerationOptions = null) { using var context = await TestContext.CreateAsync(initial, expected); var memberSymbols = GetSymbols(members, context); var type = CodeGenerationSymbolFactory.CreateNamedTypeSymbol( attributes: default, accessibility, modifiers, typeKind, name, typeParameters, baseType, interfaces, specialType, memberSymbols); context.Result = await context.Service.AddNamedTypeAsync(context.Solution, (INamespaceSymbol)context.GetDestination(), type, codeGenerationOptions); } internal static async Task TestAddAttributeAsync( string initial, string expected, Type attributeClass, SyntaxToken? target = null) { using var context = await TestContext.CreateAsync(initial, expected); var attr = CodeGenerationSymbolFactory.CreateAttributeData(GetTypeSymbol(attributeClass)(context.SemanticModel)); var oldNode = context.GetDestinationNode(); var newNode = CodeGenerator.AddAttributes(oldNode, context.Document.Project.Solution.Workspace, new[] { attr }, target) .WithAdditionalAnnotations(Formatter.Annotation); context.Result = context.Document.WithSyntaxRoot(context.SemanticModel.SyntaxTree.GetRoot().ReplaceNode(oldNode, newNode)); } internal static async Task TestRemoveAttributeAsync<T>( string initial, string expected, Type attributeClass) where T : SyntaxNode { using var context = await TestContext.CreateAsync(initial, expected); var attributeType = GetTypeSymbol(attributeClass)(context.SemanticModel); var taggedNode = context.GetDestinationNode(); var attributeTarget = context.SemanticModel.GetDeclaredSymbol(taggedNode); var attribute = attributeTarget.GetAttributes().Single(attr => Equals(attr.AttributeClass, attributeType)); var declarationNode = taggedNode.FirstAncestorOrSelf<T>(); var newNode = CodeGenerator.RemoveAttribute(declarationNode, context.Document.Project.Solution.Workspace, attribute) .WithAdditionalAnnotations(Formatter.Annotation); context.Result = context.Document.WithSyntaxRoot(context.SemanticModel.SyntaxTree.GetRoot().ReplaceNode(declarationNode, newNode)); } internal static async Task TestUpdateDeclarationAsync<T>( string initial, string expected, Accessibility? accessibility = null, IEnumerable<SyntaxToken> modifiers = null, Func<SemanticModel, ITypeSymbol> getType = null, ImmutableArray<Func<SemanticModel, ISymbol>> getNewMembers = default, bool? declareNewMembersAtTop = null, string retainedMembersKey = "RetainedMember") where T : SyntaxNode { using var context = await TestContext.CreateAsync(initial, expected); var declarationNode = context.GetDestinationNode().FirstAncestorOrSelf<T>(); var updatedDeclarationNode = declarationNode; var workspace = context.Document.Project.Solution.Workspace; if (accessibility.HasValue) { updatedDeclarationNode = CodeGenerator.UpdateDeclarationAccessibility(declarationNode, workspace, accessibility.Value); } else if (modifiers != null) { updatedDeclarationNode = CodeGenerator.UpdateDeclarationModifiers(declarationNode, workspace, modifiers); } else if (getType != null) { updatedDeclarationNode = CodeGenerator.UpdateDeclarationType(declarationNode, workspace, getType(context.SemanticModel)); } else if (getNewMembers != null) { var retainedMembers = context.GetAnnotatedDeclaredSymbols(retainedMembersKey, context.SemanticModel); var newMembersToAdd = GetSymbols(getNewMembers, context); var allMembers = new List<ISymbol>(); if (declareNewMembersAtTop.HasValue && declareNewMembersAtTop.Value) { allMembers.AddRange(newMembersToAdd); allMembers.AddRange(retainedMembers); } else { allMembers.AddRange(retainedMembers); allMembers.AddRange(newMembersToAdd); } updatedDeclarationNode = CodeGenerator.UpdateDeclarationMembers(declarationNode, workspace, allMembers); } updatedDeclarationNode = updatedDeclarationNode.WithAdditionalAnnotations(Formatter.Annotation); context.Result = context.Document.WithSyntaxRoot(context.SemanticModel.SyntaxTree.GetRoot().ReplaceNode(declarationNode, updatedDeclarationNode)); } internal static async Task TestGenerateFromSourceSymbolAsync( string symbolSource, string initial, string expected, bool onlyGenerateMembers = false, CodeGenerationOptions codeGenerationOptions = null, string forceLanguage = null) { using var context = await TestContext.CreateAsync(initial, expected, forceLanguage); var destSpan = new TextSpan(); MarkupTestFile.GetSpan(symbolSource.NormalizeLineEndings(), out symbolSource, out destSpan); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var semanticModel = await context.Solution .AddProject(projectId, "GenerationSource", "GenerationSource", TestContext.GetLanguage(symbolSource)) .AddDocument(documentId, "Source.cs", symbolSource) .GetDocument(documentId) .GetSemanticModelAsync(); var docOptions = await context.Document.GetOptionsAsync(); codeGenerationOptions ??= new CodeGenerationOptions(); codeGenerationOptions = codeGenerationOptions.With(options: codeGenerationOptions.Options ?? docOptions); var symbol = TestContext.GetSelectedSymbol<INamespaceOrTypeSymbol>(destSpan, semanticModel); var destination = context.GetDestination(); if (destination.IsType) { var members = onlyGenerateMembers ? symbol.GetMembers().ToArray() : new[] { symbol }; context.Result = await context.Service.AddMembersAsync(context.Solution, (INamedTypeSymbol)destination, members, codeGenerationOptions); } else { context.Result = await context.Service.AddNamespaceOrTypeAsync(context.Solution, (INamespaceSymbol)destination, symbol, codeGenerationOptions); } } internal static Func<SemanticModel, IParameterSymbol> Parameter(Type type, string name, bool hasDefaultValue = false, object defaultValue = null, bool isParams = false) { return s => CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, RefKind.None, isParams, GetTypeSymbol(s.Compilation, type), name, isOptional: hasDefaultValue, hasDefaultValue: hasDefaultValue, defaultValue: defaultValue); } internal static Func<SemanticModel, IParameterSymbol> Parameter(string typeFullName, string parameterName, bool hasDefaultValue = false, object defaultValue = null, bool isParams = false, int typeArrayRank = 0) { return s => CodeGenerationSymbolFactory.CreateParameterSymbol( attributes: default, RefKind.None, isParams, GetTypeSymbol(s.Compilation, typeFullName, typeArrayRank), parameterName, isOptional: hasDefaultValue, hasDefaultValue: hasDefaultValue, defaultValue: defaultValue); } private static ITypeSymbol GetTypeSymbol(Compilation compilation, Type type) => !type.IsArray ? GetTypeSymbol(compilation, type.FullName) : GetTypeSymbol(compilation, type.GetElementType().FullName, type.GetArrayRank()); private static ITypeSymbol GetTypeSymbol(Compilation compilation, string typeFullName, int arrayRank = 0) { return arrayRank == 0 ? compilation.GetTypeByMetadataName(typeFullName) : compilation.CreateArrayTypeSymbol(compilation.GetTypeByMetadataName(typeFullName), arrayRank); } internal static ImmutableArray<Func<SemanticModel, IParameterSymbol>> Parameters(params Func<SemanticModel, IParameterSymbol>[] p) => p.ToImmutableArray(); internal static ImmutableArray<Func<SemanticModel, ISymbol>> Members(params Func<SemanticModel, ISymbol>[] m) => m.ToImmutableArray(); internal static Func<SemanticModel, ITypeSymbol> CreateArrayType(Type type, int rank = 1) => s => CodeGenerationSymbolFactory.CreateArrayTypeSymbol(GetTypeSymbol(type)(s), rank); private static ImmutableArray<IParameterSymbol> GetParameterSymbols(ImmutableArray<Func<SemanticModel, IParameterSymbol>> parameters, TestContext context) => parameters.IsDefault ? default : parameters.SelectAsArray(p => p(context.SemanticModel)); private static ImmutableArray<IMethodSymbol> GetMethodSymbols( Func<SemanticModel, ImmutableArray<IMethodSymbol>> explicitInterface, TestContext context) { return explicitInterface == null ? default : explicitInterface(context.SemanticModel); } private static ImmutableArray<ISymbol> GetSymbols(ImmutableArray<Func<SemanticModel, ISymbol>> members, TestContext context) { return members == null ? default : members.SelectAsArray(m => m(context.SemanticModel)); } private static Func<SemanticModel, ISymbol> CreateEnumField(string name, object value) { return s => CodeGenerationSymbolFactory.CreateFieldSymbol( attributes: default, Accessibility.Public, new Editing.DeclarationModifiers(), GetTypeSymbol(typeof(int))(s), name, value != null, value); } internal static Func<SemanticModel, ISymbol> CreateField(Accessibility accessibility, Editing.DeclarationModifiers modifiers, Type type, string name) { return s => CodeGenerationSymbolFactory.CreateFieldSymbol( attributes: default, accessibility, modifiers, GetTypeSymbol(type)(s), name); } private static Func<SemanticModel, INamedTypeSymbol> GetTypeSymbol(Type type) => GetTypeSymbol(type.FullName); private static Func<SemanticModel, INamedTypeSymbol> GetTypeSymbol(string typeMetadataName) => s => s?.Compilation.GetTypeByMetadataName(typeMetadataName); internal static IEnumerable<SyntaxToken> CreateModifierTokens(Editing.DeclarationModifiers modifiers, string language) { if (language == LanguageNames.CSharp) { if (modifiers.IsAbstract) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.AbstractKeyword); } if (modifiers.IsAsync) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.AsyncKeyword); } if (modifiers.IsConst) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.ConstKeyword); } if (modifiers.IsNew) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.NewKeyword); } if (modifiers.IsOverride) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.OverrideKeyword); } if (modifiers.IsPartial) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.PartialKeyword); } if (modifiers.IsReadOnly) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.ReadOnlyKeyword); } if (modifiers.IsSealed) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.SealedKeyword); } if (modifiers.IsStatic) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.StaticKeyword); } if (modifiers.IsUnsafe) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.UnsafeKeyword); } if (modifiers.IsVirtual) { yield return CS.SyntaxFactory.Token(CS.SyntaxKind.VirtualKeyword); } } else { if (modifiers.IsAbstract) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.MustOverrideKeyword); } if (modifiers.IsAsync) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.AsyncKeyword); } if (modifiers.IsConst) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.ConstKeyword); } if (modifiers.IsNew) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.NewKeyword); } if (modifiers.IsOverride) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.OverridesKeyword); } if (modifiers.IsPartial) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.PartialKeyword); } if (modifiers.IsReadOnly) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.ReadOnlyKeyword); } if (modifiers.IsSealed) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.NotInheritableKeyword); } if (modifiers.IsStatic) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.StaticKeyword); } if (modifiers.IsVirtual) { yield return VB.SyntaxFactory.Token(VB.SyntaxKind.OverridableKeyword); } } } internal class TestContext : IDisposable { private readonly string _expected; public readonly bool IsVisualBasic; public Document Document; public SemanticModel SemanticModel; public SyntaxTree SyntaxTree; public ICodeGenerationService Service; public Document Result; public readonly TestWorkspace Workspace; private readonly string _language; private readonly bool _ignoreResult; public TestContext( string expected, bool ignoreResult, string language, TestWorkspace workspace, SemanticModel semanticModel) { _expected = expected.NormalizeLineEndings(); _language = language; this.IsVisualBasic = _language == LanguageNames.VisualBasic; _ignoreResult = ignoreResult; Workspace = workspace; this.Document = Workspace.CurrentSolution.Projects.Single().Documents.Single(); this.SemanticModel = semanticModel; this.SyntaxTree = SemanticModel.SyntaxTree; this.Service = Document.Project.LanguageServices.GetService<ICodeGenerationService>(); } public static async Task<TestContext> CreateAsync(string initial, string expected, string forceLanguage = null, bool ignoreResult = false) { var language = forceLanguage ?? GetLanguage(initial); var isVisualBasic = language == LanguageNames.VisualBasic; var workspace = CreateWorkspaceFromFile(initial.NormalizeLineEndings(), isVisualBasic, null, null); var semanticModel = await workspace.CurrentSolution.Projects.Single().Documents.Single().GetSemanticModelAsync(); return new TestContext(expected, ignoreResult, language, workspace, semanticModel); } public Solution Solution { get { return Workspace.CurrentSolution; } } public SyntaxNode GetDestinationNode() { var destSpan = Workspace.Documents.Single().SelectedSpans.Single(); return SemanticModel.SyntaxTree.GetRoot().FindNode(destSpan, getInnermostNodeForTie: true); } public INamespaceOrTypeSymbol GetDestination() { var destSpan = Workspace.Documents.Single().SelectedSpans.Single(); return GetSelectedSymbol<INamespaceOrTypeSymbol>(destSpan, this.SemanticModel); } public IEnumerable<ISymbol> GetAnnotatedDeclaredSymbols(string key, SemanticModel semanticModel) { var annotatedSpans = Workspace.Documents.Single().AnnotatedSpans[key]; foreach (var span in annotatedSpans) { yield return GetSelectedSymbol<ISymbol>(span, semanticModel); } } public static T GetSelectedSymbol<T>(TextSpan selection, SemanticModel semanticModel) where T : class, ISymbol { var token = semanticModel.SyntaxTree.GetRoot().FindToken(selection.Start); var symbol = token.Parent.AncestorsAndSelf() .Select(a => semanticModel.GetDeclaredSymbol(a)) .Where(s => s != null).FirstOrDefault() as T; return symbol; } public T GetSelectedSyntax<T>(bool fullSpanCoverage = false) where T : SyntaxNode { var destSpan = Workspace.Documents.Single().SelectedSpans.Single(); var token = SemanticModel.SyntaxTree.GetRoot().FindToken(destSpan.Start); return token.Parent.AncestorsAndSelf().OfType<T>().FirstOrDefault(t => !fullSpanCoverage || t.Span.End >= destSpan.End); } public ImmutableArray<SyntaxNode> ParseStatements(string statements) { if (statements == null) { return default; } using var listDisposer = ArrayBuilder<SyntaxNode>.GetInstance(out var list); var delimiter = IsVisualBasic ? "\r\n" : ";"; var parts = statements.Split(new[] { delimiter }, StringSplitOptions.RemoveEmptyEntries); foreach (var p in parts) { if (IsVisualBasic) { list.Add(VB.SyntaxFactory.ParseExecutableStatement(p)); } else { list.Add(CS.SyntaxFactory.ParseStatement(p + delimiter)); } } return list.ToImmutable(); } public void Dispose() { try { if (!_ignoreResult) { this.Document = this.Result; var actual = Formatter.FormatAsync(Simplifier.ReduceAsync(this.Document, Simplifier.Annotation).Result, Formatter.Annotation).Result .GetSyntaxRootAsync().Result.ToFullString(); Assert.Equal(_expected, actual); } } finally { Workspace.Dispose(); } } public static string GetLanguage(string input) { return ContainsVisualBasicKeywords(input) ? LanguageNames.VisualBasic : LanguageNames.CSharp; } private static bool ContainsVisualBasicKeywords(string input) { return input.Contains("Module") || input.Contains("Class") || input.Contains("Structure") || input.Contains("Namespace") || input.Contains("Sub") || input.Contains("Function") || input.Contains("Dim") || input.Contains("Enum"); } private static TestWorkspace CreateWorkspaceFromFile(string file, bool isVisualBasic, ParseOptions parseOptions, CompilationOptions compilationOptions) { return isVisualBasic ? TestWorkspace.CreateVisualBasic(file, (VB.VisualBasicParseOptions)parseOptions, (VB.VisualBasicCompilationOptions)compilationOptions) : TestWorkspace.CreateCSharp(file, (CS.CSharpParseOptions)parseOptions, (CS.CSharpCompilationOptions)compilationOptions); } } } }
46.178728
218
0.612181
[ "MIT" ]
CyrusNajmabadi/roslyn
src/EditorFeatures/Test/CodeGeneration/CodeGenerationTests.cs
42,117
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using System.Diagnostics; using Microsoft.Xna.Framework.Graphics; using ThridWolrdShooterGame.Managers; using MyExtensions; namespace ThridWolrdShooterGame.Entites.Messages { public class BonusClock:Messages.Message { private Random random = new Random(); private bool timing; private float milisecondsTimer; private float milisecondsColorTimer; public BonusClock() { this.Position = new Vector2(5, 0); this.Font = EntityManager.Resources.AnimatedMessage; timing = false; MessageString = ""; ResetTimer(); } public void StartTiming() { timing = true; shaking= true; } public void StopTiming() { timing = false; shaking = false; } public void ResetTimer() { milisecondsTimer = 18000; milisecondsColorTimer = 0; } public float MilisecondsTimer { get { return milisecondsTimer; } } public override void Update(Microsoft.Xna.Framework.GameTime gameTime) { base.Update(gameTime); if (EnemySpawner.BonusMode) { this.MessageString = milisecondsTimer.ToString(); } if (timing) { if(milisecondsTimer > 0) milisecondsTimer -= gameTime.ElapsedGameTime.Milliseconds * GameplayScreen.SlowMoMultiplier; milisecondsColorTimer += gameTime.ElapsedGameTime.Milliseconds * GameplayScreen.SlowMoMultiplier; if (shaking) { shakeTimer += (float)gameTime.ElapsedGameTime.TotalSeconds; if (shakeTimer >= shakeDuration) { shaking = false; shakeTimer = shakeDuration; } float progress = shakeTimer / shakeDuration; float magnitude = shakeMagnitude * (1f - (progress * progress)); shakeOffset = (new Vector2(nextFloat(), nextFloat()) * magnitude) * GameplayScreen.SlowMoMultiplier; if (shakeFlagCounter < milisecondsTimer) { shakeFlagCounter += 1000; shakeTimer = 0f; shaking = true; } } } } private float nextFloat() { return (float)random.NextDouble() * 2f - 1f; } public override void Draw(Microsoft.Xna.Framework.Graphics.SpriteBatch spriteBatch) { if (EnemySpawner.BonusMode) { float factor = (EnemySpawner.ShieldAux != PlayerStatus.Shield ?1:(float)milisecondsColorTimer / 18000f); spriteBatch.DrawString(this.Font, ( ((int)(milisecondsTimer / 1000)).ToString().Length < 2 ? "0" + (int)(milisecondsTimer / 1000) : ""+ (int)(milisecondsTimer / 1000) ), shakeOffset + Position, ColorUtil.HSVToRGB(10f, factor,1f), 0f, Size / 2f, 2f, SpriteEffects.None, 0f); spriteBatch.DrawString(this.Font, ":" + ( (int)(milisecondsTimer % 1000)>0?(int)(milisecondsTimer % 1000)+"":"00" ), shakeOffset + Position + new Vector2(90, 39), ColorUtil.HSVToRGB(1f, factor, 1f), 0f, Size / 2f, 1f, SpriteEffects.None, 0f); spriteBatch.DrawLine(this.Position + new Vector2(-30, 85), this.Position + new Vector2(180, 85), Color.White, 2.8f); spriteBatch.DrawString(this.Font , "Timer" , this.Position + new Vector2(0 , 85), Color.White, 0, Size/ 2, 0.7f, SpriteEffects.None,0f); } } private int shakeFlagCounter; private bool shaking { get; set; } private float shakeTimer { get; set; } private float shakeDuration = 1f; private float shakeMagnitude = 10f; private Vector2 shakeOffset; } }
35.68595
290
0.539833
[ "MIT" ]
AlanSosa/Infinite-pew-pew-PC-Version
Infinite pew pew PC Version/Infinite pew pew PC Version/Game/Entites/Messages/BonusClock.cs
4,318
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.ManagedServices.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Error response. /// </summary> public partial class ErrorResponse { /// <summary> /// Initializes a new instance of the ErrorResponse class. /// </summary> public ErrorResponse() { CustomInit(); } /// <summary> /// Initializes a new instance of the ErrorResponse class. /// </summary> /// <param name="error">Error response indicates Azure Resource Manager /// is not able to process the incoming request. The reason is provided /// in the error message.</param> public ErrorResponse(ErrorResponseError error = default(ErrorResponseError)) { Error = error; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets error response indicates Azure Resource Manager is not able to /// process the incoming request. The reason is provided in the error /// message. /// </summary> [JsonProperty(PropertyName = "error")] public ErrorResponseError Error { get; private set; } /// <summary> /// Validate the object. /// </summary> /// <exception cref="Rest.ValidationException"> /// Thrown if validation fails /// </exception> public virtual void Validate() { if (Error != null) { Error.Validate(); } } } }
30.42029
90
0.586946
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/managedservices/Microsoft.Azure.Management.ManagedServices/src/Generated/Models/ErrorResponse.cs
2,099
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace SignalRHubServer { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); } } }
21.578947
60
0.692683
[ "MIT" ]
xiong-ang/SignalRDemo
SignalRHubServer/Global.asax.cs
412
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; using Amazon.SQS; using Amazon.SQS.Model; class Program { static readonly string MessageToSend = new XDocument(new XElement("SomeNativeMessage", new XElement("ThisIsTheMessage", "Hello!"))).ToString(); static async Task Main() { Console.Title = "Samples.Sqs.NativeIntegration"; while (true) { Console.WriteLine("Enter 'S' to send a message, enter 'exit' to stop"); var line = Console.ReadLine(); switch (line?.ToLowerInvariant()) { case "exit": return; case "s": #region SendingANativeMessage await SendTo(new Dictionary<string, MessageAttributeValue> { {"MessageTypeFullName", new MessageAttributeValue {DataType = "String", StringValue = "NativeIntegration.Receiver.SomeNativeMessage"}}, // required for native integration //{"S3BodyKey", new MessageAttributeValue {DataType = "String", StringValue = "s3bodykey"}}, // optional for native integration {"SomeRandomKey", new MessageAttributeValue {DataType = "String", StringValue = "something-random"}}, {"AnotherRandomKey", new MessageAttributeValue {DataType = "String", StringValue = "something-else-thats-random"}}, //{"ReplyToAddress", new MessageAttributeValue {DataType = "String", StringValue = "my-native-endpoint"}}, //optional, used to demo replying back to the native endpoint, make sure to create the queue manually in AWS }, MessageToSend); #endregion Console.WriteLine("Message was sent."); break; } } } static async Task SendTo(Dictionary<string, MessageAttributeValue> messageAttributeValues, string message) { using (var sqsClient = new AmazonSQSClient()) { var getQueueUrlResponse = await sqsClient.GetQueueUrlAsync(new GetQueueUrlRequest { QueueName = "Samples-Sqs-SimpleReceiver" // sanitized queue name }).ConfigureAwait(false); var body = Convert.ToBase64String(Encoding.Unicode.GetBytes(message)); var sendMessageRequest = new SendMessageRequest { QueueUrl = getQueueUrlResponse.QueueUrl, MessageAttributes = messageAttributeValues, MessageBody = body }; await sqsClient.SendMessageAsync(sendMessageRequest).ConfigureAwait(false); } } }
44.603175
240
0.593238
[ "Apache-2.0" ]
Particular/docs.particular.net
samples/sqs/native-integration/Sqs_5/Sender/Program.cs
2,750
C#
using PrintServer2.Properties; using PrintService.Server; using PrintService.UI; using PrintService.Utility; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Windows.Forms; namespace PrintServer2.UI { public class PrintTray { private NotifyIcon notifyIcon = null; private Language language = null; private PrintServer printServer = null; private TrayEventHander clickHander = null; private MenuItem exitItem = null; private MenuItem selectPrinter = null; private MenuItem printNow = null; private MenuItem showLog = null; private MenuItem changeLanguage = null; private MenuItem changePort = null; private MenuItem supportedTemplate = null; public PrintTray() { this.InitServer(); this.InitEventHalder(); this.InitTray(); this.printServer.StartProcess(); } /// <summary> /// Init the event handler /// </summary> private void InitEventHalder() { this.clickHander = new TrayEventHander(this.printServer); } /// <summary> /// Init the tray object /// </summary> private void InitTray() { this.language = Language.I; this.notifyIcon = new NotifyIcon(); this.notifyIcon.BalloonTipText = AppSettingHelper.GetOne("IconHint", "Print server was runing in backgroud"); this.notifyIcon.Text = AppSettingHelper.GetOne("HideHint", "Click icon to open main window"); this.notifyIcon.Icon = this.GetTaskBarIcon(); this.notifyIcon.Visible = true; this.notifyIcon.ShowBalloonTip(2000); this.changeLanguage = new MenuItem(this.language.Text("language", "Lanaguage")); var portString = this.language.Text("language", "Lanaguage") + "(" + this.printServer.GetWorkingPort().ToString() + ")"; this.changePort = new MenuItem(); this.supportedTemplate = new MenuItem(this.language.Text("show_templates", "Show Temlpates")); this.supportedTemplate.Click += this.clickHander.SupportedTemplates_Click; this.selectPrinter = new MenuItem(this.language.Text("select_printer", "Select Printer")); this.printNow = new MenuItem(this.language.Text("print_now", "Print Now")); this.printNow.Checked = this.printServer.GetPrintMode(); this.printNow.Click += this.clickHander.PrintMode_Click; this.showLog = new MenuItem(this.language.Text("show_log", "Show Logs")); this.showLog.Click += this.clickHander.ShowLog_Click; this.exitItem = new MenuItem(this.language.Text("exit", "Exit")); this.exitItem.Click += this.clickHander.Exit_Click; MenuItem[] childen = new MenuItem[] { this.changeLanguage, this.selectPrinter, this.supportedTemplate, this.showLog, this.printNow, this.exitItem }; notifyIcon.ContextMenu = new ContextMenu(childen); } /// <summary> /// Try to get icon for task bar /// first: try to find a icon file named logo.icon in folder Resources. if not found then use the build-in icon /// </summary> /// <returns></returns> private Icon GetTaskBarIcon() { var filePath = Environment.CurrentDirectory + "\\logo.ico"; var logo = File.Exists(filePath); if (logo) { return new Icon(filePath); } return Resources._default; } /// <summary> /// Init the print server /// </summary> private void InitServer() { this.printServer = new PrintServer(); this.printServer.OnPrinterLoaded = this.OnPrinterLoaded; this.printServer.OnPrinterChanged = this.OnPrinterSelected; this.printServer.OnPrintModeChanged = this.OnPrintModeChanded; } private void OnPrintModeChanded(bool printNow) { this.printNow.Checked = printNow; } /// <summary> /// When the print server has loaded all printer names then call this method to add meun items /// </summary> /// <param name="printerNames"></param> private void OnPrinterLoaded(List<string> printerNames) { this.selectPrinter.MenuItems.Clear(); var refreshPrinter = new MenuItem(this.language.Text("refresh_printer", "Refresh Printer")); refreshPrinter.Click += this.clickHander.RefreshPrinter_Click; this.selectPrinter.MenuItems.Add(refreshPrinter); foreach (var pName in printerNames) { var printerMenu = new MenuItem(pName); printerMenu.Tag = pName; printerMenu.Click += this.clickHander.SelectPrinter_Click; this.selectPrinter.MenuItems.Add(printerMenu); } } /// <summary> /// Triggered when print selected /// </summary> /// <param name="printName"></param> private void OnPrinterSelected(string printName) { foreach (var mi in this.selectPrinter.MenuItems) { if (mi is MenuItem) { var it = mi as MenuItem; if (it.Tag != null && it.Tag.ToString() == this.printServer.GetSelectedPrinterName()) { it.Checked = true; } else { it.Checked = false; } } } } /// <summary> /// Change language name /// </summary> /// <param name="languageName"></param> private void ChangeLanguage(string languageName) { this.language.ChangLanguage(languageName); } } }
34.324176
132
0.56251
[ "MIT" ]
xiangbohua/PrintServer2
PrintServer2/UI/PrintTray.cs
6,249
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.CloudAPI.Transform; using Aliyun.Acs.CloudAPI.Transform.V20160714; namespace Aliyun.Acs.CloudAPI.Model.V20160714 { public class SetDomainRequest : RpcAcsRequest<SetDomainResponse> { public SetDomainRequest() : base("CloudAPI", "2016-07-14", "SetDomain", "apigateway", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null); } } private string securityToken; private string groupId; private string domainName; public string SecurityToken { get { return securityToken; } set { securityToken = value; DictionaryUtil.Add(QueryParameters, "SecurityToken", value); } } public string GroupId { get { return groupId; } set { groupId = value; DictionaryUtil.Add(QueryParameters, "GroupId", value); } } public string DomainName { get { return domainName; } set { domainName = value; DictionaryUtil.Add(QueryParameters, "DomainName", value); } } public override SetDomainResponse GetResponse(UnmarshallerContext unmarshallerContext) { return SetDomainResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
28.193548
135
0.665141
[ "Apache-2.0" ]
xueandfeng/aliyun-openapi-net-sdk
aliyun-net-sdk-cloudapi/CloudAPI/Model/V20160714/SetDomainRequest.cs
2,622
C#
using ChuckyBurguer.BL; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace ChuckyBurguer.WebAdmin.Controllers { [Authorize] public class ProductosController : Controller { //variable ProductosBL _productosBL; CategoriasBL _categoriasBL; //constructor public ProductosController() { _productosBL = new ProductosBL(); _categoriasBL = new CategoriasBL(); } // GET: Productos public ActionResult Index() { var listadeProductos = _productosBL.ObtenerProductos(); return View(listadeProductos); } //aaaaaaaaaaaaaaaaaaaaaaquiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiiii si da error ver esto // Get: Crear public ActionResult Crear() { var nuevoProducto = new Producto(); var categorias = _categoriasBL.ObtenerCategorias(); ViewBag.CategoriaId = new SelectList(categorias, "Id", "Descripcion"); return View(nuevoProducto); } [HttpPost] // [HttpPost] : Atributo //es lo que retorna public ActionResult Crear(Producto producto, HttpPostedFileBase imagen) { if (ModelState.IsValid) { if (producto.CategoriaId == 0) { ModelState.AddModelError("CategoriaId", "Seleccione una categoria"); return View(producto); } if (imagen != null) { producto.UrlImagen = GuardarImagen(imagen); } _productosBL.GuardarProducto(producto); return RedirectToAction("Index"); } var categorias = _categoriasBL.ObtenerCategorias(); ViewBag.CategoriaId = new SelectList(categorias, "Id", "Descripcion"); return View(producto); } //Get: Editar public ActionResult Editar(int id) { var producto = _productosBL.ObtenerProducto(id); var categorias = _categoriasBL.ObtenerCategorias(); ViewBag.CategoriaId = new SelectList(categorias, "Id", "Descripcion",producto.CategoriaId); return View(producto); } [HttpPost] //POst public ActionResult Editar(Producto producto) { if (ModelState.IsValid) { if (producto.CategoriaId == 0) { ModelState.AddModelError("CategoriaId", "Seleccione una categoria"); return View(producto); } _productosBL.GuardarProducto(producto); return RedirectToAction("Index"); } var categorias = _categoriasBL.ObtenerCategorias(); ViewBag.CategoriaId = new SelectList(categorias, "Id", "Descripcion"); return View(producto); } //Detalle public ActionResult Detalle(int id) { var producto = _productosBL.ObtenerProducto(id); return View(producto); } //Eliminar public ActionResult Eliminar(int id) { var producto = _productosBL.ObtenerProducto(id); return View(producto); } [HttpPost] public ActionResult Eliminar(Producto producto) { _productosBL.EliminarProducto(producto.Id); return RedirectToAction("Index"); } private string GuardarImagen(HttpPostedFileBase imagen) { string path = Server.MapPath("~/Imagenes/" + imagen.FileName); imagen.SaveAs(path); return "/Imagenes/" + imagen.FileName; } } }
26.821918
89
0.547497
[ "MIT" ]
HenryLCR/QuieroPizza
ChuckyBurguer/ChuckyBurguer.WebAdmin/Controllers/ProductosController.cs
3,918
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Security; using System.Security.Cryptography; using System.Security.Cryptography.Pkcs; using System.Security.Cryptography.X509Certificates; using Kerberos.NET.Crypto; using Kerberos.NET.Entities; namespace Kerberos.NET.Server { public class PaDataPkAsReqHandler : KdcPreAuthenticationHandlerBase { private static readonly Oid IdPkInitDHKeyData = new Oid("1.3.6.1.5.2.3.2"); private static readonly Oid DiffieHellman = new Oid("1.2.840.10046.2.1"); private static readonly Oid EllipticCurveDiffieHellman = new Oid("1.2.840.10045.2.1"); private static readonly ReadOnlyMemory<KeyAgreementAlgorithm> DefaultSupportedAlgorithms = new ReadOnlyMemory<KeyAgreementAlgorithm>(new[] { KeyAgreementAlgorithm.DiffieHellmanModp14, KeyAgreementAlgorithm.EllipticCurveDiffieHellmanP256, KeyAgreementAlgorithm.EllipticCurveDiffieHellmanP384, KeyAgreementAlgorithm.EllipticCurveDiffieHellmanP521 }); public X509IncludeOption IncludeOption { get; set; } = X509IncludeOption.ExcludeRoot; public ICollection<KeyAgreementAlgorithm> SupportedKeyAgreementAlgorithms { get; set; } = new List<KeyAgreementAlgorithm>(DefaultSupportedAlgorithms.ToArray()); public PaDataPkAsReqHandler(IRealmService service) : base(service) { } public override void PreValidate(PreAuthenticationContext preauth) { var asReq = (KrbKdcReq)preauth.Message; var paPk = asReq.PaData.FirstOrDefault(p => p.Type == PaDataType.PA_PK_AS_REQ); if (paPk == null) { return; } var pkreq = KrbPaPkAsReq.Decode(paPk.Value); var signedCms = new SignedCms(); signedCms.Decode(pkreq.SignedAuthPack.ToArray()); var state = new PkInitState { PkInitRequest = pkreq, Cms = signedCms, ClientCertificate = signedCms.Certificates }; preauth.PreAuthenticationState[PaDataType.PA_PK_AS_REQ] = state; } public override KrbPaData Validate(KrbKdcReq asReq, PreAuthenticationContext preauth) { if (!preauth.PreAuthenticationState.TryGetValue(PaDataType.PA_PK_AS_REQ, out PaDataState paState) || !(paState is PkInitState state)) { return null; } var authPack = ValidateAuthPack(preauth, state); ValidateAuthenticator(authPack.PKAuthenticator, asReq.Body); var requestAlg = authPack.ClientPublicValue?.Algorithm?.Algorithm; IKeyAgreement agreement; if (requestAlg?.Value == EllipticCurveDiffieHellman.Value) { agreement = FromEllipticCurveDomainParameters(authPack.ClientPublicValue); } else if (requestAlg?.Value == DiffieHellman.Value) { agreement = FromDiffieHellmanDomainParameters(authPack.ClientPublicValue); } else { throw OnlyKeyAgreementSupportedException(); } var derivedKey = agreement.GenerateAgreement(); var etype = asReq.Body.EType.First(); var transform = CryptoService.CreateTransform(etype); ReadOnlyMemory<byte> clientDHNonce = authPack.ClientDHNonce.GetValueOrDefault(); ReadOnlyMemory<byte> serverDHNonce = default; if (clientDHNonce.Length > 0) { serverDHNonce = transform.GenerateRandomBytes(agreement.PublicKey.KeyLength); Service.Principals.CacheKey(agreement.PrivateKey); } var keyInfo = new KrbKdcDHKeyInfo { SubjectPublicKey = agreement.PublicKey.EncodePublicKey() }; if (agreement.PublicKey.CacheExpiry.HasValue) { keyInfo.DHKeyExpiration = agreement.PublicKey.CacheExpiry; keyInfo.Nonce = authPack.PKAuthenticator.Nonce; } var sessionKey = PKInitString2Key.String2Key( derivedKey.Span, transform.KeySize, clientDHNonce.Span, serverDHNonce.Span ); var paPkRep = new KrbPaPkAsRep { DHInfo = new KrbDHReplyInfo { DHSignedData = SignDHResponse(keyInfo), ServerDHNonce = serverDHNonce } }; preauth.PaData = new[] { new KrbPaData { Type = PaDataType.PA_PK_AS_REP, Value = paPkRep.Encode() } }; preauth.EncryptedPartKey = new KerberosKey(key: sessionKey.ToArray(), etype: etype); preauth.ClientAuthority = PaDataType.PA_PK_AS_REQ; return null; } private ReadOnlyMemory<byte> SignDHResponse(KrbKdcDHKeyInfo keyInfo) { var signed = new SignedCms( new ContentInfo( IdPkInitDHKeyData, keyInfo.Encode().ToArray() ) ); var certificate = Service.Principals.RetrieveKdcCertificate(); var signer = new CmsSigner(certificate) { IncludeOption = IncludeOption }; signed.ComputeSignature(signer); return signed.Encode(); } private static Exception OnlyKeyAgreementSupportedException() => throw new NotSupportedException("Only key agreement is supported for PKINIT authentication"); private IKeyAgreement FromDiffieHellmanDomainParameters(KrbSubjectPublicKeyInfo clientPublicValue) { var parameters = KrbDiffieHellmanDomainParameters.DecodeSpecial(clientPublicValue.Algorithm.Parameters.Value); IKeyAgreement agreement; if (IsSupportedAlgorithm(KeyAgreementAlgorithm.DiffieHellmanModp14, Oakley.Group14.Prime, parameters.P)) { var cachedKey = Service.Principals.RetrieveKeyCache(KeyAgreementAlgorithm.DiffieHellmanModp14); agreement = CryptoPal.Platform.DiffieHellmanModp14(cachedKey); } else if (IsSupportedAlgorithm(KeyAgreementAlgorithm.DiffieHellmanModp2, Oakley.Group2.Prime, parameters.P)) { var cachedKey = Service.Principals.RetrieveKeyCache(KeyAgreementAlgorithm.DiffieHellmanModp2); agreement = CryptoPal.Platform.DiffieHellmanModp2(cachedKey); } else { var length = parameters.P.Length * 8; throw new InvalidOperationException($"Unsupported Diffie Hellman key agreement parameter with length {length}"); } var publicKey = DiffieHellmanKey.ParsePublicKey(clientPublicValue.SubjectPublicKey, agreement.PublicKey.KeyLength); agreement.ImportPartnerKey(publicKey); return agreement; } private bool IsSupportedAlgorithm(KeyAgreementAlgorithm algorithm, ReadOnlyMemory<byte> expectedPVal, ReadOnlyMemory<byte> actualPVal) { if (!SupportedKeyAgreementAlgorithms.Contains(algorithm)) { return false; } return expectedPVal.Span.SequenceEqual(actualPVal.Span); } private IKeyAgreement FromEllipticCurveDomainParameters(KrbSubjectPublicKeyInfo _) { throw new NotImplementedException(); } private void ValidateAuthenticator(KrbPKAuthenticator authenticator, KrbKdcReqBody body) { using (var sha1 = CryptoPal.Platform.Sha1()) { var encoded = body.Encode(); var paChecksum = sha1.ComputeHash(encoded.Span); if (!KerberosCryptoTransformer.AreEqualSlow(paChecksum.Span, authenticator.PaChecksum.Value.Span)) { throw new SecurityException("Invalid checksum"); } } if (!KerberosConstants.WithinSkew(Service.Now(), authenticator.CTime, authenticator.CuSec, Service.Settings.MaximumSkew)) { throw new KerberosValidationException($"PKAuthenticator time skew too great"); } ValidateNonce(authenticator.Nonce); } protected virtual void ValidateNonce(int nonce) { Debug.Assert(nonce > 0); } private static KrbAuthPack ValidateAuthPack(PreAuthenticationContext preauth, PkInitState state) { state.Cms.CheckSignature(verifySignatureOnly: true); preauth.Principal.Validate(state.Cms.Certificates); var authPack = KrbAuthPack.Decode(state.Cms.ContentInfo.Content); return authPack; } } }
35.619608
166
0.618078
[ "MIT" ]
ericlaw1979/Kerberos.NET
Kerberos.NET/Server/PaDataPkAsReqHandler.cs
9,085
C#
using System; using System.ComponentModel.DataAnnotations; namespace BookShelf.Models { public class BookShelf { public Guid Id { get; set; } [Required] public string Name { get; set; } } }
18.833333
44
0.632743
[ "MIT" ]
rafaelldi/BookShelf
src/BookShelf/Models/BookShelf.cs
226
C#
namespace ExcelDna.Fluent.Command { public interface ICommand { /// <summary> /// 命令所属控件Id, <see cref="WriteCallbackXml">生成 Ribbon Xml</see>时会更新此Id /// </summary> string ControlId { get; } } }
29.125
77
0.587983
[ "MIT" ]
zwq00000/AddinX.Ribbon
src/ExcelDna.RibbonFluent/Fluent/Command/ICommand.cs
261
C#
using Pluto.Domain.Commands.Common; using System; namespace Pluto.Domain.Commands.Order { public class RemoveProductCommand : Command { public Guid ProductId { get; set; } public Guid UserId { get; set; } } }
19.916667
47
0.665272
[ "MIT" ]
spaki/Pluto
Pluto.Domain/Commands/Order/RemoveProductCommand.cs
241
C#
using System; using Xunit; public class Account { //https://gist.github.com/nirlanka/ed10b8cc9806bc192625a33837ba4a3b [Flags] public enum Access { Delete = 1, Publish = 2, Submit = 4, Comment = 8, Modify = 16, Writer = Submit | Modify, Editor = Delete | Publish | Comment, Owner = Writer | Editor } public static void Main(string[] args) { Assert.Equal(Access.Writer.HasFlag(Access.Delete),false); Console.WriteLine(Access.Writer.HasFlag(Access.Delete)); //Should print: "False" Console.WriteLine(Access.Editor.HasFlag(Access.Delete) && Access.Writer.HasFlag(Access.Publish)); //Should print: "False" Console.WriteLine(Access.Owner.HasFlag(Access.Writer) && Access.Owner.HasFlag(Access.Editor)); //Should print: "False" } }
29.517241
129
0.635514
[ "MIT" ]
samjones00/katas
EditorEnums/Program.cs
858
C#
/* * Copyright 2004 - $Date: 2008-11-15 23:58:07 +0100 (za, 15 nov 2008) $ by PeopleWare n.v.. * * 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. */ #region Using using System.Reflection; #endregion [assembly: AssemblyCompany("Peopleware NV")] [assembly: AssemblyProduct("PPWCode Kit Tasks")] [assembly: AssemblyCopyright("Copyright © PeopleWare NV 2010-2011")] [assembly: AssemblyTrademark("")] // version used by Windows for binary compatibility [assembly: AssemblyVersion("3.0.0.0")] // version used for informational purposes // for bugfixes, this version number should be increased // and a tag should be made in subversion [assembly: AssemblyFileVersion("3.2.0.0")]
34.8
93
0.722496
[ "Apache-2.0" ]
jandockx/ppwcode
dotnet/Kit/Tasks.API_I/I/3.n/3.2.0/src/SolutionItems/SolutionInfo.cs
1,221
C#
using System.Collections.Generic; namespace YNAB.Rest { public class BulkTransactions { public IList<string> TransactionIds { get; set; } public IList<string> DuplicateImportIds { get; set; } } /* { "transaction_ids": [ "string" ], "duplicate_import_ids": [ "string" ] } */ }
17.095238
61
0.551532
[ "MIT" ]
jdhawley/YNAB.Rest
YNAB.Rest/BulkTransactions.cs
361
C#
namespace InterReact; public enum GenericTickType { Undefined = 0, OptionVolume = 100, OptionOpenInterest = 101, HistoricalVolatility = 104, AverageOptionVolume = 105, OptionImpliedVolatility = 106, CloseImpliedVolatility = 107, BondAnalytics = 125, IndexFuturePremium = 162, MiscellaneousStatistics = 165, Cscreen = 166, MarkPrice = 221, AuctionValues = 225, RealtimeVolume = 233, Shortable = 236, Inventory = 256, Fundamentals = 258, CloseImpliedVolatility2 = 291, News = 292, TradeCount = 293, TradeRate = 294, VolumeRate = 295, LastRegularTradingHoursTrade = 318, ParticipationMonitor = 370, CttTickTag = 377, IbRate = 381, RfqTickRespTag = 384, Dmm = 387, IssuerFundamentals = 388, IbWarrantImpVolCompeteTick = 391, FuturesMargins = 407, RealtimeHistoricalVolatility = 411, MonetaryClosePrice = 428, MonitorTickTag = 439, Dividends = 456, TodayClose = 459, BondFactorMultiplier = 460 }
24.186047
39
0.670192
[ "Apache-2.0" ]
dshe/InterReact
InterReact/Enums/GenericTickType.cs
1,040
C#
using System; /* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Sys.Workflow.Engine.Impl.Persistence.Entity { /// <summary> /// DeadLetterJob entity, necessary for persistence. /// /// /// </summary> [Serializable] public class DeadLetterJobEntityImpl : AbstractJobEntityImpl, IDeadLetterJobEntity { private const long serialVersionUID = 1L; public override string ToString() { return "DeadLetterJobEntity [id=" + Id + "]"; } } }
30.470588
86
0.683398
[ "Apache-2.0" ]
zhangzihan/nactivity
NActiviti/Sys.Bpm.Engine/Engine/impl/persistence/entity/DeadLetterJobEntityImpl.cs
1,038
C#
using System.Web; using System.ComponentModel.DataAnnotations; using AlloyNoJS.Models.Pages; using EPiServer.Web; using EPiServer.Core; namespace AlloyNoJS.Models.ViewModels { public class ContactBlockModel { [UIHint(UIHint.Image)] public ContentReference Image { get; set; } public string Heading { get; set; } public string LinkText { get; set; } public IHtmlString LinkUrl { get; set; } public bool ShowLink { get; set; } public ContactPage ContactPage { get; set; } } }
27.15
52
0.672192
[ "Apache-2.0" ]
episerver/AlloyNoJS
AlloyNoJS/Models/ViewModels/ContactBlockModel.cs
543
C#
// <auto-generated /> using System; using MaestroApp.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace MaestroApp.Migrations { [DbContext(typeof(MaestroAppDbContext))] [Migration("20180927062608_Upgrade_ABP_3.8.3")] partial class Upgrade_ABP_383 { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.3-rtm-32065") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Abp.Application.Editions.Edition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.HasKey("Id"); b.ToTable("AbpEditions"); }); modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Discriminator") .IsRequired(); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.Property<string>("Value") .IsRequired() .HasMaxLength(2000); b.HasKey("Id"); b.ToTable("AbpFeatures"); b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting"); }); modelBuilder.Entity("Abp.Auditing.AuditLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<string>("CustomData") .HasMaxLength(2000); b.Property<string>("Exception") .HasMaxLength(2000); b.Property<int>("ExecutionDuration"); b.Property<DateTime>("ExecutionTime"); b.Property<int?>("ImpersonatorTenantId"); b.Property<long?>("ImpersonatorUserId"); b.Property<string>("MethodName") .HasMaxLength(256); b.Property<string>("Parameters") .HasMaxLength(1024); b.Property<string>("ServiceName") .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionDuration"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Abp.Authorization.PermissionSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Discriminator") .IsRequired(); b.Property<bool>("IsGranted"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpPermissions"); b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasMaxLength(256); b.Property<string>("ClaimValue"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int>("RoleId"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("EmailAddress") .HasMaxLength(256); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastLoginTime"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.Property<long?>("UserLinkId"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("EmailAddress"); b.HasIndex("UserName"); b.HasIndex("TenantId", "EmailAddress"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "UserName"); b.ToTable("AbpUserAccounts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType") .HasMaxLength(256); b.Property<string>("ClaimValue"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("LoginProvider") .IsRequired() .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<byte>("Result"); b.Property<string>("TenancyName") .HasMaxLength(64); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.Property<string>("UserNameOrEmailAddress") .HasMaxLength(255); b.HasKey("Id"); b.HasIndex("UserId", "TenantId"); b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result"); b.ToTable("AbpUserLoginAttempts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<bool>("IsDeleted"); b.Property<long>("OrganizationUnitId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int>("RoleId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "RoleId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime?>("ExpireDate"); b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("Name") .HasMaxLength(128); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.Property<string>("Value") .HasMaxLength(512); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<bool>("IsAbandoned"); b.Property<string>("JobArgs") .IsRequired() .HasMaxLength(1048576); b.Property<string>("JobType") .IsRequired() .HasMaxLength(512); b.Property<DateTime?>("LastTryTime"); b.Property<DateTime>("NextTryTime"); b.Property<byte>("Priority"); b.Property<short>("TryCount"); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.Property<string>("Value") .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("ChangeTime"); b.Property<byte>("ChangeType"); b.Property<long>("EntityChangeSetId"); b.Property<string>("EntityId") .HasMaxLength(48); b.Property<string>("EntityTypeFullName") .HasMaxLength(192); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("EntityChangeSetId"); b.HasIndex("EntityTypeFullName", "EntityId"); b.ToTable("AbpEntityChanges"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChangeSet", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("BrowserInfo") .HasMaxLength(512); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<string>("ExtensionData"); b.Property<int?>("ImpersonatorTenantId"); b.Property<long?>("ImpersonatorUserId"); b.Property<string>("Reason") .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "CreationTime"); b.HasIndex("TenantId", "Reason"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpEntityChangeSets"); }); modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<long>("EntityChangeId"); b.Property<string>("NewValue") .HasMaxLength(512); b.Property<string>("OriginalValue") .HasMaxLength(512); b.Property<string>("PropertyName") .HasMaxLength(96); b.Property<string>("PropertyTypeFullName") .HasMaxLength(192); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("EntityChangeId"); b.ToTable("AbpEntityPropertyChanges"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<string>("Icon") .HasMaxLength(128); b.Property<bool>("IsDeleted"); b.Property<bool>("IsDisabled"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(10); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpLanguages"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Key") .IsRequired() .HasMaxLength(256); b.Property<string>("LanguageName") .IsRequired() .HasMaxLength(10); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Source") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.Property<string>("Value") .IsRequired() .HasMaxLength(67108864); b.HasKey("Id"); b.HasIndex("TenantId", "Source", "LanguageName", "Key"); b.ToTable("AbpLanguageTexts"); }); modelBuilder.Entity("Abp.Notifications.NotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Data") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasMaxLength(512); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("ExcludedUserIds") .HasMaxLength(131072); b.Property<string>("NotificationName") .IsRequired() .HasMaxLength(96); b.Property<byte>("Severity"); b.Property<string>("TenantIds") .HasMaxLength(131072); b.Property<string>("UserIds") .HasMaxLength(131072); b.HasKey("Id"); b.ToTable("AbpNotifications"); }); modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("NotificationName") .HasMaxLength(96); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId"); b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId"); b.ToTable("AbpNotificationSubscriptions"); }); modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Data") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasMaxLength(512); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("NotificationName") .IsRequired() .HasMaxLength(96); b.Property<byte>("Severity"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AbpTenantNotifications"); }); modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<int>("State"); b.Property<int?>("TenantId"); b.Property<Guid>("TenantNotificationId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId", "State", "CreationTime"); b.ToTable("AbpUserNotifications"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("Code") .IsRequired() .HasMaxLength(95); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(128); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<long?>("ParentId"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("ParentId"); b.HasIndex("TenantId", "Code"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("MaestroApp.Authorization.Roles.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("Description") .HasMaxLength(5000); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<bool>("IsDefault"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsStatic"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.Property<string>("NormalizedName") .IsRequired() .HasMaxLength(32); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("MaestroApp.Authorization.Users.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<int>("AccessFailedCount"); b.Property<string>("AuthenticationSource") .HasMaxLength(64); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken() .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("EmailAddress") .IsRequired() .HasMaxLength(256); b.Property<string>("EmailConfirmationCode") .HasMaxLength(328); b.Property<bool>("IsActive"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsEmailConfirmed"); b.Property<bool>("IsLockoutEnabled"); b.Property<bool>("IsPhoneNumberConfirmed"); b.Property<bool>("IsTwoFactorEnabled"); b.Property<DateTime?>("LastLoginTime"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<DateTime?>("LockoutEndDateUtc"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.Property<string>("NormalizedEmailAddress") .IsRequired() .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasMaxLength(256); b.Property<string>("Password") .IsRequired() .HasMaxLength(128); b.Property<string>("PasswordResetCode") .HasMaxLength(328); b.Property<string>("PhoneNumber") .HasMaxLength(32); b.Property<string>("SecurityStamp") .HasMaxLength(128); b.Property<string>("Surname") .IsRequired() .HasMaxLength(32); b.Property<int?>("TenantId"); b.Property<string>("UserName") .IsRequired() .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedEmailAddress"); b.HasIndex("TenantId", "NormalizedUserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("MaestroApp.MultiTenancy.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ConnectionString") .HasMaxLength(1024); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int?>("EditionId"); b.Property<bool>("IsActive"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<string>("TenancyName") .IsRequired() .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("EditionId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenancyName"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("EditionId"); b.HasIndex("EditionId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("EditionFeatureSetting"); }); modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("TenantFeatureSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<int>("RoleId"); b.HasIndex("RoleId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("RolePermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<long>("UserId"); b.HasIndex("UserId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("UserPermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.HasOne("MaestroApp.Authorization.Roles.Role") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.HasOne("MaestroApp.Authorization.Users.User") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.HasOne("MaestroApp.Authorization.Users.User") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.HasOne("MaestroApp.Authorization.Users.User") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.HasOne("MaestroApp.Authorization.Users.User") .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.HasOne("MaestroApp.Authorization.Users.User") .WithMany("Settings") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.HasOne("Abp.EntityHistory.EntityChangeSet") .WithMany("EntityChanges") .HasForeignKey("EntityChangeSetId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b => { b.HasOne("Abp.EntityHistory.EntityChange") .WithMany("PropertyChanges") .HasForeignKey("EntityChangeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.HasOne("Abp.Organizations.OrganizationUnit", "Parent") .WithMany("Children") .HasForeignKey("ParentId"); }); modelBuilder.Entity("MaestroApp.Authorization.Roles.Role", b => { b.HasOne("MaestroApp.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("MaestroApp.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("MaestroApp.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("MaestroApp.Authorization.Users.User", b => { b.HasOne("MaestroApp.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("MaestroApp.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("MaestroApp.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("MaestroApp.MultiTenancy.Tenant", b => { b.HasOne("MaestroApp.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("MaestroApp.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId"); b.HasOne("MaestroApp.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasOne("MaestroApp.Authorization.Roles.Role") .WithMany("Permissions") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasOne("MaestroApp.Authorization.Users.User") .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
33.594444
125
0.460275
[ "MIT" ]
dviltres18/MaestroApp
aspnet-core/src/MaestroApp.EntityFrameworkCore/Migrations/20180927062608_Upgrade_ABP_3.8.3.Designer.cs
42,331
C#
namespace WindowsForms { partial class SimpleElementsForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.button1 = new System.Windows.Forms.Button(); this.button2 = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // button1 // this.button1.Location = new System.Drawing.Point(12, 12); this.button1.Name = "button1"; this.button1.Size = new System.Drawing.Size(75, 23); this.button1.TabIndex = 0; this.button1.Text = "button1"; this.button1.UseVisualStyleBackColor = true; // // button2 // this.button2.Location = new System.Drawing.Point(12, 41); this.button2.Name = "button2"; this.button2.Size = new System.Drawing.Size(75, 23); this.button2.TabIndex = 1; this.button2.Text = "button2"; this.button2.UseVisualStyleBackColor = true; // // textBox1 // this.textBox1.Location = new System.Drawing.Point(12, 96); this.textBox1.Name = "textBox1"; this.textBox1.Size = new System.Drawing.Size(100, 20); this.textBox1.TabIndex = 2; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(12, 70); this.textBox2.Name = "textBox2"; this.textBox2.Size = new System.Drawing.Size(100, 20); this.textBox2.TabIndex = 3; this.textBox2.Text = "Enter some text"; // // SimpleElementsForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(184, 273); this.Controls.Add(this.textBox2); this.Controls.Add(this.textBox1); this.Controls.Add(this.button2); this.Controls.Add(this.button1); this.Name = "SimpleElementsForm"; this.Text = "SimpleElementsForm"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button button1; private System.Windows.Forms.Button button2; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TextBox textBox2; } }
37.129032
107
0.552853
[ "MIT" ]
Extensis/RAutomation
ext/WindowsForms/WindowsForms/SimpleElementsForm.Designer.cs
3,455
C#
namespace PofyTools.Distribution { using UnityEngine; using System.Collections; /// <summary> /// Distribution based on chance with optional Auto Deck Size /// </summary> public class Chance { private bool _autoDeckSize = true; /// <summary> /// Gets or sets a value indicating whether this <see cref="PofyTools.Distribution.Chance"/> auto deck size. /// </summary> /// <value><c>true</c> if auto deck size; otherwise, <c>false</c>.</value> public bool autoDeckSize { get { return this._autoDeckSize; } set { if (value != this._autoDeckSize) this._autoDeckSize = value; else Debug.LogWarning ("Chance: Auto Deck size is already " + value + "."); } } [Range (0f, 1f)] private float _chance = 0; /// <summary> /// Gets or sets the chance (0 - 1). /// </summary> /// <value>The chance.</value> public float chance { get { return this._chance; } set { if (value != this._chance) { this._chance = value; BuildDeck (); } } } public float percent { get { return this._chance * 100; } } private Deck<bool> _deck; /// <summary> /// Gets total card count in distribution deck. /// </summary> /// <value>The count.</value> public int Count { get { return this._deck.Count; } } public bool Value { get { return this._deck.PickNextCard ().Element; } } public bool RandomValue { get { return Random.Range (0f, 1f) < this._chance; } } void Initialize () { BuildDeck (); } void BuildDeck () { int deckSize = 0; float percent = this._chance * 100; if (this._autoDeckSize) { if (percent % 100 == 0) { deckSize = 1; } else if (percent % 50 == 0) { deckSize = 2; } else if (percent % 25 == 0) { deckSize = 4; } else if (percent % 20 == 0) { deckSize = 5; } else if (percent % 10 == 0) { deckSize = 10; } else if (percent % 5 == 0) { deckSize = 20; } else if (percent % 4 == 0) { deckSize = 25; } else if (percent % 2 == 0) { deckSize = 50; } else if (percent % 1 == 0) { deckSize = 100; } else { deckSize = 1000; } } else { deckSize = 1000; } this._deck = new Deck<bool> (deckSize); int trueCount = (int)(this._chance * deckSize); int falseCount = deckSize - trueCount; if (trueCount > 0) this._deck.AddCard (new Deck<bool>.Card (true, trueCount)); if (falseCount > 0) this._deck.AddCard (new Deck<bool>.Card (false, falseCount)); this._deck = this._deck.CreateDistributionDeck (); } public Chance () : this (1f) { } public Chance (float chance) : this (chance, true) { } public Chance (float chance, bool autoDeckSize) { this._chance = chance; this._autoDeckSize = autoDeckSize; Initialize (); } #region Static Methods public static bool FiftyFifty { get { return Random.Range (0, 2) > 0; } } public static bool TryWithChance (float chance) { chance = Mathf.Clamp01 (chance); return Random.Range (0f, 1f) < chance; } public static int GenerateDigits (int digits) { int total = 0; for (int i = 0; i < digits; ++i) { int value = (int)Mathf.Pow (10, i); int result = 0; int count = 0; while (Chance.FiftyFifty && count < 10) { count++; result += value; } total += result; } return total; } public static int GenerateDigits (int digits, int min, int max) { return Mathf.Clamp (GenerateDigits (digits), min, max); } #endregion } }
27.508671
116
0.437697
[ "MIT" ]
PofyTeam/PofyTools
Distribution/Chance.cs
4,761
C#
using AmplaData.AmplaData2008; using AmplaData.Modules.Metrics; using NUnit.Framework; namespace AmplaData.Binding.Mapping.Modules { [TestFixture] public class MetricsModuleMappingUnitTests : ModuleMappingTestFixture { public MetricsModuleMappingUnitTests() : base(MetricsViews.StandardView, () => new MetricsModuleMapping()) { } [Test] public void IdField() { CheckField<IdFieldMapping>("Id", "Id", true, false); } [Test] public void LocationField() { CheckField<ReadOnlyFieldMapping>("ObjectId", "Location", true, false); } [Test] public void StartDateTime() { CheckField<ReadOnlyFieldMapping>("StartDateTime", "Start Time", true, false); } [Test] public void EndDateTime() { CheckField<ReadOnlyFieldMapping>("EndDateTime", "End Time", true, false); } [Test] public void Period() { CheckField<ReadOnlyFieldMapping>("Period", "Period", true, false); } [Test] public void Duration() { CheckField<ReadOnlyFieldMapping>("Duration", "Duration", true, false); } [Test] public void SupportedOperations() { CheckAllowedOperations( ViewAllowedOperations.ViewRecord); } } }
25.137931
89
0.561043
[ "MIT" ]
Ampla/Ampla-Data
src/AmplaData.Tests/Binding/Mapping/Modules/MetricsModuleMappingUnitTests.cs
1,460
C#
using System; using System.Collections.Generic; using System.Text; namespace DungeonsAndCodeWizards.Entities.Characters.Contracts { public interface IAttackable { void Attack(Character character); } }
18.083333
62
0.769585
[ "MIT" ]
SimeonShterev/2018.01.22-2018.04.22-CSharpFundamentals
2018.02.12-OOPBasics/OfficialExam-SecondTry/DungeonsAndCodeWizards/Entities/Characters/Contracts/IAttackable.cs
219
C#
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; namespace Mozu.Api.ToolKit.Config { public class AppSetting : IAppSetting { public string AppName { get; private set; } public string ApplicationId { get; private set; } public string SharedSecret { get; private set; } public string SMTPServerUrl { get; private set; } public string BaseUrl { get; private set; } public string Log4NetConfig { get; private set; } public string Namespace { get; private set; } public string Version { get; private set; } public string PackageName { get; private set; } public IDictionary<string, Object> Settings { get; private set; } public AppSetting() { InitAppConfig(); } public AppSetting(string configPath, string appName, string environment) { Init(configPath, appName, environment); } private void InitAppConfig() { Settings = new Dictionary<string, object>(); foreach (var key in ConfigurationManager.AppSettings.AllKeys) { Settings.Add(key, ConfigurationManager.AppSettings[key]); } if (Settings.ContainsKey("SmtpServer")) SMTPServerUrl = Settings["SmtpServer"].ToString(); if (Settings.ContainsKey("MozuAuthUrl")) BaseUrl = Settings["MozuAuthUrl"].ToString(); if (Settings.ContainsKey("AppName")) AppName = Settings["AppName"].ToString(); SetProperties(); } private void SetProperties() { if (Settings.ContainsKey("ApplicationId")) { ApplicationId = Settings["ApplicationId"].ToString(); ParseAppKey(); } if (Settings.ContainsKey("SharedSecret")) SharedSecret = Settings["SharedSecret"].ToString(); } private void Init(string configPath, string appName, string environment) { AppName = appName; var appConfig = Path.Combine(configPath, appName, "App.config"); Log4NetConfig = Path.Combine(configPath, appName, "log4net.config"); var commonConfig = Path.Combine(configPath, "Common.config"); if (!File.Exists(appConfig)) throw new IOException("Settings File not found"); if (!File.Exists(commonConfig)) throw new IOException("Url setting File not found"); var configFileMap = new ExeConfigurationFileMap { ExeConfigFilename = appConfig }; var commonFileMap = new ExeConfigurationFileMap { ExeConfigFilename = commonConfig }; var configuration = ConfigurationManager.OpenMappedExeConfiguration(configFileMap, ConfigurationUserLevel.None); var commonConfiguration = ConfigurationManager.OpenMappedExeConfiguration(commonFileMap, ConfigurationUserLevel.None); BaseUrl = commonConfiguration.AppSettings.Settings[environment].Value; if (environment.Equals("PROD")) SMTPServerUrl = commonConfiguration.AppSettings.Settings["SmtpServer_" + environment].Value; else SMTPServerUrl = commonConfiguration.AppSettings.Settings["SmtpServer"].Value; Settings = new Dictionary<string, object>(); foreach (var key in configuration.AppSettings.Settings.AllKeys) { Settings.Add(key.EndsWith("_" + environment) ? key.Replace("_" + environment, "") : key, configuration.AppSettings.Settings[key].Value); } foreach (var key in ConfigurationManager.AppSettings.AllKeys.Where(key => !Settings.ContainsKey(key))) { Settings.Add(key, ConfigurationManager.AppSettings[key]); } SetProperties(); } private void ParseAppKey() { var parts = ApplicationId.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries); if (parts.Length < 4) return; Namespace = parts[0]; PackageName = "Release"; var packageNameOffset = 0; var lastPart = parts[parts.Length - 1]; int testInt; bool cc = int.TryParse(lastPart, out testInt); if (!cc) { // check if the last part is an int, then it is the revision of the version // otherwise, it is the package name PackageName = parts[parts.Length - 1]; packageNameOffset = 1; } // parse version var versionStartIndex = parts.Length - (3 + packageNameOffset); Version = String.Join(".", parts, versionStartIndex, 3); } } }
33.245033
130
0.58247
[ "MIT" ]
LatinWarrior/Mozu.Api.Tookit.Luis
Mozu.Api.ToolKit/Config/AppSetting.cs
5,022
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.RecoveryServices.Backup.CrossRegionRestore.Models { /// <summary> /// Defines values for ResourceHealthStatus. /// </summary> public static class ResourceHealthStatus { public const string Healthy = "Healthy"; public const string TransientDegraded = "TransientDegraded"; public const string PersistentDegraded = "PersistentDegraded"; public const string TransientUnhealthy = "TransientUnhealthy"; public const string PersistentUnhealthy = "PersistentUnhealthy"; public const string Invalid = "Invalid"; } }
35.925926
86
0.723711
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/recoveryservices-backup/Microsoft.Azure.Management.RecoveryServices.Backup/src/recoveryservicesbackupCrossregionRestoe/Generated/Models/ResourceHealthStatus.cs
970
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 System.Linq; using System.Threading.Tasks; namespace Microbenchmarks.Tests.TestModels { public class User { public int Id { get; set; } public string Name { get; set; } public string Blurb { get; set; } public DateTimeOffset DateOfBirth { get; set; } public int YearsEmployeed { get; set; } } }
23.958333
111
0.678261
[ "Apache-2.0" ]
benaadams/Performance
test/Microbenchmarks.Tests/TestModels/User.cs
577
C#
// <copyright file="UserController.cs" company="None"> // All rights reserved. // </copyright> // <author>Sander Dings</author> using System.Collections.Generic; using Newtonsoft.Json; using UnityEngine; using UnityEngine.UI; /// <summary> /// The user controller. Manages all things that belong to the user. /// </summary> public class UserController : Singleton<UserController> { /// <summary> /// The username of the current user. /// </summary> [SerializeField] private string userName; /// <summary> /// The text field that contains the username. /// </summary> [SerializeField] private Text userNameText; /// <summary> /// The text field prefab to hold a username. /// </summary> [SerializeField] private Text playerNamesText; /// <summary> /// The Transform to be the parent of the texts. /// </summary> [SerializeField] private RectTransform textParent; /// <summary> /// The list of Text fields holding the usernames. /// </summary> private Dictionary<string, Text> userNameHolders; /// <summary> /// The receiver for user changes. /// </summary> private ChatReceiver changeReceiver; /// <summary> /// The receiver for the complete list of users. /// </summary> private ChatReceiver userListReceiver; /// <summary> /// The list of names to add. /// </summary> private List<string> namesToAdd; /// <summary> /// The list of names to remove. /// </summary> private List<string> namesToRemove; /// <summary> /// Gets the username of the current user. /// </summary> public string UserName { get { return this.userName; } } /// <summary> /// Used for initialization. /// </summary> public void Awake() { this.namesToAdd = new List<string>(); this.namesToRemove = new List<string>(); this.userNameHolders = new Dictionary<string, Text>(); this.userName = Random.Range(100000000, 999999999).ToString(); this.userNameText.text = this.userName; this.changeReceiver = new ChatReceiver(); this.changeReceiver.ReceiveEvent += this.UpdateReceived; this.changeReceiver.StartExchangeListen("userchange"); this.userListReceiver = new ChatReceiver(); this.userListReceiver.ReceiveEvent += this.UserListReceived; this.userListReceiver.StartExchangeListen("newuserlist"); UserChangeSender sender = new UserChangeSender(); sender.Login(); sender.Disconnect(); } /// <summary> /// Called once per frame, used to update the UI. /// </summary> public void Update() { lock (this.namesToAdd) { for (int i = 0; i < this.namesToAdd.Count; i++) { // If we're gonna delete it anyway, why go through the effort of creating the object? (Don't add if it's in the to-remove list as well) if (this.userName != this.namesToAdd[i] && !this.namesToRemove.Contains(this.namesToAdd[i]) && !this.userNameHolders.ContainsKey(this.namesToAdd[i])) { Text text = Instantiate(this.playerNamesText); text.text = this.namesToAdd[i]; text.transform.SetParent(this.textParent); this.userNameHolders.Add(this.namesToAdd[i], text); } } this.namesToAdd.Clear(); this.textParent.sizeDelta = new Vector2(this.textParent.sizeDelta.x, 20 * (this.userNameHolders.Count + 1)); } lock (this.namesToRemove) { for (int i = 0; i < this.namesToRemove.Count; i++) { if (this.userNameHolders.ContainsKey(this.namesToRemove[i])) { this.userNameHolders.Remove(this.namesToRemove[i]); UserController.Destroy(this.userNameHolders[this.namesToRemove[i]]); } } this.namesToRemove.Clear(); this.textParent.sizeDelta = new Vector2(this.textParent.sizeDelta.x, 20 * (this.userNameHolders.Count + 1)); } } /// <summary> /// Adds a user to the list. /// </summary> /// <param name="userName">The username to add.</param> private void AddUser(string userName) { lock (this.namesToAdd) { this.namesToAdd.Add(userName); } } /// <summary> /// Removes a user from the list. /// </summary> /// <param name="userName">The username to remove.</param> private void RemoveUser(string userName) { lock (this.namesToRemove) { this.namesToRemove.Remove(userName); } } /// <summary> /// Overwrites the users dictionary with new values. /// </summary> /// <param name="usernames">The new list of usernames.</param> private void OverwriteUsers(Dictionary<string, byte> usernames) { lock (this.namesToAdd) { foreach (string s in usernames.Keys) { this.namesToAdd.Add(s); } } } /// <summary> /// The function to call when a message is received. /// </summary> /// <param name="s">The sender object.</param> /// <param name="e">The values associated with the event.</param> private void UpdateReceived(object s, Receiver.ConsumerEventArgs e) { UserJoinInfo joinInfo = JsonConvert.DeserializeObject<UserJoinInfo>(e.Message); if (joinInfo.Added) { this.AddUser(joinInfo.Username); } else { this.RemoveUser(joinInfo.Username); } } /// <summary> /// The function to call when a list of users is received. /// </summary> /// <param name="s">The sender object.</param> /// <param name="e">The values associated with the event.</param> private void UserListReceived(object s, Receiver.ConsumerEventArgs e) { Dictionary<string, byte> users = JsonConvert.DeserializeObject<Dictionary<string, byte>>(e.Message); this.OverwriteUsers(users); this.userListReceiver.CloseConnection(); } }
29.885714
165
0.592894
[ "MIT" ]
eternalflamez/ChatApplication
ChatApplication/Assets/Scripts/Controllers/UserController.cs
6,278
C#
using System.Collections.Generic; using UnityEngine; /// <summary> /// 参考来源:https://github.com/EllanJiang/StarForce /// </summary> public class DeviceModelConfig : ScriptableObject { [SerializeField] private List<DeviceModel> m_DeviceModels = null; public DeviceModel[] GetDeviceModels () { return m_DeviceModels.ToArray (); } public void NewDeviceModel () { m_DeviceModels.Add (new DeviceModel ()); } public void RemoveDeviceModelAt (int index) { m_DeviceModels.RemoveAt (index); } public QualityLevelType GetDefaultQualityLevel () { string modelName = SystemInfo.deviceModel; for (int i = 0; i < m_DeviceModels.Count; i++) { if (m_DeviceModels[i].ModelName == modelName) { return m_DeviceModels[i].QualityLevel; } } return QualityLevelType.Fastest; } }
27.181818
59
0.64437
[ "Apache-2.0" ]
mutouzdl/GF_JustOneLevel
Assets/GF_JustOneLevel/Scripts/Config/DeviceModelConfig.cs
909
C#
//--------------------------------------------------------------------- // Author: Harley Green // // Description: Class to create dynamic types // // Creation Date: 2008/3/8 //--------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Reflection; using System.Reflection.Emit; namespace SwisPowerShell { public class DataTypeBuilder { private readonly ModuleBuilder _moduleBuilder; private static int _createdTypes; private static readonly object _createdTypesLock = new object(); public DataTypeBuilder(string name) { var assemblyName = new AssemblyName { Name = name }; _moduleBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly( assemblyName, AssemblyBuilderAccess.Run).DefineDynamicModule(name); } public Type CreateType(IEnumerable<Pair<string, Type>> properties) { TypeBuilder typeBuilder = _moduleBuilder.DefineType(GetDynamicName(), TypeAttributes.Public); AddProperties(typeBuilder, properties); Type type = typeBuilder.CreateType(); return type; } private void AddProperties(TypeBuilder builder, IEnumerable<Pair<string, Type>> properties) { foreach (var pair in properties) { AddProperty(builder, pair.First, pair.Second); } } private void AddProperty(TypeBuilder builder, string propertyName, Type propertyType) { string fieldName = String.Format("_{0}", propertyName); Type type = propertyType; if (type.IsValueType) { type = GetNullableType(type); } FieldBuilder fieldBuilder = builder.DefineField(fieldName, type, FieldAttributes.Private); PropertyBuilder propertyBuilder = builder.DefineProperty(propertyName, PropertyAttributes.None, type, Type.EmptyTypes); const MethodAttributes getSetAttr = MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig; MethodBuilder getPropertyMethodBuilder = builder.DefineMethod( String.Format("get_{0}", propertyName), getSetAttr, type, Type.EmptyTypes); ILGenerator propertyNameGetIL = getPropertyMethodBuilder.GetILGenerator(); propertyNameGetIL.Emit(OpCodes.Ldarg_0); propertyNameGetIL.Emit(OpCodes.Ldfld, fieldBuilder); propertyNameGetIL.Emit(OpCodes.Ret); MethodBuilder custNameSetPropMthdBldr = builder.DefineMethod( String.Format("set_{0}", propertyName), getSetAttr, null, new[] { type }); ILGenerator propertyNameSetIL = custNameSetPropMthdBldr.GetILGenerator(); propertyNameSetIL.Emit(OpCodes.Ldarg_0); propertyNameSetIL.Emit(OpCodes.Ldarg_1); propertyNameSetIL.Emit(OpCodes.Stfld, fieldBuilder); propertyNameSetIL.Emit(OpCodes.Ret); propertyBuilder.SetGetMethod(getPropertyMethodBuilder); propertyBuilder.SetSetMethod(custNameSetPropMthdBldr); } private Type GetNullableType(Type underlying) { Type nullable = typeof(Nullable<>); Type result = nullable.MakeGenericType(underlying); return result; } private static string GetDynamicName() { lock (_createdTypesLock) { return String.Format("PscxDynamicType{0}", _createdTypes++); } } } }
35.563636
105
0.575665
[ "Apache-2.0" ]
AnaCr/OrionSDK
Src/SwisPowerShell/DataTypeBuilder.cs
3,912
C#
using System; using Telerik.Core; namespace Telerik.UI.Xaml.Controls.Grid { public abstract class GridElement : Element, IGridNode { public object ContainerType { get; set; } public object Container { get; set; } public RadSize DesiredSize { get; set; } } }
15.481481
58
0.466507
[ "Apache-2.0" ]
PseudoPlay/UI-For-UWP
Controls/Grid/Grid.UWP/Model/Common/GridElement.cs
420
C#
using ArgsAsRoutes.BL.Entities; using ArgsAsRoutes.Interfaces.ArgLang; namespace ArgsAsRoutes.BL.TokenScanners; public class CollectionOfValidCharsButDifferentStartTokenScanner : TokenScannerBase { private readonly string _validFirstCharacters; private readonly string _validNextCharacters; public CollectionOfValidCharsButDifferentStartTokenScanner(string typeName, string validFirstCharacters, string validNextCharacters) : base(typeName) { _validFirstCharacters = validFirstCharacters; _validNextCharacters = validNextCharacters; } public override IToken? GetToken(string content, ref int position) { if (_validFirstCharacters.Contains(content[position])) { return new Token( TypeName, Collect(content, ref position) ); } return null; } private string Collect(string content, ref int position) { var result = content[position].ToString(); position += 1; while (position < content.Length && _validNextCharacters.Contains(content[position])) { result += content[position]; position += 1; } return result; } }
27.717391
93
0.650196
[ "MIT" ]
stho32/CH023-Library-X-CSharp
Source/ArgsAsRoutes/ArgsAsRoutes.BL/TokenScanners/CollectionOfValidCharsButDifferentStartTokenScanner.cs
1,275
C#
using System; using System.Collections.Generic; using System.Linq; using Melanchall.DryWetMidi.Common; namespace Melanchall.DryWetMidi.Core { /// <summary> /// Provides extension methods for <see cref="TrackChunk"/>. /// </summary> public static class TrackChunkUtilities { #region Methods /// <summary> /// Gets all track chunks of a MIDI file. /// </summary> /// <param name="midiFile">MIDI file to get track chunks of.</param> /// <returns>Collection of track chunks contained in the <paramref name="midiFile"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="midiFile"/> is <c>null</c>.</exception> public static IEnumerable<TrackChunk> GetTrackChunks(this MidiFile midiFile) { ThrowIfArgument.IsNull(nameof(midiFile), midiFile); return midiFile.Chunks.OfType<TrackChunk>(); } /// <summary> /// Merges multiple track chunks into one that corresponds to <see cref="MidiFileFormat.SingleTrack"/>. /// </summary> /// <param name="trackChunks">Track chunks to merge into one.</param> /// <returns>Track chunk that containes all events from the <paramref name="trackChunks"/>.</returns> /// <remarks> /// Note that events will be cloned so events in the result track chunk will not be equal /// by reference to events in the <paramref name="trackChunks"/>. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="trackChunks"/> is <c>null</c>.</exception> public static TrackChunk Merge(this IEnumerable<TrackChunk> trackChunks) { ThrowIfArgument.IsNull(nameof(trackChunks), trackChunks); return ConvertTrackChunks(trackChunks, MidiFileFormat.SingleTrack).First(); } /// <summary> /// Splits a track chunk into multiple ones that correspond to <see cref="MidiFileFormat.MultiTrack"/>. /// </summary> /// <param name="trackChunk">Track chunk to split into multiple ones.</param> /// <returns>Multiple track chunks that represent <paramref name="trackChunk"/>.</returns> /// <remarks> /// Note that events will be cloned so events in the result track chunks will not be equal /// by reference to events in the <paramref name="trackChunk"/>. /// </remarks> /// <exception cref="ArgumentNullException"><paramref name="trackChunk"/> is <c>null</c>.</exception> public static IEnumerable<TrackChunk> Explode(this TrackChunk trackChunk) { ThrowIfArgument.IsNull(nameof(trackChunk), trackChunk); return ConvertTrackChunks(new[] { trackChunk }, MidiFileFormat.MultiTrack); } /// <summary> /// Gets all channel numbers presented in the specified <see cref="TrackChunk"/>. /// </summary> /// <param name="trackChunk"><see cref="TrackChunk"/> to get channels of.</param> /// <returns>Collection of channel numbers presented in the <paramref name="trackChunk"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="trackChunk"/> is <c>null</c>.</exception> public static IEnumerable<FourBitNumber> GetChannels(this TrackChunk trackChunk) { ThrowIfArgument.IsNull(nameof(trackChunk), trackChunk); return trackChunk.Events.OfType<ChannelEvent>().Select(e => e.Channel).Distinct().ToArray(); } /// <summary> /// Gets all channel numbers presented in the specified collection of <see cref="TrackChunk"/>. /// </summary> /// <param name="trackChunks">Collection of <see cref="TrackChunk"/> to get channels of.</param> /// <returns>Collection of channel numbers presented in the <paramref name="trackChunks"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="trackChunks"/> is <c>null</c>.</exception> public static IEnumerable<FourBitNumber> GetChannels(this IEnumerable<TrackChunk> trackChunks) { ThrowIfArgument.IsNull(nameof(trackChunks), trackChunks); return trackChunks.Where(c => c != null).SelectMany(GetChannels).Distinct().ToArray(); } private static IEnumerable<TrackChunk> ConvertTrackChunks(IEnumerable<TrackChunk> trackChunks, MidiFileFormat format) { var chunksConverter = ChunksConverterFactory.GetConverter(format); return chunksConverter.Convert(trackChunks) .OfType<TrackChunk>(); } #endregion } }
47.591837
125
0.642796
[ "MIT" ]
EnableIrelandAT/Coimbra
ProjectCoimbra.UWP/Melanchall.DryWetMidi.UWP/Core/Utilities/TrackChunkUtilities.cs
4,666
C#
using System.Collections.Generic; using System.Linq; namespace Canducci.GraphQLQuery.MSTest.Queries.Datas { public class States : List<State> { public States() { var st1 = new State { Id = 1, Name = "SP", Cities = new List<City>() }; st1.Cities.Add(new City { Id = 1, Name = "SÃO PAULO", StateId = 1 }); var st2 = new State { Id = 2, Name = "RJ", Cities = new List<City>() }; st2.Cities.Add(new City { Id = 2, Name = "RIO DE JANEIRO", StateId = 2 }); Add(st1); Add(st2); } public State AddState(State state) { state.Id = this.LastOrDefault().Id + 1; Add(state); return state; } } }
22.75
83
0.468864
[ "MIT" ]
fulviocanducci/Canducci.GraphQLQuery
Canducci.GraphQLQuery.MSTest/Queries/Datas/States.cs
822
C#
#region License // Copyright 2004-2010 Castle Project - http://www.castleproject.org/ // // 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. // #endregion namespace Castle.Facilities.NHibernateIntegration.Tests.Issues.Facilities117 { using Builders; using Castle.MicroKernel; using Core.Configuration; using Core.Resource; using MicroKernel.SubSystems.Configuration; using NUnit.Framework; using Rhino.Mocks; using Windsor.Configuration.Interpreters; using Is = Rhino.Mocks.Constraints.Is; using List = Rhino.Mocks.Constraints.List; [TestFixture] public class PersistentConfigurationBuilderConventionsFixture { private IConfiguration facilityCfg; [SetUp] public void SetUp() { var configurationStore = new DefaultConfigurationStore(); var resource = new AssemblyResource("Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities117/facility.xml"); var xmlInterpreter = new XmlInterpreter(resource); xmlInterpreter.ProcessResource(resource, configurationStore, new DefaultKernel()); facilityCfg = configurationStore.GetFacilityConfiguration(typeof(NHibernateFacility).FullName).Children["factory"]; } [Test] public void Derives_valid_filename_from_session_factory_ID_when_not_explicitly_specified() { var configurationPersister = MockRepository.GenerateMock<IConfigurationPersister>(); configurationPersister.Expect(x => x.IsNewConfigurationRequired(null, null)) .IgnoreArguments() .Constraints(Is.Equal("sessionFactory1.dat"), Is.Anything()) .Return(false); var builder = new PersistentConfigurationBuilder(configurationPersister); builder.GetConfiguration(facilityCfg); configurationPersister.VerifyAllExpectations(); } [Test] public void Includes_mapping_assemblies_in_dependent_file_list() { var configurationPersister = MockRepository.GenerateMock<IConfigurationPersister>(); configurationPersister.Expect(x => x.IsNewConfigurationRequired(null, null)) .IgnoreArguments() .Constraints(Is.Anything(), List.ContainsAll(new[] {"Castle.Facilities.NHibernateIntegration.Tests.dll"})) .Return(false); var builder = new PersistentConfigurationBuilder(configurationPersister); builder.GetConfiguration(facilityCfg); configurationPersister.VerifyAllExpectations(); } } }
35.938272
123
0.752662
[ "Apache-2.0" ]
ByteDecoder/Castle.Facilities.NHibernateIntegration
src/Castle.Facilities.NHibernateIntegration.Tests/Issues/Facilities117/PersistentConfigurationBuilderConventionsFixture.cs
2,831
C#
namespace Lykke.Service.FxPriceAdapter.FxGeteRest { public class MarketProfile { public MarketProfileResult Result { get; set; } } }
21.857143
55
0.69281
[ "MIT" ]
LykkeCity/Lykke.Service.FxPriceAdapter
src/Lykke.Service.FxPriceAdapter/FxGeteRest/MarketProfile.cs
155
C#
using MongoDB.Bson.Serialization; using Pso.Domain.Entities; namespace Pso.Infra.Data.NoSqlMongoDb.Mapping { public class LenteMap : MapBase<Lente> { public override void OnBsonClassMap(BsonClassMap<Lente> map) { map.MapMember(x => x.Cyl); map.MapMember(x => x.Eixo); map.MapMember(x => x.Grau); map.MapMember(x => x.OculosId); map.MapMember(x => x.LenteType); } } }
25.833333
68
0.584946
[ "MIT" ]
tmoreirafreitas/PSO.BackEnd
Pso.Infra.Data.NoSqlMongoDb/Mapping/LenteMap.cs
467
C#
using EpicLibrary.Services; using Playnite; using Playnite.SDK; using Playnite.Commands; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows.Media; using Playnite.SDK.Data; namespace EpicLibrary { public class EpicLibrarySettings { public int Version { get; set; } public bool ImportInstalledGames { get; set; } = EpicLauncher.IsInstalled; public bool ConnectAccount { get; set; } = false; public bool ImportUninstalledGames { get; set; } = false; } public class EpicLibrarySettingsViewModel : PluginSettingsViewModel<EpicLibrarySettings, EpicLibrary> { public bool IsUserLoggedIn { get { return new EpicAccountClient(PlayniteApi, Plugin.TokensPath).GetIsUserLoggedIn(); } } public RelayCommand<object> LoginCommand { get => new RelayCommand<object>((a) => { Login(); }); } public EpicLibrarySettingsViewModel(EpicLibrary library, IPlayniteAPI api) : base(library, api) { var savedSettings = LoadSavedSettings(); if (savedSettings != null) { if (savedSettings.Version == 0) { Logger.Debug("Updating Epic settings from version 0."); if (savedSettings.ImportUninstalledGames) { savedSettings.ConnectAccount = true; } } savedSettings.Version = 1; Settings = savedSettings; } else { Settings = new EpicLibrarySettings { Version = 1 }; } } private void Login() { try { var clientApi = new EpicAccountClient(PlayniteApi, Plugin.TokensPath); clientApi.Login(); OnPropertyChanged(nameof(IsUserLoggedIn)); } catch (Exception e) when (!Debugger.IsAttached) { PlayniteApi.Dialogs.ShowErrorMessage(PlayniteApi.Resources.GetString("LOCNotLoggedInError"), ""); Logger.Error(e, "Failed to authenticate user."); } } } }
30.821429
114
0.544226
[ "MIT" ]
JosefNemec/PlayniteExtensions
source/Libraries/EpicLibrary/EpicLibrarySettingsViewModel.cs
2,591
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.ResourceGroups { /// <summary> /// Provides a Resource Group. /// /// ## Example Usage /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var test = new Aws.ResourceGroups.Group("test", new Aws.ResourceGroups.GroupArgs /// { /// ResourceQuery = new Aws.ResourceGroups.Inputs.GroupResourceQueryArgs /// { /// Query = @"{ /// ""ResourceTypeFilters"": [ /// ""AWS::EC2::Instance"" /// ], /// ""TagFilters"": [ /// { /// ""Key"": ""Stage"", /// ""Values"": [""Test""] /// } /// ] /// } /// /// ", /// }, /// }); /// } /// /// } /// ``` /// /// ## Import /// /// Resource groups can be imported using the `name`, e.g. /// /// ```sh /// $ pulumi import aws:resourcegroups/group:Group foo resource-group-name /// ``` /// </summary> [AwsResourceType("aws:resourcegroups/group:Group")] public partial class Group : Pulumi.CustomResource { /// <summary> /// The ARN assigned by AWS for this resource group. /// </summary> [Output("arn")] public Output<string> Arn { get; private set; } = null!; /// <summary> /// A description of the resource group. /// </summary> [Output("description")] public Output<string?> Description { get; private set; } = null!; /// <summary> /// The resource group's name. A resource group name can have a maximum of 127 characters, including letters, numbers, hyphens, dots, and underscores. The name cannot start with `AWS` or `aws`. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// A `resource_query` block. Resource queries are documented below. /// </summary> [Output("resourceQuery")] public Output<Outputs.GroupResourceQuery> ResourceQuery { get; private set; } = null!; /// <summary> /// Key-value map of resource tags /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Create a Group 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 Group(string name, GroupArgs args, CustomResourceOptions? options = null) : base("aws:resourcegroups/group:Group", name, args ?? new GroupArgs(), MakeResourceOptions(options, "")) { } private Group(string name, Input<string> id, GroupState? state = null, CustomResourceOptions? options = null) : base("aws:resourcegroups/group:Group", 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 Group 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 Group Get(string name, Input<string> id, GroupState? state = null, CustomResourceOptions? options = null) { return new Group(name, id, state, options); } } public sealed class GroupArgs : Pulumi.ResourceArgs { /// <summary> /// A description of the resource group. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The resource group's name. A resource group name can have a maximum of 127 characters, including letters, numbers, hyphens, dots, and underscores. The name cannot start with `AWS` or `aws`. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// A `resource_query` block. Resource queries are documented below. /// </summary> [Input("resourceQuery", required: true)] public Input<Inputs.GroupResourceQueryArgs> ResourceQuery { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Key-value map of resource tags /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public GroupArgs() { } } public sealed class GroupState : Pulumi.ResourceArgs { /// <summary> /// The ARN assigned by AWS for this resource group. /// </summary> [Input("arn")] public Input<string>? Arn { get; set; } /// <summary> /// A description of the resource group. /// </summary> [Input("description")] public Input<string>? Description { get; set; } /// <summary> /// The resource group's name. A resource group name can have a maximum of 127 characters, including letters, numbers, hyphens, dots, and underscores. The name cannot start with `AWS` or `aws`. /// </summary> [Input("name")] public Input<string>? Name { get; set; } /// <summary> /// A `resource_query` block. Resource queries are documented below. /// </summary> [Input("resourceQuery")] public Input<Inputs.GroupResourceQueryGetArgs>? ResourceQuery { get; set; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Key-value map of resource tags /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public GroupState() { } } }
34.827103
201
0.556957
[ "ECL-2.0", "Apache-2.0" ]
aamir-locus/pulumi-aws
sdk/dotnet/ResourceGroups/Group.cs
7,453
C#
using System; namespace Tetrominoes { public class RandomMatchCalculator : IMatchCalculator { readonly Random _random; public RandomMatchCalculator(Random random) => _random = random ?? throw new ArgumentNullException(nameof(random)); public TetrominoPiece NextTetrominoPiece() => (TetrominoPiece)_random.Next(1, 8); } }
25.6
80
0.671875
[ "MIT" ]
joncloud/tetrominoes
src/Tetrominoes/RandomMatchCalculator.cs
386
C#
// <auto-generated /> using Abp.Authorization; using Abp.BackgroundJobs; using Abp.Events.Bus.Entities; using Abp.Notifications; using TityoAttendance.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.Internal; using Microsoft.EntityFrameworkCore.ValueGeneration; using System; namespace TityoAttendance.Migrations { [DbContext(typeof(TityoAttendanceDbContext))] [Migration("20180201051646_Upgraded_To_Abp_v3.4.0")] partial class Upgraded_To_Abp_v340 { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.0.1-rtm-125") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Abp.Application.Editions.Edition", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.HasKey("Id"); b.ToTable("AbpEditions"); }); modelBuilder.Entity("Abp.Application.Features.FeatureSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Discriminator") .IsRequired(); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.Property<string>("Value") .IsRequired() .HasMaxLength(2000); b.HasKey("Id"); b.ToTable("AbpFeatures"); b.HasDiscriminator<string>("Discriminator").HasValue("FeatureSetting"); }); modelBuilder.Entity("Abp.Auditing.AuditLog", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("BrowserInfo") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<string>("CustomData") .HasMaxLength(2000); b.Property<string>("Exception") .HasMaxLength(2000); b.Property<int>("ExecutionDuration"); b.Property<DateTime>("ExecutionTime"); b.Property<int?>("ImpersonatorTenantId"); b.Property<long?>("ImpersonatorUserId"); b.Property<string>("MethodName") .HasMaxLength(256); b.Property<string>("Parameters") .HasMaxLength(1024); b.Property<string>("ServiceName") .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "ExecutionDuration"); b.HasIndex("TenantId", "ExecutionTime"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpAuditLogs"); }); modelBuilder.Entity("Abp.Authorization.PermissionSetting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Discriminator") .IsRequired(); b.Property<bool>("IsGranted"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpPermissions"); b.HasDiscriminator<string>("Discriminator").HasValue("PermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType") .HasMaxLength(256); b.Property<string>("ClaimValue"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int>("RoleId"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("RoleId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpRoleClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserAccount", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("EmailAddress") .HasMaxLength(256); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastLoginTime"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.Property<long?>("UserLinkId"); b.Property<string>("UserName") .HasMaxLength(32); b.HasKey("Id"); b.HasIndex("EmailAddress"); b.HasIndex("UserName"); b.HasIndex("TenantId", "EmailAddress"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "UserName"); b.ToTable("AbpUserAccounts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType") .HasMaxLength(256); b.Property<string>("ClaimValue"); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "ClaimType"); b.ToTable("AbpUserClaims"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("LoginProvider") .IsRequired() .HasMaxLength(128); b.Property<string>("ProviderKey") .IsRequired() .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.HasIndex("TenantId", "LoginProvider", "ProviderKey"); b.ToTable("AbpUserLogins"); }); modelBuilder.Entity("Abp.Authorization.Users.UserLoginAttempt", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("BrowserInfo") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<byte>("Result"); b.Property<string>("TenancyName") .HasMaxLength(64); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.Property<string>("UserNameOrEmailAddress") .HasMaxLength(255); b.HasKey("Id"); b.HasIndex("UserId", "TenantId"); b.HasIndex("TenancyName", "UserNameOrEmailAddress", "Result"); b.ToTable("AbpUserLoginAttempts"); }); modelBuilder.Entity("Abp.Authorization.Users.UserOrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<bool>("IsDeleted"); b.Property<long>("OrganizationUnitId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "OrganizationUnitId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserOrganizationUnits"); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<int>("RoleId"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "RoleId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserRoles"); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.Property<string>("Value"); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpUserTokens"); }); modelBuilder.Entity("Abp.BackgroundJobs.BackgroundJobInfo", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<bool>("IsAbandoned"); b.Property<string>("JobArgs") .IsRequired() .HasMaxLength(1048576); b.Property<string>("JobType") .IsRequired() .HasMaxLength(512); b.Property<DateTime?>("LastTryTime"); b.Property<DateTime>("NextTryTime"); b.Property<byte>("Priority"); b.Property<short>("TryCount"); b.HasKey("Id"); b.HasIndex("IsAbandoned", "NextTryTime"); b.ToTable("AbpBackgroundJobs"); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.Property<string>("Value") .HasMaxLength(2000); b.HasKey("Id"); b.HasIndex("UserId"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpSettings"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("ChangeTime"); b.Property<byte>("ChangeType"); b.Property<long>("EntityChangeSetId"); b.Property<string>("EntityId") .HasMaxLength(48); b.Property<string>("EntityTypeFullName") .HasMaxLength(192); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("EntityChangeSetId"); b.HasIndex("EntityTypeFullName", "EntityId"); b.ToTable("AbpEntityChanges"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChangeSet", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("BrowserInfo") .HasMaxLength(256); b.Property<string>("ClientIpAddress") .HasMaxLength(64); b.Property<string>("ClientName") .HasMaxLength(128); b.Property<DateTime>("CreationTime"); b.Property<string>("ExtensionData"); b.Property<int?>("ImpersonatorTenantId"); b.Property<long?>("ImpersonatorUserId"); b.Property<string>("Reason") .HasMaxLength(256); b.Property<int?>("TenantId"); b.Property<long?>("UserId"); b.HasKey("Id"); b.HasIndex("TenantId", "CreationTime"); b.HasIndex("TenantId", "Reason"); b.HasIndex("TenantId", "UserId"); b.ToTable("AbpEntityChangeSets"); }); modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<long>("EntityChangeId"); b.Property<string>("NewValue") .HasMaxLength(512); b.Property<string>("OriginalValue") .HasMaxLength(512); b.Property<string>("PropertyName") .HasMaxLength(96); b.Property<string>("PropertyTypeFullName") .HasMaxLength(192); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("EntityChangeId"); b.ToTable("AbpEntityPropertyChanges"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguage", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<string>("Icon") .HasMaxLength(128); b.Property<bool>("IsDeleted"); b.Property<bool>("IsDisabled"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(10); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpLanguages"); }); modelBuilder.Entity("Abp.Localization.ApplicationLanguageText", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Key") .IsRequired() .HasMaxLength(256); b.Property<string>("LanguageName") .IsRequired() .HasMaxLength(10); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Source") .IsRequired() .HasMaxLength(128); b.Property<int?>("TenantId"); b.Property<string>("Value") .IsRequired() .HasMaxLength(67108864); b.HasKey("Id"); b.HasIndex("TenantId", "Source", "LanguageName", "Key"); b.ToTable("AbpLanguageTexts"); }); modelBuilder.Entity("Abp.Notifications.NotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Data") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasMaxLength(512); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("ExcludedUserIds") .HasMaxLength(131072); b.Property<string>("NotificationName") .IsRequired() .HasMaxLength(96); b.Property<byte>("Severity"); b.Property<string>("TenantIds") .HasMaxLength(131072); b.Property<string>("UserIds") .HasMaxLength(131072); b.HasKey("Id"); b.ToTable("AbpNotifications"); }); modelBuilder.Entity("Abp.Notifications.NotificationSubscriptionInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("NotificationName") .HasMaxLength(96); b.Property<int?>("TenantId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("NotificationName", "EntityTypeName", "EntityId", "UserId"); b.HasIndex("TenantId", "NotificationName", "EntityTypeName", "EntityId", "UserId"); b.ToTable("AbpNotificationSubscriptions"); }); modelBuilder.Entity("Abp.Notifications.TenantNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<string>("Data") .HasMaxLength(1048576); b.Property<string>("DataTypeName") .HasMaxLength(512); b.Property<string>("EntityId") .HasMaxLength(96); b.Property<string>("EntityTypeAssemblyQualifiedName") .HasMaxLength(512); b.Property<string>("EntityTypeName") .HasMaxLength(250); b.Property<string>("NotificationName") .IsRequired() .HasMaxLength(96); b.Property<byte>("Severity"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("TenantId"); b.ToTable("AbpTenantNotifications"); }); modelBuilder.Entity("Abp.Notifications.UserNotificationInfo", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<DateTime>("CreationTime"); b.Property<int>("State"); b.Property<int?>("TenantId"); b.Property<Guid>("TenantNotificationId"); b.Property<long>("UserId"); b.HasKey("Id"); b.HasIndex("UserId", "State", "CreationTime"); b.ToTable("AbpUserNotifications"); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Code") .IsRequired() .HasMaxLength(95); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(128); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<long?>("ParentId"); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("ParentId"); b.HasIndex("TenantId", "Code"); b.ToTable("AbpOrganizationUnits"); }); modelBuilder.Entity("TityoAttendance.Authorization.Roles.Role", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("Description") .HasMaxLength(5000); b.Property<string>("DisplayName") .IsRequired() .HasMaxLength(64); b.Property<bool>("IsDefault"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsStatic"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.Property<string>("NormalizedName") .IsRequired() .HasMaxLength(32); b.Property<int?>("TenantId"); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedName"); b.ToTable("AbpRoles"); }); modelBuilder.Entity("TityoAttendance.Authorization.Users.User", b => { b.Property<long>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("AuthenticationSource") .HasMaxLength(64); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<string>("EmailAddress") .IsRequired() .HasMaxLength(256); b.Property<string>("EmailConfirmationCode") .HasMaxLength(328); b.Property<bool>("IsActive"); b.Property<bool>("IsDeleted"); b.Property<bool>("IsEmailConfirmed"); b.Property<bool>("IsLockoutEnabled"); b.Property<bool>("IsPhoneNumberConfirmed"); b.Property<bool>("IsTwoFactorEnabled"); b.Property<DateTime?>("LastLoginTime"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<DateTime?>("LockoutEndDateUtc"); b.Property<string>("Name") .IsRequired() .HasMaxLength(32); b.Property<string>("NormalizedEmailAddress") .IsRequired() .HasMaxLength(256); b.Property<string>("NormalizedUserName") .IsRequired() .HasMaxLength(32); b.Property<string>("Password") .IsRequired() .HasMaxLength(128); b.Property<string>("PasswordResetCode") .HasMaxLength(328); b.Property<string>("PhoneNumber"); b.Property<string>("SecurityStamp"); b.Property<string>("Surname") .IsRequired() .HasMaxLength(32); b.Property<int?>("TenantId"); b.Property<string>("UserName") .IsRequired() .HasMaxLength(32); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenantId", "NormalizedEmailAddress"); b.HasIndex("TenantId", "NormalizedUserName"); b.ToTable("AbpUsers"); }); modelBuilder.Entity("TityoAttendance.MultiTenancy.Tenant", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConnectionString") .HasMaxLength(1024); b.Property<DateTime>("CreationTime"); b.Property<long?>("CreatorUserId"); b.Property<long?>("DeleterUserId"); b.Property<DateTime?>("DeletionTime"); b.Property<int?>("EditionId"); b.Property<bool>("IsActive"); b.Property<bool>("IsDeleted"); b.Property<DateTime?>("LastModificationTime"); b.Property<long?>("LastModifierUserId"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128); b.Property<string>("TenancyName") .IsRequired() .HasMaxLength(64); b.HasKey("Id"); b.HasIndex("CreatorUserId"); b.HasIndex("DeleterUserId"); b.HasIndex("EditionId"); b.HasIndex("LastModifierUserId"); b.HasIndex("TenancyName"); b.ToTable("AbpTenants"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.Property<int>("EditionId"); b.HasIndex("EditionId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("EditionFeatureSetting"); }); modelBuilder.Entity("Abp.MultiTenancy.TenantFeatureSetting", b => { b.HasBaseType("Abp.Application.Features.FeatureSetting"); b.HasIndex("TenantId", "Name"); b.ToTable("AbpFeatures"); b.HasDiscriminator().HasValue("TenantFeatureSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<int>("RoleId"); b.HasIndex("RoleId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("RolePermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasBaseType("Abp.Authorization.PermissionSetting"); b.Property<long>("UserId"); b.HasIndex("UserId"); b.ToTable("AbpPermissions"); b.HasDiscriminator().HasValue("UserPermissionSetting"); }); modelBuilder.Entity("Abp.Authorization.Roles.RoleClaim", b => { b.HasOne("TityoAttendance.Authorization.Roles.Role") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserClaim", b => { b.HasOne("TityoAttendance.Authorization.Users.User") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserLogin", b => { b.HasOne("TityoAttendance.Authorization.Users.User") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserRole", b => { b.HasOne("TityoAttendance.Authorization.Users.User") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserToken", b => { b.HasOne("TityoAttendance.Authorization.Users.User") .WithMany("Tokens") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Configuration.Setting", b => { b.HasOne("TityoAttendance.Authorization.Users.User") .WithMany("Settings") .HasForeignKey("UserId"); }); modelBuilder.Entity("Abp.EntityHistory.EntityChange", b => { b.HasOne("Abp.EntityHistory.EntityChangeSet") .WithMany("EntityChanges") .HasForeignKey("EntityChangeSetId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.EntityHistory.EntityPropertyChange", b => { b.HasOne("Abp.EntityHistory.EntityChange") .WithMany("PropertyChanges") .HasForeignKey("EntityChangeId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Organizations.OrganizationUnit", b => { b.HasOne("Abp.Organizations.OrganizationUnit", "Parent") .WithMany("Children") .HasForeignKey("ParentId"); }); modelBuilder.Entity("TityoAttendance.Authorization.Roles.Role", b => { b.HasOne("TityoAttendance.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("TityoAttendance.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("TityoAttendance.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("TityoAttendance.Authorization.Users.User", b => { b.HasOne("TityoAttendance.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("TityoAttendance.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("TityoAttendance.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("TityoAttendance.MultiTenancy.Tenant", b => { b.HasOne("TityoAttendance.Authorization.Users.User", "CreatorUser") .WithMany() .HasForeignKey("CreatorUserId"); b.HasOne("TityoAttendance.Authorization.Users.User", "DeleterUser") .WithMany() .HasForeignKey("DeleterUserId"); b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId"); b.HasOne("TityoAttendance.Authorization.Users.User", "LastModifierUser") .WithMany() .HasForeignKey("LastModifierUserId"); }); modelBuilder.Entity("Abp.Application.Features.EditionFeatureSetting", b => { b.HasOne("Abp.Application.Editions.Edition", "Edition") .WithMany() .HasForeignKey("EditionId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Roles.RolePermissionSetting", b => { b.HasOne("TityoAttendance.Authorization.Roles.Role") .WithMany("Permissions") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Abp.Authorization.Users.UserPermissionSetting", b => { b.HasOne("TityoAttendance.Authorization.Users.User") .WithMany("Permissions") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
31.92133
117
0.445108
[ "MIT" ]
BTityo/TityoAttendance
src/TityoAttendance.EntityFrameworkCore/Migrations/20180201051646_Upgraded_To_Abp_v3.4.0.Designer.cs
39,361
C#
using System; namespace Shapes.Shapes { public sealed class Side { public string Name { get; } public int MinSize { get; set; } public int MaxSize { get; set; } public int Size { get; private set; } public Side(string name, int minSize, int maxSize) { Name = name; MinSize = minSize; MaxSize = maxSize; } public void Load() { #pragma warning disable IDE0018 // Inline variable declaration int size; #pragma warning restore IDE0018 // Inline variable declaration do { Console.Write($"Zadej velikost strany {Name} <{MinSize}-{MaxSize}>: "); } while (!int.TryParse(Console.ReadLine(), out size) || size < MinSize || size > MaxSize); Size = size; } } }
25.352941
102
0.535963
[ "MIT" ]
bramborman/Area42
C#/Homeworks/Shapes/Shapes/Shapes/Side.cs
864
C#
using System; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Text; using System.Threading.Tasks; using FeedReader.Model; using FeedReader.Repository; using Moq; using NUnit.Framework; namespace FeedReader.UnitTests { [TestFixture] class DataRepositoryTests { private DataRepository repoUnderTest; private Mock<IDB> mockContext; private Mock<DbSet<Feed>> mockFeedSet; private Mock<DbSet<FeedItem>> mockFeedItemSet; private Feed singleFeed; [SetUp] public void SetUp() { mockContext = new Mock<IDB>(); mockFeedSet = new Mock<DbSet<Feed>>(); mockFeedItemSet = new Mock<DbSet<FeedItem>>(); mockContext.Setup(m => m.Feeds).Returns(mockFeedSet.Object); mockContext.Setup(m => m.FeedItems).Returns(mockFeedItemSet.Object); // Do nothing for call to Include. mockFeedItemSet.Setup(m => m.Include(It.IsAny<string>())).Returns(mockFeedItemSet.Object); singleFeed = new Feed { ID = 42, Url = "http://www.something.com", Title = "Something" }; repoUnderTest = new DataRepository(mockContext.Object); } [Test] public void Constructor_NullInput_Throws() { Assert.Throws<ArgumentNullException>(() => new DataRepository(null)); } [TestCase("AddFeed")] [TestCase("ModifyFeed")] [TestCase("DeleteFeed")] [TestCase("FeedExists")] public void Various_NullInput_Throws(string methodName) { var mi = typeof(DataRepository).GetMethod(methodName); try { mi.Invoke(repoUnderTest, new object[] { null }); } catch (System.Reflection.TargetInvocationException ex) { Assert.IsInstanceOf<ArgumentNullException>(ex.InnerException); return; } Assert.Fail($"{methodName} did not throw on null input."); } [Test] public void AddFeed_RaisesFeedAddedEvent() { bool eventRaised = false; Feed eventArgFeed = null; repoUnderTest.FeedAdded += (object sender, FeedAddedEventArgs e) => { eventRaised = true; eventArgFeed = e.AddedFeed; }; repoUnderTest.AddFeed(singleFeed); Assert.IsTrue(eventRaised, "FeedAdded event not raised."); Assert.AreEqual(singleFeed, eventArgFeed, "Wrong Feed attached to FeedAdded event."); } [Test] public void ModifyFeed_RaisesFeedModifiedEvent() { mockContext.Setup(m => m.GetEntityState(It.IsAny<Feed>())).Returns(EntityState.Modified); bool eventRaised = false; Feed eventArgFeed = null; repoUnderTest.FeedModified += (object sender, FeedModifiedEventArgs e) => { eventRaised = true; eventArgFeed = e.ModifiedFeed; }; repoUnderTest.ModifyFeed(singleFeed); Assert.IsTrue(eventRaised, "FeedModified event not raised."); Assert.AreEqual(singleFeed, eventArgFeed, "Wrong Feed attached to FeedModified event."); } [Test] public void DeleteFeed_RaisesFeedDeletedEvent() { bool eventRaised = false; Feed eventArgFeed = null; repoUnderTest.FeedDeleted += (object sender, FeedDeletedEventArgs e) => { eventRaised = true; eventArgFeed = e.DeletedFeed; }; repoUnderTest.DeleteFeed(singleFeed); Assert.IsTrue(eventRaised, "FeedDeleted event not raised."); Assert.AreEqual(singleFeed, eventArgFeed, "Wrong Feed attached to FeedDeleted event."); } } }
31.515873
102
0.591539
[ "MIT" ]
joseph-iussa/feed-reader
FeedReader.UnitTests/DataRepositoryTests.cs
3,973
C#
// // Copyright (c) Microsoft and contributors. 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. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Linq; using Microsoft.Azure; namespace Microsoft.Azure.Management.ApiManagement.SmapiModels { /// <summary> /// Generate SSO Url operations response details. /// </summary> public partial class GenerateSsoUrlResponse : AzureOperationResponse { private string _value; /// <summary> /// Optional. Gets or sets SSO URL value. /// </summary> public string Value { get { return this._value; } set { this._value = value; } } /// <summary> /// Initializes a new instance of the GenerateSsoUrlResponse class. /// </summary> public GenerateSsoUrlResponse() { } } }
29.653846
76
0.653696
[ "Apache-2.0" ]
CerebralMischief/azure-sdk-for-net
src/ResourceManagement/ApiManagement/ApiManagementManagement/Generated/SmapiModels/GenerateSsoUrlResponse.cs
1,542
C#
// Copyright (c) 2012-2021 VLINGO LABS. All rights reserved. // // This Source Code Form is subject to the terms of the // Mozilla Public License, v. 2.0. If a copy of the MPL // was not distributed with this file, You can obtain // one at https://mozilla.org/MPL/2.0/. using System; using Vlingo.Xoom.Actors.TestKit; using Vlingo.Xoom.Common; using Xunit; namespace Vlingo.Xoom.Actors.Tests { public class SchedulerTest : ActorsTest { private readonly IScheduled<CounterHolder> _scheduled; private readonly Scheduler _scheduler; public SchedulerTest() { _scheduled = new Scheduled(); _scheduler = new Scheduler(); } public override void Dispose() { _scheduler.Close(); base.Dispose(); } [Fact] public void TestScheduleOnceOneHappyDelivery() { var holder = new CounterHolder(1); _scheduler.ScheduleOnce(_scheduled, holder, TimeSpan.Zero, TimeSpan.FromMilliseconds(1)); Assert.Equal(1, holder.GetCounter()); } [Fact] public void TestScheduleManyHappyDelivery() { var holder = new CounterHolder(505); _scheduler.Schedule(_scheduled, holder, TimeSpan.Zero, TimeSpan.FromMilliseconds(1)); Assert.True(holder.GetCounter() > 500); } [Fact] public void TestThatManyScheduleOnceDeliver() { var query = World.ActorFor<IFinalCountQuery>(typeof(OnceScheduled), 10); var count = query.QueryCount().Await<int>(); Assert.Equal(10, count); } private class Scheduled : IScheduled<CounterHolder> { public void IntervalSignal(IScheduled<CounterHolder> scheduled, CounterHolder data) { data.Increment(); } } // TODO: This implementation is wrong, and needs to be changed. private class OnceScheduled : Actor, IFinalCountQuery, IScheduled<int> { private ICompletesEventually _completesEventually; private int _count; private readonly int _maximum; private readonly IScheduled<int> _scheduled; public OnceScheduled(int maximum) { _maximum = maximum; _count = 0; _scheduled = SelfAs<IScheduled<int>>(); } public ICompletes<int> QueryCount() { _completesEventually = CompletesEventually(); return (ICompletes<int>)Completes(); } public void IntervalSignal(IScheduled<int> scheduled, int data) { if (_count < _maximum) { Schedule(); } else { _completesEventually.With(_count); SelfAs<IStoppable>().Stop(); } } public override void Start() { Schedule(); } private void Schedule() { ++_count; Scheduler.ScheduleOnce(_scheduled, _count, TimeSpan.FromMilliseconds(500), TimeSpan.FromMilliseconds(1)); } } private class CounterHolder { private readonly AccessSafely _safely; public CounterHolder(int times) { var counter = new AtomicInteger(0); _safely = AccessSafely .AfterCompleting(times) .WritingWith<int>("counter", _ => counter.IncrementAndGet()) .ReadingWith("counter", counter.Get); } public void Increment() => _safely.WriteUsing("counter", 1); public int GetCounter() => _safely.ReadFrom<int>("counter"); } } public interface IFinalCountQuery { ICompletes<int> QueryCount(); } }
28.871429
121
0.544532
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Luteceo/vlingo-net-actors
src/Vlingo.Xoom.Actors.Tests/SchedulerTest.cs
4,044
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Hosting; namespace GDSHelpers.TestSite { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
26.3
70
0.581749
[ "MIT" ]
CQCDigital/GdsHelpers
GDSHelpers.TestSite/Program.cs
528
C#
using EllieMae.Encompass.BusinessObjects; namespace EncompassBrowserTab.Objects.Interface { public interface ICommitted { void Committed(object sender, PersistentObjectEventHandler e); } }
21.1
70
0.758294
[ "MIT" ]
algohubhq/EncompassBrowserTab
EncompassBrowserTab/Objects/Interface/ICommitted.cs
213
C#
using System; using System.Collections; using NUnit.Framework; using System.Collections.Generic; using System.IO; using System.Text.RegularExpressions; #if UNITY_EDITOR using UnityEditor.AddressableAssets.Settings; #endif using UnityEngine.AddressableAssets.Initialization; using UnityEngine.ResourceManagement.ResourceLocations; using UnityEngine.TestTools; namespace UnityEngine.AddressableAssets.ResourceProviders.Tests { [TestFixture] public class ContentCatalogProviderTests : AddressablesTestFixture { const string k_LocationName = "TestLocation"; const string k_LocationId = "TestLocationID"; const string k_CacheLocationId = "CacheLocationID"; const string k_RemoteLocationId = "RemoteLocationID"; private const string k_TempAssetFolder = "Assets/TempFolder"; private const string k_TempBuildFolder = "TempBuildFolder"; private readonly string m_RuntimeCatalogFilename; public ContentCatalogProviderTests() { m_RuntimeCatalogFilename = "catalog" + m_UniqueTestName + ".bundle"; } ResourceLocationBase m_SimpleLocation = new ResourceLocationBase(k_LocationName, k_LocationId, typeof(ContentCatalogProvider).FullName, typeof(object)); protected override TestBuildScriptMode BuildScriptMode => TestBuildScriptMode.Packed; #if UNITY_EDITOR internal override void Setup(AddressableAssetSettings settings, string tempAssetFolder) { settings.BundleLocalCatalog = true; } #endif [Test] public void DetermineIdToLoad_IfLocalCatalogsOnly_ReturnsMainId() { var contentCatalogOp = new ContentCatalogProvider.InternalOp(); IResourceLocation[] dependencies = new IResourceLocation[(int)ContentCatalogProvider.DependencyHashIndex.Count]; dependencies[(int)ContentCatalogProvider.DependencyHashIndex.Remote] = new ResourceLocationBase(string.Empty, k_RemoteLocationId, typeof(ContentCatalogProvider).FullName, typeof(object)); dependencies[(int)ContentCatalogProvider.DependencyHashIndex.Cache] = new ResourceLocationBase(string.Empty, k_CacheLocationId, typeof(ContentCatalogProvider).FullName, typeof(object)); var location = new ResourceLocationBase(k_LocationName, k_LocationId, typeof(ContentCatalogProvider).FullName, typeof(object), dependencies); var loadedId = contentCatalogOp.DetermineIdToLoad(location, new List<object> { "hash" , string.Empty}, true); Assert.AreEqual(k_LocationId, loadedId); } [Test] public void DetermineIdToLoad_IfNoDependencies_ReturnsMainId() { var contentCatalogOp = new ContentCatalogProvider.InternalOp(); var loadedId = contentCatalogOp.DetermineIdToLoad(m_SimpleLocation, null); Assert.AreEqual(k_LocationId, loadedId); } [Test] public void DetermineIdToLoad_IfTooFewDependencies_ReturnsMainId() { var contentCatalogOp = new ContentCatalogProvider.InternalOp(); var loadedId = contentCatalogOp.DetermineIdToLoad(m_SimpleLocation, new List<object>{1}); Assert.AreEqual(k_LocationId, loadedId); } [Test] public void DetermineIdToLoad_IfTooManyDependencies_ReturnsMainId() { var contentCatalogOp = new ContentCatalogProvider.InternalOp(); var loadedId = contentCatalogOp.DetermineIdToLoad(m_SimpleLocation, new List<object>{1,2,3}); Assert.AreEqual(k_LocationId, loadedId); } [Test] public void DetermineIdToLoad_IfOfflineAndNoCache_ReturnsMainId() { var contentCatalogOp = new ContentCatalogProvider.InternalOp(); var loadedId = contentCatalogOp.DetermineIdToLoad(m_SimpleLocation, new List<object>{string.Empty, string.Empty}); Assert.AreEqual(k_LocationId, loadedId); } [Test] public void DetermineIdToLoad_IfOfflineAndHasCache_ReturnsCacheId() { var contentCatalogOp = new ContentCatalogProvider.InternalOp(); IResourceLocation[] dependencies = new IResourceLocation[(int)ContentCatalogProvider.DependencyHashIndex.Count]; dependencies[(int)ContentCatalogProvider.DependencyHashIndex.Remote] = new ResourceLocationBase(string.Empty, k_RemoteLocationId, typeof(ContentCatalogProvider).FullName, typeof(object)); dependencies[(int)ContentCatalogProvider.DependencyHashIndex.Cache] = new ResourceLocationBase(string.Empty, k_CacheLocationId, typeof(ContentCatalogProvider).FullName, typeof(object)); var location = new ResourceLocationBase(k_LocationName, k_LocationId, typeof(ContentCatalogProvider).FullName, typeof(object), dependencies); var loadedId = contentCatalogOp.DetermineIdToLoad(location, new List<object>{string.Empty, "hash"}); Assert.AreEqual(k_CacheLocationId, loadedId); } [Test] public void DetermineIdToLoad_IfOnlineMatchesCache_ReturnsCacheId() { var contentCatalogOp = new ContentCatalogProvider.InternalOp(); IResourceLocation[] dependencies = new IResourceLocation[(int)ContentCatalogProvider.DependencyHashIndex.Count]; dependencies[(int)ContentCatalogProvider.DependencyHashIndex.Remote] = new ResourceLocationBase(string.Empty, k_RemoteLocationId, typeof(ContentCatalogProvider).FullName, typeof(object)); dependencies[(int)ContentCatalogProvider.DependencyHashIndex.Cache] = new ResourceLocationBase(string.Empty, k_CacheLocationId, typeof(ContentCatalogProvider).FullName, typeof(object)); var location = new ResourceLocationBase(k_LocationName, k_LocationId, typeof(ContentCatalogProvider).FullName, typeof(object), dependencies); var loadedId = contentCatalogOp.DetermineIdToLoad(location, new List<object>{"hash", "hash"}); Assert.AreEqual(k_CacheLocationId, loadedId); } [Test] public void DetermineIdToLoad_IfOnlineMismatchesCache_ReturnsRemoteId() { var contentCatalogOp = new ContentCatalogProvider.InternalOp(); IResourceLocation[] dependencies = new IResourceLocation[(int)ContentCatalogProvider.DependencyHashIndex.Count]; dependencies[(int)ContentCatalogProvider.DependencyHashIndex.Remote] = new ResourceLocationBase(string.Empty, k_RemoteLocationId, typeof(ContentCatalogProvider).FullName, typeof(object)); dependencies[(int)ContentCatalogProvider.DependencyHashIndex.Cache] = new ResourceLocationBase(string.Empty, k_CacheLocationId, typeof(ContentCatalogProvider).FullName, typeof(object)); var location = new ResourceLocationBase(k_LocationName, k_LocationId, typeof(ContentCatalogProvider).FullName, typeof(object), dependencies); var loadedId = contentCatalogOp.DetermineIdToLoad(location, new List<object>{"newHash", "hash"}); Assert.AreEqual(k_RemoteLocationId, loadedId); loadedId = contentCatalogOp.DetermineIdToLoad(location, new List<object>{"newHash", string.Empty}); Assert.AreEqual(k_RemoteLocationId, loadedId); } [Test] [TestCase(null, typeof(ArgumentNullException))] [TestCase("invalid", typeof(ArgumentException))] [TestCase("file.txt", typeof(ArgumentException))] public void BundledCatalog_LoadCatalogFromBundle_InvalidBundlePath_ShouldThrow(string path, Type exceptionType) { Assert.Throws(exceptionType, () => new ContentCatalogProvider.InternalOp.BundledCatalog(path)); } [UnityTest] public IEnumerator BundledCatalog_LoadCatalogFromBundle_InvalidBundleFileFormat_ShouldFail() { var bundleFilePath = Path.Combine(k_TempBuildFolder, "catalog.bundle"); Directory.CreateDirectory(Path.GetDirectoryName(bundleFilePath)); var bytes = new byte[] { 1, 2, 3, 4, 5, 6 }; File.WriteAllBytes(bundleFilePath, bytes); var bundledCatalog = new ContentCatalogProvider.InternalOp.BundledCatalog(bundleFilePath); bundledCatalog.LoadCatalogFromBundleAsync(); yield return new WaitWhile(() => bundledCatalog.OpInProgress); #if UNITY_2020_1_OR_NEWER LogAssert.Expect(LogType.Error, new Regex("Failed to read data for", RegexOptions.IgnoreCase)); #endif LogAssert.Expect(LogType.Error, new Regex("Unable to load", RegexOptions.IgnoreCase)); Assert.IsFalse(bundledCatalog.OpIsSuccess); if (Directory.Exists(k_TempBuildFolder)) Directory.Delete(k_TempBuildFolder, true); } [UnityTest] public IEnumerator BundledCatalog_LoadCatalogFromBundle_ShouldLoadCatalogAndUnloadResources() { var bundleFilePath = Path.Combine(Addressables.RuntimePath, m_RuntimeCatalogFilename); var bundledCatalog = new ContentCatalogProvider.InternalOp.BundledCatalog(bundleFilePath); bundledCatalog.LoadCatalogFromBundleAsync(); bundledCatalog.OnLoaded += catalogData => { Assert.NotNull(catalogData); Assert.AreEqual(ResourceManagerRuntimeData.kCatalogAddress, catalogData.ProviderId); }; yield return new WaitWhile(() => bundledCatalog.OpInProgress); Assert.IsTrue(bundledCatalog.OpIsSuccess); Assert.Null(bundledCatalog.m_CatalogAssetBundle); } [UnityTest] public IEnumerator BundledCatalog_LoadCatalogFromBundle_WhenCalledMultipleTimes_OpNotCompleted_FirstShouldSucceedAndOthersShouldFail() { var bundleFilePath = Path.Combine(Addressables.RuntimePath, m_RuntimeCatalogFilename); var timesCalled = 0; var bundledCatalog = new ContentCatalogProvider.InternalOp.BundledCatalog(bundleFilePath); bundledCatalog.OnLoaded += catalogData => { Assert.NotNull(catalogData); Assert.AreEqual(ResourceManagerRuntimeData.kCatalogAddress, catalogData.ProviderId); timesCalled++; }; bundledCatalog.LoadCatalogFromBundleAsync(); bundledCatalog.LoadCatalogFromBundleAsync(); LogAssert.Expect(LogType.Error, new Regex("progress", RegexOptions.IgnoreCase)); yield return new WaitWhile(() => bundledCatalog.OpInProgress); Assert.AreEqual(1, timesCalled); } [UnityTest] public IEnumerator BundledCatalog_LoadCatalogFromBundle_WhenCalledMultipleTimes_OpCompleted_AllShouldSucceed() { var bundleFilePath = Path.Combine(Addressables.RuntimePath, m_RuntimeCatalogFilename); var timesCalled = 0; var bundledCatalog = new ContentCatalogProvider.InternalOp.BundledCatalog(bundleFilePath); bundledCatalog.OnLoaded += catalogData => { Assert.NotNull(catalogData); Assert.AreEqual(ResourceManagerRuntimeData.kCatalogAddress, catalogData.ProviderId); timesCalled++; }; bundledCatalog.LoadCatalogFromBundleAsync(); yield return new WaitWhile(() => bundledCatalog.OpInProgress); bundledCatalog.LoadCatalogFromBundleAsync(); yield return new WaitWhile(() => bundledCatalog.OpInProgress); Assert.AreEqual(2, timesCalled); Assert.IsTrue(bundledCatalog.OpIsSuccess); } } }
44.752
197
0.736682
[ "MIT" ]
Wuduanyi/SkillSystemDemo
Assets/Scripts/addressables/Tests/Runtime/ResourceProviders/ContentCatalogProviderTests.cs
11,188
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 Radio.Properties { /// <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()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Radio.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
39.416667
172
0.586328
[ "MIT" ]
Yaaappee/Radio
Radio/Radio/Properties/Resources.Designer.cs
2,840
C#
[RequiredByNativeCodeAttribute] // RVA: 0xC6B30 Offset: 0xC6C31 VA: 0xC6B30 [NativeClassAttribute] // RVA: 0xC6B30 Offset: 0xC6C31 VA: 0xC6B30 [NativeHeaderAttribute] // RVA: 0xC6B30 Offset: 0xC6C31 VA: 0xC6B30 [NativeHeaderAttribute] // RVA: 0xC6B30 Offset: 0xC6C31 VA: 0xC6B30 public struct LayerMask // TypeDefIndex: 3015 { // Fields [NativeNameAttribute] // RVA: 0xCA870 Offset: 0xCA971 VA: 0xCA870 private int m_Mask; // 0x0 // Properties public int value { get; set; } // Methods // RVA: 0x1A2CC80 Offset: 0x1A2CD81 VA: 0x1A2CC80 public static int op_Implicit(LayerMask mask) { } // RVA: 0x1A2CC90 Offset: 0x1A2CD91 VA: 0x1A2CC90 public static LayerMask op_Implicit(int intVal) { } // RVA: 0x18490 Offset: 0x18591 VA: 0x18490 public int get_value() { } // RVA: 0x184A0 Offset: 0x185A1 VA: 0x184A0 public void set_value(int value) { } [NativeMethodAttribute] // RVA: 0xD6BA0 Offset: 0xD6CA1 VA: 0xD6BA0 [StaticAccessorAttribute] // RVA: 0xD6BA0 Offset: 0xD6CA1 VA: 0xD6BA0 // RVA: 0x1A2CCC0 Offset: 0x1A2CDC1 VA: 0x1A2CCC0 public static string LayerToName(int layer) { } [NativeMethodAttribute] // RVA: 0xD6C10 Offset: 0xD6D11 VA: 0xD6C10 [StaticAccessorAttribute] // RVA: 0xD6C10 Offset: 0xD6D11 VA: 0xD6C10 // RVA: 0x1A2CD10 Offset: 0x1A2CE11 VA: 0x1A2CD10 public static int NameToLayer(string layerName) { } // RVA: 0x1A2CD60 Offset: 0x1A2CE61 VA: 0x1A2CD60 public static int GetMask(string[] layerNames) { } }
34.595238
75
0.74329
[ "MIT" ]
SinsofSloth/RF5-global-metadata
UnityEngine/LayerMask.cs
1,453
C#
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon 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. // namespace Core.Arango.Relinq.Clauses { /// <summary> /// Represents a clause in a <see cref="QueryModel" />'s <see cref="QueryModel.BodyClauses" /> collection. Body clauses /// take the items generated by /// the <see cref="QueryModel.MainFromClause" />, filtering (<see cref="WhereClause" />), ordering ( /// <see cref="OrderByClause" />), augmenting /// (<see cref="AdditionalFromClause" />), or otherwise processing them before they are passed to the /// <see cref="QueryModel.SelectClause" />. /// </summary> internal interface IBodyClause : IClause { /// <summary> /// Accepts the specified visitor by calling one of its Visit... methods. /// </summary> /// <param name="visitor">The visitor to accept.</param> /// <param name="queryModel">The query model in whose context this clause is visited.</param> /// <param name="index"> /// The index of this clause in the <paramref name="queryModel" />'s /// <see cref="QueryModel.BodyClauses" /> collection. /// </param> void Accept(IQueryModelVisitor visitor, QueryModel queryModel, int index); /// <summary> /// Clones this clause, registering its clone with the <paramref name="cloneContext" /> if it is a query source clause. /// </summary> /// <param name="cloneContext">The clones of all query source clauses are registered with this <see cref="CloneContext" />.</param> /// <returns>A clone of this clause.</returns> IBodyClause Clone(CloneContext cloneContext); } }
49.8125
139
0.659138
[ "Apache-2.0" ]
ASolomatin/dotnet-arangodb
Core.Arango/Relinq/Clauses/IBodyClause.cs
2,391
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Altinn.Platform.Storage.Configuration; using Altinn.Platform.Storage.Interface.Models; using Azure; using Azure.Storage; using Azure.Storage.Blobs; using Azure.Storage.Blobs.Models; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Linq; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Newtonsoft.Json; namespace Altinn.Platform.Storage.Repository { /// <summary> /// Represents an implementation of <see cref="IDataRepository"/> using Azure CosmosDB to keep metadata /// and Azure Blob storage to keep the actual data. Blob storage is again split based on application owner. /// </summary> public class DataRepository : IDataRepository { private readonly Uri _collectionUri; private readonly string _databaseId; private readonly string _collectionId = "dataElements"; private readonly string _partitionKey = "/instanceGuid"; private readonly DocumentClient _documentClient; private readonly AzureStorageConfiguration _storageConfiguration; private readonly ISasTokenProvider _sasTokenProvider; private readonly ILogger<DataRepository> _logger; /// <summary> /// Initializes a new instance of the <see cref="DataRepository"/> class /// </summary> /// <param name="sasTokenProvider">A provider that can be asked for SAS tokens.</param> /// <param name="cosmosSettings">the configuration settings for azure cosmos database</param> /// <param name="storageConfiguration">the storage configuration for azure blob storage</param> /// <param name="logger">The logger to use when writing to logs.</param> public DataRepository( ISasTokenProvider sasTokenProvider, IOptions<AzureCosmosSettings> cosmosSettings, IOptions<AzureStorageConfiguration> storageConfiguration, ILogger<DataRepository> logger) { _storageConfiguration = storageConfiguration.Value; _sasTokenProvider = sasTokenProvider; _logger = logger; CosmosDatabaseHandler database = new CosmosDatabaseHandler(cosmosSettings.Value); _documentClient = database.CreateDatabaseAndCollection(_collectionId); _collectionUri = database.CollectionUri; Uri databaseUri = database.DatabaseUri; _databaseId = database.DatabaseName; DocumentCollection documentCollection = database.CreateDocumentCollection(_collectionId, _partitionKey); _documentClient.CreateDocumentCollectionIfNotExistsAsync( databaseUri, documentCollection).GetAwaiter().GetResult(); _documentClient.OpenAsync(); } /// <inheritdoc/> public async Task<long> WriteDataToStorage(string org, Stream stream, string blobStoragePath) { try { return await UploadFromStreamAsync(org, stream, blobStoragePath); } catch (RequestFailedException requestFailedException) { switch (requestFailedException.ErrorCode) { case "AuthenticationFailed": _logger.LogWarning("Authentication failed. Invalidating SAS token."); _sasTokenProvider.InvalidateSasToken(org); // No use retrying upload as the original stream can't be reset back to start. throw; default: throw; } } } /// <inheritdoc/> public async Task<Stream> ReadDataFromStorage(string org, string blobStoragePath) { try { return await DownloadToStreamAsync(org, blobStoragePath); } catch (RequestFailedException requestFailedException) { switch (requestFailedException.ErrorCode) { case "AuthenticationFailed": _logger.LogWarning("Authentication failed. Invalidating SAS token and retrying download operation."); _sasTokenProvider.InvalidateSasToken(org); return await DownloadToStreamAsync(org, blobStoragePath); case "InvalidRange": _logger.LogWarning($"Found possibly empty blob in storage for {org}: {blobStoragePath}"); return new MemoryStream(); default: throw; } } } /// <inheritdoc/> public async Task<bool> DeleteDataInStorage(string org, string blobStoragePath) { try { return await DeleteIfExistsAsync(org, blobStoragePath); } catch (RequestFailedException requestFailedException) { switch (requestFailedException.ErrorCode) { case "AuthenticationFailed": _logger.LogWarning("Authentication failed. Invalidating SAS token and retrying delete operation."); _sasTokenProvider.InvalidateSasToken(org); return await DeleteIfExistsAsync(org, blobStoragePath); default: throw; } } } /// <inheritdoc/> public async Task<List<DataElement>> ReadAll(Guid instanceGuid) { string instanceKey = instanceGuid.ToString(); FeedOptions feedOptions = new FeedOptions { PartitionKey = new PartitionKey(instanceKey), MaxItemCount = 10000, }; IQueryable<DataElement> filter = _documentClient .CreateDocumentQuery<DataElement>(_collectionUri, feedOptions) .Where(d => d.InstanceGuid == instanceKey); IDocumentQuery<DataElement> query = filter.AsDocumentQuery(); FeedResponse<DataElement> feedResponse = await query.ExecuteNextAsync<DataElement>(); List<DataElement> instances = feedResponse.ToList(); return instances; } /// <inheritdoc/> public async Task<DataElement> Create(DataElement dataElement) { ResourceResponse<Document> createDocumentResponse = await _documentClient.CreateDocumentAsync(_collectionUri, dataElement); Document document = createDocumentResponse.Resource; DataElement dataElementStored = JsonConvert.DeserializeObject<DataElement>(document.ToString()); return dataElementStored; } /// <inheritdoc/> public async Task<DataElement> Read(Guid instanceGuid, Guid dataElementGuid) { string instanceKey = instanceGuid.ToString(); string dataElementKey = dataElementGuid.ToString(); Uri uri = UriFactory.CreateDocumentUri(_databaseId, _collectionId, dataElementKey); DataElement dataElement = await _documentClient .ReadDocumentAsync<DataElement>( uri, new RequestOptions { PartitionKey = new PartitionKey(instanceKey) }); return dataElement; } /// <inheritdoc/> public async Task<DataElement> Update(DataElement dataElement) { ResourceResponse<Document> createDocumentResponse = await _documentClient .ReplaceDocumentAsync(UriFactory.CreateDocumentUri(_databaseId, _collectionId, dataElement.Id), dataElement); Document document = createDocumentResponse.Resource; DataElement updatedElement = JsonConvert.DeserializeObject<DataElement>(document.ToString()); return updatedElement; } /// <inheritdoc/> public async Task<bool> Delete(DataElement dataElement) { Uri uri = UriFactory.CreateDocumentUri(_databaseId, _collectionId, dataElement.Id); await _documentClient.DeleteDocumentAsync( uri.ToString(), new RequestOptions { PartitionKey = new PartitionKey(dataElement.InstanceGuid) }); return true; } private async Task<long> UploadFromStreamAsync(string org, Stream stream, string fileName) { BlobClient blockBlob = await CreateBlobClient(org, fileName); await blockBlob.UploadAsync(stream, true); BlobProperties properties = await blockBlob.GetPropertiesAsync(); return properties.ContentLength; } private async Task<Stream> DownloadToStreamAsync(string org, string fileName) { BlobClient blockBlob = await CreateBlobClient(org, fileName); var memoryStream = new MemoryStream(); await blockBlob.DownloadToAsync(memoryStream); memoryStream.Position = 0; return memoryStream; } private async Task<bool> DeleteIfExistsAsync(string org, string fileName) { BlobClient blockBlob = await CreateBlobClient(org, fileName); bool result = await blockBlob.DeleteIfExistsAsync(); return result; } private async Task<BlobClient> CreateBlobClient(string org, string blobName) { if (!_storageConfiguration.AccountName.StartsWith("devstoreaccount1")) { string sasToken = await _sasTokenProvider.GetSasToken(org); string accountName = string.Format(_storageConfiguration.OrgStorageAccount, org); string containerName = string.Format(_storageConfiguration.OrgStorageContainer, org); UriBuilder fullUri = new UriBuilder { Scheme = "https", Host = $"{accountName}.blob.core.windows.net", Path = $"{containerName}/{blobName}", Query = sasToken }; return new BlobClient(fullUri.Uri); } StorageSharedKeyCredential storageCredentials = new StorageSharedKeyCredential(_storageConfiguration.AccountName, _storageConfiguration.AccountKey); Uri storageUrl = new Uri(_storageConfiguration.BlobEndPoint); BlobServiceClient commonBlobClient = new BlobServiceClient(storageUrl, storageCredentials); BlobContainerClient blobContainerClient = commonBlobClient.GetBlobContainerClient(_storageConfiguration.StorageContainer); return blobContainerClient.GetBlobClient(blobName); } } }
38.825623
160
0.625756
[ "BSD-3-Clause" ]
TheTechArch/altinn-studio
src/Altinn.Platform/Altinn.Platform.Storage/Storage/Repository/DataRepository.cs
10,910
C#
namespace Messerli.FileManipulator.Project.MsBuild { internal static class Constant { public const string PackageReferenceTypeTag = "PackageReference"; public const string VersionMetadataAttribute = "Version"; public const string PrivateAssetsMetadataAttribute = "PrivateAssets"; public const string IncludeAssetsMetadataAttribute = "IncludeAssets"; public const string ExcludeAssetsMetadataAttribute = "ExcludeAssets"; public const char ListSeparator = ';'; } }
43.5
77
0.737548
[ "MIT" ]
messerli-informatik-ag/MetaGenerator
FileManipulator/Project/MsBuild/Constant.cs
522
C#
using System; namespace MyCore.BaseProject.Authentication.External { public class ExternalLoginProviderInfo { public string Name { get; set; } public string ClientId { get; set; } public string ClientSecret { get; set; } public Type ProviderApiType { get; set; } public ExternalLoginProviderInfo(string name, string clientId, string clientSecret, Type providerApiType) { Name = name; ClientId = clientId; ClientSecret = clientSecret; ProviderApiType = providerApiType; } } }
24.875
113
0.626466
[ "MIT" ]
liyahui520/BaseProject
aspnet-core/src/MyCore.BaseProject.Web.Core/Authentication/External/ExternalLoginProviderInfo.cs
599
C#
using EasyBlog.Support.Entities; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; namespace EasyBlog.Common { public class PreSubmissionPostingEventArgs : CancelEventArgs { public PreSubmissionPostingEventArgs(BlogPost blogPost) { BlogPost = blogPost; } public BlogPost BlogPost { get; set; } } }
21.157895
64
0.699005
[ "MIT" ]
mcarcini/EasyBlog
EasyBlog..Common/PreSubmissionPostingEventArgs.cs
402
C#
// Func<string, bool, int> //
7.5
23
0.566667
[ "MIT" ]
HighSchoolHacking/GLS-Draft
test/integration/LambdaTypeInline/two parameters return int.cs
30
C#
namespace SharpProto { [Message] public struct Person { [Field(1)] public string name; [Field(2)] public int id; } [Message] public struct Group { [Field(1)] public string name; [Field(2)] public Person member1; [Field(3)] public Person member2; } }
15.826087
30
0.491758
[ "Apache-2.0" ]
huahualeetcode/SharpProto
SharpProto/TestProto.cs
366
C#
namespace CloudFoundry.UAA { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CloudFoundry.UAA.Authentication; /// <summary> /// Class that represents the current authentication context. /// </summary> public class AuthenticationContext { private bool isLoggedIn = false; /// <summary> /// Gets the token. /// </summary> /// <value> /// The token. /// </value> public Token Token { get; internal set; } /// <summary> /// Gets or sets the URI. /// </summary> /// <value> /// The URI. /// </value> public Uri Uri { get; internal set; } /// <summary> /// Gets a value indicating whether this instance is logged in. /// </summary> /// <value> /// <c>true</c> if this instance is logged in; otherwise, <c>false</c>. /// </value> public bool IsLoggedIn { get { return this.isLoggedIn; } internal set { this.isLoggedIn = value; } } } }
23.622642
79
0.489617
[ "Apache-2.0" ]
adasescu/cf-dotnet-sdk
src/CloudFoundry.UAA.Client/Context.cs
1,254
C#
namespace Ryujinx.HLE.HOS.Kernel.Memory { static class DramMemoryMap { public const ulong DramBase = 0x80000000; public const ulong KernelReserveBase = DramBase + 0x60000; public const ulong SlabHeapBase = KernelReserveBase + 0x85000; public const ulong SlapHeapSize = 0xa21000; public const ulong SlabHeapEnd = SlabHeapBase + SlapHeapSize; public static bool IsHeapPhysicalAddress(ulong address) { return address >= SlabHeapEnd; } } }
29.277778
70
0.667932
[ "MIT" ]
2579768776/Ryujinx
Ryujinx.HLE/HOS/Kernel/Memory/DramMemoryMap.cs
527
C#
using System; using System.Threading; using System.Threading.Tasks; using ZptSharp.Config; using ZptSharp.Dom; using ZptSharp.SourceAnnotation; namespace ZptSharp.Rendering { /// <summary> /// Implementation of <see cref="IModifiesDocument"/> which adds source annotation /// to the document DOM where appropriate. Source annotation is a debugging and logging /// aid which helps developers see where each part of the output DOM originates. /// </summary> public class SourceAnnotationDocumentModifierDecorator : IModifiesDocument { readonly IGetsSourceAnnotationContextProcessor contextProcessorFactory; readonly IIterativelyModifiesDocument iterativeModifier; readonly RenderingConfig config; readonly IModifiesDocument wrapped; readonly IGetsRootExpressionContext rootContextProvider; /// <summary> /// Performs alterations for a specified document, using the specified rendering request. /// This method will manipulate the <paramref name="document"/>, according to the rules of ZPT. /// </summary> /// <returns>A task indicating when the process is complete.</returns> /// <param name="document">The document to render.</param> /// <param name="model">The model to render.</param> /// <param name="token">An object used to cancel the operation if required.</param> public async Task ModifyDocumentAsync(IDocument document, object model, CancellationToken token = default) { if (!config.IncludeSourceAnnotation) return; var contextProcessor = contextProcessorFactory.GetSourceAnnotationContextProcessor(); var rootContext = rootContextProvider.GetExpressionContext(document, model); await iterativeModifier.ModifyDocumentAsync(rootContext, contextProcessor, token) .ConfigureAwait(false); await wrapped.ModifyDocumentAsync(document, model, token) .ConfigureAwait(false); } /// <summary> /// Initializes a new instance of the /// <see cref="SourceAnnotationDocumentModifierDecorator"/> class. /// </summary> /// <param name="contextProcessorFactory">Context processor factory.</param> /// <param name="iterativeModifier">Iterative modifier.</param> /// <param name="config">Rendering config.</param> /// <param name="wrapped">Wrapped.</param> /// <param name="rootContextProvider">A provider for the root expression context.</param> public SourceAnnotationDocumentModifierDecorator(IGetsSourceAnnotationContextProcessor contextProcessorFactory, IIterativelyModifiesDocument iterativeModifier, RenderingConfig config, IModifiesDocument wrapped, IGetsRootExpressionContext rootContextProvider) { this.contextProcessorFactory = contextProcessorFactory ?? throw new ArgumentNullException(nameof(contextProcessorFactory)); this.iterativeModifier = iterativeModifier ?? throw new ArgumentNullException(nameof(iterativeModifier)); this.config = config ?? throw new ArgumentNullException(nameof(config)); this.wrapped = wrapped ?? throw new ArgumentNullException(nameof(wrapped)); this.rootContextProvider = rootContextProvider ?? throw new ArgumentNullException(nameof(rootContextProvider)); } } }
54.41791
135
0.66621
[ "MIT" ]
csf-dev/ZPT-Sharp
ZptSharp/Rendering/SourceAnnotationDocumentModifierDecorator.cs
3,646
C#
// <auto-generated /> using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; using masz.data; namespace masz.Migrations { [DbContext(typeof(DataContext))] [Migration("20210220145159_AddMotd")] partial class AddMotd { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "3.1.6") .HasAnnotation("Relational:MaxIdentifierLength", 64); modelBuilder.Entity("masz.Models.AutoModerationConfig", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<int>("AutoModerationAction") .HasColumnType("int"); b.Property<int>("AutoModerationType") .HasColumnType("int"); b.Property<string>("GuildId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("IgnoreChannels") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("IgnoreRoles") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<int?>("Limit") .HasColumnType("int"); b.Property<int?>("PunishmentDurationMinutes") .HasColumnType("int"); b.Property<int?>("PunishmentType") .HasColumnType("int"); b.Property<bool>("SendDmNotification") .HasColumnType("tinyint(1)"); b.Property<bool>("SendPublicNotification") .HasColumnType("tinyint(1)"); b.Property<int?>("TimeLimitMinutes") .HasColumnType("int"); b.HasKey("Id"); b.ToTable("AutoModerationConfigs"); }); modelBuilder.Entity("masz.Models.AutoModerationEvent", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<int?>("AssociatedCaseId") .HasColumnType("int"); b.Property<int>("AutoModerationAction") .HasColumnType("int"); b.Property<int>("AutoModerationType") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime(6)"); b.Property<string>("Discriminator") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("GuildId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("MessageContent") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("MessageId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("Nickname") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("UserId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("Username") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.HasKey("Id"); b.ToTable("AutoModerationEvents"); }); modelBuilder.Entity("masz.Models.CaseTemplate", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("CaseDescription") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("CaseLabels") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<DateTime?>("CasePunishedUntil") .HasColumnType("datetime(6)"); b.Property<string>("CasePunishment") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<int>("CasePunishmentType") .HasColumnType("int"); b.Property<string>("CaseTitle") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime(6)"); b.Property<string>("CreatedForGuildId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("TemplateName") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("UserId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<int>("ViewPermission") .HasColumnType("int"); b.Property<bool>("announceDm") .HasColumnType("tinyint(1)"); b.Property<bool>("handlePunishment") .HasColumnType("tinyint(1)"); b.Property<bool>("sendPublicNotification") .HasColumnType("tinyint(1)"); b.HasKey("Id"); b.ToTable("CaseTemplates"); }); modelBuilder.Entity("masz.Models.GuildConfig", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<string>("AdminRoleId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("GuildId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("ModInternalNotificationWebhook") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<bool>("ModNotificationDM") .HasColumnType("tinyint(1)"); b.Property<string>("ModPublicNotificationWebhook") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("ModRoleId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("MutedRoleId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.HasKey("Id"); b.ToTable("GuildConfigs"); }); modelBuilder.Entity("masz.Models.GuildMotd", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime(6)"); b.Property<string>("GuildId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("Message") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("UserId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.HasKey("Id"); b.ToTable("GuildMotds"); }); modelBuilder.Entity("masz.Models.ModCase", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<int>("CaseId") .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime(6)"); b.Property<int>("CreationType") .HasColumnType("int"); b.Property<string>("Description") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("Discriminator") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("GuildId") .IsRequired() .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("Labels") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<DateTime>("LastEditedAt") .HasColumnType("datetime(6)"); b.Property<string>("LastEditedByModId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("ModId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("Nickname") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<DateTime>("OccuredAt") .HasColumnType("datetime(6)"); b.Property<string>("Others") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<DateTime?>("PunishedUntil") .HasColumnType("datetime(6)"); b.Property<string>("Punishment") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<bool>("PunishmentActive") .HasColumnType("tinyint(1)"); b.Property<int>("PunishmentType") .HasColumnType("int"); b.Property<string>("Title") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("UserId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<string>("Username") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<bool>("Valid") .HasColumnType("tinyint(1)"); b.HasKey("Id"); b.ToTable("ModCases"); }); modelBuilder.Entity("masz.Models.ModCaseComment", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasColumnType("int"); b.Property<DateTime>("CreatedAt") .HasColumnType("datetime(6)"); b.Property<string>("Message") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.Property<int>("ModCaseId") .HasColumnType("int"); b.Property<string>("UserId") .HasColumnType("longtext CHARACTER SET utf8mb4"); b.HasKey("Id"); b.HasIndex("ModCaseId"); b.ToTable("ModCaseComments"); }); modelBuilder.Entity("masz.Models.ModCaseComment", b => { b.HasOne("masz.Models.ModCase", "ModCase") .WithMany("Comments") .HasForeignKey("ModCaseId") .OnDelete(DeleteBehavior.Cascade) .IsRequired(); }); #pragma warning restore 612, 618 } } }
36.493939
75
0.469069
[ "MIT" ]
BSscripter/discord-masz
backend/masz/Migrations/20210220145159_AddMotd.Designer.cs
12,045
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; namespace CorsStudentClient.Account { public partial class VerifyPhoneNumber : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var phonenumber = Request.QueryString["PhoneNumber"]; var code = manager.GenerateChangePhoneNumberToken(User.Identity.GetUserId(), phonenumber); PhoneNumber.Value = phonenumber; } protected void Code_Click(object sender, EventArgs e) { if (!ModelState.IsValid) { ModelState.AddModelError("", "Invalid code"); return; } var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>(); var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>(); var result = manager.ChangePhoneNumber(User.Identity.GetUserId(), PhoneNumber.Value, Code.Text); if (result.Succeeded) { var user = manager.FindById(User.Identity.GetUserId()); if (user != null) { signInManager.SignIn(user, isPersistent: false, rememberBrowser: false); Response.Redirect("/Account/Manage?m=AddPhoneNumberSuccess"); } } // If we got this far, something failed, redisplay form ModelState.AddModelError("", "Failed to verify phone"); } } }
35.44
113
0.615124
[ "MIT" ]
BCIT-ASP/WebAPI-CORS
StudentWebApiCorsLab/CorsStudentClient/Account/VerifyPhoneNumber.aspx.cs
1,774
C#
using System; using System.Globalization; namespace CoreSharp.Extensions { /// <summary> /// <see cref="ulong"/> extensions. /// </summary> public static class UlongExtensions { /// <inheritdoc cref="ToComputerSize(ulong, string, IFormatProvider)"/> public static string ToComputerSize(this ulong byteSize) => byteSize.ToComputerSize("G"); /// <inheritdoc cref="ToComputerSize(ulong, string, IFormatProvider)"/> public static string ToComputerSize(this ulong byteSize, string format) => byteSize.ToComputerSize(format, CultureInfo.CurrentCulture); /// <inheritdoc cref="ToComputerSize(ulong, string, IFormatProvider)"/> public static string ToComputerSize(this ulong byteSize, IFormatProvider formatProvider) => byteSize.ToComputerSize("G", formatProvider); /// <inheritdoc cref="ToComputerSize(ulong, string, IFormatProvider)"/> public static string ToComputerSizeCI(this ulong byteSize) => byteSize.ToComputerSize("0.###", CultureInfo.InvariantCulture); /// <summary> /// Downsizes bytes and adds appropriate prefix. /// </summary> public static string ToComputerSize(this ulong byteSize, string format, IFormatProvider formatProvider) { //Scale down bytes const int thousand = 1024; var thousandCounter = 0; //Integral division var integralLimit = (ulong)Math.Pow(thousand, 2); while (byteSize >= integralLimit) { thousandCounter++; byteSize /= thousand; } //Double division double scaledValue = byteSize; while (scaledValue >= thousand) { thousandCounter++; scaledValue /= thousand; } //Get prefix var prefixes = new[] { "", "K", "M", "G", "T", "P", "E", "Z", "Y" }; var prefix = prefixes[thousandCounter]; return scaledValue.ToString(format, formatProvider) + prefix + "B"; } } }
35.85
111
0.588563
[ "MIT" ]
efthymios-ks/CoreSharp
CoreSharp/Extensions/UlongExtensions.cs
2,153
C#
/* _BEGIN_TEMPLATE_ { "id": "BOTA_231e", "name": [ "孵化", "Incubating" ], "text": [ "<b>亡语:</b>召唤一个{0}。", "<b>Deathrattle:</b> Summon a {0}." ], "CardClass": "NEUTRAL", "type": "ENCHANTMENT", "cost": null, "rarity": null, "set": "BOOMSDAY", "collectible": null, "dbfId": 51490 } _END_TEMPLATE_ */ namespace HREngine.Bots { class Sim_BOTA_231e : SimTemplate { } }
14.821429
39
0.544578
[ "MIT" ]
chi-rei-den/Silverfish
cards/BOOMSDAY/BOTA/Sim_BOTA_231e.cs
435
C#
using System.IO; using CP77.CR2W.Reflection; using FastMember; using static CP77.CR2W.Types.Enums; namespace CP77.CR2W.Types { [REDMeta] public class scnISceneSystem : gameISceneSystem { public scnISceneSystem(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
20.866667
102
0.72524
[ "MIT" ]
Eingin/CP77Tools
CP77.CR2W/Types/cp77/scnISceneSystem.cs
299
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using wolvm; namespace wolSystem.classes { public class wolStreamWriter : wolvm.Void { public new StreamWriter value; public wolStreamWriter() : base() { strtype = "StreamWriter"; } public wolStreamWriter(StreamWriter stream) : this() { value = stream; } public override string ToString() => value.ToString(); } }
19.346154
62
0.602386
[ "Apache-2.0" ]
snaulX/frameworks-wolvm-dotnet
System/SystemFramework/System/classes/wolStreamWriter.cs
505
C#
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using Moq; using Xunit; using Assert = Microsoft.TestCommon.AssertEx; namespace System.Web.Mvc.Test { public class ValidatableObjectAdapterTest { // IValidatableObject support [Fact] public void NonIValidatableObjectInsideMetadataThrows() { // Arrange var context = new ControllerContext(); var validatable = new Mock<IValidatableObject>(); var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => 42, typeof(IValidatableObject)); var validator = new ValidatableObjectAdapter(metadata, context); // Act & Assert Assert.Throws<InvalidOperationException>( () => validator.Validate(null), "The model object inside the metadata claimed to be compatible with System.ComponentModel.DataAnnotations.IValidatableObject, but was actually System.Int32."); } [Fact] public void IValidatableObjectGetsAProperlyPopulatedValidationContext() { // Arrange var context = new ControllerContext(); var validatable = new Mock<IValidatableObject>(); var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => validatable.Object, validatable.Object.GetType()); var validator = new ValidatableObjectAdapter(metadata, context); ValidationContext validationContext = null; validatable.Setup(vo => vo.Validate(It.IsAny<ValidationContext>())) .Callback<ValidationContext>(vc => validationContext = vc) .Returns(Enumerable.Empty<ValidationResult>()) .Verifiable(); // Act validator.Validate(null); // Assert validatable.Verify(); Assert.Same(validatable.Object, validationContext.ObjectInstance); Assert.Null(validationContext.MemberName); } [Fact] public void IValidatableObjectWithNoErrors() { // Arrange var context = new ControllerContext(); var validatable = new Mock<IValidatableObject>(); var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => validatable.Object, validatable.Object.GetType()); var validator = new ValidatableObjectAdapter(metadata, context); validatable.Setup(vo => vo.Validate(It.IsAny<ValidationContext>())) .Returns(Enumerable.Empty<ValidationResult>()); // Act IEnumerable<ModelValidationResult> results = validator.Validate(null); // Assert Assert.Empty(results); } [Fact] public void IValidatableObjectWithModelLevelError() { // Arrange var context = new ControllerContext(); var validatable = new Mock<IValidatableObject>(); var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => validatable.Object, validatable.Object.GetType()); var validator = new ValidatableObjectAdapter(metadata, context); validatable.Setup(vo => vo.Validate(It.IsAny<ValidationContext>())) .Returns(new ValidationResult[] { new ValidationResult("Error Message") }); // Act ModelValidationResult result = validator.Validate(null).Single(); // Assert Assert.Equal("Error Message", result.Message); Assert.Equal(String.Empty, result.MemberName); } [Fact] public void IValidatableObjectWithMultipleModelLevelErrors() { // Arrange var context = new ControllerContext(); var validatable = new Mock<IValidatableObject>(); var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => validatable.Object, validatable.Object.GetType()); var validator = new ValidatableObjectAdapter(metadata, context); validatable.Setup(vo => vo.Validate(It.IsAny<ValidationContext>())) .Returns(new ValidationResult[] { new ValidationResult("Error Message 1"), new ValidationResult("Error Message 2") }); // Act ModelValidationResult[] results = validator.Validate(null).ToArray(); // Assert Assert.Equal(2, results.Length); Assert.Equal("Error Message 1", results[0].Message); Assert.Equal("Error Message 2", results[1].Message); } [Fact] public void IValidatableObjectWithMultiPropertyValidationFailure() { // Arrange var context = new ControllerContext(); var validatable = new Mock<IValidatableObject>(); var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => validatable.Object, validatable.Object.GetType()); var validator = new ValidatableObjectAdapter(metadata, context); validatable.Setup(vo => vo.Validate(It.IsAny<ValidationContext>())) .Returns(new[] { new ValidationResult("Error Message", new[] { "Property1", "Property2" }) }) .Verifiable(); // Act ModelValidationResult[] results = validator.Validate(null).ToArray(); // Assert validatable.Verify(); Assert.Equal(2, results.Length); Assert.Equal("Error Message", results[0].Message); Assert.Equal("Property1", results[0].MemberName); Assert.Equal("Error Message", results[1].Message); Assert.Equal("Property2", results[1].MemberName); } [Fact] public void IValidatableObjectWhichIsNullReturnsNoErrors() { // Arrange var context = new ControllerContext(); var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => null, typeof(IValidatableObject)); var validator = new ValidatableObjectAdapter(metadata, context); // Act IEnumerable<ModelValidationResult> results = validator.Validate(null); // Assert Assert.Empty(results); } [Fact] public void IValidatableObjectWhichReturnsValidationResultSuccessReturnsNoErrors() { // Arrange var context = new ControllerContext(); var validatable = new Mock<IValidatableObject>(); var metadata = ModelMetadataProviders.Current.GetMetadataForType(() => validatable.Object, validatable.Object.GetType()); var validator = new ValidatableObjectAdapter(metadata, context); validatable.Setup(vo => vo.Validate(It.IsAny<ValidationContext>())) .Returns(new[] { ValidationResult.Success }) .Verifiable(); // Act ModelValidationResult[] results = validator.Validate(null).ToArray(); // Assert validatable.Verify(); Assert.Empty(results); } } }
41.578035
175
0.61254
[ "Apache-2.0" ]
douchedetector/mvc-razor
test/System.Web.Mvc.Test/Test/ValidatableObjectAdapterTest.cs
7,195
C#
using BuildingGraph.Client; public class BGNode { internal BGNode() { } internal BGNode(PendingNode pendingNode) { intPendingNode = pendingNode; Name = pendingNode.NodeName; Id = pendingNode.TempId; WasCommited = pendingNode.WasCommited; } public static BGNode FromNameAndId(string name, string id) { return new BGNode(new PendingNode(name, id)); } public static BGNode FromName(string name) { return new BGNode(new PendingNode(name)); } internal PendingNode intPendingNode { get; set; } public string Name { get; internal set; } public string Id { get; internal set; } public bool WasCommited { get; internal set; } }
20.971429
62
0.648501
[ "MIT" ]
menome/BuildingGraph-Client-Revit
BuildingGraph.Integration.Dynamo/BGNode.cs
736
C#
using Miru.Html.Tags; namespace Miru.Tests.Html.TagHelpers; public class SrcForTagHelperTest : TagHelperTest { [Test] public async Task Should_add_src_attr_for_a_feature_url() { // arrange var tag = CreateTag(new SrcForTagHelper { For = MakeExpression(new PostShow.Query { Id = 1 }) }); // act var output = await ProcessTagAsync(tag, "img"); // assert output.TagName.ShouldBe("img"); output.Attributes["src"].Value.ShouldBe("/PostShow?Id=1"); } public class PostShow { public class Query { public long Id { get; set; } } } }
22.870968
66
0.54725
[ "MIT" ]
mirufx/miru
tests/Miru.Tests/Html/TagHelpers/SrcForTagHelperTest.cs
709
C#
using BinarySerializer; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MusyXBoy { public class Context : BinarySerializer.Context { public Context(string basePath, bool log, bool verbose = true) : base( basePath: basePath, // Pass in the base path settings: new SerializerSettings(), // Pass in the settings serializerLog: log ? new SerializerLog() : null, // Use serializer log for logging to a file fileManager: new CustomFileManager(), logger: verbose ? new ConsoleLog() : null) // Use console log { } public class CustomFileManager : IFileManager { public PathSeparatorChar SeparatorCharacter => PathSeparatorChar.ForwardSlash; public bool DirectoryExists(string path) => Directory.Exists(path); public bool FileExists(string path) => File.Exists(path); public Stream GetFileReadStream(string path) => new MemoryStream(File.ReadAllBytes(path)); public Stream GetFileWriteStream(string path, bool recreateOnWrite = true) => recreateOnWrite ? File.Create(path) : File.OpenWrite(path); public Task FillCacheForReadAsync(long length, Reader reader) => Task.CompletedTask; } public class SerializerSettings : ISerializerSettings { /// <summary> /// The default string encoding to use when none is specified /// </summary> public Encoding DefaultStringEncoding => Encoding.GetEncoding(1252); /// <summary> /// Indicates if a backup file should be created when writing to a file /// </summary> public bool CreateBackupOnWrite => false; /// <summary> /// Indicates if pointers should be saved in the Memory Map for relocation /// </summary> public bool SavePointersForRelocation => false; /// <summary> /// Indicates if caching read objects should be ignored /// </summary> public bool IgnoreCacheOnRead => false; /// <summary> /// The pointer size to use when logging a <see cref="Pointer"/>. Set to <see langword="null"/> to dynamically determine the appropriate size. /// </summary> public PointerSize? LoggingPointerSize => PointerSize.Pointer32; public Endian DefaultEndianness => Endian.Little; } public class ConsoleLog : ILogger { public void Log(object log) => Console.WriteLine(log); public void LogWarning(object log) => Console.WriteLine(log); public void LogError(object log) => Console.WriteLine(log); } public class SerializerLog : ISerializerLog { public bool IsEnabled => !string.IsNullOrEmpty(LogFile); private StreamWriter _logWriter; protected StreamWriter LogWriter => _logWriter ??= GetFile(); public string OverrideLogPath { get; set; } public string LogFile => OverrideLogPath; public int BufferSize => 0x8000000; // 1 GB public StreamWriter GetFile() { return new StreamWriter(File.Open(LogFile, FileMode.Create, FileAccess.Write, FileShare.ReadWrite), Encoding.UTF8, BufferSize); } public void Log(object obj) { if (IsEnabled) LogWriter.WriteLine(obj != null ? obj.ToString() : ""); } public void Dispose() { _logWriter?.Dispose(); _logWriter = null; } } } }
39.978495
154
0.612964
[ "MIT" ]
byvar/musyxboy
src/BinarySerializer/Context.cs
3,720
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class ShuffleBag<T> { List<T> bag; int i; public ShuffleBag(IEnumerable<T> l) { bag = l.ToList(); UnityEngine.Debug.Assert(bag.Count != 0); Reshuffle(); } void Reshuffle() { bag = bag.OrderBy(x => UnityEngine.Random.value).ToList(); i = 0; } public T Get() { var r = bag[i++]; if(i == bag.Count) Reshuffle(); return r; } }
18.269231
60
0.652632
[ "MIT" ]
2bam/ShipwreckEnsemble
Assets/Scripts/ShuffleBag.cs
477
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ssm-2014-11-06.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.SimpleSystemsManagement.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.SimpleSystemsManagement.Model.Internal.MarshallTransformations { /// <summary> /// ListComplianceItems Request Marshaller /// </summary> public class ListComplianceItemsRequestMarshaller : IMarshaller<IRequest, ListComplianceItemsRequest> , 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((ListComplianceItemsRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(ListComplianceItemsRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.SimpleSystemsManagement"); string target = "AmazonSSM.ListComplianceItems"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2014-11-06"; request.HttpMethod = "POST"; request.ResourcePath = "/"; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetFilters()) { context.Writer.WritePropertyName("Filters"); context.Writer.WriteArrayStart(); foreach(var publicRequestFiltersListValue in publicRequest.Filters) { context.Writer.WriteObjectStart(); var marshaller = ComplianceStringFilterMarshaller.Instance; marshaller.Marshall(publicRequestFiltersListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetMaxResults()) { context.Writer.WritePropertyName("MaxResults"); context.Writer.Write(publicRequest.MaxResults); } if(publicRequest.IsSetNextToken()) { context.Writer.WritePropertyName("NextToken"); context.Writer.Write(publicRequest.NextToken); } if(publicRequest.IsSetResourceIds()) { context.Writer.WritePropertyName("ResourceIds"); context.Writer.WriteArrayStart(); foreach(var publicRequestResourceIdsListValue in publicRequest.ResourceIds) { context.Writer.Write(publicRequestResourceIdsListValue); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetResourceTypes()) { context.Writer.WritePropertyName("ResourceTypes"); context.Writer.WriteArrayStart(); foreach(var publicRequestResourceTypesListValue in publicRequest.ResourceTypes) { context.Writer.Write(publicRequestResourceTypesListValue); } context.Writer.WriteArrayEnd(); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static ListComplianceItemsRequestMarshaller _instance = new ListComplianceItemsRequestMarshaller(); internal static ListComplianceItemsRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static ListComplianceItemsRequestMarshaller Instance { get { return _instance; } } } }
37.972789
153
0.594769
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/SimpleSystemsManagement/Generated/Model/Internal/MarshallTransformations/ListComplianceItemsRequestMarshaller.cs
5,582
C#
// <copyright file="EncodeBmp.cs" company="James Jackson-South"> // Copyright (c) James Jackson-South and contributors. // Licensed under the Apache License, Version 2.0. // </copyright> namespace ImageSharp.Benchmarks.Image { using System.Drawing; using System.Drawing.Imaging; using System.IO; using BenchmarkDotNet.Attributes; using CoreImage = ImageSharp.Image; public class EncodeBmp : BenchmarkBase { // System.Drawing needs this. private Stream bmpStream; private Image bmpDrawing; private Image<Rgba32> bmpCore; [GlobalSetup] public void ReadImages() { if (this.bmpStream == null) { this.bmpStream = File.OpenRead("../ImageSharp.Tests/TestImages/Formats/Bmp/Car.bmp"); this.bmpCore = CoreImage.Load<Rgba32>(this.bmpStream); this.bmpStream.Position = 0; this.bmpDrawing = Image.FromStream(this.bmpStream); } } [GlobalCleanup] public void Cleanup() { this.bmpStream.Dispose(); this.bmpCore.Dispose(); this.bmpDrawing.Dispose(); } [Benchmark(Baseline = true, Description = "System.Drawing Bmp")] public void BmpSystemDrawing() { using (MemoryStream memoryStream = new MemoryStream()) { this.bmpDrawing.Save(memoryStream, ImageFormat.Bmp); } } [Benchmark(Description = "ImageSharp Bmp")] public void BmpCore() { using (MemoryStream memoryStream = new MemoryStream()) { this.bmpCore.SaveAsBmp(memoryStream); } } } }
28.387097
101
0.573864
[ "Apache-2.0" ]
OrchardCMS/ImageSharp
tests/ImageSharp.Benchmarks/Image/EncodeBmp.cs
1,762
C#
// Copyright (c) Jan Škoruba. All Rights Reserved. // Licensed under the Apache License, Version 2.0. using Skoruba.AuditLogging.Events; using Skoruba.Duende.IdentityServer.Admin.BusinessLogic.Dtos.Configuration; namespace Skoruba.Duende.IdentityServer.Admin.BusinessLogic.Events.IdentityResource { public class IdentityResourceUpdatedEvent : AuditEvent { public IdentityResourceDto OriginalIdentityResource { get; set; } public IdentityResourceDto IdentityResource { get; set; } public IdentityResourceUpdatedEvent(IdentityResourceDto originalIdentityResource, IdentityResourceDto identityResource) { OriginalIdentityResource = originalIdentityResource; IdentityResource = identityResource; } } }
38.85
127
0.760618
[ "Apache-2.0" ]
CentauriConsulting/Duende.IdentityServer.Admin
src/Skoruba.Duende.IdentityServer.Admin.BusinessLogic/Events/IdentityResource/IdentityResourceUpdatedEvent.cs
780
C#
namespace Domain.Entities.Abstractions.Point { public interface IPointInstance { IPoint Build(); } }
15.25
45
0.655738
[ "MIT" ]
sergiobarriel/planet-exploration
src/PlanetExploration/Domain.Entities/Abstractions/Point/IPointInstance.cs
124
C#
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using IdentityServer3.Core.Models; using IdentityServer3.Core.Extensions; using IdentityServer3.Core; using IdentityModel; using IdentityServer3.Core.Services.Default; using Dnx.Identity.MongoDB; using Dnx.Identity.MongoDB.Models; using Microsoft.AspNet.Identity; namespace ModernShopping.Auth.Identity { /// <remarks> /// Taken from https://github.com/IdentityServer/IdentityServer3.Samples/blob/cf3ba612ead847d868dc64d4e39857b70f2b35ca/source/AspNetIdentity/WebHost/App_Packages/IdentityServer3.AspNetIdentity/IdentityServer3.AspNetIdentity.cs /// </remarks> public class AspNetIdentityUserService<TUser> : UserServiceBase where TUser : class { protected readonly Microsoft.AspNet.Identity.UserManager<TUser> _userManager; public AspNetIdentityUserService(Microsoft.AspNet.Identity.UserManager<TUser> userManager, Func<string> parseSubject = null) { if (userManager == null) throw new ArgumentNullException("userManager"); _userManager = userManager; EnableSecurityStamp = true; } public string DisplayNameClaimType { get; set; } public bool EnableSecurityStamp { get; } public override async Task GetProfileDataAsync(ProfileDataRequestContext ctx) { var subject = ctx.Subject; var requestedClaimTypes = ctx.RequestedClaimTypes; if (subject == null) throw new ArgumentNullException("subject"); string key = subject.GetSubjectId(); var acct = await _userManager.FindByIdAsync(key); if (acct == null) { throw new ArgumentException("Invalid subject identifier"); } var claims = await GetClaimsFromAccount(acct); if (requestedClaimTypes != null && requestedClaimTypes.Any()) { claims = claims.Where(x => requestedClaimTypes.Contains(x.Type)); } ctx.IssuedClaims = claims; } protected virtual async Task<IEnumerable<Claim>> GetClaimsFromAccount(TUser user) { var userId = await _userManager.GetUserIdAsync(user).ConfigureAwait(false); var userName = await _userManager.GetUserNameAsync(user).ConfigureAwait(false); var claims = new List<Claim>{ new Claim(Constants.ClaimTypes.Subject, userId), new Claim(Constants.ClaimTypes.PreferredUserName, userName), }; if (_userManager.SupportsUserEmail) { var email = await _userManager.GetEmailAsync(user).ConfigureAwait(false); if (!string.IsNullOrWhiteSpace(email)) { claims.Add(new Claim(Constants.ClaimTypes.Email, email)); var verified = await _userManager.IsEmailConfirmedAsync(user).ConfigureAwait(false); claims.Add(new Claim(Constants.ClaimTypes.EmailVerified, verified ? "true" : "false")); } } if (_userManager.SupportsUserPhoneNumber) { var phone = await _userManager.GetPhoneNumberAsync(user).ConfigureAwait(false); if (!string.IsNullOrWhiteSpace(phone)) { claims.Add(new Claim(Constants.ClaimTypes.PhoneNumber, phone)); var verified = await _userManager.IsPhoneNumberConfirmedAsync(user); claims.Add(new Claim(Constants.ClaimTypes.PhoneNumberVerified, verified ? "true" : "false")); } } if (_userManager.SupportsUserClaim) { claims.AddRange(await _userManager.GetClaimsAsync(user).ConfigureAwait(false)); } if (_userManager.SupportsUserRole) { var roleClaims = from role in await _userManager.GetRolesAsync(user).ConfigureAwait(false) select new Claim(Constants.ClaimTypes.Role, role); claims.AddRange(roleClaims); } return claims; } protected virtual async Task<string> GetDisplayNameForAccountAsync(string userID) { string displayName; Claim nameClaim = null; var user = await _userManager.FindByIdAsync(userID); var claims = await GetClaimsFromAccount(user); if (DisplayNameClaimType != null) { nameClaim = claims.FirstOrDefault(x => x.Type == DisplayNameClaimType); } if (nameClaim == null) { nameClaim = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.Name); } if (nameClaim == null) { nameClaim = claims.FirstOrDefault(x => x.Type == ClaimTypes.Name); } if (nameClaim != null) { displayName = nameClaim.Value; } else { displayName = await _userManager.GetUserNameAsync(user).ConfigureAwait(false); } return displayName; } protected async virtual Task<TUser> FindUserAsync(string username) { return await _userManager.FindByNameAsync(username); } protected virtual Task<AuthenticateResult> PostAuthenticateLocalAsync(TUser user, SignInMessage message) { return Task.FromResult<AuthenticateResult>(null); } public override async Task AuthenticateLocalAsync(LocalAuthenticationContext ctx) { var username = ctx.UserName; var password = ctx.Password; var message = ctx.SignInMessage; ctx.AuthenticateResult = null; if (_userManager.SupportsUserPassword) { var user = await FindUserAsync(username); if (user != null) { if (_userManager.SupportsUserLockout && await _userManager.IsLockedOutAsync(user).ConfigureAwait(false)) { return; } if (await _userManager.CheckPasswordAsync(user, password)) { if (_userManager.SupportsUserLockout) { await _userManager.ResetAccessFailedCountAsync(user).ConfigureAwait(false); } var result = await PostAuthenticateLocalAsync(user, message); if (result == null) { var claims = await GetClaimsForAuthenticateResult(user); var userId = await _userManager.GetUserIdAsync(user).ConfigureAwait(false); result = new AuthenticateResult(userId, await GetDisplayNameForAccountAsync(userId), claims); } ctx.AuthenticateResult = result; } else if (_userManager.SupportsUserLockout) { await _userManager.AccessFailedAsync(user).ConfigureAwait(false); } } } } protected virtual async Task<IEnumerable<Claim>> GetClaimsForAuthenticateResult(TUser user) { List<Claim> claims = new List<Claim>(); if (EnableSecurityStamp && _userManager.SupportsUserSecurityStamp) { var stamp = await _userManager.GetSecurityStampAsync(user).ConfigureAwait(false); if (!String.IsNullOrWhiteSpace(stamp)) { claims.Add(new Claim("security_stamp", stamp)); } } return claims; } public override async Task AuthenticateExternalAsync(ExternalAuthenticationContext ctx) { var externalUser = ctx.ExternalIdentity; var message = ctx.SignInMessage; if (externalUser == null) { throw new ArgumentNullException("externalUser"); } var user = await _userManager.FindByLoginAsync(externalUser.Provider, externalUser.ProviderId).ConfigureAwait(false); if (user == null) { ctx.AuthenticateResult = await ProcessNewExternalAccountAsync(externalUser.Provider, externalUser.ProviderId, externalUser.Claims); } else { ctx.AuthenticateResult = await ProcessExistingExternalAccountAsync(user, externalUser.Provider, externalUser.ProviderId, externalUser.Claims); } } protected virtual async Task<AuthenticateResult> ProcessNewExternalAccountAsync(string provider, string providerId, IEnumerable<Claim> claims) { var user = await TryGetExistingUserFromExternalProviderClaimsAsync(provider, claims); if (user == null) { user = await InstantiateNewUserFromExternalProviderAsync(provider, providerId, claims); if (user == null) throw new InvalidOperationException("CreateNewAccountFromExternalProvider returned null"); var createResult = await _userManager.CreateAsync(user); if (!createResult.Succeeded) { return new AuthenticateResult($"{createResult.Errors.First().Code}-{createResult.Errors.First().Description}"); } } var externalLogin = new Microsoft.AspNet.Identity.UserLoginInfo(provider, providerId, null); var addExternalResult = await _userManager.AddLoginAsync(user, externalLogin).ConfigureAwait(false); if (!addExternalResult.Succeeded) { return new AuthenticateResult($"{addExternalResult.Errors.First().Code}-{addExternalResult.Errors.First().Description}"); } var result = await AccountCreatedFromExternalProviderAsync(user, provider, providerId, claims); if (result != null) return result; return await SignInFromExternalProviderAsync(user, provider); } // TODO!!! GIANT HACK! protected virtual Task<TUser> InstantiateNewUserFromExternalProviderAsync(string provider, string providerId, IEnumerable<Claim> claims) { var user = new MongoIdentityUser(Guid.NewGuid().ToString("N")); return Task.FromResult(user as TUser); } protected virtual Task<TUser> TryGetExistingUserFromExternalProviderClaimsAsync(string provider, IEnumerable<Claim> claims) { return Task.FromResult<TUser>(null); } protected virtual async Task<AuthenticateResult> AccountCreatedFromExternalProviderAsync(TUser user, string provider, string providerId, IEnumerable<Claim> claims) { claims = await SetAccountEmailAsync(user, claims); claims = await SetAccountPhoneAsync(user, claims); return await UpdateAccountFromExternalClaimsAsync(user, provider, providerId, claims); } protected virtual async Task<AuthenticateResult> SignInFromExternalProviderAsync(TUser user, string provider) { var userId = await _userManager.GetUserIdAsync(user).ConfigureAwait(false); var claims = await GetClaimsForAuthenticateResult(user); return new AuthenticateResult( userId.ToString(), await GetDisplayNameForAccountAsync(userId), claims, authenticationMethod: Constants.AuthenticationMethods.External, identityProvider: provider); } protected virtual async Task<AuthenticateResult> UpdateAccountFromExternalClaimsAsync(TUser user, string provider, string providerId, IEnumerable<Claim> claims) { var existingClaims = await _userManager.GetClaimsAsync(user).ConfigureAwait(false); var intersection = existingClaims.Intersect(claims, new ClaimComparer()); var newClaims = claims.Except(intersection, new ClaimComparer()); foreach (var claim in newClaims) { var result = await _userManager.AddClaimAsync(user, claim).ConfigureAwait(false); if (!result.Succeeded) { return new AuthenticateResult($"{result.Errors.First().Code}-{result.Errors.First().Description}"); } } return null; } protected virtual async Task<AuthenticateResult> ProcessExistingExternalAccountAsync(TUser user, string provider, string providerId, IEnumerable<Claim> claims) { return await SignInFromExternalProviderAsync(user, provider); } protected virtual async Task<IEnumerable<Claim>> SetAccountEmailAsync(TUser user, IEnumerable<Claim> claims) { var email = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.Email); if (email != null) { var userEmail = await _userManager.GetEmailAsync(user); if (userEmail == null) { // if this fails, then presumably the email is already associated with another account // so ignore the error and let the claim pass thru var result = await _userManager.SetEmailAsync(user, email.Value); if (result.Succeeded) { var email_verified = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.EmailVerified); if (email_verified != null && email_verified.Value == "true") { var token = await _userManager.GenerateEmailConfirmationTokenAsync(user); await _userManager.ConfirmEmailAsync(user, token); } var emailClaims = new string[] { Constants.ClaimTypes.Email, Constants.ClaimTypes.EmailVerified }; return claims.Where(x => !emailClaims.Contains(x.Type)); } } } return claims; } protected virtual async Task<IEnumerable<Claim>> SetAccountPhoneAsync(TUser user, IEnumerable<Claim> claims) { var phone = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.PhoneNumber); if (phone != null) { var userPhone = await _userManager.GetPhoneNumberAsync(user); if (userPhone == null) { // if this fails, then presumably the phone is already associated with another account // so ignore the error and let the claim pass thru var result = await _userManager.SetPhoneNumberAsync(user, phone.Value); if (result.Succeeded) { var phone_verified = claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.PhoneNumberVerified); if (phone_verified != null && phone_verified.Value == "true") { var token = await _userManager.GenerateChangePhoneNumberTokenAsync(user, phone.Value); await _userManager.ChangePhoneNumberAsync(user, phone.Value, token); } var phoneClaims = new string[] { Constants.ClaimTypes.PhoneNumber, Constants.ClaimTypes.PhoneNumberVerified }; return claims.Where(x => !phoneClaims.Contains(x.Type)); } } } return claims; } public override async Task IsActiveAsync(IsActiveContext ctx) { var subject = ctx.Subject; if (subject == null) throw new ArgumentNullException("subject"); var id = subject.GetSubjectId(); var acct = await _userManager.FindByIdAsync(id).ConfigureAwait(false); ctx.IsActive = false; if (acct != null) { if (EnableSecurityStamp && _userManager.SupportsUserSecurityStamp) { var security_stamp = subject.Claims.Where(x => x.Type == "security_stamp").Select(x => x.Value).SingleOrDefault(); if (security_stamp != null) { var db_security_stamp = await _userManager.GetSecurityStampAsync(acct).ConfigureAwait(false); if (db_security_stamp != security_stamp) { return; } } } ctx.IsActive = true; } } } }
43.248768
231
0.57042
[ "MIT" ]
tugberkugurlu/ModernShopping
Auth/src/ModernShopping.Auth/Identity/AspNetIdentityUserService.cs
17,561
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace Microsoft.Azure.Cosmos.SDK.EmulatorTests { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.Cosmos.Routing; using Microsoft.Azure.Documents; using Microsoft.Azure.Documents.Client; using Microsoft.Azure.Documents.Collections; using Microsoft.Azure.Documents.Routing; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class UserAgentTests { [TestMethod] [DataRow(true)] [DataRow(false)] public async Task ValidateUserAgentHeaderWithMacOs(bool useMacOs) { const string suffix = " UserApplicationName/1.0"; CosmosClientOptions clientOptions = this.SetEnvironmentInformation(useMacOs); clientOptions.ApplicationName = suffix; using (CosmosClient client = TestCommon.CreateCosmosClient(clientOptions)) { Cosmos.UserAgentContainer userAgentContainer = client.ClientOptions.GetConnectionPolicy(client.ClientId).UserAgentContainer; string userAgentString = userAgentContainer.UserAgent; Assert.IsTrue(userAgentString.Contains(suffix)); if (useMacOs) { Assert.IsTrue(userAgentString.Contains("Darwin 18.0.0")); } Cosmos.Database db = await client.CreateDatabaseIfNotExistsAsync(Guid.NewGuid().ToString()); Assert.IsNotNull(db); await db.DeleteAsync(); } } [TestMethod] public void ValidateCustomUserAgentHeader() { const string suffix = " MyCustomUserAgent/1.0"; ConnectionPolicy policy = new ConnectionPolicy(); policy.UserAgentSuffix = suffix; Assert.IsTrue(policy.UserAgentContainer.UserAgent.EndsWith(suffix)); byte[] expectedUserAgentUTF8 = Encoding.UTF8.GetBytes(policy.UserAgentContainer.UserAgent); CollectionAssert.AreEqual(expectedUserAgentUTF8, policy.UserAgentContainer.UserAgentUTF8); } [TestMethod] public void ValidateUniqueClientIdHeader() { CosmosClient.numberOfClientsCreated = 0; using (CosmosClient client = TestCommon.CreateCosmosClient()) { string firstClientId = this.GetClientIdFromCosmosClient(client); using (CosmosClient innerClient = TestCommon.CreateCosmosClient()) { string secondClientId = this.GetClientIdFromCosmosClient(innerClient); Assert.AreNotEqual(firstClientId, secondClientId); } } } [TestMethod] public void VerifyUserAgentContent() { EnvironmentInformation envInfo = new EnvironmentInformation(); Cosmos.UserAgentContainer userAgentContainer = new Cosmos.UserAgentContainer(clientId: 0); string serialization = userAgentContainer.UserAgent; Assert.IsTrue(serialization.Contains(envInfo.ProcessArchitecture)); string[] values = serialization.Split('|'); string previewFlag = string.Empty; #if PREVIEW previewFlag = "P"; #endif Assert.AreEqual($"cosmos-netstandard-sdk/{envInfo.ClientVersion}" + previewFlag, values[0]); Assert.AreEqual(envInfo.DirectVersion, values[1]); Assert.AreEqual("0", values[2]); Assert.AreEqual(envInfo.ProcessArchitecture, values[3]); Assert.AreEqual(envInfo.OperatingSystem, values[4]); Assert.AreEqual(envInfo.RuntimeFramework, values[5]); } [TestMethod] public async Task VerifyUserAgentWithRegionConfiguration() { string databaseName = Guid.NewGuid().ToString(); string containerName = Guid.NewGuid().ToString(); { CosmosClientOptions cosmosClientOptions = new CosmosClientOptions(); // N - None. The user did not configure anything string userAgentContentToValidate = "|N|"; await this.ValidateUserAgentStringAsync( cosmosClientOptions, userAgentContentToValidate, databaseName, containerName); } { CosmosClientOptions cosmosClientOptions = new CosmosClientOptions { LimitToEndpoint = true }; // D - Disabled endpoint discovery, N - None. The user did not configure anything string userAgentContentToValidate = "|DN|"; await this.ValidateUserAgentStringAsync( cosmosClientOptions, userAgentContentToValidate, databaseName, containerName); } { CosmosClientOptions cosmosClientOptions = new CosmosClientOptions { ApplicationRegion = Regions.EastUS }; // S - Single application region is set string userAgentContentToValidate = "|S|"; await this.ValidateUserAgentStringAsync( cosmosClientOptions, userAgentContentToValidate, databaseName, containerName); } { CosmosClientOptions cosmosClientOptions = new CosmosClientOptions { LimitToEndpoint = false, ApplicationRegion = null, ApplicationPreferredRegions = new List<string>() { Regions.EastUS, Regions.WestUS } }; // L - List of region is set string userAgentContentToValidate = "|L|"; await this.ValidateUserAgentStringAsync( cosmosClientOptions, userAgentContentToValidate, databaseName, containerName); } using (CosmosClient client = TestCommon.CreateCosmosClient()) { await client.GetDatabase(databaseName).DeleteStreamAsync(); } } [TestMethod] public void VerifyDefaultUserAgentContainsRegionConfig() { UserAgentContainer userAgentContainer = new Cosmos.UserAgentContainer(clientId: 0); Assert.IsTrue(userAgentContainer.UserAgent.Contains("|NS|")); } [TestMethod] public void VerifyClientIDForUserAgentString() { CosmosClient.numberOfClientsCreated = 0; // reset const int max = 10; for (int i = 1; i < max + 5; i++) { using (CosmosClient client = TestCommon.CreateCosmosClient()) { string userAgentString = client.DocumentClient.ConnectionPolicy.UserAgentContainer.UserAgent; if (i <= max) { Assert.AreEqual(userAgentString.Split('|')[2], i.ToString()); } else { Assert.AreEqual(userAgentString.Split('|')[2], max.ToString()); } } } } [TestMethod] public async Task VerifyClientIDIncrements_Concurrent() { CosmosClient.numberOfClientsCreated = 0; // reset const int max = 10; List<int> expected = new List<int>(); for (int i = 1; i < max + 5; i++) { expected.Add(i > max ? max : i); } List<Task<CosmosClient>> tasks = new List<Task<CosmosClient>>(); for (int i = 1; i < max + 5; i++) { tasks.Add(Task.Factory.StartNew(() => TestCommon.CreateCosmosClient())); } await Task.WhenAll(tasks); List<int> actual = tasks.Select(r => int.Parse(r.Result.DocumentClient.ConnectionPolicy.UserAgentContainer.UserAgent.Split('|')[2])).ToList(); actual.Sort(); CollectionAssert.AreEqual(expected, actual); } private async Task ValidateUserAgentStringAsync( CosmosClientOptions cosmosClientOptions, string userAgentContentToValidate, string databaseName, string containerName) { HttpClientHandlerHelper httpClientHandlerHelper = new HttpClientHandlerHelper() { RequestCallBack = (request, cancellationToken) => { string userAgent = request.Headers.UserAgent.ToString(); Assert.IsTrue(userAgent.Contains(userAgentContentToValidate)); return null; } }; cosmosClientOptions.HttpClientFactory = () => new HttpClient(httpClientHandlerHelper); using (CosmosClient client = TestCommon.CreateCosmosClient(cosmosClientOptions)) { Cosmos.Database db = await client.CreateDatabaseIfNotExistsAsync(databaseName); await db.CreateContainerIfNotExistsAsync(containerName, "/pk"); } } [TestMethod] [DataRow(true, true)] [DataRow(true, false)] [DataRow(false, true)] [DataRow(false, false)] public async Task VerifyUserAgentWithFeatures(bool setApplicationName, bool useMacOs) { CosmosClientOptions cosmosClientOptions = this.SetEnvironmentInformation(useMacOs); const string suffix = " UserApplicationName/1.0"; CosmosClientOptionsFeatures featuresFlags = CosmosClientOptionsFeatures.NoFeatures; featuresFlags |= CosmosClientOptionsFeatures.AllowBulkExecution; featuresFlags |= CosmosClientOptionsFeatures.HttpClientFactory; string features = Convert.ToString((int)featuresFlags, 2).PadLeft(8, '0'); cosmosClientOptions.AllowBulkExecution = true; cosmosClientOptions.HttpClientFactory = () => new HttpClient(); if (setApplicationName) { cosmosClientOptions.ApplicationName = suffix; } using (CosmosClient client = TestCommon.CreateCosmosClient(cosmosClientOptions)) { Cosmos.UserAgentContainer userAgentContainer = client.ClientOptions.GetConnectionPolicy(client.ClientId).UserAgentContainer; string userAgentString = userAgentContainer.UserAgent; if (setApplicationName) { Assert.IsTrue(userAgentString.Contains(suffix)); } else { Assert.IsFalse(userAgentString.Contains(suffix)); } Assert.IsTrue(userAgentString.Contains($"|F {features}")); if (useMacOs) { Assert.IsTrue(userAgentString.Contains("Darwin 18.0.0")); } Cosmos.Database db = await client.CreateDatabaseIfNotExistsAsync(Guid.NewGuid().ToString()); Assert.IsNotNull(db); await db.DeleteAsync(); } cosmosClientOptions = this.SetEnvironmentInformation(useMacOs); if (setApplicationName) { cosmosClientOptions.ApplicationName = suffix; } using (CosmosClient client = TestCommon.CreateCosmosClient(cosmosClientOptions)) { Cosmos.UserAgentContainer userAgentContainer = client.ClientOptions.GetConnectionPolicy(client.ClientId).UserAgentContainer; string userAgentString = userAgentContainer.UserAgent; if (setApplicationName) { Assert.IsTrue(userAgentString.Contains(suffix)); } else { Assert.IsFalse(userAgentString.Contains(suffix)); } Assert.IsFalse(userAgentString.Contains($"|F {features}")); } } private sealed class MacUserAgentStringClientOptions : CosmosClientOptions { internal override ConnectionPolicy GetConnectionPolicy(int clientId) { ConnectionPolicy connectionPolicy = base.GetConnectionPolicy(clientId); MacOsUserAgentContainer userAgent = this.CreateUserAgentContainer(clientId); connectionPolicy.UserAgentContainer = userAgent; return connectionPolicy; } internal MacOsUserAgentContainer CreateUserAgentContainer(int clientId) { CosmosClientOptionsFeatures features = CosmosClientOptionsFeatures.NoFeatures; if (this.AllowBulkExecution) { features |= CosmosClientOptionsFeatures.AllowBulkExecution; } if (this.HttpClientFactory != null) { features |= CosmosClientOptionsFeatures.HttpClientFactory; } string featureString = null; if (features != CosmosClientOptionsFeatures.NoFeatures) { featureString = Convert.ToString((int)features, 2).PadLeft(8, '0'); } return new MacOsUserAgentContainer( clientId: clientId, features: featureString, suffix: this.ApplicationName); } } private sealed class MacOsUserAgentContainer : Cosmos.UserAgentContainer { public MacOsUserAgentContainer(int clientId, string features = null, string regionConfiguration = "N", string suffix = null) : base(clientId, features, regionConfiguration, suffix) { } protected override void GetEnvironmentInformation( out string clientVersion, out string directVersion, out string processArchitecture, out string operatingSystem, out string runtimeFramework) { //This changes the information to simulate a max os x response. Windows user agent are tested by every other emulator test. operatingSystem = "Darwin 18.0.0: Darwin/Kernel/Version 18.0.0: Wed Aug 22 20:13:40 PDT 2018; root:xnu-4903.201.2~1/RELEASE_X86_64"; base.GetEnvironmentInformation( clientVersion: out clientVersion, directVersion: out directVersion, processArchitecture: out processArchitecture, operatingSystem: out _, runtimeFramework: out runtimeFramework); } } private CosmosClientOptions SetEnvironmentInformation(bool useMacOs) { if (useMacOs) { return new MacUserAgentStringClientOptions(); } return new CosmosClientOptions(); } private string GetClientIdFromCosmosClient(CosmosClient client) { Cosmos.UserAgentContainer userAgentContainer = client.ClientOptions.GetConnectionPolicy(client.ClientId).UserAgentContainer; string userAgentString = userAgentContainer.UserAgent; string clientId = userAgentString.Split('|')[2]; return clientId; } } }
39.783654
148
0.558792
[ "MIT" ]
SaurabhSharma-MSFT/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.EmulatorTests/UserAgentTests.cs
16,552
C#
 namespace iTin.Hardware.Specification.Eedid.Blocks.EDID { using iTin.Core.Hardware.Common; using Sections; /// <summary> /// Sections available for a block <see cref="KnownDataBlock.EDID"/>. /// </summary> public enum EdidSection { /// <summary> /// <b>Header</b> section of a block <see cref="KnownDataBlock.EDID"/>, for more information see <see cref="HeaderSection" />. /// </summary> [PropertyName("Header")] [PropertyDescription("Header Section")] Header, /// <summary> /// <b>Vendor and Product</b> section of a block <see cref="KnownDataBlock.EDID"/>, for more information see <see cref="VendorSection"/>. /// </summary> [PropertyName("Vendor")] [PropertyDescription("Vendor And Product Section")] Vendor, /// <summary> /// Section <b>Version and Revision</b> of a block <see cref="KnownDataBlock.EDID"/>, for more information see <see cref="VersionSection"/>. /// </summary> [PropertyName("Version")] [PropertyDescription("Version Section")] Version, /// <summary> /// Section <b>Basic Display Parameters and Features</b> of a block <see cref="KnownDataBlock.EDID"/>, for more information see <see cref="BasicDisplaySection"/>. /// </summary> [PropertyName("Basic Display")] [PropertyDescription(">Basic Display Parameters And Features Section")] BasicDisplay, /// <summary> /// <b>Color Characteristics</b> section of a block <see cref="KnownDataBlock.EDID"/>, for more information see <see cref="ColorCharacteristicsSection"/>. /// </summary> [PropertyName("Color Characteristics")] [PropertyDescription("Color Characteristics Section")] ColorCharacteristics, /// <summary> /// <b>Established Timings I, II</b> section of a block <see cref="KnownDataBlock.EDID"/>, for more information see <see cref="EstablishedTimingsSection"/>. /// </summary> [PropertyName("Established Timings")] [PropertyDescription("Established Timings I, II Section")] EstablishedTimings, /// <summary> /// Section <b>Standard Timings 16 Bytes</b> of a block <see cref="KnownDataBlock.EDID"/>, for more information see <see cref="StandardTimingsSection"/>. /// </summary> [PropertyName("Standard Timings")] [PropertyDescription("Standard Timings 16 Bytes Section")] StandardTimings, /// <summary> /// Section <b>18 Byte Data Blocks Descriptors</b> of a block <see cref="KnownDataBlock.EDID"/>, for more information see <see cref="DataBlocksSection"/>. /// </summary> [PropertyName("Data Blocks")] [PropertyDescription("18 Byte Data Blocks Descriptors Section")] DataBlocks, /// <summary> /// <b>Extension Block Count</b> section of a block <see cref="KnownDataBlock.EDID"/>, for more information see <see cref="ExtensionBlocksSection"/>. /// </summary> [PropertyName("Extension Blocks")] [PropertyDescription("Extension Block Count Section")] ExtensionBlocks, /// <summary> /// <b> CheckSum </b> section of a block <see cref="KnownDataBlock.EDID"/>, for more information see <see cref="ChecksumSection"/>. /// </summary> [PropertyName("CheckSum")] [PropertyDescription("CheckSum Section")] Checksum } }
41.809524
170
0.622153
[ "MIT" ]
iAJTin/iEEDID
src/lib/net/iTin.Hardware/iTin.Hardware.Specification/iTin.Hardware.Specification.Eedid/EEDID/Blocks/EDID/EdidSection.cs
3,514
C#
// // System.MultiCastDelegate.cs // // Authors: // Miguel de Icaza (miguel@ximian.com) // Daniel Stodden (stodden@in.tum.de) // // (C) Ximian, Inc. http://www.ximian.com // // // Copyright (C) 2004 Novell, Inc (http://www.novell.com) // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using System.Runtime.InteropServices; namespace System { [System.Runtime.InteropServices.ComVisible (true)] [Serializable] [StructLayout (LayoutKind.Sequential)] public abstract class MulticastDelegate : Delegate { Delegate[] delegates; protected MulticastDelegate (object target, string method) : base (target, method) { } protected MulticastDelegate (Type target, string method) : base (target, method) { } public override void GetObjectData (SerializationInfo info, StreamingContext context) { base.GetObjectData (info, context); } protected sealed override object DynamicInvokeImpl (object[] args) { if (delegates == null) { return base.DynamicInvokeImpl (args); } else { object r; int i = 0, len = delegates.Length; do { r = delegates [i].DynamicInvoke (args); } while (++i < len); return r; } } // <remarks> // Equals: two multicast delegates are equal if their base is equal // and their invocations list is equal. // </remarks> public sealed override bool Equals (object obj) { if (!base.Equals (obj)) return false; MulticastDelegate d = obj as MulticastDelegate; if (d == null) return false; if (delegates == null && d.delegates == null) { return true; } else if (delegates == null ^ d.delegates == null) { return false; } else { if (delegates.Length != d.delegates.Length) return false; for (int i = 0; i < delegates.Length; ++i) { if (!delegates [i].Equals (d.delegates [i])) return false; } return true; } } // // FIXME: This could use some improvements. // public sealed override int GetHashCode () { return base.GetHashCode (); } // <summary> // Return, in order of invocation, the invocation list // of a MulticastDelegate // </summary> public sealed override Delegate[] GetInvocationList () { if (delegates != null) return (Delegate[]) delegates.Clone (); else return new Delegate[1] { this }; } // <summary> // Combines this MulticastDelegate with the (Multicast)Delegate `follow'. // This does _not_ combine with Delegates. ECMA states the whole delegate // thing should have better been a simple System.Delegate class. // Compiler generated delegates are always MulticastDelegates. // </summary> protected sealed override Delegate CombineImpl (Delegate follow) { if (follow == null) return this; MulticastDelegate other = (MulticastDelegate) follow; MulticastDelegate ret = AllocDelegateLike_internal (this); if (delegates == null && other.delegates == null) { ret.delegates = new Delegate [2] { this, other }; } else if (delegates == null) { ret.delegates = new Delegate [1 + other.delegates.Length]; ret.delegates [0] = this; Array.Copy (other.delegates, 0, ret.delegates, 1, other.delegates.Length); } else if (other.delegates == null) { ret.delegates = new Delegate [delegates.Length + 1]; Array.Copy (delegates, 0, ret.delegates, 0, delegates.Length); ret.delegates [ret.delegates.Length - 1] = other; } else { ret.delegates = new Delegate [delegates.Length + other.delegates.Length]; Array.Copy (delegates, 0, ret.delegates, 0, delegates.Length); Array.Copy (other.delegates, 0, ret.delegates, delegates.Length, other.delegates.Length); } return ret; } protected sealed override Delegate RemoveImpl (Delegate value) { if (value == null) return this; MulticastDelegate other = (MulticastDelegate) value; if (delegates == null && other.delegates == null) { /* if they are not equal and the current one is not * a multicastdelegate then we cannot delete it */ return this.Equals (other) ? null : this; } else if (delegates == null) { foreach (var d in other.delegates) { if (this.Equals (d)) return null; } return this; } else if (other.delegates == null) { int idx = Array.LastIndexOf (delegates, other); if (idx == -1) return this; if (delegates.Length <= 1) { /* delegates.Length should never be equal or * lower than 1, it should be 2 or greater */ throw new InvalidOperationException (); } if (delegates.Length == 2) return delegates [idx == 0 ? 1 : 0]; MulticastDelegate ret = AllocDelegateLike_internal (this); ret.delegates = new Delegate [delegates.Length - 1]; Array.Copy (delegates, ret.delegates, idx); Array.Copy (delegates, idx + 1, ret.delegates, idx, delegates.Length - idx - 1); return ret; } else { /* wild case : remove MulticastDelegate from MulticastDelegate * complexity is O(m * n), with n the number of elements in * this.delegates and m the number of elements in other.delegates */ MulticastDelegate ret = AllocDelegateLike_internal (this); ret.delegates = new Delegate [delegates.Length]; /* we should use a set with O(1) lookup complexity * but HashSet is implemented in System.Core.dll */ List<Delegate> other_delegates = new List<Delegate> (); for (int i = 0; i < other.delegates.Length; ++i) other_delegates.Add (other.delegates [i]); int idx = delegates.Length; /* we need to remove elements from the end to the beginning, as * the addition and removal of delegates behaves like a stack */ for (int i = delegates.Length - 1; i >= 0; --i) { /* if delegates[i] is not in other_delegates, * then we can safely add it to ret.delegates * otherwise we remove it from other_delegates */ if (!other_delegates.Remove (delegates [i])) ret.delegates [--idx] = delegates [i]; } /* the elements are at the end of the array, we * need to move them back to the beginning of it */ int count = delegates.Length - idx; Array.Copy (ret.delegates, idx, ret.delegates, 0, count); if (count == 0) return null; if (count == 1) return ret.delegates [0]; if (count != delegates.Length) Array.Resize (ref ret.delegates, count); return ret; } } public static bool operator == (MulticastDelegate d1, MulticastDelegate d2) { if (d1 == null) return d2 == null; return d1.Equals (d2); } public static bool operator != (MulticastDelegate d1, MulticastDelegate d2) { if (d1 == null) return d2 != null; return !d1.Equals (d2); } } }
29.900763
93
0.669007
[ "Apache-2.0" ]
dlech/mono
mcs/class/corlib/System/MulticastDelegate.cs
7,834
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System; using System.Net; using System.Net.Sockets; using System.Threading; using System.Text; namespace BomberTesting { public class AsynchronousClient { public static MainWindow MainWin; public static string HostIP = ""; public static string DATA = ""; // The port number for the remote device. private const int port = 11200; // ManualResetEvent instances signal completion. public static ManualResetEvent SendNow = new ManualResetEvent(false); private static ManualResetEvent connectDone = new ManualResetEvent(false); private static ManualResetEvent sendDone = new ManualResetEvent(false); private static ManualResetEvent receiveDone = new ManualResetEvent(false); // The response from the remote device. public static String Response = String.Empty; public static void StartClient() { // Connect to a remote device. try { // Establish the remote endpoint for the socket. // The name of the // remote device is "host.contoso.com". IPHostEntry ipHostInfo = Dns.Resolve(HostIP); IPAddress ipAddress = ipHostInfo.AddressList[0]; IPEndPoint remoteEP = new IPEndPoint(ipAddress, port); // Create a TCP/IP socket. Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect to the remote endpoint. client.BeginConnect(remoteEP, new AsyncCallback(ConnectCallback), client); connectDone.WaitOne(); while (true) { // Wait to send data SendNow.WaitOne(); // Send test data to the remote device. Send(client, DATA); sendDone.WaitOne(); // Receive the response from the remote device. Receive(client); receiveDone.WaitOne(); // Write the response to the console. Console.WriteLine("Response received : {0}", Response); //client.Shutdown(SocketShutdown.Both); //client.Close(); } // Release the socket. //client.Shutdown(SocketShutdown.Both); //client.Close(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } private static void ConnectCallback(IAsyncResult ar) { try { // Retrieve the socket from the state object. Socket client = (Socket)ar.AsyncState; // Complete the connection. client.EndConnect(ar); Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString()); // Signal that the connection has been made. connectDone.Set(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } private static void Receive(Socket client) { try { // Create the state object. StateObject state = new StateObject(); state.workSocket = client; // Begin receiving the data from the remote device. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(AsynchronousClient.ReceiveCallback), state); } catch (Exception e) { Console.WriteLine(e.ToString()); } } private static void ReceiveCallback(IAsyncResult ar) { try { // Retrieve the state object and the client socket // from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; Socket client = state.workSocket; String content = String.Empty; // Read data from the remote device. int bytesRead = client.EndReceive(ar); if (bytesRead > 0) { // There might be more data, so store the data received so far. state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead)); // Check for end-of-file tag. If it is not there, read // more data. content = state.sb.ToString(); if (content.IndexOf("<EOF>") > -1) { // All the data has been read from the // client. Display it on the console. Console.WriteLine("Read {0} bytes from socket. \n Data : {1}", content.Length, content); // Echo the data back to the client. Response = content.Substring(0, content.IndexOf("<EOF")); // Signal that all bytes have been received. receiveDone.Set(); } else { // Not all data received. Get more. client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(AsynchronousSocketListener.ReadCallback), state); } } //else //{ // // All the data has arrived; put it in response. // if (state.sb.Length > 1) // { // response = state.sb.ToString(); // } // // Signal that all bytes have been received. // receiveDone.Set(); //} } catch (Exception e) { Console.WriteLine(e.ToString()); } } private static void Send(Socket client, String data) { if (data.IndexOf("<EOF") == -1) data += "<EOF>"; // Convert the string data to byte data using ASCII encoding. byte[] byteData = Encoding.ASCII.GetBytes(data); // Begin sending the data to the remote device. client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client); } private static void SendCallback(IAsyncResult ar) { try { // Retrieve the socket from the state object. Socket client = (Socket)ar.AsyncState; // Complete sending the data to the remote device. int bytesSent = client.EndSend(ar); Console.WriteLine("Sent {0} bytes to server.", bytesSent); // Signal that all bytes have been sent. sendDone.Set(); } catch (Exception e) { Console.WriteLine(e.ToString()); } } } }
35.728111
92
0.478395
[ "MIT" ]
ayamnova/plat_tanks
Plat_Tanks/ServerClient.cs
7,755
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d3d10effect.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.DirectX.UnitTests; /// <summary>Provides validation of the <see cref="ID3D10Effect" /> struct.</summary> public static unsafe partial class ID3D10EffectTests { /// <summary>Validates that the <see cref="ID3D10Effect" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<ID3D10Effect>(), Is.EqualTo(sizeof(ID3D10Effect))); } /// <summary>Validates that the <see cref="ID3D10Effect" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(ID3D10Effect).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="ID3D10Effect" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(ID3D10Effect), Is.EqualTo(8)); } else { Assert.That(sizeof(ID3D10Effect), Is.EqualTo(4)); } } }
33.627907
145
0.680498
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
tests/Interop/Windows/DirectX/um/d3d10effect/ID3D10EffectTests.cs
1,448
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.txt file in the project root for more information. using System.ComponentModel.Composition; using System.Collections.Generic; using System.Threading.Tasks; namespace Microsoft.VisualStudio.InteractiveWindow.Commands { [Export(typeof(IInteractiveWindowCommand))] internal sealed class ClearScreenCommand : InteractiveWindowCommand { public override Task<ExecutionResult> Execute(IInteractiveWindow window, string arguments) { window.Operations.ClearView(); return ExecutionResult.Succeeded; } public override string Description { get { return InteractiveWindowResources.ClearScreenCommandDescription; } } public override IEnumerable<string> Names { get { yield return "cls"; yield return "clear"; } } } }
32.290323
98
0.699301
[ "MIT" ]
dotnet/interactive-window
src/Microsoft.VisualStudio.InteractiveWindow/Commands/ClearScreenCommand.cs
1,003
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Amazon.S3; using Amazon.S3.Model; namespace WebApi.Controllers { /// <summary> /// ASP.NET Core controller acting as a S3 Proxy. /// </summary> [Route("api/[controller]")] public class S3ProxyController : ControllerBase { IAmazonS3 S3Client { get; set; } ILogger Logger { get; set; } string BucketName { get; set; } public S3ProxyController(IConfiguration configuration, ILogger<S3ProxyController> logger, IAmazonS3 s3Client) { this.Logger = logger; this.S3Client = s3Client; this.BucketName = configuration[Startup.AppS3BucketKey]; if(string.IsNullOrEmpty(this.BucketName)) { logger.LogCritical("Missing configuration for S3 bucket. The AppS3Bucket configuration must be set to a S3 bucket."); throw new Exception("Missing configuration for S3 bucket. The AppS3Bucket configuration must be set to a S3 bucket."); } logger.LogInformation($"Configured to use bucket {this.BucketName}"); } [HttpGet] public async Task<JsonResult> Get() { var listResponse = await this.S3Client.ListObjectsV2Async(new ListObjectsV2Request { BucketName = this.BucketName }); try { this.Response.ContentType = "text/json"; return new JsonResult(listResponse.S3Objects); } catch(AmazonS3Exception e) { this.Response.StatusCode = (int)e.StatusCode; return new JsonResult(e.Message); } } [HttpGet("{key}")] public async Task Get(string key) { try { var getResponse = await this.S3Client.GetObjectAsync(new GetObjectRequest { BucketName = this.BucketName, Key = key }); this.Response.ContentType = getResponse.Headers.ContentType; getResponse.ResponseStream.CopyTo(this.Response.Body); } catch (AmazonS3Exception e) { this.Response.StatusCode = (int)e.StatusCode; var writer = new StreamWriter(this.Response.Body); writer.Write(e.Message); } } [HttpPut("{key}")] public async Task Put(string key) { // Copy the request body into a seekable stream required by the AWS SDK for .NET. var seekableStream = new MemoryStream(); await this.Request.Body.CopyToAsync(seekableStream); seekableStream.Position = 0; var putRequest = new PutObjectRequest { BucketName = this.BucketName, Key = key, InputStream = seekableStream }; try { var response = await this.S3Client.PutObjectAsync(putRequest); Logger.LogInformation($"Uploaded object {key} to bucket {this.BucketName}. Request Id: {response.ResponseMetadata.RequestId}"); } catch (AmazonS3Exception e) { this.Response.StatusCode = (int)e.StatusCode; var writer = new StreamWriter(this.Response.Body); writer.Write(e.Message); } } [HttpDelete("{key}")] public async Task Delete(string key) { var deleteRequest = new DeleteObjectRequest { BucketName = this.BucketName, Key = key }; try { var response = await this.S3Client.DeleteObjectAsync(deleteRequest); Logger.LogInformation($"Deleted object {key} from bucket {this.BucketName}. Request Id: {response.ResponseMetadata.RequestId}"); } catch (AmazonS3Exception e) { this.Response.StatusCode = (int)e.StatusCode; var writer = new StreamWriter(this.Response.Body); writer.Write(e.Message); } } } }
33.298507
144
0.554684
[ "MIT" ]
gangyi89/dotnetAWSServerless
WebApi/Controllers/S3ProxyController.cs
4,464
C#
// Copyright (c) Josef Pihrt. All rights reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Threading.Tasks; using Microsoft.CodeAnalysis; using Roslynator.Testing; using Roslynator.Testing.CSharp; using Xunit; namespace Roslynator.CSharp.Analysis.Tests { public class RCS1046AsynchronousMethodNameShouldEndWithAsyncTests : AbstractCSharpDiagnosticVerifier<AsyncSuffixAnalyzer, DummyCodeFixProvider> { public override DiagnosticDescriptor Descriptor { get; } = DiagnosticDescriptors.AsynchronousMethodNameShouldEndWithAsync; [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AsynchronousMethodNameShouldEndWithAsync)] public async Task Test_Task() { await VerifyDiagnosticAsync(@" using System.Threading.Tasks; class B { public virtual Task [|Foo|]() { return Task.CompletedTask; } } class C : B { public override Task Foo() { return base.Foo(); } } "); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AsynchronousMethodNameShouldEndWithAsync)] public async Task Test_Task_TypeParameter() { await VerifyDiagnosticAsync(@" using System.Threading.Tasks; class C { T [|Foo|]<T>() where T : Task { return default(T); } } "); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AsynchronousMethodNameShouldEndWithAsync)] public async Task Test_TaskOfT() { await VerifyDiagnosticAsync(@" using System.Threading.Tasks; class C { Task<object> [|Foo|]() { return Task.FromResult(default(object)); } } "); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AsynchronousMethodNameShouldEndWithAsync)] public async Task Test_TaskOfT_TypeParameter() { await VerifyDiagnosticAsync(@" using System.Threading.Tasks; class C { T [|Foo|]<T>() where T : Task<object> { return default(T); } } "); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AsynchronousMethodNameShouldEndWithAsync)] public async Task Test_ValueTaskOfT() { await VerifyDiagnosticAsync(@" using System.Threading.Tasks; class C { ValueTask<object> [|Foo|]() { return default(ValueTask<object>); } } "); } [Fact, Trait(Traits.Analyzer, DiagnosticIdentifiers.AsynchronousMethodNameShouldEndWithAsync)] public async Task TestNoDiagnostic_EntryPointMethod() { await VerifyNoDiagnosticAsync(@" using System.Threading.Tasks; class Program { static async Task Main() { await Task.CompletedTask; } } "); } } }
23.258333
160
0.666786
[ "Apache-2.0" ]
joebone/Roslynator
src/Tests/Analyzers.Tests/RCS1046AsynchronousMethodNameShouldEndWithAsyncTests.cs
2,793
C#
using System; using System.Threading; using System.Threading.Tasks; using Volo.Abp.Domain.Repositories; namespace LINGYUN.Abp.MessageService.Chat { public interface IUserChatSettingRepository : IBasicRepository<UserChatSetting, long> { Task<bool> UserHasOpendImAsync(Guid userId, CancellationToken cancellationToken = default); Task<UserChatSetting> FindByUserIdAsync(Guid userId, CancellationToken cancellationToken = default); } }
33.071429
108
0.786177
[ "MIT" ]
FanShiYou/abp-vue-admin-element-typescript
aspnet-core/modules/message/LINGYUN.Abp.MessageService.Domain/LINGYUN/Abp/MessageService/Chat/IUserChatSettingRepository.cs
465
C#
using System.Globalization; using UnityEngine; namespace UnityDataLogging.LoggingPresets { [RequireComponent(typeof(Rigidbody))] public class RigidBodyLogger : Utility.Logger { // Log the kinematic properties of the rigidbody this script is attached to. [HideInInspector] public string[] reportHeaders = new string[13] { "Position X", "Position Y", "Position Z", "Rotation X", "Rotation Y", "Rotation Z", "Rotation W", "LinVelocity X", "LinVelocity Y", "LinVelocity Z", "AngVelocity X", "AngVelocity Y", "AngVelocity Z", }; Rigidbody _body; Vector3 _bodyPos; Quaternion _bodyRot; [Header("Logger Specific Settings")] // Create a header for any logger specific settings [SerializeField] public string fileNamePrefix = "RB"; public void Start() { _body = GetComponent<Rigidbody>(); _bodyPos = _body.transform.position; _bodyRot = _body.transform.rotation; Initialize(); } public string[] GetData() { string[] strings = new string[13] { _bodyPos.x.ToString(CultureInfo.InvariantCulture), _bodyPos.y.ToString(CultureInfo.InvariantCulture), _bodyPos.z.ToString(CultureInfo.InvariantCulture), _bodyRot.x.ToString(CultureInfo.InvariantCulture), _bodyRot.y.ToString(CultureInfo.InvariantCulture), _bodyRot.z.ToString(CultureInfo.InvariantCulture), _bodyRot.w.ToString(CultureInfo.InvariantCulture), _body.velocity.x.ToString(CultureInfo.InvariantCulture), _body.velocity.y.ToString(CultureInfo.InvariantCulture), _body.velocity.z.ToString(CultureInfo.InvariantCulture), _body.angularVelocity.x.ToString(CultureInfo.InvariantCulture), _body.angularVelocity.y.ToString(CultureInfo.InvariantCulture), _body.angularVelocity.z.ToString(CultureInfo.InvariantCulture), }; return strings; } } }
35.359375
96
0.593902
[ "MIT" ]
Avdbergnmf/UnityDataLogging
LoggingPresets/RigidBodyLogger.cs
2,265
C#
using System; using System.Reactive.Linq; using System.Threading; using System.Threading.Tasks; namespace ReactiveUI.Samples.Basics.ViewModels { public class MainViewModel : ReactiveObject { public MainViewModel() { ////RxApp.MainThreadScheduler = new DispatcherScheduler(Application.Current.Dispatcher); Task.Factory.StartNew(() => { while (true) { if (Progress == 100) { Progress = 0; } Progress++; Thread.Sleep(Progress%10 == 0 ? 2000 : 400); } }); //Throttling the updates for the SlowProgress, Actually we can accomplish it with a few ways //@xpaulbettsx is there a better way? // 1: this.ObservableForProperty(vm => vm.Progress).Throttle(TimeSpan.FromSeconds(1)).Subscribe(c => { SlowProgress = Progress; }); // 2: this.WhenAny(vm => vm.Progress, model => true).Throttle(TimeSpan.FromSeconds(1), RxApp.MainThreadScheduler). Subscribe(c => SlowProgress2 = Progress); Person = new PersonViewModel(); Calculator = new CalculatorViewModel(); } private int _Progress; public int Progress { get { return _Progress; } set { this.RaiseAndSetIfChanged(ref _Progress, value); } } private int _SlowProgress; public int SlowProgress { get { return _SlowProgress; } set { this.RaiseAndSetIfChanged(ref _SlowProgress, value); } } private int _SlowProgress2; public int SlowProgress2 { get { return _SlowProgress2; } set { this.RaiseAndSetIfChanged(ref _SlowProgress2, value); } } private PersonViewModel _Person; public PersonViewModel Person { get { return _Person; } set { this.RaiseAndSetIfChanged(ref _Person, value); } } private CalculatorViewModel _Calculator; public CalculatorViewModel Calculator { get { return _Calculator; } set { this.RaiseAndSetIfChanged(ref _Calculator, value); } } } }
27.303371
120
0.531687
[ "MIT" ]
behroozbc/ReactiveUI.Samples
wpf/ReactiveUI.Samples.Basics/ViewModels/MainViewModel.cs
2,432
C#
// <copyright file="ISignUpUseCase.cs" company="Ivan Paulovich"> // Copyright © Ivan Paulovich. All rights reserved. // </copyright> namespace Application.UseCases.SignUp { using System.Threading.Tasks; /// <summary> /// <see href="https://github.com/ivanpaulovich/clean-architecture-manga/wiki/Domain-Driven-Design-Patterns#use-case"> /// Use /// Case Domain-Driven Design Pattern /// </see> /// . /// </summary> public interface ISignUpUseCase { /// <summary> /// Executes the Use Case. /// </summary> /// <returns></returns> Task Execute(); /// <summary> /// Sets the Output Port. /// </summary> /// <param name="outputPort">Output Port</param> void SetOutputPort(IOutputPort outputPort); } }
27.677419
126
0.567599
[ "Apache-2.0" ]
BrunoMoureau/clean-arch-core-3.1
src/Application/UseCases/SignUp/ISignUpUseCase.cs
859
C#
using System; using System.Collections.Generic; using System.Text; namespace Slipe.Shared.Exceptions { /// <summary> /// Exception raised when a wrapped MTA function cannot find a requested element /// </summary> public class NullElementException : System.Exception { public NullElementException(string message) : base (message) { } } }
24.733333
84
0.700809
[ "Apache-2.0" ]
Citizen01/Slipe-Core
Slipe/Core/Source/SlipeShared/Exceptions/NullElementException.cs
373
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** 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.Kubernetes.Types.Inputs.Argoproj.V1Alpha1 { public class ArgoCDSpecRedisResourcesLimitsArgs : Pulumi.ResourceArgs { public ArgoCDSpecRedisResourcesLimitsArgs() { } } }
25.35
81
0.727811
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/argocd-operator/dotnet/Kubernetes/Crds/Operators/ArgocdOperator/Argoproj/V1Alpha1/Inputs/ArgoCDSpecRedisResourcesLimitsArgs.cs
507
C#