content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using System.Collections.Generic; using ICSharpCode.NRefactory.Ast; using B = Boo.Lang.Compiler.Ast; namespace NRefactoryToBooConverter { partial class ConvertVisitor { public object VisitCompilationUnit(CompilationUnit compilationUnit, object data) { module = new B.Module(); module.LexicalInfo = new B.LexicalInfo(fileName, 1, 1); compilationUnit.AcceptChildren(this, data); if (entryPointMethod != null) { bool allMembersAreStatic = true; foreach (B.TypeMember member in entryPointMethod.DeclaringType.Members) { allMembersAreStatic &= member.IsStatic; } if (allMembersAreStatic) { entryPointMethod.DeclaringType.Attributes.Add(MakeAttribute(("module"))); } else { lastLexicalInfo = entryPointMethod.LexicalInfo; B.Expression expr = MakeReferenceExpression(entryPointMethod.DeclaringType.Name + ".Main"); B.MethodInvocationExpression mie = new B.MethodInvocationExpression(lastLexicalInfo, expr); if (entryPointMethod.Parameters.Count > 0) { mie.Arguments.Add(MakeReferenceExpression("argv")); } B.SimpleTypeReference ret = entryPointMethod.ReturnType as B.SimpleTypeReference; if (ret.Name == "void" || ret.Name == "System.Void") module.Globals.Add(new B.ExpressionStatement(mie)); else module.Globals.Add(new B.ReturnStatement(lastLexicalInfo, mie, null)); } } B.Module tmp = module; module = null; return tmp; } public object VisitNamespaceDeclaration(NamespaceDeclaration namespaceDeclaration, object data) { if (module.Namespace != null) { AddError(namespaceDeclaration, "Only one namespace declaration per file is supported."); return null; } module.Namespace = new B.NamespaceDeclaration(GetLexicalInfo(namespaceDeclaration)); module.Namespace.Name = namespaceDeclaration.Name; return namespaceDeclaration.AcceptChildren(this, data); } public object VisitUsingDeclaration(UsingDeclaration usingDeclaration, object data) { foreach (Using u in usingDeclaration.Usings) { VisitUsing(u, data); } return null; } public object VisitUsing(Using @using, object data) { B.Import import; if (@using.IsAlias) { import = new B.Import(@using.Alias.Type, null, new B.ReferenceExpression(@using.Name)); import.LexicalInfo = GetLexicalInfo(@using); } else { import = new B.Import(GetLexicalInfo(@using), @using.Name); } module.Imports.Add(import); return import; } B.TypeDefinition currentType; public object VisitTypeDeclaration(TypeDeclaration typeDeclaration, object data) { if (typeDeclaration.Templates.Count > 0) { AddError(typeDeclaration, "Generic type definitions are not supported."); } B.TypeDefinition oldType = currentType; B.TypeDefinition typeDef; switch (typeDeclaration.Type) { case ClassType.Class: typeDef = new B.ClassDefinition(GetLexicalInfo(typeDeclaration)); break; case ClassType.Interface: typeDef = new B.InterfaceDefinition(GetLexicalInfo(typeDeclaration)); break; case ClassType.Enum: typeDef = new B.EnumDefinition(GetLexicalInfo(typeDeclaration)); break; case ClassType.Struct: typeDef = new B.StructDefinition(GetLexicalInfo(typeDeclaration)); break; case ClassType.Module: typeDef = new B.ClassDefinition(GetLexicalInfo(typeDeclaration)); typeDeclaration.Modifier |= Modifiers.Static; break; default: AddError(typeDeclaration, "Unknown class type."); return null; } if (currentType != null) typeDef.Modifiers = ConvertModifier(typeDeclaration, B.TypeMemberModifiers.Private); else typeDef.Modifiers = ConvertModifier(typeDeclaration, B.TypeMemberModifiers.Internal); typeDef.Name = typeDeclaration.Name; typeDef.EndSourceLocation = GetLocation(typeDeclaration.EndLocation); ConvertAttributes(typeDeclaration.Attributes, typeDef.Attributes); ConvertTypeReferences(typeDeclaration.BaseTypes, typeDef.BaseTypes); if (currentType != null) currentType.Members.Add(typeDef); else module.Members.Add(typeDef); currentType = typeDef; typeDeclaration.AcceptChildren(this, data); currentType = oldType; return typeDef; } public object VisitDelegateDeclaration(DelegateDeclaration delegateDeclaration, object data) { B.CallableDefinition cd = new B.CallableDefinition(GetLexicalInfo(delegateDeclaration)); cd.Name = delegateDeclaration.Name; ConvertAttributes(delegateDeclaration.Attributes, cd.Attributes); cd.Modifiers = ConvertModifier(delegateDeclaration, B.TypeMemberModifiers.Private); ConvertParameters(delegateDeclaration.Parameters, cd.Parameters); cd.ReturnType = ConvertTypeReference(delegateDeclaration.ReturnType); if (currentType != null) currentType.Members.Add(cd); else module.Members.Add(cd); return cd; } void ConvertAttributes(List<AttributeSection> sections, B.AttributeCollection col) { foreach (AttributeSection s in sections) { if (s.AttributeTarget.Length > 0) { AddError(s, "Attribute target not supported"); continue; } foreach (ICSharpCode.NRefactory.Ast.Attribute a in s.Attributes) { col.Add((B.Attribute)VisitAttribute(a, null)); } } } public object VisitAttribute(ICSharpCode.NRefactory.Ast.Attribute a, object data) { B.Attribute att = new B.Attribute(GetLexicalInfo(a), a.Name); att.EndSourceLocation = GetLocation(a.EndLocation); ConvertExpressions(a.PositionalArguments, att.Arguments); foreach (NamedArgumentExpression nae in a.NamedArguments) { B.Expression expr = ConvertExpression(nae.Expression); if (expr != null) { att.NamedArguments.Add(new B.ExpressionPair(new B.ReferenceExpression(nae.Name), expr)); } } return att; } public object VisitAttributeSection(AttributeSection s, object data) { if (s.AttributeTarget.Equals("assembly", StringComparison.OrdinalIgnoreCase)) { foreach (ICSharpCode.NRefactory.Ast.Attribute a in s.Attributes) { module.AssemblyAttributes.Add((B.Attribute)VisitAttribute(a, null)); } } else { AddError(s, "Attribute must have the target 'assembly'"); } return null; } // Some classes are handled by their parent (TemplateDefinition by TypeDeclaration/MethodDeclaration etc.) // so we don't need to implement Visit for them. public object VisitTemplateDefinition(TemplateDefinition templateDefinition, object data) { throw new ApplicationException("Visited TemplateDefinition."); } public object VisitInterfaceImplementation(InterfaceImplementation interfaceImplementation, object data) { throw new ApplicationException("Visited InterfaceImplementation."); } public object VisitOptionDeclaration(OptionDeclaration optionDeclaration, object data) { AddError(optionDeclaration, "Option statement is not supported."); return null; } public object VisitExternAliasDirective(ExternAliasDirective externAliasDirective, object data) { AddError(externAliasDirective, "'extern alias' directive is not supported."); return null; } } }
36.019608
108
0.738432
[ "MIT" ]
Plankankul/SharpDevelop-w-Framework
src/AddIns/BackendBindings/Boo/NRefactoryToBooConverter/Project/ConvertVisitorGlobal.cs
7,350
C#
using Hassie.ConcussionEngine.Engine.Component.Registry; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hassie.ConcussionEngine.Engine.Component.Manager { /// <summary> /// The component manager manages the component registries /// and handles the termination of entities. /// </summary> public class ComponentManager : IComponentManager, IComponentTerminator { // Component registries. // The key is the component type the registry handles. private readonly IDictionary<Type, IComponentRegistry> registries; /// <summary> /// Constructor for the component manager. /// </summary> public ComponentManager() { // Initialise registry map. registries = new Dictionary<Type, IComponentRegistry>(); } public bool ContainsComponent<C>(int entityID) where C : struct, IComponent { return registries[typeof(C)].Contains(entityID); } public bool ContainsRegistry<C>() where C : struct, IComponent { return registries.ContainsKey(typeof(C)); } public C GetComponent<C>(int entityID) where C : struct, IComponent { return ((IComponentRegistry<C>)registries[typeof(C)]).Get(entityID); } public IComponentRegistry GetRegistry<C>() where C : struct, IComponent { return registries[typeof(C)]; } public IComponentManager RegisterType<C, R>() where C : struct, IComponent where R : IComponentRegistry<C>, new() { // Initialise registry. R registry = new R(); // Add registry. registries.Add(typeof(C), registry); // Return instance. return this; } public IComponentManager RemoveComponent<C>(int entityID) where C : struct, IComponent { // Remove component. registries[typeof(C)].Remove(entityID); // Return instance. return this; } public IComponentManager SetComponent<C>(C component) where C : struct, IComponent { // Set component. ((IComponentRegistry<C>)registries[typeof(C)]).Set(component); // Return instance. return this; } public void TerminateEntity(int entityID) { // Run through all registries and remove component. ICollection<IComponentRegistry> componentRegistries = registries.Values; foreach (IComponentRegistry registry in componentRegistries) { registry.Remove(entityID); } } } }
30.758242
94
0.598071
[ "Apache-2.0" ]
hassieswift621/concussion-engine
Hassie.ConcussionEngine.Engine/Component/Manager/ComponentManager.cs
2,801
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using DurableTask.Core; using DurableTask.Core.History; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.WebApiCompatShim; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.WebJobs.Extensions.DurableTask { /// <summary> /// Client for starting, querying, terminating, and raising events to orchestration instances. /// </summary> internal class DurableClient : IDurableClient, #pragma warning disable 618 DurableOrchestrationClientBase // for v1 legacy compatibility. #pragma warning restore 618 { private const string DefaultVersion = ""; private const int MaxInstanceIdLength = 256; private static readonly JValue NullJValue = JValue.CreateNull(); private readonly TaskHubClient client; private readonly string hubName; private readonly DurabilityProvider durabilityProvider; private readonly HttpApiHandler httpApiHandler; private readonly EndToEndTraceHelper traceHelper; private readonly DurableTaskExtension config; private readonly DurableClientAttribute attribute; // for rehydrating a Client after a webhook private readonly MessagePayloadDataConverter messageDataConverter; internal DurableClient( DurabilityProvider serviceClient, DurableTaskExtension config, HttpApiHandler httpHandler, DurableClientAttribute attribute) { this.config = config ?? throw new ArgumentNullException(nameof(config)); this.messageDataConverter = config.MessageDataConverter; this.client = new TaskHubClient(serviceClient, this.messageDataConverter); this.durabilityProvider = serviceClient; this.traceHelper = config.TraceHelper; this.httpApiHandler = httpHandler; this.hubName = attribute.TaskHub ?? config.Options.HubName; this.attribute = attribute; } public string TaskHubName => this.hubName; internal DurabilityProvider DurabilityProvider => this.durabilityProvider; /// <inheritdoc /> string IDurableOrchestrationClient.TaskHubName => this.TaskHubName; string IDurableClient.TaskHubName => this.TaskHubName; string IDurableEntityClient.TaskHubName => this.TaskHubName; /// <inheritdoc /> HttpResponseMessage IDurableOrchestrationClient.CreateCheckStatusResponse(HttpRequestMessage request, string instanceId, bool returnInternalServerErrorOnFailure) { return this.CreateCheckStatusResponse(request, instanceId, this.attribute, returnInternalServerErrorOnFailure); } /// <inheritdoc /> IActionResult IDurableOrchestrationClient.CreateCheckStatusResponse(HttpRequest request, string instanceId, bool returnInternalServerErrorOnFailure) { HttpRequestMessage requestMessage = ConvertHttpRequestMessage(request); HttpResponseMessage responseMessage = ((IDurableOrchestrationClient)this).CreateCheckStatusResponse(requestMessage, instanceId, returnInternalServerErrorOnFailure); return ConvertHttpResponseMessage(responseMessage); } /// <inheritdoc /> HttpManagementPayload IDurableOrchestrationClient.CreateHttpManagementPayload(string instanceId) { return this.CreateHttpManagementPayload(instanceId, this.attribute.TaskHub, this.attribute.ConnectionName); } /// <inheritdoc /> async Task<HttpResponseMessage> IDurableOrchestrationClient.WaitForCompletionOrCreateCheckStatusResponseAsync(HttpRequestMessage request, string instanceId, TimeSpan? timeout, TimeSpan? retryInterval) { return await this.WaitForCompletionOrCreateCheckStatusResponseAsync( request, instanceId, this.attribute, timeout ?? TimeSpan.FromSeconds(10), retryInterval ?? TimeSpan.FromSeconds(1)); } /// <inheritdoc /> async Task<IActionResult> IDurableOrchestrationClient.WaitForCompletionOrCreateCheckStatusResponseAsync(HttpRequest request, string instanceId, TimeSpan? timeout, TimeSpan? retryInterval) { HttpRequestMessage requestMessage = ConvertHttpRequestMessage(request); HttpResponseMessage responseMessage = await ((IDurableOrchestrationClient)this).WaitForCompletionOrCreateCheckStatusResponseAsync(requestMessage, instanceId, timeout, retryInterval); return ConvertHttpResponseMessage(responseMessage); } /// <inheritdoc /> async Task<string> IDurableOrchestrationClient.StartNewAsync<T>(string orchestratorFunctionName, string instanceId, T input) { if (this.ClientReferencesCurrentApp(this)) { this.config.ThrowIfFunctionDoesNotExist(orchestratorFunctionName, FunctionType.Orchestrator); } if (string.IsNullOrEmpty(instanceId)) { instanceId = Guid.NewGuid().ToString("N"); } else if (instanceId.StartsWith("@")) { throw new ArgumentException(nameof(instanceId), "Orchestration instance ids must not start with @."); } else if (instanceId.Any(IsInvalidCharacter)) { throw new ArgumentException(nameof(instanceId), "Orchestration instance ids must not contain /, \\, #, ?, or control characters."); } if (instanceId.Length > MaxInstanceIdLength) { throw new ArgumentException($"Instance ID lengths must not exceed {MaxInstanceIdLength} characters."); } var dedupeStatuses = this.GetStatusesNotToOverride(); Task<OrchestrationInstance> createTask = this.client.CreateOrchestrationInstanceAsync( orchestratorFunctionName, DefaultVersion, instanceId, input, null, dedupeStatuses); this.traceHelper.FunctionScheduled( this.TaskHubName, orchestratorFunctionName, instanceId, reason: "NewInstance", functionType: FunctionType.Orchestrator, isReplay: false); OrchestrationInstance instance = await createTask; return instance.InstanceId; } private OrchestrationStatus[] GetStatusesNotToOverride() { var overridableStates = this.config.Options.OverridableExistingInstanceStates; if (overridableStates == OverridableStates.NonRunningStates) { return new OrchestrationStatus[] { OrchestrationStatus.Running, OrchestrationStatus.ContinuedAsNew, OrchestrationStatus.Pending, }; } return new OrchestrationStatus[0]; } private static bool IsInvalidCharacter(char c) { return c == '/' || c == '\\' || c == '?' || c == '#' || char.IsControl(c); } /// <inheritdoc /> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate", Justification = "This method does not work with the .NET Framework event model.")] Task IDurableOrchestrationClient.RaiseEventAsync(string instanceId, string eventName, object eventData) { if (string.IsNullOrEmpty(eventName)) { throw new ArgumentNullException(nameof(eventName)); } return this.RaiseEventInternalAsync(this.client, this.TaskHubName, instanceId, eventName, eventData); } /// <inheritdoc /> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1030:UseEventsWhereAppropriate", Justification = "This method does not work with the .NET Framework event model.")] Task IDurableOrchestrationClient.RaiseEventAsync(string taskHubName, string instanceId, string eventName, object eventData, string connectionName) { if (string.IsNullOrEmpty(taskHubName)) { throw new ArgumentNullException(nameof(taskHubName)); } if (string.IsNullOrEmpty(eventName)) { throw new ArgumentNullException(nameof(eventName)); } if (string.IsNullOrEmpty(connectionName)) { connectionName = this.attribute.ConnectionName; } var attribute = new DurableClientAttribute { TaskHub = taskHubName, ConnectionName = connectionName, }; TaskHubClient taskHubClient = ((DurableClient)this.config.GetClient(attribute)).client; return this.RaiseEventInternalAsync(taskHubClient, taskHubName, instanceId, eventName, eventData); } /// <inheritdoc /> Task IDurableEntityClient.SignalEntityAsync(EntityId entityId, string operationName, object operationInput, string taskHubName, string connectionName) { if (string.IsNullOrEmpty(taskHubName)) { return this.SignalEntityAsyncInternal(this, this.TaskHubName, entityId, null, operationName, operationInput); } else { if (string.IsNullOrEmpty(connectionName)) { connectionName = this.attribute.ConnectionName; } var attribute = new DurableClientAttribute { TaskHub = taskHubName, ConnectionName = connectionName, }; var durableClient = (DurableClient)this.config.GetClient(attribute); return this.SignalEntityAsyncInternal(durableClient, taskHubName, entityId, null, operationName, operationInput); } } /// <inheritdoc /> Task IDurableEntityClient.SignalEntityAsync(EntityId entityId, DateTime scheduledTimeUtc, string operationName, object operationInput, string taskHubName, string connectionName) { if (string.IsNullOrEmpty(taskHubName)) { return this.SignalEntityAsyncInternal(this, this.TaskHubName, entityId, scheduledTimeUtc, operationName, operationInput); } else { if (string.IsNullOrEmpty(connectionName)) { connectionName = this.attribute.ConnectionName; } var attribute = new DurableClientAttribute { TaskHub = taskHubName, ConnectionName = connectionName, }; var durableClient = (DurableClient)this.config.GetClient(attribute); return this.SignalEntityAsyncInternal(durableClient, taskHubName, entityId, scheduledTimeUtc, operationName, operationInput); } } private async Task SignalEntityAsyncInternal(DurableClient durableClient, string hubName, EntityId entityId, DateTime? scheduledTimeUtc, string operationName, object operationInput) { var entityKey = entityId.EntityKey; if (entityKey.Any(IsInvalidCharacter)) { throw new ArgumentException(nameof(entityKey), "Entity keys must not contain /, \\, #, ?, or control characters."); } if (operationName == null) { throw new ArgumentNullException(nameof(operationName)); } if (this.ClientReferencesCurrentApp(durableClient)) { this.config.ThrowIfFunctionDoesNotExist(entityId.EntityName, FunctionType.Entity); } var guid = Guid.NewGuid(); // unique id for this request var instanceId = EntityId.GetSchedulerIdFromEntityId(entityId); var instance = new OrchestrationInstance() { InstanceId = instanceId }; var request = new RequestMessage() { ParentInstanceId = null, // means this was sent by a client ParentExecutionId = null, Id = guid, IsSignal = true, Operation = operationName, ScheduledTime = scheduledTimeUtc, }; if (operationInput != null) { request.SetInput(operationInput, this.messageDataConverter); } var jrequest = JToken.FromObject(request, this.messageDataConverter.JsonSerializer); var eventName = scheduledTimeUtc.HasValue ? EntityMessageEventNames.ScheduledRequestMessageEventName(scheduledTimeUtc.Value) : EntityMessageEventNames.RequestMessageEventName; await durableClient.client.RaiseEventAsync(instance, eventName, jrequest); this.traceHelper.FunctionScheduled( hubName, entityId.EntityName, EntityId.GetSchedulerIdFromEntityId(entityId), reason: $"EntitySignal:{operationName}", functionType: FunctionType.Entity, isReplay: false); } private bool ClientReferencesCurrentApp(DurableClient client) { return this.TaskHubMatchesCurrentApp(client) && this.ConnectionNameMatchesCurrentApp(client); } private bool TaskHubMatchesCurrentApp(DurableClient client) { var taskHubName = this.config.Options.HubName; return client.TaskHubName.Equals(taskHubName); } private bool ConnectionNameMatchesCurrentApp(DurableClient client) { return this.DurabilityProvider.ConnectionNameMatches(client.DurabilityProvider); } /// <inheritdoc /> async Task IDurableOrchestrationClient.TerminateAsync(string instanceId, string reason) { OrchestrationState state = await this.GetOrchestrationInstanceStateAsync(instanceId); if (IsOrchestrationRunning(state)) { // Terminate events are not supposed to target any particular execution ID. // We need to clear it to avoid sending messages to an expired ContinueAsNew instance. state.OrchestrationInstance.ExecutionId = null; await this.client.TerminateInstanceAsync(state.OrchestrationInstance, reason); this.traceHelper.FunctionTerminated(this.TaskHubName, state.Name, instanceId, reason); } else { this.traceHelper.ExtensionWarningEvent( hubName: this.TaskHubName, functionName: state.Name, instanceId: instanceId, message: $"Cannot terminate orchestration instance in {state.Status} state"); throw new InvalidOperationException($"Cannot terminate the orchestration instance {instanceId} because instance is in {state.Status} state"); } } /// <inheritdoc /> async Task IDurableOrchestrationClient.RewindAsync(string instanceId, string reason) { OrchestrationState state = await this.GetOrchestrationInstanceStateAsync(instanceId); if (state.OrchestrationStatus != OrchestrationStatus.Failed) { throw new InvalidOperationException("The rewind operation is only supported on failed orchestration instances."); } await this.DurabilityProvider.RewindAsync(instanceId, reason); this.traceHelper.FunctionRewound(this.TaskHubName, state.Name, instanceId, reason); } /// <inheritdoc /> async Task<DurableOrchestrationStatus> IDurableOrchestrationClient.GetStatusAsync(string instanceId, bool showHistory, bool showHistoryOutput, bool showInput) { IList<OrchestrationState> stateList; try { stateList = await this.DurabilityProvider.GetOrchestrationStateWithInputsAsync(instanceId, showInput); } catch (NotImplementedException) { // TODO: Ignore the show input flag. Should consider logging a warning. stateList = await this.client.ServiceClient.GetOrchestrationStateAsync(instanceId, allExecutions: false); } OrchestrationState state = stateList?.FirstOrDefault(); if (state == null || state.OrchestrationInstance == null) { return null; } return await GetDurableOrchestrationStatusAsync(state, this.client, showHistory, showHistoryOutput); } /// <inheritdoc /> async Task<IList<DurableOrchestrationStatus>> IDurableOrchestrationClient.GetStatusAsync(DateTime? createdTimeFrom, DateTime? createdTimeTo, IEnumerable<OrchestrationRuntimeStatus> runtimeStatus, CancellationToken cancellationToken) { return await this.GetAllStatusHelper(createdTimeFrom, createdTimeTo, runtimeStatus, cancellationToken); } private async Task<IList<DurableOrchestrationStatus>> GetAllStatusHelper(DateTime? createdTimeFrom, DateTime? createdTimeTo, IEnumerable<OrchestrationRuntimeStatus> runtimeStatus, CancellationToken cancellationToken) { var condition = this.CreateConditionFromParameters(createdTimeFrom, createdTimeTo, runtimeStatus); var response = await ((IDurableOrchestrationClient)this).ListInstancesAsync(condition, cancellationToken); return (IList<DurableOrchestrationStatus>)response.DurableOrchestrationState; } private OrchestrationStatusQueryCondition CreateConditionFromParameters(DateTime? createdTimeFrom, DateTime? createdTimeTo, IEnumerable<OrchestrationRuntimeStatus> runtimeStatus) { var condition = new OrchestrationStatusQueryCondition(); if (createdTimeFrom != null) { condition.CreatedTimeFrom = createdTimeFrom.Value; } if (createdTimeTo != null) { condition.CreatedTimeTo = createdTimeTo.Value; } if (runtimeStatus != null) { condition.RuntimeStatus = runtimeStatus; } return condition; } Task<EntityStateResponse<T>> IDurableEntityClient.ReadEntityStateAsync<T>(EntityId entityId, string taskHubName, string connectionName) { if (string.IsNullOrEmpty(taskHubName)) { return this.ReadEntityStateAsync<T>(this.DurabilityProvider, entityId); } else { if (string.IsNullOrEmpty(connectionName)) { connectionName = this.attribute.ConnectionName; } var attribute = new DurableClientAttribute { TaskHub = taskHubName, ConnectionName = connectionName, }; DurabilityProvider durabilityProvider = ((DurableClient)this.config.GetClient(attribute)).DurabilityProvider; return this.ReadEntityStateAsync<T>(durabilityProvider, entityId); } } private async Task<EntityStateResponse<T>> ReadEntityStateAsync<T>(DurabilityProvider provider, EntityId entityId) { string entityState = await provider.RetrieveSerializedEntityState(entityId, this.messageDataConverter.JsonSettings); return new EntityStateResponse<T>() { EntityExists = entityState != null, EntityState = this.messageDataConverter.Deserialize<T>(entityState), }; } /// <inheritdoc /> async Task<PurgeHistoryResult> IDurableOrchestrationClient.PurgeInstanceHistoryAsync(string instanceId) { return await this.DurabilityProvider.PurgeInstanceHistoryByInstanceId(instanceId); } /// <inheritdoc /> async Task<PurgeHistoryResult> IDurableOrchestrationClient.PurgeInstanceHistoryAsync(DateTime createdTimeFrom, DateTime? createdTimeTo, IEnumerable<OrchestrationStatus> runtimeStatus) { int numInstancesDeleted = await this.DurabilityProvider.PurgeHistoryByFilters(createdTimeFrom, createdTimeTo, runtimeStatus); return new PurgeHistoryResult(numInstancesDeleted); } Task<OrchestrationStatusQueryResult> IDurableOrchestrationClient.GetStatusAsync( OrchestrationStatusQueryCondition condition, CancellationToken cancellationToken) { return ((IDurableOrchestrationClient)this).ListInstancesAsync(condition, cancellationToken); } /// <inheritdoc /> Task<OrchestrationStatusQueryResult> IDurableOrchestrationClient.ListInstancesAsync( OrchestrationStatusQueryCondition condition, CancellationToken cancellationToken) { return this.DurabilityProvider.GetOrchestrationStateWithPagination(condition, cancellationToken); } /// <inheritdoc /> async Task<EntityQueryResult> IDurableEntityClient.ListEntitiesAsync(EntityQuery query, CancellationToken cancellationToken) { var condition = new OrchestrationStatusQueryCondition(query); var result = await ((IDurableClient)this).ListInstancesAsync(condition, cancellationToken); var entityResult = new EntityQueryResult(result); return entityResult; } private async Task<OrchestrationState> GetOrchestrationInstanceStateAsync(string instanceId) { return await GetOrchestrationInstanceStateAsync(this.client, instanceId); } private static async Task<OrchestrationState> GetOrchestrationInstanceStateAsync(TaskHubClient client, string instanceId) { if (string.IsNullOrEmpty(instanceId)) { throw new ArgumentNullException(nameof(instanceId)); } OrchestrationState state = await client.GetOrchestrationStateAsync(instanceId); if (state?.OrchestrationInstance == null) { throw new ArgumentException($"No instance with ID '{instanceId}' was found.", nameof(instanceId)); } return state; } private async Task RaiseEventInternalAsync( TaskHubClient taskHubClient, string taskHubName, string instanceId, string eventName, object eventData) { OrchestrationState status = await GetOrchestrationInstanceStateAsync(taskHubClient, instanceId); if (status == null) { return; } if (IsOrchestrationRunning(status)) { // External events are not supposed to target any particular execution ID. // We need to clear it to avoid sending messages to an expired ContinueAsNew instance. status.OrchestrationInstance.ExecutionId = null; await taskHubClient.RaiseEventAsync(status.OrchestrationInstance, eventName, eventData); this.traceHelper.FunctionScheduled( taskHubName, status.Name, instanceId, reason: "RaiseEvent:" + eventName, functionType: FunctionType.Orchestrator, isReplay: false); } else { this.traceHelper.ExtensionWarningEvent( hubName: taskHubName, functionName: status.Name, instanceId: instanceId, message: $"Cannot raise event for instance in {status.OrchestrationStatus} state"); throw new InvalidOperationException($"Cannot raise event {eventName} for orchestration instance {instanceId} because instance is in {status.OrchestrationStatus} state"); } } // Get a data structure containing status, terminate and send external event HTTP. internal HttpManagementPayload CreateHttpManagementPayload( string instanceId, string taskHubName, string connectionName) { return this.httpApiHandler.CreateHttpManagementPayload(instanceId, taskHubName, connectionName); } // Get a response that will wait for response from the durable function for predefined period of time before // pointing to our webhook handler. internal async Task<HttpResponseMessage> WaitForCompletionOrCreateCheckStatusResponseAsync( HttpRequestMessage request, string instanceId, DurableClientAttribute attribute, TimeSpan timeout, TimeSpan retryInterval) { return await this.httpApiHandler.WaitForCompletionOrCreateCheckStatusResponseAsync( request, instanceId, attribute, timeout, retryInterval); } private static bool IsOrchestrationRunning(OrchestrationState status) { return status.OrchestrationStatus == OrchestrationStatus.Running || status.OrchestrationStatus == OrchestrationStatus.Pending || status.OrchestrationStatus == OrchestrationStatus.ContinuedAsNew; } private static HttpRequestMessage ConvertHttpRequestMessage(HttpRequest request) { return new HttpRequestMessageFeature(request.HttpContext).HttpRequestMessage; } private static IActionResult ConvertHttpResponseMessage(HttpResponseMessage response) { var result = new ObjectResult(response); result.Formatters.Add(new HttpResponseMessageOutputFormatter()); return result; } private static async Task<DurableOrchestrationStatus> GetDurableOrchestrationStatusAsync(OrchestrationState orchestrationState, TaskHubClient client, bool showHistory, bool showHistoryOutput) { JArray historyArray = null; if (showHistory && orchestrationState.OrchestrationStatus != OrchestrationStatus.Pending) { string history = await client.GetOrchestrationHistoryAsync(orchestrationState.OrchestrationInstance); if (!string.IsNullOrEmpty(history)) { historyArray = MessagePayloadDataConverter.ConvertToJArray(history); var eventMapper = new Dictionary<string, EventIndexDateMapping>(); var indexList = new List<int>(); for (var i = 0; i < historyArray.Count; i++) { JObject historyItem = (JObject)historyArray[i]; if (Enum.TryParse(historyItem["EventType"].Value<string>(), out EventType eventType)) { // Changing the value of EventType from integer to string for better understanding in the history output historyItem["EventType"] = eventType.ToString(); switch (eventType) { case EventType.TaskScheduled: TrackNameAndScheduledTime(historyItem, eventType, i, eventMapper); historyItem.Remove("Version"); historyItem.Remove("Input"); break; case EventType.TaskCompleted: case EventType.TaskFailed: AddScheduledEventDataAndAggregate(ref eventMapper, "TaskScheduled", historyItem, indexList); historyItem["TaskScheduledId"]?.Parent.Remove(); if (!showHistoryOutput && eventType == EventType.TaskCompleted) { historyItem.Remove("Result"); } ConvertOutputToJToken(historyItem, showHistoryOutput && eventType == EventType.TaskCompleted); break; case EventType.SubOrchestrationInstanceCreated: TrackNameAndScheduledTime(historyItem, eventType, i, eventMapper); historyItem.Remove("Version"); historyItem.Remove("Input"); break; case EventType.SubOrchestrationInstanceCompleted: case EventType.SubOrchestrationInstanceFailed: AddScheduledEventDataAndAggregate(ref eventMapper, "SubOrchestrationInstanceCreated", historyItem, indexList); historyItem.Remove("TaskScheduledId"); if (!showHistoryOutput && eventType == EventType.SubOrchestrationInstanceCompleted) { historyItem.Remove("Result"); } ConvertOutputToJToken(historyItem, showHistoryOutput && eventType == EventType.SubOrchestrationInstanceCompleted); break; case EventType.ExecutionStarted: var functionName = historyItem["Name"]; historyItem.Remove("Name"); historyItem["FunctionName"] = functionName; historyItem.Remove("OrchestrationInstance"); historyItem.Remove("ParentInstance"); historyItem.Remove("Version"); historyItem.Remove("Tags"); historyItem.Remove("Input"); break; case EventType.ExecutionCompleted: if (Enum.TryParse(historyItem["OrchestrationStatus"].Value<string>(), out OrchestrationStatus orchestrationStatus)) { historyItem["OrchestrationStatus"] = orchestrationStatus.ToString(); } if (!showHistoryOutput) { historyItem.Remove("Result"); } ConvertOutputToJToken(historyItem, showHistoryOutput); break; case EventType.ExecutionTerminated: historyItem.Remove("Input"); break; case EventType.TimerFired: historyItem.Remove("TimerId"); break; case EventType.EventRaised: historyItem.Remove("Input"); break; case EventType.OrchestratorStarted: case EventType.OrchestratorCompleted: indexList.Add(i); break; } historyItem.Remove("EventId"); historyItem.Remove("IsPlayed"); } } var counter = 0; indexList.Sort(); foreach (var indexValue in indexList) { historyArray.RemoveAt(indexValue - counter); counter++; } } } return ConvertOrchestrationStateToStatus(orchestrationState, historyArray); } // Get a response that will point to our webhook handler. internal HttpResponseMessage CreateCheckStatusResponse( HttpRequestMessage request, string instanceId, DurableClientAttribute attribute, bool returnInternalServerErrorOnFailure = false) { return this.httpApiHandler.CreateCheckStatusResponse(request, instanceId, attribute, returnInternalServerErrorOnFailure); } private static void TrackNameAndScheduledTime(JObject historyItem, EventType eventType, int index, Dictionary<string, EventIndexDateMapping> eventMapper) { eventMapper.Add($"{eventType}_{historyItem["EventId"]}", new EventIndexDateMapping { Index = index, Name = (string)historyItem["Name"], Date = (DateTime)historyItem["Timestamp"] }); } private static void AddScheduledEventDataAndAggregate(ref Dictionary<string, EventIndexDateMapping> eventMapper, string prefix, JToken historyItem, List<int> indexList) { if (eventMapper.TryGetValue($"{prefix}_{historyItem["TaskScheduledId"]}", out EventIndexDateMapping taskScheduledData)) { historyItem["ScheduledTime"] = taskScheduledData.Date; historyItem["FunctionName"] = taskScheduledData.Name; indexList.Add(taskScheduledData.Index); } } internal static DurableOrchestrationStatus ConvertOrchestrationStateToStatus(OrchestrationState orchestrationState, JArray historyArray = null) { return new DurableOrchestrationStatus { Name = orchestrationState.Name, InstanceId = orchestrationState.OrchestrationInstance.InstanceId, CreatedTime = orchestrationState.CreatedTime, LastUpdatedTime = orchestrationState.LastUpdatedTime, RuntimeStatus = (OrchestrationRuntimeStatus)orchestrationState.OrchestrationStatus, CustomStatus = ParseToJToken(orchestrationState.Status), Input = ParseToJToken(orchestrationState.Input), Output = ParseToJToken(orchestrationState.Output), History = historyArray, }; } internal static JToken ParseToJToken(string value) { if (value == null) { return NullJValue; } // Ignore whitespace value = value.Trim(); if (value.Length == 0) { return string.Empty; } try { return MessagePayloadDataConverter.ConvertToJToken(value); } catch (JsonReaderException) { // Return the raw string value as the fallback. This is common in terminate scenarios. return value; } } private static void ConvertOutputToJToken(JObject jsonObject, bool showHistoryOutput) { if (!showHistoryOutput) { return; } jsonObject["Result"] = ParseToJToken((string)jsonObject["Result"]); } /// <inheritdoc/> Task<string> IDurableOrchestrationClient.StartNewAsync(string orchestratorFunctionName, string instanceId) { return ((IDurableOrchestrationClient)this).StartNewAsync<object>(orchestratorFunctionName, instanceId, null); } /// <inheritdoc/> Task<string> IDurableOrchestrationClient.StartNewAsync<T>(string orchestratorFunctionName, T input) { return ((IDurableOrchestrationClient)this).StartNewAsync<T>(orchestratorFunctionName, string.Empty, input); } /// <inheritdoc/> Task IDurableEntityClient.SignalEntityAsync<TEntityInterface>(string entityKey, Action<TEntityInterface> operation) { return ((IDurableEntityClient)this).SignalEntityAsync<TEntityInterface>(new EntityId(DurableEntityProxyHelpers.ResolveEntityName<TEntityInterface>(), entityKey), operation); } /// <inheritdoc/> Task IDurableEntityClient.SignalEntityAsync<TEntityInterface>(string entityKey, DateTime scheduledTimeUtc, Action<TEntityInterface> operation) { return ((IDurableEntityClient)this).SignalEntityAsync<TEntityInterface>(new EntityId(DurableEntityProxyHelpers.ResolveEntityName<TEntityInterface>(), entityKey), scheduledTimeUtc, operation); } /// <inheritdoc/> Task IDurableEntityClient.SignalEntityAsync<TEntityInterface>(EntityId entityId, Action<TEntityInterface> operation) { var proxyContext = new EntityClientProxy(this); var proxy = EntityProxyFactory.Create<TEntityInterface>(proxyContext, entityId); operation(proxy); if (proxyContext.SignalTask == null) { throw new InvalidOperationException("The operation action must perform an operation on the entity"); } return proxyContext.SignalTask; } /// <inheritdoc/> Task IDurableEntityClient.SignalEntityAsync<TEntityInterface>(EntityId entityId, DateTime scheduledTimeUtc, Action<TEntityInterface> operation) { var proxyContext = new EntityClientProxy(this, scheduledTimeUtc); var proxy = EntityProxyFactory.Create<TEntityInterface>(proxyContext, entityId); operation(proxy); if (proxyContext.SignalTask == null) { throw new InvalidOperationException("The operation action must perform an operation on the entity"); } return proxyContext.SignalTask; } private class EventIndexDateMapping { public int Index { get; set; } public DateTime Date { get; set; } public string Name { get; set; } } } }
45.335274
240
0.608916
[ "MIT" ]
scbedd/azure-functions-durable-extension
src/WebJobs.Extensions.DurableTask/ContextImplementations/DurableClient.cs
38,945
C#
using System.Collections.Generic; using System.Linq; using AcceptFramework.Domain.Evaluation; namespace AcceptFramework.Repository.Evaluation { internal static class EvaluationQuestionItemAnswersRepository { public static IEnumerable<EvaluationQuestionItemAnswer> GetAll() { return new RepositoryBase<EvaluationQuestionItemAnswer>().Select(); } public static EvaluationQuestionItemAnswer Insert(EvaluationQuestionItemAnswer record) { return new RepositoryBase<EvaluationQuestionItemAnswer>().Create(record); } public static EvaluationQuestionItemAnswer Get(int id) { return new RepositoryBase<EvaluationQuestionItemAnswer>().Select(a => a.Id == id).FirstOrDefault(); } public static EvaluationQuestionItemAnswer Update(EvaluationQuestionItemAnswer record) { return new RepositoryBase<EvaluationQuestionItemAnswer>().Update(record); } public static void Delete(EvaluationQuestionItemAnswer record) { new RepositoryBase<EvaluationQuestionItemAnswer>().Delete(record); } } }
32.638889
111
0.697872
[ "Apache-2.0" ]
accept-project/accept-api
AcceptFramework/Repository/Evaluation/EvaluationQuestionItemAnswersRepository.cs
1,177
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using WalkingTec.Mvvm.Core; using WalkingTec.Mvvm.Mvc.Admin.ViewModels.FrameworkGroupVMs; using WalkingTec.Mvvm.Core.Extensions; namespace WalkingTec.Mvvm.Mvc.Admin.ViewModels.DataPrivilegeVMs { public class DataPrivilegeVM : BaseCRUDVM<DataPrivilege> { public List<ComboSelectListItem> TableNames { get; set; } public List<ComboSelectListItem> AllItems { get; set; } public List<ComboSelectListItem> AllGroups { get; set; } [Display(Name = "允许访问")] public List<Guid?> SelectedItemsID { get; set; } [Display(Name ="用户")] public string UserItCode { get; set; } [Display(Name = "权限类别")] public DpTypeEnum DpType { get; set; } public DpListVM DpList { get; set; } [Display(Name = "全部权限")] public bool? IsAll { get; set; } public DataPrivilegeVM() { DpList = new DpListVM(); IsAll = false; } protected override void InitVM() { TableNames = new List<ComboSelectListItem>(); if (ControllerName.Contains("WalkingTec.Mvvm.Mvc.Admin.Controllers")) { AllGroups = DC.Set<FrameworkGroup>().GetSelectListItems(LoginUserInfo.DataPrivileges, null, x => x.GroupName); TableNames = ConfigInfo.DataPrivilegeSettings.ToListItems(x => x.PrivillegeName, x => x.ModelName); } SelectedItemsID = new List<Guid?>(); List<Guid?> rids = null; if (DpType == DpTypeEnum.User) { rids = DC.Set<DataPrivilege>().Where(x => x.TableName == Entity.TableName && x.UserId == Entity.UserId).Select(x => x.RelateId).ToList(); } else { rids = DC.Set<DataPrivilege>().Where(x => x.TableName == Entity.TableName && x.GroupId == Entity.GroupId).Select(x => x.RelateId).ToList(); } if (rids.Contains(null)) { IsAll = true; } else { SelectedItemsID.AddRange(rids.Select(x => x)); } } protected override void ReInitVM() { TableNames = new List<ComboSelectListItem>(); AllItems = new List<ComboSelectListItem>(); TableNames = ConfigInfo.DataPrivilegeSettings.ToListItems(x => x.PrivillegeName, x => x.ModelName); } public override void Validate() { if (DpType == DpTypeEnum.User) { if (string.IsNullOrEmpty(UserItCode)) { MSD.AddModelError("UserItCode", "用户为必填项"); } else { var user = DC.Set<FrameworkUserBase>().Where(x => x.ITCode == UserItCode).FirstOrDefault(); if (user == null) { MSD.AddModelError("UserItCode", "无法找到账号为" + UserItCode + "的用户"); } else { Entity.UserId = user.ID; } } } else { if(Entity.GroupId == null) { MSD.AddModelError("Entity.GroupId", "用户组为必填项"); } } base.Validate(); } public override void DoAdd() { if (SelectedItemsID == null && IsAll == false) { return; } List<Guid> oldIDs = null; if (DpType == DpTypeEnum.User) { oldIDs = DC.Set<DataPrivilege>().Where(x => x.UserId == Entity.UserId && x.TableName == this.Entity.TableName).Select(x => x.ID).ToList(); } else { oldIDs = DC.Set<DataPrivilege>().Where(x => x.GroupId == Entity.GroupId && x.TableName == this.Entity.TableName).Select(x => x.ID).ToList(); } foreach (var oldid in oldIDs) { DataPrivilege dp = new DataPrivilege { ID = oldid }; DC.Set<DataPrivilege>().Attach(dp); DC.DeleteEntity(dp); } if (DpType == DpTypeEnum.User) { if (IsAll == true) { DataPrivilege dp = new DataPrivilege(); dp.RelateId = null; dp.UserId = Entity.UserId; dp.TableName = this.Entity.TableName; dp.DomainId = this.Entity.DomainId; DC.Set<DataPrivilege>().Add(dp); } else { foreach (var id in SelectedItemsID) { DataPrivilege dp = new DataPrivilege(); dp.RelateId = id; dp.UserId = Entity.UserId; dp.TableName = this.Entity.TableName; dp.DomainId = this.Entity.DomainId; DC.Set<DataPrivilege>().Add(dp); } } } else { if (IsAll == true) { DataPrivilege dp = new DataPrivilege(); dp.RelateId = null; dp.GroupId = Entity.GroupId; dp.TableName = this.Entity.TableName; dp.DomainId = this.Entity.DomainId; DC.Set<DataPrivilege>().Add(dp); } else { foreach (var id in SelectedItemsID) { DataPrivilege dp = new DataPrivilege(); dp.RelateId = id; dp.GroupId = Entity.GroupId; dp.TableName = this.Entity.TableName; dp.DomainId = this.Entity.DomainId; DC.Set<DataPrivilege>().Add(dp); } } } DC.SaveChanges(); } public override void DoEdit(bool updateAllFields = false) { List<Guid> oldIDs = null; if (DpType == DpTypeEnum.User) { oldIDs = DC.Set<DataPrivilege>().Where(x => x.UserId == Entity.UserId && x.TableName == this.Entity.TableName).Select(x => x.ID).ToList(); } else { oldIDs = DC.Set<DataPrivilege>().Where(x => x.GroupId == Entity.GroupId && x.TableName == this.Entity.TableName).Select(x => x.ID).ToList(); } foreach (var oldid in oldIDs) { DataPrivilege dp = new DataPrivilege { ID = oldid }; DC.Set<DataPrivilege>().Attach(dp); DC.DeleteEntity(dp); } if(IsAll == true) { if (DpType == DpTypeEnum.User) { DataPrivilege dp = new DataPrivilege(); dp.RelateId = null; dp.UserId = Entity.UserId; dp.TableName = this.Entity.TableName; dp.DomainId = this.Entity.DomainId; DC.Set<DataPrivilege>().Add(dp); } else { DataPrivilege dp = new DataPrivilege(); dp.RelateId = null; dp.GroupId = Entity.GroupId; dp.TableName = this.Entity.TableName; dp.DomainId = this.Entity.DomainId; DC.Set<DataPrivilege>().Add(dp); } } else { if (SelectedItemsID != null) { if (DpType == DpTypeEnum.User) { foreach (var id in SelectedItemsID) { DataPrivilege dp = new DataPrivilege(); dp.RelateId = id; dp.UserId = Entity.UserId; dp.TableName = this.Entity.TableName; dp.DomainId = this.Entity.DomainId; DC.Set<DataPrivilege>().Add(dp); } } else { foreach (var id in SelectedItemsID) { DataPrivilege dp = new DataPrivilege(); dp.RelateId = id; dp.GroupId = Entity.GroupId; dp.TableName = this.Entity.TableName; dp.DomainId = this.Entity.DomainId; DC.Set<DataPrivilege>().Add(dp); } } } } DC.SaveChanges(); } public override void DoDelete() { List<Guid> oldIDs = null; if (DpType == DpTypeEnum.User) { oldIDs = DC.Set<DataPrivilege>().Where(x => x.UserId == Entity.UserId && x.TableName == this.Entity.TableName).Select(x => x.ID).ToList(); } else { oldIDs = DC.Set<DataPrivilege>().Where(x => x.GroupId == Entity.GroupId && x.TableName == this.Entity.TableName).Select(x => x.ID).ToList(); } foreach (var oldid in oldIDs) { DataPrivilege dp = new DataPrivilege { ID = oldid }; DC.Set<DataPrivilege>().Attach(dp); DC.DeleteEntity(dp); } DC.SaveChanges(); } } }
36.914498
156
0.444914
[ "MIT" ]
HowardTao/WTM
src/WalkingTec.Mvvm.Mvc.Admin/Areas/_Admin/ViewModels/DataPrivilegeVMs/DataPrivilegeVM.cs
10,006
C#
#region License /* Copyright (c) 2014 RAVC Project - Daniil Rodin Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Linq; using NUnit.Framework; using Ravc.Encoding.Transforms; namespace Ravc.Tests.Encoding { public abstract unsafe class CompressionTransformTestsBase { protected abstract void DoTest(byte[] original); [Test] public void Zeroes() { DoTest(Enumerable.Range(0, 1920 * 3 * 10).Select(x => byte.MinValue).ToArray()); } [Test] public void Ones() { DoTest(Enumerable.Range(0, 1920 * 3 * 10).Select(x => byte.MaxValue).ToArray()); } [Test] public void Constant127() { DoTest(Enumerable.Range(0, 1920 * 3 * 10).Select(x => (byte)127).ToArray()); } [Test] public void Cycling() { DoTest(Enumerable.Range(0, 1920 * 3 * 10).Select(x => (byte)x).ToArray()); } [Test] public void Steps() { DoTest(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 1, 1, 1, 1, 1, 1, 1, 1, 1, }); } [Test] public void Sin() { const int length = 1920 * 3 * 10; var original = Enumerable.Range(0, length).Select(x => (byte)(int)(128 * Math.Sin(x / 100.0))).ToArray(); DoTest(original); } [Test] public void SinDelta() { const int length = 1920 * 3 * 10; var original = Enumerable.Range(0, length).Select(x => (byte)(int)(128 * Math.Sin(x / 100.0))).ToArray(); fixed (byte* pOriginal = original) DeltaCoding.Apply(pOriginal, length); DoTest(original); } [Test] public void Random() { var random = new Random(); DoTest(Enumerable.Range(0, 1920 * 3 * 10).Select(x => (byte)random.Next(0, 256)).ToArray()); } } }
32.626263
117
0.577709
[ "MIT" ]
Zulkir/RAVC
Source/Ravc.Tests/Encoding/CompressionTransformTestsBase.cs
3,232
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 WinFormsTreeViewDragAndDrop.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("WinFormsTreeViewDragAndDrop.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.041667
193
0.607613
[ "MIT" ]
NikolaGrujic91/WinForms-Tree-View-Drag-And-Drop
WinFormsTreeViewDragAndDrop/Properties/Resources.Designer.cs
2,813
C#
// The MIT License(MIT) // // Copyright(c) 2021 Alberto Rodriguez Orozco & LiveCharts Contributors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Collections.Generic; using LiveChartsCore.Drawing; using LiveChartsCore.Easing; namespace LiveChartsCore; /// <summary> /// A set of predefined easing functions. /// </summary> public static class EasingFunctions { /// <summary> /// Gets the back in. /// </summary> /// <value> /// The back in. /// </value> public static Func<float, float> BackIn => t => BackEasingFunction.In(t); /// <summary> /// Gets the back out. /// </summary> /// <value> /// The back out. /// </value> public static Func<float, float> BackOut => t => BackEasingFunction.Out(t); /// <summary> /// Gets the back in out. /// </summary> /// <value> /// The back in out. /// </value> public static Func<float, float> BackInOut => t => BackEasingFunction.InOut(t); /// <summary> /// Gets the bounce in. /// </summary> /// <value> /// The bounce in. /// </value> public static Func<float, float> BounceIn => BounceEasingFunction.In; /// <summary> /// Gets the bounce out. /// </summary> /// <value> /// The bounce out. /// </value> public static Func<float, float> BounceOut => BounceEasingFunction.Out; /// <summary> /// Gets the bounce in out. /// </summary> /// <value> /// The bounce in out. /// </value> public static Func<float, float> BounceInOut => BounceEasingFunction.InOut; /// <summary> /// Gets the circle in. /// </summary> /// <value> /// The circle in. /// </value> public static Func<float, float> CircleIn => CircleEasingFunction.In; /// <summary> /// Gets the circle out. /// </summary> /// <value> /// The circle out. /// </value> public static Func<float, float> CircleOut => CircleEasingFunction.Out; /// <summary> /// Gets the circle in out. /// </summary> /// <value> /// The circle in out. /// </value> public static Func<float, float> CircleInOut => CircleEasingFunction.InOut; /// <summary> /// Gets the cubic in. /// </summary> /// <value> /// The cubic in. /// </value> public static Func<float, float> CubicIn => CubicEasingFunction.In; /// <summary> /// Gets the cubic out. /// </summary> /// <value> /// The cubic out. /// </value> public static Func<float, float> CubicOut => CubicEasingFunction.Out; /// <summary> /// Gets the cubic in out. /// </summary> /// <value> /// The cubic in out. /// </value> public static Func<float, float> CubicInOut => CubicEasingFunction.InOut; /// <summary> /// Gets the ease. /// </summary> /// <value> /// The ease. /// </value> public static Func<float, float> Ease => BuildCubicBezier(0.25f, 0.1f, 0.25f, 1f); /// <summary> /// Gets the ease in. /// </summary> /// <value> /// The ease in. /// </value> public static Func<float, float> EaseIn => BuildCubicBezier(0.42f, 0f, 1f, 1f); /// <summary> /// Gets the ease out. /// </summary> /// <value> /// The ease out. /// </value> public static Func<float, float> EaseOut => BuildCubicBezier(0f, 0f, 0.58f, 1f); /// <summary> /// Gets the ease in out. /// </summary> /// <value> /// The ease in out. /// </value> public static Func<float, float> EaseInOut => BuildCubicBezier(0.42f, 0f, 0.58f, 1f); /// <summary> /// Gets the elastic in. /// </summary> /// <value> /// The elastic in. /// </value> public static Func<float, float> ElasticIn => t => ElasticEasingFunction.In(t); /// <summary> /// Gets the elastic out. /// </summary> /// <value> /// The elastic out. /// </value> public static Func<float, float> ElasticOut => t => ElasticEasingFunction.Out(t); /// <summary> /// Gets the elastic in out. /// </summary> /// <value> /// The elastic in out. /// </value> public static Func<float, float> ElasticInOut => t => ElasticEasingFunction.InOut(t); /// <summary> /// Gets the exponential in. /// </summary> /// <value> /// The exponential in. /// </value> public static Func<float, float> ExponentialIn => ExponentialEasingFunction.In; /// <summary> /// Gets the exponential out. /// </summary> /// <value> /// The exponential out. /// </value> public static Func<float, float> ExponentialOut => ExponentialEasingFunction.Out; /// <summary> /// Gets the exponential in out. /// </summary> /// <value> /// The exponential in out. /// </value> public static Func<float, float> ExponentialInOut => ExponentialEasingFunction.InOut; /// <summary> /// Gets the lineal. /// </summary> /// <value> /// The lineal. /// </value> public static Func<float, float> Lineal => t => t; /// <summary> /// Gets the polinominal in. /// </summary> /// <value> /// The polinominal in. /// </value> public static Func<float, float> PolinominalIn => t => PolinominalEasingFunction.In(t); /// <summary> /// Gets the polinominal out. /// </summary> /// <value> /// The polinominal out. /// </value> public static Func<float, float> PolinominalOut => t => PolinominalEasingFunction.Out(t); /// <summary> /// Gets the polinominal in out. /// </summary> /// <value> /// The polinominal in out. /// </value> public static Func<float, float> PolinominalInOut => t => PolinominalEasingFunction.InOut(t); /// <summary> /// Gets the quadratic in. /// </summary> /// <value> /// The quadratic in. /// </value> public static Func<float, float> QuadraticIn => t => t * t; /// <summary> /// Gets the quadratic out. /// </summary> /// <value> /// The quadratic out. /// </value> public static Func<float, float> QuadraticOut => t => t * (2 - t); /// <summary> /// Gets the quadratic in out. /// </summary> /// <value> /// The quadratic in out. /// </value> public static Func<float, float> QuadraticInOut => t => ((t *= 2) <= 1 ? t * t : --t * (2 - t) + 1) / 2f; /// <summary> /// Gets the sin in. /// </summary> /// <value> /// The sin in. /// </value> public static Func<float, float> SinIn => t => +t == 1 ? 1 : unchecked((float)(1 - Math.Cos(t * Math.PI / 2d))); /// <summary> /// Gets the sin out. /// </summary> /// <value> /// The sin out. /// </value> public static Func<float, float> SinOut => t => unchecked((float)Math.Sin(t * Math.PI / 2d)); /// <summary> /// Gets the sin in out. /// </summary> /// <value> /// The sin in out. /// </value> public static Func<float, float> SinInOut => t => unchecked((float)(1 - Math.Cos(Math.PI * t))) / 2f; /// <summary> /// Gets a fuction based on the given <see cref="KeyFrame"/> collection. /// </summary> public static Func<KeyFrame[], Func<float, float>> BuildFunctionUsingKeyFrames => keyFrames => { if (keyFrames.Length < 2) throw new Exception("At least 2 key frames are required."); if (keyFrames[keyFrames.Length - 1].Time < 1) { var newKeyFrames = new List<KeyFrame>(keyFrames) { new() { Time = 1, Value = keyFrames[keyFrames.Length - 1].Value } }; keyFrames = newKeyFrames.ToArray(); } return t => { var i = 0; var current = keyFrames[i]; var next = keyFrames[i + 1]; while (next.Time < t && i < keyFrames.Length - 2) { i++; current = keyFrames[i]; next = keyFrames[i + 1]; } var dt = next.Time - current.Time; var dv = next.Value - current.Value; var p = (t - current.Time) / dt; return current.Value + next.EasingFunction(p) * dv; }; }; /// <summary> /// Gets the build custom back in. /// </summary> /// <value> /// The build custom back in. /// </value> public static Func<float, Func<float, float>> BuildCustomBackIn => overshoot => t => BackEasingFunction.In(t, overshoot); /// <summary> /// Gets the build custom back out. /// </summary> /// <value> /// The build custom back out. /// </value> public static Func<float, Func<float, float>> BuildCustomBackOut => overshoot => t => BackEasingFunction.Out(t, overshoot); /// <summary> /// Gets the build custom back in out. /// </summary> /// <value> /// The build custom back in out. /// </value> public static Func<float, Func<float, float>> BuildCustomBackInOut => overshoot => t => BackEasingFunction.InOut(t, overshoot); /// <summary> /// Gets the build custom elastic in. /// </summary> /// <value> /// The build custom elastic in. /// </value> public static Func<float, float, Func<float, float>> BuildCustomElasticIn => (amplitude, period) => t => ElasticEasingFunction.In(t, amplitude, period); /// <summary> /// Gets the build custom elastic out. /// </summary> /// <value> /// The build custom elastic out. /// </value> public static Func<float, float, Func<float, float>> BuildCustomElasticOut => (amplitude, period) => t => ElasticEasingFunction.Out(t, amplitude, period); /// <summary> /// Gets the build custom elastic in out. /// </summary> /// <value> /// The build custom elastic in out. /// </value> public static Func<float, float, Func<float, float>> BuildCustomElasticInOut => (amplitude, period) => t => ElasticEasingFunction.InOut(t, amplitude, period); /// <summary> /// Gets the build custom polinominal in. /// </summary> /// <value> /// The build custom polinominal in. /// </value> public static Func<float, Func<float, float>> BuildCustomPolinominalIn => exponent => t => PolinominalEasingFunction.In(t, exponent); /// <summary> /// Gets the build custom polinominal out. /// </summary> /// <value> /// The build custom polinominal out. /// </value> public static Func<float, Func<float, float>> BuildCustomPolinominalOut => exponent => t => PolinominalEasingFunction.Out(t, exponent); /// <summary> /// Gets the build custom polinominal in out. /// </summary> /// <value> /// The build custom polinominal in out. /// </value> public static Func<float, Func<float, float>> BuildCustomPolinominalInOut => exponent => t => PolinominalEasingFunction.InOut(t, exponent); /// <summary> /// Gets the build cubic bezier. /// </summary> /// <value> /// The build cubic bezier. /// </value> public static Func<float, float, float, float, Func<float, float>> BuildCubicBezier => (mX1, mY1, mX2, mY2) => CubicBezierEasingFunction.BuildBezierEasingFunction(mX1, mY1, mX2, mY2); }
29.810875
116
0.564631
[ "MIT" ]
Live-Charts/LiveCharts2
src/LiveChartsCore/EasingFunctions.cs
12,612
C#
using Abp.Application.Services; using YiHan.Cms.Dto; using YiHan.Cms.Logging.Dto; namespace YiHan.Cms.Logging { public interface IWebLogAppService : IApplicationService { GetLatestWebLogsOutput GetLatestWebLogs(); FileDto DownloadWebLogs(); } }
19.785714
60
0.725632
[ "MIT" ]
Letheloney/YiHanCms
src/YiHan.Cms.Application/Logging/IWebLogAppService.cs
279
C#
using System.IO; using System.Collections.Generic; using eu.sig.cspacman.board; using eu.sig.cspacman.npc; namespace eu.sig.cspacman.level { public class MapParser { private readonly LevelFactory levelCreator; private readonly BoardFactory boardCreator; public MapParser(LevelFactory levelFactory, BoardFactory boardFactory) { this.levelCreator = levelFactory; this.boardCreator = boardFactory; } public Level ParseMap(char[,] map) { int width = map.GetLength(0); int height = map.GetLength(1); Square[,] grid = new Square[width, height]; IList<NPC> ghosts = new List<NPC>(); IList<Square> startPositions = new List<Square>(); MakeGrid(map, width, height, grid, ghosts, startPositions); Board board = boardCreator.CreateBoard(grid); return levelCreator.CreateLevel(board, ghosts, startPositions); } private void MakeGrid(char[,] map, int width, int height, Square[,] grid, IList<NPC> ghosts, IList<Square> startPositions) { for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { char c = map[x, y]; AddSquare(grid, ghosts, startPositions, x, y, c); } } } private void AddSquare(Square[,] grid, IList<NPC> ghosts, IList<Square> startPositions, int x, int y, char c) { switch (c) { case ' ': grid[x, y] = boardCreator.createGround(); break; case '#': grid[x, y] = boardCreator.createWall(); break; case '.': Square pelletSquare = boardCreator.createGround(); grid[x, y] = pelletSquare; levelCreator.CreatePellet().Occupy(pelletSquare); break; case 'G': Square ghostSquare = MakeGhostSquare(ghosts); grid[x, y] = ghostSquare; break; case 'P': Square playerSquare = boardCreator.createGround(); grid[x, y] = playerSquare; startPositions.Add(playerSquare); break; default: throw new PacmanConfigurationException("Invalid character at " + x + "," + y + ": " + c); } } private Square MakeGhostSquare(IList<NPC> ghosts) { Square ghostSquare = boardCreator.createGround(); NPC ghost = levelCreator.CreateGhost(); ghosts.Add(ghost); ghost.Occupy(ghostSquare); return ghostSquare; } public Level ParseMap(IList<string> text) { CheckMapFormat(text); int height = text.Count; int width = text[0].Length; char[,] map = new char[width, height]; for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { map[x, y] = text[y][x]; } } return ParseMap(map); } private void CheckMapFormat(IList<string> text) { if (text == null) { throw new PacmanConfigurationException( "Input text cannot be null."); } if (text.Count == 0) { throw new PacmanConfigurationException( "Input text must consist of at least 1 row."); } int width = text[0].Length; if (width == 0) { throw new PacmanConfigurationException( "Input text lines cannot be empty."); } foreach (string line in text) { if (line.Length != width) { throw new PacmanConfigurationException( "Input text lines are not of equal width."); } } } public Level ParseMap(Stream source) { using (StreamReader reader = new StreamReader(new BufferedStream( source), System.Text.Encoding.UTF8)) { IList<string> lines = new List<string>(); while (!reader.EndOfStream) { lines.Add(reader.ReadLine()); } return ParseMap(lines); } } } }
30.700637
82
0.463278
[ "Apache-2.0" ]
BetterCodeHubTraining/cspacman
CsPacman/eu.sig.cspacman.level/MapParser.cs
4,820
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using System.Xml.Linq; using Umbraco.Core; using Umbraco.Core.Cache; using Umbraco.Core.Composing; using Umbraco.Core.Events; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Services; using uSync8.BackOffice.Configuration; using uSync8.BackOffice.Services; using uSync8.Core; using uSync8.Core.Dependency; using uSync8.Core.Extensions; using uSync8.Core.Models; using uSync8.Core.Serialization; using uSync8.Core.Tracking; namespace uSync8.BackOffice.SyncHandlers { public abstract class SyncHandlerRoot<TObject, TContainer> { protected readonly IProfilingLogger logger; protected readonly SyncFileService syncFileService; protected readonly IList<ISyncDependencyChecker<TObject>> dependencyCheckers; protected readonly IList<ISyncTracker<TObject>> trackers; // [Obsolete] // protected ISyncDependencyChecker<TObject> dependencyChecker => dependencyCheckers.FirstOrDefault(); protected readonly ISyncSerializer<TObject> serializer; // [Obsolete] // protected ISyncTracker<TObject> tracker => trackers.FirstOrDefault(); protected readonly IAppPolicyCache runtimeCache; /// <summary> /// Alias of the handler, used when getting settings from the config file /// </summary> public string Alias { get; private set; } /// <summary> /// Name of handler, displayed to user during reports/imports /// </summary> public string Name { get; private set; } /// <summary> /// name of the folder inside the uSync folder where items are stored /// </summary> public string DefaultFolder { get; private set; } /// <summary> /// priority order items are imported in /// </summary> /// <remarks> /// to import before anything else go below USYNC_RESERVED_LOWER (1000) /// to import after uSync has done all the other things go past USYNC_RESERVED_UPPER (2000) /// </remarks> public int Priority { get; private set; } /// <summary> /// Icon displayed on the screen while the import happens. /// </summary> public string Icon { get; private set; } /// <summary> /// does this handler require two passes at the import. /// </summary> protected bool IsTwoPass = false; /// <summary> /// the object type of the item being processed. /// </summary> public Type ItemType { get; protected set; } = typeof(TObject); /// <summary> /// Is the handler enabled /// </summary> public bool Enabled { get; set; } = true; /// <summary> /// the default configuration for this handler /// </summary> public HandlerSettings DefaultConfig { get; set; } /// <summary> /// the root folder for the handler (based on the settings) /// </summary> protected string rootFolder { get; set; } /// <summary> /// the UDIEntityType for the handler objects /// </summary> public string EntityType { get; protected set; } /// <summary> /// Name of the type (object) /// </summary> public string TypeName { get; protected set; } // we calculate these now based on the entityType ? protected UmbracoObjectTypes itemObjectType { get; set; } = UmbracoObjectTypes.Unknown; protected UmbracoObjectTypes itemContainerType = UmbracoObjectTypes.Unknown; protected Type handlerType; protected readonly ISyncItemFactory itemFactory; protected bool IsPostImportHandler = false; [Obsolete("Use constructors with collections")] protected SyncHandlerRoot( IProfilingLogger logger, AppCaches appCaches, ISyncSerializer<TObject> serializer, IEnumerable<ISyncTracker<TObject>> trackers, IEnumerable<ISyncDependencyChecker<TObject>> checkers, SyncFileService syncFileService) : this(logger, appCaches, serializer, null, syncFileService) { } public SyncHandlerRoot( IProfilingLogger logger, AppCaches appCaches, ISyncSerializer<TObject> serializer, ISyncItemFactory itemFactory, SyncFileService syncFileService) { this.logger = logger; this.itemFactory = itemFactory ?? Current.Factory.GetInstance<ISyncItemFactory>(); this.serializer = serializer; this.trackers = this.itemFactory.GetTrackers<TObject>().ToList(); this.dependencyCheckers = this.itemFactory.GetCheckers<TObject>().ToList(); this.syncFileService = syncFileService; this.IsPostImportHandler = this is ISyncPostImportHandler; handlerType = GetType(); var meta = handlerType.GetCustomAttribute<SyncHandlerAttribute>(false); if (meta == null) throw new InvalidOperationException($"The Handler {handlerType} requires a {typeof(SyncHandlerAttribute)}"); Name = meta.Name; Alias = meta.Alias; DefaultFolder = meta.Folder; Priority = meta.Priority; IsTwoPass = meta.IsTwoPass; Icon = string.IsNullOrWhiteSpace(meta.Icon) ? "icon-umb-content" : meta.Icon; EntityType = meta.EntityType; TypeName = serializer.ItemType; this.itemObjectType = uSyncObjectType.ToUmbracoObjectType(EntityType); this.itemContainerType = uSyncObjectType.ToContainerUmbracoObjectType(EntityType); var settings = Current.Configs.uSync(); GetDefaultConfig(settings); uSyncConfig.Reloaded += BackOfficeConfig_Reloaded; if (settings.CacheFolderKeys) { this.runtimeCache = appCaches.RuntimeCache; } else { logger.Info(handlerType, "No caching of handler key lookups (CacheFolderKeys = false)"); this.runtimeCache = NoAppCache.Instance; } } private void GetDefaultConfig(uSyncSettings setting) { var config = setting.DefaultHandlerSet()?.Handlers.Where(x => x.Alias.InvariantEquals(this.Alias)) .FirstOrDefault(); if (config != null) this.DefaultConfig = config; else { // handler isn't in the config, but need one ? this.DefaultConfig = new HandlerSettings(this.Alias, false) { GuidNames = new OverriddenValue<bool>(setting.UseGuidNames, false), UseFlatStructure = new OverriddenValue<bool>(setting.UseFlatStructure, false), }; } rootFolder = setting.RootFolder; } private void BackOfficeConfig_Reloaded(uSyncSettings settings) { GetDefaultConfig(settings); } #region Importing /// <summary> /// Import everything from a given folder, using the supplied config settings. /// </summary> public IEnumerable<uSyncAction> ImportAll(string folder, HandlerSettings config, bool force, SyncUpdateCallback callback = null) { using (logger.DebugDuration(handlerType, $"Importing {Alias} {Path.GetFileName(folder)}", $"Import complete {Alias}")) { var actions = new List<uSyncAction>(); var updates = new Dictionary<string, TObject>(); var cacheKey = PrepCaches(); logger.Debug(handlerType, "Clearing KeyCache {key}", cacheKey); runtimeCache.ClearByKey(cacheKey); actions.AddRange(ImportFolder(folder, config, updates, force, callback)); if (updates.Count > 0) { PerformSecondPassImports(updates, actions, config, callback); } logger.Debug(handlerType, "Clearing KeyCache {key}", cacheKey); CleanCaches(cacheKey); callback?.Invoke("Done", 3, 3); return actions; } } /// <summary> /// Import everything in a given (child) folder, based on setting /// </summary> protected virtual IEnumerable<uSyncAction> ImportFolder(string folder, HandlerSettings config, Dictionary<string, TObject> updates, bool force, SyncUpdateCallback callback) { List<uSyncAction> actions = new List<uSyncAction>(); var files = GetImportFiles(folder); var flags = SerializerFlags.None; if (force) flags |= SerializerFlags.Force; var cleanMarkers = new List<string>(); int count = 0; int total = files.Count(); foreach (string file in files) { count++; callback?.Invoke($"Importing {Path.GetFileNameWithoutExtension(file)}", count, total); var result = Import(file, config, flags); foreach (var attempt in result) { if (attempt.Success) { if (attempt.Change == ChangeType.Clean) { cleanMarkers.Add(file); } else if (attempt.Item != null && attempt.Item is TObject item) { updates.Add(file, item); } } if (attempt.Change != ChangeType.Clean) actions.Add(attempt); } } // bulk save .. if (flags.HasFlag(SerializerFlags.DoNotSave) && updates.Any()) { // callback?.Invoke($"Saving {updates.Count()} changes", 1, 1); serializer.Save(updates.Select(x => x.Value)); } var folders = syncFileService.GetDirectories(folder); foreach (var children in folders) { actions.AddRange(ImportFolder(children, config, updates, force, callback)); } if (actions.All(x => x.Success) && cleanMarkers.Count > 0) { foreach (var item in cleanMarkers.Select((filePath, Index) => new { filePath, Index })) { var folderName = Path.GetFileName(item.filePath); callback?.Invoke($"Cleaning {folderName}", item.Index, cleanMarkers.Count); var cleanActions = CleanFolder(item.filePath, false, config.UseFlatStructure); if (cleanActions.Any()) { actions.AddRange(cleanActions); } else { // nothing to delete, we report this as a no change actions.Add(uSyncAction.SetAction(true, $"Folder {Path.GetFileName(item.filePath)}", change: ChangeType.NoChange, filename: item.filePath)); } } // remove the actual cleans (they will have been replaced by the deletes actions.RemoveAll(x => x.Change == ChangeType.Clean); } return actions; } /// <summary> /// Import a single item, from the .config file supplied /// </summary> public virtual IEnumerable<uSyncAction> Import(string filePath, HandlerSettings config, SerializerFlags flags) { try { syncFileService.EnsureFileExists(filePath); var node = syncFileService.LoadXElement(filePath); return Import(node, filePath, config, flags); } catch (FileNotFoundException notFoundException) { return uSyncAction.Fail(Path.GetFileName(filePath), this.handlerType, ChangeType.Fail, $"File not found {notFoundException.Message}") .AsEnumerableOfOne(); } catch (Exception ex) { logger.Warn(handlerType, "{alias}: Import Failed : {exception}", this.Alias, ex.ToString()); return uSyncAction.Fail(Path.GetFileName(filePath), this.handlerType, ChangeType.Fail, $"Import Fail: {ex.Message}") .AsEnumerableOfOne(); } } public virtual IEnumerable<uSyncAction> Import(XElement node, string filename, HandlerSettings config, SerializerFlags flags) { if (config.FailOnMissingParent) flags |= SerializerFlags.FailMissingParent; return ImportElement(node, filename, config, new uSyncImportOptions { Flags = flags }); } virtual public IEnumerable<uSyncAction> Import(string file, HandlerSettings config, bool force) { var flags = SerializerFlags.OnePass; if (force) flags |= SerializerFlags.Force; return Import(file, config, flags); } virtual public IEnumerable<uSyncAction> ImportElement(XElement node, bool force) { var flags = SerializerFlags.OnePass; if (force) flags |= SerializerFlags.Force; return ImportElement(node, string.Empty, this.DefaultConfig, new uSyncImportOptions { Flags = flags }); } /// <summary> /// Import a node, with settings and options /// </summary> /// <remarks> /// All Imports lead here /// </remarks> virtual public IEnumerable<uSyncAction> ImportElement(XElement node, string filename, HandlerSettings settings, uSyncImportOptions options) { if (!ShouldImport(node, settings)) { return uSyncAction.SetAction(true, node.GetAlias(), type: typeof(TObject), message: "Change blocked (based on config)") .AsEnumerableOfOne(); } if (!uSyncService.FireImportingItem(node)) { // blocked return uSyncActionHelper<TObject> .ReportAction(ChangeType.NoChange, node.GetAlias(), GetNameFromFileOrNode(filename, node), node.GetKey(), this.Alias) .AsEnumerableOfOne(); } try { // merge the options from the handler and any import options into our serializer options. var serializerOptions = new SyncSerializerOptions(options.Flags, settings.Settings); serializerOptions.MergeSettings(options.Settings); // get the item. var attempt = DeserializeItem(node, serializerOptions); var action = uSyncActionHelper<TObject>.SetAction(attempt, GetNameFromFileOrNode(filename, node), node.GetKey(), this.Alias, IsPostImportHandler); // add item if we have it. if (attempt.Item != null) action.Item = attempt.Item; // add details if we have them if (attempt.Details != null && attempt.Details.Any()) action.Details = attempt.Details; // this might not be the place to do this because, two pass items are imported at another point too. uSyncService.FireImportedItem(node, attempt.Change); return action.AsEnumerableOfOne(); } catch (Exception ex) { logger.Warn(handlerType, "{alias}: Import Failed : {exception}", this.Alias, ex.ToString()); return uSyncAction.Fail(Path.GetFileName(filename), this.handlerType, ChangeType.Fail, $"Import Fail: {ex.Message}") .AsEnumerableOfOne(); } } /// <summary> /// Works through a list of items that have been processed and performs the second import pass on them. /// </summary> private void PerformSecondPassImports(IDictionary<string, TObject> updates, List<uSyncAction> actions, HandlerSettings config, SyncUpdateCallback callback = null) { foreach (var item in updates.Select((update, Index) => new { update, Index })) { callback?.Invoke($"Second Pass {Path.GetFileName(item.update.Key)}", item.Index, updates.Count); var attempt = ImportSecondPass(item.update.Key, item.update.Value, config, callback); if (attempt.Success) { // if the second attempt has a message on it, add it to the first attempt. if (!string.IsNullOrWhiteSpace(attempt.Message)) { if (actions.Any(x => x.FileName == item.update.Key)) { var action = actions.FirstOrDefault(x => x.FileName == item.update.Key); actions.Remove(action); action.Message += attempt.Message; actions.Add(action); } } // If the second attemt has change details add them to the first attempt if (attempt.Details != null && attempt.Details.Any()) { if (actions.Any(x => x.FileName == item.update.Key)) { var action = actions.FirstOrDefault(x => x.FileName == item.update.Key); var details = new List<uSyncChange>(); if (action.Details != null) { details.AddRange(action.Details); } details.AddRange(attempt.Details); actions.Remove(action); action.Details = details; actions.Add(action); } } if (attempt.Change > ChangeType.NoChange && !attempt.Saved && attempt.Item != null) { serializer.Save(attempt.Item.AsEnumerableOfOne()); } } else { // the second attempt failed - update the action. if (actions.Any(x => x.FileName == item.update.Key)) { var action = actions.FirstOrDefault(x => x.FileName == item.update.Key); actions.Remove(action); action.Success = attempt.Success; action.Message = $"Second Pass Fail: {attempt.Message}"; action.Exception = attempt.Exception; actions.Add(action); } } } } virtual public IEnumerable<uSyncAction> ImportSecondPass(uSyncAction action, HandlerSettings settings, uSyncImportOptions options) { if (!IsTwoPass) return Enumerable.Empty<uSyncAction>(); try { var file = action.FileName; var node = syncFileService.LoadXElement(file); var item = GetFromService(node.GetKey()); if (item == null) return Enumerable.Empty<uSyncAction>(); // merge the options from the handler and any import options into our serializer options. var serializerOptions = new SyncSerializerOptions(options.Flags, settings.Settings); serializerOptions.MergeSettings(options.Settings); // do the second pass on this item var result = DeserializeItemSecondPass(item, node, serializerOptions); return uSyncActionHelper<TObject>.SetAction(result,file, node.GetKey(), this.Alias).AsEnumerableOfOne(); } catch (Exception ex) { logger.Warn(handlerType, $"Second Import Failed: {ex}"); return uSyncAction.Fail(action.Name, action.ItemType, ex: ex).AsEnumerableOfOne(); } } /// <summary> /// Perform a 'second pass' import on a single item. /// </summary> virtual public SyncAttempt<TObject> ImportSecondPass(string file, TObject item, HandlerSettings config, SyncUpdateCallback callback) { if (IsTwoPass) { try { syncFileService.EnsureFileExists(file); var flags = SerializerFlags.None; var node = syncFileService.LoadXElement(file); return DeserializeItemSecondPass(item, node, new SyncSerializerOptions(flags, config.Settings)); } catch (Exception ex) { logger.Warn(handlerType, $"Second Import Failed: {ex.ToString()}"); return SyncAttempt<TObject>.Fail(GetItemAlias(item), ChangeType.Fail, ex.Message, ex); } } return SyncAttempt<TObject>.Succeed(GetItemAlias(item), ChangeType.NoChange); } /// <summary> /// given a folder we calculate what items we can remove, becuase they are /// not in one the the files in the folder. /// </summary> /// <param name="cleanFile"></param> /// <returns></returns> protected virtual IEnumerable<uSyncAction> CleanFolder(string cleanFile, bool reportOnly, bool flat) { var folder = Path.GetDirectoryName(cleanFile); if (!Directory.Exists(folder)) return Enumerable.Empty<uSyncAction>(); // get the keys for every item in this folder. // this would works on the flat folder stucture too, // there we are being super defensive, so if an item // is anywhere in the folder it won't get removed // even if the folder is wrong // be a little slower (not much though) // we cache this, (it is cleared on an ImportAll) var keys = GetFolderKeys(folder, flat); if (keys.Count > 0) { // move parent to here, we only need to check it if there are files. var parent = GetCleanParent(cleanFile); if (parent == null) return Enumerable.Empty<uSyncAction>(); logger.Debug(handlerType, "Got parent with {alias} from clean file {file}", GetItemAlias(parent), Path.GetFileName(cleanFile)); // keys should aways have at least one entry (the key from cleanFile) // if it doesn't then something might have gone wrong. // because we are being defensive when it comes to deletes, // we only then do deletes when we know we have loaded some keys! return DeleteMissingItems(parent, keys, reportOnly); } else { logger.Warn(handlerType, "Failed to get the keys for items in the folder, there might be a disk issue {folder}", folder); return Enumerable.Empty<uSyncAction>(); } } /// <summary> /// Get the GUIDs for all items in a folder /// </summary> /// <remarks> /// This is disk intensive, (checking the .config files all the time) /// so we cache it, and if we are using the flat folder stucture, then /// we only do it once, so its quicker. /// </remarks> private IList<Guid> GetFolderKeys(string folder, bool flat) { // We only need to load all the keys once per handler (if all items are in a folder that key will be used). var folderKey = folder.GetHashCode(); var cacheKey = $"{GetCacheKeyBase()}_{folderKey}"; logger.Debug(handlerType, "Getting Folder Keys : {cacheKey}", cacheKey); return runtimeCache.GetCacheItem(cacheKey, () => { // when it's not flat structure we also get the sub folders. (extra defensive get them all) var keys = new List<Guid>(); var files = syncFileService.GetFiles(folder, "*.config", !flat).ToList(); foreach (var file in files) { var node = XElement.Load(file); var key = node.GetKey(); if (!keys.Contains(key)) { keys.Add(key); } } logger.Debug(handlerType, "Loaded {count} keys from {folder} [{cacheKey}]", keys.Count, folder, cacheKey); return keys; }, null); } /// <summary> /// Get the parent item of the clean file (so we can check if the folder has any versions of this item in it) /// </summary> protected TObject GetCleanParent(string file) { var node = XElement.Load(file); var key = node.GetKey(); if (key == Guid.Empty) return default; return GetFromService(key); } /// <summary> /// remove an items that are not listed in the guids to keep /// </summary> /// <param name="parent">parent item that all keys will be under</param> /// <param name="keysToKeep">list of guids of items we don't want to delete</param> /// <param name="reportOnly">will just report what would happen (doesn't do the delete)</param> /// <returns>list of delete actions</returns> protected abstract IEnumerable<uSyncAction> DeleteMissingItems(TObject parent, IEnumerable<Guid> keysToKeep, bool reportOnly); /// <summary> /// Get the files we are going to import from a folder. /// </summary> protected virtual IEnumerable<string> GetImportFiles(string folder) => syncFileService.GetFiles(folder, "*.config").OrderBy(x => x); /// <summary> /// check to see if this element should be imported as part of the process. /// </summary> virtual protected bool ShouldImport(XElement node, HandlerSettings config) { // if createOnly is on, then we only create things that are not already there. // this lookup is slow(ish) so we only do it if we have to. if (config.GetSetting<bool>(uSyncConstants.DefaultSettings.CreateOnly, uSyncConstants.DefaultSettings.CreateOnly_Default) || config.GetSetting<bool>(uSyncConstants.DefaultSettings.OneWay, uSyncConstants.DefaultSettings.CreateOnly_Default)) { var item = serializer.FindItem(node); if (item != null) { logger.Debug(handlerType, "CreateOnly: Item {alias} already exist not importing it.", node.GetAlias()); return false; } } // Ignore alias setting. // if its set the thing with this alias is ignored. var ignore = config.GetSetting<string>("IgnoreAliases", string.Empty); if (!string.IsNullOrWhiteSpace(ignore)) { var ignoreList = ignore.ToDelimitedList(); if (ignoreList.InvariantContains(node.GetAlias())) { logger.Debug(handlerType, "Ignore: Item {alias} is in the ignore list", node.GetAlias()); return false; } } return true; } /// <summary> /// Check to see if this elment should be exported. /// </summary> virtual protected bool ShouldExport(XElement node, HandlerSettings config) => true; #endregion #region Exporting virtual public IEnumerable<uSyncAction> ExportAll(string folder, HandlerSettings config, SyncUpdateCallback callback) { // we dont clean the folder out on an export all. // because the actions (renames/deletes) live in the folder // // there will have to be a different clean option /// // syncFileService.CleanFolder(folder); return ExportAll(default, folder, config, callback); } virtual public IEnumerable<uSyncAction> ExportAll(TContainer parent, string folder, HandlerSettings config, SyncUpdateCallback callback) { var actions = new List<uSyncAction>(); if (itemContainerType != UmbracoObjectTypes.Unknown) { var containers = GetFolders(parent); foreach (var container in containers) { actions.AddRange(ExportAll(container, folder, config, callback)); } } var items = GetChildItems(parent).ToList(); foreach (var item in items.Select((Value, Index) => new { Value, Index })) { TObject concreteType; if (item.Value is TObject t) { concreteType = t; } else { concreteType = GetFromService(item.Value); } if (concreteType != null) { // only export the items (not the containers). callback?.Invoke(GetItemName(concreteType), item.Index, items.Count); actions.AddRange(Export(concreteType, folder, config)); } actions.AddRange(ExportAll(item.Value, folder, config, callback)); } return actions; } abstract protected IEnumerable<TContainer> GetChildItems(TContainer parent); abstract protected IEnumerable<TContainer> GetFolders(TContainer parent); public bool HasChildren(TContainer item) => GetFolders(item).Any() || GetChildItems(item).Any(); public IEnumerable<uSyncAction> Export(int id, string folder, HandlerSettings settings) { var item = this.GetFromService(id); return this.Export(item, folder, settings); } public IEnumerable<uSyncAction> Export(Udi udi, string folder, HandlerSettings settings) { var item = FindByUdi(udi); if (item != null) return Export(item, folder, settings); return uSyncAction.Fail(nameof(udi), typeof(TObject), ChangeType.Fail, "Item not found") .AsEnumerableOfOne(); } virtual public IEnumerable<uSyncAction> Export(TObject item, string folder, HandlerSettings config) { if (item == null) return uSyncAction.Fail(nameof(item), typeof(TObject), ChangeType.Fail, "Item not set").AsEnumerableOfOne(); if (!uSyncService.FireExportingItem(item)) { return uSyncActionHelper<TObject> .ReportAction(ChangeType.NoChange, GetItemName(item), string.Empty, GetItemKey(item), this.Alias) .AsEnumerableOfOne(); } var filename = GetPath(folder, item, config.GuidNames, config.UseFlatStructure); var attempt = SerializeItem(item, new SyncSerializerOptions(config.Settings)); if (attempt.Success) { if (ShouldExport(attempt.Item, config)) { // only write the file to disk if it should be exported. syncFileService.SaveXElement(attempt.Item, filename); } else { return uSyncAction.SetAction(true, filename, type: typeof(TObject), change: ChangeType.NoChange, message: "Not Exported (Based on config)", filename: filename).AsEnumerableOfOne(); } } uSyncService.FireExportedItem(attempt.Item, ChangeType.Export); return uSyncActionHelper<XElement>.SetAction(attempt, filename, GetItemKey(item), this.Alias).AsEnumerableOfOne(); } #endregion #region Reporting public IEnumerable<uSyncAction> Report(string folder, HandlerSettings config, SyncUpdateCallback callback) { var actions = new List<uSyncAction>(); var cacheKey = PrepCaches(); callback?.Invoke("Checking Actions", 1, 3); actions.AddRange(ReportFolder(folder, config, callback)); callback?.Invoke("Validating Report", 2, 3); actions = ValidateReport(folder, actions); CleanCaches(cacheKey); callback?.Invoke("Done", 3, 3); return actions; } private List<uSyncAction> ValidateReport(string folder, List<uSyncAction> actions) { // Alters the existing list, by chaning the type as needed. var validationActions = ReportMissingParents(actions.ToArray()); // adds new actions - for delete clashes. validationActions.AddRange(ReportDeleteCheck(folder, validationActions)); return validationActions.ToList(); } /// <summary> /// Check to returned report to see if there is a delete and an update for the same item /// because if there is then we have issues. /// </summary> protected virtual IEnumerable<uSyncAction> ReportDeleteCheck(string folder, IEnumerable<uSyncAction> actions) { var duplicates = new List<uSyncAction>(); // delete checks. foreach (var deleteAction in actions.Where(x => x.Change == ChangeType.Delete)) { // todo: this is only matching by key, but non-tree based serializers also delete by alias. // so this check actually has to be booted back down to the serializer. if (actions.Any(x => x.Change != ChangeType.Delete && DoActionsMatch(x, deleteAction))) { var duplicateAction = uSyncActionHelper<TObject>.ReportActionFail(deleteAction.Name, $"Duplicate! {deleteAction.Name} exists both as delete and import action"); // create a detail message to tell people what has happend. duplicateAction.DetailMessage = "uSync detected a duplicate actions, where am item will be both created and deleted."; var details = new List<uSyncChange>(); // add the delete message to the list of changes var filename = Path.GetFileName(deleteAction.FileName); var relativePath = deleteAction.FileName.Substring(folder.Length); details.Add(uSyncChange.Delete(filename, $"Delete: {deleteAction.Name} ({filename}", relativePath)); // add all the duplicates to the list of changes. foreach (var dup in actions.Where(x => x.Change != ChangeType.Delete && DoActionsMatch(x, deleteAction))) { var dupFilename = Path.GetFileName(dup.FileName); var dupRelativePath = dup.FileName.Substring(folder.Length); details.Add( uSyncChange.Update( path: dupFilename, name: $"{dup.Change} : {dup.Name} ({dupFilename})", oldValue: "", newValue: dupRelativePath)); } duplicateAction.Details = details; duplicates.Add(duplicateAction); } } return duplicates; } /// <summary> /// check to see if an action matches, another action. /// </summary> /// <remarks> /// how two actions match can vary based on handler, in the most part they are matched by key /// but some items will also check based on the name. /// /// when we are dealing with handlers where things can have the same /// name (tree items, such as content or media), this function has /// to be overridden to remove the name check. /// </remarks> protected virtual bool DoActionsMatch(uSyncAction a, uSyncAction b) { if (a.key == b.key) return true; if (a.Name.Equals(b.Name, StringComparison.InvariantCultureIgnoreCase)) return true; return false; } /// <summary> /// check if a node matches a item /// </summary> /// <remarks> /// Like above we want to match on key and alias, but only if the alias is unique. /// however the GetItemAlias function is overridden by tree based handlers to return a unique /// alias (the key again), so we don't get false positives. /// </remarks> protected virtual bool DoItemsMatch(XElement node, TObject item) { if (GetItemKey(item) == node.GetKey()) return true; // yes this is an or, we've done it explicity, so you can tell! if (node.GetAlias().Equals(this.GetItemAlias(item), StringComparison.InvariantCultureIgnoreCase)) return true; return false; } /// <summary> /// Check report for any items that are missing their parent items /// </summary> /// <remarks> /// The serializers will report if an item is missing a parent item within umbraco, /// but because the serializer isn't aware of the wider import (all the other items) /// it can't say if the parent is in the import. /// /// This method checks for the parent of an item in the wider list of items being /// imported. /// </remarks> private List<uSyncAction> ReportMissingParents(uSyncAction[] actions) { for (int i = 0; i < actions.Length; i++) { if (actions[i].Change != ChangeType.ParentMissing) continue; var node = XElement.Load(actions[i].FileName); var guid = node.GetParentKey(); if (guid != Guid.Empty) { if (actions.Any(x => x.key == guid && (x.Change < ChangeType.Fail || x.Change == ChangeType.ParentMissing))) { logger.Debug(handlerType, "Found existing key in actions {item}", actions[i].Name); actions[i].Change = ChangeType.Create; } else { logger.Warn(handlerType, "{item} is missing a parent", actions[i].Name); } } } return actions.ToList(); } public virtual IEnumerable<uSyncAction> ReportFolder(string folder, HandlerSettings config, SyncUpdateCallback callback) { List<uSyncAction> actions = new List<uSyncAction>(); var files = GetImportFiles(folder); int count = 0; int total = files.Count(); logger.Debug(handlerType, "ReportFolder: {folder} ({count} files)", folder, total); foreach (string file in files) { count++; callback?.Invoke(Path.GetFileNameWithoutExtension(file), count, total); actions.AddRange(ReportItem(file, config)); } foreach (var children in syncFileService.GetDirectories(folder)) { actions.AddRange(ReportFolder(children, config, callback)); } return actions; } public IEnumerable<uSyncAction> ReportElement(XElement node) => ReportElement(node, string.Empty, this.DefaultConfig); protected virtual IEnumerable<uSyncAction> ReportElement(XElement node, string filename, HandlerSettings config) => ReportElement(node, filename, config ?? this.DefaultConfig, new uSyncImportOptions()); /// <summary> /// Report an Element /// </summary> public IEnumerable<uSyncAction> ReportElement(XElement node, string filename, HandlerSettings settings, uSyncImportOptions options) { try { // there are cases when we blank key, while checking, so we should save a reference here. var nodeKey = node.GetKey(); // pre event reporting // this lets us intercept a report and // shortcut the checking (sometimes). if (!uSyncService.FireReportingItem(node)) { return uSyncActionHelper<TObject> .ReportAction(ChangeType.NoChange, node.GetAlias(), GetNameFromFileOrNode(filename, node), nodeKey, this.Alias) .AsEnumerableOfOne(); } var actions = new List<uSyncAction>(); // get the serializer options var serializerOptions = new SyncSerializerOptions(options.Flags, settings.Settings); serializerOptions.MergeSettings(options.Settings); // check if this item is current (the provided xml and exported xml match) var change = IsItemCurrent(node, serializerOptions); var action = uSyncActionHelper<TObject> .ReportAction(change.Change, node.GetAlias(), GetNameFromFileOrNode(filename, node), nodeKey, this.Alias); action.Message = ""; if (action.Change == ChangeType.Clean) { actions.AddRange(CleanFolder(filename, true, settings.UseFlatStructure)); } else if (action.Change > ChangeType.NoChange) { action.Details = GetChanges(node, change.CurrentNode, serializerOptions); if (action.Change != ChangeType.Create && (action.Details == null || action.Details.Count() == 0)) { action.Message = "xml is diffrent - but properties may not have changed"; action.Details = MakeRawChange(node, change.CurrentNode, serializerOptions).AsEnumerableOfOne(); } else { action.Message = $"{action.Change}"; } actions.Add(action); } else { actions.Add(action); } // tell other things we have reported this item. uSyncService.FireReportedItem(node, action.Change); return actions; } catch (FormatException fex) { return uSyncActionHelper<TObject> .ReportActionFail(Path.GetFileName(node.GetAlias()), $"format error {fex.Message}") .AsEnumerableOfOne(); } } private uSyncChange MakeRawChange(XElement node, XElement current, SyncSerializerOptions options) { if (current != null) return uSyncChange.Update(node.GetAlias(), "Raw XML", current.ToString(), node.ToString()); return uSyncChange.NoChange(node.GetAlias(), node.GetAlias()); } protected IEnumerable<uSyncAction> ReportItem(string file, HandlerSettings config) { try { var node = syncFileService.LoadXElement(file); if (ShouldImport(node, config)) { return ReportElement(node, file, config); } else { return uSyncActionHelper<TObject>.ReportAction(false, node.GetAlias(), "Will not be imported (Based on config)") .AsEnumerableOfOne<uSyncAction>(); } } catch (Exception ex) { return uSyncActionHelper<TObject> .ReportActionFail(Path.GetFileName(file), $"Reporting error {ex.Message}") .AsEnumerableOfOne(); } } private IEnumerable<uSyncChange> GetChanges(XElement node, XElement currentNode, SyncSerializerOptions options) => itemFactory.GetChanges<TObject>(node, currentNode, options); #endregion #region Events // // Handling the events Umbraco fires for saves/deletes/etc, // For most things these events are all handled the same way, so the root handler can copy with // it. If the events need to be handled a diffrent way, then that is done inside the Handler // by overriding the InitializeEvents method. // /// <summary> /// Method to setup the events for any given service/handler. /// </summary> protected abstract void InitializeEvents(HandlerSettings settings); /// <summary> /// Clean up the events, when umbraco terminates. /// </summary> protected virtual void TerminateEvents(HandlerSettings settings) { } protected virtual void EventDeletedItem(IService sender, DeleteEventArgs<TObject> e) { if (uSync8BackOffice.eventsPaused) return; foreach (var item in e.DeletedEntities) { ExportDeletedItem(item, Path.Combine(rootFolder, this.DefaultFolder), DefaultConfig); } } protected virtual void EventSavedItem(IService sender, SaveEventArgs<TObject> e) { if (uSync8BackOffice.eventsPaused) return; foreach (var item in e.SavedEntities) { var attempts = Export(item, Path.Combine(rootFolder, this.DefaultFolder), DefaultConfig); // if we are using guid names and a flat structure then the clean doesn't need to happen // if (!(this.DefaultConfig.GuidNames && this.DefaultConfig.UseFlatStructure)) // #216 clean up all the time, because if someone recreates a doctype, we want to find the old // version of that doctype and call it a rename // { foreach (var attempt in attempts.Where(x => x.Success)) { this.CleanUp(item, attempt.FileName, Path.Combine(rootFolder, this.DefaultFolder)); } // } } } protected virtual void EventMovedItem(IService sender, MoveEventArgs<TObject> e) { if (uSync8BackOffice.eventsPaused) return; foreach (var item in e.MoveInfoCollection) { var attempts = Export(item.Entity, Path.Combine(rootFolder, this.DefaultFolder), DefaultConfig); if (!(this.DefaultConfig.GuidNames && this.DefaultConfig.UseFlatStructure)) { foreach (var attempt in attempts.Where(x => x.Success)) { this.CleanUp(item.Entity, attempt.FileName, Path.Combine(rootFolder, this.DefaultFolder)); } } } } protected virtual void ExportDeletedItem(TObject item, string folder, HandlerSettings config) { if (item == null) return; var filename = GetPath(folder, item, config.GuidNames, config.UseFlatStructure); var attempt = serializer.SerializeEmpty(item, SyncActionType.Delete, string.Empty); if (attempt.Success) { syncFileService.SaveXElement(attempt.Item, filename); this.CleanUp(item, filename, Path.Combine(rootFolder, this.DefaultFolder)); } } /// <summary> /// Cleans up the handler folder, removing duplicate configs for this item /// </summary> /// <remarks> /// e.g if someone renames a thing (and we are using the name in the file) /// this will clean anything else in the folder that has that key / alias /// </remarks> /// </summary> protected virtual void CleanUp(TObject item, string newFile, string folder) { var physicalFile = syncFileService.GetAbsPath(newFile); var files = syncFileService.GetFiles(folder, "*.config"); foreach (string file in files) { // compare the file paths. if (!syncFileService.PathMatches(physicalFile, file)) // This is not the same file, as we are saving. { try { var node = syncFileService.LoadXElement(file); // if this xml file matches the item we have just saved. if (!node.IsEmptyItem() || node.GetEmptyAction() != SyncActionType.Rename) { // the node isn't empty, or its not a rename (because all clashes become renames) if (DoItemsMatch(node, item)) { logger.Debug(handlerType, "Duplicate {file} of {alias}, saving as rename", Path.GetFileName(file), this.GetItemAlias(item)); var attempt = serializer.SerializeEmpty(item, SyncActionType.Rename, node.GetAlias()); if (attempt.Success) { syncFileService.SaveXElement(attempt.Item, file); } } } } catch (Exception ex) { logger.Warn(handlerType, "Error during cleanup of existing files {message}", ex.Message); // cleanup should fail silently ? - because it can impact on normal Umbraco operations? } } } var folders = syncFileService.GetDirectories(folder); foreach (var children in folders) { CleanUp(item, newFile, children); } } #endregion abstract protected TObject GetFromService(int id); abstract protected TObject GetFromService(Guid key); abstract protected TObject GetFromService(string alias); abstract protected TObject GetFromService(TContainer item); abstract protected void DeleteViaService(TObject item); virtual protected TContainer GetContainer(Guid key) => default; virtual protected TContainer GetContainer(int id) => default; abstract protected string GetItemPath(TObject item, bool useGuid, bool isFlat); abstract protected string GetItemName(TObject item); virtual protected string GetItemAlias(TObject item) => GetItemName(item); virtual protected string GetPath(string folder, TObject item, bool GuidNames, bool isFlat) { if (isFlat && GuidNames) return Path.Combine(folder, $"{GetItemKey(item)}.config"); var path = Path.Combine(folder, $"{this.GetItemPath(item, GuidNames, isFlat)}.config"); // if this is flat but not using guid filenames, then we check for clashes. if (isFlat && !GuidNames) return CheckAndFixFileClash(path, item); return path; } abstract protected Guid GetItemKey(TObject item); /// <summary> /// Get a clean filename that doesn't clash with any existing items. /// </summary> /// <remarks> /// clashes we want to resolve can occur when the safeFilename for an item /// matches with the safe file name for something else. e.g /// 1 Special Doctype /// 2 Special Doctype /// /// Will both resolve to SpecialDocType.Config /// /// the first item to be written to disk for a clash will get the 'normal' name /// all subsequent items will get the appended name. /// /// this can be completely sidesteped by using guid filenames. /// </remarks> virtual protected string CheckAndFixFileClash(string path, TObject item) { if (syncFileService.FileExists(path)) { var node = syncFileService.LoadXElement(path); if (node == null) return path; if (GetItemKey(item) == node.GetKey()) return path; if (GetXmlMatchString(node) == GetItemMatchString(item)) return path; // get here we have a clash, we should append something var append = GetItemKey(item).ToShortKeyString(8); // (this is the shortened guid like media folders do) return Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path) + "_" + append + Path.GetExtension(path)); } return path; } /// <summary> /// a string we use to match this item, with other (where there are levels) /// </summary> /// <remarks> /// this works because unless it's content/media you can't actually have /// clashing aliases at diffrent levels in the folder structure. /// /// So just checking the alias works, for content we overwrite these two functions. /// </remarks> protected virtual string GetItemMatchString(TObject item) => GetItemAlias(item); protected virtual string GetXmlMatchString(XElement node) => node.GetAlias(); /// <summary> /// Rename an item /// </summary> /// <remarks> /// This doesn't get called, because renames generally are handled in the serialization because we match by key. /// </remarks> virtual public uSyncAction Rename(TObject item) => new uSyncAction(); /// <summary> /// Setup any events or other things we need to do when the event handler is started. /// </summary> public void Initialize(HandlerSettings settings) { InitializeEvents(settings); } public void Terminate(HandlerSettings settings) { TerminateEvents(settings); } #region ISyncHandler2 Methods public virtual string Group { get; protected set; } = uSyncBackOfficeConstants.Groups.Settings; public IEnumerable<uSyncAction> Report(string file, HandlerSettings config) => ReportItem(file, config); public SyncAttempt<XElement> GetElement(Udi udi) { var element = FindByUdi(udi); if (element != null) return SerializeItem(element, new SyncSerializerOptions()); return SyncAttempt<XElement>.Fail(udi.ToString(), ChangeType.Fail, "Item not found"); } private TObject FindByUdi(Udi udi) { switch (udi) { case GuidUdi guidUdi: return GetFromService(guidUdi.Guid); case StringUdi stringUdi: return GetFromService(stringUdi.Id); } return default; } public IEnumerable<uSyncDependency> GetDependencies(Guid key, DependencyFlags flags) { if (key == Guid.Empty) { return GetContainerDependencies(default, flags); } else { var item = this.GetFromService(key); if (item == null) { var container = this.GetContainer(key); if (container != null) { return GetContainerDependencies(container, flags); } return Enumerable.Empty<uSyncDependency>(); } return GetDependencies(item, flags); } } public IEnumerable<uSyncDependency> GetDependencies(int id, DependencyFlags flags) { // get them from the root. if (id == -1) return GetContainerDependencies(default, flags); var item = this.GetFromService(id); if (item == null) { var container = this.GetContainer(id); if (container != null) { return GetContainerDependencies(container, flags); } return Enumerable.Empty<uSyncDependency>(); } return GetDependencies(item, flags); } private bool HasDependencyCheckers() => dependencyCheckers != null && dependencyCheckers.Count > 0; protected IEnumerable<uSyncDependency> GetDependencies(TObject item, DependencyFlags flags) { if (item == null || !HasDependencyCheckers()) return Enumerable.Empty<uSyncDependency>(); var dependencies = new List<uSyncDependency>(); foreach (var checker in dependencyCheckers) { dependencies.AddRange(checker.GetDependencies(item, flags)); } return dependencies; } private IEnumerable<uSyncDependency> GetContainerDependencies(TContainer parent, DependencyFlags flags) { if (!HasDependencyCheckers()) return Enumerable.Empty<uSyncDependency>(); var dependencies = new List<uSyncDependency>(); var containers = GetFolders(parent); if (containers != null && containers.Any()) { foreach (var container in containers) { dependencies.AddRange(GetContainerDependencies(container, flags)); } } var children = GetChildItems(parent); if (children != null && children.Any()) { foreach (var child in children) { var childItem = GetFromService(child); if (childItem != null) { foreach (var checker in dependencyCheckers) { dependencies.AddRange(checker.GetDependencies(childItem, flags)); } } } } return dependencies.DistinctBy(x => x.Udi.ToString()).OrderByDescending(x => x.Order); } #endregion #region Serializer Calls #pragma warning disable CS0618 // Type or member is obsolete private SyncAttempt<XElement> SerializeItem(TObject item, SyncSerializerOptions options) { if (serializer is ISyncOptionsSerializer<TObject> optionSerializer) return optionSerializer.Serialize(item, options); return serializer.Serialize(item); } private SyncAttempt<TObject> DeserializeItem(XElement node, SyncSerializerOptions options) { if (serializer is ISyncOptionsSerializer<TObject> optionSerializer) return optionSerializer.Deserialize(node, options); return serializer.Deserialize(node, options.Flags); } private SyncAttempt<TObject> DeserializeItemSecondPass(TObject item, XElement node, SyncSerializerOptions options) { if (serializer is ISyncOptionsSerializer<TObject> optionSerializer) return optionSerializer.DeserializeSecondPass(item, node, options); return serializer.DeserializeSecondPass(item, node, options.Flags); } private SyncChangeInfo IsItemCurrent(XElement node, SyncSerializerOptions options) { var change = new SyncChangeInfo(); change.CurrentNode = SerializeFromNode(node, options); switch (serializer) { case ISyncNodeSerializer<TObject> nodeSerializer: change.Change = nodeSerializer.IsCurrent(node, change.CurrentNode, options); break; case ISyncOptionsSerializer<TObject> optionSerializer: change.Change = optionSerializer.IsCurrent(node, options); break; default: change.Change = serializer.IsCurrent(node); break; } return change; } #pragma warning restore CS0618 // Type or member is obsolete private XElement SerializeFromNode(XElement node, SyncSerializerOptions options) { var item = serializer.FindItem(node); if (item != null) { var cultures = node.GetCultures(); if (!string.IsNullOrWhiteSpace(cultures)) { // the cultures we serialize should match any in the file. // this means we then only check the same values at each end. options.Settings[uSyncConstants.CultureKey] = cultures; } var attempt = this.SerializeItem(item, options); if (attempt.Success) return attempt.Item; } return null; } private class SyncChangeInfo { public ChangeType Change { get; set; } public XElement CurrentNode { get; set; } } #endregion private string GetNameFromFileOrNode(string filename, XElement node) => !string.IsNullOrWhiteSpace(filename) ? filename : node.GetAlias(); private string GetCacheKeyBase() => $"keycache_{this.Alias}_{Thread.CurrentThread.ManagedThreadId}"; private string PrepCaches() { if (this.serializer is ISyncCachedSerializer cachedSerializer) cachedSerializer.InitializeCache(); // make sure the runtime cache is clean. var key = GetCacheKeyBase(); // this also cleares the folder cache - as its a starts with call. runtimeCache.ClearByKey(key); return key; } private void CleanCaches(string cacheKey) { runtimeCache.ClearByKey(cacheKey); if (this.serializer is ISyncCachedSerializer cachedSerializer) cachedSerializer.DisposeCache(); } } }
40.175985
200
0.559577
[ "MPL-2.0" ]
daisy-jump/uSync
uSync8.BackOffice/SyncHandlers/SyncHandlerRoot.cs
63,239
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. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftLeftLogicalInt6464() { var test = new ImmUnaryOpTest__ShiftLeftLogicalInt6464(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Avx.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftLeftLogicalInt6464 { private struct TestStruct { public Vector256<Int64> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref testStruct._fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogicalInt6464 testClass) { var result = Avx2.ShiftLeftLogical(_fld, 64); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 32; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static readonly int RetElementCount = Unsafe.SizeOf<Vector256<Int64>>() / sizeof(Int64); private static Int64[] _data = new Int64[Op1ElementCount]; private static Vector256<Int64> _clsVar; private Vector256<Int64> _fld; private SimpleUnaryOpTest__DataTable<Int64, Int64> _dataTable; static ImmUnaryOpTest__ShiftLeftLogicalInt6464() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _clsVar), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); } public ImmUnaryOpTest__ShiftLeftLogicalInt6464() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector256<Int64>, byte>(ref _fld), ref Unsafe.As<Int64, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector256<Int64>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = TestLibrary.Generator.GetInt64(); } _dataTable = new SimpleUnaryOpTest__DataTable<Int64, Int64>(_data, new Int64[RetElementCount], LargestVectorSize); } public bool IsSupported => Avx2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Avx2.ShiftLeftLogical( Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Avx2.ShiftLeftLogical( Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Avx2.ShiftLeftLogical( Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)), 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Avx2).GetMethod(nameof(Avx2.ShiftLeftLogical), new Type[] { typeof(Vector256<Int64>), typeof(byte) }) .Invoke(null, new object[] { Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)), (byte)64 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector256<Int64>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Avx2.ShiftLeftLogical( _clsVar, 64 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector256<Int64>>(_dataTable.inArrayPtr); var result = Avx2.ShiftLeftLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Avx.LoadVector256((Int64*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftLeftLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Avx.LoadAlignedVector256((Int64*)(_dataTable.inArrayPtr)); var result = Avx2.ShiftLeftLogical(firstOp, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { var test = new ImmUnaryOpTest__ShiftLeftLogicalInt6464(); var result = Avx2.ShiftLeftLogical(test._fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { var result = Avx2.ShiftLeftLogical(_fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { var test = TestStruct.Create(); var result = Avx2.ShiftLeftLogical(test._fld, 64); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector256<Int64> firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Int64[] inArray = new Int64[Op1ElementCount]; Int64[] outArray = new Int64[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector256<Int64>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int64, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector256<Int64>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Int64[] firstOp, Int64[] result, [CallerMemberName] string method = "") { if (0 != result[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (0 != result[i]) { Succeeded = false; break; } } } if (!Succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Avx2)}.{nameof(Avx2.ShiftLeftLogical)}<Int64>(Vector256<Int64><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); } } } }
38.567797
185
0.565443
[ "MIT" ]
MSHOY/coreclr
tests/src/JIT/HardwareIntrinsics/X86/Avx2/ShiftLeftLogical.Int64.64.cs
13,653
C#
using System; namespace Client.UI { public class UIGameOverWindowController:UIController<UIGameOverWindow,UIGameOverWindowController> { protected override string _windowResource { get { return "prefabs/ui/scene/uiovergamenew.ab"; } } protected override void _OnLoad () { } protected override void _OnHide () { } protected override void _OnShow () { } protected override void _Dispose () { } public override void Tick(float deltaTime) { } //public override void Tick (float deltaTime) //{ // if (null != _window && this.getVisible ()) // { // var window = _window as UIGameOverWindow; // window.Tick (deltaTime); // } //} public void ShowOverScene() { if (null != _window && this.getVisible ()) { var window = _window as UIGameOverWindow; window.ShowOverScene (); } } public void HideOverScene() { if (null != _window && this.getVisible ()) { var window = _window as UIGameOverWindow; window.HideOverScene (); } } } }
17.805556
99
0.519501
[ "Apache-2.0" ]
rusmass/wealthland_client
arpg_prg/client_prg/Assets/Code/Client/UI/UIGameOver/UIGameOverWindowController.cs
1,284
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 TestExample.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
35.354839
152
0.565693
[ "MIT" ]
MrL8199/NNLT2_WinForm_Example
Properties/Settings.Designer.cs
1,098
C#
/* * Copyright © 2017-2019 Tånneryd IT AB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace Tanneryd.BulkOperations.EF6.NET47.Tests.Models.DM.Prices { public class Price { public int Id { get; set; } public DateTime Date { get; set; } public string Name { get; set; } public decimal? Value { get; set; } } }
29.366667
74
0.700341
[ "Apache-2.0" ]
360imprimir/ef6-bulk-operations
Tanneryd.BulkOperations.EF6/Tanneryd.BulkOperations.EF6.NET47.Tests/Models/DM/Prices/Price.cs
885
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using Bytes2you.Validation; using Parser.Common.Contracts; using Parser.LogFile.Parser.Contracts; using Parser.LogFile.Parser.Factories; namespace Parser.LogFile.Parser.Managers { public class LogFileParserEngineManager : ILogFileParserEngineManager { private const string RequestedEngineNotFoundErrorMessage = "Requested engine not found."; private readonly IGuidStringProvider guidStringProvider; private readonly ILogFileParserEngineFactory logFileParserEngineFactory; private readonly ConcurrentDictionary<string, ILogFileParserEngine> logFileParserEngines; private readonly ConcurrentDictionary<string, ILogFileParserEngine> logFileParserEnginesByUser; private readonly ConcurrentDictionary<string, string> usernamesByEngineId; public LogFileParserEngineManager(IGuidStringProvider guidStringProvider, ILogFileParserEngineFactory logFileParserEngineFactory) { Guard.WhenArgument(guidStringProvider, nameof(IGuidStringProvider)).IsNull().Throw(); Guard.WhenArgument(logFileParserEngineFactory, nameof(ILogFileParserEngineFactory)).IsNull().Throw(); this.guidStringProvider = guidStringProvider; this.logFileParserEngineFactory = logFileParserEngineFactory; this.logFileParserEngines = new ConcurrentDictionary<string, ILogFileParserEngine>(); this.logFileParserEnginesByUser = new ConcurrentDictionary<string, ILogFileParserEngine>(); this.usernamesByEngineId = new ConcurrentDictionary<string, string>(); } protected IDictionary<string, ILogFileParserEngine> LogFileParserEngines { get { return this.logFileParserEngines; } } public ILogFileParserEngine FindLogFileParserEngineByUsername(string username) { if (this.logFileParserEnginesByUser.ContainsKey(username)) { return this.logFileParserEnginesByUser[username]; } return null; } public void EnqueueCommandEnumerationToEngineWithId(string engineId, IEnumerable<ICommand> commandEnumeration) { Guard.WhenArgument(commandEnumeration, nameof(commandEnumeration)).IsNull().Throw(); foreach (var command in commandEnumeration) { this.EnqueueCommandToEngineWithId(engineId, command); } } public void EnqueueCommandToEngineWithId(string engineId, ICommand command) { Guard.WhenArgument(engineId, nameof(engineId)).IsNullOrEmpty().Throw(); Guard.WhenArgument(command, nameof(ICommand)).IsNull().Throw(); var logFileParserEnginesContainsKey = this.logFileParserEngines.ContainsKey(engineId); if (logFileParserEnginesContainsKey) { var requestedEngine = this.logFileParserEngines[engineId]; requestedEngine.EnqueueCommand(command); } else { throw new ArgumentException(LogFileParserEngineManager.RequestedEngineNotFoundErrorMessage); } } public string StopLogFileParserEngine(string engineId) { Guard.WhenArgument(engineId, nameof(engineId)).IsNullOrEmpty().Throw(); var logFileParserEnginesContainsKey = this.logFileParserEngines.ContainsKey(engineId); if (logFileParserEnginesContainsKey) { ILogFileParserEngine outParameter; if (this.logFileParserEngines.TryRemove(engineId, out outParameter)) { var usernamesByEngineIdContainsEngineId = this.usernamesByEngineId.ContainsKey(engineId); if (usernamesByEngineIdContainsEngineId) { var username = this.usernamesByEngineId[engineId]; this.logFileParserEnginesByUser.TryRemove(username, out outParameter); } } return engineId; } else { throw new ArgumentException(LogFileParserEngineManager.RequestedEngineNotFoundErrorMessage); } } public string StartLogFileParserEngine(string username) { var newEngineId = this.guidStringProvider.NewGuidString(); var newEngine = this.logFileParserEngineFactory.CreateLogFileParserEngine(); this.logFileParserEngines.TryAdd(newEngineId, newEngine); this.AssignNewEngineToUsername(username, newEngineId, newEngine); return newEngineId; } private void AssignNewEngineToUsername(string username, string engineId, ILogFileParserEngine engine) { if (string.IsNullOrEmpty(username)) { return; } var logFileParserEnginesByUserContainsUsername = this.logFileParserEnginesByUser.ContainsKey(username); if (!logFileParserEnginesByUserContainsUsername) { this.logFileParserEnginesByUser.TryAdd(username, engine); } else { this.logFileParserEnginesByUser[username] = engine; } this.usernamesByEngineId.TryAdd(engineId, username); } } }
39.955882
137
0.66636
[ "MIT" ]
shakuu/parser
Parser/Src/Parser.LogFile.Parser/Managers/LogFileParserEngineManager.cs
5,436
C#
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange // // Copyright (c) 2005-2016 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion #if GDI using System.Drawing; using System.Drawing.Drawing2D; #endif #if WPF using System.Windows.Media; #endif namespace PdfSharp.Drawing { // In GDI+ the functions Save/Restore, BeginContainer/EndContainer, Transform, SetClip and ResetClip // can be combined in any order. E.g. you can set a clip region, save the graphics state, empty the // clip region and draw without clipping. Then you can restore to the previous clip region. With PDF // this behavior is hard to implement. To solve this problem I first an automaton that keeps track // of all clipping paths and the current transformation when the clip path was set. The automation // manages a PDF graphics state stack to calculate the desired bahaviour. It also takes into consideration // not to multiply with inverse matrixes when the user sets a new transformation matrix. // After the design works on pager I decided not to implement it because it is much to large-scale. // Instead I lay down some rules how to use the XGraphics class. // // * Before you set a transformation matrix save the graphics state (Save) or begin a new container // (BeginContainer). // // * Instead of resetting the transformation matrix, call Restore or EndContainer. If you reset the // transformation, in PDF must be multiplied with the inverse matrix. That leads to round off errors // because in PDF file only 3 digits are used and Acrobat internally uses fixed point numbers (until // versioin 6 or 7 I think). // // * When no clip path is defined, you can set or intersect a new path. // // * When a clip path is already defined, you can always intersect with a new one (wich leads in general // to a smaller clip region). // // * When a clip path is already defined, you can only reset it to the empty region (ResetClip) when // the graphics state stack is at the same position as it had when the clip path was defined. Otherwise // an error occurs. // // Keeping these rules leads to easy to read code and best results in PDF output. /// <summary> /// Represents the internal state of an XGraphics object. /// Used when the state is saved and restored. /// </summary> internal class InternalGraphicsState { public InternalGraphicsState(XGraphics gfx) { _gfx = gfx; } public InternalGraphicsState(XGraphics gfx, XGraphicsState state) { _gfx = gfx; State = state; State.InternalState = this; } public InternalGraphicsState(XGraphics gfx, XGraphicsContainer container) { _gfx = gfx; container.InternalState = this; } /// <summary> /// Gets or sets the current transformation matrix. /// </summary> public XMatrix Transform { get { return _transform; } set { _transform = value; } } XMatrix _transform; /// <summary> /// Called after this instanced was pushed on the internal graphics stack. /// </summary> public void Pushed() { #if GDI // Nothing to do. #endif #if WPF && !SILVERLIGHT // Nothing to do. #endif #if SILVERLIGHT // Save current level of Canvas stack. _stackLevel = _gfx._dc.Level; // Create new Canvas for subsequent UIElements. _gfx._dc.PushCanvas(); #endif } /// <summary> /// Called after this instanced was popped from the internal graphics stack. /// </summary> public void Popped() { Invalid = true; #if GDI // Nothing to do. #endif #if WPF && !SILVERLIGHT // Pop all objects pushed in this state. if (_gfx.TargetContext == XGraphicTargetContext.WPF) { for (int idx = 0; idx < _transformPushLevel; idx++) _gfx._dc.Pop(); _transformPushLevel = 0; for (int idx = 0; idx < _geometryPushLevel; idx++) _gfx._dc.Pop(); _geometryPushLevel = 0; } #endif #if SILVERLIGHT // Pop all Canvas objects created in this state. _gfx._dc.Pop(_gfx._dc.Level - _stackLevel); #endif } public bool Invalid; #if GDI_ /// <summary> /// The GDI+ GraphicsState if contructed from XGraphicsState. /// </summary> public GraphicsState GdiGraphicsState; #endif #if WPF && !SILVERLIGHT public void PushTransform(MatrixTransform transform) { _gfx._dc.PushTransform(transform); _transformPushLevel++; } int _transformPushLevel; public void PushClip(Geometry geometry) { _gfx._dc.PushClip(geometry); _geometryPushLevel++; } int _geometryPushLevel; #endif #if SILVERLIGHT public void PushTransform(MatrixTransform transform) { _gfx._dc.PushTransform(transform); } public void PushClip(Geometry geometry) { _gfx._dc.PushClip(geometry); } int _stackLevel; #endif readonly XGraphics _gfx; internal XGraphicsState State; } }
34.601036
110
0.642258
[ "Unlicense" ]
Ezeji/PdfSharp.Xamarin
Library/PdfSharp.Shared/Drawing/InternalGraphicsState.cs
6,678
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // <Area> Nullable - CastClass </Area> // <Title> Nullable type with castclass expr </Title> // <Description> // checking type of ulong using cast expr // </Description> // <RelatedBugs> </RelatedBugs> //<Expects Status=success></Expects> // <Code> using System.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQ(object o) { return Helper.Compare((ulong)(IComparable)o, Helper.Create(default(ulong))); } private static bool BoxUnboxToQ(object o) { return Helper.Compare((ulong?)(IComparable)o, Helper.Create(default(ulong))); } private static int Main() { ulong? s = Helper.Create(default(ulong)); if (BoxUnboxToNQ(s) && BoxUnboxToQ(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
24.341463
85
0.658317
[ "MIT" ]
2m0nd/runtime
src/tests/JIT/jit64/valuetypes/nullable/castclass/interface/castclass-interface015.cs
998
C#
using System; using System.Collections.Generic; using System.Text; namespace CFX.Production.ReworkAndRepair { /// <summary> /// CFX Topic implemented by endpoints which are involved in the repair and rework of defective or /// otherwise problematic production units discovered at any point in the production process, or later. /// </summary> internal static class NamespaceDoc { } }
29.5
107
0.726392
[ "Apache-2.0" ]
IPCConnectedFactoryExchange/CFX
CFX/Production/ReworkAndRepair/NamespaceDoc.cs
415
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.Win32; using System.IO; namespace ImageRegistrator { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private List<string> FilesToOpen = new List<string>(); private List<Image> Images = new List<Image>(); private int currentimage = 0; private int channel1=0; private int channel2=1; public MainWindow() { InitializeComponent(); } private void btnOpenFile_Click(object sender, RoutedEventArgs e) { FilesToOpen.Clear(); OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "tiff files (*.tif; *.tiff)|*.tif; *.tiff|All files (*.*)|*.*"; openFileDialog.Multiselect = true; if (openFileDialog.ShowDialog() == true) { if (openFileDialog.FileNames.Length > 0) { FilesToOpen.Clear(); foreach (string filename in openFileDialog.FileNames) FilesToOpen.Add(System.IO.Path.GetFullPath(filename)); UI_filenumberCounter.Content = FilesToOpen.Count; Images.Clear(); foreach (var file in FilesToOpen) { Images.Add(new Image(file)); } currentimage = 0; Images[currentimage].Load(); UI_Viewcounter.Content = currentimage + 1; UI_displayImage.Source = Image.ArrayToBitmap(Images[currentimage].imageArray, channel1, channel2, Images[currentimage].bytesPerSample); UI_C1Selector.Items.Clear(); UI_C2Selector.Items.Clear(); for (int i = 0; i < Images[currentimage].channels; i++) { UI_C1Selector.Items.Add("Chan " + (i+1).ToString()); UI_C2Selector.Items.Add("Chan " + (i + 1).ToString()); } UI_C1Selector.SelectedIndex = 0; UI_C2Selector.SelectedIndex = 1; } } } private void NextImage(object sender, MouseButtonEventArgs e) { NextImage(); } private void NextImage() { if ((currentimage + 1) < Images.Count) { currentimage++; if (!Images[currentimage].loaded) Images[currentimage].Load(); else { //nothing } UI_displayImage.Source= Image.ArrayToBitmap(Images[currentimage].imageArray, channel1, channel2, Images[currentimage].bytesPerSample); UI_Viewcounter.Content = currentimage +1; if(currentimage - 10 >= 0) Images[currentimage - 10].Unload(); } else { } } private void PrevImage(object sender, MouseButtonEventArgs e) { PrevImage(); } private void PrevImage() { if ((currentimage - 1) >= 0) { currentimage--; if (!Images[currentimage].loaded) Images[currentimage].Load(); else { //do nothing } UI_Viewcounter.Content = currentimage + 1; UI_displayImage.Source = Image.ArrayToBitmap(Images[currentimage].imageArray, channel1, channel2, Images[currentimage].bytesPerSample); if (currentimage + 10 < Images.Count) Images[currentimage + 10].Unload(); } else { } } private void ChannelSelectionChanged(object sender, SelectionChangedEventArgs e) { if(UI_C1Selector.SelectedIndex >= 0) channel1 = UI_C1Selector.SelectedIndex; if (UI_C2Selector.SelectedIndex >= 0) channel2 = UI_C2Selector.SelectedIndex; UI_displayImage.Source = Image.ArrayToBitmap(Images[currentimage].imageArray, channel1, channel2, Images[currentimage].bytesPerSample); } private void PrevImage(object sender, RoutedEventArgs e) { PrevImage(); } private void NextImage(object sender, RoutedEventArgs e) { NextImage(); } private void button6_Click(object sender, RoutedEventArgs e) { } private void button2_Click(object sender, RoutedEventArgs e) { } } }
29.544944
155
0.525956
[ "Unlicense" ]
VladimirAkopyan/Heimdall-Imaging
ImageRegistrator/MainWindow.xaml.cs
5,261
C#
using CommandLine; using GVFS.Common; using GVFS.Common.FileSystem; using GVFS.Common.Git; using GVFS.Common.Http; using GVFS.Common.Tracing; using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; namespace GVFS.CommandLine { [Verb(DiagnoseVerb.DiagnoseVerbName, HelpText = "Diagnose issues with a GVFS repo")] public class DiagnoseVerb : GVFSVerb.ForExistingEnlistment { private const string DiagnoseVerbName = "diagnose"; private const string DeprecatedUpgradeLogsDirectory = "Logs"; private TextWriter diagnosticLogFileWriter; private PhysicalFileSystem fileSystem; public DiagnoseVerb() : base(false) { this.fileSystem = new PhysicalFileSystem(); } protected override string VerbName { get { return DiagnoseVerbName; } } protected override void Execute(GVFSEnlistment enlistment) { string diagnosticsRoot = Path.Combine(enlistment.DotGVFSRoot, "diagnostics"); if (!Directory.Exists(diagnosticsRoot)) { Directory.CreateDirectory(diagnosticsRoot); } string archiveFolderPath = Path.Combine(diagnosticsRoot, "gvfs_" + DateTime.Now.ToString("yyyyMMdd_HHmmss")); Directory.CreateDirectory(archiveFolderPath); using (FileStream diagnosticLogFile = new FileStream(Path.Combine(archiveFolderPath, "diagnostics.log"), FileMode.CreateNew)) using (this.diagnosticLogFileWriter = new StreamWriter(diagnosticLogFile)) { this.WriteMessage("Collecting diagnostic info into temp folder " + archiveFolderPath); this.WriteMessage(string.Empty); this.WriteMessage("gvfs version " + ProcessHelper.GetCurrentProcessVersion()); GitVersion gitVersion = null; string error = null; if (!string.IsNullOrEmpty(enlistment.GitBinPath) && GitProcess.TryGetVersion(enlistment.GitBinPath, out gitVersion, out error)) { this.WriteMessage("git version " + gitVersion.ToString()); } else { this.WriteMessage("Could not determine git version. " + error); } this.WriteMessage(enlistment.GitBinPath); this.WriteMessage(string.Empty); this.WriteMessage("Enlistment root: " + enlistment.EnlistmentRoot); this.WriteMessage("Cache Server: " + CacheServerResolver.GetCacheServerFromConfig(enlistment)); string localCacheRoot; string gitObjectsRoot; this.GetLocalCachePaths(enlistment, out localCacheRoot, out gitObjectsRoot); string actualLocalCacheRoot = !string.IsNullOrWhiteSpace(localCacheRoot) ? localCacheRoot : gitObjectsRoot; this.WriteMessage("Local Cache: " + actualLocalCacheRoot); this.WriteMessage(string.Empty); this.PrintDiskSpaceInfo(actualLocalCacheRoot, this.EnlistmentRootPathParameter); this.RecordVersionInformation(); this.ShowStatusWhileRunning( () => this.RunAndRecordGVFSVerb<StatusVerb>(archiveFolderPath, "gvfs_status.txt") != ReturnCode.Success || this.RunAndRecordGVFSVerb<UnmountVerb>(archiveFolderPath, "gvfs_unmount.txt", verb => verb.SkipLock = true) == ReturnCode.Success, "Unmounting", suppressGvfsLogMessage: true); this.ShowStatusWhileRunning( () => { // .gvfs this.CopyAllFiles(enlistment.EnlistmentRoot, archiveFolderPath, GVFSPlatform.Instance.Constants.DotGVFSRoot, copySubFolders: false); // driver if (this.FlushKernelDriverLogs()) { string kernelLogsFolderPath = GVFSPlatform.Instance.KernelDriver.LogsFolderPath; // This copy sometimes fails because the OS has an exclusive lock on the etl files. The error is not actionable // for the user so we don't write the error message to stdout, just to our own log file. this.CopyAllFiles(Path.GetDirectoryName(kernelLogsFolderPath), archiveFolderPath, Path.GetFileName(kernelLogsFolderPath), copySubFolders: false, hideErrorsFromStdout: true); } // .git this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Root, copySubFolders: false); this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Hooks.Root, copySubFolders: false); this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Info.Root, copySubFolders: false); this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Logs.Root, copySubFolders: true); this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Refs.Root, copySubFolders: true); this.CopyAllFiles(enlistment.WorkingDirectoryRoot, archiveFolderPath, GVFSConstants.DotGit.Objects.Info.Root, copySubFolders: false); this.LogDirectoryEnumeration(enlistment.WorkingDirectoryRoot, Path.Combine(archiveFolderPath, GVFSConstants.DotGit.Objects.Root), GVFSConstants.DotGit.Objects.Pack.Root, "packs-local.txt"); this.LogLooseObjectCount(enlistment.WorkingDirectoryRoot, Path.Combine(archiveFolderPath, GVFSConstants.DotGit.Objects.Root), GVFSConstants.DotGit.Objects.Root, "objects-local.txt"); // databases this.CopyAllFiles(enlistment.DotGVFSRoot, Path.Combine(archiveFolderPath, GVFSPlatform.Instance.Constants.DotGVFSRoot), GVFSConstants.DotGVFS.Databases.Name, copySubFolders: false); // local cache this.CopyLocalCacheData(archiveFolderPath, localCacheRoot, gitObjectsRoot); // corrupt objects this.CopyAllFiles(enlistment.DotGVFSRoot, Path.Combine(archiveFolderPath, GVFSPlatform.Instance.Constants.DotGVFSRoot), GVFSConstants.DotGVFS.CorruptObjectsName, copySubFolders: false); // service this.CopyAllFiles( GVFSPlatform.Instance.GetDataRootForGVFS(), archiveFolderPath, this.ServiceName, copySubFolders: true); if (GVFSPlatform.Instance.UnderConstruction.SupportsGVFSUpgrade) { // upgrader this.CopyAllFiles( ProductUpgraderInfo.GetParentLogDirectoryPath(), archiveFolderPath, DeprecatedUpgradeLogsDirectory, copySubFolders: true, targetFolderName: Path.Combine(ProductUpgraderInfo.UpgradeDirectoryName, DeprecatedUpgradeLogsDirectory)); this.CopyAllFiles( ProductUpgraderInfo.GetParentLogDirectoryPath(), archiveFolderPath, ProductUpgraderInfo.LogDirectory, copySubFolders: true, targetFolderName: Path.Combine(ProductUpgraderInfo.UpgradeDirectoryName, ProductUpgraderInfo.LogDirectory)); this.LogDirectoryEnumeration( ProductUpgraderInfo.GetUpgradeProtectedDataDirectory(), Path.Combine(archiveFolderPath, ProductUpgraderInfo.UpgradeDirectoryName), ProductUpgraderInfo.DownloadDirectory, "downloaded-assets.txt"); } if (GVFSPlatform.Instance.UnderConstruction.SupportsGVFSConfig) { this.CopyFile(GVFSPlatform.Instance.GetDataRootForGVFS(), archiveFolderPath, LocalGVFSConfig.FileName); } if (!GVFSPlatform.Instance.TryCopyPanicLogs(archiveFolderPath, out string errorMessage)) { this.WriteMessage(errorMessage); } return true; }, "Copying logs"); this.ShowStatusWhileRunning( () => this.RunAndRecordGVFSVerb<MountVerb>(archiveFolderPath, "gvfs_mount.txt") == ReturnCode.Success, "Mounting", suppressGvfsLogMessage: true); this.CopyAllFiles(enlistment.DotGVFSRoot, Path.Combine(archiveFolderPath, GVFSPlatform.Instance.Constants.DotGVFSRoot), "logs", copySubFolders: false); } string zipFilePath = archiveFolderPath + ".zip"; this.ShowStatusWhileRunning( () => { ZipFile.CreateFromDirectory(archiveFolderPath, zipFilePath); this.fileSystem.DeleteDirectory(archiveFolderPath); return true; }, "Creating zip file", suppressGvfsLogMessage: true); this.Output.WriteLine(); this.Output.WriteLine("Diagnostics complete. All of the gathered info, as well as all of the output above, is captured in"); this.Output.WriteLine(zipFilePath); } private void WriteMessage(string message, bool skipStdout = false) { message = message.TrimEnd('\r', '\n'); if (!skipStdout) { this.Output.WriteLine(message); } this.diagnosticLogFileWriter.WriteLine(message); } private void RecordVersionInformation() { string information = GVFSPlatform.Instance.GetOSVersionInformation(); this.diagnosticLogFileWriter.WriteLine(information); } private void CopyFile( string sourceRoot, string targetRoot, string fileName) { string sourceFile = Path.Combine(sourceRoot, fileName); string targetFile = Path.Combine(targetRoot, fileName); try { if (!File.Exists(sourceFile)) { return; } File.Copy(sourceFile, targetFile); } catch (Exception e) { this.WriteMessage( string.Format( "Failed to copy file {0} in {1} with exception {2}", fileName, sourceRoot, e)); } } private void CopyAllFiles( string sourceRoot, string targetRoot, string folderName, bool copySubFolders, bool hideErrorsFromStdout = false, string targetFolderName = null) { string sourceFolder = Path.Combine(sourceRoot, folderName); string targetFolder = Path.Combine(targetRoot, targetFolderName ?? folderName); try { if (!Directory.Exists(sourceFolder)) { return; } this.RecursiveFileCopyImpl(sourceFolder, targetFolder, copySubFolders, hideErrorsFromStdout); } catch (Exception e) { this.WriteMessage( string.Format( "Failed to copy folder {0} in {1} with exception {2}. copySubFolders: {3}", folderName, sourceRoot, e, copySubFolders), hideErrorsFromStdout); } } private void GetLocalCachePaths(GVFSEnlistment enlistment, out string localCacheRoot, out string gitObjectsRoot) { localCacheRoot = null; gitObjectsRoot = null; try { using (ITracer tracer = new JsonTracer(GVFSConstants.GVFSEtwProviderName, "DiagnoseVerb")) { string error; if (RepoMetadata.TryInitialize(tracer, Path.Combine(enlistment.EnlistmentRoot, GVFSPlatform.Instance.Constants.DotGVFSRoot), out error)) { RepoMetadata.Instance.TryGetLocalCacheRoot(out localCacheRoot, out error); RepoMetadata.Instance.TryGetGitObjectsRoot(out gitObjectsRoot, out error); } else { this.WriteMessage("Failed to determine local cache path and git objects root, RepoMetadata error: " + error); } } } catch (Exception e) { this.WriteMessage(string.Format("Failed to determine local cache path and git objects root, Exception: {0}", e)); } finally { RepoMetadata.Shutdown(); } } private void CopyLocalCacheData(string archiveFolderPath, string localCacheRoot, string gitObjectsRoot) { try { string localCacheArchivePath = Path.Combine(archiveFolderPath, GVFSConstants.DefaultGVFSCacheFolderName); Directory.CreateDirectory(localCacheArchivePath); if (!string.IsNullOrWhiteSpace(localCacheRoot)) { // Copy all mapping.dat files in the local cache folder (i.e. mapping.dat, mapping.dat.tmp, mapping.dat.lock) foreach (string filePath in Directory.EnumerateFiles(localCacheRoot, "mapping.dat*")) { string fileName = Path.GetFileName(filePath); try { File.Copy(filePath, Path.Combine(localCacheArchivePath, fileName)); } catch (Exception e) { this.WriteMessage(string.Format( "Failed to copy '{0}' from {1} to {2} with exception {3}", fileName, localCacheRoot, archiveFolderPath, e)); } } } if (!string.IsNullOrWhiteSpace(gitObjectsRoot)) { this.LogDirectoryEnumeration(gitObjectsRoot, localCacheArchivePath, GVFSConstants.DotGit.Objects.Pack.Name, "packs-cached.txt"); this.LogLooseObjectCount(gitObjectsRoot, localCacheArchivePath, string.Empty, "objects-cached.txt"); // Store all commit-graph files this.CopyAllFiles(gitObjectsRoot, localCacheArchivePath, GVFSConstants.DotGit.Objects.Info.Root, copySubFolders: true); } } catch (Exception e) { this.WriteMessage(string.Format("Failed to copy local cache data with exception: {0}", e)); } } private void LogDirectoryEnumeration(string sourceRoot, string targetRoot, string folderName, string logfile) { try { if (!Directory.Exists(targetRoot)) { Directory.CreateDirectory(targetRoot); } string folder = Path.Combine(sourceRoot, folderName); string targetLog = Path.Combine(targetRoot, logfile); List<string> lines = new List<string>(); if (Directory.Exists(folder)) { DirectoryInfo packDirectory = new DirectoryInfo(folder); lines.Add($"Contents of {folder}:"); foreach (FileInfo file in packDirectory.EnumerateFiles()) { lines.Add($"{file.Name, -70} {file.Length, 16}"); } } File.WriteAllLines(targetLog, lines.ToArray()); } catch (Exception e) { this.WriteMessage(string.Format( "Failed to log file sizes for {0} in {1} with exception {2}. logfile: {3}", folderName, sourceRoot, e, logfile)); } } private void LogLooseObjectCount(string sourceRoot, string targetRoot, string folderName, string logfile) { try { if (!Directory.Exists(targetRoot)) { Directory.CreateDirectory(targetRoot); } string objectFolder = Path.Combine(sourceRoot, folderName); string targetLog = Path.Combine(targetRoot, logfile); List<string> lines = new List<string>(); if (Directory.Exists(objectFolder)) { DirectoryInfo objectDirectory = new DirectoryInfo(objectFolder); int countLoose = 0; int countFolders = 0; lines.Add($"Object directory stats for {objectFolder}:"); foreach (DirectoryInfo directory in objectDirectory.EnumerateDirectories()) { if (GitObjects.IsLooseObjectsDirectory(directory.Name)) { countFolders++; int numObjects = directory.EnumerateFiles().Count(); lines.Add($"{directory.Name} : {numObjects, 7} objects"); countLoose += numObjects; } } lines.Add($"Total: {countLoose} loose objects"); } File.WriteAllLines(targetLog, lines.ToArray()); } catch (Exception e) { this.WriteMessage(string.Format( "Failed to log loose object count for {0} in {1} with exception {2}. logfile: {3}", folderName, sourceRoot, e, logfile)); } } private void RecursiveFileCopyImpl(string sourcePath, string targetPath, bool copySubFolders, bool hideErrorsFromStdout) { if (!Directory.Exists(targetPath)) { Directory.CreateDirectory(targetPath); } foreach (string filePath in Directory.EnumerateFiles(sourcePath)) { string fileName = Path.GetFileName(filePath); try { string sourceFilePath = Path.Combine(sourcePath, fileName); if (!GVFSPlatform.Instance.FileSystem.IsSocket(sourceFilePath) && !GVFSPlatform.Instance.FileSystem.IsExecutable(sourceFilePath)) { File.Copy( Path.Combine(sourcePath, fileName), Path.Combine(targetPath, fileName)); } } catch (Exception e) { this.WriteMessage( string.Format( "Failed to copy '{0}' in {1} with exception {2}", fileName, sourcePath, e), hideErrorsFromStdout); } } if (copySubFolders) { DirectoryInfo dir = new DirectoryInfo(sourcePath); foreach (DirectoryInfo subdir in dir.GetDirectories()) { string targetFolderPath = Path.Combine(targetPath, subdir.Name); try { this.RecursiveFileCopyImpl(subdir.FullName, targetFolderPath, copySubFolders, hideErrorsFromStdout); } catch (Exception e) { this.WriteMessage( string.Format( "Failed to copy subfolder '{0}' to '{1}' with exception {2}", subdir.FullName, targetFolderPath, e), hideErrorsFromStdout); } } } } private ReturnCode RunAndRecordGVFSVerb<TVerb>(string archiveFolderPath, string outputFileName, Action<TVerb> configureVerb = null) where TVerb : GVFSVerb, new() { try { using (FileStream file = new FileStream(Path.Combine(archiveFolderPath, outputFileName), FileMode.CreateNew)) using (StreamWriter writer = new StreamWriter(file)) { return this.Execute<TVerb>( this.EnlistmentRootPathParameter, verb => { if (configureVerb != null) { configureVerb(verb); } verb.Output = writer; }); } } catch (Exception e) { this.WriteMessage(string.Format( "Verb {0} failed with exception {1}", typeof(TVerb), e)); return ReturnCode.GenericError; } } private bool FlushKernelDriverLogs() { string errors; bool flushSuccess = GVFSPlatform.Instance.KernelDriver.TryFlushLogs(out errors); this.diagnosticLogFileWriter.WriteLine(errors); return flushSuccess; } private void PrintDiskSpaceInfo(string localCacheRoot, string enlistmentRootParameter) { try { string enlistmentNormalizedPathRoot; string localCacheNormalizedPathRoot; string enlistmentErrorMessage; string localCacheErrorMessage; bool enlistmentSuccess = GVFSPlatform.Instance.TryGetNormalizedPathRoot(enlistmentRootParameter, out enlistmentNormalizedPathRoot, out enlistmentErrorMessage); bool localCacheSuccess = GVFSPlatform.Instance.TryGetNormalizedPathRoot(localCacheRoot, out localCacheNormalizedPathRoot, out localCacheErrorMessage); if (!enlistmentSuccess || !localCacheSuccess) { this.WriteMessage("Failed to acquire disk space information:"); if (!string.IsNullOrEmpty(enlistmentErrorMessage)) { this.WriteMessage(enlistmentErrorMessage); } if (!string.IsNullOrEmpty(localCacheErrorMessage)) { this.WriteMessage(localCacheErrorMessage); } this.WriteMessage(string.Empty); return; } DriveInfo enlistmentDrive = new DriveInfo(enlistmentNormalizedPathRoot); string enlistmentDriveDiskSpace = this.FormatByteCount(enlistmentDrive.AvailableFreeSpace); if (string.Equals(enlistmentNormalizedPathRoot, localCacheNormalizedPathRoot, StringComparison.OrdinalIgnoreCase)) { this.WriteMessage("Available space on " + enlistmentDrive.Name + " drive(enlistment and local cache): " + enlistmentDriveDiskSpace); } else { this.WriteMessage("Available space on " + enlistmentDrive.Name + " drive(enlistment): " + enlistmentDriveDiskSpace); DriveInfo cacheDrive = new DriveInfo(localCacheRoot); string cacheDriveDiskSpace = this.FormatByteCount(cacheDrive.AvailableFreeSpace); this.WriteMessage("Available space on " + cacheDrive.Name + " drive(local cache): " + cacheDriveDiskSpace); } this.WriteMessage(string.Empty); } catch (Exception e) { this.WriteMessage("Failed to acquire disk space information, exception: " + e.ToString()); this.WriteMessage(string.Empty); } } private string FormatByteCount(double byteCount) { const int Divisor = 1024; const string ByteCountFormat = "0.00"; string[] unitStrings = { " B", " KB", " MB", " GB", " TB" }; int unitIndex = 0; while (byteCount >= Divisor && unitIndex < unitStrings.Length - 1) { unitIndex++; byteCount = byteCount / Divisor; } return byteCount.ToString(ByteCountFormat) + unitStrings[unitIndex]; } } }
44.274834
214
0.5178
[ "MIT" ]
continue-nature/VFSForGit
GVFS/GVFS/CommandLine/DiagnoseVerb.cs
26,742
C#
using System; using System.Collections.Generic; using System.Diagnostics; using Newtonsoft.Json; public static class BlockchainTest { public static void Run() { Console.WriteLine("Running tests.."); Seed(); DataSecurity(); ProofOfWork(); Console.WriteLine("All tests passed"); } public static void Seed() { DateTime startTime = DateTime.Now; Chain testCoin = new Chain(); testCoin.AddBlock(new Block(DateTime.Now, null, TestTransactions()[0])); testCoin.AddBlock(new Block(DateTime.Now, null, TestTransactions()[1])); testCoin.AddBlock(new Block(DateTime.Now, null, TestTransactions()[2])); DateTime endTime = DateTime.Now; Console.WriteLine($"Time taken: {endTime - startTime}"); Debug.Assert(testCoin.DataBase[0].PreviousHash == null, "Genesis Block Test Failed", $"The previous block hash should be null"); Console.WriteLine("Genesis Block Test - Passed"); Debug.Assert(testCoin.DataBase.Count > 1, "New Block Test Failed", $"The chain has no new block. Expected {4} new blocks"); Console.WriteLine("New Block Test - Passed"); Console.WriteLine(JsonConvert.SerializeObject(testCoin, Formatting.Indented)); } public static void DataSecurity() { bool blockValidation; Chain testCoin = new Chain(); testCoin.AddBlock(new Block(DateTime.Now, null, TestTransactions()[0])); testCoin.AddBlock(new Block(DateTime.Now, null, TestTransactions()[2])); blockValidation = testCoin.IsChainValid(); Debug.Assert(blockValidation == true, "Data Security Test Failed", $"The chain is valid. Expected {blockValidation}"); Console.WriteLine("Data Security Test (Valid Blockchain) - Passed"); testCoin.DataBase[1].Data = $""; blockValidation = testCoin.IsChainValid(); Debug.Assert(blockValidation == false, "Data Security Test Failed", $"The chain is invalid. Expected {blockValidation}"); Console.WriteLine("Data Security Test (Invalid Blockchain) - Passed"); } public static void ProofOfWork() { string expectedLeadingZeros = new string('0', Config.Difficulty); Chain testCoin = new Chain(); testCoin.AddBlock(new Block(DateTime.Now, null, TestTransactions()[1])); testCoin.AddBlock(new Block(DateTime.Now, null, TestTransactions()[2])); string leadingZeros = GetLeadingZero(testCoin.DataBase[1].Hash); Debug.Assert(leadingZeros == expectedLeadingZeros, "Proof of Work Test Failed", $"Leading zeros is expected to be {expectedLeadingZeros}"); Console.WriteLine("Proof of Work Test - Passed"); } private static string[] TestTransactions() { return new string[] { "{sender:Femi,receiver:Adetayo,amount:10}", "{sender:Adetayo,receiver:Femi,amount:5}", "{sender:Adetayo,receiver:Femi,amount:2}", }; } private static string GetLeadingZero(string str) { string result = ""; foreach(char c in str) { if(c != '0') break; result += c; } return result; } }
35.397849
147
0.62819
[ "MIT" ]
femiayodeji/blockchain
BlockchainTest.cs
3,292
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using NUnit.Framework; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Shapes; using osu.Framework.Input; using osu.Framework.Timing; using osu.Framework.Utils; using osu.Game.Beatmaps; using osu.Game.Beatmaps.ControlPoints; using osu.Game.Configuration; using osu.Game.Rulesets; using osu.Game.Rulesets.Difficulty; using osu.Game.Rulesets.Mods; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Objects.Drawables; using osu.Game.Rulesets.Objects.Types; using osu.Game.Rulesets.Osu; using osu.Game.Rulesets.UI; using osu.Game.Rulesets.UI.Scrolling; using osuTK; using osuTK.Graphics; using JetBrains.Annotations; namespace osu.Game.Tests.Visual.Gameplay { public class TestSceneDrawableScrollingRuleset : OsuTestScene { /// <summary> /// The amount of time visible by the "view window" of the playfield. /// All hitobjects added through <see cref="createBeatmap"/> are spaced apart by this value, such that for a beat length of 1000, /// there will be at most 2 hitobjects visible in the "view window". /// </summary> private const double time_range = 1000; private readonly ManualClock testClock = new ManualClock(); private TestDrawableScrollingRuleset drawableRuleset; [SetUp] public void Setup() => Schedule(() => testClock.CurrentTime = 0); [TestCase("pooled")] [TestCase("non-pooled")] public void TestHitObjectLifetime(string pooled) { var beatmap = createBeatmap(_ => pooled == "pooled" ? new TestPooledHitObject() : new TestHitObject()); beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range }); createTest(beatmap); assertPosition(0, 0f); assertDead(3); setTime(3 * time_range); assertPosition(3, 0f); assertDead(0); setTime(0 * time_range); assertPosition(0, 0f); assertDead(3); } [TestCase("pooled")] [TestCase("non-pooled")] public void TestNestedHitObject(string pooled) { var beatmap = createBeatmap(i => { var h = pooled == "pooled" ? new TestPooledParentHitObject() : new TestParentHitObject(); h.Duration = 300; h.ChildTimeOffset = i % 3 * 100; return h; }); beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range }); createTest(beatmap); assertPosition(0, 0f); assertHeight(0); assertChildPosition(0); setTime(5 * time_range); assertPosition(5, 0f); assertHeight(5); assertChildPosition(5); } [TestCase("pooled")] [TestCase("non-pooled")] public void TestLifetimeRecomputedWhenTimeRangeChanges(string pooled) { var beatmap = createBeatmap(_ => pooled == "pooled" ? new TestPooledHitObject() : new TestHitObject()); beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range }); createTest(beatmap); assertDead(3); AddStep("increase time range", () => drawableRuleset.TimeRange.Value = 3 * time_range); assertPosition(3, 1); } [Test] public void TestRelativeBeatLengthScaleSingleTimingPoint() { var beatmap = createBeatmap(); beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range / 2 }); createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true); assertPosition(0, 0f); // The single timing point is 1x speed relative to itself, such that the hitobject occurring time_range milliseconds later should appear // at the bottom of the view window regardless of the timing point's beat length assertPosition(1, 1f); } [Test] public void TestRelativeBeatLengthScaleTimingPointBeyondEndDoesNotBecomeDominant() { var beatmap = createBeatmap(); beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range / 2 }); beatmap.ControlPointInfo.Add(12000, new TimingControlPoint { BeatLength = time_range }); beatmap.ControlPointInfo.Add(100000, new TimingControlPoint { BeatLength = time_range }); createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true); assertPosition(0, 0f); assertPosition(1, 1f); } [Test] public void TestRelativeBeatLengthScaleFromSecondTimingPoint() { var beatmap = createBeatmap(); beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range }); beatmap.ControlPointInfo.Add(3 * time_range, new TimingControlPoint { BeatLength = time_range / 2 }); createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true); // The first timing point should have a relative velocity of 2 assertPosition(0, 0f); assertPosition(1, 0.5f); assertPosition(2, 1f); // Move to the second timing point setTime(3 * time_range); assertPosition(3, 0f); // As above, this is the timing point that is 1x speed relative to itself, so the hitobject occurring time_range milliseconds later should be at the bottom of the view window assertPosition(4, 1f); } [Test] public void TestNonRelativeScale() { var beatmap = createBeatmap(); beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range }); beatmap.ControlPointInfo.Add(3 * time_range, new TimingControlPoint { BeatLength = time_range / 2 }); createTest(beatmap); assertPosition(0, 0f); assertPosition(1, 1); // Move to the second timing point setTime(3 * time_range); assertPosition(3, 0f); // For a beat length of 500, the view window of this timing point is elongated 2x (1000 / 500), such that the second hitobject is two TimeRanges away (offscreen) // To bring it on-screen, half TimeRange is added to the current time, bringing the second half of the view window into view, and the hitobject should appear at the bottom setTime(3 * time_range + time_range / 2); assertPosition(4, 1f); } [Test] public void TestSliderMultiplierDoesNotAffectRelativeBeatLength() { var beatmap = createBeatmap(); beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range }); beatmap.Difficulty.SliderMultiplier = 2; createTest(beatmap, d => d.RelativeScaleBeatLengthsOverride = true); AddStep("adjust time range", () => drawableRuleset.TimeRange.Value = 5000); for (int i = 0; i < 5; i++) assertPosition(i, i / 5f); } [Test] public void TestSliderMultiplierAffectsNonRelativeBeatLength() { var beatmap = createBeatmap(); beatmap.ControlPointInfo.Add(0, new TimingControlPoint { BeatLength = time_range }); beatmap.Difficulty.SliderMultiplier = 2; createTest(beatmap); AddStep("adjust time range", () => drawableRuleset.TimeRange.Value = 2000); assertPosition(0, 0); assertPosition(1, 1); } /// <summary> /// Get a <see cref="DrawableTestHitObject" /> corresponding to the <paramref name="index"/>'th <see cref="TestHitObject"/>. /// When the hit object is not alive, `null` is returned. /// </summary> [CanBeNull] private DrawableTestHitObject getDrawableHitObject(int index) { var hitObject = drawableRuleset.Beatmap.HitObjects.ElementAt(index); return (DrawableTestHitObject)drawableRuleset.Playfield.HitObjectContainer.AliveObjects.FirstOrDefault(obj => obj.HitObject == hitObject); } private float yScale => drawableRuleset.Playfield.HitObjectContainer.DrawHeight; private void assertDead(int index) => AddAssert($"hitobject {index} is dead", () => getDrawableHitObject(index) == null); private void assertHeight(int index) => AddAssert($"hitobject {index} height", () => { var d = getDrawableHitObject(index); return d != null && Precision.AlmostEquals(d.DrawHeight, yScale * (float)(d.HitObject.Duration / time_range), 0.1f); }); private void assertChildPosition(int index) => AddAssert($"hitobject {index} child position", () => { var d = getDrawableHitObject(index); return d is DrawableTestParentHitObject && Precision.AlmostEquals( d.NestedHitObjects.First().DrawPosition.Y, yScale * (float)((TestParentHitObject)d.HitObject).ChildTimeOffset / time_range, 0.1f); }); private void assertPosition(int index, float relativeY) => AddAssert($"hitobject {index} at {relativeY}", () => Precision.AlmostEquals(getDrawableHitObject(index)?.DrawPosition.Y ?? -1, yScale * relativeY)); private void setTime(double time) { AddStep($"set time = {time}", () => testClock.CurrentTime = time); } /// <summary> /// Creates an <see cref="IBeatmap"/>, containing 10 hitobjects and user-provided timing points. /// The hitobjects are spaced <see cref="time_range"/> milliseconds apart. /// </summary> /// <returns>The <see cref="IBeatmap"/>.</returns> private IBeatmap createBeatmap(Func<int, TestHitObject> createAction = null) { var beatmap = new Beatmap<TestHitObject> { BeatmapInfo = { Ruleset = new OsuRuleset().RulesetInfo } }; for (int i = 0; i < 10; i++) { var h = createAction?.Invoke(i) ?? new TestHitObject(); h.StartTime = i * time_range; beatmap.HitObjects.Add(h); } return beatmap; } private void createTest(IBeatmap beatmap, Action<TestDrawableScrollingRuleset> overrideAction = null) => AddStep("create test", () => { var ruleset = new TestScrollingRuleset(); drawableRuleset = (TestDrawableScrollingRuleset)ruleset.CreateDrawableRulesetWith(CreateWorkingBeatmap(beatmap).GetPlayableBeatmap(ruleset.RulesetInfo)); drawableRuleset.FrameStablePlayback = false; overrideAction?.Invoke(drawableRuleset); Child = new Container { Anchor = Anchor.Centre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.Y, Height = 0.75f, Width = 400, Masking = true, Clock = new FramedClock(testClock), Child = drawableRuleset }; }); #region Ruleset private class TestScrollingRuleset : Ruleset { public override IEnumerable<Mod> GetModsFor(ModType type) => throw new NotImplementedException(); public override DrawableRuleset CreateDrawableRulesetWith(IBeatmap beatmap, IReadOnlyList<Mod> mods = null) => new TestDrawableScrollingRuleset(this, beatmap, mods); public override IBeatmapConverter CreateBeatmapConverter(IBeatmap beatmap) => new TestBeatmapConverter(beatmap, null); public override DifficultyCalculator CreateDifficultyCalculator(IWorkingBeatmap beatmap) => throw new NotImplementedException(); public override string Description { get; } = string.Empty; public override string ShortName { get; } = string.Empty; } private class TestDrawableScrollingRuleset : DrawableScrollingRuleset<TestHitObject> { public bool RelativeScaleBeatLengthsOverride { get; set; } protected override bool RelativeScaleBeatLengths => RelativeScaleBeatLengthsOverride; protected override ScrollVisualisationMethod VisualisationMethod => ScrollVisualisationMethod.Overlapping; public new Bindable<double> TimeRange => base.TimeRange; public TestDrawableScrollingRuleset(Ruleset ruleset, IBeatmap beatmap, IReadOnlyList<Mod> mods = null) : base(ruleset, beatmap, mods) { TimeRange.Value = time_range; } public override DrawableHitObject<TestHitObject> CreateDrawableRepresentation(TestHitObject h) { switch (h) { case TestPooledHitObject _: case TestPooledParentHitObject _: return null; case TestParentHitObject p: return new DrawableTestParentHitObject(p); default: return new DrawableTestHitObject(h); } } protected override PassThroughInputManager CreateInputManager() => new PassThroughInputManager(); protected override Playfield CreatePlayfield() => new TestPlayfield(); } private class TestPlayfield : ScrollingPlayfield { public TestPlayfield() { AddInternal(new Container { RelativeSizeAxes = Axes.Both, Children = new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Alpha = 0.2f, }, new Container { RelativeSizeAxes = Axes.Both, Padding = new MarginPadding { Top = 150 }, Children = new Drawable[] { new Box { Anchor = Anchor.TopCentre, Origin = Anchor.Centre, RelativeSizeAxes = Axes.X, Height = 2, Colour = Color4.Green }, HitObjectContainer } } } }); RegisterPool<TestPooledHitObject, DrawableTestPooledHitObject>(1); RegisterPool<TestPooledParentHitObject, DrawableTestPooledParentHitObject>(1); } } private class TestBeatmapConverter : BeatmapConverter<TestHitObject> { public TestBeatmapConverter(IBeatmap beatmap, Ruleset ruleset) : base(beatmap, ruleset) { } public override bool CanConvert() => true; protected override IEnumerable<TestHitObject> ConvertHitObject(HitObject original, IBeatmap beatmap, CancellationToken cancellationToken) => throw new NotImplementedException(); } #endregion #region HitObject private class TestHitObject : HitObject, IHasDuration { public double EndTime => StartTime + Duration; public double Duration { get; set; } = 100; } private class TestPooledHitObject : TestHitObject { } private class TestParentHitObject : TestHitObject { public double ChildTimeOffset; protected override void CreateNestedHitObjects(CancellationToken cancellationToken) { AddNested(new TestHitObject { StartTime = StartTime + ChildTimeOffset }); } } private class TestPooledParentHitObject : TestParentHitObject { protected override void CreateNestedHitObjects(CancellationToken cancellationToken) { AddNested(new TestPooledHitObject { StartTime = StartTime + ChildTimeOffset }); } } private class DrawableTestHitObject : DrawableHitObject<TestHitObject> { public DrawableTestHitObject([CanBeNull] TestHitObject hitObject) : base(hitObject) { Anchor = Anchor.TopCentre; Origin = Anchor.TopCentre; Size = new Vector2(100, 25); AddRangeInternal(new Drawable[] { new Box { RelativeSizeAxes = Axes.Both, Colour = Color4.LightPink }, new Box { Origin = Anchor.CentreLeft, RelativeSizeAxes = Axes.X, Height = 2, Colour = Color4.Red } }); } protected override void Update() => LifetimeEnd = HitObject.EndTime; } private class DrawableTestPooledHitObject : DrawableTestHitObject { public DrawableTestPooledHitObject() : base(null) { InternalChildren[0].Colour = Color4.LightSkyBlue; InternalChildren[1].Colour = Color4.Blue; } } private class DrawableTestParentHitObject : DrawableTestHitObject { private readonly Container<DrawableHitObject> container; public DrawableTestParentHitObject([CanBeNull] TestHitObject hitObject) : base(hitObject) { InternalChildren[0].Colour = Color4.LightYellow; InternalChildren[1].Colour = Color4.Yellow; AddInternal(container = new Container<DrawableHitObject> { RelativeSizeAxes = Axes.Both, }); } protected override DrawableHitObject CreateNestedHitObject(HitObject hitObject) => new DrawableTestHitObject((TestHitObject)hitObject); protected override void AddNestedHitObject(DrawableHitObject hitObject) => container.Add(hitObject); protected override void ClearNestedHitObjects() => container.Clear(false); } private class DrawableTestPooledParentHitObject : DrawableTestParentHitObject { public DrawableTestPooledParentHitObject() : base(null) { InternalChildren[0].Colour = Color4.LightSeaGreen; InternalChildren[1].Colour = Color4.Green; } } #endregion } }
39.631474
187
0.571098
[ "MIT" ]
MATRIX-feather/osu
osu.Game.Tests/Visual/Gameplay/TestSceneDrawableScrollingRuleset.cs
19,394
C#
namespace QuickView.UI.Windows.Options { public class OptionsViewModel : BindableBase { } }
13.25
48
0.688679
[ "MIT" ]
smithderekm/quickview
src/QuickView.UI.Windows/Options/OptionsViewModel.cs
108
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("1.OddOrEvenInteger")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("1.OddOrEvenInteger")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("534977a1-1ba4-4ec1-bf04-e2048300eb6c")] // 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.081081
84
0.745919
[ "MIT" ]
KaloyanMarshalov/Telerik-Academy-Homeworks
Module One - Programming/CSharp Part One/3.Operators-and-Expressions/1.OddOrEvenInteger/Properties/AssemblyInfo.cs
1,412
C#
using System; using System.IO; using System.Text; namespace Efrpg.Mustache { /// <summary> /// Substitutes a key placeholder with the textual representation of the associated object. /// </summary> internal sealed class KeyMustacheGenerator : IMustacheGenerator { private readonly string _key; private readonly string _format; private readonly bool _isVariable; private readonly bool _isExtension; /// <summary> /// Initializes a new instance of a KeyGenerator. /// </summary> /// <param name="key">The key to substitute with its value.</param> /// <param name="alignment">The alignment specifier.</param> /// <param name="formatting">The format specifier.</param> /// <param name="isExtension">Specifies whether the key was found within triple curly braces.</param> public KeyMustacheGenerator(string key, string alignment, string formatting, bool isExtension) { if (key.StartsWith("@")) { _key = key.Substring(1); _isVariable = true; } else { _key = key; _isVariable = false; } _format = getFormat(alignment, formatting); _isExtension = isExtension; } private static string getFormat(string alignment, string formatting) { StringBuilder formatBuilder = new StringBuilder(); formatBuilder.Append("{0"); if (!String.IsNullOrWhiteSpace(alignment)) { formatBuilder.Append(","); formatBuilder.Append(alignment.TrimStart('+')); } if (!String.IsNullOrWhiteSpace(formatting)) { formatBuilder.Append(":"); formatBuilder.Append(formatting); } formatBuilder.Append("}"); return formatBuilder.ToString(); } void IMustacheGenerator.GetText(TextWriter writer, Scope scope, Scope context, Action<Substitution> postProcessor) { object value = _isVariable ? context.Find(_key, _isExtension) : scope.Find(_key, _isExtension); string result = String.Format(writer.FormatProvider, _format, value); Substitution substitution = new Substitution() { Key = _key, Substitute = result, IsExtension = _isExtension }; postProcessor(substitution); writer.Write(substitution.Substitute); } } }
36.041096
122
0.573926
[ "Apache-2.0" ]
janissimsons/EntityFramework-Reverse-POCO-Code-First-Generator
Generator/Mustache/KeyMustacheGenerator.cs
2,633
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.Remoting.Lifetime; using NetworkFrameworkX.Interface; using NetworkFrameworkX.Share; namespace NetworkFrameworkX.Server { public class PluginServer : MarshalByRefObject, IServer { public IServerConfig Config => this.Server.Config; public IUserCollection<IServerUser> UserList => this.Server.UserList; public IList<string> PluginList => this.Server.PluginList; public long Traffic_In => this.Server.Traffic_In; public long Traffic_Out => this.Server.Traffic_Out; public ISerialzation<string> JsonSerialzation => new JsonSerialzation(); public CallerType Type => CallerType.Console; public ILogger Logger => this.Server.Logger; public IPlugin Plugin { get; private set; } = null; public IServer Server { get; private set; } = null; public FunctionCollection FunctionTable => this.Server.FunctionTable; public FunctionCollection CommandTable => this.Server.CommandTable; public PluginServer(IServer server, IPlugin plugin) { this.Plugin = plugin; this.Server = server; } public int CallCommand(string name, IArguments args, ICaller caller = null) => this.Server.CallCommand(name, args, caller); public int CallCommand(string name, ICaller caller = null) => this.Server.CallCommand(name, caller); public int CallFunction(string name, IArguments args = null) => this.CallFunction(name, args); public void ForceLogout(IServerUser user) => this.Server.ForceLogout(user); public string GetFolderPath(FolderPath path) => this.Server.GetFolderPath(path); } public partial class Server<TConfig> { private void InitializePlugin() { LifetimeServices.LeaseTime = TimeSpan.Zero; LoadAllPlugin(); } private Dictionary<string, PluginLoader> pluginList = new Dictionary<string, PluginLoader>(StringComparer.OrdinalIgnoreCase); public IList<string> PluginList => this.pluginList.Keys.ToList(); public void SavePluginConfig(string name) { if (this.pluginList.ContainsKey(name)) { SavePluginConfig(this.pluginList[name]); } } private void SavePluginConfig(PluginLoader plugin) { DirectoryInfo folder = new DirectoryInfo(Path.Combine(GetFolderPath(FolderPath.PluginConfig), plugin.Name)); if (!folder.Exists) { folder.Create(); } string config = plugin.SerializeConfig(); if (!config.IsNullOrEmpty()) { File.WriteAllText(Path.Combine(folder.FullName, FILE_CONFIG), config); } } public bool LoadPlugin(IPlugin plugin, bool force = false) => LoadPlugin(new PluginLoader(plugin), force); internal bool LoadPlugin(PluginLoader plugin, bool force = false) { if (plugin.RemotePlugin == null || plugin.Name.IsNullOrEmpty()) { this.Logger.Warning(this.lang.PluginLoadError); return false; } if (this.pluginList.ContainsKey(plugin.Name)) { this.Logger.Warning(string.Format(this.lang.PluginNameDuplicate, plugin.Name)); return false; } plugin.Server = new PluginServer(this, plugin); DirectoryInfo folder = new DirectoryInfo(Path.Combine(GetFolderPath(FolderPath.PluginConfig), plugin.Name)); if (!folder.Exists) { folder.Create(); } FileInfo file = new FileInfo(Path.Combine(folder.FullName, FILE_CONFIG)); if (!file.Exists) { SavePluginConfig(plugin); } else { string config = File.ReadAllText(file.FullName); plugin.DeserializeConfig(config); } if (plugin.Config.Enabled || force) { this.pluginList.Add(plugin.Name, plugin); this.Logger.Info(string.Format(this.lang.LoadPlugin, plugin.Name)); plugin.OnLoad(); if (force) { plugin.Config.Enabled = true; SavePluginConfig(plugin); } } else { plugin.Unload(); plugin = null; } return true; } public bool LoadPlugin(string assemblyPath, bool force = false) { FileInfo file = new FileInfo(assemblyPath); string[] path = new string[] { GetFolderPath(FolderPath.Root), file.DirectoryName }; PluginLoader loader = new PluginLoader(assemblyPath, path); return LoadPlugin(loader, force); } public const string PATTERN_DLL = "*.dll"; public void LoadAllPlugin() { DirectoryInfo folderPlugin = new DirectoryInfo(GetFolderPath(FolderPath.Plugin)); foreach (DirectoryInfo folder in folderPlugin.GetDirectories()) { foreach (FileInfo file in folder.GetFiles(PATTERN_DLL)) { if (PluginLoader.ContainsType(file.FullName)) { LoadPlugin(file.FullName); } } } } public void RefreshPluginList() { } public bool UnLoadPlugin(IPlugin plugin) { plugin.OnDestroy(); if (plugin is PluginLoader pluginLoader && pluginLoader.UnLoadable) { return pluginLoader.Unload(); } return false; } public void UnLoadAllPlugin() { foreach (PluginLoader item in this.pluginList.Values) { UnLoadPlugin(item); } } } }
33.913295
133
0.600989
[ "Apache-2.0" ]
28111600/NetworkFrameworkX
NetworkFrameworkX.Server.Core/Server.Plugin.cs
5,867
C#
using System; using System.Linq.Expressions; using System.Net.Http; using System.Reflection; using System.Threading; using System.Threading.Tasks; using Vostok.Clusterclient.Transport.Helpers; using Invoker = System.Func<System.Net.Http.HttpMessageHandler, System.Net.Http.HttpRequestMessage, System.Threading.CancellationToken, System.Threading.Tasks.Task<System.Net.Http.HttpResponseMessage>>; // ReSharper disable AssignNullToNotNullAttribute namespace Vostok.Clusterclient.Transport.Sockets { // ReSharper disable once ClassNeverInstantiated.Global internal class SocketsHandlerInvoker : HttpMessageHandler { private static readonly Invoker invoker; static SocketsHandlerInvoker() { try { invoker = BuildInvoker(); CanInvokeDirectly = true; } catch (Exception error) { Console.Out.WriteLine(error); invoker = (handler, message, token) => new HttpClient(handler).SendAsync(message, HttpCompletionOption.ResponseHeadersRead, token); } } private SocketsHandlerInvoker() { } public static bool CanInvokeDirectly { get; } public static Task<HttpResponseMessage> Invoke(HttpMessageHandler handler, HttpRequestMessage message, CancellationToken token) => invoker(handler, message, token); protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage message, CancellationToken token) => throw new NotSupportedException(); private static Invoker BuildInvoker() { var handlerParameter = Expression.Parameter(typeof(HttpMessageHandler)); var socketHandler = Expression.Convert(handlerParameter, NetCore21Utils.SocketHandlerType); var messageParameter = Expression.Parameter(typeof(HttpRequestMessage)); var tokenParameter = Expression.Parameter(typeof(CancellationToken)); var sendMethod = NetCore21Utils.SocketHandlerType.GetMethod(nameof(SendAsync), BindingFlags.Instance | BindingFlags.NonPublic); var sendMethodCall = Expression.Call(socketHandler, sendMethod, messageParameter, tokenParameter); return Expression.Lambda<Invoker>(sendMethodCall, handlerParameter, messageParameter, tokenParameter).Compile(); } } }
39.393443
202
0.702039
[ "MIT" ]
bymse/clusterclient.transport
Vostok.ClusterClient.Transport/Sockets/SocketsHandlerInvoker.cs
2,405
C#
using System; using CP77SaveEditor.Core.Savegame.Attributes; namespace CP77SaveEditor.Core.Savegame.Values.Journal { public class JEntryAdvancedInfoGuid { [CName("guid")] public Guid Guid { get; set; } } }
21.363636
53
0.689362
[ "MIT" ]
blendermf/CP77SaveEditor
CP77SaveEditor.Core/Savegame/Values/Journal/JEntryAdvancedInfoGuid.cs
237
C#
using Disqord.Models; namespace Disqord.Rest.AuditLogs { public sealed class RoleData { public Optional<string> Name { get; } public Optional<GuildPermissions> Permissions { get; } public Optional<Color?> Color { get; } public Optional<bool> IsHoisted { get; } public Optional<bool> IsMentionable { get; } internal RoleData(RestDiscordClient client, AuditLogEntryModel model, bool isCreated) { var changes = new RoleChanges(client, model); if (isCreated) { Name = changes.Name.NewValue; Permissions = changes.Permissions.NewValue; Color = changes.Color.NewValue; IsHoisted = changes.IsHoisted.NewValue; IsMentionable = changes.IsMentionable.NewValue; } else { Name = changes.Name.OldValue; Permissions = changes.Permissions.OldValue; Color = changes.Color.OldValue; IsHoisted = changes.IsHoisted.OldValue; IsMentionable = changes.IsMentionable.OldValue; } } } }
31.461538
94
0.551752
[ "MIT" ]
FenikkusuKoneko/Disqord
src/Disqord.Rest/Entities/Rest/Guild/AuditLogs/Role/Data/RoleData.cs
1,229
C#
// Copyright (c) Matteo Beltrame // // com.tratteo.gibframe -> GibFrame.SceneManagement : SceneUtil.cs // // All Rights Reserved using UnityEngine; using UnityEngine.SceneManagement; namespace GibFrame.SceneManagement { internal static class SceneUtil { public const string ASYNCLOADER_SCENE_NAME = "AsyncLoaderScene"; internal static void LoadScene(string name) { Time.timeScale = 1F; int index = SceneUtility.GetBuildIndexByScenePath(name); if (index != -1) { SceneManager.LoadScene(index); } } internal static void LoadSceneAsynchronously(string name) { int index = SceneUtility.GetBuildIndexByScenePath(name); if (index != -1) { Time.timeScale = 1F; int asyncSceneIndex = SceneUtility.GetBuildIndexByScenePath(ASYNCLOADER_SCENE_NAME); AsyncLoadIndexSaver.SetIndexToPreload(index); SceneManager.LoadScene(asyncSceneIndex); } } internal static void LoadSceneAsynchronously(int sceneIndex) { LoadSceneAsynchronously(SceneUtility.GetScenePathByBuildIndex(sceneIndex)); } } }
28.931818
100
0.618225
[ "MIT" ]
tratteo/GibFrame
Runtime/Scripts/SceneManagement/SceneUtil.cs
1,275
C#
using System; namespace R5T.Tools.NuGet.Types.Construction { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
16.461538
47
0.523364
[ "MIT" ]
MinexAutomation/R5T.Tools.NuGet.Types
source/R5T.Tools.NuGet.Types.Construction/Code/Program.cs
216
C#
namespace Assets.Scripts { public delegate void ChangeState(GUIState oldState, GUIState newState); public enum GUIState { None = -1, Stop = 0, Play = 1, } }
16.583333
75
0.582915
[ "Apache-2.0" ]
dampirik/ByNekki
Assets/Scripts/GUIState.cs
201
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("SimpleGraph1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SimpleGraph1")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] //ローカライズ可能なアプリケーションのビルドを開始するには、 //.csproj ファイルの <UICulture>CultureYouAreCodingWith</UICulture> を //<PropertyGroup> 内部で設定します。たとえば、 //ソース ファイルで英語を使用している場合、<UICulture> を en-US に設定します。次に、 //下の NeutralResourceLanguage 属性のコメントを解除します。下の行の "en-US" を //プロジェクト ファイルの UICulture 設定と一致するよう更新します。 //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //テーマ固有のリソース ディクショナリが置かれている場所 //(リソースがページ、 //またはアプリケーション リソース ディクショナリに見つからない場合に使用されます) ResourceDictionaryLocation.SourceAssembly //汎用リソース ディクショナリが置かれている場所 //(リソースがページ、 //アプリケーション、またはいずれのテーマ固有のリソース ディクショナリにも見つからない場合に使用されます) )] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
33
100
0.703463
[ "Apache-2.0" ]
toydev/ExampleCSharp
WPF/OxyPlot/LogarithmicGraph/Properties/AssemblyInfo.cs
2,925
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ModalScript : MonoBehaviour { public GameObject modalWindow; // Use this for initialization public void clicked(UnityEngine.UI.Button button) { Debug.Log("Activating modal!"); modalWindow.SetActive(true); } }
20.375
50
0.742331
[ "MIT" ]
TimelyToga/tlotk
tlotk_unity/TLOTK/Assets/Main Menu/Scripts/ModalScript.cs
328
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.Evs.V2.Model { /// <summary> /// Response Object /// </summary> public class CinderListAvailabilityZonesResponse : SdkResponse { /// <summary> /// 查询请求返回的可用分区列表,请参见• [availabilityZoneInfo参数说明](https://support.huaweicloud.com/api-evs/evs_04_2081.html#evs_04_2081__li19751007201910)。 /// </summary> [JsonProperty("availabilityZoneInfo", NullValueHandling = NullValueHandling.Ignore)] public List<AzInfo> AvailabilityZoneInfo { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class CinderListAvailabilityZonesResponse {\n"); sb.Append(" availabilityZoneInfo: ").Append(AvailabilityZoneInfo).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as CinderListAvailabilityZonesResponse); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(CinderListAvailabilityZonesResponse input) { if (input == null) return false; return ( this.AvailabilityZoneInfo == input.AvailabilityZoneInfo || this.AvailabilityZoneInfo != null && input.AvailabilityZoneInfo != null && this.AvailabilityZoneInfo.SequenceEqual(input.AvailabilityZoneInfo) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.AvailabilityZoneInfo != null) hashCode = hashCode * 59 + this.AvailabilityZoneInfo.GetHashCode(); return hashCode; } } } }
31.116883
146
0.570534
[ "Apache-2.0" ]
cnblogs/huaweicloud-sdk-net-v3
Services/Evs/V2/Model/CinderListAvailabilityZonesResponse.cs
2,442
C#
using System.Collections.Generic; using System.Threading.Tasks; using ChargesApi.V1.Boundary.Request; using ChargesApi.V1.Domain; namespace ChargesApi.V1.UseCase.Interfaces { public interface IAddBatchUseCase { public Task<int> ExecuteAsync(IEnumerable<AddChargeRequest> charges); } }
23.538462
77
0.77451
[ "MIT" ]
LBHackney-IT/charges-api
ChargesApi/V1/UseCase/Interfaces/IAddBatchUseCase.cs
306
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data.SqlClient; using System.Linq; using System.Web; namespace BuildableWebApi.DataAccess { public class SqlDbAccess { public string GetData() { var connectionString = ConfigurationManager.ConnectionStrings["SqlDbAccess"].ConnectionString; var dataResult = new List<string>(); using (var sqlConnection = new SqlConnection(connectionString)) { using (var sqlCommand = new SqlCommand("SELECT * FROM Table", sqlConnection)) { sqlConnection.Open(); var sqlDataReader = sqlCommand.ExecuteReader(); while (sqlDataReader.Read()) { dataResult.Add(sqlDataReader["ColumnName"].ToString()); } sqlConnection.Close(); } } return String.Join(",", dataResult); } } }
29.857143
106
0.554067
[ "MIT" ]
kanikaul-amazon/TestProjects
net472/webapi/BuildableWebApi/BuildableWebApi/DataAccess/SqlDbAccess.cs
1,047
C#
using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Localization; using System.Threading.Tasks; using Volo.Abp.Account.Localization; using Volo.Abp.Account.Web.Pages.Account.Components.ProfileManagementGroup.Password; using Volo.Abp.Account.Web.Pages.Account.Components.ProfileManagementGroup.PersonalInfo; using Volo.Abp.Identity; using Volo.Abp.Users; namespace Smp.NobleUI.ProfileManagement { public class AccountProfileManagementPageContributor : IProfileManagementPageContributor { public async Task ConfigureAsync(ProfileManagementPageCreationContext context) { var l = context.ServiceProvider.GetRequiredService<IStringLocalizer<AccountResource>>(); if (await IsPasswordChangeEnabled(context)) { context.Groups.Add( new ProfileManagementPageGroup( "Volo.Abp.Account.Password", l["ProfileTab:Password"], typeof(AccountProfilePasswordManagementGroupViewComponent) ) ); } context.Groups.Add( new ProfileManagementPageGroup( "Volo.Abp.Account.PersonalInfo", l["ProfileTab:PersonalInfo"], typeof(AccountProfilePersonalInfoManagementGroupViewComponent) ) ); } protected virtual async Task<bool> IsPasswordChangeEnabled(ProfileManagementPageCreationContext context) { var userManager = context.ServiceProvider.GetRequiredService<IdentityUserManager>(); var currentUser = context.ServiceProvider.GetRequiredService<ICurrentUser>(); var user = await userManager.GetByIdAsync(currentUser.GetId()); return !user.IsExternal; } } }
38.204082
112
0.655983
[ "MIT" ]
BarisGurbuz/Abp.AspNetCore.Mvc.UI.Theme.AdminLTE
ProfileManagement/AccountProfileManagementPageContributor.cs
1,874
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Online_Store.Core.Factories; using Online_Store.Core.ProductServices; using Online_Store.Core.Providers; using Online_Store.Data; using Online_Store.Models; using Online_Store.Models.Enums; using System.Collections.Generic; using System.Data.Entity; using System.Linq; namespace Online_Store_Tests.Core.Services.ProductServiceTests.ProductServiceTests { [TestClass] public class ListAllProducts_Should { [TestMethod] public void ReturnAllProductsToString_WhenThereAreProducts() { // Arange var contextMock = new Mock<IStoreContext>(); var loggedUserProviderMock = new Mock<ILoggedUserProvider>(); var writerMock = new Mock<IWriter>(); var factoryMock = new Mock<IModelFactory>(); IQueryable<Product> products = new List<Product> { new Product { ProductName = "first" , Price = 200, PaymentMethod = PaymentMethodEnum.Cash }, new Product { ProductName = "second" , Price = 300, PaymentMethod = PaymentMethodEnum.Visa}, new Product { ProductName = "third" , Price = 400, PaymentMethod = PaymentMethodEnum.MasterCard}, }.AsQueryable(); var setMock = new Mock<DbSet<Product>>(); setMock.As<IQueryable<Product>>().Setup(m => m.Provider).Returns(products.Provider); setMock.As<IQueryable<Product>>().Setup(m => m.Expression).Returns(products.Expression); setMock.As<IQueryable<Product>>().Setup(m => m.ElementType).Returns(products.ElementType); setMock.As<IQueryable<Product>>().Setup(m => m.GetEnumerator()).Returns(() => products.GetEnumerator()); contextMock.Setup(m => m.Products).Returns(setMock.Object); var productService = new ProductService(contextMock.Object, loggedUserProviderMock.Object, writerMock.Object, factoryMock.Object); string expectedResult = string.Join("\n", products); // Act string actualResult = productService.ListAllProducts(); // Assert Assert.AreEqual(expectedResult, actualResult); } [TestMethod] public void ReturnCustomErrorMessage_WhenContextContainsNoProducts() { // Arange var contextMock = new Mock<IStoreContext>(); var loggedUserProviderMock = new Mock<ILoggedUserProvider>(); var writerMock = new Mock<IWriter>(); var factoryMock = new Mock<IModelFactory>(); IQueryable<Product> products = new List<Product> { }.AsQueryable(); var setMock = new Mock<DbSet<Product>>(); setMock.As<IQueryable<Product>>().Setup(m => m.Provider).Returns(products.Provider); setMock.As<IQueryable<Product>>().Setup(m => m.Expression).Returns(products.Expression); setMock.As<IQueryable<Product>>().Setup(m => m.ElementType).Returns(products.ElementType); setMock.As<IQueryable<Product>>().Setup(m => m.GetEnumerator()).Returns(() => products.GetEnumerator()); contextMock.Setup(m => m.Products).Returns(setMock.Object); var productService = new ProductService(contextMock.Object, loggedUserProviderMock.Object, writerMock.Object, factoryMock.Object); string expectedResult = "No products!"; // Act string actualResult = productService.ListAllProducts(); // Assert Assert.AreEqual(expectedResult, actualResult); } } }
40.612903
116
0.621657
[ "MIT" ]
Indeavr/Online-Store
Online_Store_Tests/Core/Services/ProductServiceTests/ListAllProducts_Should.cs
3,779
C#
namespace BeerPal.Migrations { using System; using System.Data.Entity.Migrations; public partial class AddedBeers : DbMigration { public override void Up() { CreateTable( "dbo.Beers", c => new { Id = c.Int(nullable: false, identity: true), Name = c.String(), Price = c.Int(nullable: false), }) .PrimaryKey(t => t.Id); } public override void Down() { DropTable("dbo.Beers"); } } }
23.535714
68
0.405159
[ "MIT" ]
albert18/Payment-Integration
Exercise/BeerPal/Migrations/201608251011534_AddedBeers.cs
659
C#
using System.ComponentModel.DataAnnotations; namespace WebApi.Models.Users { public class RegisterModel { [Required] public string FirstName { get; set; } [Required] public string LastName { get; set; } [Required] public string Username { get; set; } [Required] public string Password { get; set; } public string Role { get; set; } } }
20.190476
45
0.587264
[ "MIT" ]
whitie11/CTT_WebAPI
Models/Users/RegisterModel.cs
424
C#
namespace Content.Shared.Species; public class SpeciesManager { public const string DefaultSpecies = "Human"; }
16.714286
49
0.769231
[ "MIT" ]
Antares-30XX/Antares
Content.Shared/Species/SpeciesManager.cs
117
C#
using Mapster; using SS.Api.controllers.usermanagement; using SS.Api.services; using SS.Db.models.auth; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using SS.Api.models.dto; using SS.Api.models.dto.generated; using SS.Api.services.usermanagement; using tests.api.helpers; using tests.api.Helpers; using Xunit; namespace tests.controllers { public class RoleControllerTests : WrapInTransactionScope { private readonly RoleController _controller; public RoleControllerTests() : base(false) { _controller = new RoleController(new RoleService(Db)) { ControllerContext = HttpResponseTest.SetupMockControllerContext() }; } [Fact] public async Task GetRoles() { var role = await CreateRole(); var controllerResult = await _controller.Roles(); var response = HttpResponseTest.CheckForValid200HttpResponseAndReturnValue(controllerResult); Assert.NotNull(response.FirstOrDefault(r => r.Id == role.Id)); } [Fact] public async Task AddRole() { var roleDto = new RoleDto { Description = "Super Role", Name = "Super" }; var addRoleDto = new AddRoleDto() { Role = roleDto, PermissionIds = new List<int> {1} }; var controllerResult = await _controller.AddRole(addRoleDto); var response = HttpResponseTest.CheckForValid200HttpResponseAndReturnValue(controllerResult); Assert.Equal(roleDto.Description, response.Description); Assert.Equal(roleDto.Name, response.Name); Assert.NotEqual(roleDto.Id, response.Id); } [Fact] public async Task UpdateRoleAndAssignPermission() { var role = await CreateRole(); role.Name = "hello"; role.Description = "sugar"; var permission = await CreatePermission(); Detach(); var updateRoleDto = new UpdateRoleDto { Role = role.Adapt<RoleDto>(), PermissionIds = new List<int> { permission.Id } }; var controllerResult = await _controller.UpdateRole(updateRoleDto.Adapt<UpdateRoleDto>()); var response = HttpResponseTest.CheckForValid200HttpResponseAndReturnValue(controllerResult); Assert.Equal(role.Name, response.Name); Assert.Equal(role.Description, response.Description); Assert.Equal(role.Id, response.Id); var dbRole = await Db.Role.Include(r => r.RolePermissions).FirstOrDefaultAsync(r => r.Id == role.Id); Assert.NotEmpty(dbRole.RolePermissions); Detach(); updateRoleDto = new UpdateRoleDto { Role = role.Adapt<RoleDto>(), PermissionIds = new List<int> { } }; controllerResult = await _controller.UpdateRole(updateRoleDto.Adapt<UpdateRoleDto>()); response = HttpResponseTest.CheckForValid200HttpResponseAndReturnValue(controllerResult); Assert.Equal(role.Name, response.Name); Assert.Equal(role.Description, response.Description); Assert.Equal(role.Id, response.Id); dbRole = await Db.Role.Include(r => r.RolePermissions).FirstOrDefaultAsync(r => r.Id == role.Id); Assert.Empty(dbRole.RolePermissions); } [Fact] public async Task RemoveRole() { var role = await CreateRole(); var controllerResult = await _controller.RemoveRole(role.Id); HttpResponseTest.CheckForNoContentResponse(controllerResult); Assert.Null((await Db.Role.FindAsync(role.Id))); } private async Task<Permission> CreatePermission() { var permission = new Permission {Name = "Good Perm", Description = "hello"}; await Db.Permission.AddAsync(permission); await Db.SaveChangesAsync(); return permission; } private async Task<Role> CreateRole() { var role = new Role {Name = "Super Role"}; await Db.Role.AddAsync(role); await Db.SaveChangesAsync(); return role; } } }
32.941606
113
0.596942
[ "Apache-2.0" ]
seeker25/sheriff-scheduling
tests/controllers/RoleControllerTests.cs
4,515
C#
using Pliant.Utilities; using System; using System.Collections.Generic; namespace Pliant.Grammars { /// <summary> /// Defines an interval with a inclusive min and max. Does not represent empty sets. Represents single value sets with Min == Max /// </summary> public struct Interval : IComparable<Interval> { /// <summary> /// Gets the min value of the interval /// </summary> public readonly char Min; /// <summary> /// Gets the max value of the interval /// </summary> public readonly char Max; /// <summary> /// Constructs a new interval with the give min and max values /// </summary> /// <param name="min">the min inclusive value of the interval</param> /// <param name="max">the max inclusive value of the interval</param> public Interval(char min, char max) { if (min.CompareTo(max) > 0) throw new Exception($"{min} should be less than {max}"); Min = min; Max = max; } /// <summary> /// Compares two intervals /// </summary> /// <param name="other">the interval being compared</param> /// <returns>if mins are not equal returns CompareTo value of each min. If they are equal returns CompareTo of each max.</returns> public int CompareTo(Interval other) { var compareMin = Min.CompareTo(other.Min); if (compareMin != 0) return compareMin; return Max.CompareTo(other.Max); } /// <summary> /// Determines when two ranges overlap or intersect /// </summary> /// <param name="other">the interval being compared</param> /// <returns>true when the intervals overlap. false otherwise</returns> public bool Overlaps(Interval other) { return Max.CompareTo(other.Min) >= 0 && Min.CompareTo(other.Max) <= 0; } /// <summary> /// Determines when two intervals touch. Touch is when one Min differes from a Max by at most one. /// </summary> /// <param name="other"></param> /// <returns></returns> public bool Touches(Interval other) { // if intervals overlap they touch if (Overlaps(other)) return true; // char.CompareTo returns the difference between integers if (Min - other.Max == 1) return true; if (other.Min - Max == 1) return true; return false; } /// <summary> /// Joins two intervals together if they overlap. /// </summary> /// <param name="first">the first interval</param> /// <param name="second">the second interval</param> /// <returns> /// if intervals overlap returns one interval representing the global min and global max of both intervals. /// if intervals are equal returns a single interval. /// if intervals do not overlap reutrns both interval. /// </returns> public static IReadOnlyList<Interval> Join(Interval first, Interval second) { var list = new List<Interval>(); var touches = first.Touches(second); if (!touches) { list.Add(first); list.Add(second); return list; } var max = (char)Math.Max(first.Max, second.Max); var min = (char)Math.Min(first.Min, second.Min); var interval = new Interval(min, max); list.Add(interval); return list; } /// <summary> /// if the intervals do not overlap, they are echoed back. /// if the intervals overlap one interval is created that covers the overlap. /// an additional interval is created for the minimum values if they are not equal. /// an additional interval is created for the maximum values if they are not equal. /// </summary> /// <param name="first"></param> /// <param name="second"></param> /// <returns>The disjoint set of intervals</returns> public static IReadOnlyList<Interval> Split(Interval first, Interval second) { var list = new List<Interval>(); var overlaps = first.Overlaps(second); if (!overlaps) { list.Add(first); list.Add(second); return list; } // order matters to ensure intervals are sorted var minsAreEqual = first.Min.CompareTo(second.Min) == 0; var maxesAreEqual = first.Max.CompareTo(second.Max) == 0; if (!minsAreEqual && maxesAreEqual) { var localMin = (char)Math.Min(first.Min, second.Min); var localMax = (char)(Math.Max(first.Min, second.Min) - 1); list.Add(new Interval(localMin, localMax)); } var intersectMin = (char)Math.Max(first.Min, second.Min); var intersectMax = (char)Math.Min(first.Max, second.Max); list.Add(new Interval(intersectMin, intersectMax)); if (minsAreEqual && !maxesAreEqual) { var localMin = (char)(Math.Min(first.Max, second.Max) + 1); var localMax = (char)Math.Max(first.Max, second.Max); list.Add(new Interval(localMin, localMax)); } return list; } private static Interval[] EmptyList = { }; public static IReadOnlyList<Interval> Inverse(Interval interval) { if (interval.Min == char.MinValue && interval.Max == char.MaxValue) return EmptyList; var list = new List<Interval>(); if (interval.Min != char.MinValue) list.Add(new Interval(char.MinValue, (char)(interval.Min - 1))); if (interval.Max != char.MaxValue) list.Add(new Interval((char)(interval.Max + 1), char.MaxValue)); return list; } public static IReadOnlyList<Interval> Group(IReadOnlyList<Interval> input) { var intervalPool = SharedPools.Default<List<Interval>>(); var sortedIntervals = intervalPool.AllocateAndClear(); sortedIntervals.AddRange(input); sortedIntervals.Sort(); var intervalList = intervalPool.AllocateAndClear(); Interval? accumulator = null; for (var i = 0; i < sortedIntervals.Count; i++) { var interval = sortedIntervals[i]; if (accumulator is null) { accumulator = interval; continue; } var joins = Join(accumulator.Value, interval); switch (joins.Count) { case 2: intervalList.Add(joins[0]); accumulator = joins[1]; break; case 1: accumulator = joins[0]; break; } } if (accumulator != null) intervalList.Add(accumulator.Value); intervalPool.ClearAndFree(sortedIntervals); return intervalList; } public override string ToString() { return $"'[{Min}', '{Max}']"; } } }
34.791855
138
0.525686
[ "MIT" ]
patrickhuber/Earley
libraries/Pliant/Grammars/Interval.cs
7,691
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.StorageSync.V20200901 { public static class GetSyncGroup { public static Task<GetSyncGroupResult> InvokeAsync(GetSyncGroupArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetSyncGroupResult>("azure-nextgen:storagesync/v20200901:getSyncGroup", args ?? new GetSyncGroupArgs(), options.WithVersion()); } public sealed class GetSyncGroupArgs : Pulumi.InvokeArgs { /// <summary> /// The name of the resource group. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; /// <summary> /// Name of Storage Sync Service resource. /// </summary> [Input("storageSyncServiceName", required: true)] public string StorageSyncServiceName { get; set; } = null!; /// <summary> /// Name of Sync Group resource. /// </summary> [Input("syncGroupName", required: true)] public string SyncGroupName { get; set; } = null!; public GetSyncGroupArgs() { } } [OutputType] public sealed class GetSyncGroupResult { /// <summary> /// The name of the resource /// </summary> public readonly string Name; /// <summary> /// Sync group status /// </summary> public readonly string SyncGroupStatus; /// <summary> /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" /// </summary> public readonly string Type; /// <summary> /// Unique Id /// </summary> public readonly string UniqueId; [OutputConstructor] private GetSyncGroupResult( string name, string syncGroupStatus, string type, string uniqueId) { Name = name; SyncGroupStatus = syncGroupStatus; Type = type; UniqueId = uniqueId; } } }
29.743902
181
0.601066
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/StorageSync/V20200901/GetSyncGroup.cs
2,439
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 MicrosoftGraphProofOfConcept.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
36.066667
151
0.588725
[ "MIT" ]
dmtrek14/dotnet-desktop-winforms-msgraph
MicrosoftGraphProofOfConcept/Properties/Settings.Designer.cs
1,084
C#
// The MIT License(MIT) // Copyright(c) 2021 Alberto Rodriguez Orozco & LiveCharts Contributors // 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 Avalonia; using Avalonia.Media; using LiveChartsCore.Drawing; using LiveChartsCore.Motion; using System; using System.Drawing; namespace LiveChartsCore.AvaloniaView.Drawing { public class DoughnutGeometry : Geometry, IDoughnutGeometry<AvaloniaDrawingContext>, IDoughnutVisualChartPoint<AvaloniaDrawingContext> { private readonly FloatMotionProperty cxProperty; private readonly FloatMotionProperty cyProperty; private readonly FloatMotionProperty wProperty; private readonly FloatMotionProperty hProperty; private readonly FloatMotionProperty startProperty; private readonly FloatMotionProperty sweepProperty; private readonly FloatMotionProperty pushoutProperty; private readonly FloatMotionProperty innerRadiusProperty; public DoughnutGeometry() { cxProperty = RegisterMotionProperty(new FloatMotionProperty(nameof(CenterX))); cyProperty = RegisterMotionProperty(new FloatMotionProperty(nameof(CenterY))); wProperty = RegisterMotionProperty(new FloatMotionProperty(nameof(Width))); hProperty = RegisterMotionProperty(new FloatMotionProperty(nameof(Height))); startProperty = RegisterMotionProperty(new FloatMotionProperty(nameof(StartAngle))); sweepProperty = RegisterMotionProperty(new FloatMotionProperty(nameof(SweepAngle))); pushoutProperty = RegisterMotionProperty(new FloatMotionProperty(nameof(PushOut))); innerRadiusProperty = RegisterMotionProperty(new FloatMotionProperty(nameof(InnerRadius))); } public float CenterX { get => cxProperty.GetMovement(this); set => cxProperty.SetMovement(value, this); } public float CenterY { get => cyProperty.GetMovement(this); set => cyProperty.SetMovement(value, this); } public float Width { get => wProperty.GetMovement(this); set => wProperty.SetMovement(value, this); } public float Height { get => hProperty.GetMovement(this); set => hProperty.SetMovement(value, this); } public float StartAngle { get => startProperty.GetMovement(this); set => startProperty.SetMovement(value, this); } public float SweepAngle { get => sweepProperty.GetMovement(this); set => sweepProperty.SetMovement(value, this); } public float PushOut { get => pushoutProperty.GetMovement(this); set => pushoutProperty.SetMovement(value, this); } public float InnerRadius { get => innerRadiusProperty.GetMovement(this); set => innerRadiusProperty.SetMovement(value, this); } protected override SizeF OnMeasure(IDrawableTask<AvaloniaDrawingContext> paintTaks) { return new SizeF(Width, Height); } public override void OnDraw(AvaloniaDrawingContext context) { var cx = CenterX; var cy = CenterY; var wedge = InnerRadius; var r = Width * 0.5f; var startAngle = StartAngle; var sweepAngle = SweepAngle; var toRadians = (float)(Math.PI / 180); float pushout = PushOut; var sg = new StreamGeometry(); using (var path = sg.Open()) { path.BeginFigure( new Avalonia.Point( cx + Math.Cos(startAngle * toRadians) * wedge, cy + Math.Sin(startAngle * toRadians) * wedge), context.Brush != null); path.LineTo( new Avalonia.Point( cx + Math.Cos(startAngle * toRadians) * (r + pushout), cy + Math.Sin(startAngle * toRadians) * (r + pushout))); // this one is wrong... //path.ArcTo( // new SKRect { Left = X, Top = Y, Size = new SKSize { Width = Width, Height = Height } }, // startAngle, // sweepAngle, // false); path.LineTo( new Avalonia.Point( cx + Math.Cos((sweepAngle + startAngle) * toRadians) * wedge, cy + Math.Sin((sweepAngle + startAngle) * toRadians) * wedge)); //path.ArcTo( // new Avalonia.Point(wedge + pushout, Y = wedge + pushout), // 0, // SKPathArcSize.Small, // SKPathDirection.CounterClockwise, // new SKPoint // { // X = (float)(cx + Math.Cos(startAngle * toRadians) * wedge), // Y = (float)(cy + Math.Sin(startAngle * toRadians) * wedge) // }); path.EndFigure(true); } if (pushout > 0) { float pushoutAngle = startAngle + 0.5f * sweepAngle; float x = pushout * (float)Math.Cos(pushoutAngle * toRadians); float y = pushout * (float)Math.Sin(pushoutAngle * toRadians); sg.Transform = new MatrixTransform(Matrix.CreateTranslation(x, y)); } context.AvaloniaContext.DrawGeometry(context.Brush, context.Pen, sg); } } }
48.5
138
0.628554
[ "MIT" ]
cnycny/LiveCharts2
src/avalonia/LiveChartsCore.AvaloniaView/Drawing/DoughnutGeometry.cs
6,404
C#
using System; namespace NetworkProtocols { // Token: 0x02000776 RID: 1910 public class DisbandGuildLogEntryForNetwork : GuildLogEntryForNetwork { // Token: 0x060043CC RID: 17356 RVA: 0x00027147 File Offset: 0x00025347 public DisbandGuildLogEntryForNetwork() { this.InitRefTypes(); this.UniqueClassID = 2995116941u; } // Token: 0x060043CD RID: 17357 RVA: 0x00122974 File Offset: 0x00120B74 public override byte[] SerializeMessage() { byte[] newArray = ArrayManager.GetNewArray(); int num = 0; byte[] array = base.SerializeMessage(); if (array.Length + num > newArray.Length) { Array.Resize<byte>(ref newArray, array.Length + num); } Array.Copy(array, 0, newArray, num, array.Length); num += array.Length; Array.Resize<byte>(ref newArray, num); return newArray; } // Token: 0x060043CE RID: 17358 RVA: 0x001229C4 File Offset: 0x00120BC4 public override void DeserializeMessage(byte[] data) { int num = 0; byte[] array = new byte[data.Length - num]; Array.Copy(data, num, array, 0, array.Length); base.DeserializeMessage(array); } // Token: 0x060043CF RID: 17359 RVA: 0x00006297 File Offset: 0x00004497 private void InitRefTypes() { } } }
27.673913
74
0.673998
[ "Unlicense" ]
PermaNulled/OMDUC_EMU_CSharp
OMDUC_EMU/NetworkProtocols/DisbandGuildLogEntryForNetwork.cs
1,275
C#
using System; namespace ConstructionApp.Entity { public class CapPhoi { public Guid Id { get; set; } public Guid ThongTinMeTronId { get; set; } public ThongTinMeTron ThongTinMeTron { get; set; } public double Da { get; set; } public double CatNhanTao { get; set; } public double CatSong { get; set; } public double XiMang { get; set; } public double Nuoc { get; set; } public double PhuGia1 { get; set; } public double PhuGia2 { get; set; } public double TiTrong { get; set; } public Boolean Check { get; set; } } }
31.2
58
0.588141
[ "MIT" ]
Smoothiesss/ConstructionManagement
backend/webApi/Entity/CapPhoi.cs
624
C#
using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using System; using System.ComponentModel.DataAnnotations.Schema; using System.IO; namespace BioDivCollector.DB.Models.Domain { //https://docs.microsoft.com/en-us/ef/core/miscellaneous/configuring-dbcontext public class BioDivContext : DbContext { //public DbSet<Content> Contents { get; set; } //public DbSet<ContentDataType> ContentDataTypes { get; set; } public DbSet<TextData> TextData { get; set; } public DbSet<BooleanData> BooleanData { get; set; } public DbSet<NumericData> NumericData { get; set; } public DbSet<Record> Records { get; set; } public DbSet<Status> Statuses { get; set; } public DbSet<ReferenceGeometry> Geometries { get; set; } public DbSet<Project> Projects { get; set; } public DbSet<ProjectStatus> ProjectStatuses { get; set; } //public DbSet<ProjectGeometry> ProjectsGeometries { get; set; } //not in use public DbSet<ProjectLayer> ProjectsLayers { get; set; } public DbSet<Layer> Layers { get; set; } public DbSet<ChangeLog> ChangeLogs { get; set; } public DbSet<ChangeLogProject> ChangeLogsProjects { get; set; } public DbSet<ChangeLogGeometry> ChangeLogsGeometries { get; set; } public DbSet<ChangeLogRecord> ChangeLogsRecords { get; set; } public DbSet<ChangeLogGroup> ChangeLogsGroups { get; set; } public DbSet<ChangeLogLayer> ChangeLogsLayers { get; set; } public DbSet<ChangeLogForm> ChangeLogsForms { get; set; } public DbSet<User> Users { get; set; } public DbSet<Group> Groups { get; set; } public DbSet<GroupStatus> GroupStatuses { get; set; } public DbSet<ProjectGroup> ProjectsGroups { get; set; } public DbSet<GroupUser> GroupsUsers { get; set; } //public DbSet<UserRole> UsersRoles { get; set; } public DbSet<UserLayer> UsersLayers { get; set; } public DbSet<UserHasProjectLayer> UsersHaveProjectLayers { get; set; } //public DbSet<Role> Roles { get; set; } public DbSet<Form> Forms { get; set; } public DbSet<FormFormField> FormsFormFields { get; set; } public DbSet<FormField> FormFields { get; set; } public DbSet<FieldType> FieldTypes { get; set; } public DbSet<FieldChoice> FieldChoices { get; set; } public DbSet<ProjectForm> ProjectsForms { get; set; } //public BioDivContext(DbContextOptions<BioDivContext> options) // : base(options) //{ } public static readonly ILoggerFactory DebugLoggerFactory = LoggerFactory.Create(builder => { builder.AddDebug(); }); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { IConfigurationRoot configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .AddUserSecrets<BioDivContext>() .AddEnvironmentVariables() .Build(); string hmm = configuration.GetSection("Environment").GetSection("DBHost").Value; optionsBuilder .UseNpgsql( "Host="+ configuration.GetSection("Environment").GetSection("DBHost").Value + "; Database=" + configuration.GetSection("Environment").GetSection("DB").Value + ";Username=" + configuration.GetSection("Environment").GetSection("DBUser").Value + ";Password=" + configuration.GetSection("Environment").GetSection("DBPassword").Value + "", options => { options.UseNetTopologySuite(); options.EnableRetryOnFailure(); //TODO: needed? https://docs.microsoft.com/en-us/ef/core/miscellaneous/connection-resiliency } ) .UseLowerCaseNamingConvention() ; //optionsBuilder.UseLazyLoadingProxies(); optionsBuilder.UseLoggerFactory(DebugLoggerFactory); base.OnConfiguring(optionsBuilder); } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.HasDefaultSchema("public"); modelBuilder.HasPostgresExtension("postgis"); modelBuilder.Entity<ReferenceGeometry>().Property(g => g.Point).HasColumnType("geometry(POINT, 4326)"); modelBuilder.Entity<ReferenceGeometry>().Property(g => g.Line).HasColumnType("geometry(LINESTRING, 4326)"); modelBuilder.Entity<ReferenceGeometry>().Property(g => g.Polygon).HasColumnType("geometry(POLYGON, 4326)"); //Project n:m Geometry. not implemented so far... //modelBuilder.Entity<ProjectGeometry>() // .HasKey(pg => new { pg.ProjectId, pg.GeometryId }); //modelBuilder.Entity<ProjectGeometry>() // .HasOne(pg => pg.Project) // .WithMany(p => p.ProjectGeometries) // .HasForeignKey(pg => pg.ProjectId); //modelBuilder.Entity<ProjectGeometry>() // .HasOne(pg => pg.Geometry) // .WithMany(g => g.GeometryProjects) // .HasForeignKey(pg => pg.GeometryId); modelBuilder.Entity<ProjectGroup>() .HasKey(pg => new { pg.ProjectId, pg.GroupId }); modelBuilder.Entity<ProjectGroup>() .HasOne(pg => pg.Project) .WithMany(p => p.ProjectGroups) .HasForeignKey(pg => pg.ProjectId); modelBuilder.Entity<ProjectGroup>() .HasOne(pg => pg.Group) .WithMany(g => g.GroupProjects) .HasForeignKey(pg => pg.GroupId); modelBuilder.Entity<ProjectLayer>() .HasKey(pl => new { pl.ProjectId, pl.LayerId }); modelBuilder.Entity<ProjectLayer>() .HasOne(pl => pl.Project) .WithMany(p => p.ProjectLayers) .HasForeignKey(pg => pg.ProjectId); modelBuilder.Entity<ProjectLayer>() .HasOne(pl => pl.Layer) .WithMany(g => g.LayerProjects) .HasForeignKey(pl => pl.LayerId); modelBuilder.Entity<GroupUser>() .HasKey(gu => new { gu.UserId, gu.GroupId }); modelBuilder.Entity<GroupUser>() .HasOne(gu => gu.User) .WithMany(u => u.UserGroups) .HasForeignKey(gu => gu.UserId); modelBuilder.Entity<GroupUser>() .HasOne(gu => gu.Group) .WithMany(g => g.GroupUsers) .HasForeignKey(gu => gu.GroupId); modelBuilder.Entity<FormFormField>() .HasKey(fff => new { fff.FormId, fff.FormFieldId }); modelBuilder.Entity<FormFormField>() .HasOne(fff => fff.Form) .WithMany(f => f.FormFormFields) .HasForeignKey(fff => fff.FormId); modelBuilder.Entity<FormFormField>() .HasOne(fff => fff.FormField) .WithMany(ff => ff.FormFieldForms) .HasForeignKey(fff => fff.FormFieldId); modelBuilder.Entity<UserLayer>() .HasKey(ul => new { ul.UserId, ul.LayerId }); modelBuilder.Entity<UserHasProjectLayer>() .HasKey(uhpl => new { uhpl.UserId, uhpl.ProjectId, uhpl.LayerId }); modelBuilder.Entity<ProjectForm>() .HasKey(ur => new { ur.ProjectId, ur.FormId }); modelBuilder.Entity<ProjectForm>() .HasOne(gf => gf.Project) .WithMany(g => g.ProjectForms) .HasForeignKey(gf => gf.ProjectId); modelBuilder.Entity<ProjectForm>() .HasOne(gf => gf.Form) .WithMany(f => f.FormProjects) .HasForeignKey(gf => gf.FormId); modelBuilder.Entity<ChangeLog>() .Property(c => c.ChangeDate) .HasDefaultValueSql("now()"); modelBuilder.Entity<ChangeLogProject>() .HasKey(cl => new { cl.ProjectId, cl.ChangeLogId }); modelBuilder.Entity<ChangeLogGeometry>() .HasKey(cl => new { cl.GeometryId, cl.ChangeLogId }); modelBuilder.Entity<ChangeLogRecord>() .HasKey(cl => new { cl.RecordId, cl.ChangeLogId }); modelBuilder.Entity<ChangeLogGroup>() .HasKey(cl => new { cl.GroupId, cl.ChangeLogId }); modelBuilder.Entity<ChangeLogLayer>() .HasKey(cl => new { cl.LayerId, cl.ChangeLogId }); modelBuilder.Entity<ChangeLogForm>() .HasKey(cl => new { cl.FormId, cl.ChangeLogId }); modelBuilder.Entity<Project>().Property(p => p.StatusId).HasDefaultValue(StatusEnum.unchanged); modelBuilder.Entity<ReferenceGeometry>().Property(p => p.StatusId).HasDefaultValue(StatusEnum.unchanged); modelBuilder.Entity<Record>().Property(p => p.StatusId).HasDefaultValue(StatusEnum.unchanged); modelBuilder.Entity<Group>().Property(p => p.StatusId).HasDefaultValue(StatusEnum.unchanged); foreach (StatusEnum type in (StatusEnum[])Enum.GetValues(typeof(StatusEnum))) { modelBuilder.Entity<Status>() .HasData(new Status(type, type.ToString())); } modelBuilder.Entity<Project>().Property(p => p.ProjectStatusId).HasDefaultValue(ProjectStatusEnum.Projekt_neu); foreach (ProjectStatusEnum type in (ProjectStatusEnum[])Enum.GetValues(typeof(ProjectStatusEnum))) { modelBuilder.Entity<ProjectStatus>() .HasData(new ProjectStatus(type, type.ToString())); } // 20210109 chs: Standard is Gruppe_Bereit modelBuilder.Entity<Group>().Property(p => p.GroupStatusId).HasDefaultValue(GroupStatusEnum.Gruppe_bereit); foreach (GroupStatusEnum type in (GroupStatusEnum[])Enum.GetValues(typeof(GroupStatusEnum))) { modelBuilder.Entity<GroupStatus>() .HasData(new GroupStatus(type, type.ToString())); } // 20210109 chs: Groupstate per Project modelBuilder.Entity<ProjectGroup>().Property(p => p.GroupStatusId).HasDefaultValue(GroupStatusEnum.Gruppe_bereit); //modelBuilder.Entity<UserRole>().Property(p => p.Role) //foreach (RoleEnum type in (RoleEnum[])Enum.GetValues(typeof(RoleEnum))) //{ // modelBuilder.Entity<Role>() // .HasData(new Role(type, type.ToString())); //} foreach (FieldTypeEnum type in (FieldTypeEnum[])Enum.GetValues(typeof(FieldTypeEnum))) { modelBuilder.Entity<FieldType>() .HasData(new FieldType(type, type.ToString())); } } } }
49.162996
357
0.590681
[ "Apache-2.0" ]
GEOTEST-AG/BioDivCollector
Server/BioDivCollector.DB/Models/Domain/BioDivContext.cs
11,162
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; namespace Lao_Blog.Data { // Add profile data for application users by adding properties to the ApplicationUser class public class ApplicationUser : IdentityUser { } }
23.714286
96
0.743976
[ "MIT" ]
nlregulus077/Lao_Blog2
Data/ApplicationUser.cs
332
C#
namespace ConsoleBox.UI.Widgets { using Elements; public class StyleWidget : IWidget { public Style Style { get; set; } public IWidget Child { get; set; } public StyleWidget(IWidget child) { Child = child; Style = new Style(); } public StyleWidget(Style style, IWidget child) { Child = child; Style = style; } public IElement Build(BuildContext context) { return new StyleElement(Child.Build(context)) { Style = Style }; } } }
20.586207
76
0.524288
[ "MIT" ]
decoy/ConsoleBox
ConsoleBox/UI/Widgets/StyleWidget.cs
599
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.Mixer.ShortcodeOAuth; using MixerChatApp.Core.APIs; using MixerChatApp.Core.Interfaces; using MixerChatApp.Core.Models; using MixerLib; using Newtonsoft.Json; using Prism.Commands; using Prism.Mvvm; using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Http; using System.Reflection.Metadata; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using System.Timers; using Unity; namespace MixerChatApp.Core.Services { public class OAuthManager : BindableBase, IOAuthManagerable { //゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。*゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。*゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。* #region // プロパティ /// <summary>説明 を取得、設定</summary> private OAuthClient client_; /// <summary>説明 を取得、設定</summary> public OAuthClient Client { get => this.client_; set => this.SetProperty(ref this.client_, value); } /// <summary>説明 を取得、設定</summary> private string cord_; /// <summary>説明 を取得、設定</summary> public string Code { get => this.cord_; set => this.SetProperty(ref this.cord_, value); } /// <summary>説明 を取得、設定</summary> private string userName_; /// <summary>説明 を取得、設定</summary> public string UserName { get => this.userName_; set => this.SetProperty(ref this.userName_, value); } /// <summary>説明 を取得、設定</summary> private DateTimeOffset connectDate_; /// <summary>説明 を取得、設定</summary> public DateTimeOffset ConnectDate { get => this.connectDate_; set => this.SetProperty(ref this.connectDate_, value); } /// <summary>説明 を取得、設定</summary> private List<string> scorp_; /// <summary>説明 を取得、設定</summary> public List<string> Scorp { get => this.scorp_; set => this.SetProperty(ref this.scorp_, value); } /// <summary>説明 を取得、設定</summary> private OAuthTokens tokens_; /// <summary>説明 を取得、設定</summary> public OAuthTokens Tokens { get => this.tokens_; set => this.SetProperty(ref this.tokens_, value); } /// <summary>説明 を取得、設定</summary> private bool isSaveUserInformation_; /// <summary>説明 を取得、設定</summary> public bool IsSaveUserInformation { get => this.isSaveUserInformation_; set => this.SetProperty(ref this.isSaveUserInformation_, value); } #endregion //゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。*゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。*゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。* #region // コマンド #endregion //゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。*゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。*゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。* #region // コマンド用メソッド #endregion //゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。*゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。*゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。* #region // オーバーライドメソッド protected override async void OnPropertyChanged(PropertyChangedEventArgs args) { base.OnPropertyChanged(args); if (args.PropertyName == nameof(IsSaveUserInformation)) { if (this.IsSaveUserInformation) { await this.RefreshToken(); this._timer.Start(); } else { this._timer.Stop(); } } } #endregion //゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。*゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。*゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。* #region // パブリックメソッド public async Task<bool> RunAsync() { try { // Create your OAuth client. Specify your client ID, and which permissions you want. // Use the helper GrantAsync to get codes. Alternately, you can run // the granting/polling loop manually using client.GetSingleCodeAsync. var task = this.Client.GrantAsync(code => { this.Code = code; var url = "https://mixer.com/go?code=" + $"{this.Code}"; Process.Start(new ProcessStartInfo("cmd", $"/c start {url}") { CreateNoWindow = true }); }, CancellationToken.None); this.Tokens = await task; // and that's it! Debug.WriteLine($"Access token: {this.Tokens.AccessToken}"); Debug.WriteLine($"Refresh token: {this.Tokens.RefreshToken}"); Debug.WriteLine($"Expires At: {this.Tokens.ExpiresAt}"); this.ConnectDate = this.Tokens.ExpiresAt; this.UserName = await this._aPI.GetUserName(this.Tokens.AccessToken); return true; } catch (OAuthException oe) { Debug.WriteLine($"{oe.Message}"); return false; } catch (Exception e) { Debug.WriteLine($"{e.Message}"); return false; } } public async Task<bool> RefreshToken() { Debug.WriteLine($"[{DateTime.Now}] : トークンをリフレッシュします。"); try { if (this.Tokens == null) { this.UserName = ""; return false; } var token = await this.Client.RefreshAsync(this.Tokens).ConfigureAwait(false); Debug.WriteLine($"Access token: {this.Tokens.AccessToken}"); Debug.WriteLine($"Refresh token: {this.Tokens.RefreshToken}"); Debug.WriteLine($"Expires At: {this.Tokens.ExpiresAt}"); this.Tokens = token; this.ConnectDate = this.Tokens.ExpiresAt; this.UserName = await this._aPI.GetUserName(this.Tokens.AccessToken); return true; } catch (Exception e) { Debug.WriteLine($"{e.Message}"); this.UserName = ""; return false; } } #endregion //゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。*゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。*゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。* #region // プライベートメソッド private async void TimerEvent(object sender, ElapsedEventArgs e) { await this.RefreshToken(); } #endregion //゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。*゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。*゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。* #region // メンバ変数 [Dependency] public MixerAPI _aPI; private readonly System.Timers.Timer _timer; private string CLIENT_ID = "your client id"; private class SettingEntity { [JsonProperty("AcsessToken")] public string AcsessToken { get; set; } [JsonProperty("ExporesAt")] public string ExporesAt { get; set; } } #endregion //゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。*゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。*゚+。*゚+。。+゚*。+゚ ゚+。*゚+。。+゚*。+゚ ゚+。* #region // 構築・破棄 public OAuthManager() { var timespan = new TimeSpan(5, 55, 0); this._timer = new System.Timers.Timer(timespan.TotalMilliseconds); this._timer.Elapsed += this.TimerEvent; this.Scorp = new List<string>() { "channel:update:self", "chat:bypass_links", "chat:bypass_slowchat", "chat:change_ban", "chat:chat", "chat:connect", "chat:timeout", "chat:whisper", }; #if DEBUG var bulder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.Develop.json"); var configuration = bulder.Build(); var clientid = configuration["ClientId"]; #else var clientid = this.CLIENT_ID; #endif this.Client = new OAuthClient( new OAuthOptions { ClientId = clientid, Scopes = this.Scorp.ToArray(), }); } #endregion } }
34.672065
112
0.50327
[ "MIT" ]
denpadokei/MixerChatApp
MixerChatApp.Core/Services/OAuthManager.cs
9,800
C#
using System; using System.Text; class Program { static void Main() { string input = Console.ReadLine(); StringBuilder sb = new StringBuilder(); sb.Append(input[0]); for (int i = 1; i < input.Length; i++) { if (input[i]!=input[i-1]) { sb.Append(input[i]); } } Console.WriteLine(sb.ToString()); } }
20.95
47
0.47494
[ "MIT" ]
StackSmack007/Programing-Fundamentals-September-2018
Strings and Text Processing - Exercise/06. Replace Repeating Chars/Program.cs
421
C#
namespace Late4dTrain.CosmosDbStorage.Strategies; using Configuration; public class DefaultCosmosDbExponentialRetryStrategy : ExponentialRetryStrategy<CosmosDbResiliencePolicyConfiguration> { protected DefaultCosmosDbExponentialRetryStrategy(CosmosDbResiliencePolicyConfiguration configuration) : base( configuration ) { } public static DefaultCosmosDbExponentialRetryStrategy Instance => new( new CosmosDbResiliencePolicyConfiguration { Resilience = new ResilienceConfiguration { Retry = 3 } } ); }
28.6
118
0.756993
[ "MIT" ]
late4dtrain/cosmosdb-storage
Late4dTrain.CosmosDbStorage/Strategies/DefaultCosmosDbExponentialRetryStrategy.cs
574
C#
namespace Kesco.Web.Mvc.UI.Grid { using System; using System.Runtime.CompilerServices; public class IntegerFormatter : JQGridColumnFormatter { public IntegerFormatter() { } public string DefaultValue { get; set; } public string ThousandsSeparator { get; set; } } }
18.8125
57
0.687708
[ "MIT" ]
Kesco-m/Kesco.App.Web.MVC.Persons
Kesco.Web.Mvc.UI.Controls/Grid/Formatters/IntegerFormatter.cs
301
C#
// Copyright 2008 Louis DeJardin - http://whereslou.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.IO; using System.Threading; using Spark.Caching; using Spark.Spool; using Spark.Utilities; namespace Spark { public class SparkViewContext { public SparkViewContext() { Content = new Dictionary<string, TextWriter>(); Globals = new Dictionary<string, object>(); OnceTable = new Dictionary<string, string>(); } public TextWriter Output { get; set; } public Dictionary<string, TextWriter> Content { get; set; } public Dictionary<string, object> Globals { get; set; } public Dictionary<string, string> OnceTable { get; set; } } public abstract class SparkViewBase : ISparkView { private SparkViewContext _sparkViewContext; public abstract Guid GeneratedViewId { get; } public virtual bool TryGetViewData(string name, out object value) { value = null; return false; } public virtual SparkViewContext SparkViewContext { get { return _sparkViewContext ?? Interlocked.CompareExchange(ref _sparkViewContext, new SparkViewContext(), null) ?? _sparkViewContext; } set { _sparkViewContext = value; } } public TextWriter Output { get { return SparkViewContext.Output; } set { SparkViewContext.Output = value; } } public Dictionary<string, TextWriter> Content { get { return SparkViewContext.Content; } set { SparkViewContext.Content = value; } } public Dictionary<string, object> Globals { get { return SparkViewContext.Globals; } set { SparkViewContext.Globals = value; } } public Dictionary<string, string> OnceTable { get { return SparkViewContext.OnceTable; } set { SparkViewContext.OnceTable = value; } } public IDisposable OutputScope(string name) { TextWriter writer; if (!Content.TryGetValue(name, out writer)) { writer = new SpoolWriter(); Content.Add(name, writer); } return new OutputScopeImpl(this, writer); } public IDisposable OutputScope(TextWriter writer) { return new OutputScopeImpl(this, writer); } public IDisposable OutputScope() { return new OutputScopeImpl(this, new SpoolWriter()); } public IDisposable MarkdownOutputScope() { return new MarkdownOutputScopeImpl(this, new SpoolWriter()); } public bool Once(object flag) { var flagString = Convert.ToString(flag); if (SparkViewContext.OnceTable.ContainsKey(flagString)) return false; SparkViewContext.OnceTable.Add(flagString, null); return true; } public class OutputScopeImpl : IDisposable { private readonly SparkViewBase view; private readonly TextWriter previous; public OutputScopeImpl(SparkViewBase view, TextWriter writer) { this.view = view; previous = view.Output; view.Output = writer; } public void Dispose() { view.Output = previous; } } public class MarkdownOutputScopeImpl : IDisposable { private readonly SparkViewBase view; private readonly TextWriter previous; public MarkdownOutputScopeImpl(SparkViewBase view, TextWriter writer) { this.view = view; previous = view.Output; view.Output = writer; } public void Dispose() { var source = view.Output.ToString(); view.Output = previous; var markdown = new Markdown(); view.Output.Write(markdown.Transform(source)); } } protected bool BeginCachedContent(string site, CacheExpires expires, params object[] key) { _currentCacheScope = new CacheScopeImpl(this, CacheUtilities.ToIdentifier(site, key), expires); if (_currentCacheScope.Begin()) return true; EndCachedContent(); return false; } protected void EndCachedContent() { _currentCacheScope = _currentCacheScope.End(null); } protected void EndCachedContent(ICacheSignal signal) { _currentCacheScope = _currentCacheScope.End(signal); } private CacheScopeImpl _currentCacheScope; public ICacheService CacheService { get; set; } private class CacheScopeImpl { private readonly CacheScopeImpl _previousCacheScope; private readonly ICacheService _cacheService; private readonly CacheOriginator _originator; private readonly string _identifier; private readonly CacheExpires _expires; private bool _recording; private static readonly ICacheService _nullCacheService = new NullCacheService(); public CacheScopeImpl(SparkViewBase view, string identifier, CacheExpires expires) { _identifier = identifier; _expires = expires; _previousCacheScope = view._currentCacheScope; _cacheService = view.CacheService ?? _nullCacheService; _originator = new CacheOriginator(view.SparkViewContext); } public bool Begin() { var memento = _cacheService.Get(_identifier) as CacheMemento; if (memento == null) { _recording = true; _originator.BeginMemento(); } else { _recording = false; _originator.DoMemento(memento); } return _recording; } public CacheScopeImpl End(ICacheSignal signal) { if (_recording) { var memento = _originator.EndMemento(); _cacheService.Store(_identifier, _expires, signal, memento); } return _previousCacheScope; } private class NullCacheService : ICacheService { public object Get(string identifier) { return null; } public void Store(string identifier, CacheExpires expires, ICacheSignal signal, object item) { } } } public virtual void RenderView(TextWriter writer) { using (OutputScope(writer)) { Render(); } } public abstract void Render(); protected virtual void DelegateFirstRender(Action render) { render(); } } }
32.286853
143
0.551333
[ "Apache-2.0" ]
RobertTheGrey/spark
src/Spark/SparkViewBase.cs
8,106
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Model\MethodRequestBody.cs.tt namespace Microsoft.Graph { using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; /// <summary> /// The type WorkbookFunctionsCoupDaysNcRequestBody. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public partial class WorkbookFunctionsCoupDaysNcRequestBody { /// <summary> /// Gets or sets Settlement. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "settlement", Required = Newtonsoft.Json.Required.Default)] public Newtonsoft.Json.Linq.JToken Settlement { get; set; } /// <summary> /// Gets or sets Maturity. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "maturity", Required = Newtonsoft.Json.Required.Default)] public Newtonsoft.Json.Linq.JToken Maturity { get; set; } /// <summary> /// Gets or sets Frequency. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "frequency", Required = Newtonsoft.Json.Required.Default)] public Newtonsoft.Json.Linq.JToken Frequency { get; set; } /// <summary> /// Gets or sets Basis. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "basis", Required = Newtonsoft.Json.Required.Default)] public Newtonsoft.Json.Linq.JToken Basis { get; set; } } }
41.1
153
0.618005
[ "MIT" ]
AzureMentor/msgraph-sdk-dotnet
src/Microsoft.Graph/Models/Generated/WorkbookFunctionsCoupDaysNcRequestBody.cs
2,055
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using Datadog.Trace.Headers; using Datadog.Trace.Logging; namespace Datadog.Trace { internal class SpanContextPropagator { private const NumberStyles NumberStyles = System.Globalization.NumberStyles.Integer; private const int MinimumSamplingPriority = (int)SamplingPriority.UserReject; private const int MaximumSamplingPriority = (int)SamplingPriority.UserKeep; private static readonly CultureInfo InvariantCulture = CultureInfo.InvariantCulture; private static readonly Vendors.Serilog.ILogger Log = DatadogLogging.For<SpanContextPropagator>(); private static readonly int[] SamplingPriorities; static SpanContextPropagator() { SamplingPriorities = Enum.GetValues(typeof(SamplingPriority)).Cast<int>().ToArray(); } private SpanContextPropagator() { } public static SpanContextPropagator Instance { get; } = new SpanContextPropagator(); /// <summary> /// Propagates the specified context by adding new headers to a <see cref="IHeadersCollection"/>. /// This locks the sampling priority for <paramref name="context"/>. /// </summary> /// <param name="context">A <see cref="SpanContext"/> value that will be propagated into <paramref name="headers"/>.</param> /// <param name="headers">A <see cref="IHeadersCollection"/> to add new headers to.</param> /// <typeparam name="T">Type of header collection</typeparam> public void Inject<T>(SpanContext context, T headers) where T : IHeadersCollection { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (headers == null) { throw new ArgumentNullException(nameof(headers)); } // lock sampling priority when span propagates. context.TraceContext?.LockSamplingPriority(); headers.Set(HttpHeaderNames.TraceId, context.TraceId.ToString(InvariantCulture)); headers.Set(HttpHeaderNames.ParentId, context.SpanId.ToString(InvariantCulture)); // avoid writing origin header if not set, keeping the previous behavior. if (context.Origin != null) { headers.Set(HttpHeaderNames.Origin, context.Origin); } var samplingPriority = (int?)(context.TraceContext?.SamplingPriority ?? context.SamplingPriority); headers.Set( HttpHeaderNames.SamplingPriority, samplingPriority?.ToString(InvariantCulture)); } /// <summary> /// Propagates the specified context by adding new headers to a <see cref="IHeadersCollection"/>. /// This locks the sampling priority for <paramref name="context"/>. /// </summary> /// <param name="context">A <see cref="SpanContext"/> value that will be propagated into <paramref name="carrier"/>.</param> /// <param name="carrier">The headers to add to.</param> /// <param name="setter">The action that can set a header in the carrier.</param> /// <typeparam name="T">Type of header collection</typeparam> public void Inject<T>(SpanContext context, T carrier, Action<T, string, string> setter) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (carrier == null) { throw new ArgumentNullException(nameof(carrier)); } if (setter == null) { throw new ArgumentNullException(nameof(setter)); } // lock sampling priority when span propagates. context.TraceContext?.LockSamplingPriority(); setter(carrier, HttpHeaderNames.TraceId, context.TraceId.ToString(InvariantCulture)); setter(carrier, HttpHeaderNames.ParentId, context.SpanId.ToString(InvariantCulture)); // avoid writing origin header if not set, keeping the previous behavior. if (context.Origin != null) { setter(carrier, HttpHeaderNames.Origin, context.Origin); } var samplingPriority = (int?)(context.TraceContext?.SamplingPriority ?? context.SamplingPriority); setter(carrier, HttpHeaderNames.SamplingPriority, samplingPriority?.ToString(InvariantCulture)); } /// <summary> /// Extracts a <see cref="SpanContext"/> from the values found in the specified headers. /// </summary> /// <param name="headers">The headers that contain the values to be extracted.</param> /// <typeparam name="T">Type of header collection</typeparam> /// <returns>A new <see cref="SpanContext"/> that contains the values obtained from <paramref name="headers"/>.</returns> public SpanContext Extract<T>(T headers) where T : IHeadersCollection { if (headers == null) { throw new ArgumentNullException(nameof(headers)); } var traceId = ParseUInt64(headers, HttpHeaderNames.TraceId); if (traceId == 0) { // a valid traceId is required to use distributed tracing return null; } var parentId = ParseUInt64(headers, HttpHeaderNames.ParentId); var samplingPriority = ParseSamplingPriority(headers, HttpHeaderNames.SamplingPriority); var origin = ParseString(headers, HttpHeaderNames.Origin); return new SpanContext(traceId, parentId, samplingPriority, null, origin); } /// <summary> /// Extracts a <see cref="SpanContext"/> from the values found in the specified headers. /// </summary> /// <param name="carrier">The headers that contain the values to be extracted.</param> /// <param name="getter">The function that can extract a list of values for a given header name.</param> /// <typeparam name="T">Type of header collection</typeparam> /// <returns>A new <see cref="SpanContext"/> that contains the values obtained from <paramref name="carrier"/>.</returns> public SpanContext Extract<T>(T carrier, Func<T, string, IEnumerable<string>> getter) { if (carrier == null) { throw new ArgumentNullException(nameof(carrier)); } if (getter == null) { throw new ArgumentNullException(nameof(getter)); } var traceId = ParseUInt64(carrier, getter, HttpHeaderNames.TraceId); if (traceId == 0) { // a valid traceId is required to use distributed tracing return null; } var parentId = ParseUInt64(carrier, getter, HttpHeaderNames.ParentId); var samplingPriority = ParseSamplingPriority(carrier, getter, HttpHeaderNames.SamplingPriority); var origin = ParseString(carrier, getter, HttpHeaderNames.Origin); return new SpanContext(traceId, parentId, samplingPriority, null, origin); } public IEnumerable<KeyValuePair<string, string>> ExtractHeaderTags<T>(T headers, IEnumerable<KeyValuePair<string, string>> headerToTagMap) where T : IHeadersCollection { foreach (KeyValuePair<string, string> headerNameToTagName in headerToTagMap) { string headerValue = ParseString(headers, headerNameToTagName.Key); if (headerValue != null) { yield return new KeyValuePair<string, string>(headerNameToTagName.Value, headerValue); } } } private static ulong ParseUInt64<T>(T headers, string headerName) where T : IHeadersCollection { var headerValues = headers.GetValues(headerName); bool hasValue = false; foreach (string headerValue in headerValues) { if (ulong.TryParse(headerValue, NumberStyles, InvariantCulture, out var result)) { return result; } hasValue = true; } if (hasValue) { Log.Warning("Could not parse {0} headers: {1}", headerName, string.Join(",", headerValues)); } return 0; } private static ulong ParseUInt64<T>(T carrier, Func<T, string, IEnumerable<string>> getter, string headerName) { var headerValues = getter(carrier, headerName); bool hasValue = false; foreach (string headerValue in headerValues) { if (ulong.TryParse(headerValue, NumberStyles, InvariantCulture, out var result)) { return result; } hasValue = true; } if (hasValue) { Log.Warning("Could not parse {0} headers: {1}", headerName, string.Join(",", headerValues)); } return 0; } private static SamplingPriority? ParseSamplingPriority<T>(T headers, string headerName) where T : IHeadersCollection { var headerValues = headers.GetValues(headerName); bool hasValue = false; foreach (string headerValue in headerValues) { if (int.TryParse(headerValue, out var result)) { if (MinimumSamplingPriority <= result && result <= MaximumSamplingPriority) { return (SamplingPriority)result; } } hasValue = true; } if (hasValue) { Log.Warning( "Could not parse {0} headers: {1}", headerName, string.Join(",", headerValues)); } return default; } private static SamplingPriority? ParseSamplingPriority<T>(T carrier, Func<T, string, IEnumerable<string>> getter, string headerName) { var headerValues = getter(carrier, headerName); bool hasValue = false; foreach (string headerValue in headerValues) { if (int.TryParse(headerValue, out var result)) { if (MinimumSamplingPriority <= result && result <= MaximumSamplingPriority) { return (SamplingPriority)result; } } hasValue = true; } if (hasValue) { Log.Warning( "Could not parse {0} headers: {1}", headerName, string.Join(",", headerValues)); } return default; } private static string ParseString(IHeadersCollection headers, string headerName) { var headerValues = headers.GetValues(headerName); foreach (string headerValue in headerValues) { if (!string.IsNullOrEmpty(headerValue)) { return headerValue; } } return null; } private static string ParseString<T>(T carrier, Func<T, string, IEnumerable<string>> getter, string headerName) { var headerValues = getter(carrier, headerName); foreach (string headerValue in headerValues) { if (!string.IsNullOrEmpty(headerValue)) { return headerValue; } } return null; } } }
38.167742
146
0.581305
[ "Apache-2.0" ]
ConnectionMaster/dd-trace-dotnet
src/Datadog.Trace/SpanContextPropagator.cs
11,832
C#
// %BANNER_BEGIN% // --------------------------------------------------------------------- // %COPYRIGHT_BEGIN% // <copyright file="MLWebRTCVideoSink.cs" company="Magic Leap, Inc"> // // Copyright (c) 2018-present, Magic Leap, Inc. All Rights Reserved. // // </copyright> // %COPYRIGHT_END% // --------------------------------------------------------------------- // %BANNER_END% namespace UnityEngine.XR.MagicLeap { using System; using System.Threading; using System.Collections.Generic; #if PLATFORM_LUMIN using UnityEngine.XR.MagicLeap.Native; #endif /// <summary> /// MLWebRTC class contains the API to interface with the /// WebRTC C API. /// </summary> public partial class MLWebRTC { /// <summary> /// Class that represents a video sink used by the MLWebRTC API. /// Video sinks are fed data by media sources and produces frames to render. /// </summary> public partial class VideoSink : Sink { /// <summary> /// Buffer for the image planes array to use to hold the image plane data. /// </summary> private CircularBuffer<Frame.ImagePlane[]> imagePlanesBuffer = CircularBuffer<Frame.ImagePlane[]>.Create(new Frame.ImagePlane[Frame.ImagePlane.MaxImagePlanes], new Frame.ImagePlane[Frame.ImagePlane.MaxImagePlanes], new Frame.ImagePlane[Frame.ImagePlane.MaxImagePlanes]); /// <summary> /// The newest frame that the video sink knows of. /// </summary> private Frame newFrame; /// <summary> /// The newest frame handle that the video sink knows of. /// </summary> private ulong newFrameHandle; private AutoResetEvent updateVideoEvent = new AutoResetEvent(true); /// <summary> /// Initializes a new instance of the <see cref="VideoSink" /> class. /// </summary> internal VideoSink() { this.Type = MediaStream.Track.Type.Video; } /// <summary> /// Initializes a new instance of the <see cref="VideoSink" /> class. /// </summary> /// <param name="Handle">The Handle of the video sink.</param> internal VideoSink(ulong Handle) : base(Handle) { this.Type = MediaStream.Track.Type.Video; } /// <summary> /// A delegate that describes the requirements of the OnNewFrame callback. /// </summary> /// <param name="frame">The new frame of the video sink.</param> public delegate void OnNewFrameDelegate(VideoSink.Frame frame); /// <summary> /// The event invoked when a new frame is available for the video sink. /// </summary> public event OnNewFrameDelegate OnNewFrame; /// <summary> /// Creates an initialized VideoSink object. /// </summary> /// <param name="result">The MLResult object of the inner platform call(s).</param> /// <returns> An initialized VideoSink object.</returns> public static VideoSink Create(out MLResult result) { VideoSink videoSink = null; #if PLATFORM_LUMIN List<MLWebRTC.Sink> sinks = MLWebRTC.Instance.sinks; ulong Handle = MagicLeapNativeBindings.InvalidHandle; MLResult.Code resultCode = NativeBindings.MLWebRTCVideoSinkCreate(out Handle); if (!DidNativeCallSucceed(resultCode, "MLWebRTCVideoSinkCreate()")) { result = MLResult.Create(resultCode); return videoSink; } videoSink = new VideoSink(Handle); if (MagicLeapNativeBindings.MLHandleIsValid(videoSink.Handle)) { sinks.Add(videoSink); } result = MLResult.Create(resultCode); #else result = new MLResult(); #endif return videoSink; } /// <summary> /// Invokes the OnNewFrame event and releases the unmanaged frame. /// </summary> internal void InvokeOnNewFrame() { #if PLATFORM_LUMIN if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle)) { return; } if (MagicLeapNativeBindings.MLHandleIsValid(newFrameHandle)) { this.OnNewFrame?.Invoke(newFrame); DidNativeCallSucceed(NativeBindings.MLWebRTCVideoSinkReleaseFrame(Handle, newFrameHandle), "MLWebRTCVideoSinkReleaseFrame()"); newFrameHandle = MagicLeapNativeBindings.InvalidHandle; } #endif } /// <summary> /// Queries the video sink for a new frame to broadcast, then builds that frame. /// </summary> public void UpdateVideoSink() { #if PLATFORM_LUMIN if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle)) { return; } updateVideoEvent.Reset(); bool newFrameAvailable = false; // Checks for a new frame. MLResult.Code resultCode = NativeBindings.MLWebRTCVideoSinkIsNewFrameAvailable(this.Handle, out newFrameAvailable); DidNativeCallSucceed(resultCode, "MLWebRTCVideoSinkIsNewFrameAvailable()"); // If one exists, acquire the frame and it's characteristics to send to the YUV converter for rendering. if (!newFrameAvailable) { return; } ulong frameHandle = MagicLeapNativeBindings.InvalidHandle; resultCode = NativeBindings.MLWebRTCVideoSinkAcquireNextAvailableFrame(this.Handle, out frameHandle); if (!DidNativeCallSucceed(resultCode, "MLWebRTCVideoSinkAcquireNextAvailableFrame()")) { return; } Frame.NativeBindings.MLWebRTCFrame nativeFrame = Frame.NativeBindings.MLWebRTCFrame.Create(); resultCode = Frame.NativeBindings.MLWebRTCFrameGetData(frameHandle, ref nativeFrame); DidNativeCallSucceed(resultCode, "MLWebRTCFrameGetData()"); newFrame = Frame.Create(frameHandle, nativeFrame, imagePlanesBuffer.Get()); newFrameHandle = frameHandle; updateVideoEvent.Set(); #endif } /// <summary> /// Sets the track of the video sink. /// </summary> /// <param name="track">The track to use.</param> /// <returns> /// MLResult.Result will be <c>MLResult.Code.Ok</c> if destroying all handles was successful. /// MLResult.Result will be <c>MLResult.Code.WebRTCResultInstanceNotCreated</c> if MLWebRTC instance was not created. /// MLResult.Result will be <c>MLResult.Code.WebRTCResultMismatchingHandle</c> if an incorrect handle was sent. /// </returns> protected override MLResult SetTrack(MediaStream.Track track) { #if PLATFORM_LUMIN ulong sourceHandle = track != null ? track.Handle : MagicLeapNativeBindings.InvalidHandle; MLResult.Code resultCode = NativeBindings.MLWebRTCVideoSinkSetSource(this.Handle, sourceHandle); DidNativeCallSucceed(resultCode, "MLWebRTCVideoSinkSetSource()"); return MLResult.Create(resultCode); #else return new MLResult(); #endif } /// <summary> /// Sets the stream of the video sink sink. /// </summary> /// <param name="stream">The stream to use.</param> /// <returns> /// MLResult.Result will be <c>MLResult.Code.Ok</c> if destroying all handles was successful. /// MLResult.Result will be <c>MLResult.Code.WebRTCResultInstanceNotCreated</c> if MLWebRTC instance was not created. /// MLResult.Result will be <c>MLResult.Code.WebRTCResultMismatchingHandle</c> if an incorrect handle was sent. /// </returns> public MLResult SetStream(MediaStream stream) { if (this.Stream == stream) { #if PLATFORM_LUMIN return MLResult.Create(MLResult.Code.InvalidParam); #endif } this.Stream = stream; if (this.Stream == null) { return this.SetTrack(null); } return this.SetTrack(this.Stream.ActiveVideoTrack); } /// <summary> /// Destroys the video sink. /// </summary> /// <returns> /// MLResult.Result will be <c>MLResult.Code.Ok</c> if destroying all handles was successful. /// MLResult.Result will be <c>MLResult.Code.WebRTCResultInstanceNotCreated</c> if MLWebRTC instance was not created. /// MLResult.Result will be <c>MLResult.Code.WebRTCResultMismatchingHandle</c> if an incorrect handle was sent. /// </returns> public override MLResult Destroy() { #if PLATFORM_LUMIN if (!MagicLeapNativeBindings.MLHandleIsValid(this.Handle)) { return MLResult.Create(MLResult.Code.InvalidParam, "Handle is invalid."); } updateVideoEvent.WaitOne(250); this.SetStream(null); MLResult.Code resultCode = NativeBindings.MLWebRTCVideoSinkDestroy(this.Handle); DidNativeCallSucceed(resultCode, "MLWebRTCVideoSinkDestroy()"); this.InvalidateHandle(); MLWebRTC.Instance.sinks.Remove(this); return MLResult.Create(resultCode); #else return new MLResult(); #endif } } } }
40.868
282
0.561711
[ "MIT" ]
Reality-Hack-2022/TEAM-35
ExtraMile_UnityApp_MagicLeap/Packages/com.magicleap.unitysdk/APIs/WebRTC/API/MLWebRTCVideoSink.cs
10,217
C#
using System; using System.Collections.Generic; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Metadata; namespace Afonsoft.SetBox.Migrations { public partial class AspNetZero_V4_1_Changes : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_AbpRoleClaims_AbpRoles_UserId", table: "AbpRoleClaims"); migrationBuilder.DropIndex( name: "IX_AbpRoleClaims_UserId", table: "AbpRoleClaims"); migrationBuilder.DropColumn( name: "UserId", table: "AbpRoleClaims"); migrationBuilder.AddColumn<bool>( name: "IsInTrialPeriod", table: "AbpTenants", nullable: false, defaultValue: false); migrationBuilder.AddColumn<DateTime>( name: "SubscriptionEndDateUtc", table: "AbpTenants", nullable: true); migrationBuilder.AddColumn<string>( name: "SignInToken", table: "AbpUsers", nullable: true); migrationBuilder.AddColumn<DateTime>( name: "SignInTokenExpireTimeUtc", table: "AbpUsers", nullable: true); migrationBuilder.AddColumn<bool>( name: "IsDisabled", table: "AbpLanguages", nullable: false, defaultValue: false); migrationBuilder.AddColumn<string>( name: "Discriminator", table: "AbpEditions", nullable: false, defaultValue: ""); migrationBuilder.AddColumn<decimal>( name: "AnnualPrice", table: "AbpEditions", nullable: true); migrationBuilder.AddColumn<int>( name: "ExpiringEditionId", table: "AbpEditions", nullable: true); migrationBuilder.AddColumn<decimal>( name: "MonthlyPrice", table: "AbpEditions", nullable: true); migrationBuilder.AddColumn<int>( name: "TrialDayCount", table: "AbpEditions", nullable: true); migrationBuilder.AddColumn<int>( name: "WaitingDayAfterExpire", table: "AbpEditions", nullable: true); migrationBuilder.CreateTable( name: "AbpPersistedGrants", columns: table => new { Id = table.Column<string>(maxLength: 200, nullable: false), ClientId = table.Column<string>(maxLength: 200, nullable: false), CreationTime = table.Column<DateTime>(nullable: false), Data = table.Column<string>(maxLength: 50000, nullable: false), Expiration = table.Column<DateTime>(nullable: true), SubjectId = table.Column<string>(maxLength: 200, nullable: true), Type = table.Column<string>(maxLength: 50, nullable: false) }, constraints: table => { table.PrimaryKey("PK_AbpPersistedGrants", x => x.Id); }); migrationBuilder.CreateTable( name: "AppSubscriptionPayments", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), Amount = table.Column<decimal>(nullable: false), CreationTime = table.Column<DateTime>(nullable: false), CreatorUserId = table.Column<long>(nullable: true), DayCount = table.Column<int>(nullable: false), DeleterUserId = table.Column<long>(nullable: true), DeletionTime = table.Column<DateTime>(nullable: true), EditionId = table.Column<int>(nullable: false), Gateway = table.Column<int>(nullable: false), IsDeleted = table.Column<bool>(nullable: false), LastModificationTime = table.Column<DateTime>(nullable: true), LastModifierUserId = table.Column<long>(nullable: true), PaymentId = table.Column<string>(nullable: true), PaymentPeriodType = table.Column<int>(nullable: true), Status = table.Column<int>(nullable: false), TenantId = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_AppSubscriptionPayments", x => x.Id); }); migrationBuilder.CreateIndex( name: "IX_AbpTenants_CreationTime", table: "AbpTenants", column: "CreationTime"); migrationBuilder.CreateIndex( name: "IX_AbpTenants_SubscriptionEndDateUtc", table: "AbpTenants", column: "SubscriptionEndDateUtc"); migrationBuilder.CreateIndex( name: "IX_AbpPersistedGrants_SubjectId_ClientId_Type", table: "AbpPersistedGrants", columns: new[] { "SubjectId", "ClientId", "Type" }); migrationBuilder.CreateIndex( name: "IX_AppSubscriptionPayments_PaymentId_Gateway", table: "AppSubscriptionPayments", columns: new[] { "PaymentId", "Gateway" }); migrationBuilder.CreateIndex( name: "IX_AppSubscriptionPayments_Status_CreationTime", table: "AppSubscriptionPayments", columns: new[] { "Status", "CreationTime" }); migrationBuilder.AddForeignKey( name: "FK_AbpRoleClaims_AbpRoles_RoleId", table: "AbpRoleClaims", column: "RoleId", principalTable: "AbpRoles", principalColumn: "Id", onDelete: ReferentialAction.Cascade); migrationBuilder.Sql("UPDATE AbpEditions SET Discriminator = 'SubscribableEdition'"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_AbpRoleClaims_AbpRoles_RoleId", table: "AbpRoleClaims"); migrationBuilder.DropTable( name: "AbpPersistedGrants"); migrationBuilder.DropTable( name: "AppSubscriptionPayments"); migrationBuilder.DropIndex( name: "IX_AbpTenants_CreationTime", table: "AbpTenants"); migrationBuilder.DropIndex( name: "IX_AbpTenants_SubscriptionEndDateUtc", table: "AbpTenants"); migrationBuilder.DropColumn( name: "IsInTrialPeriod", table: "AbpTenants"); migrationBuilder.DropColumn( name: "SubscriptionEndDateUtc", table: "AbpTenants"); migrationBuilder.DropColumn( name: "SignInToken", table: "AbpUsers"); migrationBuilder.DropColumn( name: "SignInTokenExpireTimeUtc", table: "AbpUsers"); migrationBuilder.DropColumn( name: "IsDisabled", table: "AbpLanguages"); migrationBuilder.DropColumn( name: "Discriminator", table: "AbpEditions"); migrationBuilder.DropColumn( name: "AnnualPrice", table: "AbpEditions"); migrationBuilder.DropColumn( name: "ExpiringEditionId", table: "AbpEditions"); migrationBuilder.DropColumn( name: "MonthlyPrice", table: "AbpEditions"); migrationBuilder.DropColumn( name: "TrialDayCount", table: "AbpEditions"); migrationBuilder.DropColumn( name: "WaitingDayAfterExpire", table: "AbpEditions"); migrationBuilder.AddColumn<int>( name: "UserId", table: "AbpRoleClaims", nullable: true); migrationBuilder.CreateIndex( name: "IX_AbpRoleClaims_UserId", table: "AbpRoleClaims", column: "UserId"); migrationBuilder.AddForeignKey( name: "FK_AbpRoleClaims_AbpRoles_UserId", table: "AbpRoleClaims", column: "UserId", principalTable: "AbpRoles", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
37.308943
122
0.528873
[ "Apache-2.0" ]
afonsoft/SetBox-VideoPlayer
SetBoxWebUI_New/src/Afonsoft.SetBox.EntityFrameworkCore/Migrations/20170623075109_AspNetZero_V4_1_Changes.cs
9,180
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace com.tmobile.oss.security.taap.poptoken.builder.test { [TestClass] public class HashMapKeyValuePairTest { private Dictionary<string, string> dictionary; [TestInitialize] public void TestInitialize() { // Arrange dictionary = new Dictionary<string, string>(); dictionary.Add("Key1", "Value1"); dictionary.Add("Key2", "Value2"); dictionary.Add("Key3", "Value3"); } [TestMethod] public void HashMapKeyValuePair_Set_Test() { // Act var hashMapKeyValuePair = HashMapKeyValuePair.Set<string, string>(dictionary); // Assert Assert.IsNotNull(hashMapKeyValuePair); Assert.AreEqual(3, hashMapKeyValuePair.Count); } [TestMethod] public void HashMapKeyValuePair_Get_Test() { // Act var value1 = HashMapKeyValuePair.Get<string, string>(dictionary, "Key1"); var value2 = HashMapKeyValuePair.Get<string, string>(dictionary, "Key2"); var value3 = HashMapKeyValuePair.Get<string, string>(dictionary, "Key3"); // Assert Assert.AreEqual("Value1", value1); Assert.AreEqual("Value2", value2); Assert.AreEqual("Value3", value3); } } }
30.87234
90
0.593384
[ "Apache-2.0" ]
akost/tmobile-api-security-lib
poptoken-lib/poptoken-builder/cs-lib-tmobile-oss-poptoken-builder/poptoken.builder.test/HashMapKeyValuePair.UnitTest.cs
1,453
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Runtime.CompilerServices; using System.Runtime.Intrinsics; namespace System.Runtime.Intrinsics.X86 { /// <summary> /// This class provides access to Intel BMI1 hardware instructions via intrinsics /// </summary> [Intrinsic] [CLSCompliant(false)] public abstract class Bmi1 { internal Bmi1() { } public static bool IsSupported { get => IsSupported; } [Intrinsic] public abstract class X64 { internal X64() { } public static bool IsSupported { get => IsSupported; } /// <summary> /// unsigned __int64 _andn_u64 (unsigned __int64 a, unsigned __int64 b) /// ANDN r64a, r64b, reg/m64 /// This intrinisc is only available on 64-bit processes /// </summary> public static ulong AndNot(ulong left, ulong right) => AndNot(left, right); /// <summary> /// unsigned __int64 _bextr_u64 (unsigned __int64 a, unsigned int start, unsigned int len) /// BEXTR r64a, reg/m64, r64b /// This intrinisc is only available on 64-bit processes /// </summary> public static ulong BitFieldExtract(ulong value, byte start, byte length) => BitFieldExtract(value, (ushort)(start | (length << 8))); /// <summary> /// unsigned __int64 _bextr2_u64 (unsigned __int64 a, unsigned __int64 control) /// BEXTR r64a, reg/m64, r64b /// This intrinisc is only available on 64-bit processes /// </summary> public static ulong BitFieldExtract(ulong value, ushort control) => BitFieldExtract(value, control); /// <summary> /// unsigned __int64 _blsi_u64 (unsigned __int64 a) /// BLSI reg, reg/m64 /// This intrinisc is only available on 64-bit processes /// </summary> public static ulong ExtractLowestSetBit(ulong value) => ExtractLowestSetBit(value); /// <summary> /// unsigned __int64 _blsmsk_u64 (unsigned __int64 a) /// BLSMSK reg, reg/m64 /// This intrinisc is only available on 64-bit processes /// </summary> public static ulong GetMaskUpToLowestSetBit(ulong value) => GetMaskUpToLowestSetBit(value); /// <summary> /// unsigned __int64 _blsr_u64 (unsigned __int64 a) /// BLSR reg, reg/m64 /// This intrinisc is only available on 64-bit processes /// </summary> public static ulong ResetLowestSetBit(ulong value) => ResetLowestSetBit(value); /// <summary> /// __int64 _mm_tzcnt_64 (unsigned __int64 a) /// TZCNT reg, reg/m64 /// This intrinisc is only available on 64-bit processes /// </summary> public static ulong TrailingZeroCount(ulong value) => TrailingZeroCount(value); } /// <summary> /// unsigned int _andn_u32 (unsigned int a, unsigned int b) /// ANDN r32a, r32b, reg/m32 /// </summary> public static uint AndNot(uint left, uint right) => AndNot(left, right); /// <summary> /// unsigned int _bextr_u32 (unsigned int a, unsigned int start, unsigned int len) /// BEXTR r32a, reg/m32, r32b /// </summary> public static uint BitFieldExtract(uint value, byte start, byte length) => BitFieldExtract(value, (ushort)(start | (length << 8))); /// <summary> /// unsigned int _bextr2_u32 (unsigned int a, unsigned int control) /// BEXTR r32a, reg/m32, r32b /// </summary> public static uint BitFieldExtract(uint value, ushort control) => BitFieldExtract(value, control); /// <summary> /// unsigned int _blsi_u32 (unsigned int a) /// BLSI reg, reg/m32 /// </summary> public static uint ExtractLowestSetBit(uint value) => ExtractLowestSetBit(value); /// <summary> /// unsigned int _blsmsk_u32 (unsigned int a) /// BLSMSK reg, reg/m32 /// </summary> public static uint GetMaskUpToLowestSetBit(uint value) => GetMaskUpToLowestSetBit(value); /// <summary> /// unsigned int _blsr_u32 (unsigned int a) /// BLSR reg, reg/m32 /// </summary> public static uint ResetLowestSetBit(uint value) => ResetLowestSetBit(value); /// <summary> /// int _mm_tzcnt_32 (unsigned int a) /// TZCNT reg, reg/m32 /// </summary> public static uint TrailingZeroCount(uint value) => TrailingZeroCount(value); } }
40.237705
145
0.592585
[ "MIT" ]
2E0PGS/corefx
src/Common/src/CoreLib/System/Runtime/Intrinsics/X86/Bmi1.cs
4,909
C#
// ========================================================================== // Squidex Headless CMS // ========================================================================== // Copyright (c) Squidex UG (haftungsbeschraenkt) // All rights reserved. Licensed under the MIT license. // ========================================================================== using System; using System.Collections.Generic; using System.Security.Claims; using Squidex.Domain.Apps.Entities.Apps; using Squidex.Infrastructure; using Squidex.Infrastructure.Security; using Squidex.Shared; using Squidex.Shared.Identity; using ClaimsPermissions = Squidex.Infrastructure.Security.PermissionSet; using P = Squidex.Shared.Permissions; namespace Squidex.Domain.Apps.Entities { public sealed class Context { private static readonly IReadOnlyDictionary<string, string> EmptyHeaders = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); public IReadOnlyDictionary<string, string> Headers { get; } public ClaimsPermissions UserPermissions { get; } public ClaimsPrincipal User { get; } public IAppEntity App { get; set; } public bool IsFrontendClient => User.IsInClient(DefaultClients.Frontend); public Context(ClaimsPrincipal user, IAppEntity app) : this(app, user, user.Claims.Permissions(), EmptyHeaders) { Guard.NotNull(user, nameof(user)); } private Context(IAppEntity app, ClaimsPrincipal user, ClaimsPermissions userPermissions, IReadOnlyDictionary<string, string> headers) { App = app; User = user; UserPermissions = userPermissions; Headers = headers; } public static Context Anonymous(IAppEntity app) { var claimsIdentity = new ClaimsIdentity(); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); return new Context(claimsPrincipal, app); } public static Context Admin(IAppEntity app) { var claimsIdentity = new ClaimsIdentity(); var claimsPrincipal = new ClaimsPrincipal(claimsIdentity); claimsIdentity.AddClaim(new Claim(SquidexClaimTypes.Permissions, P.All)); return new Context(claimsPrincipal, app); } public bool Allows(string permissionId, string schema = Permission.Any) { return UserPermissions.Allows(permissionId, App.Name, schema); } private sealed class HeaderBuilder : ICloneBuilder { private readonly Context context; private Dictionary<string, string>? headers; public HeaderBuilder(Context context) { this.context = context; } public Context Build() { if (headers != null) { return new Context(context.App!, context.User, context.UserPermissions, headers); } return context; } public void Remove(string key) { headers ??= new Dictionary<string, string>(context.Headers, StringComparer.OrdinalIgnoreCase); headers.Remove(key); } public void SetHeader(string key, string value) { headers ??= new Dictionary<string, string>(context.Headers, StringComparer.OrdinalIgnoreCase); headers[key] = value; } } public Context Clone(Action<ICloneBuilder> action) { var builder = new HeaderBuilder(this); action(builder); return builder.Build(); } } public interface ICloneBuilder { void SetHeader(string key, string value); void Remove(string key); } }
31.354839
148
0.580247
[ "MIT" ]
EdoardoTona/squidex
backend/src/Squidex.Domain.Apps.Entities/Context.cs
3,890
C#
/* * Workspace API * * Agent API * * OpenAPI spec version: 9.0.000.24.2336 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = Genesys.Internal.Workspace.Client.SwaggerDateConverter; namespace Genesys.Internal.Workspace.Model { /// <summary> /// InlineResponse2003Data /// </summary> [DataContract] public partial class InlineResponse2003Data : IEquatable<InlineResponse2003Data>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="InlineResponse2003Data" /> class. /// </summary> [JsonConstructorAttribute] protected InlineResponse2003Data() { } /// <summary> /// Initializes a new instance of the <see cref="InlineResponse2003Data" /> class. /// </summary> /// <param name="Messages">Messages (required).</param> public InlineResponse2003Data(List<Object> Messages = default(List<Object>)) { // to ensure "Messages" is required (not null) if (Messages == null) { throw new InvalidDataException("Messages is a required property for InlineResponse2003Data and cannot be null"); } else { this.Messages = Messages; } } /// <summary> /// Gets or Sets Messages /// </summary> [DataMember(Name="messages", EmitDefaultValue=false)] public List<Object> Messages { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class InlineResponse2003Data {\n"); sb.Append(" Messages: ").Append(Messages).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as InlineResponse2003Data); } /// <summary> /// Returns true if InlineResponse2003Data instances are equal /// </summary> /// <param name="input">Instance of InlineResponse2003Data to be compared</param> /// <returns>Boolean</returns> public bool Equals(InlineResponse2003Data input) { if (input == null) return false; return ( this.Messages == input.Messages || this.Messages != null && this.Messages.SequenceEqual(input.Messages) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Messages != null) hashCode = hashCode * 59 + this.Messages.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
32.333333
140
0.57732
[ "MIT" ]
GenesysPureEngage/workspace-client-csharp
src/Genesys.Internal.Workspace/Model/InlineResponse2003Data.cs
4,462
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; namespace helloapp { public class Startup { // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { System.Console.WriteLine("Dev - enabled "); app.UseDeveloperExceptionPage(); } else { System.Console.WriteLine("Dev - disabled"); } app.Run(async (arg) => { System.Console.WriteLine("Got request on machine: " + System.Environment.MachineName); await arg.Response.WriteAsync("Hello World! on " + System.Environment.MachineName); }); } } }
30.3125
107
0.546392
[ "MIT" ]
matthiasSchedel/docker-compose-dotnet-app-base
helloapp/Startup.cs
972
C#
using App.Core.Entities; using System.Collections.Generic; namespace App.Core.Interfaces { public interface IUserService { User Authenticate(string username, string password); User GetById(string id); User Create(User user, string password); } }
21.846154
60
0.693662
[ "MIT" ]
michaelprosario/super-answers
App.Core/Interfaces/IUserService.cs
286
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.ECR.Outputs { /// <summary> /// An array of objects representing the details of a replication destination. /// </summary> [OutputType] public sealed class ReplicationConfigurationReplicationDestination { public readonly string Region; public readonly string RegistryId; [OutputConstructor] private ReplicationConfigurationReplicationDestination( string region, string registryId) { Region = region; RegistryId = registryId; } } }
26.757576
82
0.673839
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/ECR/Outputs/ReplicationConfigurationReplicationDestination.cs
883
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace h7t1 { class Program { /* Muokkaa tehtävää 3 harjoitukset 6:ssa niin että työntekijät pystytään tallentamaan erikseen tiedostoon listauksen ja lisäämisen lisäksi, tallennetut henkilöt pitää pystyä myös lukemaan tiedostosta erikseen. Pääohjelmassa tekstipohjainen käyttöliittymä kaikkiin toimintoihin. */ static void Main(string[] args) { Yritys henkilot = new Yritys(); while (true) { int valikko = 0; Console.WriteLine("1. Palkkaa. 2. Erota. 3. Listaa 4. Tallenna henkilöt 5. Tulosta tallennetut henkilöt 0. Lopeta:"); Console.WriteLine("Give a selection"); bool status = int.TryParse(Console.ReadLine(), out valikko); switch (valikko) { case 0: Environment.Exit(0); break; case 1: Console.WriteLine("Give a new employee"); string name = Console.ReadLine(); henkilot.AddEmployee(name); break; case 2: Console.WriteLine("Delete latest employee"); henkilot.DelEmployee(); break; case 3: Console.WriteLine("List all employees"); henkilot.PrintData(); break; case 4: Console.WriteLine("Save all employees"); henkilot.TallennaHenkilo(); break; case 5: Console.WriteLine("Print saved employees"); henkilot.TulostaHenkilo(); break; } } } } }
29.125
179
0.466381
[ "Apache-2.0" ]
AskoVaananen/Csharp-ohjelmointi
h7t1/h7t1/Program.cs
2,122
C#
// *********************************************************************** // Copyright (c) 2008 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.Collections; using System.Collections.Generic; using System.Text; namespace NUnit.Framework.Internal.Builders { class ProviderCache { private static Dictionary<CacheEntry, object> instances = new Dictionary<CacheEntry, object>(); public static object GetInstanceOf(Type providerType) { return GetInstanceOf(providerType, null); } public static object GetInstanceOf(Type providerType, object[] providerArgs) { CacheEntry entry = new CacheEntry(providerType, providerArgs); object instance = instances.ContainsKey(entry) ?instances[entry] : null; if (instance == null) instances[entry] = instance = Reflect.Construct(providerType, providerArgs); return instance; } public static void Clear() { foreach (CacheEntry key in instances.Keys) { IDisposable provider = instances[key] as IDisposable; if (provider != null) provider.Dispose(); } instances.Clear(); } class CacheEntry { private Type providerType; public CacheEntry(Type providerType, object[] providerArgs) { this.providerType = providerType; } public override bool Equals(object obj) { CacheEntry other = obj as CacheEntry; if (other == null) return false; return this.providerType == other.providerType; } public override int GetHashCode() { return providerType.GetHashCode(); } } } }
34.155556
103
0.601496
[ "MIT" ]
JetBrains/nunit
src/NUnitFramework/framework/Internal/Builders/ProviderCache.cs
3,076
C#
using System; using System.Collections.Generic; namespace WCMS.WebSystem.WebParts.RemoteIndexer.Common { interface IRemoteIndexer { string BaseAddress { get; set; } List<FileStruct> GetItemList(string address, int maxRetries); string Password { get; set; } string UserName { get; set; } bool SaveToCache(string itemAddress, string target, int maxRetries); void DeleteCache(string cachePath); char PathSeparator { get; } } }
26.105263
76
0.671371
[ "MIT" ]
dsalunga/mPortal
Portal/WebParts/SystemParts/WCMS.WebSystem.WebParts.RemoteIndexer/Common/IRemoteIndexer.cs
498
C#
using System.Text; using DocumentFormat.OpenXml.Drawing; using DocumentFormat.OpenXml.Flatten.Contexts; using DocumentFormat.OpenXml.Flatten.ElementConverters.CommonElement; using dotnetCampus.OpenXmlUnitConverter; using static DocumentFormat.OpenXml.Flatten.ElementConverters.ShapeGeometryConverters.ShapeGeometryFormulaHelper; using ElementEmuSize = dotnetCampus.OpenXmlUnitConverter.EmuSize; namespace DocumentFormat.OpenXml.Flatten.ElementConverters.ShapeGeometryConverters { /// <summary> /// 矩形:剪去左右顶角 /// </summary> internal class Snip2SameRectangleGeometry : ShapeGeometryBase { /// <inheritdoc /> public override string ToGeometryPathString(ElementEmuSize emuSize, AdjustValueList? adjusts = null) { var (h, w, l, r, t, b, hd2, hd4, hd5, hd6, hd8, ss, hc, vc, ls, ss2, ss4, ss6, ss8, wd2, wd4, wd5, wd6, wd8, wd10, cd2, cd4, cd6, cd8) = GetFormulaProperties(emuSize); //<avLst xmlns="http://schemas.openxmlformats.org/drawingml/2006/main"> // <gd name="adj1" fmla="val 16667" /> // <gd name="adj2" fmla="val 0" /> //</avLst> var customAdj1 = adjusts?.GetAdjustValue("adj1"); var customAdj2 = adjusts?.GetAdjustValue("adj2"); var adj1 = customAdj1 ?? 16667d; var adj2 = customAdj2 ?? 0d; //<gdLst xmlns="http://schemas.openxmlformats.org/drawingml/2006/main"> // <gd name="a1" fmla="pin 0 adj1 50000" /> // <gd name="a2" fmla="pin 0 adj2 50000" /> // <gd name="tx1" fmla="*/ ss a1 100000" /> // <gd name="tx2" fmla="+- r 0 tx1" /> // <gd name="bx1" fmla="*/ ss a2 100000" /> // <gd name="bx2" fmla="+- r 0 bx1" /> // <gd name="by1" fmla="+- b 0 bx1" /> // <gd name="d" fmla="+- tx1 0 bx1" /> // <gd name="dx" fmla="?: d tx1 bx1" /> // <gd name="il" fmla="*/ dx 1 2" /> // <gd name="ir" fmla="+- r 0 il" /> // <gd name="it" fmla="*/ tx1 1 2" /> // <gd name="ib" fmla="+/ by1 b 2" /> //</gdLst> // <gd name="a1" fmla="pin 0 adj1 50000" /> var a1 = Pin(0, adj1, 50000); // <gd name="a2" fmla="pin 0 adj2 50000" /> var a2 = Pin(0, adj2, 50000); // <gd name="tx1" fmla="*/ ss a1 100000" /> var tx1 = ss * a1 / 100000; // <gd name="tx2" fmla="+- r 0 tx1" /> var tx2 = r - tx1; // <gd name="bx1" fmla="*/ ss a2 100000" /> var bx1 = ss * a2 / 100000; // <gd name="bx2" fmla="+- r 0 bx1" /> var bx2 = r - bx1; // <gd name="by1" fmla="+- b 0 bx1" /> var by1 = b - bx1; // <gd name="d" fmla="+- tx1 0 bx1" /> var d = tx1 - bx1; // <gd name="dx" fmla="?: d tx1 bx1" /> var dx = d > 0 ? tx1 : bx1; // <gd name="il" fmla="*/ dx 1 2" /> var il = dx * 1 / 2; // <gd name="ir" fmla="+- r 0 il" /> var ir = r - il; // <gd name="it" fmla="*/ tx1 1 2" /> var it = tx1 * 1 / 2; // <gd name="ib" fmla="+/ by1 b 2" /> var ib = (by1 + b) / 2; //<pathLst xmlns="http://schemas.openxmlformats.org/drawingml/2006/main"> // <path> // <moveTo> // <pt x="tx1" y="t" /> // </moveTo> // <lnTo> // <pt x="tx2" y="t" /> // </lnTo> // <lnTo> // <pt x="r" y="tx1" /> // </lnTo> // <lnTo> // <pt x="r" y="by1" /> // </lnTo> // <lnTo> // <pt x="bx2" y="b" /> // </lnTo> // <lnTo> // <pt x="bx1" y="b" /> // </lnTo> // <lnTo> // <pt x="l" y="by1" /> // </lnTo> // <lnTo> // <pt x="l" y="tx1" /> // </lnTo> // <close /> // </path> // </pathLst> // <moveTo> // <pt x="tx1" y="t" /> // </moveTo> var currentPoint = new EmuPoint(tx1, t); var stringPath = new StringBuilder(); stringPath.Append($"M {EmuToPixelString(currentPoint.X)},{EmuToPixelString(currentPoint.Y)} "); // <lnTo> // <pt x="tx2" y="t" /> // </lnTo> _ = LineToToString(stringPath, tx2, t); // <lnTo> // <pt x="r" y="tx1" /> // </lnTo> _ = LineToToString(stringPath, r, tx1); // <lnTo> // <pt x="r" y="by1" /> // </lnTo> _ = LineToToString(stringPath, r, by1); // <lnTo> // <pt x="bx2" y="b" /> // </lnTo> _ = LineToToString(stringPath, bx2, b); // <lnTo> // <pt x="bx1" y="b" /> // </lnTo> _ = LineToToString(stringPath, bx1, b); // <lnTo> // <pt x="l" y="by1" /> // </lnTo> _ = LineToToString(stringPath, l, by1); // <lnTo> // <pt x="l" y="tx1" /> // </lnTo> _ = LineToToString(stringPath, l, tx1); stringPath.Append("z"); //<rect l="il" t="it" r="ir" b="ib" xmlns="http://schemas.openxmlformats.org/drawingml/2006/main" /> InitializeShapeTextRectangle(il, it, ir, ib); return stringPath.ToString(); } public override ShapePath[]? GetMultiShapePaths(ElementEmuSize emuSize, AdjustValueList? adjusts = null) { var shapePaths = new ShapePath[1]; shapePaths[0] = new ShapePath(ToGeometryPathString(emuSize, adjusts)); return shapePaths; } } }
38.216049
120
0.42901
[ "MIT" ]
dotnet-campus/DocumentFormat.OpenXml.Extensions
src/DocumentFormat.OpenXml.Flatten/DocumentFormat.OpenXml.Flatten/ElementConverters/Shape/ShapeGeometryConverters/Snip2SameRectangleGeometry.cs
6,211
C#
using System.Text; namespace Decorator.IO.Providers.Core { public interface IApplication<T> { void Apply(T item); } public interface IStringBuilderApplication : IApplication<StringBuilder> { } }
15.769231
73
0.756098
[ "MIT" ]
SirJosh3917/Decorator.IO
Decorator.IO.Providers.Core/IApplication.cs
207
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Marvin.BlazorBFF.Server { 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.148148
70
0.647309
[ "MIT" ]
KevinDockx/BlazorWASMSecurityBestPractices
Marvin.BlazorBFF/Marvin.BlazorBFF/Server/Program.cs
708
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.VideoAnalyzer.V20210501Preview { /// <summary> /// A Video Analyzer account. /// </summary> [AzureNativeResourceType("azure-native:videoanalyzer/v20210501preview:VideoAnalyzer")] public partial class VideoAnalyzer : Pulumi.CustomResource { /// <summary> /// The account encryption properties. /// </summary> [Output("encryption")] public Output<Outputs.AccountEncryptionResponse> Encryption { get; private set; } = null!; /// <summary> /// The list of endpoints associated with this resource. /// </summary> [Output("endpoints")] public Output<ImmutableArray<Outputs.EndpointResponse>> Endpoints { get; private set; } = null!; /// <summary> /// The set of managed identities associated with the Video Analyzer resource. /// </summary> [Output("identity")] public Output<Outputs.VideoAnalyzerIdentityResponse?> Identity { get; private set; } = null!; /// <summary> /// The geo-location where the resource lives /// </summary> [Output("location")] public Output<string> Location { get; private set; } = null!; /// <summary> /// The name of the resource /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The storage accounts for this resource. /// </summary> [Output("storageAccounts")] public Output<ImmutableArray<Outputs.StorageAccountResponse>> StorageAccounts { get; private set; } = null!; /// <summary> /// The system data of the Video Analyzer account. /// </summary> [Output("systemData")] public Output<Outputs.SystemDataResponse> SystemData { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a VideoAnalyzer 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 VideoAnalyzer(string name, VideoAnalyzerArgs args, CustomResourceOptions? options = null) : base("azure-native:videoanalyzer/v20210501preview:VideoAnalyzer", name, args ?? new VideoAnalyzerArgs(), MakeResourceOptions(options, "")) { } private VideoAnalyzer(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:videoanalyzer/v20210501preview:VideoAnalyzer", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:videoanalyzer/v20210501preview:VideoAnalyzer"}, new Pulumi.Alias { Type = "azure-native:videoanalyzer:VideoAnalyzer"}, new Pulumi.Alias { Type = "azure-nextgen:videoanalyzer:VideoAnalyzer"}, }, }; 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 VideoAnalyzer 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="options">A bag of options that control this resource's behavior</param> public static VideoAnalyzer Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new VideoAnalyzer(name, id, options); } } public sealed class VideoAnalyzerArgs : Pulumi.ResourceArgs { /// <summary> /// The Video Analyzer account name. /// </summary> [Input("accountName")] public Input<string>? AccountName { get; set; } /// <summary> /// The account encryption properties. /// </summary> [Input("encryption", required: true)] public Input<Inputs.AccountEncryptionArgs> Encryption { get; set; } = null!; /// <summary> /// The set of managed identities associated with the Video Analyzer resource. /// </summary> [Input("identity")] public Input<Inputs.VideoAnalyzerIdentityArgs>? Identity { get; set; } /// <summary> /// The geo-location where the resource lives /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The name of the resource group. The name is case insensitive. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; [Input("storageAccounts", required: true)] private InputList<Inputs.StorageAccountArgs>? _storageAccounts; /// <summary> /// The storage accounts for this resource. /// </summary> public InputList<Inputs.StorageAccountArgs> StorageAccounts { get => _storageAccounts ?? (_storageAccounts = new InputList<Inputs.StorageAccountArgs>()); set => _storageAccounts = value; } [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public VideoAnalyzerArgs() { } } }
38.774725
152
0.599405
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/VideoAnalyzer/V20210501Preview/VideoAnalyzer.cs
7,057
C#
using System; class F { static int[] Read() => Array.ConvertAll(Console.ReadLine().Split(), int.Parse); static (int, int, int) Read3() { var a = Read(); return (a[0], a[1], a[2]); } static void Main() { var (n, m, k) = Read3(); var a = Array.ConvertAll(new bool[n], _ => Read()); // row, count, remainder var dp = NewArray3(n, m / 2 + 1, k, -1); for (int i = 0; i < n; i++) { dp[i][0][0] = 0; for (int j = 0; j < m; j++) { for (int c = m / 2 - 1; c >= 0; c--) { for (int r = 0; r < k; r++) { if (dp[i][c][r] < 0) continue; var nv = dp[i][c][r] + a[i][j]; dp[i][c + 1][nv % k] = Math.Max(dp[i][c + 1][nv % k], nv); } } } for (int c = m / 2; c > 0; c--) { for (int r = 0; r < k; r++) { dp[i][0][r] = Math.Max(dp[i][0][r], dp[i][c][r]); } } } var sum = NewArray1(k, -1); sum[0] = 0; for (int i = 0; i < n; i++) { var t = NewArray1(k, -1); for (int r = 0; r < k; r++) { for (int ir = 0; ir < k; ir++) { if (sum[r] < 0 || dp[i][0][ir] < 0) continue; var nv = sum[r] + dp[i][0][ir]; t[nv % k] = Math.Max(t[nv % k], nv); } } sum = t; } Console.WriteLine(sum[0]); } static T[] NewArray1<T>(int n, T v = default) => Array.ConvertAll(new bool[n], _ => v); static T[][][] NewArray3<T>(int n1, int n2, int n3, T v = default) => Array.ConvertAll(new bool[n1], _ => Array.ConvertAll(new bool[n2], __ => Array.ConvertAll(new bool[n3], ___ => v))); }
24.107692
188
0.436503
[ "MIT" ]
sakapon/Codeforces-Contests
CSharp/Contests2020/CFR677/F.cs
1,569
C#
using System.Drawing; using FalseDotNet.Utility; using Pastel; namespace FalseDotNet.Compile.Optimization; public class Optimizer : IOptimizer { private readonly ILogger _logger; public Optimizer(ILogger logger) { _logger = logger; } public void Optimize(Asm asm, OptimizerConfig config) { // _logger.WriteLine(config.OptimizationLevel.ToString().Pastel(Color.Gold)); } }
21
85
0.709524
[ "MIT" ]
MixusMinimax/falsedotnet
FalseDotNet/Compile/Optimization/Optimizer.cs
422
C#
using UnityEngine; using UnityEngine.UI; /// <summary> /// Displays a very simple preview interface before purchase /// </summary> public class PreviewWindow : Singleton<PreviewWindow> { /// <summary> /// List of shop items /// </summary> [HideInInspector] public ItemList ItemList; /// <summary> /// Item to preview /// </summary> [HideInInspector] public LootItem previewItem; /// <summary> /// Used to play camera animations /// </summary> [HideInInspector] public Animator animator; /// <summary> /// Reference to the menu user interface /// </summary> [HideInInspector] public Transform menuUI; /// <summary> /// Image for the selected item /// </summary> public Image ItemImage; /// <summary> /// Image of the currency used for this item /// </summary> public Image CurrencyImage; /// <summary> /// Name of the selected item /// </summary> public Text ItemName; /// <summary> /// Description of the selected item /// </summary> public Text Description; /// <summary> /// Cost of the selected item /// </summary> public Text Cost; /// <summary> /// Required level for this item /// </summary> public Text Level; /// <summary> /// Purchases item when clicked /// </summary> public Button PurchaseButton; /// <summary> /// Upgrades weapon when clicked /// </summary> public Button UpgradeButton; /// <summary> /// Displayed when preview item is locked /// </summary> public Image ItemLockedImage; /// <summary> /// Played when item is purchased successfully /// </summary> public AudioClip PurchasedItemSound; private AudioSource audioSource; private WeaponConfiguration m_Weapon; private void Start() { if (GameManager.instance == null) { return; } audioSource = GetComponent<AudioSource>(); ItemImage.sprite = previewItem.itemSprite; CurrencyImage.sprite = previewItem.currencySprite; ItemName.text = previewItem.itemName; Cost.text = previewItem.itemCost.ToString(); Level.text = "Level " + previewItem.requiredLevel.ToString(); if (previewItem.requiredLevel > GameManager.instance.GetPlayerLevel()) { ItemLockedImage.gameObject.SetActive(true); PurchaseButton.gameObject.SetActive(false); UpgradeButton.gameObject.SetActive(false); Description.text = "DESCRIPTION NOT AVAILABLE AT THE MOMENT. REACH LEVEL " + previewItem.requiredLevel + " TO UNLOCK."; } else { if (previewItem.itemType == ItemType.Weapon) { WeaponConfiguration weapon = previewItem as WeaponConfiguration; if (GameManager.instance.IsWeaponPurchased(previewItem.id, ItemList)) { UpgradeButton.gameObject.SetActive(true); PurchaseButton.gameObject.SetActive(false); ItemLockedImage.gameObject.SetActive(false); UpgradeButton.interactable = false; /** if (weapon.levels.Length != 0 && !weapon.isAtMaxLevel) { UpgradeButton.interactable = GameManager.instance.Gold.CanAfford(weapon.levels[weapon.currentLevel].cost); } else { UpgradeButton.interactable = false; } **/ } else { PurchaseButton.gameObject.SetActive(true); ItemLockedImage.gameObject.SetActive(false); UpgradeButton.gameObject.SetActive(false); Debug.Log("Not purchased"); PurchaseButton.interactable = GameManager.instance.Gold.CanAfford((int)weapon.itemCost); } } else { PurchaseButton.gameObject.SetActive(true); UpgradeButton.gameObject.SetActive(false); Level.gameObject.SetActive(false); ItemLockedImage.gameObject.SetActive(false); if (previewItem.currency == CurrencyType.Gems) { PurchaseButton.interactable = GameManager.instance.Gems.CanAfford((int)previewItem.itemCost); } else { PurchaseButton.interactable = GameManager.instance.Gold.CanAfford((int)previewItem.itemCost); } } Description.text = previewItem.itemDescription; } // Subscribe to currency change event GameManager.instance.Gold.currencyChanged += OnGoldChanged; GameManager.instance.Gems.currencyChanged += OnGemsChanged; } /// <summary> /// Update the UI when the player purchases a weapon /// </summary> private void Update() { if (GameManager.instance.IsWeaponPurchased(previewItem.id, ItemList) && !UpgradeButton.gameObject.activeSelf) { WeaponConfiguration weapon = previewItem as WeaponConfiguration; UpgradeButton.gameObject.SetActive(true); PurchaseButton.gameObject.SetActive(false); ItemLockedImage.gameObject.SetActive(false); //UpgradeButton.interactable = GameManager.instance.Gold.CanAfford(weapon.levels[weapon.currentLevel].cost); UpgradeButton.interactable = false; } } /// <summary> /// Invoked when button is clicked /// Calls the preview item's purchase method to attempt a purchase /// </summary> public void BuyItem() { if (previewItem.TryPurchaseItem()) { if (previewItem.itemType == ItemType.Weapon) { GameManager.instance.PurchaseWeapon(previewItem.id, previewItem, ItemList); } else { if (previewItem.itemType == ItemType.Gem) return; if (previewItem.itemType == ItemType.Gold) BuyGold(); else GameManager.instance.PurchaseItem(previewItem.id, previewItem, ItemList); } audioSource.PlayOneShot(PurchasedItemSound); } else { Debug.Log("Purchase failed"); } } /// <summary> /// Actual method used to purchase gold /// </summary> private void BuyGold() { GoldItem gold = previewItem as GoldItem; GameManager.instance.Gold.AddCurrency(gold.amountGold); } /// <summary> /// Upgrades the current previewed item /// </summary> public void UpgradeItem() { if (previewItem.itemType == ItemType.Weapon) { if (previewItem.UpgradeItem()) { GameManager.instance.UpgradeWeapon(previewItem.id, previewItem, ItemList); } } } /// <summary> /// Check if the player can afford an upgrade to the next level /// if the preview item is a weapon /// </summary> private void OnGoldChanged() { if (previewItem.itemType == ItemType.Weapon) { WeaponConfiguration weapon = previewItem as WeaponConfiguration; if (weapon.levels.Length == 0 || weapon.isAtMaxLevel) { return; } if (GameManager.instance.Gold.CanAfford(weapon.levels[weapon.currentLevel].cost)) { UpgradeButton.interactable = false; } else { UpgradeButton.interactable = true; } } else { if(PurchaseButton.gameObject.activeSelf) { PurchaseButton.interactable = GameManager.instance.Gold.CanAfford((int)previewItem.itemCost); } } } /// <summary> /// Check if the player can afford to purchase the current selected item /// </summary> private void OnGemsChanged() { if (PurchaseButton.gameObject.activeSelf) { PurchaseButton.interactable = GameManager.instance.Gems.CanAfford((int)previewItem.itemCost); } } /// <summary> /// Close this window /// Unsubscribe to events /// </summary> public void CloseWindow() { if (gameObject != null) { GameManager.instance.Gold.currencyChanged -= OnGoldChanged; GameManager.instance.Gems.currencyChanged -= OnGemsChanged; animator.SetTrigger("Hide"); if (!menuUI.gameObject.activeSelf) menuUI.gameObject.SetActive(true); Destroy(gameObject); } } }
30.652921
131
0.570404
[ "Apache-2.0" ]
aeyonblack/tanya-masvita-software-development-projects
Reborn - Mobile Game Codebase (C#)/Reborn/Assets/Scripts/UI/ItemShop/PreviewWindow.cs
8,922
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Microsoft.Test.Distribution { /// <summary> /// StressDistributionStrategy: Define the strategy to distribute Stress tests. /// </summary> public class StressDistributionStrategy : DistributionStrategy { /// <summary> /// Distribute Stress tests. Each subdivision will get a randomly selected stress test. /// The algorithm ensures that every test will be distributed at least once if the number /// of subdivision is larger than that of available tests, and that every subdivision has /// one and only one test. /// </summary> /// <param name="tests">Tests to distribute</param> /// <param name="machines">Machines to distribute to</param> /// <param name="testBinariesDirectory">Location of test binaries</param> /// <returns>List of TestCollection partitioned</returns> public override List<TestRecords> PartitionTests(TestRecords tests, MachineRecord[] machines, DirectoryInfo testBinariesDirectory) { Profiler.StartMethod(); TestRecords testsToDistribute = SelectEnabledTests(tests); int subdivisionCount = machines.Length; Random r = new Random(); List<TestRecords> collections = new List<TestRecords>(); TestRecords subCollection = null; for (int i = 0; i < subdivisionCount; i++) { subCollection = new TestRecords(); // Randomly distribute a test only there is any. If no test is available, just return empty list. if (tests.TestCollection.Count != 0) { // Get the full collection back if all tests has been distributed out. if (testsToDistribute.TestCollection.Count == 0) { testsToDistribute = SelectEnabledTests(tests); } // Randomly select a test. int index = r.Next(testsToDistribute.TestCollection.Count); TestRecord test = testsToDistribute.TestCollection[index]; testsToDistribute.TestCollection.Remove(test); subCollection.TestCollection.Add(test); } collections.Add(subCollection); } Profiler.EndMethod(); return collections; } /// <summary> /// Get all Tests whose ExecutionEnabled Property is true, from a TestCollection. /// </summary> /// <param name="tests"></param> /// <returns></returns> private TestRecords SelectEnabledTests(TestRecords tests) { return new TestRecords(tests.TestCollection.Where(test => ((TestRecord)test).ExecutionEnabled)); } } }
40.141026
138
0.610029
[ "MIT" ]
batzen/wpf-test
src/Test/Infra/QualityVault/QualityVaultUtilities/Distribution/StressDistributionStrategy.cs
3,131
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mindbox.Data.Linq.Tests { public interface IValueStorage { string Value { get; set; } } }
15.928571
33
0.757848
[ "MIT" ]
guillaume86/data-linq
Mindbox.Data.Linq.Tests/IValueStorage.cs
225
C#
using Discord.Rest; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading.Tasks; using Model = Discord.API.Channel; namespace Discord.WebSocket { /// <summary> /// Represents a WebSocket-based channel in a guild that can send and receive messages. /// </summary> [DebuggerDisplay(@"{DebuggerDisplay,nq}")] public class SocketTextChannel : SocketGuildChannel, ITextChannel, ISocketMessageChannel { private readonly MessageCache _messages; /// <inheritdoc /> public string Topic { get; private set; } /// <inheritdoc /> public int SlowModeInterval { get; private set; } /// <inheritdoc /> public ulong? CategoryId { get; private set; } /// <summary> /// Gets the parent (category) of this channel in the guild's channel list. /// </summary> /// <returns> /// An <see cref="ICategoryChannel"/> representing the parent of this channel; <c>null</c> if none is set. /// </returns> public ICategoryChannel Category => CategoryId.HasValue ? Guild.GetChannel(CategoryId.Value) as ICategoryChannel : null; /// <inheritdoc /> public Task SyncPermissionsAsync(RequestOptions options = null) => ChannelHelper.SyncPermissionsAsync(this, Discord, options); private bool _nsfw; /// <inheritdoc /> public bool IsNsfw => _nsfw; /// <inheritdoc /> public string Mention => MentionUtils.MentionChannel(Id); /// <inheritdoc /> public IReadOnlyCollection<SocketMessage> CachedMessages => _messages?.Messages ?? ImmutableArray.Create<SocketMessage>(); /// <inheritdoc /> public override IReadOnlyCollection<SocketGuildUser> Users => Guild.Users.Where(x => Permissions.GetValue( Permissions.ResolveChannel(Guild, x, this, Permissions.ResolveGuild(Guild, x)), ChannelPermission.ViewChannel)).ToImmutableArray(); internal SocketTextChannel(DiscordSocketClient discord, ulong id, SocketGuild guild) : base(discord, id, guild) { if (Discord.MessageCacheSize > 0) _messages = new MessageCache(Discord); } internal new static SocketTextChannel Create(SocketGuild guild, ClientState state, Model model) { var entity = new SocketTextChannel(guild.Discord, model.Id, guild); entity.Update(state, model); return entity; } internal override void Update(ClientState state, Model model) { base.Update(state, model); CategoryId = model.CategoryId; Topic = model.Topic.Value; SlowModeInterval = model.SlowMode.GetValueOrDefault(); // some guilds haven't been patched to include this yet? _nsfw = model.Nsfw.GetValueOrDefault(); } /// <inheritdoc /> public Task ModifyAsync(Action<TextChannelProperties> func, RequestOptions options = null) => ChannelHelper.ModifyAsync(this, Discord, func, options); //Messages /// <inheritdoc /> public SocketMessage GetCachedMessage(ulong id) => _messages?.Get(id); /// <summary> /// Gets a message from this message channel. /// </summary> /// <remarks> /// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessageAsync"/>. /// Please visit its documentation for more details on this method. /// </remarks> /// <param name="id">The snowflake identifier of the message.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents an asynchronous get operation for retrieving the message. The task result contains /// the retrieved message; <c>null</c> if no message is found with the specified identifier. /// </returns> public async Task<IMessage> GetMessageAsync(ulong id, RequestOptions options = null) { IMessage msg = _messages?.Get(id); if (msg == null) msg = await ChannelHelper.GetMessageAsync(this, Discord, id, options).ConfigureAwait(false); return msg; } /// <summary> /// Gets the last N messages from this message channel. /// </summary> /// <remarks> /// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessagesAsync(int, CacheMode, RequestOptions)"/>. /// Please visit its documentation for more details on this method. /// </remarks> /// <param name="limit">The numbers of message to be gotten from.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// Paged collection of messages. /// </returns> public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, CacheMode.AllowDownload, options); /// <summary> /// Gets a collection of messages in this channel. /// </summary> /// <remarks> /// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessagesAsync(ulong, Direction, int, CacheMode, RequestOptions)"/>. /// Please visit its documentation for more details on this method. /// </remarks> /// <param name="fromMessageId">The ID of the starting message to get the messages from.</param> /// <param name="dir">The direction of the messages to be gotten from.</param> /// <param name="limit">The numbers of message to be gotten from.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// Paged collection of messages. /// </returns> public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, CacheMode.AllowDownload, options); /// <summary> /// Gets a collection of messages in this channel. /// </summary> /// <remarks> /// This method follows the same behavior as described in <see cref="IMessageChannel.GetMessagesAsync(IMessage, Direction, int, CacheMode, RequestOptions)"/>. /// Please visit its documentation for more details on this method. /// </remarks> /// <param name="fromMessage">The starting message to get the messages from.</param> /// <param name="dir">The direction of the messages to be gotten from.</param> /// <param name="limit">The numbers of message to be gotten from.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// Paged collection of messages. /// </returns> public IAsyncEnumerable<IReadOnlyCollection<IMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, CacheMode.AllowDownload, options); /// <inheritdoc /> public IReadOnlyCollection<SocketMessage> GetCachedMessages(int limit = DiscordConfig.MaxMessagesPerBatch) => SocketChannelHelper.GetCachedMessages(this, Discord, _messages, null, Direction.Before, limit); /// <inheritdoc /> public IReadOnlyCollection<SocketMessage> GetCachedMessages(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch) => SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessageId, dir, limit); /// <inheritdoc /> public IReadOnlyCollection<SocketMessage> GetCachedMessages(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch) => SocketChannelHelper.GetCachedMessages(this, Discord, _messages, fromMessage.Id, dir, limit); /// <inheritdoc /> public Task<IReadOnlyCollection<RestMessage>> GetPinnedMessagesAsync(RequestOptions options = null) => ChannelHelper.GetPinnedMessagesAsync(this, Discord, options); /// <inheritdoc /> /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception> public Task<RestUserMessage> SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null) => ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, options); /// <inheritdoc /> public Task<RestUserMessage> SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null) => ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, options); /// <inheritdoc /> /// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception> public Task<RestUserMessage> SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null) => ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, options); /// <inheritdoc /> public Task DeleteMessagesAsync(IEnumerable<IMessage> messages, RequestOptions options = null) => ChannelHelper.DeleteMessagesAsync(this, Discord, messages.Select(x => x.Id), options); /// <inheritdoc /> public Task DeleteMessagesAsync(IEnumerable<ulong> messageIds, RequestOptions options = null) => ChannelHelper.DeleteMessagesAsync(this, Discord, messageIds, options); /// <inheritdoc /> public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null) => ChannelHelper.DeleteMessageAsync(this, messageId, Discord, options); /// <inheritdoc /> public Task DeleteMessageAsync(IMessage message, RequestOptions options = null) => ChannelHelper.DeleteMessageAsync(this, message.Id, Discord, options); /// <inheritdoc /> public Task TriggerTypingAsync(RequestOptions options = null) => ChannelHelper.TriggerTypingAsync(this, Discord, options); /// <inheritdoc /> public IDisposable EnterTypingState(RequestOptions options = null) => ChannelHelper.EnterTypingState(this, Discord, options); internal void AddMessage(SocketMessage msg) => _messages?.Add(msg); internal SocketMessage RemoveMessage(ulong id) => _messages?.Remove(id); //Users /// <inheritdoc /> public override SocketGuildUser GetUser(ulong id) { var user = Guild.GetUser(id); if (user != null) { var guildPerms = Permissions.ResolveGuild(Guild, user); var channelPerms = Permissions.ResolveChannel(Guild, user, this, guildPerms); if (Permissions.GetValue(channelPerms, ChannelPermission.ViewChannel)) return user; } return null; } //Webhooks /// <summary> /// Creates a webhook in this text channel. /// </summary> /// <param name="name">The name of the webhook.</param> /// <param name="avatar">The avatar of the webhook.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous creation operation. The task result contains the newly created /// webhook. /// </returns> public Task<RestWebhook> CreateWebhookAsync(string name, Stream avatar = null, RequestOptions options = null) => ChannelHelper.CreateWebhookAsync(this, Discord, name, avatar, options); /// <summary> /// Gets a webhook available in this text channel. /// </summary> /// <param name="id">The identifier of the webhook.</param> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous get operation. The task result contains a webhook associated /// with the identifier; <c>null</c> if the webhook is not found. /// </returns> public Task<RestWebhook> GetWebhookAsync(ulong id, RequestOptions options = null) => ChannelHelper.GetWebhookAsync(this, Discord, id, options); /// <summary> /// Gets the webhooks available in this text channel. /// </summary> /// <param name="options">The options to be used when sending the request.</param> /// <returns> /// A task that represents the asynchronous get operation. The task result contains a read-only collection /// of webhooks that is available in this channel. /// </returns> public Task<IReadOnlyCollection<RestWebhook>> GetWebhooksAsync(RequestOptions options = null) => ChannelHelper.GetWebhooksAsync(this, Discord, options); //Invites /// <inheritdoc /> public async Task<IInviteMetadata> CreateInviteAsync(int? maxAge = 86400, int? maxUses = null, bool isTemporary = false, bool isUnique = false, RequestOptions options = null) => await ChannelHelper.CreateInviteAsync(this, Discord, maxAge, maxUses, isTemporary, isUnique, options).ConfigureAwait(false); /// <inheritdoc /> public async Task<IReadOnlyCollection<IInviteMetadata>> GetInvitesAsync(RequestOptions options = null) => await ChannelHelper.GetInvitesAsync(this, Discord, options).ConfigureAwait(false); private string DebuggerDisplay => $"{Name} ({Id}, Text)"; internal new SocketTextChannel Clone() => MemberwiseClone() as SocketTextChannel; //ITextChannel /// <inheritdoc /> async Task<IWebhook> ITextChannel.CreateWebhookAsync(string name, Stream avatar, RequestOptions options) => await CreateWebhookAsync(name, avatar, options).ConfigureAwait(false); /// <inheritdoc /> async Task<IWebhook> ITextChannel.GetWebhookAsync(ulong id, RequestOptions options) => await GetWebhookAsync(id, options).ConfigureAwait(false); /// <inheritdoc /> async Task<IReadOnlyCollection<IWebhook>> ITextChannel.GetWebhooksAsync(RequestOptions options) => await GetWebhooksAsync(options).ConfigureAwait(false); //IGuildChannel /// <inheritdoc /> Task<IGuildUser> IGuildChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options) => Task.FromResult<IGuildUser>(GetUser(id)); /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IGuildUser>> IGuildChannel.GetUsersAsync(CacheMode mode, RequestOptions options) => ImmutableArray.Create<IReadOnlyCollection<IGuildUser>>(Users).ToAsyncEnumerable(); //IMessageChannel /// <inheritdoc /> async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options) { if (mode == CacheMode.AllowDownload) return await GetMessageAsync(id, options).ConfigureAwait(false); else return GetCachedMessage(id); } /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, null, Direction.Before, limit, mode, options); /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessageId, dir, limit, mode, options); /// <inheritdoc /> IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options) => SocketChannelHelper.GetMessagesAsync(this, Discord, _messages, fromMessage.Id, dir, limit, mode, options); /// <inheritdoc /> async Task<IReadOnlyCollection<IMessage>> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options) => await GetPinnedMessagesAsync(options).ConfigureAwait(false); /// <inheritdoc /> async Task<IUserMessage> IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options) => await SendFileAsync(filePath, text, isTTS, embed, options).ConfigureAwait(false); /// <inheritdoc /> async Task<IUserMessage> IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options) => await SendFileAsync(stream, filename, text, isTTS, embed, options).ConfigureAwait(false); /// <inheritdoc /> async Task<IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options) => await SendMessageAsync(text, isTTS, embed, options).ConfigureAwait(false); // INestedChannel /// <inheritdoc /> Task<ICategoryChannel> INestedChannel.GetCategoryAsync(CacheMode mode, RequestOptions options) => Task.FromResult(Category); } }
57.359375
194
0.659766
[ "MIT" ]
NovusTheory/Discord.Net
src/Discord.Net.WebSocket/Entities/Channels/SocketTextChannel.cs
18,355
C#
using System.Threading; using System.Web.Mvc; namespace BrickPile.UI.Web.Mvc.Html { public static class DatePickerHelper { public static string ConvertDateFormat(this HtmlHelper html) { return ConvertDateFormat(html, Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern); } public static string ConvertDateFormat(this HtmlHelper html, string format) { var currentFormat = format; // Convert the date currentFormat = currentFormat.Replace("dddd", "DD"); currentFormat = currentFormat.Replace("ddd", "D"); // Convert month if (currentFormat.Contains("MMMM")) { currentFormat = currentFormat.Replace("MMMM", "MM"); } else if (currentFormat.Contains("MMM")) { currentFormat = currentFormat.Replace("MMM", "M"); } else if (currentFormat.Contains("MM")) { currentFormat = currentFormat.Replace("MM", "mm"); } else { currentFormat = currentFormat.Replace("M", "m"); } // Convert year currentFormat = currentFormat.Contains("yyyy") ? currentFormat.Replace("yyyy", "yy") : currentFormat.Replace("yy", "y"); return currentFormat; } public static string ConvertTimeFormat(this HtmlHelper html) { return Thread.CurrentThread.CurrentCulture.DateTimeFormat.LongTimePattern.Replace("tt","TT"); } public static string ConvertShortTimeFormat(this HtmlHelper html) { return Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortTimePattern.Replace("tt", "TT"); ; } } }
40.577778
110
0.578861
[ "MIT" ]
brickpile/brickpile
BrickPile.UI/Web/Mvc/Html/DatePickerHelper.cs
1,828
C#
// file: Math\Functions\Function.cs // // summary: Implements the function class using System; using System.Linq; using numl.Math.LinearAlgebra; using System.Collections.Generic; namespace numl.Math.Functions { /// <summary>A function.</summary> public abstract class Function : IFunction { /// <summary>Exps.</summary> /// <param name="x">The Vector to process.</param> /// <returns>A double.</returns> internal double exp(double x) { return System.Math.Exp(x); } /// <summary>Pows.</summary> /// <param name="x">The Vector to process.</param> /// <param name="a">The double to process.</param> /// <returns>A double.</returns> internal double pow(double x, double a) { return System.Math.Pow(x, a); } /// <summary>Computes the given x coordinate.</summary> /// <param name="x">The Vector to process.</param> /// <returns>A Vector.</returns> public abstract double Compute(double x); /// <summary>Derivatives the given x coordinate.</summary> /// <param name="x">The Vector to process.</param> /// <returns>A Vector.</returns> public abstract double Derivative(double x); /// <summary>Computes the given x coordinate.</summary> /// <param name="x">The Vector to process.</param> /// <returns>A Vector.</returns> public Vector Compute(Vector x) { return x.Calc(d => Compute(d)); } /// <summary>Derivatives the given x coordinate.</summary> /// <param name="x">The Vector to process.</param> /// <returns>A Vector.</returns> public Vector Derivative(Vector x) { return x.Calc(d => Derivative(d)); } } }
37.765957
81
0.593803
[ "MIT" ]
OutSorcerer/numl
numl/Math/Functions/Function.cs
1,775
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.480/blob/master/LICENSE * */ #endregion using Classes.Colours; using ComponentFactory.Krypton.Toolkit; using Microsoft.WindowsAPICodePack.Dialogs; using System; using System.Collections; using System.Drawing; using System.IO; using System.Text; using System.Windows.Forms; namespace Core.UX.Colours { public partial class HexadecimalToRGBConverter : KryptonForm { #region System private KryptonPanel kryptonPanel2; private KryptonListBox klbColours; private System.Windows.Forms.Panel panel1; private KryptonButton kbtnConvertToRGB; private KryptonTextBox ktxtHexValue; private KryptonLabel kryptonLabel5; private KryptonButton kbtnOk; private KryptonButton kbtnCancel; private KryptonButton kbtnExport; private KryptonButton kbtnLoadFromFile; private ContextMenuStrip ctxColourList; private System.ComponentModel.IContainer components; private ToolStripMenuItem removeSelectedColourToolStripMenuItem; private KryptonPanel kryptonPanel1; private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.kryptonPanel1 = new ComponentFactory.Krypton.Toolkit.KryptonPanel(); this.kbtnOk = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kbtnCancel = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kryptonPanel2 = new ComponentFactory.Krypton.Toolkit.KryptonPanel(); this.kbtnConvertToRGB = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.klbColours = new ComponentFactory.Krypton.Toolkit.KryptonListBox(); this.ktxtHexValue = new ComponentFactory.Krypton.Toolkit.KryptonTextBox(); this.kryptonLabel5 = new ComponentFactory.Krypton.Toolkit.KryptonLabel(); this.panel1 = new System.Windows.Forms.Panel(); this.kbtnExport = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.kbtnLoadFromFile = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.ctxColourList = new System.Windows.Forms.ContextMenuStrip(this.components); this.removeSelectedColourToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).BeginInit(); this.kryptonPanel1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPanel2)).BeginInit(); this.kryptonPanel2.SuspendLayout(); this.ctxColourList.SuspendLayout(); this.SuspendLayout(); // // kryptonPanel1 // this.kryptonPanel1.Controls.Add(this.kbtnLoadFromFile); this.kryptonPanel1.Controls.Add(this.kbtnExport); this.kryptonPanel1.Controls.Add(this.kbtnOk); this.kryptonPanel1.Controls.Add(this.kbtnCancel); this.kryptonPanel1.Dock = System.Windows.Forms.DockStyle.Bottom; this.kryptonPanel1.Location = new System.Drawing.Point(0, 622); this.kryptonPanel1.Name = "kryptonPanel1"; this.kryptonPanel1.Size = new System.Drawing.Size(816, 51); this.kryptonPanel1.TabIndex = 0; // // kbtnOk // this.kbtnOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.kbtnOk.AutoSize = true; this.kbtnOk.Location = new System.Drawing.Point(618, 9); this.kbtnOk.Name = "kbtnOk"; this.kbtnOk.Size = new System.Drawing.Size(90, 30); this.kbtnOk.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kbtnOk.TabIndex = 6; this.kbtnOk.Values.Text = "&Ok"; this.kbtnOk.Click += new System.EventHandler(this.kbtnOk_Click); // // kbtnCancel // this.kbtnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.kbtnCancel.AutoSize = true; this.kbtnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.kbtnCancel.Location = new System.Drawing.Point(714, 9); this.kbtnCancel.Name = "kbtnCancel"; this.kbtnCancel.Size = new System.Drawing.Size(90, 30); this.kbtnCancel.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kbtnCancel.TabIndex = 7; this.kbtnCancel.Values.Text = "Ca&ncel"; this.kbtnCancel.Click += new System.EventHandler(this.kbtnCancel_Click); // // kryptonPanel2 // this.kryptonPanel2.Controls.Add(this.kbtnConvertToRGB); this.kryptonPanel2.Controls.Add(this.klbColours); this.kryptonPanel2.Controls.Add(this.ktxtHexValue); this.kryptonPanel2.Controls.Add(this.kryptonLabel5); this.kryptonPanel2.Dock = System.Windows.Forms.DockStyle.Fill; this.kryptonPanel2.Location = new System.Drawing.Point(0, 0); this.kryptonPanel2.Name = "kryptonPanel2"; this.kryptonPanel2.Size = new System.Drawing.Size(816, 622); this.kryptonPanel2.TabIndex = 1; // // kbtnConvertToRGB // this.kbtnConvertToRGB.AutoSize = true; this.kbtnConvertToRGB.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.kbtnConvertToRGB.Enabled = false; this.kbtnConvertToRGB.Location = new System.Drawing.Point(308, 577); this.kbtnConvertToRGB.Name = "kbtnConvertToRGB"; this.kbtnConvertToRGB.Size = new System.Drawing.Size(124, 30); this.kbtnConvertToRGB.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kbtnConvertToRGB.TabIndex = 32; this.kbtnConvertToRGB.Values.Text = "&Convert to RGB"; this.kbtnConvertToRGB.Click += new System.EventHandler(this.kbtnConvertToRGB_Click); // // klbColours // this.klbColours.ContextMenuStrip = this.ctxColourList; this.klbColours.Location = new System.Drawing.Point(12, 12); this.klbColours.Name = "klbColours"; this.klbColours.Size = new System.Drawing.Size(792, 549); this.klbColours.StateCommon.Item.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.klbColours.TabIndex = 0; // // ktxtHexValue // this.ktxtHexValue.Location = new System.Drawing.Point(148, 576); this.ktxtHexValue.MaxLength = 7; this.ktxtHexValue.Name = "ktxtHexValue"; this.ktxtHexValue.Size = new System.Drawing.Size(154, 29); this.ktxtHexValue.StateCommon.Content.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.ktxtHexValue.TabIndex = 31; this.ktxtHexValue.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.ktxtHexValue.TextChanged += new System.EventHandler(this.ktxtHexValue_TextChanged); // // kryptonLabel5 // this.kryptonLabel5.Location = new System.Drawing.Point(12, 577); this.kryptonLabel5.Name = "kryptonLabel5"; this.kryptonLabel5.Size = new System.Drawing.Size(130, 26); this.kryptonLabel5.StateCommon.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kryptonLabel5.TabIndex = 30; this.kryptonLabel5.Values.Text = "Hexadecimal: #"; // // panel1 // this.panel1.BackColor = System.Drawing.SystemColors.ControlDarkDark; this.panel1.Dock = System.Windows.Forms.DockStyle.Bottom; this.panel1.Location = new System.Drawing.Point(0, 619); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(816, 3); this.panel1.TabIndex = 2; // // kbtnExport // this.kbtnExport.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.kbtnExport.AutoSize = true; this.kbtnExport.Enabled = false; this.kbtnExport.Location = new System.Drawing.Point(12, 9); this.kbtnExport.Name = "kbtnExport"; this.kbtnExport.Size = new System.Drawing.Size(147, 30); this.kbtnExport.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kbtnExport.TabIndex = 8; this.kbtnExport.Values.Text = "E&xport to File"; this.kbtnExport.Click += new System.EventHandler(this.kbtnExport_Click); // // kbtnLoadFromFile // this.kbtnLoadFromFile.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.kbtnLoadFromFile.AutoSize = true; this.kbtnLoadFromFile.Location = new System.Drawing.Point(165, 9); this.kbtnLoadFromFile.Name = "kbtnLoadFromFile"; this.kbtnLoadFromFile.Size = new System.Drawing.Size(137, 30); this.kbtnLoadFromFile.StateCommon.Content.ShortText.Font = new System.Drawing.Font("Segoe UI", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.kbtnLoadFromFile.TabIndex = 9; this.kbtnLoadFromFile.Values.Text = "&Load from File"; this.kbtnLoadFromFile.Click += new System.EventHandler(this.kbtnLoadFromFile_Click); // // ctxColourList // this.ctxColourList.Font = new System.Drawing.Font("Segoe UI", 9F); this.ctxColourList.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.removeSelectedColourToolStripMenuItem}); this.ctxColourList.Name = "ctxColourList"; this.ctxColourList.Size = new System.Drawing.Size(204, 48); // // removeSelectedColourToolStripMenuItem // this.removeSelectedColourToolStripMenuItem.Name = "removeSelectedColourToolStripMenuItem"; this.removeSelectedColourToolStripMenuItem.Size = new System.Drawing.Size(203, 22); this.removeSelectedColourToolStripMenuItem.Text = "&Remove Selected Colour"; this.removeSelectedColourToolStripMenuItem.Click += new System.EventHandler(this.removeSelectedColourToolStripMenuItem_Click); // // HexadecimalToRGBConverter // this.AcceptButton = this.kbtnCancel; this.CancelButton = this.kbtnCancel; this.ClientSize = new System.Drawing.Size(816, 673); this.Controls.Add(this.panel1); this.Controls.Add(this.kryptonPanel2); this.Controls.Add(this.kryptonPanel1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "HexadecimalToRGBConverter"; this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Hexadecimal to RGB Converter"; this.Load += new System.EventHandler(this.HexadecimalToRGBConverter_Load); ((System.ComponentModel.ISupportInitialize)(this.kryptonPanel1)).EndInit(); this.kryptonPanel1.ResumeLayout(false); this.kryptonPanel1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonPanel2)).EndInit(); this.kryptonPanel2.ResumeLayout(false); this.kryptonPanel2.PerformLayout(); this.ctxColourList.ResumeLayout(false); this.ResumeLayout(false); } #endregion #region Variables private bool _modified; private Color _targetColour = Color.Transparent; private Timer _editTimer; #endregion #region Properties public bool Modified { get { return _modified; } set { _modified = value; } } public Color TargetColour { get { return _targetColour; } set { _targetColour = value; } } #endregion public HexadecimalToRGBConverter() { InitializeComponent(); } private void HexadecimalToRGBConverter_Load(object sender, EventArgs e) { Modified = false; _editTimer = new Timer(); _editTimer.Interval = 250; _editTimer.Enabled = true; _editTimer.Tick += EditTimer_Tick; } private void EditTimer_Tick(object sender, EventArgs e) { if (klbColours.Items.Count > 0) { kbtnExport.Enabled = true; } else { kbtnExport.Enabled = false; } } private void kbtnConvertToRGB_Click(object sender, EventArgs e) { TargetColour = ColorTranslator.FromHtml($"#{ ktxtHexValue.Text }"); klbColours.Items.Add(ColourFormatting.FormatColourAsRGBString(TargetColour)); TargetColour = Color.Transparent; Modified = true; ktxtHexValue.Text = ""; kbtnConvertToRGB.Enabled = false; ktxtHexValue.Focus(); } private void kbtnExport_Click(object sender, EventArgs e) { CommonSaveFileDialog csfd = new CommonSaveFileDialog(); csfd.Filters.Add(new CommonFileDialogFilter("Normal Text Files", ".txt")); if (csfd.ShowDialog() == CommonFileDialogResult.Ok) { if (!File.Exists(Path.GetFullPath(csfd.FileName))) { File.Create(csfd.FileName); } StreamWriter writer = new StreamWriter(csfd.FileName, true, Encoding.UTF8); foreach (string item in klbColours.Items) { writer.WriteLine(item); } writer.Close(); } Modified = false; } private void kbtnOk_Click(object sender, EventArgs e) { if (Modified) { DialogResult result = KryptonMessageBox.Show("There are items that are not currently saved.\n\nSave these items now?", "Unsaved Data", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { kbtnExport.PerformClick(); } else { Hide(); } } } private void kbtnCancel_Click(object sender, EventArgs e) { } private void ktxtHexValue_TextChanged(object sender, EventArgs e) { if (ktxtHexValue.Text.Length == 6) { kbtnConvertToRGB.Enabled = true; } } private void kbtnLoadFromFile_Click(object sender, EventArgs e) { ArrayList fileContents = new ArrayList(); CommonOpenFileDialog cofd = new CommonOpenFileDialog(); cofd.Filters.Add(new CommonFileDialogFilter("Normal Text Files", ".txt")); int counter = 0; string line; if (cofd.ShowDialog() == CommonFileDialogResult.Ok) { StreamReader reader = new StreamReader(cofd.FileName, Encoding.UTF8); if (new FileInfo(cofd.FileName).Length == 0) { KryptonMessageBox.Show($"There is no data in file: '{ Path.GetFullPath(cofd.FileName) }'"); } else { while ((line = reader.ReadLine()) != null) { klbColours.Items.Add(line); counter++; } Modified = true; } } } private void removeSelectedColourToolStripMenuItem_Click(object sender, EventArgs e) { klbColours.Items.RemoveAt(klbColours.SelectedIndex); } } }
45.407792
201
0.618121
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-Extended-NET-5.480
Source/Krypton Toolkit Suite Extended/Shared/Tooling/UX/Colours/HexadecimalToRGBConverter.cs
17,484
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the mediaconnect-2018-11-14.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.MediaConnect.Model { /// <summary> /// The settings for a flow, including its source, outputs, and entitlements. /// </summary> public partial class Flow { private string _availabilityZone; private string _description; private string _egressIp; private List<Entitlement> _entitlements = new List<Entitlement>(); private string _flowArn; private string _name; private List<Output> _outputs = new List<Output>(); private Source _source; private FailoverConfig _sourceFailoverConfig; private List<Source> _sources = new List<Source>(); private Status _status; private List<VpcInterface> _vpcInterfaces = new List<VpcInterface>(); /// <summary> /// Gets and sets the property AvailabilityZone. The Availability Zone that you want to /// create the flow in. These options are limited to the Availability Zones within the /// current AWS. /// </summary> [AWSProperty(Required=true)] public string AvailabilityZone { get { return this._availabilityZone; } set { this._availabilityZone = value; } } // Check to see if AvailabilityZone property is set internal bool IsSetAvailabilityZone() { return this._availabilityZone != null; } /// <summary> /// Gets and sets the property Description. A description of the flow. This value is not /// used or seen outside of the current AWS Elemental MediaConnect account. /// </summary> public string Description { get { return this._description; } set { this._description = value; } } // Check to see if Description property is set internal bool IsSetDescription() { return this._description != null; } /// <summary> /// Gets and sets the property EgressIp. The IP address from which video will be sent /// to output destinations. /// </summary> public string EgressIp { get { return this._egressIp; } set { this._egressIp = value; } } // Check to see if EgressIp property is set internal bool IsSetEgressIp() { return this._egressIp != null; } /// <summary> /// Gets and sets the property Entitlements. The entitlements in this flow. /// </summary> [AWSProperty(Required=true)] public List<Entitlement> Entitlements { get { return this._entitlements; } set { this._entitlements = value; } } // Check to see if Entitlements property is set internal bool IsSetEntitlements() { return this._entitlements != null && this._entitlements.Count > 0; } /// <summary> /// Gets and sets the property FlowArn. The Amazon Resource Name (ARN), a unique identifier /// for any AWS resource, of the flow. /// </summary> [AWSProperty(Required=true)] public string FlowArn { get { return this._flowArn; } set { this._flowArn = value; } } // Check to see if FlowArn property is set internal bool IsSetFlowArn() { return this._flowArn != null; } /// <summary> /// Gets and sets the property Name. The name of the flow. /// </summary> [AWSProperty(Required=true)] public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Outputs. The outputs in this flow. /// </summary> [AWSProperty(Required=true)] public List<Output> Outputs { get { return this._outputs; } set { this._outputs = value; } } // Check to see if Outputs property is set internal bool IsSetOutputs() { return this._outputs != null && this._outputs.Count > 0; } /// <summary> /// Gets and sets the property Source. /// </summary> [AWSProperty(Required=true)] public Source Source { get { return this._source; } set { this._source = value; } } // Check to see if Source property is set internal bool IsSetSource() { return this._source != null; } /// <summary> /// Gets and sets the property SourceFailoverConfig. /// </summary> public FailoverConfig SourceFailoverConfig { get { return this._sourceFailoverConfig; } set { this._sourceFailoverConfig = value; } } // Check to see if SourceFailoverConfig property is set internal bool IsSetSourceFailoverConfig() { return this._sourceFailoverConfig != null; } /// <summary> /// Gets and sets the property Sources. /// </summary> public List<Source> Sources { get { return this._sources; } set { this._sources = value; } } // Check to see if Sources property is set internal bool IsSetSources() { return this._sources != null && this._sources.Count > 0; } /// <summary> /// Gets and sets the property Status. The current status of the flow. /// </summary> [AWSProperty(Required=true)] public Status Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } /// <summary> /// Gets and sets the property VpcInterfaces. The VPC Interfaces for this flow. /// </summary> public List<VpcInterface> VpcInterfaces { get { return this._vpcInterfaces; } set { this._vpcInterfaces = value; } } // Check to see if VpcInterfaces property is set internal bool IsSetVpcInterfaces() { return this._vpcInterfaces != null && this._vpcInterfaces.Count > 0; } } }
31.016598
110
0.573645
[ "Apache-2.0" ]
NGL321/aws-sdk-net
sdk/src/Services/MediaConnect/Generated/Model/Flow.cs
7,475
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.GoogleNative.Compute.V1.Outputs { /// <summary> /// UrlMaps A host-matching rule for a URL. If matched, will use the named PathMatcher to select the BackendService. /// </summary> [OutputType] public sealed class HostRuleResponse { /// <summary> /// An optional description of this resource. Provide this property when you create the resource. /// </summary> public readonly string Description; /// <summary> /// The list of host patterns to match. They must be valid hostnames with optional port numbers in the format host:port. * matches any string of ([a-z0-9-.]*). In that case, * must be the first character and must be followed in the pattern by either - or .. * based matching is not supported when the URL map is bound to a target gRPC proxy that has the validateForProxyless field set to true. /// </summary> public readonly ImmutableArray<string> Hosts; /// <summary> /// The name of the PathMatcher to use to match the path portion of the URL if the hostRule matches the URL's host portion. /// </summary> public readonly string PathMatcher; [OutputConstructor] private HostRuleResponse( string description, ImmutableArray<string> hosts, string pathMatcher) { Description = description; Hosts = hosts; PathMatcher = pathMatcher; } } }
39
401
0.658863
[ "Apache-2.0" ]
AaronFriel/pulumi-google-native
sdk/dotnet/Compute/V1/Outputs/HostRuleResponse.cs
1,794
C#
using System; namespace AmbidDataManager.Areas.HelpPage { /// <summary> /// This represents an image sample on the help page. There's a display template named ImageSample associated with this class. /// </summary> public class ImageSample { /// <summary> /// Initializes a new instance of the <see cref="ImageSample"/> class. /// </summary> /// <param name="src">The URL of an image.</param> public ImageSample(string src) { if (src == null) { throw new ArgumentNullException("src"); } Src = src; } public string Src { get; private set; } public override bool Equals(object obj) { ImageSample other = obj as ImageSample; return other != null && Src == other.Src; } public override int GetHashCode() { return Src.GetHashCode(); } public override string ToString() { return Src; } } }
26.804878
131
0.509554
[ "MIT" ]
ambid17/AmbidRetailManager
AmbidDataManager/Areas/HelpPage/SampleGeneration/ImageSample.cs
1,099
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Unidux { public class EntitiesBase { } }
13.923077
33
0.734807
[ "MIT" ]
yamertyourgod/Cyclopsgrandma.Reduxcore
Runtime/Unidux/Scripts/Core/EntitiesBase.cs
183
C#
using System; using System.Collections.Generic; using DnsClient; using System.Data; using System.Security.Claims; using Microsoft.AspNetCore.Identity; using MongoDB.Bson; using MongoDB.Bson.Serialization.Attributes; namespace AspNetCore.Identity.Mongo.Model { internal class MigrationMongoUser : MigrationMongoUser<ObjectId> { public MigrationMongoUser() : base() { } } internal class MigrationMongoUser<TKey> : IdentityUser<TKey> where TKey : IEquatable<TKey> { public MigrationMongoUser() { Roles = new List<string>(); Claims = new List<IdentityUserClaim<string>>(); Logins = new List<IdentityUserLogin<string>>(); Tokens = new List<IdentityUserToken<string>>(); RecoveryCodes = new List<TwoFactorRecoveryCode>(); } public string AuthenticatorKey { get; set; } public List<string> Roles { get; set; } public List<IdentityUserClaim<string>> Claims { get; set; } public List<IdentityUserLogin<string>> Logins { get; set; } public List<IdentityUserToken<string>> Tokens { get; set; } public List<TwoFactorRecoveryCode> RecoveryCodes { get; set; } } }
29.731707
94
0.66776
[ "MIT" ]
PascalSenn/AspNetCore.Identity.Mongo
src/AspNetCore.Identity.Mongo/Model/MigrationMongoUser.cs
1,221
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the redshift-2012-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Redshift.Model { /// <summary> /// Container for the parameters to the PurchaseReservedNodeOffering operation. /// Allows you to purchase reserved nodes. Amazon Redshift offers a predefined set of /// reserved node offerings. You can purchase one or more of the offerings. You can call /// the <a>DescribeReservedNodeOfferings</a> API to obtain the available reserved node /// offerings. You can call this API by providing a specific reserved node offering and /// the number of nodes you want to reserve. /// /// /// <para> /// For more information about reserved node offerings, go to <a href="https://docs.aws.amazon.com/redshift/latest/mgmt/purchase-reserved-node-instance.html">Purchasing /// Reserved Nodes</a> in the <i>Amazon Redshift Cluster Management Guide</i>. /// </para> /// </summary> public partial class PurchaseReservedNodeOfferingRequest : AmazonRedshiftRequest { private int? _nodeCount; private string _reservedNodeOfferingId; /// <summary> /// Gets and sets the property NodeCount. /// <para> /// The number of reserved nodes that you want to purchase. /// </para> /// /// <para> /// Default: <code>1</code> /// </para> /// </summary> public int NodeCount { get { return this._nodeCount.GetValueOrDefault(); } set { this._nodeCount = value; } } // Check to see if NodeCount property is set internal bool IsSetNodeCount() { return this._nodeCount.HasValue; } /// <summary> /// Gets and sets the property ReservedNodeOfferingId. /// <para> /// The unique identifier of the reserved node offering you want to purchase. /// </para> /// </summary> [AWSProperty(Required=true)] public string ReservedNodeOfferingId { get { return this._reservedNodeOfferingId; } set { this._reservedNodeOfferingId = value; } } // Check to see if ReservedNodeOfferingId property is set internal bool IsSetReservedNodeOfferingId() { return this._reservedNodeOfferingId != null; } } }
34.880435
173
0.647242
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/Redshift/Generated/Model/PurchaseReservedNodeOfferingRequest.cs
3,209
C#
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Reflection; using System.Runtime.CompilerServices; using System.Threading; using System.Windows.Forms; using Confuser.Core; namespace KoiVM.Confuser { internal static class KoiInfo { internal static KoiSettings settings; static bool inited; static List<Assembly> assemblies = new List<Assembly>(); static Assembly OnAssemblyResolve(object sender, ResolveEventArgs args) { var name = new AssemblyName(args.Name).Name; foreach (var asm in assemblies) { if (asm.GetName().Name == name) return asm; } string folderPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string assemblyPath = Path.Combine(folderPath, name + ".dll"); if (File.Exists(assemblyPath) == false) return null; Assembly assembly = Assembly.LoadFrom(assemblyPath); return assembly; } internal static void Init() { lock (typeof(KoiInfo)) { if (inited) return; AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve; KoiDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); settings = new KoiSettings(); inited = true; } } internal static void Init(ConfuserContext ctx) { lock (typeof(KoiInfo)) { if (inited) return; AppDomain.CurrentDomain.AssemblyResolve += OnAssemblyResolve; KoiDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); settings = new KoiSettings(); // Check if not yet processed. if (Assembly.GetExecutingAssembly().ManifestModule.GetType("KoiVM.Confuser.Internal.Fish") != null) return; if (ctx != null) { var packPath = Path.Combine(KoiDirectory, "koi.pack"); if (!File.Exists(packPath)) RetrieveKoi(ctx); else if (!settings.NoCheck) CheckUpdate(ctx); InitKoi(); } inited = true; } } static void CheckUpdate(ConfuserContext ctx) { var ver = new KoiSystem().GetVersion(settings.KoiID); if (ver == settings.Version) return; ctx.Logger.DebugFormat("New version of KoiVM: {0}", ver); ctx.Logger.DebugFormat("Current version of KoiVM: {0}", settings.Version); if (settings.NoUI) { ctx.Logger.DebugFormat("Updating..."); var sys = new KoiSystem(); var hnd = new ManualResetEvent(false); bool okay = false; sys.Progress += _ => { }; sys.Finish += f => { okay = f; hnd.Set(); }; sys.Login(settings.KoiID); hnd.WaitOne(); if (!okay) throw new InvalidOperationException("Authentication failed."); else { settings.Version = ver; settings.Save(); } } else { Application.EnableVisualStyles(); if (new UpdatePrompt(ver) { TopLevel = true }.ShowDialog() != DialogResult.OK) throw new InvalidOperationException("Authentication failed."); } } static void RetrieveKoi(ConfuserContext ctx) { if (settings.NoUI) { ctx.Logger.Debug("Retrieving Koi..."); var sys = new KoiSystem(); var hnd = new ManualResetEvent(false); bool okay = false; sys.Progress += _ => { }; sys.Finish += f => { okay = f; hnd.Set(); }; sys.Login(settings.KoiID); hnd.WaitOne(); if (!okay) throw new InvalidOperationException("Authentication failed."); } else { Application.EnableVisualStyles(); if (new LoginPrompt() { TopLevel = true }.ShowDialog() != DialogResult.OK) throw new InvalidOperationException("Authentication failed."); } } internal static void InitKoi(bool runCctor = true) { var rc4 = new RC4(Convert.FromBase64String("S29pVk0gaXMgY3V0ZSEhIQ==")); var buf = File.ReadAllBytes(Path.Combine(KoiDirectory, "koi.pack")); rc4.Crypt(buf, 0, buf.Length); using (var deflate = new DeflateStream(new MemoryStream(buf), CompressionMode.Decompress)) using (var reader = new BinaryReader(deflate)) { int count = reader.ReadInt32(); assemblies.Clear(); for (int i = 0; i < count; i++) { var asm = Assembly.Load(reader.ReadBytes(reader.ReadInt32())); assemblies.Add(asm); } } if (!runCctor) return; foreach (var asm in assemblies) { // Initialize the modules, since internal calls might not trigger module cctor RuntimeHelpers.RunModuleConstructor(asm.ManifestModule.ModuleHandle); } } public static string KoiDirectory { get; private set; } } }
29.384615
104
0.650305
[ "CC0-1.0" ]
ElektroKill/KoiVM
KoiVM.Confuser/KoiInfo.cs
4,586
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using System.Web.Http; using SFA.DAS.Commitments.Api.Orchestrators; using SFA.DAS.Commitments.Api.Types.Validation; using SFA.DAS.Commitments.Infrastructure.Authorization; namespace SFA.DAS.Commitments.Api.Controllers { [RoutePrefix("api/validation")] public class ValidationController : ApiController { private readonly ValidationOrchestrator _validationOrchestrator; public ValidationController(ValidationOrchestrator validationOrchestrator) { if (validationOrchestrator == null) { throw new ArgumentNullException(nameof(validationOrchestrator)); } _validationOrchestrator = validationOrchestrator; } [Route("apprenticeships/overlapping")] [AuthorizeRemoteOnly(Roles = "Role1")] public async Task<IHttpActionResult> ValidateOverlappingApprenticeships([FromBody]IEnumerable<ApprenticeshipOverlapValidationRequest> request) { var result = await _validationOrchestrator.ValidateOverlappingApprenticeships(request); return Ok(result); } [Route("apprenticeships/emailoverlapping")] public async Task<IHttpActionResult> ValidateEmailOverlappingApprenticeships([FromBody] IEnumerable<ApprenticeshipEmailOverlapValidationRequest> request) { var result = await _validationOrchestrator.ValidateEmailOverlappingApprenticeships(request); return Ok(result); } } }
38.243902
161
0.722577
[ "MIT" ]
SkillsFundingAgency/das-commitments
src/SFA.DAS.Commitments.Api/Controllers/ValidationController.cs
1,570
C#
using System; using Android.App; using Android.Content.Res; using Android.Graphics.Drawables; using Microsoft.Maui.Essentials; namespace Microsoft.Maui.Handlers { public partial class DatePickerHandler : ViewHandler<IDatePicker, MauiDatePicker> { DatePickerDialog? _dialog; protected override MauiDatePicker CreatePlatformView() { var mauiDatePicker = new MauiDatePicker(Context) { ShowPicker = ShowPickerDialog, HidePicker = HidePickerDialog }; var date = VirtualView?.Date; if (date != null) _dialog = CreateDatePickerDialog(date.Value.Year, date.Value.Month, date.Value.Day); return mauiDatePicker; } internal DatePickerDialog? DatePickerDialog { get { return _dialog; } } protected override void ConnectHandler(MauiDatePicker platformView) { base.ConnectHandler(platformView); DeviceDisplay.MainDisplayInfoChanged += OnMainDisplayInfoChanged; } protected override void DisconnectHandler(MauiDatePicker platformView) { if (_dialog != null) { _dialog.Hide(); _dialog.Dispose(); _dialog = null; } DeviceDisplay.MainDisplayInfoChanged -= OnMainDisplayInfoChanged; base.DisconnectHandler(platformView); } protected virtual DatePickerDialog CreateDatePickerDialog(int year, int month, int day) { var dialog = new DatePickerDialog(Context!, (o, e) => { if (VirtualView != null) { VirtualView.Date = e.Date; } }, year, month, day); return dialog; } // This is a Android-specific mapping public static void MapBackground(IDatePickerHandler handler, IDatePicker datePicker) { if (handler is DatePickerHandler platformHandler) handler.PlatformView?.UpdateBackground(datePicker); } public static void MapFormat(IDatePickerHandler handler, IDatePicker datePicker) { handler.PlatformView?.UpdateFormat(datePicker); } public static void MapDate(IDatePickerHandler handler, IDatePicker datePicker) { handler.PlatformView?.UpdateDate(datePicker); } public static void MapMinimumDate(IDatePickerHandler handler, IDatePicker datePicker) { if (handler is DatePickerHandler platformHandler) handler.PlatformView?.UpdateMinimumDate(datePicker, platformHandler._dialog); } public static void MapMaximumDate(IDatePickerHandler handler, IDatePicker datePicker) { if (handler is DatePickerHandler platformHandler) handler.PlatformView?.UpdateMaximumDate(datePicker, platformHandler._dialog); } public static void MapCharacterSpacing(IDatePickerHandler handler, IDatePicker datePicker) { handler.PlatformView?.UpdateCharacterSpacing(datePicker); } public static void MapFont(IDatePickerHandler handler, IDatePicker datePicker) { var fontManager = handler.GetRequiredService<IFontManager>(); handler.PlatformView?.UpdateFont(datePicker, fontManager); } public static void MapTextColor(IDatePickerHandler handler, IDatePicker datePicker) { if (handler is DatePickerHandler platformHandler) handler.PlatformView?.UpdateTextColor(datePicker); } void ShowPickerDialog() { if (VirtualView == null) return; if (_dialog != null && _dialog.IsShowing) return; var date = VirtualView.Date; ShowPickerDialog(date.Year, date.Month - 1, date.Day); } void ShowPickerDialog(int year, int month, int day) { if (_dialog == null) _dialog = CreateDatePickerDialog(year, month, day); else { EventHandler? setDateLater = null; setDateLater = (sender, e) => { _dialog!.UpdateDate(year, month, day); _dialog.ShowEvent -= setDateLater; }; _dialog.ShowEvent += setDateLater; } _dialog.Show(); } void HidePickerDialog() { _dialog?.Hide(); } void OnMainDisplayInfoChanged(object? sender, DisplayInfoChangedEventArgs e) { DatePickerDialog? currentDialog = _dialog; if (currentDialog != null && currentDialog.IsShowing) { currentDialog.Dismiss(); ShowPickerDialog(currentDialog.DatePicker.Year, currentDialog.DatePicker.Month, currentDialog.DatePicker.DayOfMonth); } } } }
26.225806
121
0.739729
[ "MIT" ]
GabrieleMessina/maui
src/Core/src/Handlers/DatePicker/DatePickerHandler.Android.cs
4,067
C#
//Copyright 2016 Scifoni Ivano // //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. using System; using System.Collections.Generic; using System.Text; namespace SharpBatch.Serialization.Abstract { public interface IModelSerializer { string Serialize(object data); T Deserialize<T>(string data); string Serialize<T>(T data); } }
30.821429
74
0.736964
[ "Apache-2.0" ]
iscifoni/SharpBatch
src/SharpBatch.Serialization.Abstract/IModelSerializer.cs
865
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.Sql; using System.Data.SqlClient; using System.Xml; using System.Data; using System.Web.Configuration; using System.Configuration; namespace PatanHospital { public partial class DoctorSchedule : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Label1.Text = Session["Doctor_SSN"].ToString(); Label1.Visible = false; Bind_Grid_View(); } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { } protected void GridView1_DataBound(object sender, EventArgs e) { } protected void Bind_Grid_View() { Configuration rootWebConfig = WebConfigurationManager.OpenWebConfiguration("/HospitalServer"); ConnectionStringSettings connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings["HospitalServerConnectionString"]; SqlConnection sqlConnection = new SqlConnection(connectionString.ToString()); sqlConnection.Open(); string Query = "SELECT DoctorSchedule.Date, DoctorSchedule.Start_Time, DoctorSchedule.End_Time, PatientCredientials.Fname+' '+ PatientCredientials.Lname as Name FROM PatientCredientials INNER JOIN DoctorSchedule ON PatientCredientials.SSN = DoctorSchedule.P_SSN where D_SSN ='" + this.Label1.Text + "'; "; SqlCommand cmd = new SqlCommand(Query, sqlConnection); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "DoctorSchedule"); GridView1.DataSource = ds; GridView1.DataBind(); sqlConnection.Close(); } protected void Bind_Grid_View_with_TextBox_Date() { Configuration rootWebConfig = WebConfigurationManager.OpenWebConfiguration("/HospitalServer"); ConnectionStringSettings connectionString = rootWebConfig.ConnectionStrings.ConnectionStrings["HospitalServerConnectionString"]; SqlConnection sqlConnection = new SqlConnection(connectionString.ToString()); sqlConnection.Open(); string Query = "SELECT DoctorSchedule.Date, DoctorSchedule.Start_Time, DoctorSchedule.End_Time, PatientCredientials.Fname+' '+ PatientCredientials.Lname as Patient_Name FROM PatientCredientials INNER JOIN DoctorSchedule ON PatientCredientials.SSN = DoctorSchedule.P_SSN where D_SSN ='" + this.Label1.Text + "' and Date ='" + this.TextBox1.Text + "'; "; SqlCommand cmd = new SqlCommand(Query, sqlConnection); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "DoctorSchedule"); GridView1.DataSource = ds; GridView1.DataBind(); sqlConnection.Close(); } protected void TextBox1_TextChanged(object sender, EventArgs e) { Bind_Grid_View_with_TextBox_Date(); } protected void Logo_Click(object sender, EventArgs e) { Response.Redirect("DoctorHome.aspx"); } } }
39.963415
364
0.675618
[ "Apache-2.0" ]
richa615/PatanHospital
PatanHospital/DoctorSchedule.aspx.cs
3,279
C#
namespace FileUpload.API.Areas.HelpPage.ModelDescriptions { public class DictionaryModelDescription : KeyValuePairModelDescription { } }
24.666667
74
0.790541
[ "MIT" ]
marceloazuma/FileUpload
FileUpload.API/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs
148
C#
// <copyright file="IBody.cs" company="Datadog"> // Unless explicitly stated otherwise all files in this repository are licensed under the Apache 2 License. // This product includes software developed at Datadog (https://www.datadoghq.com/). Copyright 2017 Datadog, Inc. // </copyright> namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.RabbitMQ { /// <summary> /// Body interface for ducktyping /// </summary> internal interface IBody { /// <summary> /// Gets the length of the message body /// </summary> int Length { get; } } }
31.263158
113
0.664983
[ "Apache-2.0" ]
DataDog/dd-trace-csharp
tracer/src/Datadog.Trace/ClrProfiler/AutoInstrumentation/RabbitMQ/IBody.cs
594
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using RVTR.Booking.ObjectModel.Models; namespace RVTR.Booking.ObjectModel.Interfaces { public interface IBookingRepository : IRepository<BookingModel> { Task<IEnumerable<BookingModel>> GetBookingsByDatesAsync(DateTime checkIn, DateTime checkOut); Task<IEnumerable<BookingModel>> GetByAccountId(int id); } }
28.571429
97
0.805
[ "MIT" ]
RVTR-09082020-P3/rvtrx-api-booking
aspnet/RVTR.Booking.ObjectModel/Interfaces/IBookingRepository.cs
400
C#
namespace StudentsSystem.Data { using System; using System.Data.Entity; using System.Linq; public class EfGenericRepository<T> : IRepository<T> where T : class { public EfGenericRepository(DbContext context) { if (context == null) { throw new ArgumentException("An instance of DbContext is required to use this repository.", "context"); } this.Context = context; this.DbSet = this.Context.Set<T>(); } protected IDbSet<T> DbSet { get; set; } protected DbContext Context { get; set; } public virtual IQueryable<T> All() { return this.DbSet.AsQueryable(); } public virtual T GetById(object id) { return this.DbSet.Find(id); } public virtual void Add(T entity) { var entry = this.Context.Entry(entity); if (entry.State != EntityState.Detached) { entry.State = EntityState.Added; } else { this.DbSet.Add(entity); } } public virtual void Update(T entity) { var entry = this.Context.Entry(entity); if (entry.State == EntityState.Detached) { this.DbSet.Attach(entity); } entry.State = EntityState.Modified; } public virtual void Delete(T entity) { var entry = this.Context.Entry(entity); if (entry.State != EntityState.Deleted) { entry.State = EntityState.Deleted; } else { this.DbSet.Attach(entity); this.DbSet.Remove(entity); } } public virtual void Delete(object id) { var entity = this.GetById(id); if (entity != null) { this.Delete(entity); } } public virtual T Attach(T entity) { return this.Context.Set<T>().Attach(entity); } public virtual void Detach(T entity) { var entry = this.Context.Entry(entity); entry.State = EntityState.Detached; } public int SaveChanges() { return this.Context.SaveChanges(); } public void Dispose() { this.Context.Dispose(); } } }
24.317308
119
0.4828
[ "MIT" ]
ni4ka7a/TelerikAcademyHomeworks
WebServicesAndCloud/02.ASP.NETWebAPI/01.StudentSystem/StudentsSystem.Data/EfGenericRepository.cs
2,531
C#